@fungi.computer/grove 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +106 -2
  3. package/dist/assets/Effect-BEduymlz.js +76 -0
  4. package/dist/assets/MapleMono-VF-CCDrizxw.woff2 +0 -0
  5. package/dist/assets/Nunito-VF-8c6a9bb-cyrillic-BsWUdSU9.woff2 +0 -0
  6. package/dist/assets/Nunito-VF-8c6a9bb-cyrillic-ext-Cb1j0nGJ.woff2 +0 -0
  7. package/dist/assets/Nunito-VF-8c6a9bb-latin-BYs3GYNf.woff2 +0 -0
  8. package/dist/assets/Nunito-VF-8c6a9bb-latin-ext-0RvtKGDy.woff2 +0 -0
  9. package/dist/assets/Nunito-VF-8c6a9bb-vietnamese-cS2dauUA.woff2 +0 -0
  10. package/dist/assets/anthropic-messages-Bnv5qjAJ.js +41 -0
  11. package/dist/assets/azure-openai-responses-QZaJy-8U.js +1 -0
  12. package/dist/assets/base-face-CJPKiwfc.js +1 -0
  13. package/dist/assets/burger-DMbWZ2jd.js +1 -0
  14. package/dist/assets/cat-UfLh6DHG.js +1 -0
  15. package/dist/assets/cloudflare-workers-ai-system-one-Bq-3_D9p.js +1 -0
  16. package/dist/assets/compat-CvJ9Wfru.js +2 -0
  17. package/dist/assets/diagnostics-CmW2yJSB.js +1 -0
  18. package/dist/assets/error-CJ3RHG07.js +1 -0
  19. package/dist/assets/error-body-pkrba6pf.js +1 -0
  20. package/dist/assets/extension-hook-DvcdepgP.js +560 -0
  21. package/dist/assets/extensions-1Fd4Wd8r.js +1 -0
  22. package/dist/assets/github-copilot-headers-DRgtIyTm.js +1 -0
  23. package/dist/assets/google-generative-ai-DP-8xZvz.js +1 -0
  24. package/dist/assets/google-shared-Cs5udoZV.js +8 -0
  25. package/dist/assets/google-vertex-BJiAIGUd.js +1 -0
  26. package/dist/assets/hash-yQufAZII.js +1 -0
  27. package/dist/assets/headers-FK4rgixo.js +1 -0
  28. package/dist/assets/index-DBHVAvuX.css +1 -0
  29. package/dist/assets/index-hJphFjkO.js +171 -0
  30. package/dist/assets/json-parse-nqKewMRF.js +3 -0
  31. package/dist/assets/mistral-conversations-mRYg3mWw.js +4 -0
  32. package/dist/assets/models-CcNnosqL.js +1 -0
  33. package/dist/assets/mushroom-BBaCYNmw.js +1 -0
  34. package/dist/assets/node.browser-CwSOSQcL.js +1 -0
  35. package/dist/assets/node.browser-DFtqp6Hr.js +1 -0
  36. package/dist/assets/openai-Cpe0uoXQ.js +19 -0
  37. package/dist/assets/openai-codex-responses-BMz-j1hp.js +9 -0
  38. package/dist/assets/openai-completions-BxBCgHHI.js +5 -0
  39. package/dist/assets/openai-prompt-cache-DXo9f3w5.js +1 -0
  40. package/dist/assets/openai-responses-cvwOEFWg.js +1 -0
  41. package/dist/assets/openai-responses-shared-DzD8B6NI.js +10 -0
  42. package/dist/assets/openrouter-images-DwousKhc.js +1 -0
  43. package/dist/assets/parakeet-conversation-C3pQoKx-.js +3 -0
  44. package/dist/assets/parakeet-conversation-COndlivb.css +1 -0
  45. package/dist/assets/pi-messages-CfXPQ4jp.js +7 -0
  46. package/dist/assets/preload-helper-mbhLTglw.js +8 -0
  47. package/dist/assets/provider-env-CcCbsTJq.js +1 -0
  48. package/dist/assets/provider-retry-CSlu6hjs.js +1 -0
  49. package/dist/assets/renderer-BdjuCi44.js +1 -0
  50. package/dist/assets/rolldown-runtime-hePW80VL.js +1 -0
  51. package/dist/assets/runtime-core-CvcjUkf6.js +2 -0
  52. package/dist/assets/sanitize-unicode-DmIE6hZJ.js +1 -0
  53. package/dist/assets/system-one-shared-CGF8IYMZ.js +1 -0
  54. package/dist/assets/transform-messages-CrQEqmfx.js +1 -0
  55. package/dist/assets/typesafe-system-one-CWcJw-Ys.js +1 -0
  56. package/dist/index.html +17 -0
  57. package/package.json +172 -3
