1function I(r,e,t,s,n){if(typeof e=="function"?r!==e||!0:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(r,t),t}function c(r,e,t,s){if(t==="a"&&!s)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?s:t==="a"?s.call(r):s?s.value:e.get(r)}let dt=function(){const{crypto:r}=globalThis;if(r?.randomUUID)return dt=r.randomUUID.bind(r),r.randomUUID();const e=new Uint8Array(1),t=r?()=>r.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,s=>(+s^t()&15>>+s/4).toString(16))};function Nt(r){return typeof r=="object"&&r!==null&&("name"in r&&r.name==="AbortError"||"message"in r&&String(r.message).includes("FetchRequestCanceledException"))}const Mt=r=>{if(r instanceof Error)return r;if(typeof r=="object"&&r!==null){try{if(Object.prototype.toString.call(r)==="[object Error]"){const e=new Error(r.message,r.cause?{cause:r.cause}:{});return r.stack&&(e.stack=r.stack),r.cause&&!e.cause&&(e.cause=r.cause),r.name&&(e.name=r.name),e}}catch{}try{return new Error(JSON.stringify(r))}catch{}}return new Error(r)};class g extends Error{}class L extends g{constructor(e,t,s,n){super(`${L.makeMessage(e,t,s)}`),this.status=e,this.headers=n,this.requestID=n?.get("x-request-id"),this.error=t;const i=t;this.code=i?.code,this.param=i?.param,this.type=i?.type}static makeMessage(e,t,s){const n=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):s;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,s,n){if(!e||!n)return new _t({message:s,cause:Mt(t)});const i=t?.error;return e===400?new er(e,i,s,n):e===401?new tr(e,i,s,n):e===403?new sr(e,i,s,n):e===404?new rr(e,i,s,n):e===409?new nr(e,i,s,n):e===422?new ir(e,i,s,n):e===429?new ar(e,i,s,n):e>=500?new or(e,i,s,n):new L(e,i,s,n)}}class Y extends L{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class _t extends L{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class Vt extends _t{constructor({message:e}={}){super({message:e??"Request timed out."})}}class er extends L{}class tr extends L{}class sr extends L{}class rr extends L{}class nr extends L{}class ir extends L{}class ar extends L{}class or extends L{}class cr extends g{constructor(){super("Could not parse response content as the length limit was reached")}}class ur extends g{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class Pe extends Error{constructor(e){super(e)}}class lr extends L{constructor(e,t,s){let n="OAuth2 authentication error",i;if(t&&typeof t=="object"){const o=t;i=o.error;const u=o.error_description;u&&typeof u=="string"?n=u:i&&(n=i)}super(e,t,n,s),this.error_code=i}}class di extends g{constructor(e,t,s){super(e),this.provider=t,this.cause=s}}const _i=/^[a-z][a-z0-9+.-]*:/i,fi=r=>_i.test(r);let W=r=>(W=Array.isArray,W(r)),Ps=W;function Gt(r){return typeof r!="object"?{}:r??{}}function Ss(r){if(!r)return!0;for(const e in r)return!1;return!0}function pi(r,e){return Object.prototype.hasOwnProperty.call(r,e)}function Rt(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}const mi=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new g(`${r} must be an integer`);if(e<0)throw new g(`${r} must be a positive integer`);return e},yi=r=>{try{return JSON.parse(r)}catch{return}},Fe=r=>new Promise(e=>setTimeout(e,r)),ge="6.46.0",gi=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function bi(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}const Ai=()=>{const r=bi();if(r==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ge,"X-Stainless-OS":Rs(Deno.build.os),"X-Stainless-Arch":ks(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="str
1ing"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ge,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(r==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ge,"X-Stainless-OS":Rs(globalThis.process.platform??"unknown"),"X-Stainless-Arch":ks(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=wi();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ge,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ge,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function wi(){if(typeof navigator>"u"||!navigator)return null;const r=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:e,pattern:t}of r){const s=t.exec(navigator.userAgent);if(s){const n=s[1]||0,i=s[2]||0,o=s[3]||0;return{browser:e,version:`${n}.${i}.${o}`}}}return null}const ks=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",Rs=r=>(r=r.toLowerCase(),r.includes("ios")?"iOS":r==="android"?"Android":r==="darwin"?"MacOS":r==="win32"?"Windows":r==="freebsd"?"FreeBSD":r==="openbsd"?"OpenBSD":r==="linux"?"Linux":r?`Other:${r}`:"Unknown");let vs;const xi=()=>vs??(vs=Ai());function hr(){if(typeof fetch<"u")return fetch;throw new 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 dr(...r){const e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...r)}function _r(r){let e=Symbol.asyncIterator in r?r[Symbol.asyncIterator]():r[Symbol.iterator]();return dr({start(){},async pull(t){const{done:s,value:n}=await e.next();s?t.close():t.enqueue(n)},async cancel(){await e.return?.()}})}function fr(r){if(r[Symbol.asyncIterator])return r;const e=r.getReader();return{async next(){try{const t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){const t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Cs(r){if(r===null||typeof r!="object")return;if(r[Symbol.asyncIterator]){await r[Symbol.asyncIterator]().return?.();return}const e=r.getReader(),t=e.cancel();e.releaseLock(),await t}const Ii=({headers:r,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),pr="RFC3986",mr=r=>String(r),Es={RFC1738:r=>String(r).replace(/%20/g,"+"),RFC3986:mr},$i="RFC1738";let Ft=(r,e)=>(Ft=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Ft(r,e));const ee=(()=>{const r=[];for(let e=0;e<256;++e)r.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return r})(),vt=1024,Pi=(r,e,t,s,n)=>{if(r.length===0)return r;let i=r;if(typeof r=="symbol"?i=Symbol.prototype.toString.call(r):typeof r!="string"&&(i=String(r)),t==="iso-8859-1")return escape(i).replace(/%u[0-9a-f]{4}/gi,function(u){return"%26%23"+parseInt(u.slice(2),16)+"%3B"});let o="";for(let u=0;u<i.length;u+=vt){const _=i.length>=vt?i.slice(u,u+vt):i,l=[];for(let y=0;y<_.length;++y){let h=_.charCodeAt(y);if(h===45||h===46||h===95||h===126||h>=48&&h<=57||h>=65&&h<=90||h>=97&&h<=122||n===$i&&(h===40||h===41)){l[l.length]=_.charAt(y);continue}if(h<128){l[l.length]=ee[h];continue}if(h<2048){l[l.length]=ee[192|h>>6]+ee[128|h&63];continue}if(h<55296||h>=57344){l[l.length]=ee[224|h>>12]+ee[128|h>>6&63]+ee[128|h&63];continue}y+=1,h=65536+((h&1023)<<10|_.charCodeAt(y)&1023),l[l.length]=ee[240|h>>18]+ee[128|h>>12&63]+ee[128|h>>6&63]+ee[128|h&63]}o+=l.join("")}return o};function Si(r){return!r||typeof r!="object"?!1:!!(r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer(r))}function Os(r,e){if(W(r)){const t=[];for(let s=0;s<r.length;s+=1)t.push(e(r[s]));return t}return e(r)}const yr={brackets(r){return String(r)+"[]"},comma:"comma",indices(r,e){return String(r)+"["+e+"]"},repeat(r){return String(r)}},gr=function(r,e){Array.prototype.push.apply(r,W(e)?e:[e])};let Ts;const j={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset
1:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Pi,encodeValuesOnly:!1,format:pr,formatter:mr,indices:!1,serializeDate(r){return(Ts??(Ts=Function.prototype.call.bind(Date.prototype.toISOString)))(r)},skipNulls:!1,strictNullHandling:!1};function ki(r){return typeof r=="string"||typeof r=="number"||typeof r=="boolean"||typeof r=="symbol"||typeof r=="bigint"}const Ct={};function br(r,e,t,s,n,i,o,u,_,l,y,h,m,w,p,b,x,R){let A=r,k=R,S=0,q=!1;for(;(k=k.get(Ct))!==void 0&&!q;){const O=k.get(r);if(S+=1,typeof O<"u"){if(O===S)throw new RangeError("Cyclic object value");q=!0}typeof k.get(Ct)>"u"&&(S=0)}if(typeof l=="function"?A=l(e,A):A instanceof Date?A=m?.(A):t==="comma"&&W(A)&&(A=Os(A,function(O){return O instanceof Date?m?.(O):O})),A===null){if(i)return _&&!b?_(e,j.encoder,x,"key",w):e;A=""}if(ki(A)||Si(A)){if(_){const O=b?e:_(e,j.encoder,x,"key",w);return[p?.(O)+"="+p?.(_(A,j.encoder,x,"value",w))]}return[p?.(e)+"="+p?.(String(A))]}const M=[];if(typeof A>"u")return M;let C;if(t==="comma"&&W(A))b&&_&&(A=Os(A,_)),C=[{value:A.length>0?A.join(",")||null:void 0}];else if(W(l))C=l;else{const O=Object.keys(A);C=y?O.sort(y):O}const E=u?String(e).replace(/\./g,"%2E"):String(e),D=s&&W(A)&&A.length===1?E+"[]":E;if(n&&W(A)&&A.length===0)return D+"[]";for(let O=0;O<C.length;++O){const T=C[O],Is=typeof T=="object"&&typeof T.value<"u"?T.value:A[T];if(o&&Is===null)continue;const kt=h&&u?T.replace(/\./g,"%2E"):T,hi=W(A)?typeof t=="function"?t(D,kt):D:D+(h?"."+kt:"["+kt+"]");R.set(r,S);const $s=new WeakMap;$s.set(Ct,R),gr(M,br(Is,hi,t,s,n,i,o,u,t==="comma"&&b&&W(A)?null:_,l,y,h,m,w,p,b,x,$s))}return M}function Ri(r=j){if(typeof r.allowEmptyArrays<"u"&&typeof r.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof r.encodeDotInKeys<"u"&&typeof r.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(r.encoder!==null&&typeof r.encoder<"u"&&typeof r.encoder!="function")throw new TypeError("Encoder has to be a function.");const e=r.charset||j.charset;if(typeof r.charset<"u"&&r.charset!=="utf-8"&&r.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=pr;if(typeof r.format<"u"){if(!Ft(Es,r.format))throw new TypeError("Unknown format option provided.");t=r.format}const s=Es[t];let n=j.filter;(typeof r.filter=="function"||W(r.filter))&&(n=r.filter);let i;if(r.arrayFormat&&r.arrayFormat in yr?i=r.arrayFormat:"indices"in r?i=r.indices?"indices":"repeat":i=j.arrayFormat,"commaRoundTrip"in r&&typeof r.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const o=typeof r.allowDots>"u"?r.encodeDotInKeys?!0:j.allowDots:!!r.allowDots;return{addQueryPrefix:typeof r.addQueryPrefix=="boolean"?r.addQueryPrefix:j.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof r.allowEmptyArrays=="boolean"?!!r.allowEmptyArrays:j.allowEmptyArrays,arrayFormat:i,charset:e,charsetSentinel:typeof r.charsetSentinel=="boolean"?r.charsetSentinel:j.charsetSentinel,commaRoundTrip:!!r.commaRoundTrip,delimiter:typeof r.delimiter>"u"?j.delimiter:r.delimiter,encode:typeof r.encode=="boolean"?r.encode:j.encode,encodeDotInKeys:typeof r.encodeDotInKeys=="boolean"?r.encodeDotInKeys:j.encodeDotInKeys,encoder:typeof r.encoder=="function"?r.encoder:j.encoder,encodeValuesOnly:typeof r.encodeValuesOnly=="boolean"?r.encodeValuesOnly:j.encodeValuesOnly,filter:n,format:t,formatter:s,serializeDate:typeof r.serializeDate=="function"?r.serializeDate:j.serializeDate,skipNulls:typeof r.skipNulls=="boolean"?r.skipNulls:j.skipNulls,sort:typeof r.sort=="function"?r.sort:null,strictNullHandling:typeof r.strictNullHandling=="boolean"?r.strictNullHandling:j.strictNullHandling}}function vi(r,e={}){let t=r;const s=Ri(e);let n,i;typeof s.filter=="function"?(i=s.filter,t=i("",t)):W(s.filter)&&(i=s.filter,n=i);const o=[];if(typeof t!="object"||t===null)return"";const u=yr[s.arrayFormat],_=u==="comma"&&s.commaRoundTrip;n||(n=Object.keys(t)),s.sort&&n.sort(s.sort);const l=new WeakMap;for(let m=0;m<n.length;++m){const w=n[m];s.skipNulls&&t[w]===null||gr(o,br(t[w],w,u,_,s.allowEmptyArrays,s.strictNullHandling,s.skipNulls,s.encodeDotInKeys,s.encode?s.encoder:null,s.filter,s.sort,s.allowDots,s.serializeDate,s.format,s.formatter,s.encodeValuesOnly,s.charset,l))}const y=o.join(s.delimiter);let h=s.addQueryPrefix===!0?"?":"";return s.charsetSentinel&&(s.charset==="iso-8859-1"?h+="utf8=%26%2310003%3B&":h+="utf8=%E2%9C%93&"),y.length>0?h+y:""}function Ci(r){return vi(r,{arrayFormat:"brackets"})}function Ei(r){let e=0;for(const n of r)e+=n.length;const t=new Uint8Array(e);let s=0;for(const n of r)t.set(n,s),s+=n.length;return t}let Ks;function Qt(r){let e;return(Ks??(e=new globalThis.TextEncoder,Ks=e.encode.bind(e)))(r)}let js;function Ls(r){let e;return(js??(e=new globalThis.TextDecoder,js=e.decode.bind(e)))(r)}var H,J;class ft{constructor(){H.set(this,void 0),J.set(this,void 0),I(this,H,new Uint8Array),I(this,J,null)}decode(e){if(e==null)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Qt(e):e;I(this,H,Ei([c(this,H,"f"),t]));const s=[];let n;for(;(n=Oi(c(this,H,"f"),c(this,J,"f")))!=null;){if(n.carriage&&c(this,J,"f")==null){I(this,J,n.index);continue}if(c(this,J,"f")!=null&&(n.index!==c(this,J,"f")+1||n.carriage)){s.push(Ls(c(this,H,"f").subarray(0,c(this,J,"f")-1))),I(this,H,c(this,H,"f").subarray(c(this,J,"f"))),I(this,J,null);continue}const i=c(this,J,"f")!==null?n.preceding-1:n.preceding,o=Ls(c(this,H,"f").subarray(0,i));s.push(o),I(this,H,c(this,H,"f").subarray(n.index)),I(this,J,null)}return s}flush(){return c(this,H,"f").length?this.decode(` 2`):[]}}H=new WeakMap,J=new WeakMap;ft.NEWLINE_CHARS=new Set([` 3`,"\r"]);ft.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Oi(r,e){for(let n=e??0;n<r.length;n++){if(r[n]===10)return{preceding:n,index:n+1,carriage:!1};if(r[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function Ti(r){for(let s=0;s<r.length-1;s++){if(r[s]===10&&r[s+1]===10||r[s]===13&&r[s+1]===13)return s+2;if(r[s]===13&&r[s+1]===10&&s+3<r.length&&r[s+2]===13&&r[s+3]===10)return s+4}return-1}const rt={off:0,error:200,warn:300,info:400,debug:500},Ns=(r,e,t)=>{if(r){if(pi(rt,r))return r;F(t).warn(`${e} was set to ${JSON.stringify(r)}, expected one of ${JSON.stringify(Object.keys(rt))}`)}};function Se(){}function De(r,e,t){return!e||rt[r]>rt[t]?Se:e[r].bind(e)}const Ki={error:Se,warn:Se,info:Se,debug:Se};let Ms=new WeakMap;function F(r){const e=r.logger,t=r.logLevel??"off";if(!e)return Ki;const s=Ms.get(e);if(s&&s[0]===t)return s[1];const n={error:De("error",e,t),warn:De("warn",e,t),info:De("info",e,t),debug:De("debug",e,t)};return Ms.set(e,[t,n]),n}const de=r=>(r.options&&(r.options={...r.options},delete r.options.headers),r.headers&&(r.headers=Object.fromEntries((r.headers instanceof Headers?[...r.headers]:Object.entries(r.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="x-amz-security-token"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in r&&(r.retryOfRequestLogID&&(r.retryOf=r.retryOfRequestLogID),delete r.retryOfRequestLogID),r);var Ie;class re{constructor(e,t,s){this.iterator=e,Ie.set(this,void 0),this.controller=t,I(this,Ie,s)}static fromSSEResponse(e,t,s,n){let i=!1;const o=s?F(s):console;async function*u(){if(i)throw new g("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let _=!1;try{for await(const l of ji(e,t))if(!_){if(l.data.startsWith("[DONE]")){_=!0;continue}if(l.event===null||!l.event.startsWith("thread.")){let y;try{y=JSON.parse(l.data)}catch(h){throw o.error("Could not parse message into JSON:",l.data),o.error("From chunk:",l.raw),h}if(y&&y.error)throw new L(void 0,y.error,void 0,e.headers);yield n?{event:l.event,data:y}:y}else{let y;try{y=JSON.parse(l.data)}catch(h){throw console.error("Could not parse message into JSON:",l.data),console.error("From chunk:",l.raw),h}if(l.event=="error")throw new L(void 0,y.error,y.message,void 0);yield{event:l.event,data:y}}}_=!0}catch(l){if(Nt(l))return;throw l}finally{_||t.abort()}}return new re(u,t,s)}static fromReadableStream(e,t,s){let n=!1;async function*i(){const u=new ft,_=fr(e);for await(const l of _)for(const y of u.decode(l))yield y;for(const l of u.flush())yield l}async function*o(){if(n)throw new g("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let u=!1;try{for await(const _ of i())u||_&&(yield JSON.parse(_));u=!0}catch(_){if(Nt(_))return;throw _}finally{u||t.abort()}}return new re(o,t,s)}[(Ie=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[],t=[],s=this.iterator(),n=i=>({next:()=>{if(i.length===0){const o=s.next();e.push(o),t.push(o)}return i.shift()}});return[new re(()=>n(e),this.controller,c(this,Ie,"f")),new re(()=>n(t),this.controller,c(this,Ie,"f"))]}toReadableStream(){const e=this;let t;return dr({async start(){t=e[Symbol.asyncIterator]()},async pull(s){try{const{value:n,done:i}=await t.next();if(i)return s.close();const o=Qt(JSON.stringify(n)+` 4`);s.enqueue(o)}catch(n){s.error(n)}},async cancel(){await t.return?.()}})}}async function*ji(r,e){if(!r.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new g("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 g("Attempted to iterate over a response with no body");const t=new Ni,s=new ft,n=fr(r.body);for await(const i of Li(n))for(const o of s.decode(i)){const u=t.decode(o);u&&(yield u)}for(const i of s.flush()){const o=t.decode(i);o&&(yield o)}}async function*Li(r){let e=new Uint8Array;for await(const t of r){if(t==null)continue;const s=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?Qt(t):t;let n=new Uint8Array(e.length+s.length);n.set(e),n.set(s,e.length),e=n;let i;for(;(i=Ti(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}class Ni{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const i={event:this.event,data:this.data.join(` 5`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,s,n]=Mi(e,":");return n.startsWith(" ")&&(n=n.substring(1)),t==="event"?this.event=n:t==="data"&&this.data.push(n),null}}function Mi(r,e){const t=r.indexOf(e);return t!==-1?[r.substring(0,t),e,r.substring(t+e.length)]:[r,"",""]}async function Ar(r,e){const{response:t,requestLogID:s,retryOfRequestLogID:n,startTime:i}=e,o=await(async()=>
5{if(e.options.stream)return F(r).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,r,e.options.__synthesizeEventData):re.fromSSEResponse(t,e.controller,r,e.options.__synthesizeEventData);if(t.status===204)return null;if(e.options.__binaryResponse)return t;const _=t.headers.get("content-type")?.split(";")[0]?.trim();if(_?.includes("application/json")||_?.endsWith("+json")){if(t.headers.get("content-length")==="0")return;const m=await t.json();return wr(m,t)}return await t.text()})();return F(r).debug(`[${s}] response parsed`,de({retryOfRequestLogID:n,url:t.url,status:t.status,body:o,durationMs:Date.now()-i})),o}function wr(r,e){return!r||typeof r!="object"||Array.isArray(r)?r:Object.defineProperty(r,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var ke;class pt extends Promise{constructor(e,t,s=Ar){super(n=>{n(null)}),this.responsePromise=t,this.parseResponse=s,ke.set(this,void 0),I(this,ke,e)}_thenUnwrap(e){return new pt(c(this,ke,"f"),this.responsePromise,async(t,s)=>wr(e(await this.parseResponse(t,s),s),s.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[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.parsedPromise=this.responsePromise.then(e=>this.parseResponse(c(this,ke,"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)}}ke=new WeakMap;var Ue;class mt{constructor(e,t,s,n){Ue.set(this,void 0),I(this,Ue,e),this.options=n,this.response=t,this.body=s}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new g("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await c(this,Ue,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Ue=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class Fi extends pt{constructor(e,t,s){super(e,t,async(n,i)=>new s(n,i.response,await Ar(n,i),i.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const t of e)yield t}}class le extends mt{constructor(e,t,s,n){super(e,t,s,n),this.data=s.data||[],this.object=s.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class v extends mt{constructor(e,t,s,n){super(e,t,s,n),this.data=s.data||[],this.has_more=s.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){const e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...Gt(this.options.query),after:t}}:null}}class B extends mt{constructor(e,t,s,n){super(e,t,s,n),this.data=s.data||[],this.has_more=s.has_more||!1,this.last_id=s.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){const e=this.last_id;return e?{...this.options,query:{...Gt(this.options.query),after:e}}:null}}class oe extends mt{constructor(e,t,s,n){super(e,t,s,n),this.data=s.data||[],this.has_more=s.has_more||!1,this.next=s.next||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){const e=this.next;return e?{...this.options,query:{...Gt(this.options.query),after:e}}:null}}const zi={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},Bi="urn:ietf:params:oauth:grant-type:token-exchange";class Di{constructor(e,t){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl="https://auth.openai.com/oauth/token",this.config=e,this.fetch=t??hr()}async getToken(){if(!this.cachedToken||this.isTokenExpired(this.cachedToken)){if(this.refreshPromise)return await this.refreshPromise;this.refreshPromise=this.refreshToken();try{return await this.refreshPromise}finally{this.refreshPromise=null}}return this.needsRefresh(this.cachedToken)&&!this.refreshPromise&&(this.refreshPromise=this.refreshToken().finally(()=>{this.refreshPromise=null})),this.cachedToken.token}async refreshToken(){const e=await this.config.provider.getToken(),t={grant_type:Bi,subject_token:e,subject_token_type:zi[this.config.provider.tokenType],identity_provider_id:this.config.identityProvi
5derId,service_account_id:this.config.serviceAccountId};this.config.clientId&&(t.client_id=this.config.clientId);const s=await this.fetch(this.tokenExchangeUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){const _=await s.text();let l;try{l=JSON.parse(_)}catch{}throw s.status===400||s.status===401||s.status===403?new lr(s.status,l,s.headers):L.generate(s.status,l,`Token exchange failed with status ${s.status}`,s.headers)}const n=await s.json();if(typeof n!="object"||n===null||!("access_token"in n)||typeof n.access_token!="string"||n.access_token.trim().length===0)throw new g("Token exchange response missing 'access_token' field");const i=n.access_token,o=n.expires_in??3600,u=Date.now()+o*1e3;return this.cachedToken={token:i,expiresAt:u},i}isTokenExpired(e){return Date.now()>=e.expiresAt}needsRefresh(e){const s=(this.config.refreshBufferSeconds??1200)*1e3;return Date.now()>=e.expiresAt-s}invalidateToken(){this.cachedToken=null,this.refreshPromise=null}}const xr=()=>{if(typeof File>"u"){const{process:r}=globalThis,e=typeof r?.versions?.node=="string"&&parseInt(r.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function je(r,e,t){return xr(),new File(r,e??"unknown_file",t)}function Xe(r){return(typeof r=="object"&&r!==null&&("name"in r&&r.name&&String(r.name)||"url"in r&&r.url&&String(r.url)||"filename"in r&&r.filename&&String(r.filename)||"path"in r&&r.path&&String(r.path))||"").split(/[\\/]/).pop()||void 0}const Yt=r=>r!=null&&typeof r=="object"&&typeof r[Symbol.asyncIterator]=="function",yt=async(r,e)=>zt(r.body)?{...r,body:await Ir(r.body,e)}:r,ne=async(r,e)=>({...r,body:await Ir(r.body,e)}),Fs=new WeakMap;function Ui(r){const e=typeof r=="function"?r:r.fetch,t=Fs.get(e);if(t)return t;const s=(async()=>{try{const n="Response"in e?e.Response:(await e("data:,")).constructor,i=new FormData;return i.toString()!==await new n(i).text()}catch{return!0}})();return Fs.set(e,s),s}const Ir=async(r,e)=>{if(!await Ui(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const t=new FormData;return await Promise.all(Object.entries(r||{}).map(([s,n])=>Bt(t,s,n))),t},$r=r=>r instanceof Blob&&"name"in r,Wi=r=>typeof r=="object"&&r!==null&&(r instanceof Response||Yt(r)||$r(r)),zt=r=>{if(Wi(r))return!0;if(Array.isArray(r))return r.some(zt);if(r&&typeof r=="object"){for(const e in r)if(zt(r[e]))return!0}return!1},Bt=async(r,e,t)=>{if(t!==void 0){if(t==null)throw new 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")r.append(e,String(t));else if(t instanceof Response)r.append(e,je([await t.blob()],Xe(t)));else if(Yt(t))r.append(e,je([await new Response(_r(t)).blob()],Xe(t)));else if($r(t))r.append(e,t,Xe(t));else if(Array.isArray(t))await Promise.all(t.map(s=>Bt(r,e+"[]",s)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([s,n])=>Bt(r,`${e}[${s}]`,n)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}},Pr=r=>r!=null&&typeof r=="object"&&typeof r.size=="number"&&typeof r.type=="string"&&typeof r.text=="function"&&typeof r.slice=="function"&&typeof r.arrayBuffer=="function",qi=r=>r!=null&&typeof r=="object"&&typeof r.name=="string"&&typeof r.lastModified=="number"&&Pr(r),Hi=r=>r!=null&&typeof r=="object"&&typeof r.url=="string"&&typeof r.blob=="function";async function Ji(r,e,t){if(xr(),r=await r,qi(r))return r instanceof File?r:je([await r.arrayBuffer()],r.name);if(Hi(r)){const n=await r.blob();return e||(e=new URL(r.url).pathname.split(/[\\/]/).pop()),je(await Dt(n),e,t)}const s=await Dt(r);if(e||(e=Xe(r)),!t?.type){const n=s.find(i=>typeof i=="object"&&"type"in i&&i.type);typeof n=="string"&&(t={...t,type:n})}return je(s,e,t)}async function Dt(r){let e=[];
5if(typeof r=="string"||ArrayBuffer.isView(r)||r instanceof ArrayBuffer)e.push(r);else if(Pr(r))e.push(r instanceof Blob?r:await r.arrayBuffer());else if(Yt(r))for await(const t of r)e.push(...await Dt(t));else{const t=r?.constructor?.name;throw new Error(`Unexpected data type: ${typeof r}${t?`; constructor: ${t}`:""}${Xi(r)}`)}return e}function Xi(r){return typeof r!="object"||r===null?"":`; props: [${Object.getOwnPropertyNames(r).map(t=>`"${t}"`).join(", ")}]`}class d{constructor(e){this._client=e}}function Sr(r){return r.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const zs=Object.freeze(Object.create(null)),Vi=(r=Sr)=>function(t,...s){if(t.length===1)return t[0];let n=!1;const i=[],o=t.reduce((y,h,m)=>{/[?#]/.test(h)&&(n=!0);const w=s[m];let p=(n?encodeURIComponent:r)(""+w);return m!==s.length&&(w==null||typeof w=="object"&&w.toString===Object.getPrototypeOf(Object.getPrototypeOf(w.hasOwnProperty??zs)??zs)?.toString)&&(p=w+"",i.push({start:y.length+h.length,length:p.length,error:`Value of type ${Object.prototype.toString.call(w).slice(8,-1)} is not a valid path parameter`})),y+h+(m===s.length?"":p)},""),u=o.split(/[?#]/,1)[0],_=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;let l;for(;(l=_.exec(u))!==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((y,h)=>y.start-h.start),i.length>0){let y=0;const h=i.reduce((m,w)=>{const p=" ".repeat(w.start-y),b="^".repeat(w.length);return y=w.start+w.length,m+p+b},"");throw new g(`Path parameters result in path with invalid segments: 6${i.map(m=>m.error).join(` 7`)} 8${o} 9${h}`)}return o},a=Vi(Sr);let kr=class extends d{list(e,t={},s){return this._client.getAPIList(a`/chat/completions/${e}/messages`,v,{query:t,...s,__security:{bearerAuth:!0}})}};function nt(r){return r!==void 0&&"function"in r&&r.function!==void 0}function Zt(r){return r?.$brand==="auto-parseable-response-format"}function ze(r){return r?.$brand==="auto-parseable-tool"}function Gi(r,e){return!e||!Rr(e)?{...r,choices:r.choices.map(t=>(vr(t.message.tool_calls),{...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:es(r,e)}function es(r,e){const t=r.choices.map(s=>{if(s.finish_reason==="length")throw new cr;if(s.finish_reason==="content_filter")throw new ur;return vr(s.message.tool_calls),{...s,message:{...s.message,...s.message.tool_calls?{tool_calls:s.message.tool_calls?.map(n=>Yi(e,n))??void 0}:void 0,parsed:s.message.content&&!s.message.refusal?Qi(e,s.message.content):null}}});return{...r,choices:t}}function Qi(r,e){return r.response_format?.type!=="json_schema"?null:r.response_format?.type==="json_schema"?"$parseRaw"in r.response_format?r.response_format.$parseRaw(e):JSON.parse(e):null}function Yi(r,e){const t=r.tools?.find(s=>nt(s)&&s.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:ze(t)?t.$parseRaw(e.function.arguments):t?.function.strict?JSON.parse(e.function.arguments):null}}}function Zi(r,e){if(!r||!("tools"in r)||!r.tools)return!1;const t=r.tools?.find(s=>nt(s)&&s.function?.name===e.function.name);return nt(t)&&(ze(t)||t?.function.strict||!1)}function Rr(r){return Zt(r.response_format)?!0:r.tools?.some(e=>ze(e)||e.type==="function"&&e.function.strict===!0)??!1}function vr(r){for(const e of r||[])if(e.type!=="function")throw new g(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function ea(r){for(const e of r??[]){if(e.type!=="function")throw new g(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new g(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}const it=r=>r?.role==="assistant",Cr=r=>r?.role==="tool";var Ve,Ge,Qe,Re,ve,Ye,Ce,ae,at,Ee,ot,ct,be,Er,Or;class ts{constructor(){Ve.add(this),this.controller=new AbortController,Ge.set(this,void 0),Qe.set(this,()=>{}),Re.set(this,()=>{}),ve.set(this,void 0),Ye.set(this,()=>{}),Ce.set(this,()=>{}),ae.set(this,{}),at.set(this,[]),Ee.set(this,!1),ot.set(this,!1),ct.set(this,!1),be.set(this,!1),I(this,Ge,new Promise((e,t)=>
9{I(this,Qe,e,"f"),I(this,Re,t,"f")})),I(this,ve,new Promise((e,t)=>{I(this,Ye,e,"f"),I(this,Ce,t,"f")})),c(this,Ge,"f").catch(()=>{}),c(this,ve,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},c(this,Ve,"m",Or).bind(this))},0)}_connected(){this.ended||(c(this,Qe,"f").call(this),this._emit("connect"))}get ended(){return c(this,Ee,"f")}get errored(){return c(this,ot,"f")}get aborted(){return c(this,ct,"f")}abort(){this.controller.abort()}_listenForAbort(e){if(!e||this.ended)return;if(e.aborted){this.controller.abort();return}const t=()=>this.controller.abort();e.addEventListener("abort",t,{once:!0}),c(this,at,"f").push({signal:e,listener:t})}on(e,t){return(c(this,ae,"f")[e]||(c(this,ae,"f")[e]=[])).push({listener:t}),this}off(e,t){const s=c(this,ae,"f")[e];if(!s)return this;const n=s.findIndex(i=>i.listener===t);return n>=0&&s.splice(n,1),this}once(e,t){return(c(this,ae,"f")[e]||(c(this,ae,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,s)=>{I(this,be,!0),e!=="error"&&this.once("error",s),this.once(e,t)})}async done(){I(this,be,!0),await c(this,ve,"f")}_emit(e,...t){if(c(this,Ee,"f"))return;e==="end"&&(c(this,Ve,"m",Er).call(this),I(this,Ee,!0),c(this,Ye,"f").call(this));const s=c(this,ae,"f")[e];if(s&&(c(this,ae,"f")[e]=s.filter(n=>!n.once),s.forEach(({listener:n})=>n(...t))),e==="abort"){const n=t[0];!c(this,be,"f")&&!s?.length&&Promise.reject(n),c(this,Re,"f").call(this,n),c(this,Ce,"f").call(this,n),this._emit("end");return}if(e==="error"){const n=t[0];!c(this,be,"f")&&!s?.length&&Promise.reject(n),c(this,Re,"f").call(this,n),c(this,Ce,"f").call(this,n),this._emit("end")}}_emitFinal(){}}Ge=new WeakMap,Qe=new WeakMap,Re=new WeakMap,ve=new WeakMap,Ye=new WeakMap,Ce=new WeakMap,ae=new WeakMap,at=new WeakMap,Ee=new WeakMap,ot=new WeakMap,ct=new WeakMap,be=new WeakMap,Ve=new WeakSet,Er=function(){for(const{signal:e,listener:t}of c(this,at,"f").splice(0))e.removeEventListener("abort",t)},Or=function(e){if(I(this,ot,!0),e instanceof Error&&e.name==="AbortError"&&(e=new Y),e instanceof Y)return I(this,ct,!0),this._emit("abort",e);if(e instanceof g)return this._emit("error",e);if(e instanceof Error){const t=new g(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new g(String(e)))};function ta(r){return typeof r.parse=="function"}var U,Ut,ut,Wt,qt,Ht,Tr,Kr;const sa=10;function ra(r){for(const e of r.choices)for(const t of e.message.tool_calls??[])t.id||(t.id=`call_${dt()}`)}class jr extends ts{constructor(){super(...arguments),U.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){ra(e),this._chatCompletions.push(e),this._emit("chatCompletion",e);const t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t){if(this._emit("message",e),Cr(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(it(e)&&e.tool_calls)for(const s of e.tool_calls)s.type==="function"&&this._emit("functionToolCall",s.function)}}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new g("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),c(this,U,"m",Ut).call(this)}async finalMessage(){return await this.done(),c(this,U,"m",ut).call(this)}async finalFunctionToolCall(){return await this.done(),c(this,U,"m",Wt).call(this)}async finalFunctionToolCallResult(){return await this.done(),c(this,U,"m",qt).call(this)}async totalUsage(){return await this.done(),c(this,U,"m",Ht).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=c(this,U,"m",ut).call(this);t&&this._emit("finalMessage",t);const s=c(this,U,"m",Ut).call(this);s&&this._emit("finalContent",s);const n=c(this,U,"m",Wt).call(this);n&&this._emit("finalFunctionToolCall",n);const i=c(this,U,"m",qt).call(this);i!=null&&this._emit("finalFunctionToolCallResult",i),this._chatCompletions.some(o=>o.usage)&&this._emit("totalUsage",c(this,U,"m",Ht).call(this))}async _createChatCompletion(e,t,s){this._listenForAbort(s?.signal),c(this,U,"m",Tr).call(this,t);
9const n=await e.chat.completions.create({...t,stream:!1},{...s,signal:this.controller.signal});return this._connected(),this._addChatCompletion(es(n,t))}async _runChatCompletion(e,t,s){for(const n of t.messages)this._addMessage(n,!1);return await this._createChatCompletion(e,t,s)}async _runTools(e,t,s,n){const i="tool",{tool_choice:o="auto",stream:u,..._}=t,l=typeof o!="string"&&o.type==="function"&&o?.function?.name,{maxChatCompletions:y=sa,afterCompletion:h}=n||{},m=t.tools.map(x=>{if(ze(x)){if(!x.$callback)throw new g("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:x.$callback,name:x.function.name,description:x.function.description||"",parameters:x.function.parameters,parse:x.$parseRaw,strict:!0}}}return x}),w={};for(const x of m)x.type==="function"&&(w[x.function.name||x.function.function.name]=x.function);const p="tools"in t?m.map(x=>x.type==="function"?{type:"function",function:{name:x.function.name||x.function.function.name,parameters:x.function.parameters,description:x.function.description,strict:x.function.strict}}:x):void 0;for(const x of t.messages)this._addMessage(x,!1);const b=async x=>{if(x.type!=="function")return{message:void 0,functionCalled:!1};const R=x.id,{name:A,arguments:k}=x.function,S=w[A];if(!S){const C=`Invalid tool_call: ${JSON.stringify(A)}. Available options are: ${Object.keys(w).map(E=>JSON.stringify(E)).join(", ")}. Please try again`;return{message:{role:i,tool_call_id:R,content:C},functionCalled:!1}}if(l&&l!==A){const C=`Invalid tool_call: ${JSON.stringify(A)}. ${JSON.stringify(l)} requested. Please try again`;return{message:{role:i,tool_call_id:R,content:C},functionCalled:!1}}let q;if(ta(S)){let C;try{C=await S.parse(k)}catch(E){const D=E instanceof Error?E.message:String(E);return{message:{role:i,tool_call_id:R,content:D},functionCalled:!1}}q=await S.function(C,s)}else q=await S.function(k,s);const M=c(this,U,"m",Kr).call(this,q);return{message:{role:i,tool_call_id:R,content:M},functionCalled:!0}};for(let x=0;x<y;++x){const R=await this._createChatCompletion(e,{..._,tool_choice:o,tools:p,messages:[...this.messages]},n),A=R.choices[0]?.message;if(!A)throw new g("missing message in ChatCompletion response");if(!A.tool_calls?.length){await h?.(R,s);return}if(l||t.parallel_tool_calls===!1)for(const k of A.tool_calls){const S=await b(k);if(S.message&&this._addMessage(S.message),l&&S.functionCalled){await h?.(R,s);return}}else{const k=await Promise.allSettled(A.tool_calls.map(b));for(const S of k)if(S.status==="rejected")throw S.reason;for(const S of k)S.status==="fulfilled"&&S.value.message&&this._addMessage(S.value.message)}await h?.(R,s)}}}U=new WeakSet,Ut=function(){return c(this,U,"m",ut).call(this).content??null},ut=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(it(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new g("stream ended without producing a ChatCompletionMessage with role=assistant")},Wt=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(it(t)&&t?.tool_calls?.length)for(let s=t.tool_calls.length-1;s>=0;s--){const n=t.tool_calls[s];if(n?.type==="function")return n.function}}},qt=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(Cr(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(s=>s.role==="assistant"&&s.tool_calls?.some(n=>n.type==="function"&&n.id===t.tool_call_id)))return t.content}},Ht=function(){const e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{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},Tr=function(e){if(e.n!=null&&e.n>1)throw new g("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Kr=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};class ss extends jr{static runTools(e,t,s){const n=new ss,i={...s,headers:{...s?.headers,"X-Stainless-Helper
9-Method":"runTools"}};return n._run(()=>n._runTools(e,t,n,i)),n}_addMessage(e,t=!0){super._addMessage(e,t),it(e)&&e.content&&this._emit("content",e.content)}}const Lr=1,Nr=2,Mr=4,Fr=8,zr=16,Br=32,Dr=64,Ur=128,Wr=256,qr=Ur|Wr,Hr=zr|Br|qr|Dr,Jr=Lr|Nr|Hr,Xr=Mr|Fr,na=Jr|Xr,N={STR:Lr,NUM:Nr,ARR:Mr,OBJ:Fr,NULL:zr,BOOL:Br,NAN:Dr,INFINITY:Ur,MINUS_INFINITY:Wr,INF:qr,SPECIAL:Hr,ATOM:Jr,COLLECTION:Xr,ALL:na};class ia extends Error{}class aa extends Error{}function oa(r,e=N.ALL){if(typeof r!="string")throw new TypeError(`expecting str, got ${typeof r}`);if(!r.trim())throw new Error(`${r} is empty`);return ca(r.trim(),e)}const ca=(r,e)=>{const t=r.length;let s=0;const n=m=>{throw new ia(`${m} at position ${s}`)},i=m=>{throw new aa(`${m} at position ${s}`)},o=()=>(h(),s>=t&&n("Unexpected end of input"),r[s]==='"'?u():r[s]==="{"?_():r[s]==="["?l():r.substring(s,s+4)==="null"||N.NULL&e&&t-s<4&&"null".startsWith(r.substring(s))?(s+=4,null):r.substring(s,s+4)==="true"||N.BOOL&e&&t-s<4&&"true".startsWith(r.substring(s))?(s+=4,!0):r.substring(s,s+5)==="false"||N.BOOL&e&&t-s<5&&"false".startsWith(r.substring(s))?(s+=5,!1):r.substring(s,s+8)==="Infinity"||N.INFINITY&e&&t-s<8&&"Infinity".startsWith(r.substring(s))?(s+=8,1/0):r.substring(s,s+9)==="-Infinity"||N.MINUS_INFINITY&e&&1<t-s&&t-s<9&&"-Infinity".startsWith(r.substring(s))?(s+=9,-1/0):r.substring(s,s+3)==="NaN"||N.NAN&e&&t-s<3&&"NaN".startsWith(r.substring(s))?(s+=3,NaN):y()),u=()=>{const m=s;let w=!1;for(s++;s<t&&(r[s]!=='"'||w&&r[s-1]==="\\");)w=r[s]==="\\"?!w:!1,s++;if(r.charAt(s)=='"')try{return JSON.parse(r.substring(m,++s-Number(w)))}catch(p){i(String(p))}else if(N.STR&e)try{return JSON.parse(r.substring(m,s-Number(w))+'"')}catch{return JSON.parse(r.substring(m,r.lastIndexOf("\\"))+'"')}n("Unterminated string literal")},_=()=>{s++,h();const m={};try{for(;r[s]!=="}";){if(h(),s>=t&&N.OBJ&e)return m;const w=u();h(),s++;try{const p=o();Object.defineProperty(m,w,{value:p,writable:!0,enumerable:!0,configurable:!0})}catch(p){if(N.OBJ&e)return m;throw p}h(),r[s]===","&&s++}}catch{if(N.OBJ&e)return m;n("Expected '}' at end of object")}return s++,m},l=()=>{s++;const m=[];try{for(;r[s]!=="]";)m.push(o()),h(),r[s]===","&&s++}catch{if(N.ARR&e)return m;n("Expected ']' at end of array")}return s++,m},y=()=>{if(s===0){r==="-"&&N.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(r)}catch(w){if(N.NUM&e)try{return r[r.length-1]==="."?JSON.parse(r.substring(0,r.lastIndexOf("."))):JSON.parse(r.substring(0,r.lastIndexOf("e")))}catch{}i(String(w))}}const m=s;for(r[s]==="-"&&s++;r[s]&&!",]}".includes(r[s]);)s++;s==t&&!(N.NUM&e)&&n("Unterminated number literal");try{return JSON.parse(r.substring(m,s))}catch{r.substring(m,s)==="-"&&N.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(r.substring(m,r.lastIndexOf("e")))}catch(p){i(String(p))}}},h=()=>{for(;s<t&&` 10\r `.includes(r[s]);)s++};return o()},Bs=r=>oa(r,N.ALL^N.NUM);var K,ie,ye,ce,Et,We,Ot,Tt,Kt,qe,jt,Ds;class Me extends jr{constructor(e){super(),K.add(this),ie.set(this,void 0),ye.set(this,void 0),ce.set(this,void 0),I(this,ie,e),I(this,ye,[])}get currentChatCompletionSnapshot(){return c(this,ce,"f")}static fromReadableStream(e){const t=new Me(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,s){const n=new Me(t);return n._run(()=>n._runChatCompletion(e,{...t,stream:!0},{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createChatCompletion(e,t,s){super._createChatCompletion,this._listenForAbort(s?.signal),c(this,K,"m",Et).call(this);const n=await e.chat.completions.create({...t,stream:!0},{...s,signal:this.controller.signal});this._connected();for await(const i of n)c(this,K,"m",Ot).call(this,i);if(n.controller.signal?.aborted)throw new Y;return this._addChatCompletion(c(this,K,"m",qe).call(this))}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),c(this,K,"m",Et).call(this),this._connected();const s=re.fromReadableStream(e,this.controller);let n;for await(const i of s)n&&n!==i.id&&this._addChatCompletion(c(this,K,"m",qe).call(this)),c(this,K,"m",Ot).call(this,i),n=i.id;if(s.controller.signal?.aborted)throw new Y;return this._addChatCompletion(c(this,K,"m",qe).call(this))}[(ie=new WeakMap,ye=new WeakMap,ce=new WeakMap,K=new WeakSet,Et=function(){this.ended||I(this,ce,void 0)},We=function(t){let s=c(this,ye,"f")[t.index];return s||(s={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},c(this,ye,"f")[t.index]=s,s)},Ot=function(t){if(this.ended)return;const s=c(this,K,"m",Ds).call(this,t);this._emit("chunk",t,s);for(const n of t.choices){const i=s.choices[n.index];
10n.delta.content!=null&&i.message?.role==="assistant"&&i.message?.content&&(this._emit("content",n.delta.content,i.message.content),this._emit("content.delta",{delta:n.delta.content,snapshot:i.message.content,parsed:i.message.parsed})),n.delta.refusal!=null&&i.message?.role==="assistant"&&i.message?.refusal&&this._emit("refusal.delta",{delta:n.delta.refusal,snapshot:i.message.refusal}),n.logprobs?.content!=null&&i.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:n.logprobs?.content,snapshot:i.logprobs?.content??[]}),n.logprobs?.refusal!=null&&i.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:n.logprobs?.refusal,snapshot:i.logprobs?.refusal??[]});const o=c(this,K,"m",We).call(this,i);i.finish_reason&&(c(this,K,"m",Kt).call(this,i),o.current_tool_call_index!=null&&c(this,K,"m",Tt).call(this,i,o.current_tool_call_index));for(const u of n.delta.tool_calls??[])o.current_tool_call_index!==u.index&&(c(this,K,"m",Kt).call(this,i),o.current_tool_call_index!=null&&c(this,K,"m",Tt).call(this,i,o.current_tool_call_index)),o.current_tool_call_index=u.index;for(const u of n.delta.tool_calls??[]){const _=i.message.tool_calls?.[u.index];_?.type&&(_?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:_.function?.name,index:u.index,arguments:_.function.arguments,parsed_arguments:_.function.parsed_arguments,arguments_delta:u.function?.arguments??""}):(_?.type,void 0))}}},Tt=function(t,s){if(c(this,K,"m",We).call(this,t).done_tool_calls.has(s))return;const i=t.message.tool_calls?.[s];if(!i)throw new Error("no tool call snapshot");if(!i.type)throw new Error("tool call snapshot missing `type`");if(i.type==="function"){const o=c(this,ie,"f")?.tools?.find(u=>nt(u)&&u.function.name===i.function.name);this._emit("tool_calls.function.arguments.done",{name:i.function.name,index:s,arguments:i.function.arguments,parsed_arguments:ze(o)?o.$parseRaw(i.function.arguments):o?.function.strict?JSON.parse(i.function.arguments):null})}else i.type},Kt=function(t){const s=c(this,K,"m",We).call(this,t);if(t.message.content&&!s.content_done){s.content_done=!0;const n=c(this,K,"m",jt).call(this);this._emit("content.done",{content:t.message.content,parsed:n?n.$parseRaw(t.message.content):null})}t.message.refusal&&!s.refusal_done&&(s.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal})),t.logprobs?.content&&!s.logprobs_content_done&&(s.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content})),t.logprobs?.refusal&&!s.logprobs_refusal_done&&(s.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},qe=function(){if(this.ended)throw new g("stream has ended, this shouldn't happen");const t=c(this,ce,"f");if(!t)throw new g("request ended without sending any chunks");return I(this,ce,void 0),I(this,ye,[]),ua(t,c(this,ie,"f"))},jt=function(){const t=c(this,ie,"f")?.response_format;return Zt(t)?t:null},Ds=function(t){var s,n,i,o;let u=c(this,ce,"f");const{choices:_,...l}=t;u?Object.assign(u,l):u=I(this,ce,{...l,choices:[]});for(const{delta:y,finish_reason:h,index:m,logprobs:w=null,...p}of t.choices){let b=u.choices[m];if(b||(b=u.choices[m]={finish_reason:h,index:m,message:{},logprobs:w,...p}),w)if(!b.logprobs)b.logprobs=Object.assign({},w);else{const{content:M,refusal:C,...E}=w;Object.assign(b.logprobs,E),M&&((s=b.logprobs).content??(s.content=[]),b.logprobs.content.push(...M)),C&&((n=b.logprobs).refusal??(n.refusal=[]),b.logprobs.refusal.push(...C))}if(h&&(b.finish_reason=h,c(this,ie,"f")&&Rr(c(this,ie,"f")))){if(h==="length")throw new cr;if(h==="content_filter")throw new ur}if(Object.assign(b,p),!y)continue;const{content:x,refusal:R,function_call:A,role:k,tool_calls:S,...q}=y;if(Object.assign(b.message,q),R&&(b.message.refusal=(b.message.refusal||"")+R),k&&(b.message.role=k),A&&(b.message.function_call?(A.name&&(b.message.function_call.name=A.name),A.arguments&&((i=b.message.function_call).arguments??(i.arguments=""),b.message.function_call.arguments+=A.arguments)):b.message.function_call=A),x&&(b.message.content=(b.message.content||"")+x,!b.message.refusal&&c(this,K,"m",jt).call(this)&&(b.message.parsed=b.message.content.trim()?Bs(b.message.content):null)),S){b.message.tool_calls||(b.message.tool_calls=[]);for(const{index:M,id:C,type:E,function:D,...O}of S){const T=(o=b.message.tool_calls)[M]??(o[M]={});Object.assign(T,O),C&&(T.id=C),E&&(T.type=E),D&&(T.function??(T.function={name:D.name??"",arguments:""})),D?.name&&(T.function.name=D.name),D?.arguments&&(T.function.arguments+=D.arguments,Zi(c(this,ie,"f"),T)&&(T.function.parsed_arguments=Bs(T.function.arguments)))}}}return u},Symbol.asyncIterator)](){const e=[],t=[];let s=!1;return this.on("chunk",n=>{const i=t.shift();i?i.resolve(n):e.push(n)}),this.on("end",()=>{s=!0;for(const n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{s=!0;for(const i of t)i.reject(n);t.length=0}),this.on("error",n=>{s=!0;for(const i of t)i.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((i,o)=>t.push({resolve:i,reject:o})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new re(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function ua(r,e){const{id:t,choices:s,created:n,model:i,system_fingerprint:o,...u}=r,_={...u,id:t,choices:s.map(({message:l,finish_reason:y,index:h,logprobs:m,...w})=>{if(!y)throw new g(`missing finish_reason for choice ${h}`);const{content:p=null,function_call:b,tool_calls:x,...R}=l,A=l.role;if(!A)throw new g(`missing role for choice ${h}`);
10if(b){const{arguments:k,name:S}=b;if(k==null)throw new g(`missing function_call.arguments for choice ${h}`);if(!S)throw new g(`missing function_call.name for choice ${h}`);return{...w,message:{content:p,function_call:{arguments:k,name:S},role:A,refusal:l.refusal??null},finish_reason:y,index:h,logprobs:m}}return x?{...w,index:h,finish_reason:y,logprobs:m,message:{...R,role:A,content:p,refusal:l.refusal??null,tool_calls:x.map((k,S)=>{const{function:q,type:M,id:C,...E}=k,{arguments:D,name:O,...T}=q||{};if(M==null)throw new g(`missing choices[${h}].tool_calls[${S}].type 11${Lt(r)}`);if(O==null)throw new g(`missing choices[${h}].tool_calls[${S}].function.name 12${Lt(r)}`);if(D==null)throw new g(`missing choices[${h}].tool_calls[${S}].function.arguments 13${Lt(r)}`);return{...E,id:C||`call_${dt()}`,type:M,function:{...T,name:O,arguments:D}}})}}:{...w,message:{...R,content:p,role:A,refusal:l.refusal??null},finish_reason:y,index:h,logprobs:m}}),created:n,model:i,object:"chat.completion",...o?{system_fingerprint:o}:{}};return Gi(_,e)}function Lt(r){return JSON.stringify(r)}class lt extends Me{static fromReadableStream(e){const t=new lt(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,s){const n=new lt(t),i={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,t,n,i)),n}}let rs=class extends d{constructor(){super(...arguments),this.messages=new kr(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(a`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,s){return this._client.post(a`/chat/completions/${e}`,{body:t,...s,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/chat/completions",v,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(a`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}parse(e,t){return ea(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(s=>es(s,e))}runTools(e,t){return e.stream?lt.runTools(this._client,e,t):ss.runTools(this._client,e,t)}stream(e,t){return Me.createChatCompletion(this._client,e,t)}};rs.Messages=kr;class ns extends d{constructor(){super(...arguments),this.completions=new rs(this._client)}}ns.Completions=rs;class Vr extends d{create(e,t){return this._client.post("/organization/admin_api_keys",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(a`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/admin_api_keys",v,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(a`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}}class Gr extends d{list(e={},t){return this._client.getAPIList("/organization/audit_logs",B,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}}let Qr=class extends d{create(e,t){return this._client.post("/organization/certificates",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},s){return this._client.get(a`/organization/certificates/${e}`,{query:t,...s,__security:{adminAPIKeyAuth:!0}})}update(e,t,s){return this._client.post(a`/organization/certificates/${e}`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/certificates",B,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(a`/organization/certificates/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}activate(e,t){return this._client.getAPIList("/organization/certificates/activate",le,{body:e,method:"post",...t,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t){return this._client.getAPIList("/organization/certificates/deactivate",le,{body:e,method:"post",...t,__security:{adminAPIKeyAuth:!0}})}},Yr=class extends d{retrieve(e){return this._client.get("/organization/data_retention",{...e,__security:{adminAPIKeyAuth:!0}})}update(e,t){return this._client.post("/organization/data_retention",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}};class Zr extends d{create(e,t){return this._client.post("/organization/invites",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(a`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/invites",B,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(a`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}}let en=class extends d{create(e,t){return this._client.post("/organization/roles",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(a`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}
13update(e,t,s){return this._client.post(a`/organization/roles/${e}`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/roles",oe,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(a`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},tn=class extends d{create(e,t){return this._client.post("/organization/spend_alerts",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(a`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,s){return this._client.post(a`/organization/spend_alerts/${e}`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/spend_alerts",B,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(a`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};class sn extends d{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}})}}let rn=class extends d{create(e,t,s){return this._client.post(a`/organization/groups/${e}/roles`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,s){const{group_id:n}=t;return this._client.get(a`/organization/groups/${n}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}list(e,t={},s){return this._client.getAPIList(a`/organization/groups/${e}/roles`,oe,{query:t,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,t,s){const{group_id:n}=t;return this._client.delete(a`/organization/groups/${n}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}},nn=class extends d{create(e,t,s){return this._client.post(a`/organization/groups/${e}/users`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,s){const{group_id:n}=t;return this._client.get(a`/organization/groups/${n}/users/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}list(e,t={},s){return this._client.getAPIList(a`/organization/groups/${e}/users`,oe,{query:t,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,t,s){const{group_id:n}=t;return this._client.delete(a`/organization/groups/${n}/users/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}},gt=class extends d{constructor(){super(...arguments),this.users=new nn(this._client),this.roles=new rn(this._client)}create(e,t){return this._client.post("/organization/groups",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(a`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,s){return this._client.post(a`/organization/groups/${e}`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/groups",oe,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(a`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};gt.Users=nn;gt.Roles=rn;
13class an extends d{retrieve(e,t,s){const{project_id:n}=t;return this._client.get(a`/organization/projects/${n}/api_keys/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}list(e,t={},s){return this._client.getAPIList(a`/organization/projects/${e}/api_keys`,B,{query:t,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,t,s){const{project_id:n}=t;return this._client.delete(a`/organization/projects/${n}/api_keys/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}}class on extends d{list(e,t={},s){return this._client.getAPIList(a`/organization/projects/${e}/certificates`,B,{query:t,...s,__security:{adminAPIKeyAuth:!0}})}activate(e,t,s){return this._client.getAPIList(a`/organization/projects/${e}/certificates/activate`,le,{body:t,method:"post",...s,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t,s){return this._client.getAPIList(a`/organization/projects/${e}/certificates/deactivate`,le,{body:t,method:"post",...s,__security:{adminAPIKeyAuth:!0}})}}class cn extends d{retrieve(e,t){return this._client.get(a`/organization/projects/${e}/data_retention`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,s){return this._client.post(a`/organization/projects/${e}/data_retention`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}}class un extends d{retrieve(e,t){return this._client.get(a`/organization/projects/${e}/hosted_tool_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,s){return this._client.post(a`/organization/projects/${e}/hosted_tool_permissions`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}}class ln extends d{retrieve(e,t){return this._client.get(a`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,s){return this._client.post(a`/organization/projects/${e}/model_permissions`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(a`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}}class hn extends d{listRateLimits(e,t={},s){return this._client.getAPIList(a`/organization/projects/${e}/rate_limits`,B,{query:t,...s,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,t,s){const{project_id:n,...i}=t;return this._client.post(a`/organization/projects/${n}/rate_limits/${e}`,{body:i,...s,__security:{adminAPIKeyAuth:!0}})}}let dn=class extends d{create(e,t,s){return this._client.post(a`/projects/${e}/roles`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,s){const{project_id:n}=t;return this._client.get(a`/projects/${n}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}update(e,t,s){const{project_id:n,...i}=t;return this._client.post(a`/projects/${n}/roles/${e}`,{body:i,...s,__security:{adminAPIKeyAuth:!0}})}list(e,t={},s){return this._client.getAPIList(a`/projects/${e}/roles`,oe,{query:t,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,t,s){const{project_id:n}=t;return this._client.delete(a`/projects/${n}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}};class _n extends d{create(e,t,s){return this._client.post(a`/organization/projects/${e}/service_accounts`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,s){const{project_id:n}=t;return this._client.get(a`/organization/projects/${n}/service_accounts/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}update(e,t,s){const{project_id:n,...i}=t;return this._client.post(a`/organization/projects/${n}/service_accounts/${e}`,{body:i,...s,__security:{adminAPIKeyAuth:!0}})}list(e,t={},s){return this._client.getAPIList(a`/organization/projects/${e}/service_accounts`,B,{query:t,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,t,s){const{project_id:n}=t;return this._client.delete(a`/organization/projects/${n}/service_accounts/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}}class fn extends d{create(e,t,s){return this._client.post(a`/organization/projects/${e}/spend_alerts`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,s){const{project_id:n}=t;return this._client.get(a`/organization/projects/${n}/spend_alerts/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}update(e,t,s){const{project_id:n,...i}=t;return this._client.post(a`/organization/projects/${n}/spend_alerts/${e}`,{body:i,...s,__security:{adminAPIKeyAuth:!0}})}list(e,t={},s){return this._client.getAPIList(a`/organization/projects/${e}/spend_alerts`,B,{query:t,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,t,s){const{project_id:n}=t;return this._client.delete(a`/organization/projects/${n}/spend_alerts/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}}
13let pn=class extends d{create(e,t,s){const{project_id:n,...i}=t;return this._client.post(a`/projects/${n}/groups/${e}/roles`,{body:i,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,s){const{project_id:n,group_id:i}=t;return this._client.get(a`/projects/${n}/groups/${i}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}list(e,t,s){const{project_id:n,...i}=t;return this._client.getAPIList(a`/projects/${n}/groups/${e}/roles`,oe,{query:i,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,t,s){const{project_id:n,group_id:i}=t;return this._client.delete(a`/projects/${n}/groups/${i}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}};class is extends d{constructor(){super(...arguments),this.roles=new pn(this._client)}create(e,t,s){return this._client.post(a`/organization/projects/${e}/groups`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,s){const{project_id:n,...i}=t;return this._client.get(a`/organization/projects/${n}/groups/${e}`,{query:i,...s,__security:{adminAPIKeyAuth:!0}})}list(e,t={},s){return this._client.getAPIList(a`/organization/projects/${e}/groups`,oe,{query:t,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,t,s){const{project_id:n}=t;return this._client.delete(a`/organization/projects/${n}/groups/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}}is.Roles=pn;let mn=class extends d{create(e,t,s){const{project_id:n,...i}=t;return this._client.post(a`/projects/${n}/users/${e}/roles`,{body:i,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,s){const{project_id:n,user_id:i}=t;return this._client.get(a`/projects/${n}/users/${i}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}list(e,t,s){const{project_id:n,...i}=t;return this._client.getAPIList(a`/projects/${n}/users/${e}/roles`,oe,{query:i,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,t,s){const{project_id:n,user_id:i}=t;return this._client.delete(a`/projects/${n}/users/${i}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}},as=class extends d{constructor(){super(...arguments),this.roles=new mn(this._client)}
13create(e,t,s){return this._client.post(a`/organization/projects/${e}/users`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,s){const{project_id:n}=t;return this._client.get(a`/organization/projects/${n}/users/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}update(e,t,s){const{project_id:n,...i}=t;return this._client.post(a`/organization/projects/${n}/users/${e}`,{body:i,...s,__security:{adminAPIKeyAuth:!0}})}list(e,t={},s){return this._client.getAPIList(a`/organization/projects/${e}/users`,B,{query:t,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,t,s){const{project_id:n}=t;return this._client.delete(a`/organization/projects/${n}/users/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}};as.Roles=mn;class V extends d{constructor(){super(...arguments),this.users=new as(this._client),this.serviceAccounts=new _n(this._client),this.apiKeys=new an(this._client),this.rateLimits=new hn(this._client),this.modelPermissions=new ln(this._client),this.hostedToolPermissions=new un(this._client),this.groups=new is(this._client),this.roles=new dn(this._client),this.dataRetention=new cn(this._client),this.spendAlerts=new fn(this._client),this.certificates=new on(this._client)}create(e,t){return this._client.post("/organization/projects",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(a`/organization/projects/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,s){return this._client.post(a`/organization/projects/${e}`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/projects",B,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}archive(e,t){return this._client.post(a`/organization/projects/${e}/archive`,{...t,__security:{adminAPIKeyAuth:!0}})}}V.Users=as;V.ServiceAccounts=_n;V.APIKeys=an;V.RateLimits=hn;V.ModelPermissions=ln;V.HostedToolPermissions=un;V.Groups=is;V.Roles=dn;V.DataRetention=cn;V.SpendAlerts=fn;V.Certificates=on;class yn extends d{create(e,t,s){return this._client.post(a`/organization/users/${e}/roles`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,s){const{user_id:n}=t;return this._client.get(a`/organization/users/${n}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}list(e,t={},s){return this._client.getAPIList(a`/organization/users/${e}/roles`,oe,{query:t,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,t,s){const{user_id:n}=t;return this._client.delete(a`/organization/users/${n}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}}class os extends d{constructor(){super(...arguments),this.roles=new yn(this._client)}retrieve(e,t){return this._client.get(a`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,s){return this._client.post(a`/organization/users/${e}`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/users",B,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(a`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}}os.Roles=yn;class G extends d{constructor(){super(...arguments),this.auditLogs=new Gr(this._client),this.adminAPIKeys=new Vr(this._client),this.usage=new sn(this._client),this.invites=new Zr(this._client),this.users=new os(this._client),this.groups=new gt(this._client),this.roles=new en(this._client),this.dataRetention=new Yr(this._client),this.spendAlerts=new tn(this._client),this.certificates=new Qr(this._client),this.projects=new V(this._client)}}G.AuditLogs=Gr;G.AdminAPIKeys=Vr;G.Usage=sn;G.Invites=Zr;G.Users=os;G.Groups=gt;G.Roles=en;G.DataRetention=Yr;G.SpendAlerts=tn;G.Certificates=Qr;G.Projects=V;class cs extends d{constructor(){super(...arguments),this.organization=new G(this._client)}}cs.Organization=G;const gn=Symbol("brand.privateNullableHeaders");function*la(r){if(!r)return;if(gn in r){const{values:s,nulls:n}=r;yield*s.entries();for(const i of n)yield[i,null];return}let e=!1,t;r instanceof Headers?t=r.entries():Ps(r)?t=r:(e=!0,t=Object.entries(r??{}));for(let s of t){const n=s[0];if(typeof n!="string")throw new TypeError("expected header name to be a string");const i=Ps(s[1])?s[1]:[s[1]];let o=!1;for(const u of i)u!==void 0&&(e&&!o&&(o=!0,yield[n,null]),yield[n,u])}}const f=r=>{const e=new Headers,t=new Set;for(const s of r){const n=new Set;for(const[i,o]of la(s)){const u=i.toLowerCase();n.has(u)||(e.delete(i),n.add(u)),o===null?(e.delete(i),t.add(u)):(e.append(i,o),t.delete(u))}}return{[gn]:!0,values:e,nulls:t}};class bn extends d{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:f([{Accept:"application/octet-stream"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}class An extends d{create(e,t){return this._client.post("/audio/transcriptions",ne({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}}class wn extends d{create(e,t){return this._client.post("/audio/translations",ne({body:e,...t,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}}class Be extends d{constructor(){super(...arguments),this.transcriptions=new An(this._client),this.translations=new wn(this._client),this.speech=new bn(this._client)}}Be.Transcriptions=An;Be.Translations=wn;Be.Speech=bn;class xn extends d{create(e,t){return this._client.post("/batches",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(a`/batches/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/batches",v,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(a`/batches/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}}class In extends d{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:f([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(a`/assistants/${e}`,{...t,headers:f([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}
13update(e,t,s){return this._client.post(a`/assistants/${e}`,{body:t,...s,headers:f([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/assistants",v,{query:e,...t,headers:f([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(a`/assistants/${e}`,{...t,headers:f([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}}let $n=class extends d{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:f([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}};class Pn extends d{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:f([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}}let bt=class extends d{constructor(){super(...arguments),this.sessions=new $n(this._client),this.transcriptionSessions=new Pn(this._client)}};bt.Sessions=$n;bt.TranscriptionSessions=Pn;class Sn extends d{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:f([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(a`/chatkit/sessions/${e}/cancel`,{...t,headers:f([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}}let kn=class extends d{retrieve(e,t){return this._client.get(a`/chatkit/threads/${e}`,{...t,headers:f([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/chatkit/threads",B,{query:e,...t,headers:f([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(a`/chatkit/threads/${e}`,{...t,headers:f([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}listItems(e,t={},s){return this._client.getAPIList(a`/chatkit/threads/${e}/items`,B,{query:t,...s,headers:f([{"OpenAI-Beta":"chatkit_beta=v1"},s?.headers]),__security:{bearerAuth:!0}})}};class At extends d{constructor(){super(...arguments),this.sessions=new Sn(this._client),this.threads=new kn(this._client)}}At.Sessions=Sn;At.Threads=kn;let Rn=class extends d{list(e,t={},s){const{betas:n,...i}=t??{};return this._client.getAPIList(a`/responses/${e}/input_items?beta=true`,v,{query:i,...s,headers:f([{...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},s?.headers]),__security:{bearerAuth:!0}})}},vn=class extends d{count(e={},t){const{betas:s,...n}=e??{};return this._client.post("/responses/input_tokens?beta=true",{body:n,...t,headers:f([{...s?.toString()!=null?{"openai-beta":s?.toString()}:void 0},t?.headers]),__security:{bearerAuth:!0}})}},wt=class extends d{constructor(){super(...arguments),this.inputItems=new Rn(this._client),this.inputTokens=new vn(this._client)}create(e,t){const{betas:s,...n}=e;return this._client.post("/responses?beta=true",{body:n,...t,headers:f([{...s?.toString()!=null?{"openai-beta":s?.toString()}:void 0},t?.headers]),stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,t={},s){const{betas:n,...i}=t??{};return this._client.get(a`/responses/${e}?beta=true`,{query:i,...s,headers:f([{...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},s?.headers]),stream:t?.stream??!1,__security:{bearerAuth:!0}})}delete(e,t={},s){const{betas:n}=t??{};return this._client.delete(a`/responses/${e}?beta=true`,{...s,headers:f([{Accept:"*/*",...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},s?.headers]),__security:{bearerAuth:!0}})}cancel(e,t={},s){const{betas:n}=t??{};return this._client.post(a`/responses/${e}/cancel?beta=true`,{...s,headers:f([{...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},s?.headers]),__security:{bearerAuth:!0}})}compact(e,t){const{betas:s,...n}=e;return this._client.post("/responses/compact?beta=true",{body:n,...t,headers:f([{...s?.toString()!=null?{"openai-beta":s?.toString()}:void 0},t?.headers]),__security:{bearerAuth:!0}})}};wt.InputItems=Rn;wt.InputTokens=vn;class Cn extends d{create(e,t,s){return this._client.post(a`/threads/${e}/messages`,{body:t,...s,headers:f([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}
13retrieve(e,t,s){const{thread_id:n}=t;return this._client.get(a`/threads/${n}/messages/${e}`,{...s,headers:f([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}update(e,t,s){const{thread_id:n,...i}=t;return this._client.post(a`/threads/${n}/messages/${e}`,{body:i,...s,headers:f([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}list(e,t={},s){return this._client.getAPIList(a`/threads/${e}/messages`,v,{query:t,...s,headers:f([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}delete(e,t,s){const{thread_id:n}=t;return this._client.delete(a`/threads/${n}/messages/${e}`,{...s,headers:f([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}}class En extends d{retrieve(e,t,s){const{thread_id:n,run_id:i,...o}=t;return this._client.get(a`/threads/${n}/runs/${i}/steps/${e}`,{query:o,...s,headers:f([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}list(e,t,s){const{thread_id:n,...i}=t;return this._client.getAPIList(a`/threads/${n}/runs/${e}/steps`,v,{query:i,...s,headers:f([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}}const ha=r=>{if(typeof Buffer<"u"){const e=Buffer.from(r,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{const e=atob(r),t=e.length,s=new Uint8Array(t);for(let n=0;n<t;n++)s[n]=e.charCodeAt(n);return Array.from(new Float32Array(s.buffer))}};var da={};const ue=r=>{if(typeof globalThis.process<"u")return da?.[r]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(r)?.trim()||void 0};var z,fe,Jt,te,Ze,Z,pe,we,_e,ht,X,et,tt,Le,Oe,Te,Us,Ws,qs,Hs,Js,Xs,Vs;class Ne extends ts{constructor(){super(...arguments),z.add(this),Jt.set(this,[]),te.set(this,{}),Ze.set(this,{}),Z.set(this,void 0),pe.set(this,void 0),we.set(this,void 0),_e.set(this,void 0),ht.set(this,void 0),X.set(this,void 0),et.set(this,void 0),tt.set(this,void 0),Le.set(this,void 0)}[(Jt=new WeakMap,te=new WeakMap,Ze=new WeakMap,Z=new WeakMap,pe=new WeakMap,we=new WeakMap,_e=new WeakMap,ht=new WeakMap,X=new WeakMap,et=new WeakMap,tt=new WeakMap,Le=new WeakMap,z=new WeakSet,Symbol.asyncIterator)](){const e=[],t=[];let s=!1;return this.on("event",n=>{const i=t.shift();i?i.resolve(n):e.push(n)}),this.on("end",()=>{s=!0;for(const n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{s=!0;for(const i of t)i.reject(n);t.length=0}),this.on("error",n=>{s=!0;for(const i of t)i.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((i,o)=>t.push({resolve:i,reject:o})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){const t=new fe;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),this._connected();const s=re.fromReadableStream(e,this.controller);for await(const n of s)c(this,z,"m",Oe).call(this,n);if(s.controller.signal?.aborted)throw new Y;return this._addRun(c(this,z,"m",Te).call(this))}toReadableStream(){return new re(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,s,n){const i=new fe;return i._run(()=>i._runToolAssistantStream(e,t,s,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),i}async _createToolAssistantStream(e,t,s,n){this._listenForAbort(n?.signal);const i={...s,stream:!0},o=await e.submitToolOutputs(t,i,{...n,signal:this.controller.signal});this._connected();for await(const u of o)c(this,z,"m",Oe).call(this,u);if(o.controller.signal?.aborted)throw new Y;return this._addRun(c(this,z,"m",Te).call(this))}static createThreadAssistantStream(e,t,s){const n=new fe;return n._run(()=>n._threadAssistantStream(e,t,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),n}static createAssistantStream(e,t,s,n){const i=new fe;return i._run(()=>i._runAssistantStream(e,t,s,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),i}currentEvent(){return c(this,et,"f")}currentRun(){return c(this,tt,"f")}currentMessageSnapshot(){return c(this,Z,"f")}currentRunStepSnapshot(){return c(this,Le,"f")}async finalRunSteps(){return await this.done(),Object.values(c(this,te,"f"))}async finalMessages(){return await this.done(),Object.values(c(this,Ze,"f"))}async finalRun(){if(await this.done(),!c(this,pe,"f"))throw Error("Final run was not received.");return c(this,pe,"f")}async _createThreadAssistantStream(e,t,s){this._listenForAbort(s?.signal);const n={...t,stream:!0},i=await e.createAndRun(n,{...s,signal:this.controller.signal});this._connected();for await(const o of i)c(this,z,"m",Oe).call(this,o);if(i.controller.signal?.aborted)throw new Y;return this._addRun(c(this,z,"m",Te).call(this))}async _createAssistantStream(e,t,s,n){this._listenForAbort(n?.signal);const i={...s,stream:!0},o=await e.create(t,i,{...n,signal:this.controller.signal});this._connected();for await(const u of o)c(this,z,"m",Oe).call(this,u);if(o.controller.signal?.aborted)throw new Y;return this._addRun(c(this,z,"m",Te).call(this))}static accumulateDelta(e,t){for(const[s,n]of Object.entries(t)){if(!e.hasOwnProperty(s)){e[s]=n;continue}let i=e[s];if(i==null){e[s]=n;continue}if(s==="index"||s==="type"){e[s]=n;continue}if(typeof i=="string"&&typeof n=="string")i+=n;else if(typeof i=="number"&&typeof n=="number")i+=n;else if(Rt(i)&&Rt(n))i=this.accumulateDelta(i,n);else if(Array.isArray(i)&&Array.isArray(n)){if(i.every(o=>
13typeof o=="string"||typeof o=="number")){i.push(...n);continue}for(const o of n){if(!Rt(o))throw new Error(`Expected array delta entry to be an object but got: ${o}`);const u=o.index;if(u==null)throw console.error(o),new Error("Expected array delta entry to have an `index` property");if(typeof u!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${u}`);const _=i[u];_==null?i[u]=o:i[u]=this.accumulateDelta(_,o)}continue}else throw Error(`Unhandled record type: ${s}, deltaValue: ${n}, accValue: ${i}`);e[s]=i}return e}_addRun(e){return e}async _threadAssistantStream(e,t,s){return await this._createThreadAssistantStream(t,e,s)}async _runAssistantStream(e,t,s,n){return await this._createAssistantStream(t,e,s,n)}async _runToolAssistantStream(e,t,s,n){return await this._createToolAssistantStream(t,e,s,n)}}fe=Ne,Oe=function(e){if(!this.ended)switch(I(this,et,e),c(this,z,"m",qs).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":c(this,z,"m",Vs).call(this,e);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":c(this,z,"m",Ws).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":c(this,z,"m",Us).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},Te=function(){if(this.ended)throw new g("stream has ended, this shouldn't happen");if(!c(this,pe,"f"))throw Error("Final run has not been received");return c(this,pe,"f")},Us=function(e){const[t,s]=c(this,z,"m",Js).call(this,e,c(this,Z,"f"));I(this,Z,t),c(this,Ze,"f")[t.id]=t;for(const n of s){const i=t.content[n.index];i?.type=="text"&&this._emit("textCreated",i.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(const n of e.data.delta.content){if(n.type=="text"&&n.text){let i=n.text,o=t.content[n.index];if(o&&o.type=="text")this._emit("textDelta",i,o.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(n.index!=c(this,we,"f")){if(c(this,_e,"f"))switch(c(this,_e,"f").type){case"text":this._emit("textDone",c(this,_e,"f").text,c(this,Z,"f"));break;case"image_file":this._emit("imageFileDone",c(this,_e,"f").image_file,c(this,Z,"f"));break}I(this,we,n.index)}I(this,_e,t.content[n.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(c(this,we,"f")!==void 0){const n=e.data.content[c(this,we,"f")];if(n)switch(n.type){case"image_file":this._emit("imageFileDone",n.image_file,c(this,Z,"f"));break;case"text":this._emit("textDone",n.text,c(this,Z,"f"));break}}c(this,Z,"f")&&this._emit("messageDone",e.data),I(this,Z,void 0)}},Ws=function(e){const t=c(this,z,"m",Hs).call(this,e);switch(I(this,Le,t),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":const s=e.data.delta;if(s.step_details&&s.step_details.type=="tool_calls"&&s.step_details.tool_calls&&t.step_details.type=="tool_calls")for(const i of s.step_details.tool_calls)i.index==c(this,ht,"f")?this._emit("toolCallDelta",i,t.step_details.tool_calls[i.index]):(c(this,X,"f")&&this._emit("toolCallDone",c(this,X,"f")),I(this,ht,i.index),I(this,X,t.step_details.tool_calls[i.index]),c(this,X,"f")&&this._emit("toolCallCreated",c(this,X,"f")));this._emit("runStepDelta",e.data.delta,t);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":I(this,Le,void 0),e.data.step_details.type=="tool_calls"&&c(this,X,"f")&&(this._emit("toolCallDone",c(this,X,"f")),I(this,X,void 0)),this._emit("runStepDone",e.data,t);break}},qs=function(e){c(this,Jt,"f").push(e),this._emit("event",e)},Hs=function(e){switch(e.event){case"thread.run.step.created":return c(this,te,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=c(this,te,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let s=e.data;if(s.delta){const n=fe.accumulateDelta(t,s.delta);c(this,te,"f")[e.data.id]=n}return c(this,te,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":c(this,te,"f")[e.data.id]=e.data;break}if(c(this,te,"f")[e.data.id])return c(this,te,"f")[e.data.id];throw new Error("No snapshot available")},Js=function(e,t){let s=[];switch(e.event){case"thread.message.created":return[e.data,s];case"thread.message.delta":if(!t)throw Error("Received a delta with
13no existing snapshot (there should be one from message creation)");let n=e.data;if(n.delta.content)for(const i of n.delta.content)if(i.index in t.content){let o=t.content[i.index];t.content[i.index]=c(this,z,"m",Xs).call(this,i,o)}else t.content[i.index]=i,s.push(i);return[t,s];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,s];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Xs=function(e,t){return fe.accumulateDelta(t,e)},Vs=function(e){switch(I(this,tt,e.data),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":I(this,pe,e.data),c(this,X,"f")&&(this._emit("toolCallDone",c(this,X,"f")),I(this,X,void 0));break}};let us=class extends d{constructor(){super(...arguments),this.steps=new En(this._client)}
13create(e,t,s){const{include:n,...i}=t;return this._client.post(a`/threads/${e}/runs`,{query:{include:n},body:i,...s,headers:f([{"OpenAI-Beta":"assistants=v2"},s?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve(e,t,s){const{thread_id:n}=t;return this._client.get(a`/threads/${n}/runs/${e}`,{...s,headers:f([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}update(e,t,s){const{thread_id:n,...i}=t;return this._client.post(a`/threads/${n}/runs/${e}`,{body:i,...s,headers:f([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}list(e,t={},s){return this._client.getAPIList(a`/threads/${e}/runs`,v,{query:t,...s,headers:f([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,s){const{thread_id:n}=t;return this._client.post(a`/threads/${n}/runs/${e}/cancel`,{...s,headers:f([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,s){const n=await this.create(e,t,s);return await this.poll(n.id,{thread_id:e},s)}createAndStream(e,t,s){return Ne.createAssistantStream(e,this._client.beta.threads.runs,t,s)}async poll(e,t,s){const n=f([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:i,response:o}=await this.retrieve(e,t,{...s,headers:{...s?.headers,...n}}).withResponse();switch(i.status){case"queued":case"in_progress":case"cancelling":let u=5e3;if(s?.pollIntervalMs)u=s.pollIntervalMs;else{const _=o.headers.get("openai-poll-after-ms");if(_){const l=parseInt(_);isNaN(l)||(u=l)}}await Fe(u);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return i}}}stream(e,t,s){return Ne.createAssistantStream(e,this._client.beta.threads.runs,t,s)}submitToolOutputs(e,t,s){const{thread_id:n,...i}=t;return this._client.post(a`/threads/${n}/runs/${e}/submit_tool_outputs`,{body:i,...s,headers:f([{"OpenAI-Beta":"assistants=v2"},s?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async submitToolOutputsAndPoll(e,t,s){const n=await this.submitToolOutputs(e,t,s);return await this.poll(n.id,t,s)}submitToolOutputsStream(e,t,s){return Ne.createToolAssistantStream(e,this._client.beta.threads.runs,t,s)}};us.Steps=En;class xt extends d{constructor(){super(...arguments),this.runs=new us(this._client),this.messages=new Cn(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:f([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(a`/threads/${e}`,{...t,headers:f([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,s){return this._client.post(a`/threads/${e}`,{body:t,...s,headers:f([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(a`/threads/${e}`,{...t,headers:f([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:f([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async createAndRunPoll(e,t){const s=await this.createAndRun(e,t);return await this.runs.poll(s.id,{thread_id:s.thread_id},t)}createAndRunStream(e,t){return Ne.createThreadAssistantStream(e,this._client.beta.threads,t)}}xt.Runs=us;xt.Messages=Cn;class me extends d{constructor(){super(...arguments),this.realtime=new bt(this._client),this.responses=new wt(this._client),this.chatkit=new At(this._client),this.assistants=new In(this._client),this.threads=new xt(this._client)}}me.Realtime=bt;me.Responses=wt;me.ChatKit=At;me.Assistants=In;me.Threads=xt;class On extends d{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}}let Tn=class extends d{retrieve(e,t,s){const{container_id:n}=t;return this._client.get(a`/containers/${n}/files/${e}/content`,{...s,headers:f([{Accept:"application/binary"},s?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},ls=class extends d{constructor(){super(...arguments),this.content=new Tn(this._client)}
13create(e,t,s){return this._client.post(a`/containers/${e}/files`,yt({body:t,...s,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,s){const{container_id:n}=t;return this._client.get(a`/containers/${n}/files/${e}`,{...s,__security:{bearerAuth:!0}})}list(e,t={},s){return this._client.getAPIList(a`/containers/${e}/files`,v,{query:t,...s,__security:{bearerAuth:!0}})}delete(e,t,s){const{container_id:n}=t;return this._client.delete(a`/containers/${n}/files/${e}`,{...s,headers:f([{Accept:"*/*"},s?.headers]),__security:{bearerAuth:!0}})}};ls.Content=Tn;class hs extends d{constructor(){super(...arguments),this.files=new ls(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(a`/containers/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/containers",v,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(a`/containers/${e}`,{...t,headers:f([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}}hs.Files=ls;class Kn extends d{create(e,t,s){const{include:n,...i}=t;return this._client.post(a`/conversations/${e}/items`,{query:{include:n},body:i,...s,__security:{bearerAuth:!0}})}retrieve(e,t,s){const{conversation_id:n,...i}=t;return this._client.get(a`/conversations/${n}/items/${e}`,{query:i,...s,__security:{bearerAuth:!0}})}list(e,t={},s){return this._client.getAPIList(a`/conversations/${e}/items`,B,{query:t,...s,__security:{bearerAuth:!0}})}delete(e,t,s){const{conversation_id:n}=t;return this._client.delete(a`/conversations/${n}/items/${e}`,{...s,__security:{bearerAuth:!0}})}}class ds extends d{constructor(){super(...arguments),this.items=new Kn(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(a`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,s){return this._client.post(a`/conversations/${e}`,{body:t,...s,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(a`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}}ds.Items=Kn;class jn extends d{create(e,t){const s=!!e.encoding_format;let n=s?e.encoding_format:"base64";s&&F(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);const i=this._client.post("/embeddings",{body:{...e,encoding_format:n},...t,__security:{bearerAuth:!0}});return s?i:(F(this._client).debug("embeddings/decoding base64 embeddings from base64"),i._thenUnwrap(o=>(o&&o.data&&o.data.forEach(u=>{const _=u.embedding;u.embedding=ha(_)}),o)))}}class Ln extends d{retrieve(e,t,s){const{eval_id:n,run_id:i}=t;return this._client.get(a`/evals/${n}/runs/${i}/output_items/${e}`,{...s,__security:{bearerAuth:!0}})}list(e,t,s){const{eval_id:n,...i}=t;return this._client.getAPIList(a`/evals/${n}/runs/${e}/output_items`,v,{query:i,...s,__security:{bearerAuth:!0}})}}class _s extends d{constructor(){super(...arguments),this.outputItems=new Ln(this._client)}
13create(e,t,s){return this._client.post(a`/evals/${e}/runs`,{body:t,...s,__security:{bearerAuth:!0}})}retrieve(e,t,s){const{eval_id:n}=t;return this._client.get(a`/evals/${n}/runs/${e}`,{...s,__security:{bearerAuth:!0}})}list(e,t={},s){return this._client.getAPIList(a`/evals/${e}/runs`,v,{query:t,...s,__security:{bearerAuth:!0}})}delete(e,t,s){const{eval_id:n}=t;return this._client.delete(a`/evals/${n}/runs/${e}`,{...s,__security:{bearerAuth:!0}})}cancel(e,t,s){const{eval_id:n}=t;return this._client.post(a`/evals/${n}/runs/${e}`,{...s,__security:{bearerAuth:!0}})}}_s.OutputItems=Ln;class fs extends d{constructor(){super(...arguments),this.runs=new _s(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(a`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,s){return this._client.post(a`/evals/${e}`,{body:t,...s,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/evals",v,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(a`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}}fs.Runs=_s;let Nn=class extends d{create(e,t){return this._client.post("/files",ne({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(a`/files/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/files",v,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(a`/files/${e}`,{...t,__security:{bearerAuth:!0}})}content(e,t){return this._client.get(a`/files/${e}/content`,{...t,headers:f([{Accept:"application/binary"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:s=30*60*1e3}={}){const n=new Set(["processed","error","deleted"]),i=Date.now();let o=await this.retrieve(e);for(;!o.status||!n.has(o.status);)if(await Fe(t),o=await this.retrieve(e),Date.now()-i>s)throw new Vt({message:`Giving up on waiting for file ${e} to finish processing after ${s} milliseconds.`});return o}};class Mn extends d{}let Fn=class extends d{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t,__security:{bearerAuth:!0}})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t,__security:{bearerAuth:!0}})}};class ps extends d{constructor(){super(...arguments),this.graders=new Fn(this._client)}}ps.Graders=Fn;class zn extends d{create(e,t,s){return this._client.getAPIList(a`/fine_tuning/checkpoints/${e}/permissions`,le,{body:t,method:"post",...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},s){return this._client.get(a`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...s,__security:{adminAPIKeyAuth:!0}})}list(e,t={},s){return this._client.getAPIList(a`/fine_tuning/checkpoints/${e}/permissions`,B,{query:t,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,t,s){const{fine_tuned_model_checkpoint:n}=t;return this._client.delete(a`/fine_tuning/checkpoints/${n}/permissions/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}}let ms=class extends d{constructor(){super(...arguments),this.permissions=new zn(this._client)}};ms.Permissions=zn;class Bn extends d{list(e,t={},s){return this._client.getAPIList(a`/fine_tuning/jobs/${e}/checkpoints`,v,{query:t,...s,__security:{bearerAuth:!0}})}}class ys extends d{constructor(){super(...arguments),this.checkpoints=new Bn(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(a`/fine_tuning/jobs/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",v,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(a`/fine_tuning/jobs/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}listEvents(e,t={},s){return this._client.getAPIList(a`/fine_tuning/jobs/${e}/events`,v,{query:t,...s,__security:{bearerAuth:!0}})}pause(e,t){return this._client.post(a`/fine_tuning/jobs/${e}/pause`,{...t,__security:{bearerAuth:!0}})}resume(e,t){return this._client.post(a`/fine_tuning/jobs/${e}/resume`,{...t,__security:{bearerAuth:!0}})}}ys.Checkpoints=Bn;class xe extends d{constructor(){super(...arguments),this.methods=new Mn(this._client),this.jobs=new ys(this._client),this.checkpoints=new ms(this._client),this.alpha=new ps(this._client)}}xe.Methods=Mn;xe.Jobs=ys;xe.Checkpoints=ms;xe.Alpha=ps;class Dn extends d{}
13class gs extends d{constructor(){super(...arguments),this.graderModels=new Dn(this._client)}}gs.GraderModels=Dn;class Un extends d{createVariation(e,t){return this._client.post("/images/variations",ne({body:e,...t,__security:{bearerAuth:!0}},this._client))}edit(e,t){return this._client.post("/images/edits",ne({body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}}class Wn extends d{retrieve(e,t){return this._client.get(a`/models/${e}`,{...t,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList("/models",le,{...e,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(a`/models/${e}`,{...t,__security:{bearerAuth:!0}})}}class qn extends d{create(e,t){return this._client.post("/moderations",{body:e,...t,__security:{bearerAuth:!0}})}}class Hn extends d{accept(e,t,s){return this._client.post(a`/realtime/calls/${e}/accept`,{body:t,...s,headers:f([{Accept:"*/*"},s?.headers]),__security:{bearerAuth:!0}})}hangup(e,t){return this._client.post(a`/realtime/calls/${e}/hangup`,{...t,headers:f([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}refer(e,t,s){return this._client.post(a`/realtime/calls/${e}/refer`,{body:t,...s,headers:f([{Accept:"*/*"},s?.headers]),__security:{bearerAuth:!0}})}reject(e,t={},s){return this._client.post(a`/realtime/calls/${e}/reject`,{body:t,...s,headers:f([{Accept:"*/*"},s?.headers]),__security:{bearerAuth:!0}})}}class Jn extends d{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t,__security:{bearerAuth:!0}})}}class It extends d{constructor(){super(...arguments),this.clientSecrets=new Jn(this._client),this.calls=new Hn(this._client)}}It.ClientSecrets=Jn;It.Calls=Hn;function _a(r,e){if(!e||!pa(e)){const t={...r,output_parsed:null,output:r.output.map(s=>s.type==="function_call"?{...s,parsed_arguments:null}:s.type==="message"?{...s,content:s.content.map(n=>({...n,parsed:null}))}:s)};return Vn(r,t)&&se(t),t}return Xn(r,e)}function Xn(r,e){const t=!r.status||r.status==="completed",s=r.output.map(i=>{if(i.type==="function_call")return{...i,parsed_arguments:t?ga(e,i):null};if(i.type==="message"){const o=i.content.map(u=>u.type==="output_text"?{...u,parsed:t?fa(e,u.text):null}:u);return{...i,content:o}}return i}),n=Object.assign({},r,{output:s});return Vn(r,n)&&se(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(const i of n.output)if(i.type==="message"){for(const o of i.content)if(o.type==="output_text"&&o.parsed!==null)return o.parsed}return null}}),n}function fa(r,e){return r.text?.format?.type!=="json_schema"?null:"$parseRaw"in r.text?.format?(r.text?.format).$parseRaw(e):JSON.parse(e)}function pa(r){return!!Zt(r.text?.format)}function ma(r){return r?.$brand==="auto-parseable-tool"}function ya(r,e){return r.find(t=>t.type==="function"&&t.name===e)}function ga(r,e){const t=ya(r.tools??[],e.name);return{...e,...e,parsed_arguments:ma(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function Vn(r,e){return!Object.getOwnPropertyDescriptor(r,"output_text")||e.output_text==null}function se(r){const e=[];for(const t of r.output)if(t.type==="message")for(const s of t.content)s.type==="output_text"&&e.push(s.text);r.output_text=e.join("")}function ba(r,e){if(!e){if(r.type!=="response.created")throw new g(`When snapshot hasn't been set yet, expected 'response.created' event, got ${r.type}`);return Gs(r.response)}switch(r.type){case"response.output_item.added":{e.output.push(structuredClone(r.item)),r.item.type==="message"&&se(e);break}case"response.output_item.done":{P(e,r.output_index),e.output[r.output_index]=structuredClone(r.item),r.item.type==="message"&&se(e);break}case"response.content_part.added":{const t=P(e,r.output_index),s=t.type,n=r.part;s==="message"&&n.type!=="reasoning_text"?(t.content.push(structuredClone(n)),n.type==="output_text"&&se(e)):s==="reasoning"&&n.type==="reasoning_text"&&(t.content||(t.content=[]),t.content.push(structuredClone(n)));break}case"response.content_part.done":{const t=P(e,r.output_index),s=r.part;if(t.type==="message"&&s.type!=="reasoning_text")Q(t.content,r.content_index),t.content[r.content_index]=structuredClone(s),s.type==="output_text"&&se(e);else if(t.type==="reasoning"&&s.type==="reasoning_text"){const n=t.content;if(!n)throw new g(`missing content at index ${r.content_index}`);Q(n,r.content_index),n[r.content_index]=structuredClone(s)}break}case"response.output_text.delta":{const t=P(e,r.output_index);if(t.type==="message"){const s=Q(t.content,r.content_index);if(s.type!=="output_text")throw new g(`expected content to be 'output_text', got ${s.type}`);s.text+=r.delta,e.output_text+=r.delta}break}case"response.output_text.done":{const t=P(e,r.output_index);if(t.type==="message"){const s=Q(t.content,r.content_index);if(s.type!=="output_text")throw new g(`expected content to be 'output_text', got ${s.type}`);s.text=r.text,se(e)}break}case"response.output_text.annotation.added":{const t=P(e,r.output_index);if(t.type==="message"){const s=Q(t.content,r.content_index);if(s.type!=="output_text")throw new g(`expected content to be 'output_text', got ${s.type}`);s.annotations[r.annotation_index]=structuredClone(r.annotation)}break}case"response.refusal.delta":{const t=P(e,r.output_index);if(t.type==="message"){const s=Q(t.content,r.content_index);if(s.type!=="refusal")throw new g(`expected content to be 'refusal', got ${s.type}`);s.refusal+=r.delta}break}case"response.refusal.done":{const t=P(e,r.output_index);if(t.type==="message"){const s=Q(t.content,r.content_index);if(s.type!=="refusal")throw new g(`expected content to be 'refusal', got ${s.type}`);s.refusal=r.refusal}break}case"response.function_call_arguments.delta":{const t=P(e,r.output_index);t.type==="function_call"&&(t.arguments+=r.delta);break}case"response.function_call_arguments.done":{const t=P(e,r.output_index);t.type==="function_call"&&(t.arguments=r.arguments);break}case"response.reasoning_text.delta":{const t=P(e,r.output_index);if(t.type==="reasoning"){if(!t.content)throw new g(`missing content at index ${r.content_index}`);const s=Q(t.content,r.content_index);if(s.type!=="reasoning_text")throw new g(`expected content to be 'reasoning_text', got ${s.type}`);s.text+=r.delta}break}case"response.reasoning_text.done":{const t=P(e,r.output_index);if(t.type==="reasoning"){if(!t.content)throw new g(`missing content at index ${r.content_index}`);const s=Q(t.content,r.content_index);if(s.type!=="reasoning_text")throw new g(`expected content to be 'reasoning_text', got ${s.type}`);s.text=r.text}break}case"response.reasoning_summary_part.added":{const t=P(e,r.output_index);t.type==="reasoning"&&t.summary.push(structuredClone(r.part));break}case"response.reasoning_summary_part.done":{const t=P(e,r.output_index);t.type==="reasoning"&&(Q(t.summary,r.summary_index),t.summary[r.summary_index]=structuredClone(r.part));break}case"response.reasoning_summary_text.delta":{const t=P(e,r.output_index);if(t.type==="reasoning"){const s=Q(t.summary,r.summary_index);s.text+=r.delta}break}case"response.reasoning_summary_text.done":{const t=P(e,r.output_index);if(t.type==="reasoning"){const s=Q(t.summary,r.summary_index);s.text=r.text}break}case"response.custom_tool_call_input.delta":{const t=P(e,r.output_index);t.type==="custom_tool_call"&&(t.input+=r.delta);break}case"response.custom_tool_call_input.done":{const t=P(e,r.output_index);t.type==="custom_tool_call"&&(t.input=r.input);break}case"response.mcp_call_arguments.delta":{const t=P(e,r.output_index);t.type==="mcp_call"&&(t.arguments+=r.delta);break}case"response.mcp_call_arguments.done":{const t=P(e,r.output_index);t.type==="mcp_call"&&(t.arguments=r.arguments);break}case"response.code_interpreter_call_code.delta":{const t=P(e,r.output_index);t.type==="code_interpreter_call"&&(t.code=(t.code??"")+r.delta);break}case"response.code_interpreter_call_code.done":{const t=P(e,r.output_index);t.type==="code_interpreter_call"&&(t.code=r.code);break}case"response.code_interpreter_call.in_progress":{const t=P(e,r.output_index);t.type==="code_interpreter_call"&&(t.status="in_progress");break}case"response.code_interpreter_call.interpreting":{const t=P(e,r.output_index);t.type==="code_interpreter_call"&&(t.status="interpreting");break}case"response.code_interpreter_call.completed":{const t=P(e,r.output_index);t.type==="code_interpreter_call"&&(t.status="completed");break}case"response.file_search_call.in_progress":{const t=P(e,r.output_index);t.type==="file_search_call"&&(t.status="in_progress");break}case"response.file_search_call.searching":{const t=P(e,r.output_index);t.type==="file_search_call"&&(t.status="searching");break}case"response.file_search_call.completed":{const t=P(e,r.output_index);t.type==="file_search_call"&&(t.status="completed");break}case"response.web_search_call.in_progress":{const t=P(e,r.output_index);t.type==="web_search_call"&&(t.status="in_progress");break}case"response.web_search_call.searching":{const t=P(e,r.output_index);t.type==="web_search_call"&&(t.status="searching");break}case"response.web_search_call.completed":{const t=P(e,r.output_index);t.type==="web_search_call"&&(t.status="completed");break}case"response.image_generation_call.in_progress":{const t=P(e,r.output_index);t.type==="image_generation_call"&&(t.status="in_progress");break}case"response.image_generation_call.generating":{const t=P(e,r.output_index);t.type==="image_generation_call"&&(t.status="generating");break}case"response.image_generation_call.completed":{const t=P(e,r.output_index);t.type==="image_generation_call"&&(t.status="completed");break}case"response.mcp_call.in_progress":{const t=P(e,r.output_index);t.type==="mcp_call"&&(t.status="in_progress");break}case"response.mcp_call.completed":{const t=P(e,r.output_index);t.type==="mcp_call"&&(t.status="completed");break}case"response.mcp_call.failed":{const t=P(e,r.output_index);t.type==="mcp_call"&&(t.status="failed");break}case"response.created":case"response.queued":case"response.in_progress":case"response.completed":case"response.failed":case"response.incomplete":{e=Gs(r.response);break}case"response.audio.delta":case"response.audio.done":case"response.audio.transcript.delta":case"response.audio.transcript.done":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":break;default:Aa(r)}return e}function Gs(r){const e=structuredClone(r);return(!Object.getOwnPropertyDescriptor(e,"output_text")||e.output_text==null)&&se(e),e}function P(r,e){const t=r.output[e];
13if(!t)throw new g(`missing output at index ${e}`);return t}function Q(r,e){const t=r[e];if(!t)throw new g(`missing content at index ${e}`);return t}function Aa(r){throw new g(`Unhandled response stream event: ${JSON.stringify(r)}`)}var $e,He,he,Je,Qs,Ys,Zs;class bs extends ts{constructor(e){super(),$e.add(this),He.set(this,void 0),he.set(this,void 0),Je.set(this,void 0),I(this,He,e)}static createResponse(e,t,s){const n=new bs(t);return n._run(()=>n._createOrRetrieveResponse(e,t,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createOrRetrieveResponse(e,t,s){this._listenForAbort(s?.signal),c(this,$e,"m",Qs).call(this);let n,i=null;"response_id"in t?(n=await e.responses.retrieve(t.response_id,{stream:!0},{...s,signal:this.controller.signal,stream:!0}),i=t.starting_after??null):n=await e.responses.create({...t,stream:!0},{...s,signal:this.controller.signal}),this._connected();for await(const o of n)c(this,$e,"m",Ys).call(this,o,i);if(n.controller.signal?.aborted)throw new Y;return c(this,$e,"m",Zs).call(this)}[(He=new WeakMap,he=new WeakMap,Je=new WeakMap,$e=new WeakSet,Qs=function(){this.ended||I(this,he,void 0)},Ys=function(t,s){if(this.ended)return;const n=(o,u)=>{(s==null||u.sequence_number>s)&&this._emit(o,u)},i=ba(t,c(this,he,"f"));switch(I(this,he,i),n("event",t),t.type){case"response.output_text.delta":{const o=i.output[t.output_index];if(!o)throw new g(`missing output at index ${t.output_index}`);if(o.type==="message"){const u=o.content[t.content_index];if(!u)throw new g(`missing content at index ${t.content_index}`);if(u.type!=="output_text")throw new g(`expected content to be 'output_text', got ${u.type}`);n("response.output_text.delta",{...t,snapshot:u.text})}break}case"response.function_call_arguments.delta":{const o=i.output[t.output_index];if(!o)throw new g(`missing output at index ${t.output_index}`);o.type==="function_call"&&n("response.function_call_arguments.delta",{...t,snapshot:o.arguments});break}default:n(t.type,t);break}},Zs=function(){if(this.ended)throw new g("stream has ended, this shouldn't happen");const t=c(this,he,"f");if(!t)throw new g("request ended without sending any events");I(this,he,void 0);const s=wa(t,c(this,He,"f"));return I(this,Je,s),s},Symbol.asyncIterator)](){const e=[],t=[];let s=!1;return this.on("event",n=>{const i=t.shift();i?i.resolve(n):e.push(n)}),this.on("end",()=>{s=!0;for(const n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{s=!0;for(const i of t)i.reject(n);t.length=0}),this.on("error",n=>{s=!0;for(const i of t)i.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((i,o)=>t.push({resolve:i,reject:o})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const e=c(this,Je,"f");if(!e)throw new g("stream ended without producing a ChatCompletion");return e}}function wa(r,e){return _a(r,e)}class Gn extends d{list(e,t={},s){return this._client.getAPIList(a`/responses/${e}/input_items`,v,{query:t,...s,__security:{bearerAuth:!0}})}}class Qn extends d{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t,__security:{bearerAuth:!0}})}}class $t extends d{constructor(){super(...arguments),this.inputItems=new Gn(this._client),this.inputTokens=new Qn(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(s=>("object"in s&&s.object==="response"&&se(s),s))}retrieve(e,t={},s){return this._client.get(a`/responses/${e}`,{query:t,...s,stream:t?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(n=>("object"in n&&n.object==="response"&&se(n),n))}delete(e,t){return this._client.delete(a`/responses/${e}`,{...t,headers:f([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(s=>Xn(s,e))}stream(e,t){return bs.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(a`/responses/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}compact(e,t){return this._client.post("/responses/compact",{body:e,...t,__security:{bearerAuth:!0}})}}$t.InputItems=Gn;$t.InputTokens=Qn;let Yn=class extends d{retrieve(e,t){return this._client.get(a`/skills/${e}/content`,{...t,headers:f([{Accept:"application/binary"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};
13class Zn extends d{retrieve(e,t,s){const{skill_id:n}=t;return this._client.get(a`/skills/${n}/versions/${e}/content`,{...s,headers:f([{Accept:"application/binary"},s?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}class As extends d{constructor(){super(...arguments),this.content=new Zn(this._client)}create(e,t={},s){return this._client.post(a`/skills/${e}/versions`,yt({body:t,...s,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,s){const{skill_id:n}=t;return this._client.get(a`/skills/${n}/versions/${e}`,{...s,__security:{bearerAuth:!0}})}list(e,t={},s){return this._client.getAPIList(a`/skills/${e}/versions`,v,{query:t,...s,__security:{bearerAuth:!0}})}delete(e,t,s){const{skill_id:n}=t;return this._client.delete(a`/skills/${n}/versions/${e}`,{...s,__security:{bearerAuth:!0}})}}As.Content=Zn;class Pt extends d{constructor(){super(...arguments),this.content=new Yn(this._client),this.versions=new As(this._client)}create(e={},t){return this._client.post("/skills",yt({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(a`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,s){return this._client.post(a`/skills/${e}`,{body:t,...s,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/skills",v,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(a`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}}Pt.Content=Yn;Pt.Versions=As;class ei extends d{create(e,t,s){return this._client.post(a`/uploads/${e}/parts`,ne({body:t,...s,__security:{bearerAuth:!0}},this._client))}}class ws extends d{constructor(){super(...arguments),this.parts=new ei(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(a`/uploads/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}complete(e,t,s){return this._client.post(a`/uploads/${e}/complete`,{body:t,...s,__security:{bearerAuth:!0}})}}ws.Parts=ei;const xa=async r=>{const e=await Promise.allSettled(r),t=e.filter(n=>n.status==="rejected");if(t.length){for(const n of t)console.error(n.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}const s=[];for(const n of e)n.status==="fulfilled"&&s.push(n.value);return s};class ti extends d{create(e,t,s){return this._client.post(a`/vector_stores/${e}/file_batches`,{body:t,...s,headers:f([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,s){const{vector_store_id:n}=t;return this._client.get(a`/vector_stores/${n}/file_batches/${e}`,{...s,headers:f([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,s){const{vector_store_id:n}=t;return this._client.post(a`/vector_stores/${n}/file_batches/${e}/cancel`,{...s,headers:f([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,s){const n=await this.create(e,t);return await this.poll(e,n.id,s)}listFiles(e,t,s){const{vector_store_id:n,...i}=t;return this._client.getAPIList(a`/vector_stores/${n}/file_batches/${e}/files`,v,{query:i,...s,headers:f([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}async poll(e,t,s){const n=f([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:i,response:o}=await this.retrieve(t,{vector_store_id:e},{...s,headers:n}).withResponse();switch(i.status){case"in_progress":let u=5e3;if(s?.pollIntervalMs)u=s.pollIntervalMs;else{const _=o.headers.get("openai-poll-after-ms");if(_){const l=parseInt(_);isNaN(l)||(u=l)}}await Fe(u);break;case"failed":case"cancelled":case"completed":return i}}}async uploadAndPoll(e,{files:t,fileIds:s=[]},n){if(t==null||t.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const i=n?.maxConcurrency??5,o=Math.min(i,t.length),u=this._client,_=t.values(),l=[...s];async function y(m){for(let w of m){const p=await u.files.create({file:w,purpose:"assistants"},n);l.push(p.id)}}const h=Array(o).fill(_).map(y);return await xa(h),await this.createAndPoll(e,{file_ids:l})}}
13class si extends d{create(e,t,s){return this._client.post(a`/vector_stores/${e}/files`,{body:t,...s,headers:f([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,s){const{vector_store_id:n}=t;return this._client.get(a`/vector_stores/${n}/files/${e}`,{...s,headers:f([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}update(e,t,s){const{vector_store_id:n,...i}=t;return this._client.post(a`/vector_stores/${n}/files/${e}`,{body:i,...s,headers:f([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}list(e,t={},s){return this._client.getAPIList(a`/vector_stores/${e}/files`,v,{query:t,...s,headers:f([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}delete(e,t,s){const{vector_store_id:n}=t;return this._client.delete(a`/vector_stores/${n}/files/${e}`,{...s,headers:f([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,s){const n=await this.create(e,t,s);return await this.poll(e,n.id,s)}async poll(e,t,s){const n=f([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){const i=await this.retrieve(t,{vector_store_id:e},{...s,headers:n}).withResponse(),o=i.data;switch(o.status){case"in_progress":let u=5e3;if(s?.pollIntervalMs)u=s.pollIntervalMs;else{const _=i.response.headers.get("openai-poll-after-ms");if(_){const l=parseInt(_);isNaN(l)||(u=l)}}await Fe(u);break;case"failed":case"completed":return o}}}async upload(e,t,s){const n=await this._client.files.create({file:t,purpose:"assistants"},s);return this.create(e,{file_id:n.id},s)}async uploadAndPoll(e,t,s){const n=await this.upload(e,t,s);return await this.poll(e,n.id,s)}content(e,t,s){const{vector_store_id:n}=t;return this._client.getAPIList(a`/vector_stores/${n}/files/${e}/content`,le,{...s,headers:f([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}}class St extends d{constructor(){super(...arguments),this.files=new si(this._client),this.fileBatches=new ti(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:f([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(a`/vector_stores/${e}`,{...t,headers:f([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,s){return this._client.post(a`/vector_stores/${e}`,{body:t,...s,headers:f([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/vector_stores",v,{query:e,...t,headers:f([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(a`/vector_stores/${e}`,{...t,headers:f([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}search(e,t,s){return this._client.getAPIList(a`/vector_stores/${e}/search`,le,{body:t,method:"post",...s,headers:f([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}}St.Files=si;St.FileBatches=ti;class ri extends d{create(e,t){return this._client.post("/videos",ne({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(a`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/videos",B,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(a`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}createCharacter(e,t){return this._client.post("/videos/characters",ne({body:e,...t,__security:{bearerAuth:!0}},this._client))}downloadContent(e,t={},s){return this._client.get(a`/videos/${e}/content`,{query:t,...s,headers:f([{Accept:"application/binary"},s?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,t){return this._client.post("/videos/edits",ne({body:e,...t,__security:{bearerAuth:!0}},this._client))}extend(e,t){return this._client.post("/videos/extensions",ne({body:e,...t,__security:{bearerAuth:!0}},this._client))}getCharacter(e,t){return this._client.get(a`/videos/characters/${e}`,{...t,__security:{bearerAuth:!0}})}remix(e,t,s){return this._client.post(a`/videos/${e}/remix`,yt({body:t,...s,__security:{bearerAuth:!0}},this._client))}}var Ae,ni,st;class ii extends d{constructor(){super(...arguments),Ae.add(this)}async unwrap(e,t,s=this._client.webhookSecret,n=300){return await this.verifySignature(e,t,s,n),JSON.parse(e)}async verifySignature(e,t,s=this._client.webhookSecret,n=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");c(this,Ae,"m",ni).call(this,s);const i=f([t]).values,o=c(this,Ae,"m",st).call(this,i,"webhook-signature"),u=c(this,Ae,"m",st).call(this,i,"webhook-timestamp"),_=c(this,Ae,"m",st).call(this,i,"webhook-id"),l=parseInt(u,10);if(isNaN(l))throw new Pe("Invalid webhook timestamp format");const y=Math.floor(Date.now()/1e3);if(y-l>n)throw new Pe("Webhook timestamp is too old");if(l>y+n)throw new Pe("Webhook timestamp is too new");const h=o.split(" ").map(b=>b.startsWith("v1,")?b.substring(3):b),m=s.startsWith("whsec_")?Buffer.from(s.replace("whsec_",""),"base64"):Buffer.from(s,"utf-8"),w=_?`${_}.${u}.${e}`:`${u}.${e}`,p=await crypto.subtle.importKey("raw",m,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(const b of h)try{const x=Buffer.from(b,"base64");if(await crypto.subtle.verify("HMAC",p,x,new TextEncoder().encode(w)))return}catch{continue}throw new Pe("The given webhook signature does not match the expected signature")}}Ae=new WeakSet,ni=function(e){if(typeof e!="string"||e.length===0)throw new 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")},st=function(e,t){if(!e)throw new Error("Headers are required");const s=e.get(t);if(s==null)throw new Error(`Missing required header: ${t}`);return s};const ai=Symbol.for("openai.node.providerDefinitions.v1"),oi=globalThis,ci=oi[ai],ui=ci??new WeakMap;ci||Object.defineProperty(oi,ai,{value:ui});function Ia(r){const e=ui.get(r);if(!e)throw new Error("Invalid provider. Providers must be created with createProvider().");return e.configure()}var Xt,xs,Ke,li;const $a="workload-identity-auth";class ${constructor(e={}){Xt.add(this),Ke.set(this,void 0),this.completions=new On(this),this.chat=new ns(this),this.embeddings=new jn(this),this.files=new Nn(this),this.images=new Un(this),this.audio=new Be(this),this.moderations=new qn(this),this.models=new Wn(this),this.fineTuning=new xe(this),this.graders=new gs(this),this.vectorStores=new St(this),this.webhooks=new ii(this),this.beta=new me(this),this.batches=new xn(this),this.uploads=new ws(this),this.admin=new cs(this),this.responses=new $t(this),this.realtime=new It(this),this.conversations=new ds(this),this.evals=new fs(this),this.containers=new hs(this),this.skills=new Pt(this),this.videos=new ri(this);const t=e.provider;if(t){const b=["apiKey","adminAPIKey","workloadIdentity","baseURL"].filter(x=>e[x]!=null);if(b.length)throw new g(`The \`provider\` option cannot be used with ${b.map(x=>`\`${x}\``).join(", ")}. Configure authentication and the base URL through the provider instead.`)}const{baseURL:s=t?null:ue("OPENAI_BASE_URL"),apiKey:n=t?null:ue("OPENAI_API_KEY")??null,adminAPIKey:i=t?null:ue("OPENAI_ADMIN_KEY")??null,organization:o=t?null:ue("OPENAI_ORG_ID")??null,project:u=t?null:ue("OPENAI_PROJECT_ID")??null,webhookSecret:_=ue("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:l,...y}=e,h=t?Ia(t):void 0,m={apiKey:n,adminAPIKey:i,organization:o,project:u,webhookSecret:_,workloadIdentity:l,provider:t,...y,baseURL:h?.baseURL??(s||"https://api.openai.com/v1")};if(n&&l)throw new g("The `apiKey` and `workloadIdentity` options are mutually exclusive");
13if(!h&&!n&&!i&&!l)throw new g("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!m.dangerouslyAllowBrowser&&gi())throw new g(`It looks like you're running in a browser-like environment. 14 15This is disabled by default, as it risks exposing your secret API credentials to attackers. 16If you understand the risks and have appropriate mitigations in place, 17you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g., 18 19new OpenAI({ apiKey, dangerouslyAllowBrowser: true }); 20 21https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety 22`);this.baseURL=m.baseURL,this.timeout=m.timeout??xs.DEFAULT_TIMEOUT,this.logger=m.logger??console;const w="warn";this.logLevel=w,this.logLevel=Ns(m.logLevel,"ClientOptions.logLevel",this)??Ns(ue("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??w,this.fetchOptions=m.fetchOptions,this.maxRetries=m.maxRetries??2,this.fetch=m.fetch??hr(),I(this,Ke,Ii);const p=t?void 0:ue("OPENAI_CUSTOM_HEADERS");if(p){const b={};for(const x of p.split(` 23`)){const R=x.indexOf(":");R>=0&&(b[x.substring(0,R).trim()]=x.substring(R+1).trim())}m.defaultHeaders=f([b,m.defaultHeaders])}this._options=m,this._provider=h,l&&(this._workloadIdentityAuth=new Di(l,this.fetch)),this.apiKey=typeof n=="string"?n:null,this.adminAPIKey=i,this.organization=o,this.project=u,this.webhookSecret=_}withOptions(e){const t=this._options.provider,s=e.provider??t,n={...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:this._options.workloadIdentity,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret};return s&&(delete n.apiKey,delete n.adminAPIKey,delete n.workloadIdentity,delete n.baseURL,s!==t&&(delete n.organization,delete n.project,delete n.defaultHeaders)),new this.constructor({...n,...e,provider:s})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t},s={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get("authorization")||e.get("api-key"))&&!(t.has("authorization")||t.has("api-key"))&&!(this._workloadIdentityAuth&&s.bearerAuth))throw new 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 f([t.bearerAuth?await this.bearerAuth(e):null,t.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){if(this._workloadIdentityAuth)return f([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey!=null)return f([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return f([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return Ci(e)}getUserAgent(){return`${this.constructor.name}/JS ${ge}`}defaultIdempotencyKey(){return`stainless-node-retry-${dt()}`}makeStatusError(e,t,s,n){return L.generate(e,t,s,n)}async _callApiKey(){if(this._provider)return!1;const e=this._options.apiKey;if(typeof e!="function")return!1;let t;try{t=await e()}catch(s){throw s instanceof g?s:new g(`Failed to get token from 'apiKey' function: ${s.message}`,{cause:s})}if(typeof t!="string"||!t)throw new g(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,s){const n=!c(this,Xt,"m",li).call(this)&&s||this.baseURL,i=fi(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),o=this.defaultQuery(),u=Object.fromEntries(i.searchParams);return(!Ss(o)||!Ss(u))&&(t={...u,...o,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}async prepareOptions(e){if(this._provider)return;(e.__security??{bearerAuth:!0}).bearerAuth&&await this._callApiKey()}async prepareRequest(e,{url:t,options:s}){}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,s){return this.request(Promise.resolve(s).then(n=>({method:e,path:t,...n})))}
23request(e,t=null){return new pt(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,s){const n=await e,i=n.maxRetries??this.maxRetries;t==null&&(t=i),await this.prepareOptions(n);const{req:o,url:u,timeout:_}=await this.buildRequest(n,{retryCount:i-t});await this.prepareRequest(o,{url:u,options:n}),await this._provider?.prepareRequest?.(o,{url:u,options:n});const l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),y=s===void 0?"":`, retryOf: ${s}`,h=Date.now();if(F(this).debug(`[${l}] sending request`,de({retryOfRequestLogID:s,method:n.method,url:u,options:n,headers:o.headers})),n.signal?.aborted)throw new Y;const m=n.__security??{bearerAuth:!0},w=new AbortController,p=await this.fetchWithAuth(u,o,_,w,m).catch(Mt),b=Date.now();if(p instanceof globalThis.Error){const A=`retrying, ${t} attempts remaining`;if(n.signal?.aborted)throw new Y;const k=Nt(p)||/timed? ?out/i.test(String(p)+("cause"in p?String(p.cause):""));if(t)return F(this).info(`[${l}] connection ${k?"timed out":"failed"} - ${A}`),F(this).debug(`[${l}] connection ${k?"timed out":"failed"} (${A})`,de({retryOfRequestLogID:s,url:u,durationMs:b-h,message:p.message})),this.retryRequest(n,t,s??l);throw F(this).info(`[${l}] connection ${k?"timed out":"failed"} - error; no more retries left`),F(this).debug(`[${l}] connection ${k?"timed out":"failed"} (error; no more retries left)`,de({retryOfRequestLogID:s,url:u,durationMs:b-h,message:p.message})),p instanceof lr||p instanceof di?p:k?new Vt:new _t({message:Pa(p),cause:p})}const x=[...p.headers.entries()].filter(([A])=>A==="x-request-id").map(([A,k])=>", "+A+": "+JSON.stringify(k)).join(""),R=`[${l}${y}${x}] ${o.method} ${u} ${p.ok?"succeeded":"failed"} with status ${p.status} in ${b-h}ms`;if(!p.ok){if(p.status===401&&this._workloadIdentityAuth&&m.bearerAuth&&!n.__metadata?.hasStreamingBody&&!n.__metadata?.workloadIdentityTokenRefreshed)return await Cs(p.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...n,__metadata:{...n.__metadata,workloadIdentityTokenRefreshed:!0}},t,s??l);const A=await this.shouldRetry(p);if(t&&A){const E=`retrying, ${t} attempts remaining`;return await Cs(p.body),F(this).info(`${R} - ${E}`),F(this).debug(`[${l}] response error (${E})`,de({retryOfRequestLogID:s,url:p.url,status:p.status,headers:p.headers,durationMs:b-h})),this.retryRequest(n,t,s??l,p.headers)}const k=A?"error; no more retries left":"error; not retryable";F(this).info(`${R} - ${k}`);const S=await p.text().catch(E=>Mt(E).message),q=yi(S),M=q?void 0:S;throw F(this).debug(`[${l}] response error (${k})`,de({retryOfRequestLogID:s,url:p.url,status:p.status,headers:p.headers,message:M,durationMs:Date.now()-h})),this.makeStatusError(p.status,q,M,p.headers)}return F(this).info(R),F(this).debug(`[${l}] response start`,de({retryOfRequestLogID:s,url:p.url,status:p.status,headers:p.headers,durationMs:b-h})),{response:p,options:n,controller:w,requestLogID:l,retryOfRequestLogID:s,startTime:h}}getAPIList(e,t,s){return this.requestAPIList(t,s&&"then"in s?s.then(n=>({method:"get",path:e,...n})):{method:"get",path:e,...s})}requestAPIList(e,t){const s=this.makeRequest(t,null,void 0);return new Fi(this,s,e)}async fetchWithAuth(e,t,s,n,i={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&i.bearerAuth){const u=t.headers,_=u.get("Authorization");if(!_||_===`Bearer ${$a}`){const l=await this._workloadIdentityAuth.getToken();u.set("Authorization",`Bearer ${l}`)}}return await this.fetchWithTimeout(e,t,s,n)}async fetchWithTimeout(e,t,s,n){const{signal:i,method:o,...u}=t||{},_=this._makeAbort(n);i&&i.addEventListener("abort",_,{once:!0});const l=setTimeout(_,s),y=globalThis.ReadableStream&&u.body instanceof globalThis.ReadableStream||typeof u.body=="object"&&u.body!==null&&Symbol.asyncIterator in u.body,h={signal:n.signal,...y?{duplex:"half"}:{},method:"GET",...u};o&&(h.method=o.toUpperCase());try{return await this.fetch.call(void 0,e,h)}finally{clearTimeout(l)}}async shouldRetry(e){const 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,s,n){let i;const o=n?.get("retry-after-ms");if(o){const _=parseFloat(o);Number.isNaN(_)||(i=_)}const u=n?.get("retry-after");if(u&&!i){const _=parseFloat(u);Number.isNaN(_)?i=Date.parse(u)-Date.now():i=_*1e3}if(i===void 0){const _=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,_)}
23return await Fe(i),this.makeRequest(e,t-1,s)}calculateDefaultRetryTimeoutMillis(e,t){const i=t-e,o=Math.min(.5*Math.pow(2,i),8),u=1-Math.random()*.25;return o*u*1e3}async buildRequest(e,{retryCount:t=0}={}){const s={...e},{method:n,path:i,query:o,defaultBaseURL:u}=s,_=this.buildURL(i,o,u);"timeout"in s&&mi("timeout",s.timeout),s.timeout=s.timeout??this.timeout;const{bodyHeaders:l,body:y,isStreamingBody:h}=this.buildBody({options:s});h&&(e.__metadata={...e.__metadata,hasStreamingBody:!0});const m=await this.buildHeaders({options:e,method:n,bodyHeaders:l,retryCount:t});return{req:{method:n,headers:m,...s.signal&&{signal:s.signal},...globalThis.ReadableStream&&y instanceof globalThis.ReadableStream&&{duplex:"half"},...y&&{body:y},...this.fetchOptions??{},...s.fetchOptions??{}},url:_,timeout:s.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:s,retryCount:n}){let i={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);const o=f([i,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(n),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...xi(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},this._provider?void 0:await this.authHeaders(e,e.__security??{bearerAuth:!0}),this._options.defaultHeaders,s,e.headers]);return this._provider||this.validateHeaders(o,e.__security??{bearerAuth:!0}),o.values}_makeAbort(e){return()=>e.abort()}buildBody({options:e}){const{body:t,headers:s}=e;if(!t)return t===void 0&&"body"in e?{...c(this,Ke,"f").call(this,{body:t,headers:f([s])}),isStreamingBody:!1}:{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};const n=f([s]),i=typeof globalThis.ReadableStream<"u"&&t instanceof globalThis.ReadableStream,o=!i&&(typeof t=="string"||t instanceof ArrayBuffer||ArrayBuffer.isView(t)||typeof globalThis.Blob<"u"&&t instanceof globalThis.Blob||t instanceof URLSearchParams||t instanceof FormData);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t=="string"&&n.values.has("content-type")||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||i?{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:_r(t),isStreamingBody:!0}:typeof t=="object"&&n.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(t),isStreamingBody:!1}:{...c(this,Ke,"f").call(this,{body:t,headers:n}),isStreamingBody:!1}}}xs=$,Ke=new WeakMap,Xt=new WeakSet,li=function(){return this._provider!==void 0||this.baseURL!=="https://api.openai.com/v1"};$.OpenAI=xs;$.DEFAULT_TIMEOUT=6e5;$.OpenAIError=g;$.APIError=L;$.APIConnectionError=_t;$.APIConnectionTimeoutError=Vt;$.APIUserAbortError=Y;$.NotFoundError=rr;$.ConflictError=nr;$.RateLimitError=ar;$.BadRequestError=er;$.AuthenticationError=tr;$.InternalServerError=or;$.PermissionDeniedError=sr;$.UnprocessableEntityError=ir;$.InvalidWebhookSignatureError=Pe;$.toFile=Ji;$.Completions=On;$.Chat=ns;$.Embeddings=jn;$.Files=Nn;$.Images=Un;$.Audio=Be;$.Moderations=qn;$.Models=Wn;$.FineTuning=xe;$.Graders=gs;$.VectorStores=St;$.Webhooks=ii;$.Beta=me;$.Batches=xn;$.Uploads=ws;$.Admin=cs;$.Responses=$t;$.Realtime=It;$.Conversations=ds;$.Evals=fs;$.Containers=hs;$.Skills=Pt;$.Videos=ri;function Pa(r){if(Sa(r))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 Sa(r){let e=r;for(let t=0;t<8&&e&&typeof e=="object";t++){const s=e;if(s.code==="UND_ERR_INVALID_ARG"&&typeof s.message=="string"&&s.message.includes("invalid onRequestStart method"))return!0;e=s.cause}return!1}export{_t as APIConnectionError,Vt as APIConnectionTimeoutError,L as APIError,pt as APIPromise,Y as APIUserAbortError,tr as AuthenticationError,er as BadRequestError,nr as ConflictError,or as InternalServerError,Pe as InvalidWebhookSignatureError,rr as NotFoundError,lr as OAuthError,$ as OpenAI,g as OpenAIError,Fi as PagePromise,sr as PermissionDeniedError,ar as RateLimitError,di as SubjectTokenProviderError,ir as UnprocessableEntityError,$ as default,Ji as toFile};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.