@@ -0,0 +1,19 @@
1
+ import{n as e,r as t,t as n}from"./rolldown-runtime-hePW80VL.js";function r(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}function i(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}var a=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return a=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(+e^n()&15>>e/4).toString(16))};function o(e){return typeof e==`object`&&!!e&&(`name`in e&&e.name===`AbortError`||`message`in e&&String(e.message).includes(`FetchRequestCanceledException`))}var s=e=>{if(e instanceof Error)return e;if(typeof e==`object`&&e){try{if(Object.prototype.toString.call(e)===`[object Error]`){let t=`cause`in e,n=Error(e.message,t?{cause:e.cause}:{});return e.stack&&(n.stack=e.stack),t&&!Object.prototype.hasOwnProperty.call(n,`cause`)&&(n.cause=e.cause),e.name&&(n.name=e.name),n}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)},c=class extends Error{},l=class e extends c{constructor(t,n,r,i){super(`${e.makeMessage(t,n,r)}`),this.status=t,this.headers=i,this.requestID=i?.get(`x-request-id`),this.error=n;let a=n;this.code=a?.code,this.param=a?.param,this.type=a?.type}static makeMessage(e,t,n){let r=t?.message?typeof t.message==`string`?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||`(no status code or body)`}static generate(t,n,r,i){if(!t||!i)return new d({message:r,cause:s(n)});let a=n?.error;return t===400?new p(t,a,r,i):t===401?new m(t,a,r,i):t===403?new h(t,a,r,i):t===404?new g(t,a,r,i):t===409?new _(t,a,r,i):t===422?new v(t,a,r,i):t===429?new y(t,a,r,i):t>=500?new b(t,a,r,i):new e(t,a,r,i)}},u=class extends l{constructor({message:e}={}){super(void 0,void 0,e||`Request was aborted.`,void 0)}},d=class extends l{constructor({message:e,cause:t}){super(void 0,void 0,e||`Connection error.`,void 0),t&&(this.cause=t)}},f=class extends d{constructor({message:e}={}){super({message:e??`Request timed out.`})}},p=class extends l{},m=class extends l{},h=class extends l{},g=class extends l{},_=class extends l{},v=class extends l{},y=class extends l{},b=class extends l{},x=class extends c{constructor(){super(`Could not parse response content as the length limit was reached`)}},ee=class extends c{constructor(){super(`Could not parse response content as the request was rejected by the content filter`)}},S=class extends Error{constructor(e){super(e)}},C=class extends l{constructor(e,t,n){let r=`OAuth2 authentication error`,i;if(t&&typeof t==`object`){let e=t;i=e.error;let n=e.error_description;n&&typeof n==`string`?r=n:i&&(r=i)}super(e,t,r,n),this.error_code=i}},te=class extends c{constructor(e,t,n){super(e),this.provider=t,this.cause=n}},w=/^[a-z][a-z0-9+.-]*:/i,ne=e=>w.test(e),T=e=>(T=Array.isArray,T(e)),re=T;function ie(e){return typeof e==`object`?e??{}:{}}function ae(e){if(!e)return!0;for(let t in e)return!1;return!0}function E(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function oe(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var se=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t))throw new c(`${e} must be an integer`);if(t<0)throw new c(`${e} must be a positive integer`);return t},ce=e=>{try{return JSON.parse(e)}catch{return}},le=(e,...t)=>new Promise((n,r)=>{let i=[...new Set(t.filter(e=>e!=null))],a,o=!1,s=()=>{for(let e of i)try{e.removeEventListener(`abort`,l)}catch{}},c=e=>{o||(o=!0,a!==void 0&&(clearTimeout(a),a=void 0),s(),e())},l=()=>{c(()=>r())};if(i.some(e=>e.aborted)){l();return}a=setTimeout(()=>{c(n)},e);for(let e of i){if(o)break;try{e.addEventListener(`abort`,l,{once:!0})}catch(e){c(()=>r(e))}}i.some(e=>e.aborted)&&l()}),ue=globalThis,de=typeof ue.FinalizationRegistry==`function`?new ue.FinalizationRegistry(e=>{try{e()}catch{}}):void 0,fe=new WeakMap,pe=new WeakMap;function me(e,t,n){let r=pe.get(e);if(!r){let t=new Set,i=()=>{pe.delete(e);for(let e of t)n.unregister(e),e.deref()?.();t.clear()};r={callbacks:t,abort:i},e.addEventListener(`abort`,i,{once:!0}),pe.set(e,r)}let i=r;return i.callbacks.add(t),()=>{i.callbacks.delete(t),n.unregister(t),i.callbacks.size===0&&(pe.get(e)===i&&pe.delete(e),e.removeEventListener(`abort`,i.abort))}}function he(e,t,n){e.addEventListener(`abort`,()=>t.deref()?.delete(n),{once:!0})}function ge(e,t,n){if(typeof ue.WeakRef==`function`&&de&&!n.aborted){let r=fe.get(e);r||(r=new Set,fe.set(e,r)),r.add(t),he(n,new ue.WeakRef(r),t)}}function _e(e,t,n){if(e.aborted)return t(),()=>{};if(typeof ue.WeakRef!=`function`||!de)return e.addEventListener(`abort`,t,{once:!0}),()=>e.removeEventListener(`abort`,t);let r=new ue.WeakRef(t),i=me(e,r,de);return de.register(t,i,r),ge(n,t,n),i}function ve(){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 ye(...e){let t=globalThis.ReadableStream;if(t===void 0)throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function be(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return ye({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}function xe(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){let e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Se(e){if(typeof e!=`object`||!e)return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),n=t.cancel();t.releaseLock(),await n}var Ce;function we(e){let t;return(Ce??=(t=new globalThis.TextEncoder,t.encode.bind(t)))(e)}var Te;function Ee(e){let t;return(Te??=(t=new globalThis.TextDecoder,t.decode.bind(t)))(e)}var De,D,O,k,Oe,ke,Ae,je=65536,Me=class{constructor(){De.add(this),D.set(this,void 0),O.set(this,void 0),k.set(this,void 0),Oe.set(this,void 0),ke.set(this,void 0),r(this,D,new Uint8Array,`f`),r(this,O,0,`f`),r(this,k,0,`f`),r(this,Oe,0,`f`),r(this,ke,!1,`f`)}decode(e){if(e==null)return[];let t;if(t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==`string`?we(e):e,t.length===0||i(this,ke,`f`)&&(r(this,ke,!1,`f`),t[0]===10&&(t=t.subarray(1)),t.length===0))return[];i(this,De,`m`,Ae).call(this,t);let n=[],a;for(;(a=Ne(i(this,D,`f`),i(this,Oe,`f`),i(this,k,`f`)))!=null;){let e=Ee(i(this,D,`f`).subarray(i(this,O,`f`),a.preceding));n.push(e),r(this,O,a.index,`f`),a.carriage&&(i(this,O,`f`)<i(this,k,`f`)&&i(this,D,`f`)[i(this,O,`f`)]===10?r(this,O,i(this,O,`f`)+1,`f`):i(this,O,`f`)===i(this,k,`f`)&&r(this,ke,!0,`f`)),r(this,Oe,i(this,O,`f`),`f`)}if(r(this,Oe,i(this,k,`f`),`f`),i(this,O,`f`)===i(this,k,`f`))r(this,O,0,`f`),r(this,k,0,`f`),r(this,Oe,0,`f`),i(this,D,`f`).length>je&&r(this,D,new Uint8Array,`f`);else if(n.length>0&&i(this,D,`f`).length>je){let e=i(this,k,`f`)-i(this,O,`f`);if(e<=je||i(this,D,`f`).length>e*4){let t=e<=je?Math.min(Math.max(e*2,256),je):e*2,n=new Uint8Array(t);n.set(i(this,D,`f`).subarray(i(this,O,`f`),i(this,k,`f`))),r(this,D,n,`f`),r(this,O,0,`f`),r(this,k,e,`f`),r(this,Oe,e,`f`)}}return n}flush(){return r(this,ke,!1,`f`),i(this,O,`f`)===i(this,k,`f`)?[]:this.decode(`
2
+ `)}};D=new WeakMap,O=new WeakMap,k=new WeakMap,Oe=new WeakMap,ke=new WeakMap,De=new WeakSet,Ae=function(e){if(i(this,k,`f`)+e.length>i(this,D,`f`).length){let t=i(this,k,`f`)-i(this,O,`f`);if(i(this,O,`f`)>=i(this,D,`f`).length/2&&t+e.length<=i(this,D,`f`).length)i(this,D,`f`).copyWithin(0,i(this,O,`f`),i(this,k,`f`));else{let n=Math.max(i(this,D,`f`).length*2,t+e.length,256),a=new Uint8Array(n);a.set(i(this,D,`f`).subarray(i(this,O,`f`),i(this,k,`f`))),r(this,D,a,`f`)}r(this,Oe,i(this,Oe,`f`)-i(this,O,`f`),`f`),r(this,k,t,`f`),r(this,O,0,`f`)}i(this,D,`f`).set(e,i(this,k,`f`)),r(this,k,i(this,k,`f`)+e.length,`f`)},Me.NEWLINE_CHARS=new Set([`
3
+ `,`\r`]),Me.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Ne(e,t,n){for(let r=t;r<n;r++){if(e[r]===10)return{preceding:r,index:r+1,carriage:!1};if(e[r]===13)return{preceding:r,index:r+1,carriage:!0}}return null}function Pe(e){for(let t=0;t<e.length-1;t++){let n=Fe(e,t);if(n>0){let r=t+n,i=Fe(e,r);if(i>0)return r+i}}return-1}function Fe(e,t){return e[t]===10?1:e[t]===13?e[t+1]===10?2:1:0}var Ie={off:0,error:200,warn:300,info:400,debug:500},Le=(e,t,n)=>{if(e){if(E(Ie,e))return e;A(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(Ie))}`)}};function Re(){}function ze(e,t,n){return!t||Ie[e]>Ie[n]?Re:t[e].bind(t)}var Be={error:Re,warn:Re,info:Re,debug:Re},Ve=new WeakMap;function A(e){let t=e.logger,n=e.logLevel??`off`;if(!t)return Be;let r=Ve.get(t);if(r&&r[0]===n)return r[1];let i={error:ze(`error`,t,n),warn:ze(`warn`,t,n),info:ze(`info`,t,n),debug:ze(`debug`,t,n)};return Ve.set(t,[n,i]),i}var He=new Set([`apikey`,`accesstoken`,`refreshtoken`,`sessiontoken`,`sessionid`,`idtoken`,`authtoken`,`authorization`,`token`,`password`,`clientsecret`,`signingsecret`,`xamzsecuritytoken`,`xamzsignature`,`xamzcredential`]);function Ue(e){let t=e.toLowerCase().replace(/[-_]/gu,``);return He.has(t)||He.has(t.replace(/^x/u,``))}var We=new Set([`authorization`,`proxy-authorization`,`api-key`,`x-api-key`,`x-amz-security-token`,`cookie`,`set-cookie`,`x-session-token`,`x-session-id`,`x-auth-token`,`x-id-token`]);function Ge(e){return We.has(e.toLowerCase().replace(/_/gu,`-`))||Ue(e)}function Ke(e){let t=new URL(e);t.username=``,t.password=``,t.hash=``;for(let e of t.searchParams.keys())Ue(e)&&t.searchParams.set(e,`***`);return t.href}var qe=e=>{if(e.options){if(e.options={...e.options},delete e.options.headers,e.options.path){let t=e.options.path,n=new URL(Ke(new URL(t,`https://redacted.invalid`).href));e.options.path=n.origin===`https://redacted.invalid`?`${t.startsWith(`/`)?`/`:``}${n.pathname.slice(1)}${n.search}`:n.href}e.options.query&&(e.options.query=Object.fromEntries(Object.entries(e.options.query).map(([e,t])=>[e,Ue(e)?`***`:t])))}return e.url&&=Ke(e.url),e.headers&&=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,Ge(e)?`***`:t])),`retryOfRequestLogID`in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e},Je,Ye,Xe,Ze;function Qe(e){return!(e instanceof l)&&o(e)}function $e(){let e=[],t=0,n=!1;return{get length(){return e.length-t},get canceled(){return n},enqueue(t){n||e.push(t)},dequeue(){if(t===e.length)return;let n=e[t];return e[t]=void 0,t+=1,t===e.length?(e=[],t=0):t>=1024&&t*2>=e.length&&(e=e.slice(t),t=0),n},cancel(){n=!0,e.length=0,t=0}}}var et=class e{constructor(e,t,n){Je.add(this),Ye.set(this,void 0),Xe.set(this,!1),this.iterator=e,this.controller=t,r(this,Ye,n,`f`)}static fromSSEResponse(t,n,r,i){let a=!1,o=r?A(r):console;async function*s(){if(a)throw new c("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");a=!0;let e=!1,r=!1,s=nt(t,n),u=s.return.bind(s);s.return=e=>(r||n.abort(),u(e));try{for await(let e of s){if(e.data===`[DONE]`){r=!0;break}if(e.event===null||!e.event.startsWith(`thread.`)){let n;try{n=JSON.parse(e.data)}catch{throw o.error(`Could not parse message into JSON:`),o.error(`From chunk:`),SyntaxError(`Error reading response: malformed server-sent event JSON.`)}if(e.event===`error`)throw new l(void 0,n?.error??n,void 0,t.headers);if(n&&n.error)throw new l(void 0,n.error,void 0,t.headers);yield i?{event:e.event,data:n}:n}else{let t;try{t=JSON.parse(e.data)}catch{throw o.error(`Could not parse message into JSON:`),o.error(`From chunk:`),SyntaxError(`Error reading response: malformed server-sent event JSON.`)}yield{event:e.event,data:t}}}e=!0}catch(e){if(r||Qe(e)||n.signal.aborted&&e===n.signal.reason)return;throw e}finally{e||n.abort()}}return new e(s,n,r)}static fromReadableStream(t,n,r){let i=!1;async function*a(){let e=new Me,r=t.getReader(),i=!1,a,o=()=>{a??=r.cancel(),a.catch(()=>void 0)};n.signal.addEventListener(`abort`,o,{once:!0});try{if(n.signal.aborted){o();return}for(;;){let{value:t,done:a}=await r.read();if(a){i=!0;break}if(n.signal.aborted)return;for(let r of e.decode(t)){if(n.signal.aborted)return;yield r}}if(n.signal.aborted)return;for(let t of e.flush()){if(n.signal.aborted)return;yield t}}finally{n.signal.removeEventListener(`abort`,o),i||o(),r.releaseLock()}}async function*s(){if(i)throw new c("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let e=!1;try{for await(let e of a())if(e){let t;try{t=JSON.parse(e)}catch(e){throw e instanceof SyntaxError?SyntaxError(`Error reading response: malformed newline-delimited JSON.`):e}yield t}e=!0}catch(e){if(n.signal.aborted||o(e))return;throw e}finally{e||n.abort()}}return new e(s,n,r)}[(Ye=new WeakMap,Xe=new WeakMap,Je=new WeakSet,Symbol.asyncIterator)](){return this.iterator()}tee(){let{controller:t}=this,n=$e(),a=$e(),o=this.iterator(),s=e=>({next:()=>{if(e.canceled)return Promise.resolve({value:void 0,done:!0});if(e.length===0){let e=o.next();n.enqueue(e),a.enqueue(e)}return e.dequeue()},return:async()=>(e.canceled||(e.cancel(),n.canceled&&a.canceled&&await i(this,Je,`m`,Ze).call(this,o,t)),{value:void 0,done:!0})}),c=n=>{let a=new e(()=>s(n),t,i(this,Ye,`f`));return r(a,Xe,!0,`f`),a};return[c(n),c(a)]}toReadableStream(){let{controller:e}=this,t,n,r=()=>n??=i(this,Je,`m`,Ze).call(this,t,e);return ye({start:async()=>{t=this[Symbol.asyncIterator]()},async pull(e){try{let{value:n,done:r}=await t.next();if(r)return e.close();let i=we(JSON.stringify(n)+`
4
+ `);e.enqueue(i)}catch(t){e.error(t),r().catch(()=>void 0)}},cancel:r})}};Ze=async function(e,t){let n=e.return;n&&(i(this,Xe,`f`)||t.abort(),await Reflect.apply(n,e,[]))};function tt(e,t){let n=typeof e.getReader==`function`?e.getReader():void 0,r=n?{next:()=>n.read(),return:()=>n.cancel()}:xe(e)[Symbol.asyncIterator](),i={value:void 0,done:!0},a=!1,s=!1,c,l,u=()=>new Promise(e=>{l=e}),d=()=>{if(s||a)return c;s=!0;try{c=Promise.resolve(r.return?.())}catch(e){c=Promise.reject(e)}return c.catch(()=>void 0),c},f=()=>{queueMicrotask(()=>{l?.(),d()})};return{iterator:{async next(){if(t.aborted)return i;let e=u().then(()=>i);try{let n=await Promise.race([r.next(),e]);return t.aborted?i:n.done?(a=!0,i):{value:n.value,done:!1}}catch(e){if(t.aborted&&(o(e)||e===t.reason))return i;throw e}finally{l=void 0}},async return(){let e=d();if(e&&!t.aborted){let n=u();try{t.aborted||await Promise.race([e,n])}finally{l=void 0}}return i},[Symbol.asyncIterator](){return this}},start(){t.addEventListener(`abort`,f,{once:!0}),t.aborted&&f()},async cleanup(e){let r;try{t.removeEventListener(`abort`,f)}catch(e){r=e}if(!a){let n=d();if(n&&!e&&!t.aborted)try{await n}catch(e){r??=e}}if(n)try{n.releaseLock()}catch(e){r??=e}if(r!==void 0&&!e&&!t.aborted)throw r}}}async function*nt(e,t){if(!e.body)throw t.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product===`ReactNative`?new c(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`):new c(`Attempted to iterate over a response with no body`);let n=new at,r=new Me,{signal:i}=t,a=tt(e.body,i),s=!1;try{a.start();for await(let e of it(a.iterator)){if(i.aborted)return;for(let t of r.decode(e)){if(i.aborted)return;let e=n.decode(t);e&&(yield e)}}if(i.aborted)return;for(let e of r.flush()){if(i.aborted)return;let t=n.decode(e);t&&(yield t)}if(i.aborted)return;let e=n.flush();e&&(yield e)}catch(e){if(s=!0,!i.aborted||!o(e)&&e!==i.reason)throw e}finally{await a.cleanup(s)}}var rt=3;async function*it(e){let t=new Uint8Array,n=0,r=0,i=0;for await(let a of e){if(a==null)continue;let e;if(e=a instanceof ArrayBuffer?new Uint8Array(a):typeof a==`string`?we(a):a,r+e.length>t.length){let a=r-n;if(n>=t.length/2&&a+e.length<=t.length)t.copyWithin(0,n,r);else{let i=new Uint8Array(Math.max(t.length*2,a+e.length));i.set(t.subarray(n,r)),t=i}i-=n,n=0,r=a}t.set(e,r),r+=e.length;let o;for(;(o=Pe(t.subarray(i,r)))!==-1;)o+=i,yield t.slice(n,o),n=o,i=n;i=Math.max(n,r-rt)}r>n&&(yield t.slice(n,r))}var at=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith(`\r`)&&(e=e.slice(0,-1)),!e){if(!this.event&&!this.data.length)return null;let e={event:this.event,data:this.data.join(`
5
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(`:`))return null;let[t,,n]=ot(e,`:`),r=n;return r.startsWith(` `)&&(r=r.slice(1)),t===`event`?this.event=r:t===`data`&&this.data.push(r),null}flush(){return this.decode(``)}};function ot(e,t){let n=e.indexOf(t);return n===-1?[e,``,``]:[e.slice(0,n),t,e.slice(n+t.length)]}async function st(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o,s=await(async()=>{if(t.options.stream)return A(e).debug(`response`,n.status,n.url,n.headers,n.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(n,t.controller,e,t.options.__synthesizeEventData):et.fromSSEResponse(n,t.controller,e,t.options.__synthesizeEventData);if(n.status===204)return null;if(t.options.__binaryResponse)return n;let r=n.headers.get(`content-type`)?.split(`;`)[0]?.trim().toLowerCase();if(r?.includes(`application/json`)||r?.endsWith(`+json`)){if(n.headers.get(`content-length`)===`0`)return;let e=await n.text();if(!e)return;let t=JSON.parse(e);return o=e.length,lt(t,n)}return await n.text()})().catch(e=>{throw ct(e,t.controller.signal)});return e.logLevel===`debug`&&A(e).debug(`[${r}] response parsed`,qe({retryOfRequestLogID:i,url:n.url,status:n.status,body:o===void 0?s:{type:`json`,length:o},durationMs:Date.now()-a})),s}function ct(e,t){if(!t.aborted||e!==t.reason||o(e))return e;let n=`This operation was aborted`,r=globalThis.DOMException;return typeof r==`function`?new r(n,`AbortError`):Object.assign(Error(n),{name:`AbortError`})}function lt(e,t){return!e||typeof e!=`object`||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get(`x-request-id`),enumerable:!1})}var ut=`7.19.0`,dt=()=>typeof window<`u`&&window.document!==void 0&&typeof navigator<`u`;function ft(){return typeof Deno<`u`&&Deno.build!=null?`deno`:typeof EdgeRuntime<`u`?`edge`:Object.prototype.toString.call(globalThis.process===void 0?0:globalThis.process)===`[object process]`?`node`:`unknown`}var pt=()=>{let e=ft();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":ut,"X-Stainless-OS":gt(Deno.build.os),"X-Stainless-Arch":ht(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":ut,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":`edge`,"X-Stainless-Runtime-Version":globalThis.process?.version??`unknown`};if(e===`node`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":ut,"X-Stainless-OS":gt(globalThis.process.platform??`unknown`),"X-Stainless-Arch":ht(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=mt();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":ut,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":ut,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}};function mt(){if(typeof navigator>`u`||!navigator)return null;for(let{key:e,pattern:t}of[{key:`edge`,pattern:/\bEdg(?:e|A|iOS)?\b(?:\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/}]){let n=t.exec(navigator.userAgent);if(n)return{browser:e,version:`${n[1]||0}.${n[2]||0}.${n[3]||0}`}}return null}var ht=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,gt=e=>(e=e.toLowerCase(),e.includes(`ios`)?`iOS`:e===`android`?`Android`:e===`darwin`?`MacOS`:e===`win32`?`Windows`:e===`freebsd`?`FreeBSD`:e===`openbsd`?`OpenBSD`:e===`linux`?`Linux`:e?`Other:${e}`:`Unknown`),_t,vt=()=>_t??=pt(),yt=new WeakMap;function bt(e,t){let n=yt.get(e);return n||(n=new Set,yt.set(e,n)),n.add(t),()=>{let n=yt.get(e);n&&(n.delete(t),n.size===0&&yt.delete(e))}}var xt=({headers:e,body:t})=>{let n=typeof t==`object`&&t?yt.get(t):void 0,r;if(!n||n.size===0)r=JSON.stringify(t);else{let e=[...n];r=JSON.stringify(t,function(t,n){let r=n;for(let n of e){let e=n.value(this,t,r);e!==void 0&&(r=e)}return r});for(let t of e)t.complete()}return{bodyHeaders:{"content-type":`application/json`},body:r}},St=`RFC3986`,Ct=String,wt={RFC1738:e=>String(e).replace(/%20/g,`+`),RFC3986:Ct},Tt,Et=(e,t)=>{let n=Tt??Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty);return Tt=n,n(e,t)},Dt=(()=>{let e=[];for(let t=0;t<256;++t)e.push(`%`+((t<16?`0`:``)+t.toString(16)).toUpperCase());return e})(),Ot=1024,kt=(e,t,n,r,i)=>{if(e.length===0)return e;let a=e;if(typeof e==`symbol`?a=Symbol.prototype.toString.call(e):typeof e!=`string`&&(a=String(e)),n===`iso-8859-1`)return escape(a).replace(/%u[0-9a-f]{4}/gi,e=>`%26%23`+Number.parseInt(e.slice(2),16)+`%3B`);let o=``;for(let e=0;e<a.length;){let t=Math.min((Math.floor(e/Ot)+1)*Ot,a.length);t<a.length&&a.codePointAt(t-1)>65535&&(t+=1);let n=a.length>=Ot?a.slice(e,t):a,r=[];for(let e=0;e<n.length;++e){let t=n.charCodeAt(e);if(t===45||t===46||t===95||t===126||t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||i===`RFC1738`&&(t===40||t===41)){r[r.length]=n.charAt(e);continue}if(t<128){r[r.length]=Dt[t];continue}if(t<2048){r[r.length]=Dt[192|t>>6]+Dt[128|t&63];continue}if(t<55296||t>=57344){r[r.length]=Dt[224|t>>12]+Dt[128|t>>6&63]+Dt[128|t&63];continue}e+=1,t=65536+((t&1023)<<10|n.charCodeAt(e)&1023),r[r.length]=Dt[240|t>>18]+Dt[128|t>>12&63]+Dt[128|t>>6&63]+Dt[128|t&63]}o+=r.join(``),e=t}return o};function At(e){return!e||typeof e!=`object`?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function jt(e,t){if(T(e)){let n=[];for(let r of e)n.push(t(r));return n}return t(e)}var Mt={brackets(e){return String(e)+`[]`},comma:`comma`,indices(e,t){return String(e)+`[`+t+`]`},repeat(e){return String(e)}},Nt=function(e,t){Array.prototype.push.apply(e,T(t)?t:[t])},Pt,j={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:`indices`,charset:`utf-8`,charsetSentinel:!1,delimiter:`&`,encode:!0,encodeDotInKeys:!1,encoder:kt,encodeValuesOnly:!1,format:St,formatter:Ct,indices:!1,serializeDate(e){return(Pt??=Function.prototype.call.bind(Date.prototype.toISOString))(e)},skipNulls:!1,strictNullHandling:!1};function Ft(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`symbol`||typeof e==`bigint`}var It={};function Lt(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_){let v=e,y=_,b=0,x=!1;for(;(y=y.get(It))!==void 0&&!x;){let t=y.get(e);if(b+=1,t!==void 0){if(t===b)throw RangeError(`Cyclic object value`);x=!0}y.get(It)===void 0&&(b=0)}if(typeof l==`function`?v=l(t,v):v instanceof Date?v=f?.(v):n===`comma`&&T(v)&&(v=jt(v,e=>e instanceof Date?f?.(e):e)),v===null){if(a)return c&&!h?c(t,j.encoder,g,`key`,p):t;v=``}if(Ft(v)||At(v)){if(c){let e=h?t:c(t,j.encoder,g,`key`,p);return[m?.(e)+`=`+m?.(c(v,j.encoder,g,`value`,p))]}return[m?.(t)+`=`+m?.(String(v))]}let ee=[];if(v===void 0)return ee;let S;if(n===`comma`&&T(v))h&&c&&(v=jt(v,c)),S=[{value:v.length>0?v.join(`,`)||null:void 0}];else if(T(l))S=l;else{let e=Object.keys(v);u&&e.sort(u),S=e}let C=s?String(t).replace(/\./g,`%2E`):String(t),te=r&&T(v)&&v.length===1?C+`[]`:C;if(i&&T(v)&&v.length===0)return te+`[]`;for(let t of S){let y=typeof t==`object`&&t.value!==void 0?t.value:v[t];if(o&&y===null)continue;let x=d&&s?t.replace(/\./g,`%2E`):t,S;S=T(v)?typeof n==`function`?n(te,x):te:te+(d?`.`+x:`[`+x+`]`),_.set(e,b);let C=new WeakMap([[It,_]]);Nt(ee,Lt(y,S,n,r,i,a,o,s,n===`comma`&&h&&T(v)?null:c,l,u,d,f,p,m,h,g,C))}return ee}function Rt(e=j){if(e.allowEmptyArrays!==void 0&&typeof e.allowEmptyArrays!=`boolean`)throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(e.encodeDotInKeys!==void 0&&typeof e.encodeDotInKeys!=`boolean`)throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&e.encoder!==void 0&&typeof e.encoder!=`function`)throw TypeError(`Encoder has to be a function.`);let t=e.charset||j.charset;if(e.charset!==void 0&&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 n=St;if(e.format!==void 0){if(!Et(wt,e.format))throw TypeError(`Unknown format option provided.`);n=e.format}let r=wt[n],i=j.filter;(typeof e.filter==`function`||T(e.filter))&&(i=e.filter);let a;if(a=e.arrayFormat&&e.arrayFormat in Mt?e.arrayFormat:`indices`in e?e.indices?`indices`:`repeat`:j.arrayFormat,`commaRoundTrip`in e&&typeof e.commaRoundTrip!=`boolean`)throw TypeError("`commaRoundTrip` must be a boolean, or absent");let o;return o=e.allowDots===void 0?e.encodeDotInKeys?!0:j.allowDots:!!e.allowDots,{addQueryPrefix:typeof e.addQueryPrefix==`boolean`?e.addQueryPrefix:j.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof e.allowEmptyArrays==`boolean`?!!e.allowEmptyArrays:j.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel==`boolean`?e.charsetSentinel:j.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:e.delimiter===void 0?j.delimiter:e.delimiter,encode:typeof e.encode==`boolean`?e.encode:j.encode,encodeDotInKeys:typeof e.encodeDotInKeys==`boolean`?e.encodeDotInKeys:j.encodeDotInKeys,encoder:typeof e.encoder==`function`?e.encoder:j.encoder,encodeValuesOnly:typeof e.encodeValuesOnly==`boolean`?e.encodeValuesOnly:j.encodeValuesOnly,filter:i,format:n,formatter:r,serializeDate:typeof e.serializeDate==`function`?e.serializeDate:j.serializeDate,skipNulls:typeof e.skipNulls==`boolean`?e.skipNulls:j.skipNulls,sort:typeof e.sort==`function`?e.sort:null,strictNullHandling:typeof e.strictNullHandling==`boolean`?e.strictNullHandling:j.strictNullHandling}}function zt(e,t={}){let n=e,r=Rt(t),i,a;typeof r.filter==`function`?(a=r.filter,n=a(``,n)):T(r.filter)&&(a=r.filter,i=a);let o=[];if(typeof n!=`object`||!n)return``;let s=Mt[r.arrayFormat],c=s===`comma`&&r.commaRoundTrip;i||=Object.keys(n),r.sort&&i.sort(r.sort);let l=new WeakMap;for(let e of i)r.skipNulls&&n[e]===null||Nt(o,Lt(n[e],e,s,c,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,l));let u=o.join(r.delimiter),d=r.addQueryPrefix===!0?`?`:``;return r.charsetSentinel&&(d+=r.charset===`iso-8859-1`?`utf8=%26%2310003%3B&`:`utf8=%E2%9C%93&`),u.length>0?d+u:``}function Bt(e){return zt(e,{arrayFormat:`brackets`})}var Vt=new Map([[`global`,`https://api.openai.com/v1`],[`us`,`https://us.api.openai.com/v1`],[`eu`,`https://eu.api.openai.com/v1`],[`ae`,`https://ae.api.openai.com/v1`]]);function Ht(e){if(e.dataResidency===null||e.dataResidency===void 0)return;if(E(e,`baseURL`))throw new c("The `dataResidency` and `baseURL` options are mutually exclusive.");let t=Vt.get(e.dataResidency);if(t===void 0)throw new c("Invalid `dataResidency`; expected one of: global, us, eu, ae.");return t}function Ut(e,t){if(e!=null)throw new c(`${t} does not support \`dataResidency\`.`)}var Wt,Gt=class e extends Promise{constructor(e,t,n=st){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=n,Wt.set(this,void 0),r(this,Wt,e,`f`)}_thenUnwrap(t){return new e(i(this,Wt,`f`),this.responsePromise,async(e,n)=>lt(t(await this.parseResponse(e,n),n),n.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(){return this.parsedPromise||=this.responsePromise.then(e=>this.parseResponse(i(this,Wt,`f`),e)),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)}};Wt=new WeakMap;var Kt,qt=class{constructor(e,t,n,i){Kt.set(this,void 0),r(this,Kt,e,`f`),this.options=i,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new c("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await i(this,Kt,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Kt=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},Jt=class extends Gt{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await st(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},Yt=class extends qt{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},M=class extends qt{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more!==!1&&super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...ie(this.options.query),after:t}}:null}},N=class extends qt{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.last_id=n.last_id||``}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more!==!1&&super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...ie(this.options.query),after:e}}:null}},Xt=class extends qt{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.next=n.next||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more!==!1&&this.nextPageRequestOptions()!=null}nextPageRequestOptions(){let e=this.next;return e?{...this.options,query:{...ie(this.options.query),after:e}}:null}},Zt=class extends qt{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.next=n.next||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more!==!1&&this.nextPageRequestOptions()!=null}nextPageRequestOptions(){let e=this.next;return e?{...this.options,query:{...ie(this.options.query),page:e}}:null}},Qt={jwt:`urn:ietf:params:oauth:token-type:jwt`,id:`urn:ietf:params:oauth:token-type:id_token`},$t=`urn:ietf:params:oauth:grant-type:token-exchange`,en=.5;function tn(e,t){if(typeof e!=`number`||!Number.isFinite(e)||e<=0)throw new c(`Token exchange response has invalid 'expires_in' field`);let n=Date.now(),r=n+e*1e3;if(!Number.isSafeInteger(r)||r<=n)throw new c(`Token exchange response has invalid 'expires_in' field`);let i=r-(performance.now()-t);if(i<=n)throw new c(`Workload identity token expired before its exchange completed.`);return i}function nn(e,t,n){let r=(n??1200)*1e3;return e-Math.min(r,t*1e3*en)}var rn=Response.prototype,an=rn.arrayBuffer;function on(e,t){let n=Object.getOwnPropertyDescriptor(t,`constructor`)?.value;if(t===e||typeof n!=`function`||Object.getOwnPropertyDescriptor(n,`name`)?.value!==`Response`||Object.getOwnPropertyDescriptor(n,`prototype`)?.value!==t)return!1;let r=Object.getOwnPropertyDescriptor(t,Symbol.toStringTag);return(r?.value===`Response`||typeof r?.get==`function`)&&typeof Object.getOwnPropertyDescriptor(t,`headers`)?.get==`function`&&typeof Object.getOwnPropertyDescriptor(t,`ok`)?.get==`function`&&typeof Object.getOwnPropertyDescriptor(t,`status`)?.get==`function`}function sn(e,t){if(e===t)return!0;let n=Object.getOwnPropertyDescriptor(e,`constructor`)?.value;return t!==null&&Object.getPrototypeOf(t)===e&&typeof n==`function`&&Object.getOwnPropertyDescriptor(n,`name`)?.value===`Body`&&Object.getOwnPropertyDescriptor(n,`prototype`)?.value===e}function cn(e){return new TextDecoder(`utf-8`,{ignoreBOM:typeof globalThis.Bun?.version==`string`}).decode(e)}async function ln(e){let t,n=null;for(let r=0,i=e;i!==null&&r<16&&i!==rn;i=Object.getPrototypeOf(i),r+=1){on(e,i)&&(n=i);let r=Object.getOwnPropertyDescriptor(i,`json`);if(!r)continue;if(typeof r.value!=`function`)break;let a=Object.getOwnPropertyDescriptor(i,`text`)?.value;if(typeof a==`function`&&sn(i,n)){t=a;break}return r.value.call(e)}let r=t===void 0?cn(await an.call(e)):await t.call(e);try{return JSON.parse(r)}catch{throw SyntaxError(`Token exchange response contains invalid JSON`)}}function un(e){return typeof globalThis.Bun?.version==`string`?/[^\t\u0020-\u007E]|^[\t ]|[\t ]$/u.test(e):/[^\t\u0020-\u007E\u0080-\u00FF]|^[\t ]|[\t ]$/u.test(e)}var dn=class e{constructor(e,t){this.cachedToken=null,this.refreshPromise=null,this.tokenGeneration=0,this.tokenExchangeUrl=`https://auth.openai.com/oauth/token`;let{identityProviderId:n,serviceAccountId:r,clientId:i,refreshBufferSeconds:a,provider:o}=e;this.config={identityProviderId:n,serviceAccountId:r,...i===void 0?{}:{clientId:i},...a===void 0?{}:{refreshBufferSeconds:a},provider:{tokenType:o.tokenType,getToken:o.getToken.bind(o)}},this.fetch=t??ve()}async getToken(){if(!this.cachedToken||e.isTokenExpired(this.cachedToken)){if(this.refreshPromise)return await this.refreshPromise;let e=this.refreshToken(this.tokenGeneration);this.refreshPromise=e;try{return await e}finally{this.refreshPromise===e&&(this.refreshPromise=null)}}if(e.needsRefresh(this.cachedToken)&&!this.refreshPromise){let e=this.refreshToken(this.tokenGeneration).finally(()=>{this.refreshPromise===e&&(this.refreshPromise=null)});this.refreshPromise=e,e.catch(()=>null)}return this.cachedToken.token}async refreshToken(e){let t={grant_type:$t,subject_token:await this.config.provider.getToken(),subject_token_type:Qt[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId};this.config.clientId&&(t.client_id=this.config.clientId);let n=performance.now(),r=await this.fetch(this.tokenExchangeUrl,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t),redirect:`manual`});if(!r.ok){let e=await r.text(),t;try{t=JSON.parse(e)}catch{}throw r.status===400||r.status===401||r.status===403?new C(r.status,t,r.headers):l.generate(r.status,t,`Token exchange failed with status ${r.status}`,r.headers)}let i=await ln(r),a=typeof i==`object`&&i&&`access_token`in i?i.access_token:void 0;if(typeof a!=`string`||a.trim().length===0||un(a))throw new c(`Token exchange response missing 'access_token' field`);let o=i.expires_in??3600,s=tn(o,n);return this.tokenGeneration===e&&(this.cachedToken={token:a,expiresAt:s,refreshAt:nn(s,o,this.config.refreshBufferSeconds)}),a}static isTokenExpired(e){return Date.now()>=e.expiresAt}static needsRefresh(e){return Date.now()>=e.refreshAt}invalidateToken(){this.tokenGeneration+=1,this.cachedToken=null,this.refreshPromise=null}};function fn(e){let t;try{t=new URL(e)}catch{throw new c(`X.509 workload identity requires the approved global mTLS API origin.`)}if(t.origin!==`https://mtls.api.openai.com`||t.username||t.password)throw new c(`X.509 workload identity requires the approved global mTLS API origin.`);for(let e of t.searchParams.keys())if(Ue(e))throw new c(`X.509 workload identity cannot send conflicting query authentication credentials.`);return t}var pn=Symbol(`brand.privateNullableHeaders`),mn=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function*hn(e){if(!e)return;if(pn in e){let{values:t,nulls:n}=e;yield*t.entries();for(let e of n)yield[e,null];return}let t=!1,n,r=Symbol.iterator in e?e[Symbol.iterator]:void 0;typeof r==`function`?n={[Symbol.iterator]:()=>r.call(e)}:(t=!0,n=Object.entries(e??{}));for(let e of n){let n=e[0];if(typeof n!=`string`)throw TypeError(`expected header name to be a string`);let r=re(e[1])?e[1]:[e[1]],i=!1;for(let e of r)e!==void 0&&(t&&!i&&(i=!0,yield[n,null]),yield[n,e])}}var P=e=>{let t=new Headers,n=new Set;for(let r of e){let e=new Set;for(let[i,a]of hn(r)){if(!mn.test(i))throw TypeError(`Header name must be a valid HTTP token ["${i}"]`);let r=i.toLowerCase();e.has(r)||(t.delete(r),e.add(r)),a===null?(t.delete(r),n.add(r)):(t.append(r,a),n.delete(r))}}return{[pn]:!0,values:t,nulls:n}},gn=e({findRegisteredX509Transport:()=>Cn,findX509Credential:()=>Pn,findX509OAuthError:()=>Mn,isApprovedX509Client:()=>An,isRetryableX509IssuerError:()=>On,isTransientX509ConnectionError:()=>En,markApprovedX509Client:()=>kn,markRetryableX509IssuerError:()=>Dn,markTransientX509ConnectionError:()=>Tn,rememberRegisteredX509Transport:()=>wn,rememberX509Credential:()=>Nn,rememberX509OAuthError:()=>jn}),_n=new WeakMap,vn=new WeakSet,yn=new WeakSet,bn=new WeakSet,xn=new WeakMap,Sn=new WeakMap,Cn=WeakMap.prototype.get.bind(_n),wn=WeakMap.prototype.set.bind(_n),Tn=WeakSet.prototype.add.bind(vn),En=WeakSet.prototype.has.bind(vn),Dn=WeakSet.prototype.add.bind(yn),On=WeakSet.prototype.has.bind(yn),kn=WeakSet.prototype.add.bind(bn),An=WeakSet.prototype.has.bind(bn),jn=WeakMap.prototype.set.bind(xn),Mn=WeakMap.prototype.get.bind(xn),Nn=WeakMap.prototype.set.bind(Sn),Pn=WeakMap.prototype.get.bind(Sn),Fn=t(n(((e,t)=>{if(t!==void 0&&t!==globalThis.module&&e!==void 0&&t.exports===e){Object.defineProperty(e,"__esModule",{value:!0}),e.findX509Credential=e.rememberX509Credential=e.findX509OAuthError=e.rememberX509OAuthError=e.isApprovedX509Client=e.markApprovedX509Client=e.isRetryableX509IssuerError=e.markRetryableX509IssuerError=e.isTransientX509ConnectionError=e.markTransientX509ConnectionError=e.rememberRegisteredX509Transport=e.findRegisteredX509Transport=void 0;let t=new WeakMap,n=new WeakSet,r=new WeakSet,i=new WeakSet,a=new WeakMap,o=new WeakMap;e.findRegisteredX509Transport=WeakMap.prototype.get.bind(t),e.rememberRegisteredX509Transport=WeakMap.prototype.set.bind(t),e.markTransientX509ConnectionError=WeakSet.prototype.add.bind(n),e.isTransientX509ConnectionError=WeakSet.prototype.has.bind(n),e.markRetryableX509IssuerError=WeakSet.prototype.add.bind(r),e.isRetryableX509IssuerError=WeakSet.prototype.has.bind(r),e.markApprovedX509Client=WeakSet.prototype.add.bind(i),e.isApprovedX509Client=WeakSet.prototype.has.bind(i),e.rememberX509OAuthError=WeakMap.prototype.set.bind(a),e.findX509OAuthError=WeakMap.prototype.get.bind(a),e.rememberX509Credential=WeakMap.prototype.set.bind(o),e.findX509Credential=WeakMap.prototype.get.bind(o)}}))(),1),{findRegisteredX509Transport:In,rememberRegisteredX509Transport:Ln,markTransientX509ConnectionError:Rn,isTransientX509ConnectionError:zn,markRetryableX509IssuerError:Bn,isRetryableX509IssuerError:Vn,markApprovedX509Client:Hn,isApprovedX509Client:Un,rememberX509OAuthError:Wn,findX509OAuthError:Gn,rememberX509Credential:Kn,findX509Credential:qn}=typeof Fn.findRegisteredX509Transport==`function`?Fn:gn;function Jn(e){if(!e||typeof e!=`object`)throw new c(`X.509 workload identity requires an approved X.509 transport capability.`);let t=In(e);if(!t)throw new c(`X.509 workload identity requires an approved X.509 transport capability.`);return t}var F,Yn,Xn,Zn,Qn,$n,er,tr,I,nr,rr,ir,ar,or,sr,cr,lr,ur,dr,fr,pr,L,mr,hr=[`dispatcher`,`agent`,`client`,`tls`,`proxy`],gr=(e,t)=>Headers.prototype.get.call(e,t),_r=12e5,vr=1e3,yr=e=>{let t=new u;return Object.defineProperty(t,"cause",{value:e.reason,writable:!0,configurable:!0}),t};function br(e){for(let t of Headers.prototype.keys.call(e)){let e=t.toLowerCase().split(`_`).join(`-`);if(e!==`authorization`&&Ge(e)||e===`host`)throw new c(`X.509 workload identity cannot send conflicting authentication credentials.`)}}function xr(e,t){let n=new AbortController,r=e===void 0?void 0:setTimeout(()=>n.abort(new f),e),i=r;typeof i==`object`&&i&&`unref`in i&&typeof i.unref==`function`&&i.unref();let a=()=>n.abort(t?.reason);return t?.addEventListener(`abort`,a,{once:!0}),t?.aborted&&a(),{signal:n.signal,dispose:()=>{t?.removeEventListener(`abort`,a),r&&clearTimeout(r)}}}function Sr(e,t){let n,r=new Promise((e,r)=>{n=()=>r(t.reason),t.addEventListener(`abort`,n,{once:!0}),t.aborted&&n()});return{result:Promise.race([e.promise,r]),dispose:()=>{n&&t.removeEventListener(`abort`,n)}}}function Cr(e){if(!e||typeof e!=`object`)return!1;let t=e;for(;t!==null&&t!==Object.prototype;){let e=Object.getOwnPropertyDescriptor(t,`provider`);if(e){if(!(`value`in e)||e.value!==void 0)return!1;break}t=Object.getPrototypeOf(t)}let n=e;for(;n!==null&&n!==Object.prototype;){let e=Object.getOwnPropertyDescriptor(n,`type`);if(e){if(!(`value`in e))throw new c(`X.509 workload identity type must be a plain data property.`);return e.value===`x509`}n=Object.getPrototypeOf(n)}return!1}function wr(e){if(!e)return;for(let t of hr)if(E(e,t))throw new c(`X.509 workload identity cannot override its approved transport capability.`);let t=Object.getOwnPropertyDescriptor(e,`redirect`)?.value;if(t!==void 0&&t!==`manual`)throw new c(`X.509 workload identity requests require manual redirects.`)}function Tr(e){if(wr(e),e&&[`body`,`headers`,`method`,`signal`].some(t=>E(e,t)))throw new c(`X.509 workload identity cannot override its request body, headers, method, or signal through fetch options.`)}function Er(e){Tr(e);let t={...e};return Tr(t),t}var Dr=class{constructor(e,t,n,a){if(F.add(this),Xn.set(this,void 0),Zn.set(this,void 0),Qn.set(this,void 0),$n.set(this,void 0),er.set(this,void 0),tr.set(this,void 0),I.set(this,void 0),nr.set(this,void 0),rr.set(this,void 0),ir.set(this,void 0),ar.set(this,0),r(this,I,Jn(t),`f`),r(this,Xn,e.identityProviderId,`f`),r(this,Zn,e.serviceAccountId,`f`),r(this,Qn,e.refreshBufferMs,`f`),r(this,$n,e.refreshBufferSeconds,`f`),r(this,er,n,`f`),r(this,tr,a,`f`),i(this,Qn,`f`)!==void 0&&i(this,$n,`f`)!==void 0)throw new c(`X.509 workload identity cannot combine refreshBufferSeconds and refreshBufferMs.`);if(i(this,Qn,`f`)!==void 0&&(!Number.isSafeInteger(i(this,Qn,`f`))||i(this,Qn,`f`)<0))throw new c(`X.509 workload identity requires a nonnegative integer refreshBufferMs.`);if(i(this,$n,`f`)!==void 0&&(!Number.isSafeInteger(i(this,$n,`f`))||i(this,$n,`f`)<0||!Number.isSafeInteger(i(this,$n,`f`)*1e3)))throw new c(`X.509 workload identity requires a nonnegative integer refreshBufferSeconds.`);r(this,nr,i(this,$n,`f`)===void 0?i(this,Qn,`f`)??_r:i(this,$n,`f`)*1e3,`f`)}identitySnapshot(){return{type:`x509`,identityProviderId:i(this,Xn,`f`),serviceAccountId:i(this,Zn,`f`),...i(this,Qn,`f`)===void 0?{}:{refreshBufferMs:i(this,Qn,`f`)},...i(this,$n,`f`)===void 0?{}:{refreshBufferSeconds:i(this,$n,`f`)}}}static shouldAuthenticate(e,t,n=e.headers){return!P([t,n]).nulls.has(`authorization`)}snapshotHeaders(e,t){let n=i(this,F,`m`,L).call(this);return n.defaultHeaders??=P([e]),n.requestHeaders??=P([t]),this.headerSnapshots()}headerSnapshots(){let{defaultHeaders:e,requestHeaders:t}=i(this,F,`m`,L).call(this);if(!e||!t)throw new c(`X.509 workload identity requires snapshotted request headers.`);return{defaultHeaders:e,requestHeaders:t}}snapshotTenant(e,t){if(e!==i(this,er,`f`)||t!==i(this,tr,`f`))throw new c(`X.509 workload identity cannot override its enrolled organization or project.`);let n=i(this,F,`m`,L).call(this);return n.tenant={organization:e,project:t},n.tenant}tenantSnapshot(){let{tenant:e}=i(this,F,`m`,L).call(this);if(!e)throw new c(`X.509 workload identity requires snapshotted tenant selectors.`);return e}snapshotAPIURL(e){fn(e),i(this,F,`m`,L).call(this).apiURL=e}requestAPIURL(){let{apiURL:e}=i(this,F,`m`,L).call(this);if(e===void 0)throw new c(`X.509 workload identity requires a snapshotted API destination.`);return e}snapshotRequest(e,t,n){var r;(r=i(this,F,`m`,L).call(this)).request??(r.request={signal:e,timeout:t,fetchOptions:n})}requestSnapshot(){let{request:e}=i(this,F,`m`,L).call(this);if(!e)throw new c(`X.509 workload identity requires snapshotted request settings.`);return e}beginRequestPreparation(){let e=i(this,F,`m`,L).call(this);e.deadlineArmed&&e.preparationStartedAt===void 0&&(e.preparationStartedAt=performance.now(),e.preparationWallStartedAt=Date.now())}beginRequestPlanning(){i(this,F,`m`,L).call(this).phase=`planning`}beginRequestNetwork(){let e=i(this,F,`m`,L).call(this);e.deadlineArmed?e.preparationStartedAt!==void 0&&(e.monotonicStartedAt+=performance.now()-e.preparationStartedAt,e.wallStartedAt+=Date.now()-(e.preparationWallStartedAt??Date.now()),delete e.preparationStartedAt,delete e.preparationWallStartedAt):(e.wallStartedAt=Date.now(),e.monotonicStartedAt=performance.now(),e.deadlineArmed=!0)}isPlanningRequest(){return i(this,F,`m`,L).call(this).phase===`planning`}authorizePlannedRequest(e,t,n,r=!1){let a=i(this,F,`m`,L).call(this),o=Object.getOwnPropertyDescriptor(t,`headers`),s=Object.getOwnPropertyDescriptor(t,`body`),l=Object.getOwnPropertyDescriptor(t,`signal`),u=Object.getOwnPropertyDescriptor(t,`redirect`);if(a.phase!==`planning`||!o||!(o.value instanceof Headers)||!s&&`body`in t||[s,l,u].some(e=>e&&!(`value`in e)))throw new c(`X.509 workload identity requires an approved final request.`);this.snapshotAPIURL(e),wr(t);try{br(o.value)}catch{throw new c(`X.509 workload identity cannot use caller-supplied authentication credentials.`)}if(gr(o.value,`Authorization`)!==null)throw new c(`X.509 workload identity cannot use caller-supplied authorization credentials.`);if(i(this,F,`m`,mr).call(this,o.value),!r&&(l?.value??void 0)!==(this.requestSnapshot().signal??void 0))throw new c(`X.509 workload identity must preserve its approved request signal.`);let d=this.requestSnapshot();a.request={...d,timeout:Math.min(d.timeout,n)},a.phase=`authorizing`}ownRequestBody(e,t){e instanceof ReadableStream&&e!==t&&(i(this,F,`m`,L).call(this).materializedBody=e)}static isStreamingRequestBody(e){return globalThis.ReadableStream!==void 0&&e instanceof globalThis.ReadableStream||typeof e==`object`&&!!e&&(Symbol.asyncIterator in e||Symbol.iterator in e&&`next`in e&&typeof e.next==`function`)}retireRequestBody(){let e=i(this,F,`m`,L).call(this),t=e.materializedBody;delete e.materializedBody,t&&i(Yn,Yn,`m`,or).call(Yn,t)}releaseRequestBody(e){let t=i(this,F,`m`,L).call(this);t.materializedBody===e?delete t.materializedBody:this.retireRequestBody()}setEffectiveSignal(e){e?i(this,F,`m`,L).call(this).effectiveSignal=e:delete i(this,F,`m`,L).call(this).effectiveSignal}effectiveSignal(){let e=i(this,F,`m`,L).call(this);return e.effectiveSignal??e.request?.signal}runRequest(e,t){return i(this,I,`f`).run(async()=>{let n=i(this,I,`f`).current();if(!n)throw new c(`X.509 workload identity requires an active certificate request scope.`);n.owner=this,n.requestOwner=t;try{return await e()}finally{this.retireRequestBody(),this.releaseRequestCredentials(),delete n.requestOwner,delete n.owner}})}inRequest(e){let t=i(this,I,`f`).current();return t?.owner===this&&t.requestOwner===e&&t.phase!==`authorizing`}matches(e){return i(this,I,`f`)===i(e,I,`f`)&&i(this,Xn,`f`)===i(e,Xn,`f`)&&i(this,Zn,`f`)===i(e,Zn,`f`)&&i(this,er,`f`)===i(e,er,`f`)&&i(this,tr,`f`)===i(e,tr,`f`)&&i(this,nr,`f`)===i(e,nr,`f`)}continuation(){let{wallStartedAt:e,monotonicStartedAt:t,deadlineArmed:n,request:r,requestOwner:a,effectiveSignal:o}=i(this,F,`m`,L).call(this),s={wallStartedAt:e,monotonicStartedAt:t,owner:this,...n?{deadlineArmed:n}:{},...r?{request:r}:{},...o?{effectiveSignal:o}:{},...a?{requestOwner:a}:{}};return e=>i(this,I,`f`).resume(s,async()=>{try{return await e()}finally{this.releaseRequestCredentials(),delete s.requestOwner,delete s.owner}})}releaseRequestCredentials(){let e=i(this,F,`m`,L).call(this);delete e.request,delete e.phase,delete e.deadlineArmed,delete e.preparationStartedAt,delete e.preparationWallStartedAt,delete e.effectiveSignal,delete e.materializedBody,delete e.apiURL,delete e.tenant,delete e.token,delete e.defaultHeaders,delete e.requestHeaders,delete e.tokenGeneration,delete e.headers,delete e.authorization}requestStartedAt(e){return i(this,I,`f`).current()?.wallStartedAt}usedWorkloadToken(e){return i(this,I,`f`).current()?.token!==void 0}remainingTimeout(e,t){let n=i(this,I,`f`).current();if(n===void 0)return t;let r=t-(performance.now()-n.monotonicStartedAt);if(r<=0)throw new f;return r}async waitForRetry(e,t){try{await i(this,I,`f`).sleep(e,t)}catch(e){throw t?.aborted?yr(t):e}}static isRetryableFailure(e){return typeof e==`object`&&!!e&&(zn(e)||Vn(e))}static retryHeaders(e){if(!e||typeof e!=`object`||!Vn(e))return;let t=Object.getOwnPropertyDescriptor(e,`headers`)?.value;return t instanceof Headers?t:void 0}async getToken(e,t){let n=t?t.signal:e?.signal;if(n?.aborted)throw yr(n);e&&Tr(t?t.fetchOptions:e.fetchOptions),i(this,F,`m`,pr).call(this,t);let r=e?i(this,F,`m`,L).call(this):void 0,a=i(this,rr,`f`);if(a&&performance.now()<a.refreshAt&&Date.now()<a.wallRefreshAt)return i(Yn,Yn,`m`,sr).call(Yn,r,a);let{signal:o,dispose:s}=xr(t&&e?this.remainingTimeout(e,t.timeout):t?.timeout,n);if(n?.aborted)throw s(),yr(n);let c=i(this,ir,`f`)??i(this,F,`m`,dr).call(this);c.waiters+=1;let l=Sr(c,o);try{let e=await l.result,t=i(this,rr,`f`);if(!t||t.accessToken!==e.accessToken)throw new u;return i(Yn,Yn,`m`,sr).call(Yn,r,t)}catch(n){return await i(this,F,`m`,cr).call(this,n,c,a,r,e,t)}finally{l.dispose(),s(),--c.waiters,i(this,F,`m`,ur).call(this,c)}}invalidateToken(){let e=i(this,I,`f`).current();if(!e?.token||i(this,rr,`f`)?.accessToken!==e.token||i(this,rr,`f`).generation!==e.tokenGeneration)return;r(this,ar,i(this,ar,`f`)+1,`f`),r(this,rr,void 0,`f`);let t=i(this,ir,`f`);r(this,ir,void 0,`f`),t?.controller.abort(new u)}bindRequest(e,t,n){if(!(t.headers instanceof Headers))throw new c(`X.509 workload identity requires the original workload authorization headers.`);let r=i(this,F,`m`,L).call(this),{token:a}=r,o=e.__security??{bearerAuth:!0},s=a?`Bearer ${a}`:null;!a&&o.adminAPIKeyAuth&&n!==null&&gr(t.headers,`Authorization`)!==null&&(s=new Headers({Authorization:`Bearer ${n}`}).get(`Authorization`)),r.headers=t.headers,r.authorization=s,this.assertRequest(t)}adoptRequestHeaders(e){let t=i(this,F,`m`,L).call(this),n=t.headers;if(!(n instanceof Headers)||!(e.headers instanceof Headers))throw new c(`X.509 workload identity must preserve its issued workload authorization.`);t.headers=e.headers;try{this.assertRequest(e)}catch(e){throw t.headers=n,e}}assertRequest(e){let{headers:t}=e;if(!(t instanceof Headers))throw new c(`X.509 workload identity must preserve its issued workload authorization.`);let n=i(this,I,`f`).current();if(!n||n.headers!==t||n.authorization===void 0||gr(t,`Authorization`)!==n.authorization)throw new c(`X.509 workload identity must preserve its issued workload authorization.`);i(this,F,`m`,mr).call(this,t),br(t)}fetch(){return async(e,t={})=>{let n=fn(typeof e==`string`||e instanceof URL?e:e.url);wr(t),this.assertRequest(t);let r=t.headers;if(!(r instanceof Headers))throw new c(`X.509 workload identity must preserve its issued workload authorization.`);let a=new Headers([...Headers.prototype.entries.call(r)]);return br(a),t.headers=a,t.redirect=`manual`,await i(this,I,`f`).dispatch(n,t)}}};Yn=Dr,Xn=new WeakMap,Zn=new WeakMap,Qn=new WeakMap,$n=new WeakMap,er=new WeakMap,tr=new WeakMap,I=new WeakMap,nr=new WeakMap,rr=new WeakMap,ir=new WeakMap,ar=new WeakMap,F=new WeakSet,or=async function(e){try{await Se(e)}catch{}},sr=function(e,t){return e&&(e.token=t.accessToken,e.tokenGeneration=t.generation),t.accessToken},cr=async function(e,t,n,r,a,o){let s=o?o.signal:a?.signal;if(s?.aborted)throw yr(s);if(t.controller.signal.aborted&&t.generation!==i(this,ar,`f`))return await this.getToken(a,o);let c=i(this,F,`m`,lr).call(this,e,n,r);if(c!==void 0)return c;if(e&&typeof e==`object`&&!(e instanceof C)){let t=Gn(e);if(t)throw new C(t.status,t.error,t.headers)}throw e},lr=function(e,t,n){if(!t||t!==i(this,rr,`f`)||performance.now()>=t.expiresAt||Date.now()>=t.wallExpiresAt||!Yn.isRetryableFailure(e))return;let r=Yn.retryHeaders(e),a=r?.get(`retry-after-ms`),o=a?Number(a):void 0,s=r?.get(`retry-after`);if(s&&(o===void 0||Number.isNaN(o))){let e=Number(s);o=Number.isNaN(e)?Date.parse(s)-Date.now():e*1e3}let c=o!==void 0&&Number.isFinite(o)&&o>=0&&o<=6e4?Math.max(vr,o):vr;return t.refreshAt=Math.min(t.expiresAt,performance.now()+c),t.wallRefreshAt=Math.min(t.wallExpiresAt,Date.now()+c),i(Yn,Yn,`m`,sr).call(Yn,n,t)},ur=function(e){e.waiters===0&&i(this,ir,`f`)===e&&queueMicrotask(()=>{e.waiters===0&&i(this,ir,`f`)===e&&(r(this,ir,void 0,`f`),r(this,ar,i(this,ar,`f`)+1,`f`),e.controller.abort(new u))})},dr=function(){let e=new AbortController,t=i(this,ar,`f`),n={controller:e,generation:t,waiters:0,promise:i(this,F,`m`,fr).call(this,e,t)};return r(this,ir,n,`f`),n},fr=async function(e,t){let n=performance.now(),a=Date.now();try{let o=await i(this,I,`f`).exchange(i(this,Xn,`f`),i(this,Zn,`f`),e.signal),s=o.expiresIn*1e3,l=n+s,d=a+s;if(performance.now()>=l||Date.now()>=d)throw new c(`X.509 workload identity token expired before its exchange completed.`);if(i(this,ar,`f`)!==t||e.signal.aborted||i(this,ir,`f`)?.controller!==e)throw new u;return r(this,ar,i(this,ar,`f`)+1,`f`),r(this,rr,{accessToken:o.accessToken,generation:i(this,ar,`f`),expiresAt:l,refreshAt:l-Math.min(i(this,nr,`f`),s/2),wallExpiresAt:d,wallRefreshAt:d-Math.min(i(this,nr,`f`),s/2)},`f`),o}finally{i(this,ir,`f`)?.controller===e&&r(this,ir,void 0,`f`)}},pr=function(e){if(!e)return;if(e.organization!==i(this,er,`f`)||e.project!==i(this,tr,`f`))throw new c(`X.509 workload identity cannot override its enrolled organization or project.`);fn(e.apiURL);let t=P([e.defaultHeaders,e.requestHeaders]);if(i(this,er,`f`)!==null&&t.nulls.has(`openai-organization`)||i(this,tr,`f`)!==null&&t.nulls.has(`openai-project`))throw new c(`X.509 workload identity cannot omit its enrolled organization or project.`);for(let n of t.values.keys()){let r=n.toLowerCase().split(`_`).join(`-`);if((r===`openai-organization`||r===`openai-project`)&&(n!==r||gr(t.values,n)!==(r===`openai-organization`?e.organization:e.project)))throw new c(`X.509 workload identity cannot override its enrolled organization or project.`);if(Ge(r)||r===`host`)throw new c(`X.509 workload identity cannot use caller-supplied authentication credentials.`)}},L=function(){let e=i(this,I,`f`).current();if(!e||e.owner!==this)throw new c(`X.509 workload identity requires an active certificate request scope.`);return e},mr=function(e){if(gr(e,`OpenAI-Organization`)!==i(this,er,`f`)||gr(e,`OpenAI-Project`)!==i(this,tr,`f`))throw new c(`X.509 workload identity cannot override its enrolled organization or project.`);for(let t of Headers.prototype.keys.call(e)){let e=t.toLowerCase().split(`_`).join(`-`);if((e===`openai-organization`||e===`openai-project`)&&t!==e)throw new c(`X.509 workload identity cannot override its enrolled organization or project.`)}};function Or(e){let{credential:t}=e;if(t===void 0)return{credential:t,options:e};let n=qn(t);if(!n)throw new c(`An X.509 credential must be created by the SDK authentication helper.`);let r=[`apiKey`,`adminAPIKey`,`workloadIdentity`,`x509Transport`].filter(t=>e[t]!=null);if(r.length>0)throw new c(`The \`credential\` option cannot be combined with ${r.map(e=>`\`${e}\``).join(`, `)}.`);return{credential:t,options:{...e,apiKey:null,adminAPIKey:null,baseURL:e.baseURL??null,organization:e.organization??null,project:e.project??null,workloadIdentity:n.identity,x509Transport:n.transport}}}function kr({apiKey:e,adminAPIKey:t}){return e!=null||t!=null}function Ar(e,t){let n=e.provider,r=t.credential??t.workloadIdentity,i=t.provider??(r?void 0:n);return i!==n&&(delete e.baseURL,delete e.organization,delete e.project,delete e.defaultHeaders,delete e.defaultQuery,delete e.fetchOptions,delete e.fetch),i&&(delete e.apiKey,delete e.adminAPIKey,delete e.credential,delete e.workloadIdentity,delete e.x509Transport,delete e.baseURL),i}function jr(e,t,n,r){let i=E(t,`workloadIdentity`)?t.workloadIdentity:e.workloadIdentity,a=n!==void 0&&(kr(t)&&t.workloadIdentity===void 0||t.provider!==void 0);n!==void 0&&E(t,`workloadIdentity`)&&delete e.x509Transport;let o=n!==void 0&&!a&&t.credential===void 0&&!E(t,`workloadIdentity`)&&!E(t,`x509Transport`)?n:void 0,s=t.credential===void 0?o:t.credential,c=s!==void 0||!a&&Cr(i);return r!==c&&(delete e.fetch,delete e.baseURL,delete e.organization,delete e.project,delete e.defaultHeaders,delete e.defaultQuery,delete e.fetchOptions,c?e.apiKey=null:(delete e.x509Transport,a&&delete e.workloadIdentity)),s!==void 0&&(delete e.apiKey,delete e.adminAPIKey,delete e.workloadIdentity,delete e.x509Transport,e.credential=s,t.credential!==void 0&&(delete e.organization,delete e.project,delete e.defaultHeaders,delete e.defaultQuery,delete e.fetchOptions)),{credential:s,provider:Ar(e,t)}}var Mr=Symbol(`brand.privateStreamingFile`);function Nr(e,t,n){if(typeof t!=`string`||!t)throw TypeError(`toStreamingFile requires a non-empty file name`);let r=n?.type;return r&&oi(r),{[Mr]:!0,data:e,name:t,...r?{type:r}:{}}}var Pr=()=>{if(typeof File>`u`){let{process:e}=globalThis,t=typeof e?.versions?.node==`string`&&Number.parseInt(e.versions.node.split(`.`),10)<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to a supported Node.js LTS release, or set `globalThis.File` to `import('node:buffer').File`.":``))}};function Fr(e,t,n){return Pr(),new File(e,t??`unknown_file`,n)}function Ir(e,t){if(typeof e!=`object`||!e)return;let n=`name`in e?e.name:void 0,r=n&&String(n)||`filename`in e&&e.filename&&String(e.filename);if(r)return t?.stripFilename===!1?Rr(r):Lr(r);let i=`url`in e&&e.url&&String(e.url);if(i)try{return Lr(new URL(i).pathname)}catch{return Lr(i)}let a=`path`in e&&e.path&&String(e.path);return a?Lr(a):void 0}function Lr(e){return e.split(/[\\/]/).pop()||void 0}function Rr(e){let t=e.replace(/\\/g,`/`);if(t.startsWith(`/`)||/^[A-Za-z]:/.test(t)||t.split(`/`).includes(`..`))throw TypeError(`Upload file name must be a safe relative path without parent directory segments`);return t}var zr=Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,`byteLength`)?.get;function Br(e){try{return zr?.call(e)!==void 0}catch{return!1}}var Vr=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,Hr=async(e,t,n)=>Qr(e.body)?Zr(e.body)?ei(e,n):{...e,body:await Kr(e.body,t,n)}:e,Ur=async(e,t,n)=>Zr(e.body)?ei(e,n):{...e,body:await Kr(e.body,t,n)},Wr=new WeakMap;function Gr(e){let t=typeof e==`function`?e:e.fetch,n=Wr.get(t);if(n)return n;let r=(async()=>{try{let e;if(`Response`in t)e=t.Response;else{let n=await t(`data:,`);await n.arrayBuffer(),e=n.constructor}let n=new FormData;return n.toString()!==await new e(n).text()}catch{return!0}})();return Wr.set(t,r),r}var Kr=async(e,t,n={})=>{if(!await Gr(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(([e,t])=>ui(r,e,t,n))),r},qr=e=>e instanceof Blob,Jr=e=>typeof e==`object`&&!!e&&`getReader`in e&&typeof e.getReader==`function`,Yr=e=>typeof e==`object`&&!!e&&Mr in e,Xr=e=>typeof e==`object`&&!!e&&(e instanceof Response||Vr(e)||Jr(e)||Yr(e)||qr(e)),Zr=e=>{if(Yr(e)||Vr(e)||Jr(e))return!0;if(Array.isArray(e))return e.some(Zr);if(e&&typeof e==`object`&&!qr(e)&&!(e instanceof Response)){for(let t of Object.keys(e))if(Zr(e[t]))return!0}return!1},Qr=e=>{if(Xr(e))return!0;if(Array.isArray(e))return e.some(Qr);if(e&&typeof e==`object`){for(let t of Object.keys(e))if(Qr(e[t]))return!0}return!1},$r=(e,t)=>{let n=[];for(let r of e)Xr(r.value)&&!t.has(r.value)&&t.set(r.value,ii(r.value,{stripFilenames:!1})),n.push(r);return n},ei=(e,t={})=>{let n=ni(e.body),r=t.stripFilenames===!1?new WeakMap:void 0,i=r?$r(n,r):n,a=`openai-${Math.random().toString(36).slice(2)}`,o=be(ti(i,a,t,r));return{...e,body:o,headers:P([{"content-type":`multipart/form-data; boundary=${a}`},e.headers])}};async function*ti(e,t,n,r){for await(let{key:i,value:a}of e){if(Xr(a)){let e=r?.get(a)??ii(a,n),o=ai(a);yield we(`--${t}\r\n`),yield we(`Content-Disposition: form-data; name="${li(i)}"; filename="${li(e)}"\r\nContent-Type: ${o}\r\n\r\n`),yield*ci(si(a))}else yield we(`--${t}\r\n`),yield we(`Content-Disposition: form-data; name="${li(i)}"\r\n\r\n${String(a)}`);yield we(`\r
6
+ `)}yield we(`--${t}--\r\n`)}function*ni(e){if(!(!e||typeof e!=`object`))for(let[t,n]of Object.entries(e))yield*ri(t,n)}function*ri(e,t){if(t!==void 0){if(t==null)throw TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t==`string`||typeof t==`number`||typeof t==`boolean`||Xr(t))yield{key:e,value:t};else if(Array.isArray(t))for(let n of t)yield*ri(e+`[]`,n);else if(typeof t==`object`)for(let[n,r]of Object.entries(t))yield*ri(`${e}[${n}]`,r);else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}}function ii(e,t){if(Yr(e)){let{name:n}=e;if(typeof n!=`string`||!n)throw TypeError(`Streaming upload file name must be a non-empty string`);return t.stripFilenames===!1?Rr(n):Lr(n)??`unknown_file`}return Ir(e,{stripFilename:t.stripFilenames})??`unknown_file`}function ai(e){let t;return Yr(e)||qr(e)?{type:t}=e:e instanceof Response&&(t=e.headers.get(`content-type`)??void 0),oi(t||`application/octet-stream`)}function oi(e){if(typeof e!=`string`)throw TypeError(`Streaming upload content type must be a string`);for(let t=0;t<e.length;t+=1){let n=e.codePointAt(t)??0;if(n<=31||n===127)throw TypeError(`Streaming upload content type must not contain control characters`)}return e}function si(e){return Yr(e)?e.data:e}async function*ci(e){if(typeof e==`string`)yield we(e);else if(ArrayBuffer.isView(e))yield new Uint8Array(e.buffer,e.byteOffset,e.byteLength);else if(Br(e))yield new Uint8Array(e);else if(e instanceof Response)yield*ci(e.body||await e.blob());else if(e instanceof Blob)typeof e.stream==`function`?yield*ci(e.stream()):yield new Uint8Array(await e.arrayBuffer());else if(Jr(e))for await(let t of xe(e))yield*ci(t);else if(Vr(e))for await(let t of e)yield*ci(t);else throw TypeError(`Invalid streaming file chunk: ${String(e)}`)}function li(e){return Array.from(e,e=>{let t=e.codePointAt(0)??0;return t<=31||t===127||e===`"`||e===`\\`?encodeURIComponent(e):e}).join(``)}var ui=async(e,t,n,r)=>{if(n!==void 0){if(n==null)throw TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof n==`string`||typeof n==`number`||typeof n==`boolean`)e.append(t,String(n));else if(n instanceof Response){let i=await n.blob();e.append(t,Fr([i],Ir(n,{stripFilename:r.stripFilenames}),{type:i.type}))}else if(Vr(n))e.append(t,Fr([await new Response(be(n)).blob()],Ir(n,{stripFilename:r.stripFilenames})));else if(qr(n)){let i=Ir(n,{stripFilename:r.stripFilenames});i===void 0?e.append(t,n):e.append(t,n,i)}else if(Array.isArray(n)){let i=await Promise.all(n.map(async e=>{let n=new FormData;return await ui(n,t+`[]`,e,r),n}));for(let t of i)if(t)for(let[n,r]of t.entries())e.append(n,r)}else if(typeof n==`object`)await Promise.all(Object.entries(n).map(([n,i])=>ui(e,`${t}[${n}]`,i,r)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},di=e=>typeof e==`object`&&!!e&&typeof e.size==`number`&&typeof e.type==`string`&&typeof e.text==`function`&&typeof e.slice==`function`&&typeof e.arrayBuffer==`function`,fi=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&di(e),pi=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`,mi=(e,t)=>t?.type!=null&&t.type!==e.type||t?.lastModified!=null&&t.lastModified!==e.lastModified||t?.endings!=null,hi=(e,t,n)=>(t==null||t===e.name)&&!mi(e,n);async function gi(e,t,n){if(Pr(),e=await e,fi(e)){let r={...n,type:n?.type??e.type,lastModified:n?.lastModified??e.lastModified};return e instanceof File?hi(e,t,n)?e:Fr([e],t??e.name,r):Fr([await e.arrayBuffer()],t??e.name,r)}if(pi(e)){let r=await e.blob();t??=Ir(e);let i=n?.type===void 0&&r.type?{...n,type:r.type}:n;return Fr(await _i(r),t,i)}let r=await _i(e);if(t??=Ir(e),n?.type===void 0){let e=r.find(e=>typeof e==`object`&&`type`in e&&!!e.type);e&&(n={...n,type:e.type})}return Fr(r,t,n)}async function _i(e){let t=[];if(typeof e==`string`||ArrayBuffer.isView(e)||Br(e))t.push(e);else if(di(e))t.push(e instanceof Blob?e:new Blob([await e.arrayBuffer()],{type:e.type}));else if(Vr(e))for await(let n of e)t.push(...await _i(n));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:``}${vi(e)}`)}return t}function vi(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}var R=class{constructor(e){this._client=e}};function yi(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var bi=Object.freeze(Object.create(null)),z=((e=yi)=>function(t,...n){if(t.length===1)return t[0];let r=!1,i=[],a=``;for(let o=0;o<t.length;o+=1)if(o in t){let s=t[o];/[?#]/.test(s)&&(r=!0);let c=n[o],l=(r?encodeURIComponent:e)(``+c);o!==n.length&&(c==null||typeof c==`object`&&c.toString===Object.getPrototypeOf(Object.getPrototypeOf(c.hasOwnProperty??bi)??bi)?.toString)&&(l=c+``,i.push({start:a.length+s.length,length:l.length,error:`Value of type ${Object.prototype.toString.call(c).slice(8,-1)} is not a valid path parameter`})),a+=s+(o===n.length?``:l)}let o=a.split(/[?#]/,1)[0],s=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,l;for(;(l=s.exec(o))!==null;)i.push({start:l.index,length:l[0].length,error:`Value "${l[0]}" can't be safely passed as a path parameter`});if(i.sort((e,t)=>e.start-t.start),i.length>0){let e=0,t=``;for(let n of i){let r=` `.repeat(n.start-e),i=`^`.repeat(n.length);e=n.start+n.length,t+=r+i}throw new c(`Path parameters result in path with invalid segments:\n${i.map(e=>e.error).join(`
7
+ `)}\n${a}\n${t}`)}return a})(yi),xi=class extends R{list(e,t={},n){return this._client.getAPIList(z`/chat/completions/${e}/messages`,M,{query:t,...n,__security:{bearerAuth:!0}})}};function Si(e){return e!==void 0&&`function`in e&&e.function!==void 0}function Ci(e){return e?.$brand===`auto-parseable-response-format`}function wi(e){return Ci(e)||e?.type===`json_schema`}function Ti(e,t){if(!wi(e))return null;if(typeof e==`object`&&e&&`$parseRaw`in e&&typeof e.$parseRaw==`function`)return e.$parseRaw(t);try{return JSON.parse(t)}catch(e){throw e instanceof SyntaxError?SyntaxError(`Error reading response: invalid structured output JSON.`):e}}function Ei(e){return e?.$brand===`auto-parseable-tool`}function Di(e,t){return!t||!Mi(t)?{...e,choices:e.choices.map(e=>({...e,message:{...e.message,parsed:null,...e.message.tool_calls?{tool_calls:e.message.tool_calls}:void 0}}))}:Oi(e,t)}function Oi(e,t){let n=e.choices.map(e=>{if(e.finish_reason===`length`)throw new x;if(e.finish_reason===`content_filter`)throw new ee;return{...e,message:{...e.message,...e.message.tool_calls?{tool_calls:e.message.tool_calls?.map(e=>Ai(t,e))??void 0}:void 0,parsed:e.message.content!==null&&e.message.content!==void 0&&!e.message.refusal&&(e.message.content!==``||!e.message.tool_calls?.length&&!e.message.function_call)?ki(t,e.message.content):null}}});return{...e,choices:n}}function ki(e,t){return Ti(e.response_format,t)}function Ai(e,t){if(t.type===`custom`)return t;if(t.type!==`function`){let e=t.type;throw new c(`Currently only \`function\` and \`custom\` tool calls are supported; Received \`${e}\``)}let n=e.tools?.find(e=>Si(e)&&e.function?.name===t.function.name),r=null;return Ei(n)?r=n.$parseRaw(t.function.arguments):n?.function.strict&&(r=Ti({type:`json_schema`,$parseRaw:void 0},t.function.arguments)),{...t,function:{...t.function,parsed_arguments:r}}}function ji(e,t){if(!e||!(`tools`in e)||!e.tools||t.type!==`function`)return!1;let n=e.tools?.find(e=>Si(e)&&e.function?.name===t.function?.name);return Si(n)&&(Ei(n)||n?.function.strict||!1)}function Mi(e){return wi(e.response_format)?!0:e.tools?.some(e=>Ei(e)||e.type===`function`&&e.function.strict===!0)??!1}function Ni(e){for(let t of e??[])if(t.type!==`custom`){if(t.type!==`function`){let e=t.type;throw new c(`Currently only \`function\` and \`custom\` tool types are supported; Received \`${e}\``)}if(t.function.strict!==!0)throw new c(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var Pi=e=>e?.role===`assistant`,Fi=e=>e?.role===`tool`,Ii,Li,Ri,zi,Bi,Vi,Hi,Ui,Wi,Gi,Ki,qi,Ji,Yi,Xi,Zi,Qi,$i,ea,ta,na,ra,ia,aa,oa,sa=4096,ca=8388608,la=4096,ua=256,da=JSON.stringify,fa=JSON.parse,pa=new WeakSet,ma=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),`buffer`)?.get,ha=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),`length`)?.get,ga=Object.getOwnPropertyDescriptor(DataView.prototype,`buffer`)?.get,_a=Object.getOwnPropertyDescriptor(Symbol.prototype,`description`)?.get,va=Date.prototype.getTime,ya=Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,`byteLength`)?.get,ba=typeof SharedArrayBuffer==`function`?Object.getOwnPropertyDescriptor(SharedArrayBuffer.prototype,`byteLength`)?.get:void 0,xa=Object.getOwnPropertyDescriptor(Error(`native stack descriptor`),`stack`),Sa=Function.prototype.toString,Ca=Object.prototype.toString,wa=Object.getOwnPropertyDescriptor(Error,`isError`),Ta=wa&&`value`in wa&&typeof wa.value==`function`?wa.value:void 0,Ea=Sa.call(Error),Da=Sa.call(Date),Oa=Sa.call(Function),ka=new Set([d.prototype,f.prototype,l.prototype,c.prototype,u.prototype,m.prototype,p.prototype,_.prototype,ee.prototype,b.prototype,S.prototype,x.prototype,g.prototype,C.prototype,h.prototype,y.prototype,te.prototype,v.prototype]),Aa=new Set,ja=new Map,Ma=new WeakMap;function Na(){if(!(typeof process>`u`))try{let e=Object.getOwnPropertyDescriptor(process,`getBuiltinModule`);if(!e||!(`value`in e)||typeof e.value!=`function`)return;let t=Reflect.apply(e.value,process,[`node:util`]);if(typeof t!=`object`||!t)return;let n=Object.getOwnPropertyDescriptor(t,`types`);if(!n||!(`value`in n)||typeof n.value!=`object`||n.value===null)return;let r=Object.getOwnPropertyDescriptor(n.value,`isProxy`);return!r||!(`value`in r)||typeof r.value!=`function`?void 0:r.value}catch{return}}var Pa=Na();function Fa(e){if(typeof e!=`function`)return;let t=Object.getOwnPropertyDescriptor(e,`prototype`);if(!t||!(`value`in t)||typeof t.value!=`object`&&typeof t.value!=`function`)return;ka.add(t.value);let n=Sa.call(e);if(/^function [A-Za-z_$][\w$]*\(\) \{ \[native code\] \}$/u.test(n)&&t.configurable===!1&&t.writable===!1){Aa.add(n);let e=new Map;for(let n of Reflect.ownKeys(t.value)){let r=Object.getOwnPropertyDescriptor(t.value,n);r&&e.set(n,r)}ja.set(n,e)}}for(let e of[Object,Function,Array,Date,Map,Set,ArrayBuffer,DataView,Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array,Int8Array,Int16Array,Int32Array,Float32Array,Float64Array])Fa(e);for(let e of[`SharedArrayBuffer`,`AggregateError`,`Float16Array`,`BigInt64Array`,`BigUint64Array`,`Blob`,`File`,`Headers`]){let t=Object.getOwnPropertyDescriptor(globalThis,e);t&&`value`in t&&Fa(t.value)}var Ia=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),`constructor`);Ia&&`value`in Ia&&Fa(Ia.value),typeof Buffer==`function`&&Fa(Buffer);var La=(()=>{if(typeof Blob==`function`)try{let e=new Blob([]);for(let t of Object.getOwnPropertySymbols(e)){let n=Object.getOwnPropertyDescriptor(e,t);if(n&&`value`in n&&typeof n.value==`object`&&n.value)return Object.getPrototypeOf(n.value)}}catch{return}})(),Ra=Map.prototype.entries,za=Set.prototype.values,Ba=typeof Headers==`function`?Object.getOwnPropertyDescriptor(Headers.prototype,`entries`):void 0,Va=Ba&&`value`in Ba&&typeof Ba.value==`function`?Ba.value:void 0,Ha=new Set([`ArrayBuffer`,`SharedArrayBuffer`,`Blob`,`File`,`Map`,`Date`,`Set`,`Headers`]);function Ua(e){let t=Object.getOwnPropertyDescriptor(e,`constructor`);if(!t||!(`value`in t)||typeof t.value!=`function`)return;let n=t.value,r=Sa.call(n),i=ja.get(r);if(!Aa.has(r)||!i)return;let a=Object.getOwnPropertyDescriptor(n,`prototype`);if(!(!a||!(`value`in a)||a.value!==e||a.configurable!==!1||a.writable!==!1))return{constructor:n,descriptors:i,functionPrototype:Object.getPrototypeOf(n)}}function Wa(e){return ka.has(e)||Ua(e)!==void 0}function Ga(e,t,n){if(t===void 0)return e===void 0;if(typeof e!=`function`||typeof t!=`function`)return!1;let r=Sa.call(t);if(Sa.call(e)!==r)return!1;let i=Object.getPrototypeOf(e);if(i===n)return!0;if(!/^function [A-Za-z_$][\w$]*\(\) \{ \[native code\] \}$/u.test(r))return!1;let a=Ua(i);return a!==void 0&&Sa.call(a.constructor)===Oa}function Ka(e,t,n){return!t||e.configurable!==t.configurable||e.enumerable!==t.enumerable||`value`in e!=`value`in t?!1:`value`in e&&`value`in t?e.writable===t.writable?typeof t.value==`function`?Ga(e.value,t.value,n):t.value!==null&&typeof t.value==`object`?!1:Object.is(e.value,t.value):!1:Ga(e.get,t.get,n)&&Ga(e.set,t.set,n)}function qa(e){if(Ta)return Ta.call(Error,e);let t=e;for(let e=0;t!==null&&e<ua;e+=1){if(Object.getOwnPropertyDescriptor(t,Symbol.toStringTag))return!1;t=Object.getPrototypeOf(t)}return t===null&&Ca.call(e)===`[object Error]`}function Ja(e,t){if(typeof t.get!=`function`||typeof t.set!=`function`)return;let n=Object.getPrototypeOf(e);for(let e=0;n!==null&&e<ua;e+=1){let e=Object.getOwnPropertyDescriptor(n,`constructor`);if(e&&`value`in e&&typeof e.value==`function`){let r=e.value;if(Sa.call(r)===Ea&&Wa(n)){let e=Object.getPrototypeOf(r);return Object.getPrototypeOf(t.get)===e&&Object.getPrototypeOf(t.set)===e?{constructor:r,prototype:n}:void 0}}n=Object.getPrototypeOf(n)}}function Ya(e,t){if(!qa(e))return!1;if(xa&&!(`value`in xa)&&typeof xa.get==`function`&&Object.prototype.isPrototypeOf.call(Error.prototype,e)&&t.get===xa.get&&t.set===xa.set)return!0;let n=Ja(e,t);if(!n)return!1;let r=Ma.get(n.prototype);if(!r){let e=Reflect.construct(n.constructor,[]);if(typeof e!=`object`||!e||!qa(e)||Object.getPrototypeOf(e)!==n.prototype||(r=Object.getOwnPropertyDescriptor(e,`stack`),!r||`value`in r||typeof r.get!=`function`||typeof r.set!=`function`))return!1;Ma.set(n.prototype,r)}return t.get===r.get&&t.set===r.set}function Xa(){let e=[],t=0;return{get length(){return e.length-t},enqueue(t){e.push(t)},dequeue(){if(t===e.length)return;let n=e[t];return e[t]=void 0,t+=1,t===e.length?(e=[],t=0):t>=1024&&t*2>=e.length&&(e=e.slice(t),t=0),n},clear(){e=[],t=0}}}function Za(e){let t=Object.getPrototypeOf(e);for(let e=0;t!==null&&e<ua;e+=1){if(t===Date.prototype)return`Date`;if(!ka.has(t)){let e=Object.getOwnPropertyDescriptor(t,`constructor`);if(e&&`value`in e&&typeof e.value==`function`&&Sa.call(e.value)===Da&&Ua(t))return`Date`}let e=Object.getOwnPropertyDescriptor(t,Symbol.toStringTag);if(e&&`value`in e&&typeof e.value==`string`&&Ha.has(e.value))return e.value;t=Object.getPrototypeOf(t)}}function Qa(e,t,n){if(ArrayBuffer.isView(e)){let r,i=`typed-array`;try{r=ma?.call(e)}catch{i=`data-view`,r=ga?.call(e)}return typeof r!=`object`||!r?{bytes:1/0,kind:i}:(t(r,n+1),{bytes:0,kind:i})}let r=Za(e);if(!r)return;let i;switch(r){case`ArrayBuffer`:i=ya;break;case`SharedArrayBuffer`:i=ba;break;case`Blob`:case`File`:return{bytes:1/0,kind:`blob`};case`Map`:return{bytes:0,kind:`map`};case`Date`:return Reflect.apply(va,e,[]),{bytes:8,kind:`date`};case`Set`:return{bytes:0,kind:`set`};case`Headers`:return{bytes:0,kind:`headers`};default:return}let a=i?.call(e);return{bytes:typeof a==`number`&&Number.isSafeInteger(a)&&a>=0?a:1/0,kind:`buffer`}}function $a(e,t,n){if(t===`map`){for(let[t,r]of Ra.call(e))if(!n(t,8)||!n(r,8))return!1}if(t===`set`){for(let t of za.call(e))if(!n(t,8))return!1}if(t===`headers`){if(!Va)return!1;for(let[t,r]of Va.call(e))if(!n(t,8)||!n(r,8))return!1}return!0}function eo(e,t,n){if(Array.isArray(e)){let t=Object.getOwnPropertyDescriptor(e,`length`),r=t&&`value`in t?t.value:void 0;if(typeof r!=`number`||!Number.isSafeInteger(r)||r<0||r>Math.floor(n/16))return}if(t!==`typed-array`)return Reflect.ownKeys(e);let r=ha?.call(e);if(!(typeof r!=`number`||!Number.isSafeInteger(r)||r<0||r>la))return Reflect.ownKeys(e).filter(e=>{if(typeof e!=`string`)return!0;let t=Number(e);return!Number.isInteger(t)||t<0||t>=r||String(t)!==e})}function to(e,t,n,r,i,a){let o=eo(e,t,r());if(o===void 0)return!1;for(let r of o){if(!i(typeof r==`string`?r.length*2+8:8))return!1;typeof r==`symbol`&&a(r,n+1);let o=Object.getOwnPropertyDescriptor(e,r);if(!o)return!1;if(!(`value`in o)){if(r===`stack`&&Ya(e,o))continue;return!1}a(o.value,n+1,t===`blob`)}return!0}function no(e,t,n,r,i,a,o,s){let c=Object.getPrototypeOf(e);for(let e=t+1;c!==null;e+=1){if(e>=ua)return!1;if(ka.has(c)||n&&c===La)return!0;if(r.has(c))return o(c,e),i()>=0;r.add(c);let t=c;if(!s(t,()=>{if(!a(16))return!1;let n=Ua(t);if(!n)return to(t,void 0,e,i,a,o);for(let r of Reflect.ownKeys(t)){let i=Object.getOwnPropertyDescriptor(t,r);if(!i)return!1;if(!Ka(i,n.descriptors.get(r),n.functionPrototype)){if(!a(typeof r==`string`?r.length*2+8:8)||!(`value`in i))return!1;typeof r==`symbol`&&o(r,e+1),o(i.value,e+1)}}return i()>=0}))return!1;c=Object.getPrototypeOf(t)}return!0}var ro=32,io=32,ao=8,oo=16,so=131072;function co(e,t){let n=0,r=0,i=new WeakSet,a=new Set,o=new Set,s=new Map,c,l=()=>t-n,u=e=>!Number.isSafeInteger(e)||e<0?(n=t+1,!1):(n+=e,c?c.bytes+=e:r+=e,n<=t),d=e=>{c?c.edges.add(e):o.add(e)},f=(e,t)=>{d(e);let n={bytes:0,edges:new Set};s.set(e,n);let r=c;c=n;try{return t()}finally{c=r}},p=e=>{if(a.has(e)){d(e),u(8);return}a.add(e),f(e,()=>{if(!_a)return!1;let t=Reflect.apply(_a,e,[]);return u(8+(t?.length??0)*2)})||(n=t+1)},m=(e,r,a=!1)=>{if(!(n>t)){if(typeof e==`string`){u(e.length*2);return}if(typeof e==`symbol`){p(e);return}if(typeof e==`function`){n=t+1;return}if(typeof e!=`object`||!e){u(8);return}if(Pa?.(e)){n=t+1;return}if(r>=ua){n=t+1;return}if(i.has(e)){d(e),u(8);return}i.add(e),f(e,()=>{if(!u(16))return!1;let o=Qa(e,m,r);return!no(e,r,a,i,l,u,m,f)||o!==void 0&&!u(o.bytes)||!$a(e,o?.kind,(e,i)=>u(i)?(m(e,r+1),n<=t):!1)?!1:to(e,o?.kind,r,l,u,m)})||(n=t+1)}};try{m(e,0)}catch{return}return n<=t?{scalarBytes:r,roots:o,nodes:s}:void 0}function lo(e,t){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}function uo(e,t){return e.bytes+io+e.edges.size*ao+t*oo}function fo(e){return ro+e.scalarBytes+e.roots.size*ao}function po(e,t,n,r){let i=new Set,a=[...e];for(;a.length;){if(--r.remaining,r.remaining<0)return;let e=a.pop();if(i.has(e))continue;let o=t.get(e)??n.get(e);if(!o)return;i.add(e);for(let e of o.edges)a.push(e)}return i}function mo(e,t,n,r,i){let a=r.get(e);if(a)return i&&(a.node=i),a;let o=i??t.nodes.get(e)??n.get(e);if(!o)return;let s={node:o,ownerDelta:0};return r.set(e,s),s}function ho(e,t,n,r,i){let a=new Set([e]);for(let[e,o]of t.nodes){if(--i.remaining,i.remaining<0)return;let s=n.get(e);if(!s)continue;let c=!lo(s.edges,o.edges);if((s.bytes!==o.bytes||c)&&mo(e,t,n,r,o),c)for(let e of s.owners){if(--i.remaining,i.remaining<0)return;a.add(e)}}return a}function go(e,t,n,r,i,a){for(let o of e.identities){if(--a.remaining,a.remaining<0)return!1;if(!t.has(o)){let e=mo(o,n,r,i);if(!e)return!1;--e.ownerDelta}}for(let o of t){if(--a.remaining,a.remaining<0)return!1;if(!e.identities.has(o)){let e=mo(o,n,r,i);if(!e)return!1;e.ownerDelta+=1}}return!0}function _o(e,t,n,r,i,a){let o=new Map;for(let s of n){let n=po(s===e?t.roots:s.roots,t.nodes,r,a);if(!n||!go(s,n,t,r,i,a))return;o.set(s,n)}return o}function vo(e,t,n,r,i,a){let o=e-(r?0:fo(t))+fo(n);for(let[e,t]of i){let n=a.get(e),r=(n?.owners.size??0)+t.ownerDelta;if(r<0)return;n&&(o-=uo(n,n.owners.size)),r&&(o+=uo(t.node,r))}return Number.isSafeInteger(o)&&o>=0&&o<=ca?o:void 0}function yo(e,t,n){for(let[n,r]of t){let t=e.get(n);(t?.owners.size??0)+r.ownerDelta&&(t?(t.bytes=r.node.bytes,t.edges=r.node.edges):e.set(n,{bytes:r.node.bytes,edges:r.node.edges,owners:new Set}))}for(let[t,r]of n){for(let n of t.identities)r.has(n)||e.get(n)?.owners.delete(t);for(let n of r)t.identities.has(n)||e.get(n).owners.add(t);t.identities=r}for(let n of t.keys())e.get(n)?.owners.size===0&&e.delete(n)}function bo(){let e=new Map,t=0,n=(n,r,i)=>{let a={remaining:so},o=new Map,s=ho(n,r,e,o,a);if(!s)return!1;let c=_o(n,r,s,e,o,a);if(!c)return!1;let l=vo(t,n,r,i,o,e);return l!==void 0&&(yo(e,o,c),n.scalarBytes=r.scalarBytes,n.roots=r.roots,t=l,!0)};return{retain(e){let t={scalarBytes:0,roots:new Set,identities:new Set};return n(t,e,!0)?t:void 0},refresh(e,t){return n(e,t,!1)},release:n=>{t-=fo(n);for(let r of n.identities){let i=e.get(r);i?.owners.delete(n)&&(t-=oo,i.owners.size===0&&(t-=uo(i,0),e.delete(r)))}n.identities.clear()},clear(){e.clear(),t=0}}}var xo=class{constructor(){Ii.add(this),this.controller=new AbortController,Li.set(this,void 0),Ri.set(this,()=>void 0),zi.set(this,()=>void 0),Bi.set(this,void 0),Vi.set(this,()=>void 0),Hi.set(this,()=>void 0),Ui.set(this,Object.create(null)),Wi.set(this,[]),Gi.set(this,new WeakMap),Ki.set(this,new Set),qi.set(this,new Set),Ji.set(this,0),Yi.set(this,!1),Xi.set(this,!1),Zi.set(this,!1),Qi.set(this,!1),$i.set(this,void 0),r(this,Li,new Promise((e,t)=>{r(this,Ri,e,`f`),r(this,zi,t,`f`)}),`f`),r(this,Bi,new Promise((e,t)=>{r(this,Vi,e,`f`),r(this,Hi,t,`f`)}),`f`),i(this,Li,`f`).catch(()=>void 0),i(this,Bi,`f`).catch(()=>void 0)}_run(e){setTimeout(()=>{let t=!1;Promise.resolve().then(e).catch(e=>{t=!0,i(this,Ii,`m`,aa).call(this,e)}).then(()=>{if(!t){try{this._emitFinal()}catch(e){i(this,Ii,`m`,aa).call(this,e);return}this._emit(`end`)}})},0)}_connected(){this.ended||(i(this,Ri,`f`).call(this),this._emit(`connect`))}get ended(){return i(this,Yi,`f`)}get errored(){return i(this,Xi,`f`)}get aborted(){return i(this,Zi,`f`)}abort(){this.controller.abort()}_userAbortError(){let e=new u;return Object.defineProperty(e,"cause",{value:this.controller.signal.reason,writable:!0,configurable:!0}),e}_listenForAbort(e){if(!e||this.ended)return;if(e.aborted){i(this,Ii,`m`,ea).call(this,e);return}if(i(this,Wi,`f`).some(t=>t.signal===e))return;let t=()=>i(this,Ii,`m`,ea).call(this,e);e.addEventListener(`abort`,t,{once:!0}),i(this,Wi,`f`).push({signal:e,listener:t})}on(e,t){var n;return((n=i(this,Ui,`f`))[e]||(n[e]=[])).push({listener:t}),this}off(e,t){let n=i(this,Ui,`f`)[e];if(!n)return this;let r=i(this,Gi,`f`).get(t);if(r?.event===e&&!r.registration.removed&&!r.registration.detached)return i(this,Ii,`m`,ra).call(this,e,r.registration),this;let a=n.findIndex(e=>!e.removed&&e.listener===t);return a!==-1&&n.splice(a,1),this}once(e,t){var n;return((n=i(this,Ui,`f`))[e]||(n[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{r(this,Qi,!0,`f`);let a=t=>{this.off(e,o),n(t)},o=(...n)=>{e!==`error`&&this.off(`error`,a),t(n.length>1?n:n[0])};e!==`error`&&i(this,Ii,`m`,na).call(this,`error`,a),i(this,Ii,`m`,na).call(this,e,o)})}events(e){return this._createIterator(t=>{let n=(...e)=>{pa.add(e);try{t(e)}finally{pa.delete(e)}};return this.on(e,n),()=>this.off(e,n)},{rejectOnError:e!==`error`,rejectOnAbort:e!==`abort`})}_createIterator(e,{rejectOnError:t=!0,rejectOnAbort:n=!0,onReturn:r}={}){let a=Xa(),o=Xa(),s=Xa(),l=bo(),u=this.ended,d,f=!1,p=()=>void 0,m=()=>({value:void 0,done:!0}),h=()=>{for(;s.length;)s.dequeue().resolve(m())},g=()=>{!d||f||!s.length||(f=!0,s.dequeue().reject(d))},_=()=>{p(),this.off(`end`,C),t&&this.off(`error`,ee),n&&this.off(`abort`,ee)},v=e=>{e.active=!1,e.check&&=(i(this,qi,`f`).delete(e.check),void 0)},y=(e=!1)=>{if(e){for(;o.length;)v(o.dequeue());a.clear(),l.clear()}let t=new c(`Event stream iterator buffer limit exceeded (${sa} events or ${ca} bytes); consume events as they arrive.`);try{i(this,Ii,`m`,aa).call(this,t)}finally{this.controller.abort()}return t},b=(e,t)=>{if(!t.active||i(this,Yi,`f`))return;let n=co(e,ca);(!n||!l.refresh(t.retention,n))&&y(!0)},x=e=>{if(u)return;let t=s.dequeue();if(t)t.resolve({value:e,done:!1});else{if(a.length>=sa){y();return}let t=co(e,ca),n=t&&l.retain(t);if(!n){y();return}if(typeof e==`object`&&e&&pa.has(e)){let t=e;for(let e=0;e<t.length;e+=1){let n=t[e];typeof n==`string`&&(t[e]=fa(da(n)))}}let r={retention:n,active:!0,check:void 0};a.enqueue(e),o.enqueue(r);let s=()=>{r.check=void 0,b(e,r)};r.check=s,i(this,qi,`f`).add(s)}},ee=e=>{d=e,a.length||g()},S=()=>{if(d)return;let e=i(this,$i,`f`);e&&(e.kind===`error`?t:n)&&(d=e.error)},C=()=>{u=!0,S(),_(),a.length||(g(),h())};return u||(p=e(x),this.on(`end`,C),t&&this.on(`error`,ee),n&&this.on(`abort`,ee)),{next:()=>{if(a.length){let e=a.dequeue(),t=o.dequeue();v(t);let n=co(e,ca);if(!n||!l.refresh(t.retention,n)){let e=y(!0);return f=!0,Promise.reject(e)}return l.release(t.retention),Promise.resolve({value:e,done:!1})}return(u||this.ended)&&S(),d&&!f?(f=!0,Promise.reject(d)):u?Promise.resolve(m()):new Promise((e,t)=>{s.enqueue({resolve:e,reject:t})})},return:()=>{for(u=!0,f=!0;o.length;)v(o.dequeue());return a.clear(),l.clear(),_(),h(),r&&(this.done().catch(()=>void 0),r()),Promise.resolve(m())},[Symbol.asyncIterator](){return this}}}async done(){r(this,Qi,!0,`f`),await i(this,Bi,`f`)}_hasListeners(e){return!!i(this,Ui,`f`)[e]?.some(e=>!e.removed)}_emit(e,...t){if(i(this,Yi,`f`))return;e===`end`&&(i(this,Ii,`m`,ta).call(this),r(this,Yi,!0,`f`),i(this,Vi,`f`).call(this));let n=i(this,Ui,`f`)[e],a,o=!1;try{if(n){i(this,Ui,`f`)[e]=n.filter(e=>(e.once&&(e.detached=!0),!e.once&&!e.removed)),r(this,Ji,i(this,Ji,`f`)+1,`f`);try{for(let e of n)if(!e.removed){let{listener:n}=e;n(...t)}}finally{if(r(this,Ji,i(this,Ji,`f`)-1,`f`),i(this,Ji,`f`)===0){i(this,Ii,`m`,ia).call(this);for(let e of i(this,qi,`f`))i(this,qi,`f`).delete(e),i(this,Yi,`f`)||e()}}}}catch(e){a=e,o=!0}try{i(this,Ii,`m`,oa).call(this,e,t,!!n?.length)}catch(e){o||=(a=e,!0)}if(o)throw a}_emitFinal(){}};Li=new WeakMap,Ri=new WeakMap,zi=new WeakMap,Bi=new WeakMap,Vi=new WeakMap,Hi=new WeakMap,Ui=new WeakMap,Wi=new WeakMap,Gi=new WeakMap,Ki=new WeakMap,qi=new WeakMap,Ji=new WeakMap,Yi=new WeakMap,Xi=new WeakMap,Zi=new WeakMap,Qi=new WeakMap,$i=new WeakMap,Ii=new WeakSet,ea=function(e){try{this.controller.abort(e.reason)}catch{this.controller.abort()}},ta=function(){for(let{signal:e,listener:t}of i(this,Wi,`f`).splice(0))e.removeEventListener(`abort`,t)},na=function(e,t){let n=i(this,Ui,`f`)[e],r=n?.length??0;this.once(e,t);let a=i(this,Ui,`f`)[e],[o]=a?.slice(-1)??[];(n===void 0||a===n)&&a?.length===r+1&&o?.listener===t&&o.once&&i(this,Gi,`f`).set(t,{event:e,registration:o})},ra=function(e,t){t.removed||(t.removed=!0,i(this,Gi,`f`).delete(t.listener),i(this,Ki,`f`).add(e),i(this,Ji,`f`)===0&&i(this,Ii,`m`,ia).call(this))},ia=function(){for(let e of i(this,Ki,`f`)){let t=e,n=i(this,Ui,`f`)[t];n&&(i(this,Ui,`f`)[t]=n.filter(e=>!e.removed))}i(this,Ki,`f`).clear()},aa=function(e){if(r(this,Xi,!0,`f`),e instanceof Error&&e.name===`AbortError`&&(e=this._userAbortError()),e instanceof u)return r(this,Zi,!0,`f`),this._emit(`abort`,e);if(e instanceof c)return this._emit(`error`,e);if(e instanceof Error){let t=new c(e.message);return t.cause=e,this._emit(`error`,t)}return this._emit(`error`,new c(String(e)))},oa=function(e,t,n){if(e===`abort`){let e=t[0];r(this,$i,i(this,$i,`f`)??{kind:`abort`,error:e},`f`),!i(this,Qi,`f`)&&!n&&Promise.reject(e),i(this,zi,`f`).call(this,e),i(this,Hi,`f`).call(this,e),this._emit(`end`);return}if(e===`error`){let e=t[0];r(this,$i,i(this,$i,`f`)??{kind:`error`,error:e},`f`),!i(this,Qi,`f`)&&!n&&Promise.reject(e),i(this,zi,`f`).call(this,e),i(this,Hi,`f`).call(this,e),this._emit(`end`)}};function So(e){return typeof e.parse==`function`}var B,Co,wo,To,Eo,Do,Oo,ko,Ao,jo,Mo,No,Po=10;function Fo(e){for(let t of e.choices)for(let e of t.message.tool_calls??[])e.id||=`call_${a()}`}function Io(e){if(!Pi(e))return e;let t={role:`assistant`};return e.audio!=null&&(t.audio={id:e.audio.id}),e.content!==void 0&&(t.content=e.content),e.function_call!=null&&(t.function_call=e.function_call),e.name!==void 0&&(t.name=e.name),e.refusal!=null&&(t.refusal=e.refusal),e.tool_calls!==void 0&&(t.tool_calls=e.tool_calls.map(e=>e.type===`custom`?{id:e.id,type:e.type,custom:{input:e.custom.input,name:e.custom.name}}:{id:e.id,type:e.type,function:{arguments:e.function.arguments,name:e.function.name}})),t}var Lo=class extends xo{constructor(){super(...arguments),B.add(this),this._chatCompletions=[],wo.set(this,!1),To.set(this,!1),this.messages=[]}_addChatCompletion(e){r(this,wo,!this.controller.signal.aborted,`f`),Fo(e),this._chatCompletions.push(e),this._emit(`chatCompletion`,e);let t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0,n=!0){if(n&&!(`content`in e)&&(e.content=null),this.messages.push(e),t){if(this._emit(`message`,e),Fi(e)&&e.content)this._emit(`functionToolCallResult`,e.content);else if(Pi(e)&&e.tool_calls)for(let t of e.tool_calls)t.type===`function`&&this._emit(`functionToolCall`,t.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new c(`stream ended without producing a ChatCompletion`);return e}async finalContent(){return await this.done(),i(this,B,`m`,Eo).call(this)}async finalMessage(){return await this.done(),i(this,B,`m`,Do).call(this)}async finalFunctionToolCall(){return await this.done(),i(this,B,`m`,Oo).call(this)}async finalFunctionToolCallResult(){return await this.done(),i(this,B,`m`,ko).call(this)}async totalUsage(){return await this.done(),i(this,B,`m`,Ao).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){i(this,To,`f`)&&i(this,B,`m`,jo).call(this);let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit(`finalChatCompletion`,e);let t=i(this,B,`m`,Do).call(this);t&&this._emit(`finalMessage`,t);let n=i(this,B,`m`,Eo).call(this);n&&this._emit(`finalContent`,n);let r=i(this,B,`m`,Oo).call(this);r&&this._emit(`finalFunctionToolCall`,r);let a=i(this,B,`m`,ko).call(this);a!=null&&this._emit(`finalFunctionToolCallResult`,a),this._chatCompletions.some(e=>e.usage)&&this._emit(`totalUsage`,i(this,B,`m`,Ao).call(this))}async _createChatCompletion(e,t,n){this._listenForAbort(n?.signal),i(Co,Co,`m`,Mo).call(Co,t);let r=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Oi(r,t))}async _runChatCompletion(e,t,n){for(let e of t.messages)this._addMessage(e,!1,!1);return await this._createChatCompletion(e,t,n)}async _runTools(e,t,n,a){let o=`tool`,{tool_choice:s=`auto`,stream:l,toolContext:u,...d}=t,f=u,p=typeof s!=`string`&&s.type===`function`&&s?.function?.name,{maxChatCompletions:m=Po,afterCompletion:h}=a||{},g=async e=>{h!=null&&(r(this,To,!0,`f`),await h(e,n),i(this,B,`m`,jo).call(this))},_=t.tools.map(e=>{if(Ei(e)){if(!e.$callback)throw new c("Tool given to `.runTools()` that does not have an associated function");return{type:`function`,function:{function:e.$callback,name:e.function.name,description:e.function.description||``,parameters:e.function.parameters,parse:e.$parseRaw,strict:!0}}}return e}),v=Object.create(null);for(let e of _)e.type===`function`&&(v[e.function.name||e.function.function.name]=e.function);let y=`tools`in t?_.map(e=>e.type===`function`?{type:`function`,function:{name:e.function.name||e.function.function.name,parameters:e.function.parameters,description:e.function.description,strict:e.function.strict}}:e):void 0;for(let e of t.messages)this._addMessage(e,!1,!1);let b=!1,x=async e=>{let t=b;if(b=!1,e.type!==`function`)return{message:void 0,functionCalled:!1};let r=e.id,{name:a,arguments:s}=e.function,c=v[a];if(!c){let e=`Invalid tool_call: ${JSON.stringify(a)}. Available options are: ${Object.keys(v).map(e=>JSON.stringify(e)).join(`, `)}. Please try again`;return{message:{role:o,tool_call_id:r,content:e},functionCalled:!1}}if(p&&p!==a){let e=`Invalid tool_call: ${JSON.stringify(a)}. ${JSON.stringify(p)} requested. Please try again`;return{message:{role:o,tool_call_id:r,content:e},functionCalled:!1}}let l;if(So(c)){let e;try{e=await c.parse(s)}catch(e){if(this.controller.signal.aborted)throw this._userAbortError();let t=e instanceof Error?e.message:String(e);return{message:{role:o,tool_call_id:r,content:t},functionCalled:!1}}if(this.controller.signal.aborted)throw this._userAbortError();try{l=await c.function(e,n,f)}catch(e){throw this.controller.signal.aborted&&Object.is(e,this.controller.signal.reason)?this._userAbortError():e}}else{if(this.controller.signal.aborted&&!t)throw this._userAbortError();try{l=await c.function(s,n,f)}catch(e){throw this.controller.signal.aborted&&Object.is(e,this.controller.signal.reason)?this._userAbortError():e}}let u=i(Co,Co,`m`,No).call(Co,l);return{message:{role:o,tool_call_id:r,content:u},functionCalled:!0}};for(let n=0;n<m;++n){let n=await this._createChatCompletion(e,{...d,tool_choice:s,tools:y,messages:this.messages.map(Io)},a);b=this.controller.signal.aborted&&i(this,wo,`f`);let r=n.choices[0]?.message;if(!r)throw new c(`missing message in ChatCompletion response`);if(!r.tool_calls?.length){await g(n);return}if(p||t.parallel_tool_calls===!1)for(let e of r.tool_calls){let t=await x(e);if(t.message&&this._addMessage(t.message),this.controller.signal.aborted)throw this._userAbortError();if(p&&t.functionCalled){await g(n);return}}else{let e=await Promise.allSettled(r.tool_calls.map(x));if(!this.controller.signal.aborted){for(let t of e)if(t.status===`rejected`)throw t.reason}for(let t of e)t.status===`fulfilled`&&t.value.message&&this._addMessage(t.value.message);if(this.controller.signal.aborted)throw this._userAbortError()}await g(n)}}};Co=Lo,wo=new WeakMap,To=new WeakMap,B=new WeakSet,Eo=function(){return i(this,B,`m`,Do).call(this).content??null},Do=function(){let e=this.messages.length;for(;e-->0;){let t=this.messages[e];if(Pi(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new c(`stream ended without producing a ChatCompletionMessage with role=assistant`)},Oo=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(Pi(t)&&t?.tool_calls?.length)for(let e=t.tool_calls.length-1;e>=0;e--){let n=t.tool_calls[e];if(n?.type===`function`)return n.function}}},ko=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(Fi(t)&&t.content!=null&&typeof t.content==`string`&&this.messages.some(e=>e.role===`assistant`&&e.tool_calls?.some(e=>e.type===`function`&&e.id===t.tool_call_id)))return t.content}},Ao=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},jo=function(){if(this.controller.signal.aborted)throw this._userAbortError()},Mo=function(e){if(e.n!=null&&e.n>1)throw new c(`ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.`)},No=function(e){return typeof e==`string`?e:e===void 0?`undefined`:JSON.stringify(e)};var Ro=class e extends Lo{static runTools(t,n,r){let i=new e,a={...r,__metadata:{...r?.__metadata,helperMethod:`runTools`}};return i._run(()=>i._runTools(t,n,i,a)),i}_addMessage(e,t=!0,n=!0){super._addMessage(e,t,n),t&&Pi(e)&&e.content&&this._emit(`content`,e.content)}},V={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511},zo=class extends Error{},Bo=class extends Error{};function Vo(e,t=V.ALL){if(typeof e!=`string`)throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return Ho(e.trim(),t)}var Ho=(e,t)=>{let n=e.length,r=0,i=e=>{throw new zo(`${e} at position ${r}`)},a=e=>{throw new Bo(`${e} at position ${r}`)},o=()=>(d(),r>=n&&i(`Unexpected end of input`),e[r]===`"`?s():e[r]===`{`?c():e[r]===`[`?l():e.substring(r,r+4)===`null`||V.NULL&t&&n-r<4&&`null`.startsWith(e.substring(r))?(r+=4,null):e.substring(r,r+4)===`true`||V.BOOL&t&&n-r<4&&`true`.startsWith(e.substring(r))?(r+=4,!0):e.substring(r,r+5)===`false`||V.BOOL&t&&n-r<5&&`false`.startsWith(e.substring(r))?(r+=5,!1):e.substring(r,r+8)===`Infinity`||V.INFINITY&t&&n-r<8&&`Infinity`.startsWith(e.substring(r))?(r+=8,1/0):e.substring(r,r+9)===`-Infinity`||V.MINUS_INFINITY&t&&n-r>1&&n-r<9&&`-Infinity`.startsWith(e.substring(r))?(r+=9,-1/0):e.substring(r,r+3)===`NaN`||V.NAN&t&&n-r<3&&`NaN`.startsWith(e.substring(r))?(r+=3,NaN):u()),s=()=>{let o=r,s=!1;for(r++;r<n&&(e[r]!==`"`||s&&e[r-1]===`\\`);)s=e[r]===`\\`&&!s,r++;if(e.charAt(r)===`"`)try{return JSON.parse(e.substring(o,++r-Number(s)))}catch(e){a(String(e))}else if(V.STR&t)try{return JSON.parse(e.substring(o,r-Number(s))+`"`)}catch{return JSON.parse(e.substring(o,e.lastIndexOf(`\\`))+`"`)}i(`Unterminated string literal`)},c=()=>{r++,d();let a={};try{for(;e[r]!==`}`;){if(d(),r>=n&&V.OBJ&t)return a;let i=s();d(),r++;try{let e=o();Object.defineProperty(a,i,{value:e,writable:!0,enumerable:!0,configurable:!0})}catch(e){if(V.OBJ&t)return a;throw e}d(),e[r]===`,`&&r++}}catch{if(V.OBJ&t)return a;i(`Expected '}' at end of object`)}return r++,a},l=()=>{r++;let n=[];try{for(;e[r]!==`]`;)n.push(o()),d(),e[r]===`,`&&r++}catch{if(V.ARR&t)return n;i(`Expected ']' at end of array`)}return r++,n},u=()=>{if(r===0){e===`-`&&V.NUM&t&&i(`Not sure what '-' is`);try{return JSON.parse(e)}catch(n){if(V.NUM&t)try{return e[e.length-1]===`.`?JSON.parse(e.substring(0,e.lastIndexOf(`.`))):JSON.parse(e.substring(0,e.lastIndexOf(`e`)))}catch{}a(String(n))}}let o=r;for(e[r]===`-`&&r++;e[r]&&!`,]}`.includes(e[r]);)r++;r===n&&!(V.NUM&t)&&i(`Unterminated number literal`);let s=e.substring(o,r);try{return JSON.parse(s)}catch{s===`-`&&V.NUM&t&&i(`Not sure what '-' is`);try{return JSON.parse(s.substring(0,s.lastIndexOf(`e`)))}catch(e){a(String(e))}}},d=()=>{for(;r<n&&`
8
+ \r `.includes(e[r]);)r++};return o()},Uo=e=>Vo(e,V.ALL^V.NUM),H,U,Wo,Go,Ko,W,qo,Jo,Yo,Xo,Zo,Qo,$o,es,ts,ns;function rs(e){try{return Uo(e)}catch(t){if(t instanceof Bo||t instanceof SyntaxError)return Ti({type:`json_schema`,$parseRaw:void 0},e);throw t}}var is=`chat.completion.chunk.message:`;function as(e,t,n){let r={type:`message`,message:t,...n?{tool_call_ids:n}:{}};return{id:e.id,choices:[],created:e.created,model:e.model,object:`${is}${JSON.stringify(r)}`}}function os(e){return`type`in e&&e.type===`message`&&`message`in e||`object`in e&&typeof e.object==`string`&&e.object.startsWith(is)}function ss(e){return`type`in e?e:JSON.parse(e.object.slice(30))}var cs=128,ls=128,us=16777216,ds=65536,fs=128,ps=67108864,ms=1024;function hs(){return{bytes:0,depth:0,fragments:0,work:0,escaped:!1,has_non_whitespace:!1,in_string:!1,last_parsed_bytes:0,pending_high_surrogate:!1}}function gs(e,t,n,r){if(t.fragments>=ds)throw new c(`Chat completion stream exceeded its structured JSON fragment limit`);let i=0,{depth:a,escaped:o,has_non_whitespace:s,in_string:l}=e,u=!1,d=!0;for(let f of n){let n=i,p=f.codePointAt(0);if(d&&e.pending_high_surrogate&&p>=56320&&p<=57343?i+=1:i+=p<=127?1:p<=2047?2:p<=65535?3:4,d=!1,t.bytes+i>us)throw new c(`Chat completion stream exceeded its structured JSON byte limit`);if(r&&r.work+i>ps)throw r.work+=n,new c(`Chat completion stream exceeded its structured JSON parse-work limit`);if(f!==` `&&f!==`
9
+ `&&f!==`\r`&&f!==` `&&(s=!0),l){o?o=!1:f===`\\`?o=!0:f===`"`&&(l=!1,u||=a===0);continue}if(f===`"`)l=!0;else if(f===`{`||f===`[`){if(a+=1,a>fs)throw new c(`Chat completion stream exceeded its structured JSON nesting depth limit`)}else(f===`}`||f===`]`)&&a>0&&(--a,u||=a===0)}if(e.bytes+=i,e.fragments+=1,e.depth=a,e.escaped=o,e.has_non_whitespace=s,e.in_string=l,n.length>0){let t=n.codePointAt(n.length-1)??0;e.pending_high_surrogate=t>=55296&&t<=56319}if(t.bytes+=i,t.fragments+=1,r&&(r.work+=i),!s||i===0)return!1;let f=Math.max(ms,Math.floor(e.last_parsed_bytes/2));return!(e.bytes>ms&&!u&&e.bytes-e.last_parsed_bytes<f)}function _s(e,t){return t.work+e.bytes>ps?!1:(t.work+=e.bytes,e.work+=e.bytes,e.last_parsed_bytes=e.bytes,!0)}function vs(e,t){let n=Object.getOwnPropertyDescriptor(e,t);if(!n){let n=Object.getPrototypeOf(e);for(let e=0;n!==null;e+=1){if(e>=fs||Object.getOwnPropertyDescriptor(n,t))throw new c(`Chat completion stream contains an unsafe structured JSON snapshot`);n=Object.getPrototypeOf(n)}return}if(!(`value`in n)||typeof n.value!=`string`&&n.value!==null&&n.value!==void 0)throw new c(`Chat completion stream contains an unsafe structured JSON snapshot`);return n.value}function ys(e){let t=Object.getOwnPropertyDescriptor(e,`message`);if(!t||!(`value`in t)||typeof t.value!=`object`||t.value===null)throw new c(`Chat completion stream contains an unsafe structured JSON snapshot`);return t.value}function bs(e,t,n,r){let i=Object.getOwnPropertyDescriptor(e,t);if(!i){let n=Object.getPrototypeOf(e);for(let e=0;n!==null;e+=1){if(e>=fs||Object.getOwnPropertyDescriptor(n,t))throw new c(`Chat completion stream contains an unsafe snapshot ${r} collection`);n=Object.getPrototypeOf(n)}return}if(!(`value`in i)||!Array.isArray(i.value))throw new c(`Chat completion stream contains an unsafe snapshot ${r} collection`);let a=Object.getOwnPropertyDescriptor(i.value,`length`);if(!a||!(`value`in a)||!Number.isSafeInteger(a.value)||a.value>n)throw new c(`Chat completion stream exceeded its snapshot ${r} limit`);return i.value}function xs(e,t){let n=Object.getOwnPropertyDescriptor(e,t);if(n){if(!(`value`in n))throw new c(`Chat completion stream contains an unsafe structured JSON snapshot`);return n.value}}function Ss(e,t,n,r){let i=Object.getOwnPropertyDescriptor(e,`length`),a=i&&`value`in i?i.value:void 0;if(typeof a!=`number`||!Number.isSafeInteger(a)||a<0||a>t)throw new c(`Chat completion stream exceeded its snapshot ${n} limit`);let o=[];o.length=a;for(let t=0;t<a;t+=1){let n=Object.getOwnPropertyDescriptor(e,t);if(n){if(!(`value`in n))throw new c(`Chat completion stream contains an unsafe structured JSON snapshot`);o[t]=r(n.value,t)}}return o}function Cs(e,t,n){let r=hs(),i=t??{bytes:0,fragments:0,work:0};if(gs(r,i,e,n),!_s(r,i))throw new c(`Chat completion stream exceeded its structured JSON parse-work limit`);return e}function ws(e){let t=Object.getOwnPropertyDescriptor(e,`type`),n=Object.getOwnPropertyDescriptor(e,`function`);if(!t||!(`value`in t)||t.value!==`function`||!n||!(`value`in n)||typeof n.value!=`object`||n.value===null)return;let r=Object.getOwnPropertyDescriptor(n.value,`name`);if(!(!r||!(`value`in r)||typeof r.value!=`string`||r.value.length===0))return{type:`function`,name:r.value}}function Ts(e,t){let n=ws(e);if(!n||n.name!==t.name||n.type!==t.type)throw new c(`Chat completion stream contains a changed tool call identity`)}function Es(e,t){return Object.prototype.propertyIsEnumerable.call(t,`__proto__`)&&!E(e,`__proto__`)&&Object.defineProperty(e,"__proto__",{value:void 0,writable:!0,enumerable:!0,configurable:!0}),Object.assign(e,t)}function Ds(e,t=[]){let n=Object.getOwnPropertyDescriptors(e);for(let r of t){let t=n[r];!t&&!(r in e)||(n[r]={value:t&&`value`in t?t.value:Reflect.get(e,r,e),enumerable:t?.enumerable??!1,configurable:t?.configurable??!0,writable:t&&`writable`in t?t.writable:!1})}return Object.create(Object.getPrototypeOf(e),n)}function Os(e){let t=Ds(e);if(e.tools){let n=[],r=Object.getOwnPropertyDescriptor(e.tools,`length`),i=r&&`value`in r?r.value:void 0,a=typeof i==`number`&&Number.isSafeInteger(i)&&i>=0?Math.min(i,ls):0;for(let t=0;t<a;t+=1){let r=Object.getOwnPropertyDescriptor(e.tools,String(t));if(!r||!(`value`in r)){n.length=t+1;continue}let i=r.value,a=Ds(i,[`type`,`$brand`,`$parseRaw`,`$callback`,`function`]),o=Object.getOwnPropertyDescriptors(a);if(Si(a)){let e=o.function;o.function={...e&&`value`in e?e:{configurable:!0,enumerable:!0,writable:!0},value:Ds(a.function,[`name`,`strict`])}}n[t]=Object.create(Object.getPrototypeOf(i),o)}t.tools=n}return e.response_format&&(t.response_format=Ds(e.response_format,[`type`,`$brand`,`$parseRaw`])),t}var ks=4096,As=JSON.stringify,js=1048576,Ms=64,Ns=Symbol(`omitted serialized parser value`),G=Symbol(`unsafe serialized parser value`);function Ps(e,t){let n=new WeakSet,r=e=>!Number.isSafeInteger(e)||e<0||t.bytes+e>js?!1:(t.bytes+=e,!0),i=(e,a)=>{if(a>Ms||t.nodes>=ks)return G;if(t.nodes+=1,e===void 0||typeof e==`function`||typeof e==`symbol`)return Ns;if(typeof e==`bigint`)return G;if(e===null||typeof e==`boolean`||typeof e==`number`){let t=As(e);return typeof t==`string`&&r(t.length)?t:G}if(typeof e==`string`)return r(e.length*6+2)?As(e):G;if(typeof e!=`object`||n.has(e))return G;let o=Array.isArray(e),s=Object.getPrototypeOf(e);if(o&&s!==Array.prototype||!o&&s!==null&&s!==Object.prototype)return G;for(let t=e;t!==null;t=Object.getPrototypeOf(t)){let e=Object.getOwnPropertyDescriptor(t,`toJSON`);if(e){if(!(`value`in e)||typeof e.value==`function`)return G;break}}n.add(e);try{if(!r(2))return G;if(o){let n=Object.getOwnPropertyDescriptor(e,`length`),o=n&&`value`in n?n.value:void 0;if(typeof o!=`number`||!Number.isSafeInteger(o)||o<0||o>ks-t.nodes)return G;let s=[];for(let n=0;n<o;n+=1){let o=String(n),c=Object.getOwnPropertyDescriptor(e,o);if(!c){if(Object.getOwnPropertyDescriptor(Array.prototype,o)||Object.getOwnPropertyDescriptor(Object.prototype,o)||(t.nodes+=1,!r(4)))return G;s.push(`null`);continue}if(!(`value`in c))return G;let l=i(c.value,a+1);if(l===G)return l;s.push(l===Ns?`null`:l)}return`[${s.join(`,`)}]`}let n=Reflect.ownKeys(e);if(n.length>ks-t.nodes)return G;let s=[];for(let t of n){if(typeof t!=`string`)continue;let n=Object.getOwnPropertyDescriptor(e,t);if(!n)return G;if(n.enumerable){if(!(`value`in n))return G;s.push([t,n.value])}}s.sort(([e],[t])=>e===t?0:e<t?-1:1);let c=[];for(let[e,t]of s){let n=i(t,a+1);if(n===G)return n;if(n!==Ns){if(!r(e.length*6+3))return G;c.push(`${As(e)}:${n}`)}}return`{${c.join(`,`)}}`}finally{n.delete(e)}};try{let t=i(e,0);return typeof t==`string`?t:void 0}catch{return}}function Fs(e,t,n,r){let i=Object.getOwnPropertyDescriptor(t,`$parseRaw`),a=Object.getOwnPropertyDescriptor(n,r);if(!i||!(`value`in i)||typeof i.value!=`function`||!a||!(`value`in a))return;let o=Ps(a.value,{nodes:0,bytes:0});o!==void 0&&e.set(t,o)}function Is(e,t,n,r,i){let a=t&&e.get(t),o=Object.getOwnPropertyDescriptor(n,r);return a!==void 0&&o!==void 0&&`value`in o&&Ps(i,{nodes:0,bytes:0})===a}function Ls(e,t){return e&&`value`in e?{...e,value:t}:{configurable:!0,enumerable:!0,writable:!0,value:t}}function Rs(e,t,n){for(let r of n){let n=e[r];!n&&!(r in t)||(e[r]=n&&`value`in n?{...n,value:void 0}:{configurable:n?.configurable??!0,enumerable:n?.enumerable??!1,writable:!1,value:void 0})}}function zs(e){let t=e.source??{type:e.type,...e.type===`function`?{function:{}}:{}},n=Object.getOwnPropertyDescriptors(t);if(n.type=Ls(n.type,e.type),e.type!==`function`||!e.function)return n.function&&=Ls(n.function,void 0),Rs(n,t,[`$brand`,`$parseRaw`,`$callback`]),Object.create(Object.getPrototypeOf(t),n);let r=n.function,i=r&&`value`in r&&typeof r.value==`object`&&r.value!==null?r.value:{},a=Object.getOwnPropertyDescriptors(i);return a.name=Ls(a.name,e.function.name),a.strict=Ls(a.strict,e.function.strict),n.function=Ls(r,Object.create(Object.getPrototypeOf(i),a)),e.function.schemaMatches||Rs(n,t,[`$brand`,`$parseRaw`,`$callback`]),Object.create(Object.getPrototypeOf(t),n)}function Bs(e){let t=e.source??{type:e.type},n=Object.getOwnPropertyDescriptors(t);return n.type=Ls(n.type,e.type),(e.type!==`json_schema`||!e.source||!e.schemaMatches)&&Rs(n,t,[`$brand`,`$parseRaw`]),Object.create(Object.getPrototypeOf(t),n)}function Vs(e,t){let n=Object.getOwnPropertyDescriptor(e,t);if(!n||!(`value`in n))return;let{value:r}=n;return typeof r==`object`&&r?r:void 0}function Hs(e,t,n){let r=new WeakMap,i=new WeakMap;if(e.tools)for(let n=0;n<e.tools.length&&n<ls;n+=1){let a=Vs(e.tools,String(n)),o=t.tools?.[n];if(a&&o){r.set(a,o);let e=Vs(o,`function`);e&&Fs(i,o,e,`parameters`)}}t.response_format&&Fs(i,t.response_format,t.response_format,`json_schema`);let a,o,s,c,l=[],u=new WeakMap,d=new Map,f=new WeakMap;return bt(e,{value(n,p,m){if(!a&&p===``&&typeof m==`object`&&m){a=m,o=void 0,s=void 0,c=void 0,l=[],u=new WeakMap,d=new Map,f=new WeakMap;return}if(n===a&&p===`response_format`){typeof m==`object`&&m&&(s=m,c={source:Vs(n,p)===e.response_format?t.response_format:void 0,schemaMatches:!1});return}if(n===a&&p===`tools`)return Array.isArray(m)?(o=new Proxy(m,{get(e,t){let n=Reflect.get(e,t,e);if(typeof t==`string`){let e=Number(t);Number.isSafeInteger(e)&&e>=0&&e<ls&&String(e)===t&&d.set(e,typeof n==`object`&&n?n:void 0)}return n}}),o):void 0;if(n===o){let e=Number(p);if(!Number.isSafeInteger(e)||e<0||e>=ls||typeof m!=`object`||!m)return;let t=d.get(e),n={source:t?r.get(t):void 0};l[e]=n,u.set(m,n);return}let h=u.get(n);if(h){if(p===`type`&&typeof m==`string`)h.type=m;else if(p===`function`&&typeof m==`object`&&m){let e={source:h.source,schemaMatches:!1};h.function=e,f.set(m,e)}return}if(n===s&&c){p===`type`&&typeof m==`string`?c.type=m:p===`json_schema`&&(c.schemaMatches=Is(i,c.source,n,p,m));return}let g=f.get(n);g&&(p===`name`&&typeof m==`string`?g.name=m:p===`strict`&&typeof m==`boolean`?g.strict=m:p===`parameters`&&(g.schemaMatches=Is(i,g.source,n,p,m)))},complete(){if(!a)return;let e=Ds(t);if(o){let t=[];for(let e=0;e<l.length;e+=1){let n=l[e];n&&(t[e]=zs(n))}e.tools=t}else delete e.tools;c?e.response_format=Bs(c):delete e.response_format,n(e),a=void 0,o=void 0,s=void 0,c=void 0,l=[],u=new WeakMap,d=new Map,f=new WeakMap}})}var Us=class e extends Lo{constructor(e){super(),H.add(this),U.set(this,void 0),Wo.set(this,!1),Go.set(this,void 0),Ko.set(this,void 0),W.set(this,void 0),qo.set(this,void 0),Jo.set(this,void 0),r(this,U,e,`f`),r(this,Go,new Set,`f`),r(this,Ko,[],`f`),r(this,qo,!1,`f`);let t=e?.tools,n=t&&Object.getOwnPropertyDescriptor(t,`length`),i=n&&`value`in n?n.value:void 0;if(t&&typeof i==`number`&&Number.isSafeInteger(i)&&i>=0)for(let e=0;e<Math.min(i,ls);e+=1){let n=Object.getOwnPropertyDescriptor(t,String(e));if(!n||!(`value`in n))continue;let i=n.value;if(Si(i)&&(Ei(i)||i.function.strict===!0)){r(this,qo,!0,`f`);break}}r(this,Jo,{bytes:0,fragments:0,work:0},`f`)}get currentChatCompletionSnapshot(){return i(this,W,`f`)}static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}static createChatCompletion(t,n,r){let i=new e(n);return i._run(()=>i._runChatCompletion(t,{...n,stream:!0},{...r,__metadata:{...r?.__metadata,helperMethod:`stream`}})),i}_runTools(e,t,n,i){return r(this,Wo,!0,`f`),super._runTools(e,t,n,i)}async _createChatCompletion(e,t,n){this._listenForAbort(n?.signal);let a={...t,stream:!0};r(this,U,a,`f`),i(this,H,`m`,Yo).call(this);let o=Os(a);r(this,U,o,`f`),r(this,qo,o.tools?.some(e=>Si(e)&&(Ei(e)||e.function.strict===!0))??!1,`f`);let s=a.tools||a.response_format?Hs(a,o,e=>{r(this,U,e,`f`),r(this,qo,e.tools?.some(e=>Si(e)&&(Ei(e)||e.function.strict===!0))??!1,`f`)}):void 0,c=await e.chat.completions.create(a,{...n,signal:this.controller.signal}).finally(s);this._connected();for await(let e of c)i(this,H,`m`,Zo).call(this,e);if(c.controller.signal?.aborted)throw this._userAbortError();return this._addChatCompletion(i(this,H,`m`,ts).call(this))}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),i(this,H,`m`,Yo).call(this),this._connected();let n=et.fromReadableStream(e,this.controller),r;for await(let e of n){if(`error`in e&&E(e,`error`)&&typeof e.error==`object`&&e.error!==null)throw new l(void 0,e.error,void 0,void 0);if(os(e)){let t=ss(e);if(i(this,W,`f`)){let e=i(this,W,`f`).choices[0]?.message.tool_calls;for(let[n,r]of t.tool_call_ids?.entries()??[]){let t=e?.[n];t&&r&&(t.id=r)}this._addChatCompletion(i(this,H,`m`,ts).call(this)),r=void 0}this._addMessage(t.message);continue}let t=e;r&&t.id&&r!==t.id&&this._addChatCompletion(i(this,H,`m`,ts).call(this)),i(this,H,`m`,Zo).call(this,t),t.id&&(r=t.id)}if(n.controller.signal?.aborted)throw this._userAbortError();if(i(this,W,`f`))return this._addChatCompletion(i(this,H,`m`,ts).call(this));let a=this._chatCompletions[this._chatCompletions.length-1];if(a)return a;throw new c(`request ended without sending any chunks`)}[(U=new WeakMap,Wo=new WeakMap,Go=new WeakMap,Ko=new WeakMap,W=new WeakMap,qo=new WeakMap,Jo=new WeakMap,H=new WeakSet,Yo=function(){this.ended||(r(this,Go,new Set,`f`),r(this,W,void 0,`f`),r(this,Jo,{bytes:0,fragments:0,work:0},`f`))},Xo=function(e){let t=i(this,Ko,`f`)[e.index];return t||(t={content_done:!1,content_parse_state:void 0,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null,tool_call_parse_states:new Map,tool_call_identities:new Map},i(this,Ko,`f`)[e.index]=t,t)},Zo=function(e){if(this.ended)return;let t=new WeakMap,n=i(this,H,`m`,ns).call(this,e,t);this._emit(`chunk`,e,n);for(let r of e.choices){let e=t.get(r),a=n.choices[e?.index??r.index],o=e?.tool_calls??[],{delta:s}=r,l=wi(i(this,U,`f`)?.response_format),u=l||i(this,qo,`f`),d=u?ys(a):a.message,f=u?vs(d,`refusal`):d.refusal,p=!f&&l?vs(d,`content`):d.content;s?.content!=null&&d.role===`assistant`&&p&&(this._emit(`content`,s.content,p),this._emit(`content.delta`,{delta:s.content,snapshot:p,parsed:d.parsed})),s?.refusal!=null&&d.role===`assistant`&&f&&this._emit(`refusal.delta`,{delta:s.refusal,snapshot:f}),r.logprobs?.content!=null&&d.role===`assistant`&&this._emit(`logprobs.content.delta`,{content:r.logprobs?.content,snapshot:a.logprobs?.content??[]}),r.logprobs?.refusal!=null&&d.role===`assistant`&&this._emit(`logprobs.refusal.delta`,{refusal:r.logprobs?.refusal,snapshot:a.logprobs?.refusal??[]});let m=i(this,H,`m`,Xo).call(this,a);a.finish_reason&&(i(this,H,`m`,$o).call(this,a),m.current_tool_call_index!=null&&i(this,H,`m`,Qo).call(this,a,m.current_tool_call_index));for(let e of o)m.current_tool_call_index!==e.index&&(i(this,H,`m`,$o).call(this,a),m.current_tool_call_index!=null&&i(this,H,`m`,Qo).call(this,a,m.current_tool_call_index)),m.current_tool_call_index=e.index;for(let e of o){let t=d.tool_calls?.[e.index];if(t?.type){if(t.type===`function`){let n=m.tool_call_identities.get(e.index),r;if(n?.parseable){let e=vs(t.function,`arguments`);if(typeof e!=`string`)throw new c(`Chat completion stream contains an unsafe structured JSON snapshot`);r=e}else r=t.function.arguments;this._emit(`tool_calls.function.arguments.delta`,{name:t.function.name,index:e.index,arguments:r,parsed_arguments:t.function.parsed_arguments,arguments_delta:e.arguments_delta})}else t.type}}}},Qo=function(e,t){let n=i(this,H,`m`,Xo).call(this,e);if(n.done_tool_calls.has(t))return;let r=(i(this,qo,`f`)?ys(e):e.message).tool_calls?.[t];if(!r)throw Error(`no tool call snapshot`);let a=n.tool_call_identities.get(t);if(a&&Ts(r,a),!r.type)throw Error("tool call snapshot missing `type`");if(r.type===`function`){let a=i(this,U,`f`)?.tools?.find(e=>Si(e)&&e.function.name===r.function.name),o=null,s=Ei(a)||a?.function.strict===!0,l;if(s){i(this,W,`f`)&&i(this,H,`m`,es).call(this,i(this,W,`f`));let e=vs(r.function,`arguments`);if(typeof e!=`string`)throw new c(`Chat completion stream contains an unsafe structured JSON snapshot`);l=e}else l=r.function.arguments;Ei(a)?o=a.$parseRaw(Cs(l)):a?.function.strict&&(o=Ti({type:`json_schema`,$parseRaw:void 0},Cs(l))),e.finish_reason&&n.done_tool_calls.add(t),this._emit(`tool_calls.function.arguments.done`,{name:r.function.name,index:t,arguments:l,parsed_arguments:o})}else r.type},$o=function(e){let t=i(this,H,`m`,Xo).call(this,e),n=wi(i(this,U,`f`)?.response_format),r=n||i(this,qo,`f`),a=r?ys(e):e.message,o=r?vs(a,`refusal`):a.refusal,s=!o&&n,c=s?vs(a,`content`):a.content;c!=null&&(c!==``||!o&&!a.tool_calls?.length&&!a.function_call)&&!t.content_done&&(s&&i(this,W,`f`)&&i(this,H,`m`,es).call(this,i(this,W,`f`)),t.content_done=!0,this._emit(`content.done`,{content:c,parsed:o?null:Ti(i(this,U,`f`)?.response_format,s?Cs(c):c)})),o&&!t.refusal_done&&(t.refusal_done=!0,this._emit(`refusal.done`,{refusal:o})),e.logprobs?.content&&!t.logprobs_content_done&&(t.logprobs_content_done=!0,this._emit(`logprobs.content.done`,{content:e.logprobs.content})),e.logprobs?.refusal&&!t.logprobs_refusal_done&&(t.logprobs_refusal_done=!0,this._emit(`logprobs.refusal.done`,{refusal:e.logprobs.refusal}))},es=function(e){let t={bytes:0,fragments:0,work:0},n=wi(i(this,U,`f`)?.response_format),r=new WeakMap,a=bs(e,`choices`,cs,`choice`);if(!a)throw new c(`Chat completion stream contains an unsafe snapshot choice collection`);for(let e=0;e<a.length;e+=1){let o=xs(a,e);if(!o)continue;let s=ys(o),l=vs(s,`refusal`),u=vs(s,`content`),d=new Map,f=bs(s,`tool_calls`,ls,`tool-call`);r.set(o,Object.freeze({message:s,content:u,refusal:l,toolCallCollection:f,toolCalls:d}));let p=i(this,Ko,`f`)[o.index];n&&!l&&typeof u==`string`&&Cs(u,t,i(this,Jo,`f`));for(let[e,t]of p?.tool_call_identities??[]){let n=f&&xs(f,e);if(!n)throw new c(`Chat completion stream contains a changed tool call identity`);Ts(n,t)}if(i(this,qo,`f`))for(let e=0;e<(f?.length??0);e+=1){let n=xs(f,e);if(!n)continue;let r=ws(n);if(!r){let e=Object.getOwnPropertyDescriptor(n,`type`);if(e&&!(`value`in e))throw new c(`Chat completion stream contains an unsafe structured JSON snapshot`);if(e?.value!==`function`)continue;let t=Object.getOwnPropertyDescriptor(n,`function`);if(t&&!(`value`in t))throw new c(`Chat completion stream contains an unsafe structured JSON snapshot`);if(t&&typeof t.value==`object`&&t.value!==null){let e=Object.getOwnPropertyDescriptor(t.value,`name`);if(e&&!(`value`in e))throw new c(`Chat completion stream contains an unsafe structured JSON snapshot`)}continue}if(!ji(i(this,U,`f`),{type:r.type,function:{name:r.name}}))continue;let a=Object.getOwnPropertyDescriptor(n,`function`);if(!a||!(`value`in a))throw new c(`Chat completion stream contains an unsafe structured JSON snapshot`);let o=a.value,s=vs(o,`arguments`);if(typeof s!=`string`)throw new c(`Chat completion stream contains an unsafe structured JSON snapshot`);Cs(s,t,i(this,Jo,`f`)),d.set(e,Object.freeze({tool:n,function:o,type:r.type,name:r.name,arguments:s}))}}return r},ts=function(){if(this.ended)throw new c(`stream has ended, this shouldn't happen`);let e=i(this,W,`f`);if(!e)throw new c(`request ended without sending any chunks`);let t=i(this,H,`m`,es).call(this,e),n=i(this,Go,`f`);return r(this,Go,new Set,`f`),r(this,W,void 0,`f`),r(this,Ko,[],`f`),Ws(e,i(this,U,`f`),n,t)},ns=function(e,t){var n,a,o,s,l;let u=i(this,W,`f`),{choices:d,obfuscation:f,...p}=e;if(u)e.id&&Es(u,p);else{let e={...p,choices:[]};r(this,W,e,`f`),u=e}let m=i(this,U,`f`)?.n,h=typeof m==`number`&&Number.isSafeInteger(m)&&m>0?Math.min(m,cs):cs;for(let r of e.choices){let{delta:e,finish_reason:d,index:f,logprobs:p=null,...m}=r,g=[];if(t.set(r,Object.freeze({index:f,tool_calls:g})),!Number.isSafeInteger(f)||f<0||f>=h)throw new c(`Chat completion stream contains an invalid choice index: ${f}`);let _=u.choices[f];if(!_){let e={finish_reason:d,index:f,message:{},logprobs:null,...m};u.choices[f]=e,_=e}if((wi(i(this,U,`f`)?.response_format)||i(this,qo,`f`))&&vs(ys(_),`refusal`),p){if(_.logprobs){let{content:e,refusal:t,...r}=p;Es(_.logprobs,r),e&&((n=_.logprobs).content??(n.content=[]),_.logprobs.content.push(...e)),t&&((a=_.logprobs).refusal??(a.refusal=[]),_.logprobs.refusal.push(...t))}else _.logprobs={...p},p.content&&(_.logprobs.content=[...p.content]),p.refusal&&(_.logprobs.refusal=[...p.refusal])}if(d&&(_.finish_reason=d,i(this,U,`f`)&&(i(this,Wo,`f`)||Mi(i(this,U,`f`))))){if(d===`length`)throw new x;if(d===`content_filter`)throw new ee}if(Es(_,m),!e){Object.freeze(g);continue}i(this,Go,`f`).delete(f);let{audio:v,content:y,refusal:b,function_call:S,role:C,...te}=e,{tool_calls:w,...ne}=te,T=E(te,`tool_calls`)?w:e.tool_calls;if(Es(_.message,ne),v?.expires_at!=null&&v.id==null&&v.data==null&&v.transcript==null&&y==null&&b==null&&S==null&&C==null&&T==null&&Object.keys(ne).length===0&&i(this,Go,`f`).add(f),b&&(_.message.refusal=(_.message.refusal||``)+b),C&&(_.message.role=C),v){let e=(o=_.message).audio??(o.audio={});v.id!=null&&(e.id=v.id),v.data!=null&&(e.data=(e.data??``)+v.data),v.transcript!=null&&(e.transcript=(e.transcript??``)+v.transcript),v.expires_at!=null&&(e.expires_at=v.expires_at)}if(S&&(_.message.function_call?(S.name&&(_.message.function_call.name=S.name),S.arguments&&((s=_.message.function_call).arguments??(s.arguments=``),_.message.function_call.arguments+=S.arguments)):_.message.function_call=S),y!=null){if(!_.message.refusal&&wi(i(this,U,`f`)?.response_format)){let e=i(this,H,`m`,Xo).call(this,_),t=e.content_parse_state??=hs(),n=gs(t,i(this,Jo,`f`),y);_.message.content=(vs(_.message,`content`)||``)+y,t.has_non_whitespace?n&&_s(t,i(this,Jo,`f`))?(i(this,H,`m`,es).call(this,u),_.message.parsed=rs(Cs(_.message.content))):y.length>0&&(_.message.parsed=null):_.message.parsed=null}else _.message.content=(_.message.content||``)+y}if(T){let e=(l=_.message).tool_calls??(l.tool_calls=[]);for(let t of T){let{index:n,id:r,type:a,function:o,custom:s,...l}=t;if(!Number.isSafeInteger(n)||n<0||n>=ls)throw new c(`Chat completion stream contains an invalid tool call index: ${n}`);let d=``,f=e[n]??(e[n]={}),p=o?.name,m=i(this,qo,`f`)?i(this,H,`m`,Xo).call(this,_):void 0,h=m?.tool_call_identities.get(n);if(h&&(Ts(f,h),a!==void 0&&a!==h.type||p!==void 0&&p!==h.name))throw new c(`Chat completion stream contains a changed tool call identity`);if(Es(f,l),r&&(f.id=r),a&&(f.type=a),s){let e=f.custom??={name:s.name??``,input:``};s.name&&(e.name=s.name),s.input&&(e.input+=s.input)}if(o){let e=f.function??={name:p??``,arguments:``};if(p&&(e.name=p),m&&!h){let e=ws(f),t=e&&i(this,U,`f`)?.tools?.find(t=>Si(t)&&t.function.name===e.name);if(e&&(h={...e,parseable:t!==void 0&&ji(i(this,U,`f`),{type:e.type,function:{name:e.name}})},m.tool_call_identities.set(n,h),!h.parseable)){let e=m.tool_call_parse_states.get(n);e&&(i(this,Jo,`f`).bytes-=e.bytes,i(this,Jo,`f`).fragments-=e.fragments,i(this,Jo,`f`).work-=e.work,m.tool_call_parse_states.delete(n))}}let t=o.arguments;if(t!=null){if(d=t,m&&h?.parseable!==!1){let r=m.tool_call_parse_states.get(n);r||(r=hs(),m.tool_call_parse_states.set(n,r));let a=gs(r,i(this,Jo,`f`),t),o=vs(e,`arguments`);if(typeof o!=`string`)throw new c(`Chat completion stream contains an unsafe structured JSON snapshot`);e.arguments=o+t,a&&h?.parseable===!0&&_s(r,i(this,Jo,`f`))?(i(this,H,`m`,es).call(this,u),e.parsed_arguments=rs(Cs(e.arguments))):t.length>0&&E(e,`parsed_arguments`)&&(e.parsed_arguments=void 0)}else e.arguments+=t}}g.push(Object.freeze({index:n,arguments_delta:d}))}}Object.freeze(g)}return u},Symbol.asyncIterator)](){return this._createIterator(e=>{let t=t=>e(t);return this.on(`chunk`,t),()=>this.off(`chunk`,t)},{onReturn:()=>this.abort()})}toReadableStream(){return new et(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function Ws(e,t,n,r){let{id:i,choices:o,created:s,model:l,system_fingerprint:u,...d}=e;return Di({...d,id:i,choices:Ss(o,cs,`choice`,e=>{let i=r.get(e);if(!i)throw new c(`Chat completion stream contains an unsafe structured JSON snapshot`);let{message:o,finish_reason:s,index:l,logprobs:u,...d}=new Proxy(e,{get(e,t,n){return t===`message`?i.message:Reflect.get(e,t,n)}}),f=new Proxy(o,{get(e,t,n){return t===`content`?i.content:t===`refusal`?i.refusal:t===`tool_calls`?i.toolCallCollection:Reflect.get(e,t,n)}}),{content:p=null,function_call:m,tool_calls:h,audio:g,..._}=f,v=s??(n.has(l)&&Gs(g)?`stop`:null);if(!v)throw new c(`missing finish_reason for choice ${l}`);let y=g?{audio:g}:{},b=f.role;if(!b)throw new c(`missing role for choice ${l}`);if(m){let{arguments:e,name:t}=m;if(e==null)throw new c(`missing function_call.arguments for choice ${l}`);if(!t)throw new c(`missing function_call.name for choice ${l}`);return{...d,message:{...y,content:p,function_call:{arguments:e,name:t},role:b,refusal:f.refusal??null},finish_reason:v,index:l,logprobs:u}}return h?{...d,index:l,finish_reason:v,logprobs:u,message:{..._,...y,role:b,content:p,refusal:f.refusal??null,tool_calls:Ss(h,ls,`tool-call`,(e,n)=>{let r=i.toolCalls.get(n);if(!r){let n=ws(e);if(n&&ji(t,{type:n.type,function:{name:n.name}}))throw new c(`Chat completion stream contains an unsafe structured JSON snapshot`)}if(r&&r.tool!==e)throw new c(`Chat completion stream contains a changed tool call identity`);let o=r&&new Proxy(r.function,{get(e,t,n){return t===`arguments`?r.arguments:t===`name`?r.name:Reflect.get(e,t,n)}}),s=r&&o?new Proxy(e,{get(e,t,n){return t===`type`?r.type:t===`function`?o:Reflect.get(e,t,n)}}):e;if(s.type==null)throw new c(`missing choices[${l}].tool_calls[${n}].type`);if(s.type===`custom`){let{custom:e,type:t,id:r,...i}=s,{input:o=``,name:u,...d}=e||{};if(u==null)throw new c(`missing choices[${l}].tool_calls[${n}].custom.name`);return{...i,id:r||`call_${a()}`,type:t,custom:{...d,name:u,input:o}}}let{function:u,type:d,id:f,...p}=s,{arguments:m,name:h,...g}=u||{};if(h==null)throw new c(`missing choices[${l}].tool_calls[${n}].function.name`);if(m==null)throw new c(`missing choices[${l}].tool_calls[${n}].function.arguments`);return{...p,id:f||`call_${a()}`,type:d,function:{...g,name:h,arguments:m}}})}}:{...d,message:{..._,...y,content:p,role:b,refusal:f.refusal??null},finish_reason:v,index:l,logprobs:u}}),created:s,model:l,object:`chat.completion`,...u?{system_fingerprint:u}:{}},t)}function Gs(e){return e?.id!=null&&e.data!=null&&e.transcript!=null&&e.expires_at!=null}var Ks=class e extends Us{static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}toReadableStream(){let e,t,n=this._createIterator(n=>{let r=t=>{e=t,n(t)},i=r=>{if(Pi(r)){t=r.tool_calls?.map(e=>e.id);return}if(Fi(r)){if(!e)throw new c(`cannot serialize a tool message before receiving any chunks`);n(as(e,r,t)),t=void 0}};return this.on(`chunk`,r),this.on(`message`,i),()=>{this.off(`chunk`,r),this.off(`message`,i)}},{onReturn:()=>this.abort()});return new et(()=>n,this.controller).toReadableStream()}static runTools(t,n,r){let i=new e(n),a={...r,__metadata:{...r?.__metadata,helperMethod:`runTools`}};return i._run(()=>i._runTools(t,n,i,a)),i}},qs=class extends R{constructor(){super(...arguments),this.messages=new xi(this._client)}create(e,t){return this._client.post(`/chat/completions`,{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(z`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(z`/chat/completions/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/chat/completions`,M,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(z`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}parse(e,t){return Ni(e.tools),this._client.chat.completions.create(e,{...t,__metadata:{...t?.__metadata,helperMethod:`chat.completions.parse`}})._thenUnwrap(t=>Oi(t,e))}runTools(e,t){return e.stream?Ks.runTools(this._client,e,t):Ro.runTools(this._client,e,t)}stream(e,t){return Us.createChatCompletion(this._client,e,t)}};qs.Messages=xi;var Js=class extends R{constructor(){super(...arguments),this.completions=new qs(this._client)}};Js.Completions=qs;var Ys=class extends R{create(e,t){return this._client.post(`/organization/admin_api_keys`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(z`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/admin_api_keys`,M,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(z`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},Xs=class extends R{list(e={},t){return this._client.getAPIList(`/organization/audit_logs`,N,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}},Zs=class extends R{create(e,t){return this._client.post(`/organization/certificates`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},n){return this._client.get(z`/organization/certificates/${e}`,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(z`/organization/certificates/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/certificates`,N,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(z`/organization/certificates/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}activate(e,t){return this._client.getAPIList(`/organization/certificates/activate`,Yt,{body:e,method:`post`,...t,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t){return this._client.getAPIList(`/organization/certificates/deactivate`,Yt,{body:e,method:`post`,...t,__security:{adminAPIKeyAuth:!0}})}},Qs=class extends R{retrieve(e){return this._client.get(`/organization/data_retention`,{...e,__security:{adminAPIKeyAuth:!0}})}update(e,t){return this._client.post(`/organization/data_retention`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}},$s=class extends R{create(e,t){return this._client.post(`/organization/invites`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(z`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/invites`,N,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(z`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},ec=class extends R{create(e,t){return this._client.post(`/organization/roles`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(z`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(z`/organization/roles/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/roles`,Xt,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(z`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},tc=class extends R{create(e,t){return this._client.post(`/organization/spend_alerts`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(z`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(z`/organization/spend_alerts/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/spend_alerts`,N,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(z`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},nc=class extends R{retrieve(e){return this._client.get(`/organization/spend_limit`,{...e,__security:{adminAPIKeyAuth:!0}})}update(e,t){return this._client.post(`/organization/spend_limit`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e){return this._client.delete(`/organization/spend_limit`,{...e,__security:{adminAPIKeyAuth:!0}})}},rc=class extends R{audioSpeeches(e,t){return this._client.get(`/organization/usage/audio_speeches`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}audioTranscriptions(e,t){return this._client.get(`/organization/usage/audio_transcriptions`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}codeInterpreterSessions(e,t){return this._client.get(`/organization/usage/code_interpreter_sessions`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}completions(e,t){return this._client.get(`/organization/usage/completions`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}costs(e,t){return this._client.get(`/organization/costs`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}embeddings(e,t){return this._client.get(`/organization/usage/embeddings`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}fileSearchCalls(e,t){return this._client.get(`/organization/usage/file_search_calls`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}images(e,t){return this._client.get(`/organization/usage/images`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}moderations(e,t){return this._client.get(`/organization/usage/moderations`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}vectorStores(e,t){return this._client.get(`/organization/usage/vector_stores`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}webSearchCalls(e,t){return this._client.get(`/organization/usage/web_search_calls`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}},ic=class extends R{create(e,t,n){return this._client.post(z`/organization/groups/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{group_id:r}=t;return this._client.get(z`/organization/groups/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(z`/organization/groups/${e}/roles`,Xt,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{group_id:r}=t;return this._client.delete(z`/organization/groups/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},ac=class extends R{create(e,t,n){return this._client.post(z`/organization/groups/${e}/users`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{group_id:r}=t;return this._client.get(z`/organization/groups/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(z`/organization/groups/${e}/users`,Xt,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{group_id:r}=t;return this._client.delete(z`/organization/groups/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},oc=class extends R{constructor(){super(...arguments),this.users=new ac(this._client),this.roles=new ic(this._client)}create(e,t){return this._client.post(`/organization/groups`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(z`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(z`/organization/groups/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/groups`,Xt,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(z`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};oc.Users=ac,oc.Roles=ic;var sc=class extends R{retrieve(e,t,n){let{project_id:r}=t;return this._client.get(z`/organization/projects/${r}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(z`/organization/projects/${e}/api_keys`,N,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(z`/organization/projects/${r}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},cc=class extends R{list(e,t={},n){return this._client.getAPIList(z`/organization/projects/${e}/certificates`,N,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}activate(e,t,n){return this._client.getAPIList(z`/organization/projects/${e}/certificates/activate`,Yt,{body:t,method:`post`,...n,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t,n){return this._client.getAPIList(z`/organization/projects/${e}/certificates/deactivate`,Yt,{body:t,method:`post`,...n,__security:{adminAPIKeyAuth:!0}})}},lc=class extends R{retrieve(e,t){return this._client.get(z`/organization/projects/${e}/data_retention`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(z`/organization/projects/${e}/data_retention`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}},uc=class extends R{retrieve(e,t){return this._client.get(z`/organization/projects/${e}/hosted_tool_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(z`/organization/projects/${e}/hosted_tool_permissions`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}},dc=class extends R{retrieve(e,t){return this._client.get(z`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(z`/organization/projects/${e}/model_permissions`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(z`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}},fc=class extends R{listRateLimits(e,t={},n){return this._client.getAPIList(z`/organization/projects/${e}/rate_limits`,N,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,t,n){let{project_id:r,...i}=t;return this._client.post(z`/organization/projects/${r}/rate_limits/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}},pc=class extends R{create(e,t,n){return this._client.post(z`/projects/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(z`/projects/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(z`/projects/${r}/roles/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(z`/projects/${e}/roles`,Xt,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(z`/projects/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},mc=class extends R{create(e,t,n){return this._client.post(z`/organization/projects/${e}/spend_alerts`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(z`/organization/projects/${r}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(z`/organization/projects/${r}/spend_alerts/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(z`/organization/projects/${e}/spend_alerts`,N,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(z`/organization/projects/${r}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},hc=class extends R{retrieve(e,t){return this._client.get(z`/organization/projects/${e}/spend_limit`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(z`/organization/projects/${e}/spend_limit`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(z`/organization/projects/${e}/spend_limit`,{...t,__security:{adminAPIKeyAuth:!0}})}},gc=class extends R{create(e,t,n){let{project_id:r,...i}=t;return this._client.post(z`/projects/${r}/groups/${e}/roles`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r,group_id:i}=t;return this._client.get(z`/projects/${r}/groups/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t,n){let{project_id:r,...i}=t;return this._client.getAPIList(z`/projects/${r}/groups/${e}/roles`,Xt,{query:i,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r,group_id:i}=t;return this._client.delete(z`/projects/${r}/groups/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},_c=class extends R{constructor(){super(...arguments),this.roles=new gc(this._client)}create(e,t,n){return this._client.post(z`/organization/projects/${e}/groups`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r,...i}=t;return this._client.get(z`/organization/projects/${r}/groups/${e}`,{query:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(z`/organization/projects/${e}/groups`,Xt,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(z`/organization/projects/${r}/groups/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};_c.Roles=gc;var vc=class extends R{create(e,t,n){let{project_id:r,...i}=t;return this._client.post(z`/organization/projects/${r}/service_accounts/${e}/api_keys`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}},yc=class extends R{constructor(){super(...arguments),this.apiKeys=new vc(this._client)}create(e,t,n){return this._client.post(z`/organization/projects/${e}/service_accounts`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(z`/organization/projects/${r}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(z`/organization/projects/${r}/service_accounts/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(z`/organization/projects/${e}/service_accounts`,N,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(z`/organization/projects/${r}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};yc.APIKeys=vc;var bc=class extends R{create(e,t,n){let{project_id:r,...i}=t;return this._client.post(z`/projects/${r}/users/${e}/roles`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r,user_id:i}=t;return this._client.get(z`/projects/${r}/users/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t,n){let{project_id:r,...i}=t;return this._client.getAPIList(z`/projects/${r}/users/${e}/roles`,Xt,{query:i,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r,user_id:i}=t;return this._client.delete(z`/projects/${r}/users/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},xc=class extends R{constructor(){super(...arguments),this.roles=new bc(this._client)}create(e,t,n){return this._client.post(z`/organization/projects/${e}/users`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(z`/organization/projects/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(z`/organization/projects/${r}/users/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(z`/organization/projects/${e}/users`,N,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(z`/organization/projects/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};xc.Roles=bc;var Sc=class extends R{constructor(){super(...arguments),this.users=new xc(this._client),this.serviceAccounts=new yc(this._client),this.apiKeys=new sc(this._client),this.rateLimits=new fc(this._client),this.modelPermissions=new dc(this._client),this.hostedToolPermissions=new uc(this._client),this.groups=new _c(this._client),this.roles=new pc(this._client),this.dataRetention=new lc(this._client),this.spendLimit=new hc(this._client),this.spendAlerts=new mc(this._client),this.certificates=new cc(this._client)}create(e,t){return this._client.post(`/organization/projects`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(z`/organization/projects/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(z`/organization/projects/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/projects`,N,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}archive(e,t){return this._client.post(z`/organization/projects/${e}/archive`,{...t,__security:{adminAPIKeyAuth:!0}})}};Sc.Users=xc,Sc.ServiceAccounts=yc,Sc.APIKeys=sc,Sc.RateLimits=fc,Sc.ModelPermissions=dc,Sc.HostedToolPermissions=uc,Sc.Groups=_c,Sc.Roles=pc,Sc.DataRetention=lc,Sc.SpendLimit=hc,Sc.SpendAlerts=mc,Sc.Certificates=cc;var Cc=class extends R{create(e,t,n){return this._client.post(z`/organization/users/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{user_id:r}=t;return this._client.get(z`/organization/users/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(z`/organization/users/${e}/roles`,Xt,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{user_id:r}=t;return this._client.delete(z`/organization/users/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},wc=class extends R{constructor(){super(...arguments),this.roles=new Cc(this._client)}retrieve(e,t){return this._client.get(z`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(z`/organization/users/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/users`,N,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(z`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};wc.Roles=Cc;var Tc=class extends R{constructor(){super(...arguments),this.auditLogs=new Xs(this._client),this.adminAPIKeys=new Ys(this._client),this.usage=new rc(this._client),this.invites=new $s(this._client),this.users=new wc(this._client),this.groups=new oc(this._client),this.roles=new ec(this._client),this.dataRetention=new Qs(this._client),this.spendLimit=new nc(this._client),this.spendAlerts=new tc(this._client),this.certificates=new Zs(this._client),this.projects=new Sc(this._client)}};Tc.AuditLogs=Xs,Tc.AdminAPIKeys=Ys,Tc.Usage=rc,Tc.Invites=$s,Tc.Users=wc,Tc.Groups=oc,Tc.Roles=ec,Tc.DataRetention=Qs,Tc.SpendLimit=nc,Tc.SpendAlerts=tc,Tc.Certificates=Zs,Tc.Projects=Sc;var Ec=class extends R{constructor(){super(...arguments),this.organization=new Tc(this._client)}};Ec.Organization=Tc;var Dc=class extends R{create(e,t){return this._client.post(`/audio/speech`,{body:e,...t,headers:P([{Accept:`application/octet-stream`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},Oc=class extends R{create(e,t){return this._client.post(`/audio/transcriptions`,Ur({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}},kc=class extends R{create(e,t){return this._client.post(`/audio/translations`,Ur({body:e,...t,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}},Ac=class extends R{constructor(){super(...arguments),this.transcriptions=new Oc(this._client),this.translations=new kc(this._client),this.speech=new Dc(this._client)}};Ac.Transcriptions=Oc,Ac.Translations=kc,Ac.Speech=Dc;var jc=class extends R{create(e,t){return this._client.post(`/batches`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(z`/batches/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/batches`,M,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(z`/batches/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}},Mc=class extends R{create(e,t){return this._client.post(`/assistants`,{body:e,...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(z`/assistants/${e}`,{...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(z`/assistants/${e}`,{body:t,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/assistants`,M,{query:e,...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(z`/assistants/${e}`,{...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}},Nc=class extends R{create(e,t){return this._client.post(`/realtime/sessions`,{body:e,...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}},Pc=class extends R{create(e,t){return this._client.post(`/realtime/transcription_sessions`,{body:e,...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}},Fc=class extends R{constructor(){super(...arguments),this.sessions=new Nc(this._client),this.transcriptionSessions=new Pc(this._client)}};Fc.Sessions=Nc,Fc.TranscriptionSessions=Pc;var Ic=class extends R{create(e,t,n){return this._client.post(z`/agents/environments/${e}/files`,{body:t,...n,headers:P([{"OpenAI-Beta":`agents=v1`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(z`/agents/environments/${e}/files`,Zt,{query:t,...n,headers:P([{"OpenAI-Beta":`agents=v1`},n?.headers]),__security:{bearerAuth:!0}})}},Lc=class extends R{create(e={},t){return this._client.post(`/agents/environments/templates`,{body:e,...t,headers:P([{"OpenAI-Beta":`agents=v1`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(z`/agents/environments/templates/${e}`,{...t,headers:P([{"OpenAI-Beta":`agents=v1`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t={},n){return this._client.post(z`/agents/environments/templates/${e}`,{body:t,...n,headers:P([{"OpenAI-Beta":`agents=v1`},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/agents/environments/templates`,M,{query:e,...t,headers:P([{"OpenAI-Beta":`agents=v1`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(z`/agents/environments/templates/${e}`,{...t,headers:P([{"OpenAI-Beta":`agents=v1`},t?.headers]),__security:{bearerAuth:!0}})}},Rc=class extends R{constructor(){super(...arguments),this.files=new Ic(this._client),this.templates=new Lc(this._client)}retrieve(e,t){return this._client.get(z`/agents/environments/${e}`,{...t,headers:P([{"OpenAI-Beta":`agents=v1`},t?.headers]),__security:{bearerAuth:!0}})}};Rc.Files=Ic,Rc.Templates=Lc;var zc,Bc,Vc,Hc,Uc=class{constructor(){zc.set(this,void 0),Bc.set(this,!1),Vc.set(this,new Set),Hc.set(this,new Set)}accept(e){if(i(this,Vc,`f`).has(e.event_id))return!1;if(i(this,Vc,`f`).size===1024){let e=i(this,Vc,`f`).values().next();e.done||i(this,Vc,`f`).delete(e.value)}return i(this,Vc,`f`).add(e.event_id),e.type===`agent.session.turn.created`&&e.turn.subagent_id===null&&i(this,zc,`f`)===void 0&&r(this,zc,e.turn_id,`f`),(e.type===`agent.session.turn.completed`||e.type===`agent.session.turn.failed`||e.type===`agent.session.turn.cancelled`)&&i(this,zc,`f`)!==void 0&&e.turn_id===i(this,zc,`f`)&&r(this,Bc,!0,`f`),!0}terminal(e){return e.type===`agent.session.failed`||e.type===`agent.session.idle`&&i(this,Bc,`f`)}call(e){if(e.type!==`agent.session.turn.item.added`||e.item.type!==`function_call`)return;let t=e.item,n=JSON.stringify([t.turn_id,t.call_id]);if(!i(this,Hc,`f`).has(n))return i(this,Hc,`f`).add(n),t}};zc=new WeakMap,Bc=new WeakMap,Vc=new WeakMap,Hc=new WeakMap;var K,Wc,Gc,Kc,qc,Jc,Yc,Xc,Zc,Qc,$c,el,tl,nl,rl,il,al;function ol(e){if(!oe(e))return!1;let t=e,n;if(t.type===`input_text`)n=`text`;else if(t.type===`input_image`)n=`image_url`;else return!1;return E(t,`type`)&&E(t,n)&&typeof t[n]==`string`}function sl(e){if(e===null)return null;if(typeof e==`string`||Array.isArray(e)&&e.every(ol))return e;throw new c(`Tool output must be text, content, a JSON object, or null`)}function cl(e,t){let n=oe(t)?JSON.stringify(t):t,r=JSON.stringify(n);if(r===void 0)throw new c(`Tool output must be JSON serializable`);return{type:`agent.session.input.tool_result`,turn_id:e.turn_id,call_id:e.call_id,success:!0,output:sl(typeof n==`string`?n:JSON.parse(r))}}async function ll(e){try{await e?.body?.cancel()}catch{}}var ul=class{constructor(e,t,n,i){K.add(this),this.controller=new AbortController,Wc.set(this,!1),Gc.set(this,void 0),Kc.set(this,void 0),qc.set(this,!1),Jc.set(this,void 0),Yc.set(this,void 0),Xc.set(this,void 0),Zc.set(this,void 0),Qc.set(this,void 0),$c.set(this,void 0);let o=typeof n.input==`string`?[{role:`user`,content:[{type:`input_text`,text:n.input}]}]:n.input;if(n.input.length===0)throw new c(`input must not be empty`);r(this,Jc,e,`f`),r(this,Yc,t,`f`),r(this,Xc,{type:`agent.session.input.message`,input:o},`f`),r(this,Zc,new Map(Object.entries(n.toolHandlers??{})),`f`);let s=P([i?.headers]);r(this,Qc,s.nulls.has(`idempotency-key`)?void 0:s.values.get(`idempotency-key`)??n.idempotencyKey??i?.idempotencyKey??a(),`f`),s.values.delete(`idempotency-key`),s.nulls.delete(`idempotency-key`);let{idempotencyKey:l,...u}=i??{};r(this,$c,{...u,headers:s},`f`)}abort(e){this.controller.abort(e),i(this,Gc,`f`)?.controller.abort(this.controller.signal.reason),i(this,qc,`f`)||ll(i(this,Kc,`f`))}[(Wc=new WeakMap,Gc=new WeakMap,Kc=new WeakMap,qc=new WeakMap,Jc=new WeakMap,Yc=new WeakMap,Xc=new WeakMap,Zc=new WeakMap,Qc=new WeakMap,$c=new WeakMap,K=new WeakSet,Symbol.asyncIterator)](){if(i(this,Wc,`f`))throw new c(`An AgentSessionStream can only be consumed once`);return r(this,Wc,!0,`f`),i(this,K,`m`,el).call(this)}};el=async function*(){let e=i(this,$c,`f`).signal,t=()=>this.abort(e?.aborted?e.reason:this.controller.signal.reason);e?.addEventListener(`abort`,t,{once:!0}),this.controller.signal.addEventListener(`abort`,t,{once:!0});let n={...i(this,$c,`f`),signal:this.controller.signal},a=new Uc;try{if(e?.aborted&&this.abort(e.reason),i(this,K,`m`,nl).call(this),(await i(this,Jc,`f`).retrieve(i(this,Yc,`f`),n)).status!==`idle`)throw new c(`sessions.stream requires an idle session; use sessions.events.stream for active sessions`);let t=await i(this,Jc,`f`).events.stream(i(this,Yc,`f`),n).withResponse();r(this,Gc,t.data,`f`),r(this,Kc,t.response,`f`),i(this,K,`m`,nl).call(this),await i(this,Jc,`f`).events.create(i(this,Yc,`f`),{events:[i(this,Xc,`f`)],...i(this,Qc,`f`)===void 0?{}:{"Idempotency-Key":i(this,Qc,`f`)}},{...n,headers:P([n.headers,{"Idempotency-Key":i(this,Qc,`f`)??null}])}),i(this,K,`m`,nl).call(this),r(this,qc,!0,`f`);for await(let e of i(this,Gc,`f`)){if(i(this,K,`m`,nl).call(this),!a.accept(e))continue;let t=a.terminal(e),r=a.call(e),o=r&&i(this,Zc,`f`).get(r.name),s=r&&o?structuredClone(r):void 0;if(t&&i(this,Gc,`f`).controller.abort(),yield e,t)return;if(i(this,K,`m`,nl).call(this),!s||!o)continue;let c=await i(this,K,`m`,tl).call(this,s,o);i(this,K,`m`,nl).call(this),await i(this,K,`m`,al).call(this,c,n)}throw i(this,K,`m`,nl).call(this),new c(`Session event stream ended before the turn reached idle or failed`)}finally{e?.removeEventListener(`abort`,t),this.controller.signal.removeEventListener(`abort`,t),this.abort()}},tl=async function(e,t){try{let n=typeof e.arguments==`string`?JSON.parse(e.arguments):e.arguments;if(!oe(n))throw new c(`Function arguments must be a JSON object`);return cl(e,await i(this,K,`m`,il).call(this,()=>t(n)))}catch{return i(this,K,`m`,nl).call(this),{type:`agent.session.input.tool_result`,turn_id:e.turn_id,call_id:e.call_id,success:!1,error:`Tool handler failed.`}}},nl=function(){if(this.controller.signal.aborted)throw i(this,K,`m`,rl).call(this)},rl=function(){let e=new u;return Object.defineProperty(e,"cause",{value:this.controller.signal.reason,writable:!0,configurable:!0}),e},il=async function(e){let t,n=new Promise((e,n)=>{t=()=>n(i(this,K,`m`,rl).call(this)),this.controller.signal.addEventListener(`abort`,t,{once:!0})});try{return i(this,K,`m`,nl).call(this),await Promise.race([(async()=>await e())(),n])}finally{t&&this.controller.signal.removeEventListener(`abort`,t)}},al=async function e(t,n,r=a(),o=0){i(this,K,`m`,nl).call(this);try{await i(this,Jc,`f`).events.create(i(this,Yc,`f`),{events:[t],"Idempotency-Key":r},n)}catch(a){let s=[100,300,600][o];if(s===void 0||!(a instanceof p)||a.code!==`invalid_request_error`||!a.error||!(`message`in a.error)||a.error.message!==`Unknown pending tool call: ${t.call_id}`)throw a;let c;try{await i(this,K,`m`,il).call(this,()=>new Promise(e=>{c=setTimeout(e,s)}))}finally{c!==void 0&&clearTimeout(c)}await i(this,K,`m`,e).call(this,t,n,r,o+1)}};var dl=class extends R{retrieve(e,t,n){let{session_id:r}=t;return this._client.get(z`/agents/sessions/${r}/artifacts/${e}`,{...n,headers:P([{"OpenAI-Beta":`agents=v1`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(z`/agents/sessions/${e}/artifacts`,M,{query:t,...n,headers:P([{"OpenAI-Beta":`agents=v1`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{session_id:r}=t;return this._client.delete(z`/agents/sessions/${r}/artifacts/${e}`,{...n,headers:P([{"OpenAI-Beta":`agents=v1`},n?.headers]),__security:{bearerAuth:!0}})}content(e,t,n){let{session_id:r}=t;return this._client.get(z`/agents/sessions/${r}/artifacts/${e}/content`,{...n,headers:P([{"OpenAI-Beta":`agents=v1`,Accept:`application/octet-stream`},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},fl=class extends R{create(e,t,n){let{"Idempotency-Key":r,...i}=t;return this._client.post(z`/agents/sessions/${e}/events`,{body:i,...n,headers:P([{"OpenAI-Beta":`agents=v1`,Accept:`*/*`,...r==null?void 0:{"Idempotency-Key":r}},n?.headers]),__security:{bearerAuth:!0}})}stream(e,t){return this._client.get(z`/agents/sessions/${e}/events`,{...t,headers:P([{"OpenAI-Beta":`agents=v1`,Accept:`text/event-stream`},t?.headers]),stream:!0,__security:{bearerAuth:!0}})}},pl=class extends R{list(e,t={},n){return this._client.getAPIList(z`/agents/sessions/${e}/items`,M,{query:t,...n,headers:P([{"OpenAI-Beta":`agents=v1`},n?.headers]),__security:{bearerAuth:!0}})}},ml=class extends R{retrieve(e,t,n){let{session_id:r}=t;return this._client.get(z`/agents/sessions/${r}/turns/${e}`,{...n,headers:P([{"OpenAI-Beta":`agents=v1`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(z`/agents/sessions/${e}/turns`,M,{query:t,...n,headers:P([{"OpenAI-Beta":`agents=v1`},n?.headers]),__security:{bearerAuth:!0}})}},hl=class extends R{list(e,t,n){let{session_id:r,...i}=t;return this._client.getAPIList(z`/agents/sessions/${r}/subagents/${e}/items`,M,{query:i,...n,headers:P([{"OpenAI-Beta":`agents=v1`},n?.headers]),__security:{bearerAuth:!0}})}},gl=class extends R{list(e,t,n){let{session_id:r,subagent_id:i,...a}=t;return this._client.getAPIList(z`/agents/sessions/${r}/subagents/${i}/turns/${e}/items`,M,{query:a,...n,headers:P([{"OpenAI-Beta":`agents=v1`},n?.headers]),__security:{bearerAuth:!0}})}},_l=class extends R{constructor(){super(...arguments),this.items=new gl(this._client)}retrieve(e,t,n){let{session_id:r,subagent_id:i}=t;return this._client.get(z`/agents/sessions/${r}/subagents/${i}/turns/${e}`,{...n,headers:P([{"OpenAI-Beta":`agents=v1`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t,n){let{session_id:r,...i}=t;return this._client.getAPIList(z`/agents/sessions/${r}/subagents/${e}/turns`,M,{query:i,...n,headers:P([{"OpenAI-Beta":`agents=v1`},n?.headers]),__security:{bearerAuth:!0}})}};_l.Items=gl;var vl=class extends R{constructor(){super(...arguments),this.items=new hl(this._client),this.turns=new _l(this._client)}retrieve(e,t,n){let{session_id:r}=t;return this._client.get(z`/agents/sessions/${r}/subagents/${e}`,{...n,headers:P([{"OpenAI-Beta":`agents=v1`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(z`/agents/sessions/${e}/subagents`,M,{query:t,...n,headers:P([{"OpenAI-Beta":`agents=v1`},n?.headers]),__security:{bearerAuth:!0}})}};vl.Items=hl,vl.Turns=_l;var yl=class extends R{constructor(){super(...arguments),this.subagents=new vl(this._client),this.artifacts=new dl(this._client),this.items=new pl(this._client),this.events=new fl(this._client),this.turns=new ml(this._client)}stream(e,t,n){return new ul(this,e,t,n)}create(e,t){return this._client.post(`/agents/sessions`,{body:e,...t,headers:P([{"OpenAI-Beta":`agents=v1`},t?.headers]),stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(z`/agents/sessions/${e}`,{...t,headers:P([{"OpenAI-Beta":`agents=v1`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t={},n){return this._client.post(z`/agents/sessions/${e}`,{body:t,...n,headers:P([{"OpenAI-Beta":`agents=v1`},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/agents/sessions`,M,{query:e,...t,headers:P([{"OpenAI-Beta":`agents=v1`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(z`/agents/sessions/${e}`,{...t,headers:P([{"OpenAI-Beta":`agents=v1`},t?.headers]),__security:{bearerAuth:!0}})}};yl.Subagents=vl,yl.Artifacts=dl,yl.Items=pl,yl.Events=fl,yl.Turns=ml;var bl=class extends R{create(e,t,n){return this._client.post(z`/vaults/${e}/credentials`,{body:t,...n,headers:P([{"OpenAI-Beta":`agents=v1`},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{vault_id:r}=t;return this._client.get(z`/vaults/${r}/credentials/${e}`,{...n,headers:P([{"OpenAI-Beta":`agents=v1`},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{vault_id:r,...i}=t;return this._client.post(z`/vaults/${r}/credentials/${e}`,{body:i,...n,headers:P([{"OpenAI-Beta":`agents=v1`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(z`/vaults/${e}/credentials`,M,{query:t,...n,headers:P([{"OpenAI-Beta":`agents=v1`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{vault_id:r}=t;return this._client.delete(z`/vaults/${r}/credentials/${e}`,{...n,headers:P([{"OpenAI-Beta":`agents=v1`},n?.headers]),__security:{bearerAuth:!0}})}},xl=class extends R{constructor(){super(...arguments),this.credentials=new bl(this._client)}create(e={},t){return this._client.post(`/vaults`,{body:e,...t,headers:P([{"OpenAI-Beta":`agents=v1`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(z`/vaults/${e}`,{...t,headers:P([{"OpenAI-Beta":`agents=v1`},t?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/vaults`,M,{query:e,...t,headers:P([{"OpenAI-Beta":`agents=v1`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(z`/vaults/${e}`,{...t,headers:P([{"OpenAI-Beta":`agents=v1`},t?.headers]),__security:{bearerAuth:!0}})}};xl.Credentials=bl;var Sl=class extends R{constructor(){super(...arguments),this.environments=new Rc(this._client),this.vaults=new xl(this._client),this.sessions=new yl(this._client)}create(e,t){return this._client.post(`/agents`,{body:e,...t,headers:P([{"OpenAI-Beta":`agents=v1`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(z`/agents/${e}`,{...t,headers:P([{"OpenAI-Beta":`agents=v1`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t={},n){return this._client.post(z`/agents/${e}`,{body:t,...n,headers:P([{"OpenAI-Beta":`agents=v1`},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/agents`,M,{query:e,...t,headers:P([{"OpenAI-Beta":`agents=v1`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(z`/agents/${e}`,{...t,headers:P([{"OpenAI-Beta":`agents=v1`},t?.headers]),__security:{bearerAuth:!0}})}};Sl.Environments=Rc,Sl.Vaults=xl,Sl.Sessions=yl;var Cl=class extends R{create(e,t){return this._client.post(`/chatkit/sessions`,{body:e,...t,headers:P([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(z`/chatkit/sessions/${e}/cancel`,{...t,headers:P([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}},wl=class extends R{retrieve(e,t){return this._client.get(z`/chatkit/threads/${e}`,{...t,headers:P([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/chatkit/threads`,N,{query:e,...t,headers:P([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(z`/chatkit/threads/${e}`,{...t,headers:P([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}listItems(e,t={},n){return this._client.getAPIList(z`/chatkit/threads/${e}/items`,N,{query:t,...n,headers:P([{"OpenAI-Beta":`chatkit_beta=v1`},n?.headers]),__security:{bearerAuth:!0}})}},Tl=class extends R{constructor(){super(...arguments),this.sessions=new Cl(this._client),this.threads=new wl(this._client)}};Tl.Sessions=Cl,Tl.Threads=wl;var El=class extends R{list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(z`/responses/${e}/input_items?beta=true`,M,{query:i,...n,headers:P([{...r?.toString()==null?void 0:{"openai-beta":r?.toString()}},n?.headers]),__security:{bearerAuth:!0}})}},Dl=class extends R{count(e={},t){let{betas:n,...r}=e??{};return this._client.post(`/responses/input_tokens?beta=true`,{body:r,...t,headers:P([{...n?.toString()==null?void 0:{"openai-beta":n?.toString()}},t?.headers]),__security:{bearerAuth:!0}})}},Ol=class extends R{constructor(){super(...arguments),this.inputItems=new El(this._client),this.inputTokens=new Dl(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/responses?beta=true`,{body:r,...t,headers:P([{...n?.toString()==null?void 0:{"openai-beta":n?.toString()}},t?.headers]),stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,t={},n){let{betas:r,...i}=t??{};return this._client.get(z`/responses/${e}?beta=true`,{query:i,...n,headers:P([{...r?.toString()==null?void 0:{"openai-beta":r?.toString()}},n?.headers]),stream:t?.stream??!1,__security:{bearerAuth:!0}})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(z`/responses/${e}?beta=true`,{...n,headers:P([{Accept:`*/*`,...r?.toString()==null?void 0:{"openai-beta":r?.toString()}},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,t={},n){let{betas:r}=t??{};return this._client.post(z`/responses/${e}/cancel?beta=true`,{...n,headers:P([{...r?.toString()==null?void 0:{"openai-beta":r?.toString()}},n?.headers]),__security:{bearerAuth:!0}})}compact(e,t){let{betas:n,...r}=e;return this._client.post(`/responses/compact?beta=true`,{body:r,...t,headers:P([{...n?.toString()==null?void 0:{"openai-beta":n?.toString()}},t?.headers]),__security:{bearerAuth:!0}})}};Ol.InputItems=El,Ol.InputTokens=Dl;var kl=class extends R{create(e,t,n){return this._client.post(z`/threads/${e}/messages`,{body:t,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{thread_id:r}=t;return this._client.get(z`/threads/${r}/messages/${e}`,{...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(z`/threads/${r}/messages/${e}`,{body:i,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(z`/threads/${e}/messages`,M,{query:t,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{thread_id:r}=t;return this._client.delete(z`/threads/${r}/messages/${e}`,{...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}},Al=class extends R{retrieve(e,t,n){let{thread_id:r,run_id:i,...a}=t;return this._client.get(z`/threads/${r}/runs/${i}/steps/${e}`,{query:a,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t,n){let{thread_id:r,...i}=t;return this._client.getAPIList(z`/threads/${r}/runs/${e}/steps`,M,{query:i,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}},jl=e=>{if(globalThis.Buffer!==void 0){let t=globalThis.Buffer.from(e,`base64`);return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}if(typeof atob<`u`){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}throw new c("Cannot decode base64 string; Expected `Buffer` or `atob` to be defined")},Ml=e=>{if(typeof Buffer<`u`){let t=Buffer.from(e,`base64`);if(t.length%Float32Array.BYTES_PER_ELEMENT!==0)throw RangeError(`Invalid base64-encoded float32 array: byte length must be a multiple of 4`);return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}{let t=atob(e),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.charCodeAt(e);return Array.from(new Float32Array(r.buffer))}},Nl=e=>{try{if(globalThis.process!==void 0)return{}[e]?.trim()||void 0;if(globalThis.Deno!==void 0)return globalThis.Deno.env?.get?.(e)?.trim()||void 0}catch{return}},Pl=1024,Fl=65536;function Il(e){switch(e){case`value`:case`arguments`:case`input`:case`text`:case`content`:case`annotations`:case`metadata`:case`name`:case`role`:case`status`:case`tool_calls`:case`step_details`:return e;default:return`unknown`}}var Ll=new WeakMap,Rl=new WeakSet;function zl(e){return{arrays:new Map,cacheArrays:e,records:new WeakMap}}function Bl(e){for(let[t,n]of e.arrays)n.cacheable&&!Rl.has(t)?Ll.set(t,{length:n.length,ownEntryCount:n.ownEntryCount}):Ll.delete(t)}function Vl(e){return typeof e==`string`||typeof e==`number`}function Hl(e,t){return t.every(Vl)&&e.every(Vl)}function Ul(e){let t=0;for(let n of Object.keys(e)){let r=Number(n);Number.isSafeInteger(r)&&r>=0&&r<e.length&&String(r)===n&&(t+=1)}return t}function Wl(e,t,n){return t?n?.length===e.length?n.ownEntryCount:Ul(e):0}function Gl(e,t,n){let{index:r}=e;if(t===`array`&&r==null)throw Error("Expected array delta entry to have an `index` property");if(t===`array`&&typeof r!=`number`)throw TypeError("Expected array delta entry `index` property to be a number but got an invalid value");if(!Number.isSafeInteger(r)||r<0||r>=n+Pl||r>=Fl)throw new c(`Assistant stream delta contains an invalid ${t} index: ${typeof r==`number`?r:`unknown`}`);return r}function Kl(e,t,n,r,i){let a=r.arrays.get(e);if(!a){let t=r.cacheArrays&&!Rl.has(e),n=t?Ll.get(e):void 0;a={baselineLength:e.length,cacheable:t,enforceSparseHoleBudget:t,entries:new Map,length:e.length,ownEntryCount:Wl(e,t,n)},r.arrays.set(e,a)}for(let o of t){if(!oe(o))throw Error(`Expected array delta entry to be an object but got an invalid value`);let t=Gl(o,n,a.baselineLength),s;a.entries.has(t)?s=a.entries.get(t):E(e,t)?(s=e[t],s??a.entries.set(t,o)):(a.entries.set(t,o),a.ownEntryCount+=1);let l=Math.max(a.length,t+1);if(a.enforceSparseHoleBudget&&l-a.ownEntryCount>Pl)throw new c(`Assistant stream delta contains an invalid ${n} index: ${t}`);oe(s)&&i(s,o,r),a.length=l}}function ql(e,t,n){let r=n.records.get(e);for(let[i,a]of Object.entries(t)){if(i===`index`||i===`type`)continue;let t;if(r?.has(i)?t=r.get(i):E(e,i)&&(t=e[i]),t==null){r||(r=new Map,n.records.set(e,r)),r.set(i,a);continue}oe(t)&&oe(a)?ql(t,a,n):Array.isArray(t)&&Array.isArray(a)&&!Hl(t,a)&&Kl(t,a,`array`,n,ql)}}function Jl(e){return(oe(e)||Array.isArray(e))&&Rl.has(e)}function Yl(e){if(!(!oe(e)&&!Array.isArray(e)||Rl.has(e))){Rl.add(e),Array.isArray(e)&&Ll.delete(e);for(let t of Reflect.ownKeys(e)){let n=Object.getOwnPropertyDescriptor(e,t);n&&`value`in n&&Yl(n.value)}}}function Xl(e,t,n){Rl.has(e)&&Yl(n),Object.defineProperty(e,t,{configurable:!0,enumerable:!0,value:n,writable:!0})}function Zl(e){let{index:t}=e;if(t==null)throw Error("Expected array delta entry to have an `index` property");if(typeof t!=`number`)throw TypeError("Expected array delta entry `index` property to be a number but got an invalid value");return t}function Ql(e,t,n){if(Hl(e,t)){e.push(...t),Ll.delete(e);return}for(let r of t){if(!oe(r))throw Error(`Expected array delta entry to be an object but got an invalid value`);let t=Zl(r);if(E(e,t)){let i=e[t];i==null?(Rl.has(e)&&Yl(r),e[t]=r):e[t]=n(i,r)}else Xl(e,t,r)}}function $l(e,t){let n=Rl.has(e);for(let[r,i]of Object.entries(t)){if(r===`__proto__`||r===`constructor`||r===`prototype`)throw new c(`Assistant stream delta contains an unsafe property: ${r}`);if(!E(e,r)){n&&Yl(i),e[r]=i;continue}let t=e[r];if(t==null){n&&Yl(i),e[r]=i;continue}if(r===`index`||r===`type`){e[r]=i;continue}if(typeof t==`string`&&typeof i==`string`)t+=i;else if(typeof t==`number`&&typeof i==`number`)t+=i;else if(oe(t)&&oe(i))t=$l(t,i);else if(Array.isArray(t)&&Array.isArray(i)){Ql(t,i,$l);continue}else throw TypeError(`Unhandled record type: ${Il(r)}`);e[r]=t}return e}function eu(e){if(!(!oe(e)&&!Array.isArray(e)))for(let[t,n]of Object.entries(e)){if(t===`__proto__`||t===`constructor`||t===`prototype`)throw new c(`Assistant stream delta contains an unsafe property: ${t}`);eu(n)}}function tu(e,t,n=!1){eu(t);let r=e,i=t,a=zl(n&&!Jl(e));return ql(r,i,a),$l(r,i),Bl(a),e}function nu(e,t,n,r=!0){eu(t);let i=zl(r&&!Jl(e));return Kl(e,t,n,i,ql),()=>Bl(i)}var q,J,ru,iu,au,ou,Y,su,cu,lu,uu,du,fu,pu,mu,hu,gu,_u,vu,yu,bu,xu,Su,Cu,X,wu,Tu,Eu,Du,Ou;function ku(e){let t=Object.getOwnPropertyDescriptor(e,`event`),n=Object.getOwnPropertyDescriptor(e,`data`),r=Reflect.get(e,`event`,e),i=Reflect.get(e,`data`,e),a=i;if(r===`thread.message.created`||r===`thread.message.in_progress`||r===`thread.message.delta`||r===`thread.message.completed`||r===`thread.message.incomplete`||r===`thread.run.step.created`||r===`thread.run.step.in_progress`||r===`thread.run.step.delta`||r===`thread.run.step.completed`||r===`thread.run.step.failed`||r===`thread.run.step.cancelled`||r===`thread.run.step.expired`){let e=Object.getOwnPropertyDescriptor(i,`id`);if(e&&`value`in e&&i.id!==e.value){let t=e.value;a=new Proxy(i,{get(e,n){return n===`id`?t:Reflect.get(e,n,e)}})}}return{event:Object.freeze({event:r,data:a}),exposedEvent:t!==void 0&&`value`in t&&t.value===r&&n!==void 0&&`value`in n&&n.value===i&&a===i?e:{event:r,data:a}}}var Au=class e extends xo{constructor(){super(...arguments),q.add(this),J.set(this,Object.create(null)),ru.set(this,new Map),iu.set(this,void 0),au.set(this,Object.create(null)),ou.set(this,new Map),Y.set(this,void 0),su.set(this,void 0),cu.set(this,void 0),lu.set(this,void 0),uu.set(this,void 0),du.set(this,void 0),fu.set(this,void 0),pu.set(this,void 0),mu.set(this,void 0),hu.set(this,void 0)}[(J=new WeakMap,ru=new WeakMap,iu=new WeakMap,au=new WeakMap,ou=new WeakMap,Y=new WeakMap,su=new WeakMap,cu=new WeakMap,lu=new WeakMap,uu=new WeakMap,du=new WeakMap,fu=new WeakMap,pu=new WeakMap,mu=new WeakMap,hu=new WeakMap,q=new WeakSet,Symbol.asyncIterator)](){return this._createIterator(e=>{let t=t=>e(structuredClone(t));return this.on(`event`,t),()=>this.off(`event`,t)},{onReturn:()=>this.abort()})}static fromReadableStream(t){let n=new e;return n._run(()=>n._fromReadableStream(t)),n}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),this._connected();let n=et.fromReadableStream(e,this.controller);for await(let e of n)i(this,q,`m`,gu).call(this,e);if(n.controller.signal?.aborted)throw this._userAbortError();return this._addRun(i(this,q,`m`,_u).call(this))}toReadableStream(){return new et(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(t,n,r,i){let a=new e;return a._run(()=>a._runToolAssistantStream(t,n,r,{...i,__metadata:{...i?.__metadata,helperMethod:`stream`}})),a}async _createToolAssistantStream(e,t,n,r){this._listenForAbort(r?.signal);let a={...n,stream:!0},o=await e.submitToolOutputs(t,a,{...r,signal:this.controller.signal});this._connected();for await(let e of o)i(this,q,`m`,gu).call(this,e);if(o.controller.signal?.aborted)throw this._userAbortError();return this._addRun(i(this,q,`m`,_u).call(this))}static createThreadAssistantStream(t,n,r){let i=new e;return i._run(()=>i._threadAssistantStream(t,n,{...r,__metadata:{...r?.__metadata,helperMethod:`stream`}})),i}static createAssistantStream(t,n,r,i){let a=new e;return a._run(()=>a._runAssistantStream(t,n,r,{...i,__metadata:{...i?.__metadata,helperMethod:`stream`}})),a}currentEvent(){return Yl(i(this,pu,`f`)),i(this,pu,`f`)}currentRun(){return Yl(i(this,mu,`f`)),i(this,mu,`f`)}currentMessageSnapshot(){return Yl(i(this,Y,`f`)),i(this,Y,`f`)}currentRunStepSnapshot(){return Yl(i(this,hu,`f`)),i(this,hu,`f`)}async finalRunSteps(){return await this.done(),Object.values(i(this,J,`f`))}async finalMessages(){return await this.done(),Object.values(i(this,au,`f`))}async finalRun(){if(await this.done(),!i(this,cu,`f`))throw Error(`Final run was not received.`);return i(this,cu,`f`)}async _createThreadAssistantStream(e,t,n){this._listenForAbort(n?.signal);let r={...t,stream:!0},a=await e.createAndRun(r,{...n,signal:this.controller.signal});this._connected();for await(let e of a)i(this,q,`m`,gu).call(this,e);if(a.controller.signal?.aborted)throw this._userAbortError();return this._addRun(i(this,q,`m`,_u).call(this))}async _createAssistantStream(e,t,n,r){this._listenForAbort(r?.signal);let a={...n,stream:!0},o=await e.create(t,a,{...r,signal:this.controller.signal});this._connected();for await(let e of o)i(this,q,`m`,gu).call(this,e);if(o.controller.signal?.aborted)throw this._userAbortError();return this._addRun(i(this,q,`m`,_u).call(this))}static accumulateDelta(e,t){return tu(e,t)}_addRun(e){return i(this,q,`m`,X).call(this,`run`,e),e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,r){return await this._createAssistantStream(t,e,n,r)}async _runToolAssistantStream(e,t,n,r){return await this._createToolAssistantStream(t,e,n,r)}};gu=function(e){if(this.ended)return;let{event:t,exposedEvent:n}=ku(e),a,o,s,u;switch(t.event){case`thread.message.created`:case`thread.message.in_progress`:case`thread.message.delta`:case`thread.message.completed`:case`thread.message.incomplete`:a=i(this,q,`m`,bu).call(this,t),o=t.data;break;case`thread.run.step.created`:case`thread.run.step.in_progress`:case`thread.run.step.delta`:case`thread.run.step.completed`:case`thread.run.step.failed`:case`thread.run.step.cancelled`:case`thread.run.step.expired`:s=i(this,q,`m`,vu).call(this,t),u=t.data}switch(r(this,pu,n,`f`),i(this,q,`m`,wu).call(this,n),a!==void 0&&o!==void 0&&i(this,q,`m`,xu).call(this,o,a),s!==void 0&&u!==void 0&&i(this,q,`m`,yu).call(this,u,s),s===void 0&&i(this,iu,`f`)!==void 0&&i(this,hu,`f`)&&i(this,q,`m`,yu).call(this,i(this,hu,`f`),i(this,iu,`f`)),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,q,`m`,Ou).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`:{if(s===void 0)throw new c(`Received assistant run-step event without a canonical run-step ID`);let e=i(this,J,`f`)[s];e&&i(this,q,`m`,yu).call(this,e,s),i(this,q,`m`,Cu).call(this,t,s),i(this,q,`m`,yu).call(this,t.data,s);let n=i(this,J,`f`)[s];n&&i(this,q,`m`,yu).call(this,n,s);break}case`thread.message.created`:case`thread.message.in_progress`:case`thread.message.delta`:case`thread.message.completed`:case`thread.message.incomplete`:if(a!==void 0&&i(this,Y,`f`)&&i(this,q,`m`,xu).call(this,i(this,Y,`f`),a),i(this,q,`m`,Su).call(this,t),a!==void 0){i(this,q,`m`,xu).call(this,t.data,a);let e=i(this,au,`f`)[a];e&&i(this,q,`m`,xu).call(this,e,a)}break;case`error`:throw new l(void 0,t.data,void 0,void 0)}},_u=function(){if(this.ended)throw new c(`stream has ended, this shouldn't happen`);if(!i(this,cu,`f`))throw Error(`Final run has not been received`);return i(this,cu,`f`)},vu=function(e){let t=Object.getOwnPropertyDescriptor(e.data,`id`),n=t&&`value`in t?t.value:void 0;if(typeof n!=`string`||n.length===0)throw new c(`Received assistant run-step event with an invalid run-step ID`);if(e.event===`thread.run.step.delta`){let t=e.data.delta;if(t&&E(t,`id`))throw new c(`Run-step deltas must not contain an id field`)}if(e.event===`thread.run.step.created`){if(i(this,iu,`f`)!==void 0)throw new c(`Received run-step creation for "${n}" before the active run step "${i(this,iu,`f`)}" reached a terminal state`);if(E(i(this,J,`f`),n)||i(this,ru,`f`).has(n))throw new c(`Received run-step creation for run step "${n}", which has already been created`);return r(this,iu,n,`f`),i(this,ru,`f`).set(n,n),n}if(i(this,iu,`f`)!==void 0){if(n!==i(this,iu,`f`))throw new c(`Received ${e.event} for run step "${n}", which does not match the active run step "${i(this,iu,`f`)}"`);return n}if(e.event===`thread.run.step.delta`)throw E(i(this,J,`f`),n)?new c(`Received run-step delta for "${n}" with no active run step`):new c(`Received a RunStepDelta before creation of a snapshot`);if(E(i(this,J,`f`),n)||i(this,ru,`f`).has(n))throw new c(`Received run-step event for run step "${n}", which has already been created`);return i(this,ru,`f`).set(n,n),e.event===`thread.run.step.in_progress`&&r(this,iu,n,`f`),n},yu=function(e,t){let n=Object.getOwnPropertyDescriptor(e,`id`),r=n&&`value`in n?n.value:void 0;if(typeof r!=`string`||r.length===0)throw new c(`Received assistant run-step event with an invalid run-step ID`);let a=i(this,ru,`f`).get(r);if(a!==void 0&&a!==t)throw new c(`Received run-step creation for run step "${r}", which has already been created`);i(this,ru,`f`).set(r,t)},bu=function(e){let t=Object.getOwnPropertyDescriptor(e.data,`id`),n=t&&`value`in t?t.value:void 0;if(typeof n!=`string`||n.length===0)throw new c(`Received assistant message event with an invalid message ID`);if(e.event===`thread.message.created`){if(i(this,Y,`f`))throw new c(`Received message creation for "${n}" before the active message "${i(this,su,`f`)}" reached a terminal state`);if(E(i(this,au,`f`),n)||i(this,ou,`f`).has(n))throw new c(`Received message creation for message "${n}", which has already been created`);return r(this,su,n,`f`),i(this,ou,`f`).set(n,n),n}if(!i(this,Y,`f`))throw e.event===`thread.message.delta`?new c(`Received a delta with no existing snapshot (there should be one from message creation)`):new c(`Received thread message event with no existing snapshot`);if(n!==i(this,su,`f`))throw new c(`Received ${e.event} for message "${n}", which does not match the active message "${i(this,su,`f`)}"`);return n},xu=function(e,t){let n=Object.getOwnPropertyDescriptor(e,`id`),r=n&&`value`in n?n.value:void 0;if(typeof r!=`string`||r.length===0)throw new c(`Received assistant message event with an invalid message ID`);let a=i(this,ou,`f`).get(r);if(a!==void 0&&a!==t)throw new c(`Received message creation for message "${r}", which has already been created`);i(this,ou,`f`).set(r,t)},Su=function(e){let[t,n]=i(this,q,`m`,Eu).call(this,e,i(this,Y,`f`));if(r(this,Y,t,`f`),!i(this,su,`f`))throw new c(`Received thread message event with no active message ID`);i(this,au,`f`)[i(this,su,`f`)]=t;for(let e of n){let n=t.content[e.index];n?.type===`text`&&i(this,q,`m`,X).call(this,`textCreated`,n.text)}switch(e.event){case`thread.message.created`:r(this,lu,void 0,`f`),r(this,uu,void 0,`f`),i(this,q,`m`,X).call(this,`messageCreated`,e.data);break;case`thread.message.in_progress`:break;case`thread.message.delta`:if(i(this,q,`m`,X).call(this,`messageDelta`,e.data.delta,t),e.data.delta.content)for(let n of e.data.delta.content){if(n.type===`text`&&n.text){let e=n.text,r=t.content[n.index];if(r&&r.type===`text`)i(this,q,`m`,X).call(this,`textDelta`,e,r.text);else throw Error(`The snapshot associated with this text delta is not text or missing`)}if(n.index!==i(this,lu,`f`)){if(i(this,uu,`f`))switch(i(this,uu,`f`).type){case`text`:i(this,q,`m`,X).call(this,`textDone`,i(this,uu,`f`).text,i(this,Y,`f`));break;case`image_file`:i(this,q,`m`,X).call(this,`imageFileDone`,i(this,uu,`f`).image_file,i(this,Y,`f`))}r(this,lu,n.index,`f`)}r(this,uu,t.content[n.index],`f`)}break;case`thread.message.completed`:case`thread.message.incomplete`:if(i(this,lu,`f`)!==void 0){let t=e.data.content[i(this,lu,`f`)];if(t)switch(t.type){case`image_file`:i(this,q,`m`,X).call(this,`imageFileDone`,t.image_file,i(this,Y,`f`));break;case`text`:i(this,q,`m`,X).call(this,`textDone`,t.text,i(this,Y,`f`))}}i(this,Y,`f`)&&i(this,q,`m`,X).call(this,`messageDone`,e.data),r(this,lu,void 0,`f`),r(this,uu,void 0,`f`),r(this,Y,void 0,`f`),r(this,su,void 0,`f`)}},Cu=function(e,t){let n=i(this,q,`m`,Tu).call(this,e,t);switch(r(this,hu,n,`f`),e.event){case`thread.run.step.created`:r(this,du,void 0,`f`),r(this,fu,void 0,`f`),i(this,q,`m`,X).call(this,`runStepCreated`,e.data);break;case`thread.run.step.delta`:{let t=e.data.delta;if(t.step_details&&t.step_details.type===`tool_calls`&&t.step_details.tool_calls&&n.step_details.type===`tool_calls`)for(let e of t.step_details.tool_calls)e.index===i(this,du,`f`)?i(this,q,`m`,X).call(this,`toolCallDelta`,e,n.step_details.tool_calls[e.index]):(i(this,fu,`f`)&&i(this,q,`m`,X).call(this,`toolCallDone`,i(this,fu,`f`)),r(this,du,e.index,`f`),r(this,fu,n.step_details.tool_calls[e.index],`f`),i(this,fu,`f`)&&i(this,q,`m`,X).call(this,`toolCallCreated`,i(this,fu,`f`)));i(this,q,`m`,X).call(this,`runStepDelta`,e.data.delta,n);break}case`thread.run.step.completed`:case`thread.run.step.failed`:case`thread.run.step.cancelled`:case`thread.run.step.expired`:r(this,hu,void 0,`f`),r(this,iu,void 0,`f`),e.data.step_details.type===`tool_calls`&&i(this,fu,`f`)&&i(this,q,`m`,X).call(this,`toolCallDone`,i(this,fu,`f`)),i(this,q,`m`,X).call(this,`runStepDone`,e.data,n),r(this,du,void 0,`f`),r(this,fu,void 0,`f`)}},X=function(e,...t){if(this._hasListeners(e))for(let e of t)Yl(e);this._emit(e,...t)},wu=function(e){i(this,q,`m`,X).call(this,`event`,e)},Tu=function(e,t){switch(e.event){case`thread.run.step.created`:return i(this,J,`f`)[t]=e.data,e.data;case`thread.run.step.delta`:{let n=i(this,J,`f`)[t];if(!n)throw Error(`Received a RunStepDelta before creation of a snapshot`);let r=e.data.delta;if(r){if(E(r,`id`))throw new c(`Run-step deltas must not contain an id field`);let e=tu(n,r,!0);i(this,J,`f`)[t]=e}return i(this,J,`f`)[t]}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,J,`f`)[t]=e.data}if(i(this,J,`f`)[t])return i(this,J,`f`)[t];throw Error(`No snapshot available`)},Eu=function(e,t){let n=[];switch(e.event){case`thread.message.created`:return[e.data,n];case`thread.message.delta`:{if(!t)throw Error(`Received a delta with no existing snapshot (there should be one from message creation)`);let r=e.data;if(r.delta.content){eu(r.delta);let e=!Jl(t),a=nu(t.content,r.delta.content,`content`,e);for(let a of r.delta.content)if(E(t.content,a.index)){let n=t.content[a.index];t.content[a.index]=i(this,q,`m`,Du).call(this,a,n,e)}else Xl(t.content,a.index,a),n.push(a);a()}return[t,n]}case`thread.message.in_progress`:case`thread.message.completed`:case`thread.message.incomplete`:if(t)return[e.event===`thread.message.in_progress`?t:e.data,n];throw Error(`Received thread message event with no existing snapshot`)}throw Error(`Tried to accumulate a non-message event`)},Du=function(e,t,n){return tu(t,e,n)},Ou=function(e){switch(r(this,mu,e.data,`f`),e.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`:r(this,cu,e.data,`f`),i(this,fu,`f`)&&i(this,q,`m`,X).call(this,`toolCallDone`,i(this,fu,`f`)),r(this,du,void 0,`f`),r(this,fu,void 0,`f`)}};function ju(e,t){return new Promise((n,r)=>{let i,a,o=!1,s=e=>{try{t.removeEventListener(`abort`,e)}catch{}},c=()=>{if(i!==void 0&&(clearTimeout(i),i=void 0),a){let e=a;a=void 0,s(e)}},l=()=>{if(!o){o=!0,c();try{let e=new u;Object.defineProperty(e,"cause",{value:t.reason,writable:!0,configurable:!0}),r(e)}catch(e){r(e)}}};if(t.aborted){l();return}i=setTimeout(()=>{o||(o=!0,c(),n())},e),a=l;try{t.addEventListener(`abort`,l,{once:!0}),o?s(l):t.aborted&&l()}catch(e){o?s(l):(o=!0,c(),r(e))}})}async function Mu(e,t,n,r){let i=P([r?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:a,response:o}=await e(i).withResponse(),{status:s}=a;if(t.includes(s)){let e=5e3,t=r?.pollIntervalMs;if(t||t===0)e=t;else{let t=o.headers.get(`openai-poll-after-ms`);if(t){let n=Number.parseInt(t);Number.isNaN(n)||(e=n)}}let n=r&&Object.prototype.propertyIsEnumerable.call(r,`signal`)?r.signal:void 0;await(n?ju(e,n):le(e))}else if(n.includes(s))return a}}function Nu(e,t,n,r){return Mu(i=>e.retrieve(t,n,{...r,headers:{...r?.headers,...i}}),[`queued`,`in_progress`,`cancelling`],[`requires_action`,`incomplete`,`cancelled`,`completed`,`failed`,`expired`],r)}var Pu=class extends R{constructor(){super(...arguments),this.steps=new Al(this._client)}create(e,t,n){let{include:r,...i}=t;return this._client.post(z`/threads/${e}/runs`,{query:{include:r},body:i,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{thread_id:r}=t;return this._client.get(z`/threads/${r}/runs/${e}`,{...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(z`/threads/${r}/runs/${e}`,{body:i,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(z`/threads/${e}/runs`,M,{query:t,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,n){let{thread_id:r}=t;return this._client.post(z`/threads/${r}/runs/${e}/cancel`,{...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,n){let r=await this.create(e,t,n);return await this.poll(r.id,{thread_id:e},n)}createAndStream(e,t,n){return Au.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){return await Nu(this,e,t,n)}stream(e,t,n){return Au.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n){let{thread_id:r,...i}=t;return this._client.post(z`/threads/${r}/runs/${e}/submit_tool_outputs`,{body:i,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async submitToolOutputsAndPoll(e,t,n){let r=await this.submitToolOutputs(e,t,n);return await this.poll(r.id,t,n)}submitToolOutputsStream(e,t,n){return Au.createToolAssistantStream(e,this._client.beta.threads.runs,t,n)}};Pu.Steps=Al;var Fu=class extends R{constructor(){super(...arguments),this.runs=new Pu(this._client),this.messages=new kl(this._client)}create(e={},t){return this._client.post(`/threads`,{body:e,...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(z`/threads/${e}`,{...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(z`/threads/${e}`,{body:t,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(z`/threads/${e}`,{...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,t){return this._client.post(`/threads/runs`,{body:e,...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async createAndRunPoll(e,t){let n=await this.createAndRun(e,t);return await this.runs.poll(n.id,{thread_id:n.thread_id},t)}createAndRunStream(e,t){return Au.createThreadAssistantStream(e,this._client.beta.threads,t)}};Fu.Runs=Pu,Fu.Messages=kl;var Iu=class extends R{constructor(){super(...arguments),this.realtime=new Fc(this._client),this.agents=new Sl(this._client),this.responses=new Ol(this._client),this.chatkit=new Tl(this._client),this.assistants=new Mc(this._client),this.threads=new Fu(this._client)}};Iu.Realtime=Fc,Iu.Agents=Sl,Iu.Responses=Ol,Iu.ChatKit=Tl,Iu.Assistants=Mc,Iu.Threads=Fu;var Lu=class extends R{create(e,t){return this._client.post(`/completions`,{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}},Ru=class extends R{retrieve(e,t,n){let{container_id:r}=t;return this._client.get(z`/containers/${r}/files/${e}/content`,{...n,headers:P([{Accept:`application/binary`},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},zu=class extends R{constructor(){super(...arguments),this.content=new Ru(this._client)}create(e,t,n){return this._client.post(z`/containers/${e}/files`,Hr({body:t,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,n){let{container_id:r}=t;return this._client.get(z`/containers/${r}/files/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(z`/containers/${e}/files`,M,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{container_id:r}=t;return this._client.delete(z`/containers/${r}/files/${e}`,{...n,headers:P([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}};zu.Content=Ru;var Bu=class extends R{constructor(){super(...arguments),this.files=new zu(this._client)}create(e,t){return this._client.post(`/containers`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(z`/containers/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/containers`,M,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(z`/containers/${e}`,{...t,headers:P([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}};Bu.Files=zu;var Vu=class extends R{create(e,t){return this._client.post(`/content_provenance_checks`,Ur({body:e,...t,__security:{bearerAuth:!0}},this._client))}},Hu=class extends R{create(e,t,n){let{include:r,...i}=t;return this._client.post(z`/conversations/${e}/items`,{query:{include:r},body:i,...n,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{conversation_id:r,...i}=t;return this._client.get(z`/conversations/${r}/items/${e}`,{query:i,...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(z`/conversations/${e}/items`,N,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{conversation_id:r}=t;return this._client.delete(z`/conversations/${r}/items/${e}`,{...n,__security:{bearerAuth:!0}})}},Uu=class extends R{constructor(){super(...arguments),this.items=new Hu(this._client)}create(e={},t){return this._client.post(`/conversations`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(z`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(z`/conversations/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(z`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}};Uu.Items=Hu;function Wu(e,t,n){let r=!!t.encoding_format,i=r?t.encoding_format:`base64`;r&&A(e).debug(`embeddings/user defined encoding_format:`,t.encoding_format);let a={body:{...t,encoding_format:i},...n,__security:{bearerAuth:!0}},o=e.post(`/embeddings`,a);return r?o:(A(e).debug(`embeddings/decoding base64 embeddings from base64`),o._thenUnwrap(e=>{let t=e?.data;if(t!==void 0){if(!Array.isArray(t))throw TypeError(`Expected embeddings response data to be an array`);let{length:e}=t;for(let n=0;n<e;n+=1)if(n in t){let e=t[n],{embedding:r}=e;if(Array.isArray(r))continue;e.embedding=Ml(r)}}return e}))}var Gu=class extends R{create(e,t){return Wu(this._client,e,t)}},Ku=class extends R{retrieve(e,t,n){let{eval_id:r,run_id:i}=t;return this._client.get(z`/evals/${r}/runs/${i}/output_items/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t,n){let{eval_id:r,...i}=t;return this._client.getAPIList(z`/evals/${r}/runs/${e}/output_items`,M,{query:i,...n,__security:{bearerAuth:!0}})}},qu=class extends R{constructor(){super(...arguments),this.outputItems=new Ku(this._client)}create(e,t,n){return this._client.post(z`/evals/${e}/runs`,{body:t,...n,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{eval_id:r}=t;return this._client.get(z`/evals/${r}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(z`/evals/${e}/runs`,M,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{eval_id:r}=t;return this._client.delete(z`/evals/${r}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}cancel(e,t,n){let{eval_id:r}=t;return this._client.post(z`/evals/${r}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}};qu.OutputItems=Ku;var Ju=class extends R{constructor(){super(...arguments),this.runs=new qu(this._client)}create(e,t){return this._client.post(`/evals`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(z`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(z`/evals/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/evals`,M,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(z`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}};Ju.Runs=qu;async function Yu(e,t,n,r){let i=new Set([`processed`,`error`,`deleted`]),a=performance.now(),o=await e.retrieve(t);for(;!o.status||!i.has(o.status);)if(await le(n),o=await e.retrieve(t),performance.now()-a>r)throw new f({message:`Giving up on waiting for file ${t} to finish processing after ${r} milliseconds.`});return o}var Xu=class extends R{create(e,t){return this._client.post(`/files`,Ur({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(z`/files/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/files`,M,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(z`/files/${e}`,{...t,__security:{bearerAuth:!0}})}content(e,t){return this._client.get(z`/files/${e}/content`,{...t,headers:P([{Accept:`application/binary`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:n=18e5}={}){return await Yu(this,e,t,n)}},Zu=class extends R{},Qu=class extends R{run(e,t){return this._client.post(`/fine_tuning/alpha/graders/run`,{body:e,...t,__security:{bearerAuth:!0}})}validate(e,t){return this._client.post(`/fine_tuning/alpha/graders/validate`,{body:e,...t,__security:{bearerAuth:!0}})}},$u=class extends R{constructor(){super(...arguments),this.graders=new Qu(this._client)}};$u.Graders=Qu;var ed=class extends R{create(e,t,n){return this._client.getAPIList(z`/fine_tuning/checkpoints/${e}/permissions`,Yt,{body:t,method:`post`,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},n){return this._client.get(z`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(z`/fine_tuning/checkpoints/${e}/permissions`,N,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{fine_tuned_model_checkpoint:r}=t;return this._client.delete(z`/fine_tuning/checkpoints/${r}/permissions/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},td=class extends R{constructor(){super(...arguments),this.permissions=new ed(this._client)}};td.Permissions=ed;var nd=class extends R{list(e,t={},n){return this._client.getAPIList(z`/fine_tuning/jobs/${e}/checkpoints`,M,{query:t,...n,__security:{bearerAuth:!0}})}},rd=class extends R{constructor(){super(...arguments),this.checkpoints=new nd(this._client)}create(e,t){return this._client.post(`/fine_tuning/jobs`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(z`/fine_tuning/jobs/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/fine_tuning/jobs`,M,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(z`/fine_tuning/jobs/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}listEvents(e,t={},n){return this._client.getAPIList(z`/fine_tuning/jobs/${e}/events`,M,{query:t,...n,__security:{bearerAuth:!0}})}pause(e,t){return this._client.post(z`/fine_tuning/jobs/${e}/pause`,{...t,__security:{bearerAuth:!0}})}resume(e,t){return this._client.post(z`/fine_tuning/jobs/${e}/resume`,{...t,__security:{bearerAuth:!0}})}};rd.Checkpoints=nd;var id=class extends R{constructor(){super(...arguments),this.methods=new Zu(this._client),this.jobs=new rd(this._client),this.checkpoints=new td(this._client),this.alpha=new $u(this._client)}};id.Methods=Zu,id.Jobs=rd,id.Checkpoints=td,id.Alpha=$u;var ad=class extends R{},od=class extends R{constructor(){super(...arguments),this.graderModels=new ad(this._client)}};od.GraderModels=ad;var sd=class extends R{createVariation(e,t){return this._client.post(`/images/variations`,Ur({body:e,...t,__security:{bearerAuth:!0}},this._client))}edit(e,t){return this._client.post(`/images/edits`,Ur({body:e,...t,stream:e.stream??!1,__metadata:{...t?.__metadata,...e.model==null?{}:{model:e.model}},__security:{bearerAuth:!0}},this._client))}generate(e,t){return this._client.post(`/images/generations`,{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}},cd=class extends R{accept(e,t,n){return this._client.post(z`/live/sessions/${e}/accept`,{body:t,...n,headers:P([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}downloadRecording(e,t){return this._client.get(z`/live/sessions/${e}/content`,{...t,headers:P([{Accept:`application/binary`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}fork(e,t,n){return this._client.post(z`/live/sessions/${e}/fork`,{body:t,...n,__security:{bearerAuth:!0}})}hangup(e,t){return this._client.post(z`/live/sessions/${e}/hangup`,{...t,headers:P([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}refer(e,t,n){return this._client.post(z`/live/sessions/${e}/refer`,{body:t,...n,headers:P([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}reject(e,t,n){return this._client.post(z`/live/sessions/${e}/reject`,{body:t,...n,headers:P([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}},ld=class extends R{},ud=class extends R{},dd=class extends R{constructor(){super(...arguments),this.sideband=new ud(this._client),this.forks=new ld(this._client),this.sessions=new cd(this._client)}create(e,t){return this._client.post(`/live/sessions`,{body:e,...t,__security:{bearerAuth:!0}})}};dd.Sideband=ud,dd.Forks=ld,dd.Sessions=cd;var fd=class extends R{retrieve(e,t){return this._client.get(z`/models/${e}`,{...t,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList(`/models`,Yt,{...e,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(z`/models/${e}`,{...t,__security:{bearerAuth:!0}})}},pd=class extends R{create(e,t){return this._client.post(`/moderations`,{body:e,...t,__security:{bearerAuth:!0}})}};async function md(e,t,n,r=null){if(e.body===null||typeof e.body!=`object`||Array.isArray(e.body))throw TypeError(`Multipart request body must be an object`);let i=Object.fromEntries(Object.entries(e.body).filter(([,e])=>e!==void 0));if(r!==null&&Object.keys(i).length===1&&Object.prototype.hasOwnProperty.call(i,r)){let t=i[r];if(typeof t!=`string`)throw TypeError(`Raw multipart alternative must be a string`);return{...e,body:t,headers:P([e.headers,{"content-type":n[r].content_type}])}}let a=[];for(let[e,t]of Object.entries(n)){if(!Object.prototype.hasOwnProperty.call(i,e))continue;let n=i[e],r=t.json?JSON.stringify(n):n;if(typeof r!=`string`)throw TypeError(`Multipart field ${e} must encode as a string`);a.push([e,Fr([r],``,{type:t.content_type})]),delete i[e]}let o=(await Ur({...e,body:i},t)).body;if(!(o instanceof FormData))throw await o.cancel(),TypeError(`Unexpected streaming upload in typed multipart request body`);for(let[e,t]of a)o.append(e,t,``);return{...e,body:o,headers:P([e.headers,{"content-type":null}])}}var hd=class extends R{create(e,t){return this._client.post(`/realtime/calls`,md({body:e,...t,headers:P([{Accept:`application/sdp`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0},this._client,{sdp:{content_type:`application/sdp`,json:!1},session:{content_type:`application/json`,json:!0}},`sdp`))}accept(e,t,n){return this._client.post(z`/realtime/calls/${e}/accept`,{body:t,...n,headers:P([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}hangup(e,t){return this._client.post(z`/realtime/calls/${e}/hangup`,{...t,headers:P([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}refer(e,t,n){return this._client.post(z`/realtime/calls/${e}/refer`,{body:t,...n,headers:P([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}reject(e,t={},n){return this._client.post(z`/realtime/calls/${e}/reject`,{body:t,...n,headers:P([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}},gd=class extends R{create(e,t){return this._client.post(`/realtime/client_secrets`,{body:e,...t,__security:{bearerAuth:!0}})}},_d=class extends R{constructor(){super(...arguments),this.clientSecrets=new gd(this._client),this.calls=new hd(this._client)}};_d.ClientSecrets=gd,_d.Calls=hd;function vd(e,t){if(!t||!xd(t)){let t={...e,output_parsed:null,output:e.output.map(e=>e.type===`function_call`?{...e,parsed_arguments:null}:e.type===`message`?{...e,content:e.content.map(e=>({...e,parsed:null}))}:e)};return Td(e,t)&&Ed(t),t}return yd(e,t)}function yd(e,t){let n=!e.status||e.status===`completed`,r=e.output.map(e=>{if(e.type===`function_call`)return n?wd(t,e):{...e,parsed_arguments:null};if(e.type===`message`){let r=e.content.map(e=>e.type===`output_text`?{...e,parsed:n?bd(t,e.text):null}:e);return{...e,content:r}}return e}),i={...e,output:r};return Td(e,i)&&Ed(i),Object.defineProperty(i,"output_parsed",{enumerable:!0,get(){for(let e of i.output)if(e.type===`message`){for(let t of e.content)if(t.type===`output_text`&&t.parsed!==null)return t.parsed}return null}}),i}function bd(e,t){return Ti(e.text?.format,t)}function xd(e){return wi(e.text?.format)?!0:Array.isArray(e.tools)&&e.tools.some(e=>Sd(e)||e.type===`function`&&e.strict===!0||e.type===`namespace`&&e.tools.some(e=>e.type===`function`&&(Sd(e)||e.strict===!0)))}function Sd(e){return e?.$brand===`auto-parseable-tool`}function Cd(e,t,n){for(let r of e)if(n==null){if(r.type===`function`&&r.name===t)return r}else if(r.type===`namespace`&&r.name===n)return r.tools.find(e=>e.type===`function`&&e.name===t)}function wd(e,t){let n=Cd(e.tools??[],t.name,t.namespace),r=null;return Sd(n)?r=n.$parseRaw(t.arguments):n?.strict&&(r=Ti({type:`json_schema`,$parseRaw:void 0},t.arguments)),{...t,parsed_arguments:r}}function Td(e,t){return!Object.getOwnPropertyDescriptor(e,`output_text`)||t.output_text==null}function Ed(e){let t=[];for(let n of e.output)if(n.type===`message`)for(let e of n.content)e.type===`output_text`&&t.push(e.text);e.output_text=t.join(``)}var Dd=class{constructor(){this.capacity=1,this.values=[0,0],this.size=0}get length(){return this.size}append(e){this.size===this.capacity&&this.grow();let t=this.size;this.size+=1,this.update(t,e)}update(e,t){if(!Number.isSafeInteger(e)||e<0||e>=this.size)throw RangeError(`missing output at index ${e}`);let n=this.capacity+e,r=t-(this.values[n]??0);if(r!==0)for(;n>=1;)this.values[n]=(this.values[n]??0)+r,n=Math.floor(n/2)}prefixSum(e){if(!Number.isSafeInteger(e)||e<0||e>this.size)throw RangeError(`missing output at index ${e}`);let t=this.capacity,n=this.capacity+e,r=0;for(;t<n;)t%2==1&&(r+=this.values[t]??0,t+=1),n%2==1&&(--n,r+=this.values[n]??0),t=Math.floor(t/2),n=Math.floor(n/2);return r}grow(){let e=this.capacity;this.capacity*=2;let t=Array.from({length:this.capacity*2},()=>0);for(let n=0;n<this.size;n+=1)t[this.capacity+n]=this.values[e+n]??0;for(let e=this.capacity-1;e>0;--e)t[e]=(t[e*2]??0)+(t[e*2+1]??0);this.values=t}};function Od(){return{canonicalSnapshot:void 0,outputTextLengths:new WeakMap,outputTextIndex:new Dd}}function kd(e,t){if(t.type!==`message`)return``;let n=``;for(let e of t.content)e.type===`output_text`&&(n+=e.text);return e.outputTextLengths.set(t,n.length),n}function Ad(e,t){if(e.canonicalSnapshot===t)return;let n=new Dd,r=``;for(let i of t.output){let t=kd(e,i);r+=t,n.append(t.length)}t.output_text=r,e.outputTextIndex=n,e.canonicalSnapshot=t}function jd(e,t){e.canonicalSnapshot=void 0,e.outputTextLengths=new WeakMap,e.outputTextIndex=new Dd;let n=structuredClone(t);return!Object.getOwnPropertyDescriptor(n,`output_text`)||n.output_text===null||n.output_text===void 0?Ad(e,n):n.output.length===0&&n.output_text===``&&(e.canonicalSnapshot=n),n}function Md(e,t,n,r,i){let a=e.outputTextLengths.get(t);if(a!==void 0){let o=a-r.length+i.length;e.outputTextLengths.set(t,o),e.outputTextIndex.update(n,o)}}function Nd(e,t,n){if(t.length===0){e.output_text+=n;return}e.output_text=e.output_text.slice(0,e.output_text.length-t.length)+n}function Pd(e,t,n,r){if(n===void 0||t?.type!==`message`)return 0;if(n<t.content.length-n-1){let e=0;for(let r=0;r<n;r+=1){let n=t.content[r];n?.type===`output_text`&&(e+=n.text.length)}return e}let i=0;for(let e=n+1;e<t.content.length;e+=1){let n=t.content[e];n?.type===`output_text`&&(i+=n.text.length)}return(e.outputTextLengths.get(t)??kd(e,t).length)-i-r.length}function Fd(e,t,n,r,i,a){if(r===i)return;let o=t.output[n];if(n===t.output.length-1&&(a===void 0||o?.type===`message`&&a===o.content.length-1)){Nd(t,r,i);return}let s=Pd(e,o,a,i),c=e.outputTextIndex.prefixSum(n)+s;if(c+r.length===t.output_text.length){Nd(t,r,i);return}t.output_text=t.output_text.slice(0,c)+i+t.output_text.slice(c+r.length)}var Id=new WeakMap;function Ld(e,t,n,r=!1){if(!Array.isArray(e)||!Number.isSafeInteger(t)||t<0||t>e.length||(t===e.length?!r||t in e:!E(e,t)))throw new c(`missing ${n} at index ${t}`)}function Rd(e,t,n){if(t!==e.length)throw new c(`missing ${n} at index ${t}`);Ld(e,t,n,!0)}function Z(e,t){Ld(e.output,t,`output`);let n=e.output[t];if(!n)throw new c(`missing output at index ${t}`);return n}function zd(e){return e.type===`function_call`||e.type===`custom_tool_call`||e.type===`shell_call`||e.type===`shell_call_output`}function Bd(e,t){if(!E(e,`type`)||typeof e.type!=`string`)throw new c(`expected an own output item type for ${t}`);let n=e.type===`function_call`||e.type===`custom_tool_call`,r=[];if(E(e,`id`)){if(typeof e.id!=`string`||e.id.length===0)throw new c(`expected a non-empty output item id for ${t}`);r.push(`id:${e.id}`)}else if(!n)throw new c(`expected a non-empty output item id for ${t}`);if(zd(e)){if(!E(e,`call_id`)||typeof e.call_id!=`string`||e.call_id.length===0)throw new c(`expected a non-empty output item call_id for ${t}`);r.push(`call:${e.type}:${e.call_id}`)}return r}function Vd(e,t){for(let n of t)if(e.has(n))throw new c(`duplicate output item identity '${n}'`)}function Hd(e,t){Vd(e,t);for(let n of t)e.add(n)}function Ud(e){let t={snapshot:e,output:e.output,length:e.output.length,identities:new Set};for(let n=0;n<e.output.length;n+=1){let r=Z(e,n);Hd(t.identities,Bd(r,`response snapshot`))}return t}function Wd(e,t){let n=Id.get(e);if(n&&n.snapshot===t&&n.output===t.output&&n.length===t.output.length)return n;let r=Ud(t);return Id.set(e,r),r}function Gd(e,t){let n=Od(),r=jd(n,t),i=Ud(r);return e.canonicalSnapshot=n.canonicalSnapshot,e.outputTextLengths=n.outputTextLengths,e.outputTextIndex=n.outputTextIndex,Id.set(e,i),r}var Kd={"response.output_text.delta":`message`,"response.output_text.done":`message`,"response.output_text.annotation.added":`message`,"response.refusal.delta":`message`,"response.refusal.done":`message`,"response.function_call_arguments.delta":`function_call`,"response.function_call_arguments.done":`function_call`,"response.custom_tool_call_input.delta":`custom_tool_call`,"response.custom_tool_call_input.done":`custom_tool_call`,"response.mcp_call_arguments.delta":`mcp_call`,"response.mcp_call_arguments.done":`mcp_call`,"response.mcp_call.in_progress":`mcp_call`,"response.mcp_call.completed":`mcp_call`,"response.mcp_call.failed":`mcp_call`,"response.shell_call_output_content.delta":`shell_call_output`,"response.shell_call_output_content.done":`shell_call_output`,"response.reasoning_text.delta":`reasoning`,"response.reasoning_text.done":`reasoning`,"response.reasoning_summary_part.added":`reasoning`,"response.reasoning_summary_part.done":`reasoning`,"response.reasoning_summary_text.delta":`reasoning`,"response.reasoning_summary_text.done":`reasoning`,"response.code_interpreter_call_code.delta":`code_interpreter_call`,"response.code_interpreter_call_code.done":`code_interpreter_call`,"response.code_interpreter_call.in_progress":`code_interpreter_call`,"response.code_interpreter_call.interpreting":`code_interpreter_call`,"response.code_interpreter_call.completed":`code_interpreter_call`,"response.file_search_call.in_progress":`file_search_call`,"response.file_search_call.searching":`file_search_call`,"response.file_search_call.completed":`file_search_call`,"response.web_search_call.in_progress":`web_search_call`,"response.web_search_call.searching":`web_search_call`,"response.web_search_call.completed":`web_search_call`,"response.image_generation_call.in_progress":`image_generation_call`,"response.image_generation_call.generating":`image_generation_call`,"response.image_generation_call.completed":`image_generation_call`,"response.image_generation_call.partial_image":`image_generation_call`,"response.mcp_list_tools.in_progress":`mcp_list_tools`,"response.mcp_list_tools.completed":`mcp_list_tools`,"response.mcp_list_tools.failed":`mcp_list_tools`,"response.compaction.compacting":`compaction`};function qd(e){return e.type===`response.content_part.added`||e.type===`response.content_part.done`?e.part.type===`reasoning_text`?`reasoning`:`message`:Kd[e.type]}function Jd(e,t){let n=Z(t,e.output_index),r=e.item;if(Bd(n,e.type),Bd(r,e.type),!E(r,`type`)||n.type!==r.type)throw new c(`expected output item type '${n.type}', got '${r.type}'`);let i=E(n,`id`)?n.id:void 0,a=E(r,`id`)?r.id:void 0;if(i!==a)throw new c(`expected output item id '${i}', got '${a}'`);if(zd(n)&&zd(r)&&n.call_id!==r.call_id)throw new c(`expected output item call_id '${n.call_id}', got '${r.call_id}'`)}function Yd(e,t,n){if(e.type===`response.output_item.done`){Jd(e,t);return}if(n&&(e.type===`response.shell_call_command.added`||e.type===`response.shell_call_command.delta`||e.type===`response.shell_call_command.done`)){let n=Z(t,e.output_index);if(!E(n,`type`)||n.type!==`shell_call`)throw new c(`expected output item type 'shell_call', got '${n.type}'`);return}if(e.type!==`response.content_part.added`&&e.type!==`response.content_part.done`&&!E(Kd,e.type))return;let r=e;if(!E(e,`item_id`)||typeof r.item_id!=`string`||r.item_id.length===0)throw new c(`expected a non-empty item_id for ${e.type}`);let i=Z(t,r.output_index),a=E(i,`id`)?i.id:void 0;if(a!==r.item_id)throw new c(`expected item_id '${a}', got '${r.item_id}'`);let o=qd(r);if(i.type!==o)throw new c(`expected output item type '${o}', got '${i.type}'`)}function Xd(e,t){Ld(e,t,`content`);let n=e[t];if(!n)throw new c(`missing content at index ${t}`);return n}function Zd(e,t,n){let r=e.output.find(e=>e.type===`shell_call`&&e.call_id===t.call_id);for(r?Ld(r.action.commands,n,`command`):Ld(t.output,n,`content`,!0);t.output.length<=n;)t.output.push({stdout:``,stderr:``,outcome:{type:`exit`,exit_code:0}});return Xd(t.output,n)}function Qd(e){return new Set(e)}var $d=Qd(`response.output_item.added,response.output_item.done,response.content_part.added,response.content_part.done,response.output_text.delta,response.output_text.done,response.output_text.annotation.added,response.refusal.delta,response.refusal.done,response.function_call_arguments.delta,response.function_call_arguments.done,response.custom_tool_call_input.delta,response.custom_tool_call_input.done,response.mcp_call_arguments.delta,response.mcp_call_arguments.done,response.shell_call_command.added,response.shell_call_command.done,response.shell_call_command.delta,response.shell_call_output_content.delta,response.shell_call_output_content.done,response.reasoning_text.delta,response.reasoning_text.done,response.reasoning_summary_part.added,response.reasoning_summary_part.done,response.reasoning_summary_text.delta,response.reasoning_summary_text.done,response.code_interpreter_call_code.delta,response.code_interpreter_call_code.done,response.code_interpreter_call.in_progress,response.code_interpreter_call.interpreting,response.code_interpreter_call.completed,response.file_search_call.in_progress,response.file_search_call.searching,response.file_search_call.completed,response.web_search_call.in_progress,response.web_search_call.searching,response.web_search_call.completed,response.image_generation_call.in_progress,response.image_generation_call.generating,response.image_generation_call.completed,response.mcp_call.in_progress,response.mcp_call.completed,response.mcp_call.failed,response.created,response.queued,response.in_progress,response.completed,response.failed,response.incomplete,response.audio.delta,response.audio.done,response.audio.transcript.delta,response.audio.transcript.done,response.compaction.compacting,response.image_generation_call.partial_image,response.mcp_list_tools.in_progress,response.mcp_list_tools.completed,response.mcp_list_tools.failed,keepalive,error`.split(`,`));function ef(e){throw new c(`Unhandled response stream event: unknown`)}var tf=[`item_id`,`output_index`,`content_index`,`annotation_index`,`command_index`,`summary_index`];function nf(e){let t;try{t=Object.getOwnPropertyDescriptor(e,`type`)}catch{return ef(e)}let n=t?.value;if(typeof n!=`string`||!$d.has(n))return ef(e);let r=new Map([[`type`,n]]);if(n===`response.output_item.added`||n===`response.output_item.done`||n===`response.content_part.added`||n===`response.content_part.done`||n===`response.shell_call_command.added`||n===`response.shell_call_command.delta`||n===`response.shell_call_command.done`||E(Kd,n))try{for(let t of tf){let n=Object.getOwnPropertyDescriptor(e,t);r.set(t,n?e[t]:void 0)}n===`response.output_item.done`?r.set(`item`,structuredClone(e.item)):(n===`response.content_part.added`||n===`response.content_part.done`)&&r.set(`part`,structuredClone(e.part))}catch{return ef(e)}return new Proxy(e,{get(e,t){return r.has(t)?r.get(t):Reflect.get(e,t,e)}})}function rf(e,t,n){switch(e.type){case`response.output_item.added`:{Rd(t.output,e.output_index,`output`);let r=Wd(n,t),i=structuredClone(e.item),a=Bd(i,e.type);Vd(r.identities,a),i.type===`message`&&Ad(n,t),t.output.push(i),Hd(r.identities,a),r.length=t.output.length;let o=kd(n,i);return n.canonicalSnapshot===t&&n.outputTextIndex.append(o.length),o&&(t.output_text+=o),!0}case`response.output_item.done`:{let r=Z(t,e.output_index),i=kd(n,r),a=e.item;(r.type===`message`||a.type===`message`)&&Ad(n,t),t.output[e.output_index]=a;let o=kd(n,a);return n.canonicalSnapshot===t&&n.outputTextIndex.update(e.output_index,o.length),Fd(n,t,e.output_index,i,o),!0}default:return!1}}function af(e,t,n){switch(e.type){case`response.content_part.added`:{let r=Z(t,e.output_index),{type:i}=r,{part:a}=e;if(i===`message`&&a.type!==`reasoning_text`){Rd(r.content,e.content_index,`content`);let i=a;i.type===`output_text`&&Ad(n,t),r.content.push(i),i.type===`output_text`&&(Md(n,r,e.output_index,``,i.text),Fd(n,t,e.output_index,``,i.text,e.content_index))}else if(i===`reasoning`&&a.type===`reasoning_text`){let t=r.content??[];Rd(t,e.content_index,`content`),r.content||=t,t.push(a)}return!0}default:return!1}}function of(e,t,n){switch(e.type){case`response.content_part.done`:{let r=Z(t,e.output_index),{part:i}=e;if(r.type===`message`&&i.type!==`reasoning_text`){let a=Xd(r.content,e.content_index),o=a.type===`output_text`?a.text:``,s=i;(a.type===`output_text`||s.type===`output_text`)&&Ad(n,t),r.content[e.content_index]=s;let c=s.type===`output_text`?s.text:``;Md(n,r,e.output_index,o,c),Fd(n,t,e.output_index,o,c,e.content_index)}else if(r.type===`reasoning`&&i.type===`reasoning_text`){let{content:t}=r;if(!t)throw new c(`missing content at index ${e.content_index}`);Xd(t,e.content_index),t[e.content_index]=i}return!0}default:return!1}}function sf(e,t,n){switch(e.type){case`response.output_text.delta`:{let r=Z(t,e.output_index);if(r.type===`message`){let i=Xd(r.content,e.content_index);if(i.type!==`output_text`)throw new c(`expected content to be 'output_text', got ${i.type}`);let a=i.text;Ad(n,t),i.text=a+e.delta,Md(n,r,e.output_index,a,i.text),e.output_index===t.output.length-1&&e.content_index===r.content.length-1?t.output_text+=e.delta:Fd(n,t,e.output_index,a,i.text,e.content_index)}return!0}case`response.output_text.done`:{let r=Z(t,e.output_index);if(r.type===`message`){let i=Xd(r.content,e.content_index);if(i.type!==`output_text`)throw new c(`expected content to be 'output_text', got ${i.type}`);let a=i.text;Ad(n,t),i.text=e.text,Md(n,r,e.output_index,a,e.text),Fd(n,t,e.output_index,a,e.text,e.content_index)}return!0}case`response.output_text.annotation.added`:{let n=Z(t,e.output_index);if(n.type===`message`){let t=Xd(n.content,e.content_index);if(t.type!==`output_text`)throw new c(`expected content to be 'output_text', got ${t.type}`);Ld(t.annotations,e.annotation_index,`annotation`,!0),t.annotations[e.annotation_index]=structuredClone(e.annotation)}return!0}default:return!1}}function cf(e,t){switch(e.type){case`response.refusal.delta`:{let n=Z(t,e.output_index);if(n.type===`message`){let t=Xd(n.content,e.content_index);if(t.type!==`refusal`)throw new c(`expected content to be 'refusal', got ${t.type}`);t.refusal+=e.delta}return!0}case`response.refusal.done`:{let n=Z(t,e.output_index);if(n.type===`message`){let t=Xd(n.content,e.content_index);if(t.type!==`refusal`)throw new c(`expected content to be 'refusal', got ${t.type}`);t.refusal=e.refusal}return!0}case`response.function_call_arguments.delta`:{let n=Z(t,e.output_index);return n.type===`function_call`&&(n.arguments+=e.delta),!0}case`response.function_call_arguments.done`:{let n=Z(t,e.output_index);return n.type===`function_call`&&(n.arguments=e.arguments),!0}case`response.custom_tool_call_input.delta`:{let n=Z(t,e.output_index);return n.type===`custom_tool_call`&&(n.input+=e.delta),!0}case`response.custom_tool_call_input.done`:{let n=Z(t,e.output_index);return n.type===`custom_tool_call`&&(n.input=e.input),!0}case`response.mcp_call_arguments.delta`:{let n=Z(t,e.output_index);return n.type===`mcp_call`&&(n.arguments+=e.delta),!0}case`response.mcp_call_arguments.done`:{let n=Z(t,e.output_index);return n.type===`mcp_call`&&(n.arguments=e.arguments),!0}default:return!1}}function lf(e,t){switch(e.type){case`response.shell_call_command.added`:case`response.shell_call_command.done`:{let n=Z(t,e.output_index);if(n.type===`shell_call`){let t=e.type===`response.shell_call_command.added`;Ld(n.action.commands,e.command_index,`command`,t),n.action.commands[e.command_index]=e.command}return!0}case`response.shell_call_command.delta`:{let n=Z(t,e.output_index);return n.type===`shell_call`&&(Ld(n.action.commands,e.command_index,`command`),n.action.commands[e.command_index]+=e.delta),!0}case`response.shell_call_output_content.delta`:{let n=Z(t,e.output_index);if(n.type===`shell_call_output`){let r=Zd(t,n,e.command_index);r.stdout+=e.delta.stdout??``,r.stderr+=e.delta.stderr??``}return!0}case`response.shell_call_output_content.done`:{let n=Z(t,e.output_index);if(n.type===`shell_call_output`){let r=Xd(e.output,0);Zd(t,n,e.command_index),n.output[e.command_index]=structuredClone(r)}return!0}default:return!1}}function uf(e,t){switch(e.type){case`response.reasoning_text.delta`:{let n=Z(t,e.output_index);if(n.type===`reasoning`){if(!n.content)throw new c(`missing content at index ${e.content_index}`);let t=Xd(n.content,e.content_index);if(t.type!==`reasoning_text`)throw new c(`expected content to be 'reasoning_text', got ${t.type}`);t.text+=e.delta}return!0}case`response.reasoning_text.done`:{let n=Z(t,e.output_index);if(n.type===`reasoning`){if(!n.content)throw new c(`missing content at index ${e.content_index}`);let t=Xd(n.content,e.content_index);if(t.type!==`reasoning_text`)throw new c(`expected content to be 'reasoning_text', got ${t.type}`);t.text=e.text}return!0}case`response.reasoning_summary_part.added`:{let n=Z(t,e.output_index);return n.type===`reasoning`&&(Rd(n.summary,e.summary_index,`content`),n.summary.push(structuredClone(e.part))),!0}case`response.reasoning_summary_part.done`:{let n=Z(t,e.output_index);return n.type===`reasoning`&&(Xd(n.summary,e.summary_index),n.summary[e.summary_index]=structuredClone(e.part)),!0}case`response.reasoning_summary_text.delta`:{let n=Z(t,e.output_index);if(n.type===`reasoning`){let t=Xd(n.summary,e.summary_index);t.text+=e.delta}return!0}case`response.reasoning_summary_text.done`:{let n=Z(t,e.output_index);if(n.type===`reasoning`){let t=Xd(n.summary,e.summary_index);t.text=e.text}return!0}default:return!1}}function df(e,t){switch(e.type){case`response.code_interpreter_call_code.delta`:{let n=Z(t,e.output_index);return n.type===`code_interpreter_call`&&(n.code=(n.code??``)+e.delta),!0}case`response.code_interpreter_call_code.done`:{let n=Z(t,e.output_index);return n.type===`code_interpreter_call`&&(n.code=e.code),!0}case`response.code_interpreter_call.in_progress`:{let n=Z(t,e.output_index);return n.type===`code_interpreter_call`&&(n.status=`in_progress`),!0}case`response.code_interpreter_call.interpreting`:{let n=Z(t,e.output_index);return n.type===`code_interpreter_call`&&(n.status=`interpreting`),!0}case`response.code_interpreter_call.completed`:{let n=Z(t,e.output_index);return n.type===`code_interpreter_call`&&(n.status=`completed`),!0}default:return!1}}function ff(e,t){switch(e.type){case`response.file_search_call.in_progress`:{let n=Z(t,e.output_index);return n.type===`file_search_call`&&(n.status=`in_progress`),!0}case`response.file_search_call.searching`:{let n=Z(t,e.output_index);return n.type===`file_search_call`&&(n.status=`searching`),!0}case`response.file_search_call.completed`:{let n=Z(t,e.output_index);return n.type===`file_search_call`&&(n.status=`completed`),!0}case`response.web_search_call.in_progress`:{let n=Z(t,e.output_index);return n.type===`web_search_call`&&(n.status=`in_progress`),!0}case`response.web_search_call.searching`:{let n=Z(t,e.output_index);return n.type===`web_search_call`&&(n.status=`searching`),!0}case`response.web_search_call.completed`:{let n=Z(t,e.output_index);return n.type===`web_search_call`&&(n.status=`completed`),!0}default:return!1}}function pf(e,t){switch(e.type){case`response.image_generation_call.in_progress`:{let n=Z(t,e.output_index);return n.type===`image_generation_call`&&(n.status=`in_progress`),!0}case`response.image_generation_call.generating`:{let n=Z(t,e.output_index);return n.type===`image_generation_call`&&(n.status=`generating`),!0}case`response.image_generation_call.completed`:{let n=Z(t,e.output_index);return n.type===`image_generation_call`&&(n.status=`completed`),!0}case`response.mcp_call.in_progress`:{let n=Z(t,e.output_index);return n.type===`mcp_call`&&(n.status=`in_progress`),!0}case`response.mcp_call.completed`:{let n=Z(t,e.output_index);return n.type===`mcp_call`&&(n.status=`completed`),!0}case`response.mcp_call.failed`:{let n=Z(t,e.output_index);return n.type===`mcp_call`&&(n.status=`failed`),!0}default:return!1}}function mf(e){switch(e.type){case`response.created`:case`response.queued`:case`response.in_progress`:case`response.completed`:case`response.failed`:case`response.incomplete`:return!0;default:return!1}}function hf(e){switch(e.type){case`response.audio.delta`:case`response.audio.done`:case`response.audio.transcript.delta`:case`response.audio.transcript.done`:case`response.compaction.compacting`:case`response.image_generation_call.partial_image`:case`response.mcp_list_tools.in_progress`:case`response.mcp_list_tools.completed`:case`response.mcp_list_tools.failed`:case`keepalive`:case`error`:return!0;default:return!1}}function gf(){return Od()}function _f(e,t,n,r=!1,i){let a=nf(e);if(i&&a.type!==`keepalive`&&i(a),!t){if(a.type!==`response.created`)throw new c(`When snapshot hasn't been set yet, expected 'response.created' event, got ${a.type}`);return Gd(n,a.response)}return Yd(a,t,r),rf(a,t,n)||af(a,t,n)||of(a,t,n)||sf(a,t,n)||cf(a,t)||lf(a,t)||uf(a,t)||df(a,t)||ff(a,t)||pf(a,t)?t:mf(a)?Gd(n,a.response):hf(a)?t:ef(a)}var vf,yf,bf,xf,Sf,Cf,wf,Tf,Ef=class e extends xo{constructor(e){super(),vf.add(this),yf.set(this,void 0),bf.set(this,void 0),xf.set(this,void 0),Sf.set(this,gf()),r(this,yf,e,`f`)}static createResponse(t,n,r){let i=new e(n);return i._run(()=>i._createOrRetrieveResponse(t,n,{...r,__metadata:{...r?.__metadata,helperMethod:`stream`}})),i}static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}async _createOrRetrieveResponse(e,t,n){this._listenForAbort(n?.signal),i(this,vf,`m`,Cf).call(this);let r,a=null;`response_id`in t?(r=await e.responses.retrieve(t.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),a=t.starting_after??null):r=await e.responses.create({...t,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(let e of r)i(this,vf,`m`,wf).call(this,e,a);if(r.controller.signal?.aborted)throw this._userAbortError();return i(this,vf,`m`,Tf).call(this)}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),i(this,vf,`m`,Cf).call(this),this._connected();let n=et.fromReadableStream(e,this.controller);for await(let e of n)i(this,vf,`m`,wf).call(this,e,null);if(n.controller.signal?.aborted)throw this._userAbortError();return i(this,vf,`m`,Tf).call(this)}[(yf=new WeakMap,bf=new WeakMap,xf=new WeakMap,Sf=new WeakMap,vf=new WeakSet,Cf=function(){this.ended||(r(this,bf,void 0,`f`),r(this,Sf,gf(),`f`))},wf=function(e,t){if(this.ended)return;let n=(e,n)=>{(t==null||n.sequence_number>t)&&this._emit(e,n)};if(e.type===`error`)throw new l(void 0,`error`in e&&typeof e.error==`object`&&e.error!==null?e.error:e,e.message,void 0);let a=e,o=_f(e,i(this,bf,`f`),i(this,Sf,`f`),!0,e=>{a=e});switch(r(this,bf,o,`f`),n(`event`,e),a.type){case`response.output_text.delta`:{let e=o.output[a.output_index];if(!e)throw new c(`missing output at index ${a.output_index}`);if(e.type===`message`){let t=e.content[a.content_index];if(!t)throw new c(`missing content at index ${a.content_index}`);if(t.type!==`output_text`)throw new c(`expected content to be 'output_text', got ${t.type}`);n(`response.output_text.delta`,{...a,type:a.type,item_id:a.item_id,output_index:a.output_index,content_index:a.content_index,snapshot:t.text})}break}case`response.function_call_arguments.delta`:{let e=o.output[a.output_index];if(!e)throw new c(`missing output at index ${a.output_index}`);e.type===`function_call`&&n(`response.function_call_arguments.delta`,{...a,type:a.type,item_id:a.item_id,output_index:a.output_index,snapshot:e.arguments});break}default:n(a.type,e)}},Tf=function(){if(this.ended)throw new c(`stream has ended, this shouldn't happen`);let e=i(this,bf,`f`);if(!e)throw new c(`request ended without sending any events`);r(this,bf,void 0,`f`),r(this,Sf,gf(),`f`);let t=Df(e,i(this,yf,`f`));return r(this,xf,t,`f`),t},Symbol.asyncIterator)](){return this._createIterator(e=>{let t=t=>e(t);return this.on(`event`,t),()=>this.off(`event`,t)},{onReturn:()=>this.abort()})}async finalResponse(){await this.done();let e=i(this,xf,`f`);if(!e)throw new c(`stream ended without producing a Response`);return e}};function Df(e,t){return vd(e,t)}var Of=class extends R{list(e,t={},n){return this._client.getAPIList(z`/responses/${e}/input_items`,M,{query:t,...n,__security:{bearerAuth:!0}})}},kf=class extends R{count(e={},t){return this._client.post(`/responses/input_tokens`,{body:e,...t,__security:{bearerAuth:!0}})}},Af=class extends R{constructor(){super(...arguments),this.inputItems=new Of(this._client),this.inputTokens=new kf(this._client)}create(e,t){return this._client.post(`/responses`,{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(e=>(`object`in e&&e.object===`response`&&Ed(e),e))}retrieve(e,t={},n){return this._client.get(z`/responses/${e}`,{query:t,...n,stream:t?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(e=>(`object`in e&&e.object===`response`&&Ed(e),e))}delete(e,t){return this._client.delete(z`/responses/${e}`,{...t,headers:P([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(t=>yd(t,e))}stream(e,t){return Ef.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(z`/responses/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}compact(e,t){return this._client.post(`/responses/compact`,{body:e,...t,__security:{bearerAuth:!0}})}};Af.InputItems=Of,Af.InputTokens=kf;var jf=class extends R{retrieve(e,t){return this._client.get(z`/safety/alerts/${e}`,{...t,__security:{bearerAuth:!0}})}},Mf=class extends R{constructor(){super(...arguments),this.alerts=new jf(this._client)}};Mf.Alerts=jf;var Nf=class extends R{retrieve(e,t){return this._client.get(z`/skills/${e}/content`,{...t,headers:P([{Accept:`application/binary`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},Pf=class extends R{retrieve(e,t,n){let{skill_id:r}=t;return this._client.get(z`/skills/${r}/versions/${e}/content`,{...n,headers:P([{Accept:`application/binary`},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},Ff=class extends R{constructor(){super(...arguments),this.content=new Pf(this._client)}create(e,t={},n){return this._client.post(z`/skills/${e}/versions`,Hr({body:t,...n,__security:{bearerAuth:!0}},this._client,{stripFilenames:!1}))}retrieve(e,t,n){let{skill_id:r}=t;return this._client.get(z`/skills/${r}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(z`/skills/${e}/versions`,M,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{skill_id:r}=t;return this._client.delete(z`/skills/${r}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}};Ff.Content=Pf;var If=class extends R{constructor(){super(...arguments),this.content=new Nf(this._client),this.versions=new Ff(this._client)}create(e={},t){return this._client.post(`/skills`,Hr({body:e,...t,__security:{bearerAuth:!0}},this._client,{stripFilenames:!1}))}retrieve(e,t){return this._client.get(z`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(z`/skills/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/skills`,M,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(z`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}};If.Content=Nf,If.Versions=Ff;var Lf=class extends R{create(e,t,n){return this._client.post(z`/uploads/${e}/parts`,Ur({body:t,...n,__security:{bearerAuth:!0}},this._client))}},Rf=class extends R{constructor(){super(...arguments),this.parts=new Lf(this._client)}create(e,t){return this._client.post(`/uploads`,{body:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(z`/uploads/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}complete(e,t,n){return this._client.post(z`/uploads/${e}/complete`,{body:t,...n,__security:{bearerAuth:!0}})}};Rf.Parts=Lf;function zf(e,t,n,r){return Mu(i=>e.retrieve(n,{vector_store_id:t},{...r,headers:i}),[`in_progress`],[`failed`,`cancelled`,`completed`],r)}function Bf(e,t,n,r){return Mu(i=>e.retrieve(n,{vector_store_id:t},{...r,headers:i}),[`in_progress`],[`failed`,`cancelled`,`completed`],r)}var Vf=async e=>{let t=await Promise.allSettled(e),n=t.filter(e=>e.status===`rejected`);if(n.length)throw Object.defineProperty(Error(`${n.length} promise(s) failed`),"rejections",{configurable:!0,value:n.map(({reason:e})=>e),writable:!0});let r=[];for(let e of t)e.status===`fulfilled`&&r.push(e.value);return r};async function Hf(e,t,n,r,i,a){if(r==null||r.length===0)throw Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let o=a?.maxConcurrency??5,s=Math.min(o,r.length);if(s===0)throw RangeError(`maxConcurrency must be greater than 0`);let c=r.values(),l=[...i];async function u(e){for(let n of e){let e=await t.files.create({file:n,purpose:`assistants`},a);l.push(e.id)}}let d=[];d.length=s;for(let e=0;e<d.length;e+=1)d[e]=u(c);return await Vf(d),await e.createAndPoll(n,{file_ids:l},a)}var Uf=class extends R{create(e,t,n){return this._client.post(z`/vector_stores/${e}/file_batches`,{body:t,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(z`/vector_stores/${r}/file_batches/${e}`,{...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,n){let{vector_store_id:r}=t;return this._client.post(z`/vector_stores/${r}/file_batches/${e}/cancel`,{...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,n){let r=await this.create(e,t,n);return await this.poll(e,r.id,n)}listFiles(e,t,n){let{vector_store_id:r,...i}=t;return this._client.getAPIList(z`/vector_stores/${r}/file_batches/${e}/files`,M,{query:i,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async poll(e,t,n){return await Bf(this,e,t,n)}async uploadAndPoll(e,{files:t,fileIds:n=[]},r){return await Hf(this,this._client,e,t,n,r)}},Wf=class extends R{create(e,t,n){return this._client.post(z`/vector_stores/${e}/files`,{body:t,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(z`/vector_stores/${r}/files/${e}`,{...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{vector_store_id:r,...i}=t;return this._client.post(z`/vector_stores/${r}/files/${e}`,{body:i,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(z`/vector_stores/${e}/files`,M,{query:t,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{vector_store_id:r}=t;return this._client.delete(z`/vector_stores/${r}/files/${e}`,{...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,n){let r=await this.create(e,t,n);return await this.poll(e,r.id,n)}async poll(e,t,n){return await zf(this,e,t,n)}async upload(e,t,n){let r=await this._client.files.create({file:t,purpose:`assistants`},n);return this.create(e,{file_id:r.id},n)}async uploadAndPoll(e,t,n){let r=await this.upload(e,t,n);return await this.poll(e,r.id,n)}content(e,t,n){let{vector_store_id:r}=t;return this._client.getAPIList(z`/vector_stores/${r}/files/${e}/content`,Yt,{...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}},Gf=class extends R{constructor(){super(...arguments),this.files=new Wf(this._client),this.fileBatches=new Uf(this._client)}create(e,t){return this._client.post(`/vector_stores`,{body:e,...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(z`/vector_stores/${e}`,{...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(z`/vector_stores/${e}`,{body:t,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/vector_stores`,M,{query:e,...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(z`/vector_stores/${e}`,{...t,headers:P([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}search(e,t,n){return this._client.getAPIList(z`/vector_stores/${e}/search`,Yt,{body:t,method:`post`,...n,headers:P([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}};Gf.Files=Wf,Gf.FileBatches=Uf;var Kf=class extends R{create(e,t){return this._client.post(`/videos`,Ur({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(z`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/videos`,N,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(z`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}createCharacter(e,t){return this._client.post(`/videos/characters`,Ur({body:e,...t,__security:{bearerAuth:!0}},this._client))}downloadContent(e,t={},n){return this._client.get(z`/videos/${e}/content`,{query:t,...n,headers:P([{Accept:`application/binary`},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,t){return this._client.post(`/videos/edits`,Ur({body:e,...t,__security:{bearerAuth:!0}},this._client))}extend(e,t){return this._client.post(`/videos/extensions`,Ur({body:e,...t,__security:{bearerAuth:!0}},this._client))}getCharacter(e,t){return this._client.get(z`/videos/characters/${e}`,{...t,__security:{bearerAuth:!0}})}remix(e,t,n){return this._client.post(z`/videos/${e}/remix`,Hr({body:t,...n,__security:{bearerAuth:!0}},this._client))}},qf=32,Jf=32;function Yf(e){return e.split(` `,33).length>qf}function*Xf(e){let t=0;for(;t<=e.length;){let n=e.indexOf(` `,t),r=e.slice(t,n===-1?void 0:n);if(yield r.startsWith(`v1,`)?r.slice(3):r,n===-1)break;t=n+1}}function Zf(e){try{let t=jl(e);return t.byteLength===Jf?t:void 0}catch{return}}function Qf(e){for(let t of Xf(e)){let e=Zf(t);if(e)return e}}function $f(e,t,n){let r=n;for(let n of Xf(e)){let e=Zf(n);if(!e)continue;let i=0;for(let[n,r]of e.entries())i|=r^(t[n]??0);i===0&&(r=e)}return r}async function ep(e,t,n,r,i,a){let o=Number.parseInt(n,10);if(Number.isNaN(o))throw new S(`Invalid webhook timestamp format`);let s=Math.floor(Date.now()/1e3);if(s-o>a)throw new S(`Webhook timestamp is too old`);if(o>s+a)throw new S(`Webhook timestamp is too new`);let c=Yf(t),l=c?Qf(t):void 0;if(c&&!l)throw new S(`The given webhook signature does not match the expected signature`);let u=Uint8Array.from(i.startsWith(`whsec_`)?jl(i.slice(6)):we(i)),d=r?`${r}.${n}.${e}`:`${n}.${e}`,f=Uint8Array.from(we(d)),p=await crypto.subtle.importKey(`raw`,u,{name:`HMAC`,hash:`SHA-256`},!1,c?[`sign`,`verify`]:[`verify`]);if(c&&l){let e=$f(t,new Uint8Array(await crypto.subtle.sign(`HMAC`,p,f)),l);try{if(await crypto.subtle.verify(`HMAC`,p,Uint8Array.from(e),f))return}catch{}throw new S(`The given webhook signature does not match the expected signature`)}for(let e of Xf(t))try{let t=Uint8Array.from(jl(e));if(await crypto.subtle.verify(`HMAC`,p,t,f))return}catch{}throw new S(`The given webhook signature does not match the expected signature`)}var tp=class extends R{list(e){return this._client.get(`/webhook_event_types`,{...e,__security:{bearerAuth:!0}})}},np,rp,ip,ap=class extends R{constructor(){super(...arguments),np.add(this),this.eventTypes=new tp(this._client)}create(e,t){return this._client.post(`/webhook_endpoints`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(z`/webhook_endpoints/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t={},n){return this._client.post(z`/webhook_endpoints/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/webhook_endpoints`,M,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(z`/webhook_endpoints/${e}`,{...t,__security:{bearerAuth:!0}})}rotateSecret(e,t={},n){return this._client.post(z`/webhook_endpoints/${e}/rotate_secret`,{body:t,...n,__security:{bearerAuth:!0}})}test(e,t,n){return this._client.post(z`/webhook_endpoints/${e}/test`,{body:t,...n,__security:{bearerAuth:!0}})}async unwrap(e,t,n=this._client.webhookSecret,r=300){return await this.verifySignature(e,t,n,r),JSON.parse(e)}async verifySignature(e,t,n=this._client.webhookSecret,r=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,np,`m`,rp).call(this,n);let a=P([t]).values,o=i(this,np,`m`,ip).call(this,a,`webhook-signature`),s=i(this,np,`m`,ip).call(this,a,`webhook-timestamp`),c=i(this,np,`m`,ip).call(this,a,`webhook-id`);if(Yf(o)&&typeof crypto.subtle.sign!=`function`)throw Error("Webhook signature verification is only supported when the `crypto` global is defined");return await ep(e,o,s,c,n,r)}};np=new WeakSet,rp=function(e){if(typeof e!=`string`||e.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`)},ip=function(e,t){if(!e)throw Error(`Headers are required`);let n=e.get(t);if(n==null)throw Error(`Missing required header: ${t}`);return n},ap.EventTypes=tp;async function op(e){let t,n=await e._callApiKey(e=>{t=e});return{apiKey:t===void 0?e.apiKey:t,isProvider:n}}var sp=Symbol.for(`openai.node.providerDefinitions.v1`),cp=globalThis,lp=cp[sp],up=lp??new WeakMap;lp||Object.defineProperty(cp,sp,{value:up});function dp(e){let t=up.get(e);if(!t)throw Error(`Invalid provider. Providers must be created with createProvider().`);return t.configure()}var fp,pp,mp,Q,hp,gp,_p,vp,yp;function bp(){if(dt())return!0;let e=globalThis;return typeof e.WorkerGlobalScope==`function`&&e instanceof e.WorkerGlobalScope&&typeof e.WorkerNavigator==`function`&&e.navigator instanceof e.WorkerNavigator&&typeof e.navigator?.userAgent==`string`&&e.navigator.userAgent!==`Cloudflare-Workers`&&e.process?.versions?.node===void 0&&e.Deno===void 0&&e.Bun===void 0&&e.EdgeRuntime===void 0&&e.WebSocketPair===void 0}var xp=`workload-identity-auth`,Sp=Symbol(`inheritedDataResidencySelection`),$=class{constructor(e={}){fp.add(this),mp.set(this,void 0),Q.set(this,void 0),hp.set(this,void 0),gp.set(this,void 0),_p.set(this,!1),vp.set(this,new WeakMap),this.completions=new Lu(this),this.chat=new Js(this),this.embeddings=new Gu(this),this.files=new Xu(this),this.images=new sd(this),this.contentProvenanceChecks=new Vu(this),this.audio=new Ac(this),this.moderations=new pd(this),this.models=new fd(this),this.fineTuning=new id(this),this.graders=new od(this),this.vectorStores=new Gf(this),this.safety=new Mf(this),this.webhooks=new ap(this),this.beta=new Iu(this),this.batches=new jc(this),this.uploads=new Rf(this),this.admin=new Ec(this),this.responses=new Af(this),this.live=new dd(this),this.realtime=new _d(this),this.conversations=new Uu(this),this.evals=new Ju(this),this.containers=new Bu(this),this.skills=new If(this),this.videos=new Kf(this);let{credential:t,options:n}=Or(e);e=n;let a=Ht(e),o=e.provider,{baseURL:s=o?null:Nl(`OPENAI_BASE_URL`),dataResidency:l,[Sp]:u=!1,apiKey:d=o?null:Nl(`OPENAI_API_KEY`)??null,adminAPIKey:f=o?null:Nl(`OPENAI_ADMIN_KEY`)??null,organization:p=o?null:Nl(`OPENAI_ORG_ID`)??null,project:m=o?null:Nl(`OPENAI_PROJECT_ID`)??null,webhookSecret:h=Nl(`OPENAI_WEBHOOK_SECRET`)??null,workloadIdentity:g,x509Transport:_,credential:v,...y}=e;if(o){let t=[`apiKey`,`adminAPIKey`,`workloadIdentity`,`x509Transport`,`baseURL`,`dataResidency`].filter(t=>(t===`workloadIdentity`?g:e[t])!=null);if(t.length)throw new c(`The \`provider\` option cannot be used with ${t.map(e=>`\`${e}\``).join(`, `)}. Configure authentication and the base URL through the provider instead.`)}let b=Cr(g)?{x509:g,legacy:void 0}:{x509:void 0,legacy:g},x=b.x509,ee=x!==void 0,S=o?dp(o):void 0,C={apiKey:d,adminAPIKey:f,organization:p,project:m,webhookSecret:h,workloadIdentity:g,x509Transport:_,provider:o,...y,baseURL:S?.baseURL??a??(s||(ee?`https://mtls.api.openai.com/v1`:`https://api.openai.com/v1`))};if(_&&!ee)throw new c(`An X.509 transport requires an X.509 workload identity.`);if(ee){if(a!==void 0||u)throw new c(`X.509 workload identity does not support data residency selection.`);if(e.fetch!==void 0)throw new c(`X.509 workload identity does not support a custom fetch implementation.`);if(fn(C.baseURL),Tr(C.fetchOptions),this.fetchWithAuth!==pp.prototype.fetchWithAuth||this.fetchWithTimeout!==pp.prototype.fetchWithTimeout)throw new c(`X.509 workload identity does not support overridden fetch dispatch hooks.`)}if(d&&g)throw new c("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!S&&!d&&!f&&!g)throw new c("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!C.dangerouslyAllowBrowser&&bp())throw new c(`It looks like you're running in a browser-like environment.
10
+
11
+ This is disabled by default, as it risks exposing your secret API credentials to attackers.
12
+ If you understand the risks and have appropriate mitigations in place,
13
+ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
14
+
15
+ new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
16
+
17
+ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
18
+ `);this.baseURL=C.baseURL,r(this,_p,a!==void 0||u,`f`),this.timeout=C.timeout??pp.DEFAULT_TIMEOUT,this.logger=C.logger??console;let te=`warn`;this.logLevel=te,this.logLevel=Le(C.logLevel,`ClientOptions.logLevel`,this)??Le(Nl(`OPENAI_LOG`),`process.env['OPENAI_LOG']`,this)??te,this.fetchOptions=C.fetchOptions,this.maxRetries=C.maxRetries??2,this.fetch=C.fetch??ve(),r(this,mp,xt,`f`);let w=o||t?void 0:Nl(`OPENAI_CUSTOM_HEADERS`);if(w){let e={};for(let t of w.split(`
19
+ `)){let n=t.indexOf(`:`);n>=0&&(e[t.substring(0,n).trim()]=t.substring(n+1).trim())}C.defaultHeaders=P([e,C.defaultHeaders])}if(this._options=C,this._provider=S,x){let e=new Dr(x,_,p,m);this._workloadIdentityAuth=e,r(this,Q,e,`f`),r(this,hp,t,`f`),r(this,gp,e.fetch(),`f`),this.fetch=i(this,gp,`f`),Hn(this)}else b.legacy&&(this._workloadIdentityAuth=new dn(b.legacy,this.fetch));this.apiKey=typeof d==`string`?d:null,this.adminAPIKey=f,this.organization=p,this.project=m,this.webhookSecret=h}withOptions(e){let t=Ht(e),n=i(this,Q,`f`),a={...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:i(this,Q,`f`)?void 0:this.fetch,fetchOptions:this.fetchOptions,apiKey:this._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:n?.identitySnapshot()??this._options.workloadIdentity,x509Transport:this._options.x509Transport,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret},{credential:o,provider:s}=jr(a,e,i(this,hp,`f`),n!==void 0);t!==void 0&&delete a.baseURL;let c={...a,...e,credential:o,provider:s,[Sp]:i(this,_p,`f`)&&t===void 0&&!E(e,`baseURL`)&&e.credential===void 0&&!s},l=new this.constructor(c);return s&&new URL(l.baseURL).origin!==new URL(this.baseURL).origin&&(Object.assign(l._options,{defaultHeaders:e.defaultHeaders,defaultQuery:e.defaultQuery,fetchOptions:e.fetchOptions,fetch:e.fetch}),l.fetchOptions=e.fetchOptions,l.fetch=e.fetch??ve(),l.organization=e.organization??null,l.project=e.project??null),i(this,Q,`f`)&&i(l,Q,`f`)&&this.baseURL===l.baseURL&&i(this,Q,`f`).matches(i(l,Q,`f`))&&(l._workloadIdentityAuth=i(this,Q,`f`),r(l,Q,i(this,Q,`f`),`f`),r(l,gp,i(this,gp,`f`),`f`)),l}defaultQuery(){return this._options.defaultQuery}_buildWebSocketHeaders(e){return Object.fromEntries(P([{"User-Agent":this.getUserAgent(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},e,this._options.defaultHeaders]).values)}validateHeaders({values:e,nulls:t},n={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get(`authorization`)||e.get(`api-key`))&&!(t.has(`authorization`)||t.has(`api-key`))&&!(this._workloadIdentityAuth&&n.bearerAuth))throw Error(`Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted`)}async authHeaders(e,t={bearerAuth:!0,adminAPIKeyAuth:!0}){return(i(this,Q,`f`)??this._workloadIdentityAuth)instanceof Dr&&t.adminAPIKeyAuth&&this.adminAPIKey!==null?await this.adminAPIKeyAuth(e):P([t.bearerAuth?await this.bearerAuth(e):null,t.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){let t=i(this,Q,`f`)??this._workloadIdentityAuth;if(t){if(t instanceof Dr){if(t===this._workloadIdentityAuth&&(this.fetchWithAuth!==pp.prototype.fetchWithAuth||this.fetchWithTimeout!==pp.prototype.fetchWithTimeout))throw new c(`X.509 workload identity does not support overridden fetch dispatch hooks.`);let n=t.headerSnapshots();if(!Dr.shouldAuthenticate(e,n.defaultHeaders,n.requestHeaders))return}return P([{Authorization:`Bearer ${t instanceof Dr?await t.getToken(e,{apiURL:t.requestAPIURL(),...t.headerSnapshots(),...t.requestSnapshot(),signal:t.effectiveSignal(),...t.tenantSnapshot()}):await t.getToken()}`}])}let{apiKey:n}=await op(this);if(n!=null)return P([{Authorization:`Bearer ${n}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return P([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return Bt(e)}getUserAgent(){return`${this.constructor.name}/JS ${ut}`}defaultIdempotencyKey(){return`stainless-node-retry-${a()}`}makeStatusError(e,t,n,r){let i=t&&typeof t==`object`&&t.error==null?{error:t}:t;return l.generate(e,i,n,r)}_hasApiKeyProvider(){return typeof this._options.apiKey==`function`}async _callApiKey(e){if(this._provider)return e?.(this.apiKey),!1;let t=this._options.apiKey;if(typeof t!=`function`)return e?.(this.apiKey),!1;let n;try{n=await t()}catch(e){throw e instanceof c?e:new c(`Failed to get token from 'apiKey' function: ${e.message}`,{cause:e})}if(typeof n!=`string`||!n)throw new c(`Expected 'apiKey' function argument to return a string but it returned ${n}`);return this.apiKey=n,e?.(this.apiKey),!0}buildURL(e,t,n){let r=!i(this,fp,`m`,yp).call(this)&&n||this.baseURL,a=ne(e)?new URL(e):new URL(r+(r.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e)),o=this.defaultQuery(),s=Object.fromEntries(a.searchParams);return(!ae(o)||!ae(s))&&(t={...s,...o,...t}),typeof t==`object`&&t&&!Array.isArray(t)&&(a.search=this.stringifyQuery(t)),a.toString()}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest(`get`,e,t)}post(e,t){return this.methodRequest(`post`,e,t)}patch(e,t){return this.methodRequest(`patch`,e,t)}put(e,t){return this.methodRequest(`put`,e,t)}delete(e,t){return this.methodRequest(`delete`,e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(n=>({method:e,path:t,...n})))}request(e,t=null){let n=i(this,Q,`f`)??this._workloadIdentityAuth,r=n instanceof Dr?Promise.resolve(e).then(e=>n.runRequest(()=>this.makeRequest(e,t,void 0),this)):this.makeRequest(e,t,void 0);return this.responsePromise(r)}responsePromise(e,t=(e,t)=>this.parseResponseWithTimeout(e,t)){let n=new Gt(this,e,(e,n)=>{let r=i(this,vp,`f`).get(n.controller)?.continueRequest;return r?r(()=>t(e,n)):t(e,n)});return n.withResponse=async()=>{let t=await n,{response:r}=await e;return{data:t,response:r,request_id:r.headers.get(`x-request-id`)}},n._thenUnwrap=n=>this.responsePromise(e,async(e,r)=>lt(n(await t(e,r),r),r.response)),n}async parseResponseWithTimeout(e,t){if(t.options.stream||t.options.__binaryResponse||t.response.status===204||t.response.headers.get(`content-length`)===`0`)return st(e,t);for(;;){let n=i(this,vp,`f`).get(t.controller),r=n?.timeout??t.options.timeout??this.timeout,a=n?.authentication,o=a?t.controller.signal:t.options.signal,s=()=>a&&o?this._makeUserAbortError(o):new u,l;try{l=a?.remainingTimeout(t.options,r)??Math.max(0,t.startTime+r-Date.now())}catch(e){let n=o?.aborted?s():void 0;throw t.controller.abort(),Se(t.response.body).catch(()=>void 0),n??e}let p,m,h=!1;try{if(o?.aborted&&n?.helperMethod!==`runTools`)throw s();let r=new Promise((e,n)=>{p=setTimeout(()=>{h=!0,t.controller.abort(),n(new f)},l),o&&(m=()=>{h||n(s())},o.addEventListener(`abort`,m,{once:!0}))});return await Promise.race([st(e,t),r])}catch(e){if(o?.aborted&&!h)throw s();if(!h)throw a&&e instanceof SyntaxError?SyntaxError(`X.509 workload identity API response contains invalid JSON.`):a&&!(e instanceof c)?new d({message:`X.509 workload identity API response body could not be read.`}):e;let r=n?.retriesRemaining??0;if(!r||n?.hasStreamingBody||t.options.__metadata?.hasStreamingBody||globalThis.ReadableStream&&t.options.body instanceof globalThis.ReadableStream||typeof t.options.body==`object`&&t.options.body!==null&&(Symbol.asyncIterator in t.options.body||Symbol.iterator in t.options.body&&`next`in t.options.body&&typeof t.options.body.next==`function`))throw new f;p!==void 0&&clearTimeout(p),m&&o?.removeEventListener(`abort`,m),m=void 0;let i=await this.retryRequest(t.options,r,t.retryOfRequestLogID??t.requestLogID,void 0,t.requestSignal);Object.assign(t,i)}finally{p!==void 0&&clearTimeout(p),m&&o?.removeEventListener(`abort`,m)}}}async readX509ResponseError(e,t,n,r,i){let a=new AbortController,o=r.signal,s=!1,c=()=>a.abort(o.reason);o.addEventListener(`abort`,c,{once:!0}),o.aborted&&c();try{let r=i.remainingTimeout(t,n),s=i.waitForRetry(r,a.signal).then(()=>{throw new f}),c=await Promise.race([e.text().catch(()=>`X.509 workload identity API response body could not be read.`),s]);if(o.aborted)throw this._makeUserAbortError(o);return c}catch(t){throw t instanceof f&&(s=!o.aborted,r.abort(),Se(e.body).catch(()=>void 0)),o.aborted&&!s?this._makeUserAbortError(o):t}finally{o.removeEventListener(`abort`,c),a.abort()}}async makeRequest(e,t,n){let r=await e,a=r.maxRetries??this.maxRetries;t??=a;let c=i(this,Q,`f`);c?.beginRequestPreparation(),await this.prepareOptions(r),c?.beginRequestPlanning();let l;try{let e=await this.buildRequest(r,{retryCount:a-t});if(l={req:e.req,url:e.url,timeout:e.timeout},c){se(`timeout`,l.timeout),c.authorizePlannedRequest(l.url,l.req,l.timeout),Dr.isStreamingRequestBody(l.req.body)&&(r.__metadata={...r.__metadata,hasStreamingBody:!0}),await this.prepareRequest(l.req,{url:l.url,options:r}),await this._provider?.prepareRequest?.(l.req,{url:l.url,options:r}),c.beginRequestPlanning(),c.authorizePlannedRequest(l.url,l.req,l.timeout,!0),Dr.isStreamingRequestBody(l.req.body)&&(r.__metadata={...r.__metadata,hasStreamingBody:!0});let e=c.requestSnapshot().signal;if(e?.aborted||l.req.signal?.aborted)throw this._makeUserAbortError(e?.aborted?e:l.req.signal);c.setEffectiveSignal(l.req.signal||e?wp(l.req.signal??e,e).signal:void 0),c.beginRequestNetwork();let t=r.__security??{bearerAuth:!0},n=await this.authHeaders(r,t),i=c.headerSnapshots(),a=P([i.defaultHeaders,i.requestHeaders]);for(let[e,t]of n?.values??[])!a.nulls.has(e)&&!l.req.headers.has(e)&&l.req.headers.set(e,t);this.validateHeaders(P([a,l.req.headers]),t)}}catch(e){if(c?.retireRequestBody(),c&&t&&!r.__metadata?.hasStreamingBody&&Dr.isRetryableFailure(e))return await this.retryRequest(r,t,n??`x509-token-exchange`,Dr.retryHeaders(e));throw e}let{req:u,url:p}=l,m=c?Math.min(l.timeout,c.requestSnapshot().timeout):l.timeout;c?.bindRequest(r,u,this.adminAPIKey);let h=r.__metadata?.hasStreamingBody===!0;c||(await this.prepareRequest(u,{url:p,options:r}),await this._provider?.prepareRequest?.(u,{url:p,options:r})),c?.adoptRequestHeaders(u),c&&Dr.isStreamingRequestBody(u.body)&&(h=!0);let g=`log_`+(Math.random()*(1<<24)|0).toString(16).padStart(6,`0`),_=n===void 0?``:`, retryOf: ${n}`,v=c?.requestStartedAt(r)??Date.now();if(this.logLevel===`debug`){let e=typeof u.body==`string`?{type:`string`,length:u.body.length}:u.body;A(this).debug(`[${g}] sending request`,qe({retryOfRequestLogID:n,method:r.method,url:p,options:c?{body:e,...c.requestSnapshot()}:{...r,body:e},headers:u.headers}))}let y=c?c.requestSnapshot().signal:r.signal;if(y?.aborted||u.signal?.aborted)throw this._makeUserAbortError(y?.aborted?y:u.signal);let b=r.__security??{bearerAuth:!0},x=c||this.fetchWithTimeout===pp.prototype.fetchWithTimeout?wp(u.signal??(c?y:void 0),c?y:void 0):new AbortController,ee=c?.remainingTimeout(r,m)??m,S=c?pp.prototype.fetchWithAuth:this.fetchWithAuth;c?.releaseRequestBody(u.body);let w=await S.call(this,p,u,ee,x,b).catch(s),ne=Date.now();if(w instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(y?.aborted||u.signal?.aborted)throw this._makeUserAbortError(y?.aborted?y:u.signal);let i=o(w)||/timed? ?out/i.test(String(w)+(`cause`in w?String(w.cause):``));if(t&&!h&&(!c||zn(w)))return A(this).info(`[${g}] connection ${i?`timed out`:`failed`} - ${e}`),A(this).debug(`[${g}] connection ${i?`timed out`:`failed`} (${e})`,qe({retryOfRequestLogID:n,url:p,durationMs:ne-v,message:c?`X.509 workload identity API connection failed.`:w.message})),this.retryRequest(r,t,n??g,void 0,u.signal);let a=h?`error; streaming body cannot be retried`:`error; no more retries left`;if(A(this).info(`[${g}] connection ${i?`timed out`:`failed`} - ${a}`),A(this).debug(`[${g}] connection ${i?`timed out`:`failed`} (${a})`,qe({retryOfRequestLogID:n,url:p,durationMs:ne-v,message:c?`X.509 workload identity API connection failed.`:w.message})),w instanceof C||w instanceof te)throw w;if(i){let e=`cause`in w?w.cause:void 0,t=typeof e==`object`&&e&&`code`in e&&e.code===`UND_ERR_HEADERS_TIMEOUT`?new f({message:`Request timed out. Node.js fetch timed out waiting for response headers; configure a matching undici fetch and fetchOptions.dispatcher with an Agent whose headersTimeout is at least the SDK timeout.`}):new f;throw c?new f:Object.assign(t,{cause:w})}throw c?new d({message:`X.509 workload identity API connection failed.`}):new d({message:Tp(w),cause:w})}let T=`[${g}${_}${[...w.headers.entries()].filter(([e])=>e===`x-request-id`).map(([e,t])=>`, `+e+`: `+JSON.stringify(t)).join(``)}] ${u.method} ${Ke(p)} ${w.ok?`succeeded`:`failed`} with status ${w.status} in ${ne-v}ms`;if(!w.ok){let e=w.status===401&&c&&b.bearerAuth&&c.usedWorkloadToken(r);if(e&&c.invalidateToken(),w.status===401&&(c||this._workloadIdentityAuth)&&b.bearerAuth&&(!c||c.usedWorkloadToken(r))&&(!c||t>0)&&!h&&!r.__metadata?.workloadIdentityTokenRefreshed){c?Se(w.body).catch(()=>void 0):(await Se(w.body),this._workloadIdentityAuth?.invalidateToken());let e={...r,__metadata:{...r.__metadata,workloadIdentityTokenRefreshed:!0}};return this.makeRequest(e,c?t-1:t,n??g)}let i=e&&r.__metadata?.workloadIdentityTokenRefreshed?!1:await this.shouldRetry(w);if(t&&i&&!h){let e=`retrying, ${t} attempts remaining`;return c?Se(w.body).catch(()=>void 0):await Se(w.body),A(this).info(`${T} - ${e}`),A(this).debug(`[${g}] response error (${e})`,qe({retryOfRequestLogID:n,url:w.url,status:w.status,headers:w.headers,durationMs:ne-v})),this.retryRequest(r,t,n??g,w.headers,u.signal)}let a=i?h?`error; streaming body cannot be retried`:`error; no more retries left`:`error; not retryable`;A(this).info(`${T} - ${a}`);let o=c?await this.readX509ResponseError(w,r,m,x,c):await w.text().catch(e=>s(e).message),l=ce(o),d=l?void 0:o;throw A(this).debug(`[${g}] response error (${a})`,qe({retryOfRequestLogID:n,url:w.url,status:w.status,headers:w.headers,message:d,durationMs:Date.now()-v})),this.makeStatusError(w.status,l,d,w.headers)}A(this).info(T),A(this).debug(`[${g}] response start`,qe({retryOfRequestLogID:n,url:w.url,status:w.status,headers:w.headers,durationMs:ne-v}));let re=c?.continuation();return c?.releaseRequestCredentials(),i(this,vp,`f`).set(x,{timeout:m,retriesRemaining:t,hasStreamingBody:h,...c?{authentication:c}:{},helperMethod:r.__metadata?.helperMethod,...re?{continueRequest:re}:{}}),{response:w,options:r,controller:x,requestSignal:u.signal,requestLogID:g,retryOfRequestLogID:n,startTime:v}}getAPIList(e,t,n){return this.requestAPIList(t,n&&`then`in n?n.then(t=>({method:`get`,path:e,...t})):{method:`get`,path:e,...n})}requestAPIList(e,t){let n=i(this,Q,`f`)??this._workloadIdentityAuth,r=n instanceof Dr?Promise.resolve(t).then(e=>n.runRequest(()=>this.makeRequest(e,null,void 0),this)):this.makeRequest(t,null,void 0),a=new Jt(this,r,e),o=this.responsePromise(r,async(t,n)=>{let r=await this.parseResponseWithTimeout(t,n);return new e(t,n.response,r,n.options)});return a.then=o.then.bind(o),a.catch=o.catch.bind(o),a.finally=o.finally.bind(o),a.withResponse=o.withResponse.bind(o),a._thenUnwrap=o._thenUnwrap.bind(o),a}async fetchWithAuth(e,t,n,r,a={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&!i(this,gp,`f`)&&a.bearerAuth){let e=t.headers;if(e.get(`Authorization`)===`Bearer ${xp}`){let t=await this._workloadIdentityAuth.getToken();e.set(`Authorization`,`Bearer ${t}`)}}return await(i(this,gp,`f`)?pp.prototype.fetchWithTimeout:this.fetchWithTimeout).call(this,e,t,n,r)}async fetchWithTimeout(e,t,n,r){let{signal:a,method:o,...s}=t||{},c=this._makeAbort(r),l=!!a&&Cp.get(r)===a,u=a&&!l?_e(a,c,r.signal):void 0,d=setTimeout(c,n),f=globalThis.ReadableStream&&s.body instanceof globalThis.ReadableStream||typeof s.body==`object`&&s.body!==null&&Symbol.asyncIterator in s.body,p={signal:r.signal,...f?{duplex:`half`}:{},method:`GET`,...s};o&&(p.method=o.toUpperCase());try{let t=await(i(this,gp,`f`)??this.fetch).call(void 0,e,p);return u&&ge(t.body??t,c,r.signal),t}catch(e){throw u?.(),e}finally{clearTimeout(d)}}async shouldRetry(e){let t=e.headers.get(`x-should-retry`);return t===`true`?!0:t===`false`?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,r,a=e.signal){let o,s=r?.get(`retry-after-ms`);if(s){let e=parseFloat(s);Number.isNaN(e)||(o=e)}let c=r?.get(`retry-after`);if(c&&o===void 0){let e=parseFloat(c);o=Number.isNaN(e)?Date.parse(c)-Date.now():e*1e3}if(o===void 0||!Number.isFinite(o)||o<0||o>6e4){let n=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(t,n)}let l=i(this,Q,`f`);if(l){let t=l.remainingTimeout(e,l.requestSnapshot().timeout);if(o>=t)throw new f}if(l)await l.waitForRetry(o,l.effectiveSignal());else{let t=a===e.signal?[a]:[a,e.signal];try{await le(o,...t)}catch(e){let n=t.find(e=>e?.aborted);throw n?this._makeUserAbortError(n):e}}return this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e;return Math.min(.5*2**n,8)*(1-Math.random()*.25)*1e3}async buildRequest(e,{retryCount:t=0}={}){if(i(this,Q,`f`)&&!i(this,Q,`f`).inRequest(this)){let n=i(this,Q,`f`);return await n.runRequest(async()=>{let r=await pp.prototype.buildRequest.call(this,e,{retryCount:t});return n.releaseRequestBody(r.req.body),r},this)}let n={...e},r=i(this,Q,`f`),a=r?.snapshotTenant(this.organization,this.project),o=r?.snapshotHeaders(this._options.defaultHeaders,n.headers);o&&(n.headers=o.requestHeaders);let s=r?Er(this.fetchOptions):void 0,c=r?Er(n.fetchOptions):void 0,{method:l,path:u,query:d,defaultBaseURL:f}=n,p=this.buildURL(u,d,f);r?.snapshotAPIURL(p);let m=`timeout`in n;if(m&&se(`timeout`,n.timeout),n.timeout=n.timeout??this.timeout,r&&c&&r.snapshotRequest(n.signal,n.timeout,c),r){let e=r.requestSnapshot();n.timeout=e.timeout,e.signal===void 0?delete n.signal:n.signal=e.signal}let h=this._provider||r?void 0:await this.authHeaders(e,e.__security??{bearerAuth:!0}),{bodyHeaders:g,body:_,isStreamingBody:v}=this.buildBody({options:n});return v&&(e.__metadata={...e.__metadata,hasStreamingBody:!0},r?.ownRequestBody(_,n.body)),{req:{method:l,headers:await this.buildHeaders({options:e,method:l,bodyHeaders:g,authenticationHeaders:h,retryCount:t,x509Headers:o,x509Timeout:m?n.timeout:void 0,x509Tenant:a}),...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&_ instanceof globalThis.ReadableStream&&{duplex:`half`},..._&&{body:_},...(r?s:this.fetchOptions)??{},...(r?c:n.fetchOptions)??{}},url:p,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,authenticationHeaders:r,retryCount:a,x509Headers:o,x509Timeout:s,x509Tenant:c}){let l={};this.idempotencyHeader&&t!==`get`&&(e.idempotencyKey||=this.defaultIdempotencyKey(),l[this.idempotencyHeader]=e.idempotencyKey);let u=e.__metadata?.helperMethod,d=o?s:e.timeout,f=P([l,{Accept:`application/json`,...bp()?void 0:{"User-Agent":this.getUserAgent()},"X-Stainless-Retry-Count":String(a),...d?{"X-Stainless-Timeout":String(Math.trunc(d/1e3))}:{},...vt(),...typeof u==`string`?{"X-Stainless-Helper-Method":u}:{},"OpenAI-Organization":c?c.organization:this.organization,"OpenAI-Project":c?c.project:this.project},i(this,Q,`f`)&&!i(this,Q,`f`).isPlanningRequest()?await this.authHeaders(e,e.__security??{bearerAuth:!0}):r,o?.defaultHeaders??this._options.defaultHeaders,n,o?.requestHeaders??e.headers]);return!this._provider&&!i(this,Q,`f`)?.isPlanningRequest()&&this.validateHeaders(f,e.__security??{bearerAuth:!0}),f.values}_makeAbort(e){return()=>e.abort()}_makeUserAbortError(e){let t=new u;return Object.defineProperty(t,"cause",{value:e.reason,writable:!0,configurable:!0}),t}buildBody({options:e}){let{body:t,headers:n}=e;if(!t)return t===void 0&&`body`in e?{...i(this,mp,`f`).call(this,{body:t,headers:P([n])}),isStreamingBody:!1}:{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let r=P([n]),a=globalThis.ReadableStream!==void 0&&t instanceof globalThis.ReadableStream,o=!a&&(typeof t==`string`||t instanceof ArrayBuffer||ArrayBuffer.isView(t)||globalThis.Blob!==void 0&&t instanceof globalThis.Blob||t instanceof URLSearchParams||t instanceof FormData);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t==`string`&&r.values.has(`content-type`)||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||a?{bodyHeaders:void 0,body:t,isStreamingBody:!o}:typeof t==`object`&&(Symbol.asyncIterator in t||Symbol.iterator in t&&`next`in t&&typeof t.next==`function`)?{bodyHeaders:void 0,body:be(t),isStreamingBody:!0}:typeof t==`object`&&r.values.get(`content-type`)===`application/x-www-form-urlencoded`?{bodyHeaders:{"content-type":`application/x-www-form-urlencoded`},body:this.stringifyQuery(t),isStreamingBody:!1}:{...i(this,mp,`f`).call(this,{body:t,headers:r}),isStreamingBody:!1}}};pp=$,mp=new WeakMap,Q=new WeakMap,hp=new WeakMap,gp=new WeakMap,_p=new WeakMap,vp=new WeakMap,fp=new WeakSet,yp=function(){return i(this,_p,`f`)||this._provider!==void 0||this.baseURL!==`https://api.openai.com/v1`},$.OpenAI=pp,$.DEFAULT_TIMEOUT=6e5,$.OpenAIError=c,$.APIError=l,$.APIConnectionError=d,$.APIConnectionTimeoutError=f,$.APIUserAbortError=u,$.NotFoundError=g,$.ConflictError=_,$.RateLimitError=y,$.BadRequestError=p,$.AuthenticationError=m,$.InternalServerError=b,$.PermissionDeniedError=h,$.UnprocessableEntityError=v,$.InvalidWebhookSignatureError=S,$.toFile=gi,$.toStreamingFile=Nr,$.Completions=Lu,$.Chat=Js,$.Embeddings=Gu,$.Files=Xu,$.Images=sd,$.ContentProvenanceChecks=Vu,$.Audio=Ac,$.Moderations=pd,$.Models=fd,$.FineTuning=id,$.Graders=od,$.VectorStores=Gf,$.Safety=Mf,$.Webhooks=ap,$.Beta=Iu,$.Batches=jc,$.Uploads=Rf,$.Admin=Ec,$.Responses=Af,$.Live=dd,$.Realtime=_d,$.Conversations=Uu,$.Evals=Ju,$.Containers=Bu,$.Skills=If,$.Videos=Kf,$.ConversationCursorPage=N,$.CursorPage=M,$.NextCursorPage=Xt,$.Page=Yt,$.TokenPage=Zt;var Cp=new WeakMap;function wp(e,t){let n=new AbortController;if(!e)return n;let r=globalThis.AbortSignal;if(typeof r?.any!=`function`||!(e instanceof r))return n;try{let i=[n.signal,e];t&&t!==e&&i.push(t);let a=r.any(i);Object.defineProperty(n,"signal",{value:a,configurable:!0}),Cp.set(n,e)}catch{}return n}function Tp(e){if(Ep(e))return`Connection error. This may be caused by passing an undici dispatcher, such as ProxyAgent, that is incompatible with the fetch implementation. If you are using undici's ProxyAgent, pass the fetch implementation from the same undici package: import { fetch, ProxyAgent } from 'undici'; new OpenAI({ fetch, fetchOptions: { dispatcher: new ProxyAgent(...) } });`}function Ep(e){let t=e;for(let e=0;e<8&&t&&typeof t==`object`;e++){let e=t;if(e.code===`UND_ERR_INVALID_ARG`&&typeof e.message==`string`&&e.message.includes(`invalid onRequestStart method`))return!0;t=e.cause}return!1}var Dp=class extends ${constructor({baseURL:e=Nl(`OPENAI_BASE_URL`),apiKey:t=Nl(`AZURE_OPENAI_API_KEY`),apiVersion:n=Nl(`OPENAI_API_VERSION`),endpoint:r,deployment:i,azureADTokenProvider:a,dangerouslyAllowBrowser:o,dataResidency:s,...l}={}){if(Ut(s,`AzureOpenAI`),!n)throw new c(`The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).`);if(typeof a==`function`&&(o??=!0),!a&&!t)throw new c("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(a&&t)throw new c("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(l.defaultQuery={...l.defaultQuery,"api-version":n},!e){if(r||={}.AZURE_OPENAI_ENDPOINT,!r)throw new c("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");let t=r.length;for(;t>0&&r[t-1]===`/`;)t--;e=`${r.slice(0,t)}/openai`}else if(r)throw new c(`baseURL and endpoint are mutually exclusive`);super({apiKey:a??t,baseURL:e,...l,...o===void 0?{}:{dangerouslyAllowBrowser:o}}),this.apiVersion=``,this.apiVersion=n,this.deploymentName=i}withOptions(e){let t={apiVersion:this.apiVersion,deployment:this.deploymentName,...e};return E(e,`endpoint`)&&e.endpoint!==void 0&&!E(e,`baseURL`)&&(t.baseURL=void 0),super.withOptions(t)}async buildRequest(e,t={}){if(kp.has(e.path)&&e.method===`post`&&e.body!==void 0){if(!oe(e.body))throw Error(`Expected request body to be an object`);let t=this.deploymentName||e.body.model||e.__metadata?.model;t!==void 0&&!Op(this.baseURL)&&(e.path=z`/deployments/${t}`+e.path)}let n=await super.buildRequest(e,t);return n.req.headers.has(`api-key`)&&(n.req.redirect=`manual`),n}async fetchWithAuth(e,t,n,r,i){return new Headers(t.headers).has(`api-key`)&&(t.redirect=`manual`),super.fetchWithAuth(e,t,n,r,i)}async authHeaders(e,t){let n=t??{bearerAuth:!0,adminAPIKeyAuth:!0};return n.bearerAuth&&typeof this._options.apiKey==`string`?P([{"api-key":this.apiKey}]):super.authHeaders(e,n)}};function Op(e){try{return new URL(e).pathname.split(`/`).includes(`deployments`)}catch{return!1}}var kp=new Set([`/completions`,`/chat/completions`,`/embeddings`,`/audio/transcriptions`,`/audio/translations`,`/audio/speech`,`/images/generations`,`/batches`,`/images/edits`]);export{$ as n,Dp as t};