tempest.games 0.1.15 → 0.1.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,19 @@
1
1
  # tempest.games
2
2
 
3
+ ## 0.1.17
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [8f6fc6c]
8
+ - atom.io@0.30.3
9
+
10
+ ## 0.1.16
11
+
12
+ ### Patch Changes
13
+
14
+ - 806a254: 🐛 Fix issue where the frontend would not shut down when updates are ready.
15
+ - e4662c3: ✨ Added an entrypoint for using Drizzle Studio from the production instance.
16
+
3
17
  ## 0.1.15
4
18
 
5
19
  ### Patch Changes
@@ -5,7 +5,7 @@ var z4=Object.create;var{getPrototypeOf:_4,defineProperty:hW,getOwnPropertyNames
5
5
  `,JSON.stringify(k,null," "),`
6
6
  `,`Here's the error message from zod:
7
7
  `,y.error.toString()),X.push({response:k,error:y.error})}return S?.error(`safegen was unable to generate well-formed data after ${A} failed attempts.`),M}}}function SX(T){return["Please generate a response in JSON that conforms to the following JSON Schema:",JSON.stringify(T,null,2)].join(`
8
- `)}import{createHash as r6}from"crypto";var GF="RFC3986",zF={RFC1738:(T)=>String(T).replace(/%20/g,"+"),RFC3986:(T)=>String(T)},$X="RFC1738";var ow=Array.isArray,X$=(()=>{let T=[];for(let S=0;S<256;++S)T.push("%"+((S<16?"0":"")+S.toString(16)).toUpperCase());return T})();var z0=1024,fX=(T,S,$,f,M)=>{if(T.length===0)return T;let J=T;if(typeof T==="symbol")J=Symbol.prototype.toString.call(T);else if(typeof T!=="string")J=String(T);if($==="iso-8859-1")return escape(J).replace(/%u[0-9a-f]{4}/gi,function(W){return"%26%23"+parseInt(W.slice(2),16)+"%3B"});let F="";for(let W=0;W<J.length;W+=z0){let A=J.length>=z0?J.slice(W,W+z0):J,k=[];for(let X=0;X<A.length;++X){let y=A.charCodeAt(X);if(y===45||y===46||y===95||y===126||y>=48&&y<=57||y>=65&&y<=90||y>=97&&y<=122||M===$X&&(y===40||y===41)){k[k.length]=A.charAt(X);continue}if(y<128){k[k.length]=X$[y];continue}if(y<2048){k[k.length]=X$[192|y>>6]+X$[128|y&63];continue}if(y<55296||y>=57344){k[k.length]=X$[224|y>>12]+X$[128|y>>6&63]+X$[128|y&63];continue}X+=1,y=65536+((y&1023)<<10|A.charCodeAt(X)&1023),k[k.length]=X$[240|y>>18]+X$[128|y>>12&63]+X$[128|y>>6&63]+X$[128|y&63]}F+=k.join("")}return F};function MX(T){if(!T||typeof T!=="object")return!1;return!!(T.constructor&&T.constructor.isBuffer&&T.constructor.isBuffer(T))}function _0(T,S){if(ow(T)){let $=[];for(let f=0;f<T.length;f+=1)$.push(S(T[f]));return $}return S(T)}var gw=Object.prototype.hasOwnProperty,JX={brackets(T){return String(T)+"[]"},comma:"comma",indices(T,S){return String(T)+"["+S+"]"},repeat(T){return String(T)}},y$=Array.isArray,tw=Array.prototype.push,FX=function(T,S){tw.apply(T,y$(S)?S:[S])},pw=Date.prototype.toISOString,dT={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:fX,encodeValuesOnly:!1,format:GF,formatter:zF[GF],indices:!1,serializeDate(T){return pw.call(T)},skipNulls:!1,strictNullHandling:!1};function iw(T){return typeof T==="string"||typeof T==="number"||typeof T==="boolean"||typeof T==="symbol"||typeof T==="bigint"}var H0={};function WX(T,S,$,f,M,J,F,W,A,k,X,y,K,G,z,Q,E,B){let L=T,b=B,C=0,D=!1;while((b=b.get(H0))!==void 0&&!D){let O=b.get(T);if(C+=1,typeof O!=="undefined")if(O===C)throw new RangeError("Cyclic object value");else D=!0;if(typeof b.get(H0)==="undefined")C=0}if(typeof k==="function")L=k(S,L);else if(L instanceof Date)L=K?.(L);else if($==="comma"&&y$(L))L=_0(L,function(O){if(O instanceof Date)return K?.(O);return O});if(L===null){if(J)return A&&!Q?A(S,dT.encoder,E,"key",G):S;L=""}if(iw(L)||MX(L)){if(A){let O=Q?S:A(S,dT.encoder,E,"key",G);return[z?.(O)+"="+z?.(A(L,dT.encoder,E,"value",G))]}return[z?.(S)+"="+z?.(String(L))]}let H=[];if(typeof L==="undefined")return H;let U;if($==="comma"&&y$(L)){if(Q&&A)L=_0(L,A);U=[{value:L.length>0?L.join(",")||null:void 0}]}else if(y$(k))U=k;else{let O=Object.keys(L);U=X?O.sort(X):O}let Z=W?String(S).replace(/\./g,"%2E"):String(S),h=f&&y$(L)&&L.length===1?Z+"[]":Z;if(M&&y$(L)&&L.length===0)return h+"[]";for(let O=0;O<U.length;++O){let o=U[O],P=typeof o==="object"&&typeof o.value!=="undefined"?o.value:L[o];if(F&&P===null)continue;let a=y&&W?o.replace(/\./g,"%2E"):o,MT=y$(L)?typeof $==="function"?$(h,a):h:h+(y?"."+a:"["+a+"]");B.set(T,C);let fT=new WeakMap;fT.set(H0,B),FX(H,WX(P,MT,$,f,M,J,F,W,$==="comma"&&Q&&y$(L)?null:A,k,X,y,K,G,z,Q,E,fT))}return H}function lw(T=dT){if(typeof T.allowEmptyArrays!=="undefined"&&typeof T.allowEmptyArrays!=="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof T.encodeDotInKeys!=="undefined"&&typeof T.encodeDotInKeys!=="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(T.encoder!==null&&typeof T.encoder!=="undefined"&&typeof T.encoder!=="function")throw new TypeError("Encoder has to be a function.");let S=T.charset||dT.charset;if(typeof T.charset!=="undefined"&&T.charset!=="utf-8"&&T.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let $=GF;if(typeof T.format!=="undefined"){if(!gw.call(zF,T.format))throw new TypeError("Unknown format option provided.");$=T.format}let f=zF[$],M=dT.filter;if(typeof T.filter==="function"||y$(T.filter))M=T.filter;let J;if(T.arrayFormat&&T.arrayFormat in JX)J=T.arrayFormat;else if("indices"in T)J=T.indices?"indices":"repeat";else J=dT.arrayFormat;if("commaRoundTrip"in T&&typeof T.commaRoundTrip!=="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let F=typeof T.allowDots==="undefined"?!!T.encodeDotInKeys===!0?!0:dT.allowDots:!!T.allowDots;return{addQueryPrefix:typeof T.addQueryPrefix==="boolean"?T.addQueryPrefix:dT.addQueryPrefix,allowDots:F,allowEmptyArrays:typeof T.allowEmptyArrays==="boolean"?!!T.allowEmptyArrays:dT.allowEmptyArrays,arrayFormat:J,charset:S,charsetSentinel:typeof T.charsetSentinel==="boolean"?T.charsetSentinel:dT.charsetSentinel,commaRoundTrip:!!T.commaRoundTrip,delimiter:typeof T.delimiter==="undefined"?dT.delimiter:T.delimiter,encode:typeof T.encode==="boolean"?T.encode:dT.encode,encodeDotInKeys:typeof T.encodeDotInKeys==="boolean"?T.encodeDotInKeys:dT.encodeDotInKeys,encoder:typeof T.encoder==="function"?T.encoder:dT.encoder,encodeValuesOnly:typeof T.encodeValuesOnly==="boolean"?T.encodeValuesOnly:dT.encodeValuesOnly,filter:M,format:$,formatter:f,serializeDate:typeof T.serializeDate==="function"?T.serializeDate:dT.serializeDate,skipNulls:typeof T.skipNulls==="boolean"?T.skipNulls:dT.skipNulls,sort:typeof T.sort==="function"?T.sort:null,strictNullHandling:typeof T.strictNullHandling==="boolean"?T.strictNullHandling:dT.strictNullHandling}}function D0(T,S={}){let $=T,f=lw(S),M,J;if(typeof f.filter==="function")J=f.filter,$=J("",$);else if(y$(f.filter))J=f.filter,M=J;let F=[];if(typeof $!=="object"||$===null)return"";let W=JX[f.arrayFormat],A=W==="comma"&&f.commaRoundTrip;if(!M)M=Object.keys($);if(f.sort)M.sort(f.sort);let k=new WeakMap;for(let K=0;K<M.length;++K){let G=M[K];if(f.skipNulls&&$[G]===null)continue;FX(F,WX($[G],G,W,A,f.allowEmptyArrays,f.strictNullHandling,f.skipNulls,f.encodeDotInKeys,f.encode?f.encoder:null,f.filter,f.sort,f.allowDots,f.serializeDate,f.format,f.formatter,f.encodeValuesOnly,f.charset,k))}let X=F.join(f.delimiter),y=f.addQueryPrefix===!0?"?":"";if(f.charsetSentinel)if(f.charset==="iso-8859-1")y+="utf8=%26%2310003%3B&";else y+="utf8=%E2%9C%93&";return X.length>0?y+X:""}var ff="4.71.1";var AX=!1,Mf=void 0,E0=void 0,dw=void 0,rw=void 0,aw=void 0,Q0=void 0,ew=void 0,_F=void 0,U0=void 0,V0=void 0,B0=void 0,HF=void 0,L0=void 0;function kX(T,S={auto:!1}){if(AX)throw new Error(`you must \`import 'openai/shims/${T.kind}'\` before importing anything else from openai`);if(Mf)throw new Error(`can't \`import 'openai/shims/${T.kind}'\` after \`import 'openai/shims/${Mf}'\``);AX=S.auto,Mf=T.kind,E0=T.fetch,dw=T.Request,rw=T.Response,aw=T.Headers,Q0=T.FormData,ew=T.Blob,_F=T.File,U0=T.ReadableStream,V0=T.getMultipartRequestOptions,B0=T.getDefaultAgent,HF=T.fileFromPath,L0=T.isFsReadStream}class N0{constructor(T){this.body=T}get[Symbol.toStringTag](){return"MultipartBody"}}function XX({manuallyImported:T}={}){let S=T?"You may need to use polyfills":`Add one of these imports before your first \`import \u2026 from 'openai'\`:
8
+ `)}import{createHash as r6}from"crypto";var GF="RFC3986",zF={RFC1738:(T)=>String(T).replace(/%20/g,"+"),RFC3986:(T)=>String(T)},$X="RFC1738";var ow=Array.isArray,X$=(()=>{let T=[];for(let S=0;S<256;++S)T.push("%"+((S<16?"0":"")+S.toString(16)).toUpperCase());return T})();var z0=1024,fX=(T,S,$,f,M)=>{if(T.length===0)return T;let J=T;if(typeof T==="symbol")J=Symbol.prototype.toString.call(T);else if(typeof T!=="string")J=String(T);if($==="iso-8859-1")return escape(J).replace(/%u[0-9a-f]{4}/gi,function(W){return"%26%23"+parseInt(W.slice(2),16)+"%3B"});let F="";for(let W=0;W<J.length;W+=z0){let A=J.length>=z0?J.slice(W,W+z0):J,k=[];for(let X=0;X<A.length;++X){let y=A.charCodeAt(X);if(y===45||y===46||y===95||y===126||y>=48&&y<=57||y>=65&&y<=90||y>=97&&y<=122||M===$X&&(y===40||y===41)){k[k.length]=A.charAt(X);continue}if(y<128){k[k.length]=X$[y];continue}if(y<2048){k[k.length]=X$[192|y>>6]+X$[128|y&63];continue}if(y<55296||y>=57344){k[k.length]=X$[224|y>>12]+X$[128|y>>6&63]+X$[128|y&63];continue}X+=1,y=65536+((y&1023)<<10|A.charCodeAt(X)&1023),k[k.length]=X$[240|y>>18]+X$[128|y>>12&63]+X$[128|y>>6&63]+X$[128|y&63]}F+=k.join("")}return F};function MX(T){if(!T||typeof T!=="object")return!1;return!!(T.constructor&&T.constructor.isBuffer&&T.constructor.isBuffer(T))}function _0(T,S){if(ow(T)){let $=[];for(let f=0;f<T.length;f+=1)$.push(S(T[f]));return $}return S(T)}var gw=Object.prototype.hasOwnProperty,JX={brackets(T){return String(T)+"[]"},comma:"comma",indices(T,S){return String(T)+"["+S+"]"},repeat(T){return String(T)}},y$=Array.isArray,tw=Array.prototype.push,FX=function(T,S){tw.apply(T,y$(S)?S:[S])},pw=Date.prototype.toISOString,dT={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:fX,encodeValuesOnly:!1,format:GF,formatter:zF[GF],indices:!1,serializeDate(T){return pw.call(T)},skipNulls:!1,strictNullHandling:!1};function iw(T){return typeof T==="string"||typeof T==="number"||typeof T==="boolean"||typeof T==="symbol"||typeof T==="bigint"}var H0={};function WX(T,S,$,f,M,J,F,W,A,k,X,y,K,G,z,Q,E,B){let L=T,b=B,C=0,D=!1;while((b=b.get(H0))!==void 0&&!D){let O=b.get(T);if(C+=1,typeof O!=="undefined")if(O===C)throw new RangeError("Cyclic object value");else D=!0;if(typeof b.get(H0)==="undefined")C=0}if(typeof k==="function")L=k(S,L);else if(L instanceof Date)L=K?.(L);else if($==="comma"&&y$(L))L=_0(L,function(O){if(O instanceof Date)return K?.(O);return O});if(L===null){if(J)return A&&!Q?A(S,dT.encoder,E,"key",G):S;L=""}if(iw(L)||MX(L)){if(A){let O=Q?S:A(S,dT.encoder,E,"key",G);return[z?.(O)+"="+z?.(A(L,dT.encoder,E,"value",G))]}return[z?.(S)+"="+z?.(String(L))]}let H=[];if(typeof L==="undefined")return H;let U;if($==="comma"&&y$(L)){if(Q&&A)L=_0(L,A);U=[{value:L.length>0?L.join(",")||null:void 0}]}else if(y$(k))U=k;else{let O=Object.keys(L);U=X?O.sort(X):O}let Z=W?String(S).replace(/\./g,"%2E"):String(S),h=f&&y$(L)&&L.length===1?Z+"[]":Z;if(M&&y$(L)&&L.length===0)return h+"[]";for(let O=0;O<U.length;++O){let o=U[O],P=typeof o==="object"&&typeof o.value!=="undefined"?o.value:L[o];if(F&&P===null)continue;let a=y&&W?o.replace(/\./g,"%2E"):o,MT=y$(L)?typeof $==="function"?$(h,a):h:h+(y?"."+a:"["+a+"]");B.set(T,C);let fT=new WeakMap;fT.set(H0,B),FX(H,WX(P,MT,$,f,M,J,F,W,$==="comma"&&Q&&y$(L)?null:A,k,X,y,K,G,z,Q,E,fT))}return H}function lw(T=dT){if(typeof T.allowEmptyArrays!=="undefined"&&typeof T.allowEmptyArrays!=="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof T.encodeDotInKeys!=="undefined"&&typeof T.encodeDotInKeys!=="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(T.encoder!==null&&typeof T.encoder!=="undefined"&&typeof T.encoder!=="function")throw new TypeError("Encoder has to be a function.");let S=T.charset||dT.charset;if(typeof T.charset!=="undefined"&&T.charset!=="utf-8"&&T.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let $=GF;if(typeof T.format!=="undefined"){if(!gw.call(zF,T.format))throw new TypeError("Unknown format option provided.");$=T.format}let f=zF[$],M=dT.filter;if(typeof T.filter==="function"||y$(T.filter))M=T.filter;let J;if(T.arrayFormat&&T.arrayFormat in JX)J=T.arrayFormat;else if("indices"in T)J=T.indices?"indices":"repeat";else J=dT.arrayFormat;if("commaRoundTrip"in T&&typeof T.commaRoundTrip!=="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let F=typeof T.allowDots==="undefined"?!!T.encodeDotInKeys===!0?!0:dT.allowDots:!!T.allowDots;return{addQueryPrefix:typeof T.addQueryPrefix==="boolean"?T.addQueryPrefix:dT.addQueryPrefix,allowDots:F,allowEmptyArrays:typeof T.allowEmptyArrays==="boolean"?!!T.allowEmptyArrays:dT.allowEmptyArrays,arrayFormat:J,charset:S,charsetSentinel:typeof T.charsetSentinel==="boolean"?T.charsetSentinel:dT.charsetSentinel,commaRoundTrip:!!T.commaRoundTrip,delimiter:typeof T.delimiter==="undefined"?dT.delimiter:T.delimiter,encode:typeof T.encode==="boolean"?T.encode:dT.encode,encodeDotInKeys:typeof T.encodeDotInKeys==="boolean"?T.encodeDotInKeys:dT.encodeDotInKeys,encoder:typeof T.encoder==="function"?T.encoder:dT.encoder,encodeValuesOnly:typeof T.encodeValuesOnly==="boolean"?T.encodeValuesOnly:dT.encodeValuesOnly,filter:M,format:$,formatter:f,serializeDate:typeof T.serializeDate==="function"?T.serializeDate:dT.serializeDate,skipNulls:typeof T.skipNulls==="boolean"?T.skipNulls:dT.skipNulls,sort:typeof T.sort==="function"?T.sort:null,strictNullHandling:typeof T.strictNullHandling==="boolean"?T.strictNullHandling:dT.strictNullHandling}}function D0(T,S={}){let $=T,f=lw(S),M,J;if(typeof f.filter==="function")J=f.filter,$=J("",$);else if(y$(f.filter))J=f.filter,M=J;let F=[];if(typeof $!=="object"||$===null)return"";let W=JX[f.arrayFormat],A=W==="comma"&&f.commaRoundTrip;if(!M)M=Object.keys($);if(f.sort)M.sort(f.sort);let k=new WeakMap;for(let K=0;K<M.length;++K){let G=M[K];if(f.skipNulls&&$[G]===null)continue;FX(F,WX($[G],G,W,A,f.allowEmptyArrays,f.strictNullHandling,f.skipNulls,f.encodeDotInKeys,f.encode?f.encoder:null,f.filter,f.sort,f.allowDots,f.serializeDate,f.format,f.formatter,f.encodeValuesOnly,f.charset,k))}let X=F.join(f.delimiter),y=f.addQueryPrefix===!0?"?":"";if(f.charsetSentinel)if(f.charset==="iso-8859-1")y+="utf8=%26%2310003%3B&";else y+="utf8=%E2%9C%93&";return X.length>0?y+X:""}var ff="4.72.0";var AX=!1,Mf=void 0,E0=void 0,dw=void 0,rw=void 0,aw=void 0,Q0=void 0,ew=void 0,_F=void 0,U0=void 0,V0=void 0,B0=void 0,HF=void 0,L0=void 0;function kX(T,S={auto:!1}){if(AX)throw new Error(`you must \`import 'openai/shims/${T.kind}'\` before importing anything else from openai`);if(Mf)throw new Error(`can't \`import 'openai/shims/${T.kind}'\` after \`import 'openai/shims/${Mf}'\``);AX=S.auto,Mf=T.kind,E0=T.fetch,dw=T.Request,rw=T.Response,aw=T.Headers,Q0=T.FormData,ew=T.Blob,_F=T.File,U0=T.ReadableStream,V0=T.getMultipartRequestOptions,B0=T.getDefaultAgent,HF=T.fileFromPath,L0=T.isFsReadStream}class N0{constructor(T){this.body=T}get[Symbol.toStringTag](){return"MultipartBody"}}function XX({manuallyImported:T}={}){let S=T?"You may need to use polyfills":`Add one of these imports before your first \`import \u2026 from 'openai'\`:
9
9
  - \`import 'openai/shims/node'\` (if you're running on Node)
10
10
  - \`import 'openai/shims/web'\` (otherwise)
11
11
  `,$,f,M,J;try{$=fetch,f=Request,M=Response,J=Headers}catch(F){throw new Error(`this environment is missing the following Web Fetch API type: ${F.message}. ${S}`)}return{kind:"web",fetch:$,Request:f,Response:M,Headers:J,FormData:typeof FormData!=="undefined"?FormData:class F{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${S}`)}},Blob:typeof Blob!=="undefined"?Blob:class F{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${S}`)}},File:typeof File!=="undefined"?File:class F{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${S}`)}},ReadableStream:typeof ReadableStream!=="undefined"?ReadableStream:class F{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${S}`)}},getMultipartRequestOptions:async(F,W)=>({...W,body:new N0(F)}),getDefaultAgent:(F)=>{return},fileFromPath:()=>{throw new Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/openai/openai-node#file-uploads")},isFsReadStream:(F)=>!1}}import{ReadStream as T6}from"fs";function yX(){let T=XX();function S($){return $ instanceof T6}return{...T,isFsReadStream:S}}if(!Mf)kX(yX(),{auto:!0});class $T extends Error{}class gT extends $T{constructor(T,S,$,f){super(`${gT.makeMessage(T,S,$)}`);this.status=T,this.headers=f,this.request_id=f?.["x-request-id"];let M=S;this.error=M,this.code=M?.code,this.param=M?.param,this.type=M?.type}static makeMessage(T,S,$){let f=S?.message?typeof S.message==="string"?S.message:JSON.stringify(S.message):S?JSON.stringify(S):$;if(T&&f)return`${T} ${f}`;if(T)return`${T} status code (no body)`;if(f)return f;return"(no status code or body)"}static generate(T,S,$,f){if(!T)return new Jf({message:$,cause:CF(S)});let M=S?.error;if(T===400)return new DF(T,M,$,f);if(T===401)return new EF(T,M,$,f);if(T===403)return new QF(T,M,$,f);if(T===404)return new UF(T,M,$,f);if(T===409)return new VF(T,M,$,f);if(T===422)return new BF(T,M,$,f);if(T===429)return new LF(T,M,$,f);if(T>=500)return new NF(T,M,$,f);return new gT(T,M,$,f)}}class SS extends gT{constructor({message:T}={}){super(void 0,void 0,T||"Request was aborted.",void 0);this.status=void 0}}class Jf extends gT{constructor({message:T,cause:S}){super(void 0,void 0,T||"Connection error.",void 0);if(this.status=void 0,S)this.cause=S}}class Ff extends Jf{constructor({message:T}={}){super({message:T??"Request timed out."})}}class DF extends gT{constructor(){super(...arguments);this.status=400}}class EF extends gT{constructor(){super(...arguments);this.status=401}}class QF extends gT{constructor(){super(...arguments);this.status=403}}class UF extends gT{constructor(){super(...arguments);this.status=404}}class VF extends gT{constructor(){super(...arguments);this.status=409}}class BF extends gT{constructor(){super(...arguments);this.status=422}}class LF extends gT{constructor(){super(...arguments);this.status=429}}class NF extends gT{}class aM extends $T{constructor(){super("Could not parse response content as the length limit was reached")}}class eM extends $T{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class o${constructor(){this.buffer=[],this.trailingCR=!1}decode(T){let S=this.decodeText(T);if(this.trailingCR)S="\r"+S,this.trailingCR=!1;if(S.endsWith("\r"))this.trailingCR=!0,S=S.slice(0,-1);if(!S)return[];let $=o$.NEWLINE_CHARS.has(S[S.length-1]||""),f=S.split(o$.NEWLINE_REGEXP);if($)f.pop();if(f.length===1&&!$)return this.buffer.push(f[0]),[];if(this.buffer.length>0)f=[this.buffer.join("")+f[0],...f.slice(1)],this.buffer=[];if(!$)this.buffer=[f.pop()||""];return f}decodeText(T){if(T==null)return"";if(typeof T==="string")return T;if(typeof Buffer!=="undefined"){if(T instanceof Buffer)return T.toString();if(T instanceof Uint8Array)return Buffer.from(T).toString();throw new $T(`Unexpected: received non-Uint8Array (${T.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if(typeof TextDecoder!=="undefined"){if(T instanceof Uint8Array||T instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(T);throw new $T(`Unexpected: received non-Uint8Array/ArrayBuffer (${T.constructor.name}) in a web platform. Please report this error.`)}throw new $T("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length&&!this.trailingCR)return[];let T=[this.buffer.join("")];return this.buffer=[],this.trailingCR=!1,T}}o$.NEWLINE_CHARS=new Set(["\n","\r"]);o$.NEWLINE_REGEXP=/\r\n|[\n\r]/g;class NS{constructor(T,S){this.iterator=T,this.controller=S}static fromSSEResponse(T,S){let $=!1;async function*f(){if($)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");$=!0;let M=!1;try{for await(let J of $6(T,S)){if(M)continue;if(J.data.startsWith("[DONE]")){M=!0;continue}if(J.event===null){let F;try{F=JSON.parse(J.data)}catch(W){throw console.error("Could not parse message into JSON:",J.data),console.error("From chunk:",J.raw),W}if(F&&F.error)throw new gT(void 0,F.error,void 0,void 0);yield F}else{let F;try{F=JSON.parse(J.data)}catch(W){throw console.error("Could not parse message into JSON:",J.data),console.error("From chunk:",J.raw),W}if(J.event=="error")throw new gT(void 0,F.error,F.message,void 0);yield{event:J.event,data:F}}}M=!0}catch(J){if(J instanceof Error&&J.name==="AbortError")return;throw J}finally{if(!M)S.abort()}}return new NS(f,S)}static fromReadableStream(T,S){let $=!1;async function*f(){let J=new o$,F=wX(T);for await(let W of F)for(let A of J.decode(W))yield A;for(let W of J.flush())yield W}async function*M(){if($)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");$=!0;let J=!1;try{for await(let F of f()){if(J)continue;if(F)yield JSON.parse(F)}J=!0}catch(F){if(F instanceof Error&&F.name==="AbortError")return;throw F}finally{if(!J)S.abort()}}return new NS(M,S)}[Symbol.asyncIterator](){return this.iterator()}tee(){let T=[],S=[],$=this.iterator(),f=(M)=>{return{next:()=>{if(M.length===0){let J=$.next();T.push(J),S.push(J)}return M.shift()}}};return[new NS(()=>f(T),this.controller),new NS(()=>f(S),this.controller)]}toReadableStream(){let T=this,S,$=new TextEncoder;return new U0({async start(){S=T[Symbol.asyncIterator]()},async pull(f){try{let{value:M,done:J}=await S.next();if(J)return f.close();let F=$.encode(JSON.stringify(M)+"\n");f.enqueue(F)}catch(M){f.error(M)}},async cancel(){await S.return?.()}})}}async function*$6(T,S){if(!T.body)throw S.abort(),new $T("Attempted to iterate over a response with no body");let $=new KX,f=new o$,M=wX(T.body);for await(let J of f6(M))for(let F of f.decode(J)){let W=$.decode(F);if(W)yield W}for(let J of f.flush()){let F=$.decode(J);if(F)yield F}}async function*f6(T){let S=new Uint8Array;for await(let $ of T){if($==null)continue;let f=$ instanceof ArrayBuffer?new Uint8Array($):typeof $==="string"?new TextEncoder().encode($):$,M=new Uint8Array(S.length+f.length);M.set(S),M.set(f,S.length),S=M;let J;while((J=M6(S))!==-1)yield S.slice(0,J),S=S.slice(J)}if(S.length>0)yield S}function M6(T){for(let f=0;f<T.length-2;f++){if(T[f]===10&&T[f+1]===10)return f+2;if(T[f]===13&&T[f+1]===13)return f+2;if(T[f]===13&&T[f+1]===10&&f+3<T.length&&T[f+2]===13&&T[f+3]===10)return f+4}return-1}class KX{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(T){if(T.endsWith("\r"))T=T.substring(0,T.length-1);if(!T){if(!this.event&&!this.data.length)return null;let M={event:this.event,data:this.data.join("\n"),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],M}if(this.chunks.push(T),T.startsWith(":"))return null;let[S,$,f]=J6(T,":");if(f.startsWith(" "))f=f.substring(1);if(S==="event")this.event=f;else if(S==="data")this.data.push(f);return null}}function J6(T,S){let $=T.indexOf(S);if($!==-1)return[T.substring(0,$),S,T.substring($+S.length)];return[T,"",""]}function wX(T){if(T[Symbol.asyncIterator])return T;let S=T.getReader();return{async next(){try{let $=await S.read();if($?.done)S.releaseLock();return $}catch($){throw S.releaseLock(),$}},async return(){let $=S.cancel();return S.releaseLock(),await $,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}var YX=(T)=>T!=null&&typeof T==="object"&&typeof T.url==="string"&&typeof T.blob==="function",RX=(T)=>T!=null&&typeof T==="object"&&typeof T.name==="string"&&typeof T.lastModified==="number"&&sM(T),sM=(T)=>T!=null&&typeof T==="object"&&typeof T.size==="number"&&typeof T.type==="string"&&typeof T.text==="function"&&typeof T.slice==="function"&&typeof T.arrayBuffer==="function",F6=(T)=>{return RX(T)||YX(T)||L0(T)};async function j0(T,S,$){if(T=await T,RX(T))return T;if(YX(T)){let M=await T.blob();S||(S=new URL(T.url).pathname.split(/[\\/]/).pop()??"unknown_file");let J=sM(M)?[await M.arrayBuffer()]:[M];return new _F(J,S,$)}let f=await W6(T);if(S||(S=k6(T)??"unknown_file"),!$?.type){let M=f[0]?.type;if(typeof M==="string")$={...$,type:M}}return new _F(f,S,$)}async function W6(T){let S=[];if(typeof T==="string"||ArrayBuffer.isView(T)||T instanceof ArrayBuffer)S.push(T);else if(sM(T))S.push(await T.arrayBuffer());else if(X6(T))for await(let $ of T)S.push($);else throw new Error(`Unexpected data type: ${typeof T}; constructor: ${T?.constructor?.name}; props: ${A6(T)}`);return S}function A6(T){return`[${Object.getOwnPropertyNames(T).map(($)=>`"${$}"`).join(", ")}]`}function k6(T){return C0(T.name)||C0(T.filename)||C0(T.path)?.split(/[\\/]/).pop()}var C0=(T)=>{if(typeof T==="string")return T;if(typeof Buffer!=="undefined"&&T instanceof Buffer)return String(T);return},X6=(T)=>T!=null&&typeof T==="object"&&typeof T[Symbol.asyncIterator]==="function",I0=(T)=>T&&typeof T==="object"&&T.body&&T[Symbol.toStringTag]==="MultipartBody";var vS=async(T)=>{let S=await OX(T.body);return V0(S,T)},OX=async(T)=>{let S=new Q0;return await Promise.all(Object.entries(T||{}).map(([$,f])=>x0(S,$,f))),S};var x0=async(T,S,$)=>{if($===void 0)return;if($==null)throw new TypeError(`Received null for "${S}"; to pass null in FormData, you must use the string 'null'`);if(typeof $==="string"||typeof $==="number"||typeof $==="boolean")T.append(S,String($));else if(F6($)){let f=await j0($);T.append(S,f)}else if(Array.isArray($))await Promise.all($.map((f)=>x0(T,S+"[]",f)));else if(typeof $==="object")await Promise.all(Object.entries($).map(([f,M])=>x0(T,`${S}[${f}]`,M)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${$} instead`)};var K6=function(T,S,$,f,M){if(f==="m")throw new TypeError("Private method is not writable");if(f==="a"&&!M)throw new TypeError("Private accessor was defined without a setter");if(typeof S==="function"?T!==S||!M:!S.has(T))throw new TypeError("Cannot write private member to an object whose class did not declare it");return f==="a"?M.call(T,$):M?M.value=$:S.set(T,$),$},w6=function(T,S,$,f){if($==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof S==="function"?T!==S||!f:!S.has(T))throw new TypeError("Cannot read private member from an object whose class did not declare it");return $==="m"?f:$==="a"?f.call(T):f?f.value:S.get(T)},xF;async function EX(T){let{response:S}=T;if(T.options.stream){if(ef("response",S.status,S.url,S.headers,S.body),T.options.__streamClass)return T.options.__streamClass.fromSSEResponse(S,T.controller);return NS.fromSSEResponse(S,T.controller)}if(S.status===204)return null;if(T.options.__binaryResponse)return S;let $=S.headers.get("content-type");if($?.includes("application/json")||$?.includes("application/vnd.api+json")){let J=await S.json();return ef("response",S.status,S.url,S.headers,J),QX(J,S)}let M=await S.text();return ef("response",S.status,S.url,S.headers,M),M}function QX(T,S){if(!T||typeof T!=="object"||Array.isArray(T))return T;return Object.defineProperty(T,"_request_id",{value:S.headers.get("x-request-id"),enumerable:!1})}class jF extends Promise{constructor(T,S=EX){super(($)=>{$(null)});this.responsePromise=T,this.parseResponse=S}_thenUnwrap(T){return new jF(this.responsePromise,async(S)=>QX(T(await this.parseResponse(S),S),S.response))}asResponse(){return this.responsePromise.then((T)=>T.response)}async withResponse(){let[T,S]=await Promise.all([this.parse(),this.asResponse()]);return{data:T,response:S,request_id:S.headers.get("x-request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then(this.parseResponse);return this.parsedPromise}then(T,S){return this.parse().then(T,S)}catch(T){return this.parse().catch(T)}finally(T){return this.parse().finally(T)}}class q0{constructor({baseURL:T,maxRetries:S=2,timeout:$=600000,httpAgent:f,fetch:M}){this.baseURL=T,this.maxRetries=b0("maxRetries",S),this.timeout=b0("timeout",$),this.httpAgent=f,this.fetch=M??E0}authHeaders(T){return{}}defaultHeaders(T){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...z6(),...this.authHeaders(T)}}validateHeaders(T,S){}defaultIdempotencyKey(){return`stainless-node-retry-${E6()}`}get(T,S){return this.methodRequest("get",T,S)}post(T,S){return this.methodRequest("post",T,S)}patch(T,S){return this.methodRequest("patch",T,S)}put(T,S){return this.methodRequest("put",T,S)}delete(T,S){return this.methodRequest("delete",T,S)}methodRequest(T,S,$){return this.request(Promise.resolve($).then(async(f)=>{let M=f&&sM(f?.body)?new DataView(await f.body.arrayBuffer()):f?.body instanceof DataView?f.body:f?.body instanceof ArrayBuffer?new DataView(f.body):f&&ArrayBuffer.isView(f?.body)?new DataView(f.body.buffer):f?.body;return{method:T,path:S,...f,body:M}}))}getAPIList(T,S,$){return this.requestAPIList(S,{method:"get",path:T,...$})}calculateContentLength(T){if(typeof T==="string"){if(typeof Buffer!=="undefined")return Buffer.byteLength(T,"utf8").toString();if(typeof TextEncoder!=="undefined")return new TextEncoder().encode(T).length.toString()}else if(ArrayBuffer.isView(T))return T.byteLength.toString();return null}buildRequest(T,{retryCount:S=0}={}){let{method:$,path:f,query:M,headers:J={}}=T,F=ArrayBuffer.isView(T.body)||T.__binaryRequest&&typeof T.body==="string"?T.body:I0(T.body)?T.body.body:T.body?JSON.stringify(T.body,null,2):null,W=this.calculateContentLength(F),A=this.buildURL(f,M);if("timeout"in T)b0("timeout",T.timeout);let k=T.timeout??this.timeout,X=T.httpAgent??this.httpAgent??B0(A),y=k+1000;if(typeof X?.options?.timeout==="number"&&y>(X.options.timeout??0))X.options.timeout=y;if(this.idempotencyHeader&&$!=="get"){if(!T.idempotencyKey)T.idempotencyKey=this.defaultIdempotencyKey();J[this.idempotencyHeader]=T.idempotencyKey}let K=this.buildHeaders({options:T,headers:J,contentLength:W,retryCount:S});return{req:{method:$,...F&&{body:F},headers:K,...X&&{agent:X},signal:T.signal??null},url:A,timeout:k}}buildHeaders({options:T,headers:S,contentLength:$,retryCount:f}){let M={};if($)M["content-length"]=$;let J=this.defaultHeaders(T);if(HX(M,J),HX(M,S),I0(T.body)&&Mf!=="node")delete M["content-type"];if(DX(J,"x-stainless-retry-count")===void 0&&DX(S,"x-stainless-retry-count")===void 0)M["x-stainless-retry-count"]=String(f);return this.validateHeaders(M,S),M}async prepareOptions(T){}async prepareRequest(T,{url:S,options:$}){}parseHeaders(T){return!T?{}:(Symbol.iterator in T)?Object.fromEntries(Array.from(T).map((S)=>[...S])):{...T}}makeStatusError(T,S,$,f){return gT.generate(T,S,$,f)}request(T,S=null){return new jF(this.makeRequest(T,S))}async makeRequest(T,S){let $=await T,f=$.maxRetries??this.maxRetries;if(S==null)S=f;await this.prepareOptions($);let{req:M,url:J,timeout:F}=this.buildRequest($,{retryCount:f-S});if(await this.prepareRequest(M,{url:J,options:$}),ef("request",J,$,M.headers),$.signal?.aborted)throw new SS;let W=new AbortController,A=await this.fetchWithTimeout(J,M,F,W).catch(CF);if(A instanceof Error){if($.signal?.aborted)throw new SS;if(S)return this.retryRequest($,S);if(A.name==="AbortError")throw new Ff;throw new Jf({cause:A})}let k=Y6(A.headers);if(!A.ok){if(S&&this.shouldRetry(A)){let Q=`retrying, ${S} attempts remaining`;return ef(`response (error; ${Q})`,A.status,J,k),this.retryRequest($,S,k)}let X=await A.text().catch((Q)=>CF(Q).message),y=_6(X),K=y?void 0:X;throw ef(`response (error; ${S?"(error; no more retries left)":"(error; not retryable)"})`,A.status,J,k,K),this.makeStatusError(A.status,y,K,k)}return{response:A,options:$,controller:W}}requestAPIList(T,S){let $=this.makeRequest(S,null);return new UX(this,$,T)}buildURL(T,S){let $=D6(T)?new URL(T):new URL(this.baseURL+(this.baseURL.endsWith("/")&&T.startsWith("/")?T.slice(1):T)),f=this.defaultQuery();if(!VX(f))S={...f,...S};if(typeof S==="object"&&S&&!Array.isArray(S))$.search=this.stringifyQuery(S);return $.toString()}stringifyQuery(T){return Object.entries(T).filter(([S,$])=>typeof $!=="undefined").map(([S,$])=>{if(typeof $==="string"||typeof $==="number"||typeof $==="boolean")return`${encodeURIComponent(S)}=${encodeURIComponent($)}`;if($===null)return`${encodeURIComponent(S)}=`;throw new $T(`Cannot stringify type ${typeof $}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}async fetchWithTimeout(T,S,$,f){let{signal:M,...J}=S||{};if(M)M.addEventListener("abort",()=>f.abort());let F=setTimeout(()=>f.abort(),$);return this.getRequestClient().fetch.call(void 0,T,{signal:f.signal,...J}).finally(()=>{clearTimeout(F)})}getRequestClient(){return{fetch:this.fetch}}shouldRetry(T){let S=T.headers.get("x-should-retry");if(S==="true")return!0;if(S==="false")return!1;if(T.status===408)return!0;if(T.status===409)return!0;if(T.status===429)return!0;if(T.status>=500)return!0;return!1}async retryRequest(T,S,$){let f,M=$?.["retry-after-ms"];if(M){let F=parseFloat(M);if(!Number.isNaN(F))f=F}let J=$?.["retry-after"];if(J&&!f){let F=parseFloat(J);if(!Number.isNaN(F))f=F*1000;else f=Date.parse(J)-Date.now()}if(!(f&&0<=f&&f<60000)){let F=T.maxRetries??this.maxRetries;f=this.calculateDefaultRetryTimeoutMillis(S,F)}return await D$(f),this.makeRequest(T,S-1)}calculateDefaultRetryTimeoutMillis(T,S){let M=S-T,J=Math.min(0.5*Math.pow(2,M),8),F=1-Math.random()*0.25;return J*F*1000}getUserAgent(){return`${this.constructor.name}/JS ${ff}`}}class IF{constructor(T,S,$,f){xF.set(this,void 0),K6(this,xF,T,"f"),this.options=f,this.response=S,this.body=$}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageInfo()!=null}async getNextPage(){let T=this.nextPageInfo();if(!T)throw new $T("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");let S={...this.options};if("params"in T&&typeof S.query==="object")S.query={...S.query,...T.params};else if("url"in T){let $=[...Object.entries(S.query||{}),...T.url.searchParams.entries()];for(let[f,M]of $)T.url.searchParams.set(f,M);S.query=void 0,S.path=T.url.toString()}return await w6(this,xF,"f").requestAPIList(this.constructor,S)}async*iterPages(){let T=this;yield T;while(T.hasNextPage())T=await T.getNextPage(),yield T}async*[(xF=new WeakMap,Symbol.asyncIterator)](){for await(let T of this.iterPages())for(let S of T.getPaginatedItems())yield S}}class UX extends jF{constructor(T,S,$){super(S,async(f)=>new $(T,f.response,await EX(f),f.options))}async*[Symbol.asyncIterator](){let T=await this;for await(let S of T)yield S}}var Y6=(T)=>{return new Proxy(Object.fromEntries(T.entries()),{get(S,$){let f=$.toString();return S[f.toLowerCase()]||S[f]}})},R6={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},LT=(T)=>{return typeof T==="object"&&T!==null&&!VX(T)&&Object.keys(T).every((S)=>BX(R6,S))},O6=()=>{if(typeof Deno!=="undefined"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ff,"X-Stainless-OS":zX(Deno.build.os),"X-Stainless-Arch":GX(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version==="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime!=="undefined")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ff,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if(Object.prototype.toString.call(typeof process!=="undefined"?process:0)==="[object process]")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ff,"X-Stainless-OS":zX(process.platform),"X-Stainless-Arch":GX(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};let T=G6();if(T)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ff,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${T.browser}`,"X-Stainless-Runtime-Version":T.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ff,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function G6(){if(typeof navigator==="undefined"||!navigator)return null;let T=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:S,pattern:$}of T){let f=$.exec(navigator.userAgent);if(f){let M=f[1]||0,J=f[2]||0,F=f[3]||0;return{browser:S,version:`${M}.${J}.${F}`}}}return null}var GX=(T)=>{if(T==="x32")return"x32";if(T==="x86_64"||T==="x64")return"x64";if(T==="arm")return"arm";if(T==="aarch64"||T==="arm64")return"arm64";if(T)return`other:${T}`;return"unknown"},zX=(T)=>{if(T=T.toLowerCase(),T.includes("ios"))return"iOS";if(T==="android")return"Android";if(T==="darwin")return"MacOS";if(T==="win32")return"Windows";if(T==="freebsd")return"FreeBSD";if(T==="openbsd")return"OpenBSD";if(T==="linux")return"Linux";if(T)return`Other:${T}`;return"Unknown"},_X,z6=()=>{return _X??(_X=O6())},_6=(T)=>{try{return JSON.parse(T)}catch(S){return}},H6=new RegExp("^(?:[a-z]+:)?//","i"),D6=(T)=>{return H6.test(T)},D$=(T)=>new Promise((S)=>setTimeout(S,T)),b0=(T,S)=>{if(typeof S!=="number"||!Number.isInteger(S))throw new $T(`${T} must be an integer`);if(S<0)throw new $T(`${T} must be a positive integer`);return S},CF=(T)=>{if(T instanceof Error)return T;if(typeof T==="object"&&T!==null)try{return new Error(JSON.stringify(T))}catch{}return new Error(T)};var TJ=(T)=>{if(typeof process!=="undefined")return process.env?.[T]?.trim()??void 0;if(typeof Deno!=="undefined")return Deno.env?.get?.(T)?.trim();return};function VX(T){if(!T)return!0;for(let S in T)return!1;return!0}function BX(T,S){return Object.prototype.hasOwnProperty.call(T,S)}function HX(T,S){for(let $ in S){if(!BX(S,$))continue;let f=$.toLowerCase();if(!f)continue;let M=S[$];if(M===null)delete T[f];else if(M!==void 0)T[f]=M}}function ef(T,...S){if(typeof process!=="undefined"&&process?.env?.DEBUG==="true")console.log(`OpenAI:DEBUG:${T}`,...S)}var E6=()=>{return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(T)=>{let S=Math.random()*16|0;return(T==="x"?S:S&3|8).toString(16)})},LX=()=>{return typeof window!=="undefined"&&typeof window.document!=="undefined"&&typeof navigator!=="undefined"},Q6=(T)=>{return typeof T?.get==="function"};var DX=(T,S)=>{let $=S.toLowerCase();if(Q6(T)){let f=S[0]?.toUpperCase()+S.substring(1).replace(/([^\w])(\w)/g,(M,J,F)=>J+F.toUpperCase());for(let M of[S,$,S.toUpperCase(),f]){let J=T.get(M);if(J)return J}}for(let[f,M]of Object.entries(T))if(f.toLowerCase()===$){if(Array.isArray(M)){if(M.length<=1)return M[0];return console.warn(`Received ${M.length} entries for the ${S} header, using the first entry.`),M[0]}return M}return};function SJ(T){return T!=null&&typeof T==="object"&&!Array.isArray(T)}class Z0 extends IF{constructor(T,S,$,f){super(T,S,$,f);this.data=$.data||[],this.object=$.object}getPaginatedItems(){return this.data??[]}nextPageParams(){return null}nextPageInfo(){return null}}class PT extends IF{constructor(T,S,$,f){super(T,S,$,f);this.data=$.data||[]}getPaginatedItems(){return this.data??[]}nextPageParams(){let T=this.nextPageInfo();if(!T)return null;if("params"in T)return T.params;let S=Object.fromEntries(T.url.searchParams);if(!Object.keys(S).length)return null;return S}nextPageInfo(){let T=this.getPaginatedItems();if(!T.length)return null;let S=T[T.length-1]?.id;if(!S)return null;return{params:{after:S}}}}class i{constructor(T){this._client=T}}class $J extends i{create(T,S){return this._client.post("/chat/completions",{body:T,...S,stream:T.stream??!1})}}class Af extends i{constructor(){super(...arguments);this.completions=new $J(this._client)}}Af.Completions=$J;class fJ extends i{create(T,S){return this._client.post("/audio/speech",{body:T,...S,__binaryResponse:!0})}}class MJ extends i{create(T,S){return this._client.post("/audio/transcriptions",vS({body:T,...S}))}}class JJ extends i{create(T,S){return this._client.post("/audio/translations",vS({body:T,...S}))}}class E$ extends i{constructor(){super(...arguments);this.transcriptions=new MJ(this._client),this.translations=new JJ(this._client),this.speech=new fJ(this._client)}}E$.Transcriptions=MJ;E$.Translations=JJ;E$.Speech=fJ;class kf extends i{create(T,S){return this._client.post("/batches",{body:T,...S})}retrieve(T,S){return this._client.get(`/batches/${T}`,S)}list(T={},S){if(LT(T))return this.list({},T);return this._client.getAPIList("/batches",sf,{query:T,...S})}cancel(T,S){return this._client.post(`/batches/${T}/cancel`,S)}}class sf extends PT{}kf.BatchesPage=sf;class TM extends i{create(T,S){return this._client.post("/assistants",{body:T,...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers}})}retrieve(T,S){return this._client.get(`/assistants/${T}`,{...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers}})}update(T,S,$){return this._client.post(`/assistants/${T}`,{body:S,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}list(T={},S){if(LT(T))return this.list({},T);return this._client.getAPIList("/assistants",FJ,{query:T,...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers}})}del(T,S){return this._client.delete(`/assistants/${T}`,{...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers}})}}class FJ extends PT{}TM.AssistantsPage=FJ;function m0(T){return typeof T.parse==="function"}var g$=(T)=>{return T?.role==="assistant"},h0=(T)=>{return T?.role==="function"},v0=(T)=>{return T?.role==="tool"};var T$=function(T,S,$,f,M){if(f==="m")throw new TypeError("Private method is not writable");if(f==="a"&&!M)throw new TypeError("Private accessor was defined without a setter");if(typeof S==="function"?T!==S||!M:!S.has(T))throw new TypeError("Cannot write private member to an object whose class did not declare it");return f==="a"?M.call(T,$):M?M.value=$:S.set(T,$),$},mT=function(T,S,$,f){if($==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof S==="function"?T!==S||!f:!S.has(T))throw new TypeError("Cannot read private member from an object whose class did not declare it");return $==="m"?f:$==="a"?f.call(T):f?f.value:S.get(T)},P0,bF,qF,WJ,AJ,ZF,kJ,Q$,XJ,mF,hF,SM,NX;class yJ{constructor(){P0.add(this),this.controller=new AbortController,bF.set(this,void 0),qF.set(this,()=>{}),WJ.set(this,()=>{}),AJ.set(this,void 0),ZF.set(this,()=>{}),kJ.set(this,()=>{}),Q$.set(this,{}),XJ.set(this,!1),mF.set(this,!1),hF.set(this,!1),SM.set(this,!1),T$(this,bF,new Promise((T,S)=>{T$(this,qF,T,"f"),T$(this,WJ,S,"f")}),"f"),T$(this,AJ,new Promise((T,S)=>{T$(this,ZF,T,"f"),T$(this,kJ,S,"f")}),"f"),mT(this,bF,"f").catch(()=>{}),mT(this,AJ,"f").catch(()=>{})}_run(T){setTimeout(()=>{T().then(()=>{this._emitFinal(),this._emit("end")},mT(this,P0,"m",NX).bind(this))},0)}_connected(){if(this.ended)return;mT(this,qF,"f").call(this),this._emit("connect")}get ended(){return mT(this,XJ,"f")}get errored(){return mT(this,mF,"f")}get aborted(){return mT(this,hF,"f")}abort(){this.controller.abort()}on(T,S){return(mT(this,Q$,"f")[T]||(mT(this,Q$,"f")[T]=[])).push({listener:S}),this}off(T,S){let $=mT(this,Q$,"f")[T];if(!$)return this;let f=$.findIndex((M)=>M.listener===S);if(f>=0)$.splice(f,1);return this}once(T,S){return(mT(this,Q$,"f")[T]||(mT(this,Q$,"f")[T]=[])).push({listener:S,once:!0}),this}emitted(T){return new Promise((S,$)=>{if(T$(this,SM,!0,"f"),T!=="error")this.once("error",$);this.once(T,S)})}async done(){T$(this,SM,!0,"f"),await mT(this,AJ,"f")}_emit(T,...S){if(mT(this,XJ,"f"))return;if(T==="end")T$(this,XJ,!0,"f"),mT(this,ZF,"f").call(this);let $=mT(this,Q$,"f")[T];if($)mT(this,Q$,"f")[T]=$.filter((f)=>!f.once),$.forEach(({listener:f})=>f(...S));if(T==="abort"){let f=S[0];if(!mT(this,SM,"f")&&!$?.length)Promise.reject(f);mT(this,WJ,"f").call(this,f),mT(this,kJ,"f").call(this,f),this._emit("end");return}if(T==="error"){let f=S[0];if(!mT(this,SM,"f")&&!$?.length)Promise.reject(f);mT(this,WJ,"f").call(this,f),mT(this,kJ,"f").call(this,f),this._emit("end")}}_emitFinal(){}}bF=new WeakMap,qF=new WeakMap,WJ=new WeakMap,AJ=new WeakMap,ZF=new WeakMap,kJ=new WeakMap,Q$=new WeakMap,XJ=new WeakMap,mF=new WeakMap,hF=new WeakMap,SM=new WeakMap,P0=new WeakSet,NX=function T(S){if(T$(this,mF,!0,"f"),S instanceof Error&&S.name==="AbortError")S=new SS;if(S instanceof SS)return T$(this,hF,!0,"f"),this._emit("abort",S);if(S instanceof $T)return this._emit("error",S);if(S instanceof Error){let $=new $T(S.message);return $.cause=S,this._emit("error",$)}return this._emit("error",new $T(String(S)))};function n0(T){return T?.$brand==="auto-parseable-response-format"}function Xf(T){return T?.$brand==="auto-parseable-tool"}function CX(T,S){if(!S||!c0(S))return{...T,choices:T.choices.map(($)=>({...$,message:{...$.message,parsed:null,tool_calls:$.message.tool_calls??[]}}))};return KJ(T,S)}function KJ(T,S){let $=T.choices.map((f)=>{if(f.finish_reason==="length")throw new aM;if(f.finish_reason==="content_filter")throw new eM;return{...f,message:{...f.message,tool_calls:f.message.tool_calls?.map((M)=>x6(S,M))??[],parsed:f.message.content&&!f.message.refusal?C6(S,f.message.content):null}}});return{...T,choices:$}}function C6(T,S){if(T.response_format?.type!=="json_schema")return null;if(T.response_format?.type==="json_schema"){if("$parseRaw"in T.response_format)return T.response_format.$parseRaw(S);return JSON.parse(S)}return null}function x6(T,S){let $=T.tools?.find((f)=>f.function?.name===S.function.name);return{...S,function:{...S.function,parsed_arguments:Xf($)?$.$parseRaw(S.function.arguments):$?.function.strict?JSON.parse(S.function.arguments):null}}}function xX(T,S){if(!T)return!1;let $=T.tools?.find((f)=>f.function?.name===S.function.name);return Xf($)||$?.function.strict||!1}function c0(T){if(n0(T.response_format))return!0;return T.tools?.some((S)=>Xf(S)||S.type==="function"&&S.function.strict===!0)??!1}function jX(T){for(let S of T??[]){if(S.type!=="function")throw new $T(`Currently only \`function\` tool types support auto-parsing; Received \`${S.type}\``);if(S.function.strict!==!0)throw new $T(`The \`${S.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var DS=function(T,S,$,f){if($==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof S==="function"?T!==S||!f:!S.has(T))throw new TypeError("Cannot read private member from an object whose class did not declare it");return $==="m"?f:$==="a"?f.call(T):f?f.value:S.get(T)},KS,o0,vF,g0,t0,p0,bX,i0,IX=10;class wJ extends yJ{constructor(){super(...arguments);KS.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(T){this._chatCompletions.push(T),this._emit("chatCompletion",T);let S=T.choices[0]?.message;if(S)this._addMessage(S);return T}_addMessage(T,S=!0){if(!("content"in T))T.content=null;if(this.messages.push(T),S){if(this._emit("message",T),(h0(T)||v0(T))&&T.content)this._emit("functionCallResult",T.content);else if(g$(T)&&T.function_call)this._emit("functionCall",T.function_call);else if(g$(T)&&T.tool_calls){for(let $ of T.tool_calls)if($.type==="function")this._emit("functionCall",$.function)}}}async finalChatCompletion(){await this.done();let T=this._chatCompletions[this._chatCompletions.length-1];if(!T)throw new $T("stream ended without producing a ChatCompletion");return T}async finalContent(){return await this.done(),DS(this,KS,"m",o0).call(this)}async finalMessage(){return await this.done(),DS(this,KS,"m",vF).call(this)}async finalFunctionCall(){return await this.done(),DS(this,KS,"m",g0).call(this)}async finalFunctionCallResult(){return await this.done(),DS(this,KS,"m",t0).call(this)}async totalUsage(){return await this.done(),DS(this,KS,"m",p0).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let T=this._chatCompletions[this._chatCompletions.length-1];if(T)this._emit("finalChatCompletion",T);let S=DS(this,KS,"m",vF).call(this);if(S)this._emit("finalMessage",S);let $=DS(this,KS,"m",o0).call(this);if($)this._emit("finalContent",$);let f=DS(this,KS,"m",g0).call(this);if(f)this._emit("finalFunctionCall",f);let M=DS(this,KS,"m",t0).call(this);if(M!=null)this._emit("finalFunctionCallResult",M);if(this._chatCompletions.some((J)=>J.usage))this._emit("totalUsage",DS(this,KS,"m",p0).call(this))}async _createChatCompletion(T,S,$){let f=$?.signal;if(f){if(f.aborted)this.controller.abort();f.addEventListener("abort",()=>this.controller.abort())}DS(this,KS,"m",bX).call(this,S);let M=await T.chat.completions.create({...S,stream:!1},{...$,signal:this.controller.signal});return this._connected(),this._addChatCompletion(KJ(M,S))}async _runChatCompletion(T,S,$){for(let f of S.messages)this._addMessage(f,!1);return await this._createChatCompletion(T,S,$)}async _runFunctions(T,S,$){let{function_call:M="auto",stream:J,...F}=S,W=typeof M!=="string"&&M?.name,{maxChatCompletions:A=IX}=$||{},k={};for(let y of S.functions)k[y.name||y.function.name]=y;let X=S.functions.map((y)=>({name:y.name||y.function.name,parameters:y.parameters,description:y.description}));for(let y of S.messages)this._addMessage(y,!1);for(let y=0;y<A;++y){let G=(await this._createChatCompletion(T,{...F,function_call:M,functions:X,messages:[...this.messages]},$)).choices[0]?.message;if(!G)throw new $T("missing message in ChatCompletion response");if(!G.function_call)return;let{name:z,arguments:Q}=G.function_call,E=k[z];if(!E){let C=`Invalid function_call: ${JSON.stringify(z)}. Available options are: ${X.map((D)=>JSON.stringify(D.name)).join(", ")}. Please try again`;this._addMessage({role:"function",name:z,content:C});continue}else if(W&&W!==z){let C=`Invalid function_call: ${JSON.stringify(z)}. ${JSON.stringify(W)} requested. Please try again`;this._addMessage({role:"function",name:z,content:C});continue}let B;try{B=m0(E)?await E.parse(Q):Q}catch(C){this._addMessage({role:"function",name:z,content:C instanceof Error?C.message:String(C)});continue}let L=await E.function(B,this),b=DS(this,KS,"m",i0).call(this,L);if(this._addMessage({role:"function",name:z,content:b}),W)return}}async _runTools(T,S,$){let{tool_choice:M="auto",stream:J,...F}=S,W=typeof M!=="string"&&M?.function?.name,{maxChatCompletions:A=IX}=$||{},k=S.tools.map((K)=>{if(Xf(K)){if(!K.$callback)throw new $T("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:K.$callback,name:K.function.name,description:K.function.description||"",parameters:K.function.parameters,parse:K.$parseRaw,strict:!0}}}return K}),X={};for(let K of k)if(K.type==="function")X[K.function.name||K.function.function.name]=K.function;let y="tools"in S?k.map((K)=>K.type==="function"?{type:"function",function:{name:K.function.name||K.function.function.name,parameters:K.function.parameters,description:K.function.description,strict:K.function.strict}}:K):void 0;for(let K of S.messages)this._addMessage(K,!1);for(let K=0;K<A;++K){let z=(await this._createChatCompletion(T,{...F,tool_choice:M,tools:y,messages:[...this.messages]},$)).choices[0]?.message;if(!z)throw new $T("missing message in ChatCompletion response");if(!z.tool_calls?.length)return;for(let Q of z.tool_calls){if(Q.type!=="function")continue;let E=Q.id,{name:B,arguments:L}=Q.function,b=X[B];if(!b){let U=`Invalid tool_call: ${JSON.stringify(B)}. Available options are: ${Object.keys(X).map((Z)=>JSON.stringify(Z)).join(", ")}. Please try again`;this._addMessage({role:"tool",tool_call_id:E,content:U});continue}else if(W&&W!==B){let U=`Invalid tool_call: ${JSON.stringify(B)}. ${JSON.stringify(W)} requested. Please try again`;this._addMessage({role:"tool",tool_call_id:E,content:U});continue}let C;try{C=m0(b)?await b.parse(L):L}catch(U){let Z=U instanceof Error?U.message:String(U);this._addMessage({role:"tool",tool_call_id:E,content:Z});continue}let D=await b.function(C,this),H=DS(this,KS,"m",i0).call(this,D);if(this._addMessage({role:"tool",tool_call_id:E,content:H}),W)return}}return}}KS=new WeakSet,o0=function T(){return DS(this,KS,"m",vF).call(this).content??null},vF=function T(){let S=this.messages.length;while(S-- >0){let $=this.messages[S];if(g$($)){let{function_call:f,...M}=$,J={...M,content:$.content??null,refusal:$.refusal??null};if(f)J.function_call=f;return J}}throw new $T("stream ended without producing a ChatCompletionMessage with role=assistant")},g0=function T(){for(let S=this.messages.length-1;S>=0;S--){let $=this.messages[S];if(g$($)&&$?.function_call)return $.function_call;if(g$($)&&$?.tool_calls?.length)return $.tool_calls.at(-1)?.function}return},t0=function T(){for(let S=this.messages.length-1;S>=0;S--){let $=this.messages[S];if(h0($)&&$.content!=null)return $.content;if(v0($)&&$.content!=null&&typeof $.content==="string"&&this.messages.some((f)=>f.role==="assistant"&&f.tool_calls?.some((M)=>M.type==="function"&&M.id===$.tool_call_id)))return $.content}return},p0=function T(){let S={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:$}of this._chatCompletions)if($)S.completion_tokens+=$.completion_tokens,S.prompt_tokens+=$.prompt_tokens,S.total_tokens+=$.total_tokens;return S},bX=function T(S){if(S.n!=null&&S.n>1)throw new $T("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},i0=function T(S){return typeof S==="string"?S:S===void 0?"undefined":JSON.stringify(S)};class $M extends wJ{static runFunctions(T,S,$){let f=new $M,M={...$,headers:{...$?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return f._run(()=>f._runFunctions(T,S,M)),f}static runTools(T,S,$){let f=new $M,M={...$,headers:{...$?.headers,"X-Stainless-Helper-Method":"runTools"}};return f._run(()=>f._runTools(T,S,M)),f}_addMessage(T,S=!0){if(super._addMessage(T,S),g$(T)&&T.content)this._emit("content",T.content)}}var sT={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511};class qX extends Error{}class ZX extends Error{}function j6(T,S=sT.ALL){if(typeof T!=="string")throw new TypeError(`expecting str, got ${typeof T}`);if(!T.trim())throw new Error(`${T} is empty`);return I6(T.trim(),S)}var I6=(T,S)=>{let $=T.length,f=0,M=(K)=>{throw new qX(`${K} at position ${f}`)},J=(K)=>{throw new ZX(`${K} at position ${f}`)},F=()=>{if(y(),f>=$)M("Unexpected end of input");if(T[f]==='"')return W();if(T[f]==="{")return A();if(T[f]==="[")return k();if(T.substring(f,f+4)==="null"||sT.NULL&S&&$-f<4&&"null".startsWith(T.substring(f)))return f+=4,null;if(T.substring(f,f+4)==="true"||sT.BOOL&S&&$-f<4&&"true".startsWith(T.substring(f)))return f+=4,!0;if(T.substring(f,f+5)==="false"||sT.BOOL&S&&$-f<5&&"false".startsWith(T.substring(f)))return f+=5,!1;if(T.substring(f,f+8)==="Infinity"||sT.INFINITY&S&&$-f<8&&"Infinity".startsWith(T.substring(f)))return f+=8,1/0;if(T.substring(f,f+9)==="-Infinity"||sT.MINUS_INFINITY&S&&1<$-f&&$-f<9&&"-Infinity".startsWith(T.substring(f)))return f+=9,-1/0;if(T.substring(f,f+3)==="NaN"||sT.NAN&S&&$-f<3&&"NaN".startsWith(T.substring(f)))return f+=3,NaN;return X()},W=()=>{let K=f,G=!1;f++;while(f<$&&(T[f]!=='"'||G&&T[f-1]==="\\"))G=T[f]==="\\"?!G:!1,f++;if(T.charAt(f)=='"')try{return JSON.parse(T.substring(K,++f-Number(G)))}catch(z){J(String(z))}else if(sT.STR&S)try{return JSON.parse(T.substring(K,f-Number(G))+'"')}catch(z){return JSON.parse(T.substring(K,T.lastIndexOf("\\"))+'"')}M("Unterminated string literal")},A=()=>{f++,y();let K={};try{while(T[f]!=="}"){if(y(),f>=$&&sT.OBJ&S)return K;let G=W();y(),f++;try{let z=F();Object.defineProperty(K,G,{value:z,writable:!0,enumerable:!0,configurable:!0})}catch(z){if(sT.OBJ&S)return K;else throw z}if(y(),T[f]===",")f++}}catch(G){if(sT.OBJ&S)return K;else M("Expected '}' at end of object")}return f++,K},k=()=>{f++;let K=[];try{while(T[f]!=="]")if(K.push(F()),y(),T[f]===",")f++}catch(G){if(sT.ARR&S)return K;M("Expected ']' at end of array")}return f++,K},X=()=>{if(f===0){if(T==="-"&&sT.NUM&S)M("Not sure what '-' is");try{return JSON.parse(T)}catch(G){if(sT.NUM&S)try{if(T[T.length-1]===".")return JSON.parse(T.substring(0,T.lastIndexOf(".")));return JSON.parse(T.substring(0,T.lastIndexOf("e")))}catch(z){}J(String(G))}}let K=f;if(T[f]==="-")f++;while(T[f]&&!",]}".includes(T[f]))f++;if(f==$&&!(sT.NUM&S))M("Unterminated number literal");try{return JSON.parse(T.substring(K,f))}catch(G){if(T.substring(K,f)==="-"&&sT.NUM&S)M("Not sure what '-' is");try{return JSON.parse(T.substring(K,T.lastIndexOf("e")))}catch(z){J(String(z))}}},y=()=>{while(f<$&&" \n\r\t".includes(T[f]))f++};return F()},l0=(T)=>j6(T,sT.ALL^sT.NUM);var fM=function(T,S,$,f,M){if(f==="m")throw new TypeError("Private method is not writable");if(f==="a"&&!M)throw new TypeError("Private accessor was defined without a setter");if(typeof S==="function"?T!==S||!M:!S.has(T))throw new TypeError("Cannot write private member to an object whose class did not declare it");return f==="a"?M.call(T,$):M?M.value=$:S.set(T,$),$},DT=function(T,S,$,f){if($==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof S==="function"?T!==S||!f:!S.has(T))throw new TypeError("Cannot read private member from an object whose class did not declare it");return $==="m"?f:$==="a"?f.call(T):f?f.value:S.get(T)},rT,U$,MM,t$,u0,PF,d0,r0,a0,nF,e0,mX;class yf extends wJ{constructor(T){super();rT.add(this),U$.set(this,void 0),MM.set(this,void 0),t$.set(this,void 0),fM(this,U$,T,"f"),fM(this,MM,[],"f")}get currentChatCompletionSnapshot(){return DT(this,t$,"f")}static fromReadableStream(T){let S=new yf(null);return S._run(()=>S._fromReadableStream(T)),S}static createChatCompletion(T,S,$){let f=new yf(S);return f._run(()=>f._runChatCompletion(T,{...S,stream:!0},{...$,headers:{...$?.headers,"X-Stainless-Helper-Method":"stream"}})),f}async _createChatCompletion(T,S,$){super._createChatCompletion;let f=$?.signal;if(f){if(f.aborted)this.controller.abort();f.addEventListener("abort",()=>this.controller.abort())}DT(this,rT,"m",u0).call(this);let M=await T.chat.completions.create({...S,stream:!0},{...$,signal:this.controller.signal});this._connected();for await(let J of M)DT(this,rT,"m",d0).call(this,J);if(M.controller.signal?.aborted)throw new SS;return this._addChatCompletion(DT(this,rT,"m",nF).call(this))}async _fromReadableStream(T,S){let $=S?.signal;if($){if($.aborted)this.controller.abort();$.addEventListener("abort",()=>this.controller.abort())}DT(this,rT,"m",u0).call(this),this._connected();let f=NS.fromReadableStream(T,this.controller),M;for await(let J of f){if(M&&M!==J.id)this._addChatCompletion(DT(this,rT,"m",nF).call(this));DT(this,rT,"m",d0).call(this,J),M=J.id}if(f.controller.signal?.aborted)throw new SS;return this._addChatCompletion(DT(this,rT,"m",nF).call(this))}[(U$=new WeakMap,MM=new WeakMap,t$=new WeakMap,rT=new WeakSet,u0=function T(){if(this.ended)return;fM(this,t$,void 0,"f")},PF=function T(S){let $=DT(this,MM,"f")[S.index];if($)return $;return $={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},DT(this,MM,"f")[S.index]=$,$},d0=function T(S){if(this.ended)return;let $=DT(this,rT,"m",mX).call(this,S);this._emit("chunk",S,$);for(let f of S.choices){let M=$.choices[f.index];if(f.delta.content!=null&&M.message?.role==="assistant"&&M.message?.content)this._emit("content",f.delta.content,M.message.content),this._emit("content.delta",{delta:f.delta.content,snapshot:M.message.content,parsed:M.message.parsed});if(f.delta.refusal!=null&&M.message?.role==="assistant"&&M.message?.refusal)this._emit("refusal.delta",{delta:f.delta.refusal,snapshot:M.message.refusal});if(f.logprobs?.content!=null&&M.message?.role==="assistant")this._emit("logprobs.content.delta",{content:f.logprobs?.content,snapshot:M.logprobs?.content??[]});if(f.logprobs?.refusal!=null&&M.message?.role==="assistant")this._emit("logprobs.refusal.delta",{refusal:f.logprobs?.refusal,snapshot:M.logprobs?.refusal??[]});let J=DT(this,rT,"m",PF).call(this,M);if(M.finish_reason){if(DT(this,rT,"m",a0).call(this,M),J.current_tool_call_index!=null)DT(this,rT,"m",r0).call(this,M,J.current_tool_call_index)}for(let F of f.delta.tool_calls??[]){if(J.current_tool_call_index!==F.index){if(DT(this,rT,"m",a0).call(this,M),J.current_tool_call_index!=null)DT(this,rT,"m",r0).call(this,M,J.current_tool_call_index)}J.current_tool_call_index=F.index}for(let F of f.delta.tool_calls??[]){let W=M.message.tool_calls?.[F.index];if(!W?.type)continue;if(W?.type==="function")this._emit("tool_calls.function.arguments.delta",{name:W.function?.name,index:F.index,arguments:W.function.arguments,parsed_arguments:W.function.parsed_arguments,arguments_delta:F.function?.arguments??""});else vX(W?.type)}}},r0=function T(S,$){if(DT(this,rT,"m",PF).call(this,S).done_tool_calls.has($))return;let M=S.message.tool_calls?.[$];if(!M)throw new Error("no tool call snapshot");if(!M.type)throw new Error("tool call snapshot missing `type`");if(M.type==="function"){let J=DT(this,U$,"f")?.tools?.find((F)=>F.type==="function"&&F.function.name===M.function.name);this._emit("tool_calls.function.arguments.done",{name:M.function.name,index:$,arguments:M.function.arguments,parsed_arguments:Xf(J)?J.$parseRaw(M.function.arguments):J?.function.strict?JSON.parse(M.function.arguments):null})}else vX(M.type)},a0=function T(S){let $=DT(this,rT,"m",PF).call(this,S);if(S.message.content&&!$.content_done){$.content_done=!0;let f=DT(this,rT,"m",e0).call(this);this._emit("content.done",{content:S.message.content,parsed:f?f.$parseRaw(S.message.content):null})}if(S.message.refusal&&!$.refusal_done)$.refusal_done=!0,this._emit("refusal.done",{refusal:S.message.refusal});if(S.logprobs?.content&&!$.logprobs_content_done)$.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:S.logprobs.content});if(S.logprobs?.refusal&&!$.logprobs_refusal_done)$.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:S.logprobs.refusal})},nF=function T(){if(this.ended)throw new $T("stream has ended, this shouldn't happen");let S=DT(this,t$,"f");if(!S)throw new $T("request ended without sending any chunks");return fM(this,t$,void 0,"f"),fM(this,MM,[],"f"),b6(S,DT(this,U$,"f"))},e0=function T(){let S=DT(this,U$,"f")?.response_format;if(n0(S))return S;return null},mX=function T(S){var $,f,M,J;let F=DT(this,t$,"f"),{choices:W,...A}=S;if(!F)F=fM(this,t$,{...A,choices:[]},"f");else Object.assign(F,A);for(let{delta:k,finish_reason:X,index:y,logprobs:K=null,...G}of S.choices){let z=F.choices[y];if(!z)z=F.choices[y]={finish_reason:X,index:y,message:{},logprobs:K,...G};if(K)if(!z.logprobs)z.logprobs=Object.assign({},K);else{let{content:D,refusal:H,...U}=K;if(hX(U),Object.assign(z.logprobs,U),D)($=z.logprobs).content??($.content=[]),z.logprobs.content.push(...D);if(H)(f=z.logprobs).refusal??(f.refusal=[]),z.logprobs.refusal.push(...H)}if(X){if(z.finish_reason=X,DT(this,U$,"f")&&c0(DT(this,U$,"f"))){if(X==="length")throw new aM;if(X==="content_filter")throw new eM}}if(Object.assign(z,G),!k)continue;let{content:Q,refusal:E,function_call:B,role:L,tool_calls:b,...C}=k;if(hX(C),Object.assign(z.message,C),E)z.message.refusal=(z.message.refusal||"")+E;if(L)z.message.role=L;if(B)if(!z.message.function_call)z.message.function_call=B;else{if(B.name)z.message.function_call.name=B.name;if(B.arguments)(M=z.message.function_call).arguments??(M.arguments=""),z.message.function_call.arguments+=B.arguments}if(Q){if(z.message.content=(z.message.content||"")+Q,!z.message.refusal&&DT(this,rT,"m",e0).call(this))z.message.parsed=l0(z.message.content)}if(b){if(!z.message.tool_calls)z.message.tool_calls=[];for(let{index:D,id:H,type:U,function:Z,...h}of b){let O=(J=z.message.tool_calls)[D]??(J[D]={});if(Object.assign(O,h),H)O.id=H;if(U)O.type=U;if(Z)O.function??(O.function={name:Z.name??"",arguments:""});if(Z?.name)O.function.name=Z.name;if(Z?.arguments){if(O.function.arguments+=Z.arguments,xX(DT(this,U$,"f"),O))O.function.parsed_arguments=l0(O.function.arguments)}}}}return F},Symbol.asyncIterator)](){let T=[],S=[],$=!1;return this.on("chunk",(f)=>{let M=S.shift();if(M)M.resolve(f);else T.push(f)}),this.on("end",()=>{$=!0;for(let f of S)f.resolve(void 0);S.length=0}),this.on("abort",(f)=>{$=!0;for(let M of S)M.reject(f);S.length=0}),this.on("error",(f)=>{$=!0;for(let M of S)M.reject(f);S.length=0}),{next:async()=>{if(!T.length){if($)return{value:void 0,done:!0};return new Promise((M,J)=>S.push({resolve:M,reject:J})).then((M)=>M?{value:M,done:!1}:{value:void 0,done:!0})}return{value:T.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}toReadableStream(){return new NS(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function b6(T,S){let{id:$,choices:f,created:M,model:J,system_fingerprint:F,...W}=T,A={...W,id:$,choices:f.map(({message:k,finish_reason:X,index:y,logprobs:K,...G})=>{if(!X)throw new $T(`missing finish_reason for choice ${y}`);let{content:z=null,function_call:Q,tool_calls:E,...B}=k,L=k.role;if(!L)throw new $T(`missing role for choice ${y}`);if(Q){let{arguments:b,name:C}=Q;if(b==null)throw new $T(`missing function_call.arguments for choice ${y}`);if(!C)throw new $T(`missing function_call.name for choice ${y}`);return{...G,message:{content:z,function_call:{arguments:b,name:C},role:L,refusal:k.refusal??null},finish_reason:X,index:y,logprobs:K}}if(E)return{...G,index:y,finish_reason:X,logprobs:K,message:{...B,role:L,content:z,refusal:k.refusal??null,tool_calls:E.map((b,C)=>{let{function:D,type:H,id:U,...Z}=b,{arguments:h,name:O,...o}=D||{};if(U==null)throw new $T(`missing choices[${y}].tool_calls[${C}].id\n${cF(T)}`);if(H==null)throw new $T(`missing choices[${y}].tool_calls[${C}].type\n${cF(T)}`);if(O==null)throw new $T(`missing choices[${y}].tool_calls[${C}].function.name\n${cF(T)}`);if(h==null)throw new $T(`missing choices[${y}].tool_calls[${C}].function.arguments\n${cF(T)}`);return{...Z,id:U,type:H,function:{...o,name:O,arguments:h}}})}};return{...G,message:{...B,content:z,role:L,refusal:k.refusal??null},finish_reason:X,index:y,logprobs:K}}),created:M,model:J,object:"chat.completion",...F?{system_fingerprint:F}:{}};return CX(A,S)}function cF(T){return JSON.stringify(T)}function hX(T){return}function vX(T){}class Kf extends yf{static fromReadableStream(T){let S=new Kf(null);return S._run(()=>S._fromReadableStream(T)),S}static runFunctions(T,S,$){let f=new Kf(null),M={...$,headers:{...$?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return f._run(()=>f._runFunctions(T,S,M)),f}static runTools(T,S,$){let f=new Kf(S),M={...$,headers:{...$?.headers,"X-Stainless-Helper-Method":"runTools"}};return f._run(()=>f._runTools(T,S,M)),f}}class oF extends i{parse(T,S){return jX(T.tools),this._client.chat.completions.create(T,{...S,headers:{...S?.headers,"X-Stainless-Helper-Method":"beta.chat.completions.parse"}})._thenUnwrap(($)=>KJ($,T))}runFunctions(T,S){if(T.stream)return Kf.runFunctions(this._client,T,S);return $M.runFunctions(this._client,T,S)}runTools(T,S){if(T.stream)return Kf.runTools(this._client,T,S);return $M.runTools(this._client,T,S)}stream(T,S){return yf.createChatCompletion(this._client,T,S)}}class YJ extends i{constructor(){super(...arguments);this.completions=new oF(this._client)}}(function(T){T.Completions=oF})(YJ||(YJ={}));var u=function(T,S,$,f){if($==="a"&&!f)throw new TypeError("Private accessor was defined without a getter");if(typeof S==="function"?T!==S||!f:!S.has(T))throw new TypeError("Cannot read private member from an object whose class did not declare it");return $==="m"?f:$==="a"?f.call(T):f?f.value:S.get(T)},CS=function(T,S,$,f,M){if(f==="m")throw new TypeError("Private method is not writable");if(f==="a"&&!M)throw new TypeError("Private accessor was defined without a setter");if(typeof S==="function"?T!==S||!M:!S.has(T))throw new TypeError("Cannot write private member to an object whose class did not declare it");return f==="a"?M.call(T,$):M?M.value=$:S.set(T,$),$},$S,s0,K$,gF,S$,Yf,JM,wf,iF,xS,tF,pF,GJ,RJ,OJ,PX,nX,cX,oX,gX,tX,pX;class jS extends yJ{constructor(){super(...arguments);$S.add(this),s0.set(this,[]),K$.set(this,{}),gF.set(this,{}),S$.set(this,void 0),Yf.set(this,void 0),JM.set(this,void 0),wf.set(this,void 0),iF.set(this,void 0),xS.set(this,void 0),tF.set(this,void 0),pF.set(this,void 0),GJ.set(this,void 0)}[(s0=new WeakMap,K$=new WeakMap,gF=new WeakMap,S$=new WeakMap,Yf=new WeakMap,JM=new WeakMap,wf=new WeakMap,iF=new WeakMap,xS=new WeakMap,tF=new WeakMap,pF=new WeakMap,GJ=new WeakMap,$S=new WeakSet,Symbol.asyncIterator)](){let T=[],S=[],$=!1;return this.on("event",(f)=>{let M=S.shift();if(M)M.resolve(f);else T.push(f)}),this.on("end",()=>{$=!0;for(let f of S)f.resolve(void 0);S.length=0}),this.on("abort",(f)=>{$=!0;for(let M of S)M.reject(f);S.length=0}),this.on("error",(f)=>{$=!0;for(let M of S)M.reject(f);S.length=0}),{next:async()=>{if(!T.length){if($)return{value:void 0,done:!0};return new Promise((M,J)=>S.push({resolve:M,reject:J})).then((M)=>M?{value:M,done:!1}:{value:void 0,done:!0})}return{value:T.shift(),done:!1}},return:async()=>{return this.abort(),{value:void 0,done:!0}}}}static fromReadableStream(T){let S=new jS;return S._run(()=>S._fromReadableStream(T)),S}async _fromReadableStream(T,S){let $=S?.signal;if($){if($.aborted)this.controller.abort();$.addEventListener("abort",()=>this.controller.abort())}this._connected();let f=NS.fromReadableStream(T,this.controller);for await(let M of f)u(this,$S,"m",RJ).call(this,M);if(f.controller.signal?.aborted)throw new SS;return this._addRun(u(this,$S,"m",OJ).call(this))}toReadableStream(){return new NS(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(T,S,$,f,M){let J=new jS;return J._run(()=>J._runToolAssistantStream(T,S,$,f,{...M,headers:{...M?.headers,"X-Stainless-Helper-Method":"stream"}})),J}async _createToolAssistantStream(T,S,$,f,M){let J=M?.signal;if(J){if(J.aborted)this.controller.abort();J.addEventListener("abort",()=>this.controller.abort())}let F={...f,stream:!0},W=await T.submitToolOutputs(S,$,F,{...M,signal:this.controller.signal});this._connected();for await(let A of W)u(this,$S,"m",RJ).call(this,A);if(W.controller.signal?.aborted)throw new SS;return this._addRun(u(this,$S,"m",OJ).call(this))}static createThreadAssistantStream(T,S,$){let f=new jS;return f._run(()=>f._threadAssistantStream(T,S,{...$,headers:{...$?.headers,"X-Stainless-Helper-Method":"stream"}})),f}static createAssistantStream(T,S,$,f){let M=new jS;return M._run(()=>M._runAssistantStream(T,S,$,{...f,headers:{...f?.headers,"X-Stainless-Helper-Method":"stream"}})),M}currentEvent(){return u(this,tF,"f")}currentRun(){return u(this,pF,"f")}currentMessageSnapshot(){return u(this,S$,"f")}currentRunStepSnapshot(){return u(this,GJ,"f")}async finalRunSteps(){return await this.done(),Object.values(u(this,K$,"f"))}async finalMessages(){return await this.done(),Object.values(u(this,gF,"f"))}async finalRun(){if(await this.done(),!u(this,Yf,"f"))throw Error("Final run was not received.");return u(this,Yf,"f")}async _createThreadAssistantStream(T,S,$){let f=$?.signal;if(f){if(f.aborted)this.controller.abort();f.addEventListener("abort",()=>this.controller.abort())}let M={...S,stream:!0},J=await T.createAndRun(M,{...$,signal:this.controller.signal});this._connected();for await(let F of J)u(this,$S,"m",RJ).call(this,F);if(J.controller.signal?.aborted)throw new SS;return this._addRun(u(this,$S,"m",OJ).call(this))}async _createAssistantStream(T,S,$,f){let M=f?.signal;if(M){if(M.aborted)this.controller.abort();M.addEventListener("abort",()=>this.controller.abort())}let J={...$,stream:!0},F=await T.create(S,J,{...f,signal:this.controller.signal});this._connected();for await(let W of F)u(this,$S,"m",RJ).call(this,W);if(F.controller.signal?.aborted)throw new SS;return this._addRun(u(this,$S,"m",OJ).call(this))}static accumulateDelta(T,S){for(let[$,f]of Object.entries(S)){if(!T.hasOwnProperty($)){T[$]=f;continue}let M=T[$];if(M===null||M===void 0){T[$]=f;continue}if($==="index"||$==="type"){T[$]=f;continue}if(typeof M==="string"&&typeof f==="string")M+=f;else if(typeof M==="number"&&typeof f==="number")M+=f;else if(SJ(M)&&SJ(f))M=this.accumulateDelta(M,f);else if(Array.isArray(M)&&Array.isArray(f)){if(M.every((J)=>typeof J==="string"||typeof J==="number")){M.push(...f);continue}for(let J of f){if(!SJ(J))throw new Error(`Expected array delta entry to be an object but got: ${J}`);let F=J.index;if(F==null)throw console.error(J),new Error("Expected array delta entry to have an `index` property");if(typeof F!=="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${F}`);let W=M[F];if(W==null)M.push(J);else M[F]=this.accumulateDelta(W,J)}continue}else throw Error(`Unhandled record type: ${$}, deltaValue: ${f}, accValue: ${M}`);T[$]=M}return T}_addRun(T){return T}async _threadAssistantStream(T,S,$){return await this._createThreadAssistantStream(S,T,$)}async _runAssistantStream(T,S,$,f){return await this._createAssistantStream(S,T,$,f)}async _runToolAssistantStream(T,S,$,f,M){return await this._createToolAssistantStream($,T,S,f,M)}}RJ=function T(S){if(this.ended)return;switch(CS(this,tF,S,"f"),u(this,$S,"m",cX).call(this,S),S.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.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":u(this,$S,"m",pX).call(this,S);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":u(this,$S,"m",nX).call(this,S);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":u(this,$S,"m",PX).call(this,S);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},OJ=function T(){if(this.ended)throw new $T("stream has ended, this shouldn't happen");if(!u(this,Yf,"f"))throw Error("Final run has not been received");return u(this,Yf,"f")},PX=function T(S){let[$,f]=u(this,$S,"m",gX).call(this,S,u(this,S$,"f"));CS(this,S$,$,"f"),u(this,gF,"f")[$.id]=$;for(let M of f){let J=$.content[M.index];if(J?.type=="text")this._emit("textCreated",J.text)}switch(S.event){case"thread.message.created":this._emit("messageCreated",S.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",S.data.delta,$),S.data.delta.content)for(let M of S.data.delta.content){if(M.type=="text"&&M.text){let J=M.text,F=$.content[M.index];if(F&&F.type=="text")this._emit("textDelta",J,F.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(M.index!=u(this,JM,"f")){if(u(this,wf,"f"))switch(u(this,wf,"f").type){case"text":this._emit("textDone",u(this,wf,"f").text,u(this,S$,"f"));break;case"image_file":this._emit("imageFileDone",u(this,wf,"f").image_file,u(this,S$,"f"));break}CS(this,JM,M.index,"f")}CS(this,wf,$.content[M.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(u(this,JM,"f")!==void 0){let M=S.data.content[u(this,JM,"f")];if(M)switch(M.type){case"image_file":this._emit("imageFileDone",M.image_file,u(this,S$,"f"));break;case"text":this._emit("textDone",M.text,u(this,S$,"f"));break}}if(u(this,S$,"f"))this._emit("messageDone",S.data);CS(this,S$,void 0,"f")}},nX=function T(S){let $=u(this,$S,"m",oX).call(this,S);switch(CS(this,GJ,$,"f"),S.event){case"thread.run.step.created":this._emit("runStepCreated",S.data);break;case"thread.run.step.delta":let f=S.data.delta;if(f.step_details&&f.step_details.type=="tool_calls"&&f.step_details.tool_calls&&$.step_details.type=="tool_calls")for(let J of f.step_details.tool_calls)if(J.index==u(this,iF,"f"))this._emit("toolCallDelta",J,$.step_details.tool_calls[J.index]);else{if(u(this,xS,"f"))this._emit("toolCallDone",u(this,xS,"f"));if(CS(this,iF,J.index,"f"),CS(this,xS,$.step_details.tool_calls[J.index],"f"),u(this,xS,"f"))this._emit("toolCallCreated",u(this,xS,"f"))}this._emit("runStepDelta",S.data.delta,$);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":if(CS(this,GJ,void 0,"f"),S.data.step_details.type=="tool_calls"){if(u(this,xS,"f"))this._emit("toolCallDone",u(this,xS,"f")),CS(this,xS,void 0,"f")}this._emit("runStepDone",S.data,$);break;case"thread.run.step.in_progress":break}},cX=function T(S){u(this,s0,"f").push(S),this._emit("event",S)},oX=function T(S){switch(S.event){case"thread.run.step.created":return u(this,K$,"f")[S.data.id]=S.data,S.data;case"thread.run.step.delta":let $=u(this,K$,"f")[S.data.id];if(!$)throw Error("Received a RunStepDelta before creation of a snapshot");let f=S.data;if(f.delta){let M=jS.accumulateDelta($,f.delta);u(this,K$,"f")[S.data.id]=M}return u(this,K$,"f")[S.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":u(this,K$,"f")[S.data.id]=S.data;break}if(u(this,K$,"f")[S.data.id])return u(this,K$,"f")[S.data.id];throw new Error("No snapshot available")},gX=function T(S,$){let f=[];switch(S.event){case"thread.message.created":return[S.data,f];case"thread.message.delta":if(!$)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let M=S.data;if(M.delta.content)for(let J of M.delta.content)if(J.index in $.content){let F=$.content[J.index];$.content[J.index]=u(this,$S,"m",tX).call(this,J,F)}else $.content[J.index]=J,f.push(J);return[$,f];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if($)return[$,f];else throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},tX=function T(S,$){return jS.accumulateDelta($,S)},pX=function T(S){switch(CS(this,pF,S.data,"f"),S.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":if(CS(this,Yf,S.data,"f"),u(this,xS,"f"))this._emit("toolCallDone",u(this,xS,"f")),CS(this,xS,void 0,"f");break;case"thread.run.cancelling":break}};class FM extends i{create(T,S,$){return this._client.post(`/threads/${T}/messages`,{body:S,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}retrieve(T,S,$){return this._client.get(`/threads/${T}/messages/${S}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}update(T,S,$,f){return this._client.post(`/threads/${T}/messages/${S}`,{body:$,...f,headers:{"OpenAI-Beta":"assistants=v2",...f?.headers}})}list(T,S={},$){if(LT(S))return this.list(T,{},S);return this._client.getAPIList(`/threads/${T}/messages`,zJ,{query:S,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}del(T,S,$){return this._client.delete(`/threads/${T}/messages/${S}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}}class zJ extends PT{}FM.MessagesPage=zJ;class WM extends i{retrieve(T,S,$,f={},M){if(LT(f))return this.retrieve(T,S,$,{},f);return this._client.get(`/threads/${T}/runs/${S}/steps/${$}`,{query:f,...M,headers:{"OpenAI-Beta":"assistants=v2",...M?.headers}})}list(T,S,$={},f){if(LT($))return this.list(T,S,{},$);return this._client.getAPIList(`/threads/${T}/runs/${S}/steps`,_J,{query:$,...f,headers:{"OpenAI-Beta":"assistants=v2",...f?.headers}})}}class _J extends PT{}WM.RunStepsPage=_J;class p$ extends i{constructor(){super(...arguments);this.steps=new WM(this._client)}create(T,S,$){let{include:f,...M}=S;return this._client.post(`/threads/${T}/runs`,{query:{include:f},body:M,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers},stream:S.stream??!1})}retrieve(T,S,$){return this._client.get(`/threads/${T}/runs/${S}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}update(T,S,$,f){return this._client.post(`/threads/${T}/runs/${S}`,{body:$,...f,headers:{"OpenAI-Beta":"assistants=v2",...f?.headers}})}list(T,S={},$){if(LT(S))return this.list(T,{},S);return this._client.getAPIList(`/threads/${T}/runs`,HJ,{query:S,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}cancel(T,S,$){return this._client.post(`/threads/${T}/runs/${S}/cancel`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}async createAndPoll(T,S,$){let f=await this.create(T,S,$);return await this.poll(T,f.id,$)}createAndStream(T,S,$){return jS.createAssistantStream(T,this._client.beta.threads.runs,S,$)}async poll(T,S,$){let f={...$?.headers,"X-Stainless-Poll-Helper":"true"};if($?.pollIntervalMs)f["X-Stainless-Custom-Poll-Interval"]=$.pollIntervalMs.toString();while(!0){let{data:M,response:J}=await this.retrieve(T,S,{...$,headers:{...$?.headers,...f}}).withResponse();switch(M.status){case"queued":case"in_progress":case"cancelling":let F=5000;if($?.pollIntervalMs)F=$.pollIntervalMs;else{let W=J.headers.get("openai-poll-after-ms");if(W){let A=parseInt(W);if(!isNaN(A))F=A}}await D$(F);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return M}}}stream(T,S,$){return jS.createAssistantStream(T,this._client.beta.threads.runs,S,$)}submitToolOutputs(T,S,$,f){return this._client.post(`/threads/${T}/runs/${S}/submit_tool_outputs`,{body:$,...f,headers:{"OpenAI-Beta":"assistants=v2",...f?.headers},stream:$.stream??!1})}async submitToolOutputsAndPoll(T,S,$,f){let M=await this.submitToolOutputs(T,S,$,f);return await this.poll(T,M.id,f)}submitToolOutputsStream(T,S,$,f){return jS.createToolAssistantStream(T,S,this._client.beta.threads.runs,$,f)}}class HJ extends PT{}p$.RunsPage=HJ;p$.Steps=WM;p$.RunStepsPage=_J;class V$ extends i{constructor(){super(...arguments);this.runs=new p$(this._client),this.messages=new FM(this._client)}create(T={},S){if(LT(T))return this.create({},T);return this._client.post("/threads",{body:T,...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers}})}retrieve(T,S){return this._client.get(`/threads/${T}`,{...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers}})}update(T,S,$){return this._client.post(`/threads/${T}`,{body:S,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}del(T,S){return this._client.delete(`/threads/${T}`,{...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers}})}createAndRun(T,S){return this._client.post("/threads/runs",{body:T,...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers},stream:T.stream??!1})}async createAndRunPoll(T,S){let $=await this.createAndRun(T,S);return await this.runs.poll($.thread_id,$.id,S)}createAndRunStream(T,S){return jS.createThreadAssistantStream(T,this._client.beta.threads,S)}}V$.Runs=p$;V$.RunsPage=HJ;V$.Messages=FM;V$.MessagesPage=zJ;var iX=async(T)=>{let S=await Promise.allSettled(T),$=S.filter((M)=>M.status==="rejected");if($.length){for(let M of $)console.error(M.reason);throw new Error(`${$.length} promise(s) failed - see the above errors`)}let f=[];for(let M of S)if(M.status==="fulfilled")f.push(M.value);return f};class AM extends i{create(T,S,$){return this._client.post(`/vector_stores/${T}/files`,{body:S,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}retrieve(T,S,$){return this._client.get(`/vector_stores/${T}/files/${S}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}list(T,S={},$){if(LT(S))return this.list(T,{},S);return this._client.getAPIList(`/vector_stores/${T}/files`,Rf,{query:S,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}del(T,S,$){return this._client.delete(`/vector_stores/${T}/files/${S}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}async createAndPoll(T,S,$){let f=await this.create(T,S,$);return await this.poll(T,f.id,$)}async poll(T,S,$){let f={...$?.headers,"X-Stainless-Poll-Helper":"true"};if($?.pollIntervalMs)f["X-Stainless-Custom-Poll-Interval"]=$.pollIntervalMs.toString();while(!0){let M=await this.retrieve(T,S,{...$,headers:f}).withResponse(),J=M.data;switch(J.status){case"in_progress":let F=5000;if($?.pollIntervalMs)F=$.pollIntervalMs;else{let W=M.response.headers.get("openai-poll-after-ms");if(W){let A=parseInt(W);if(!isNaN(A))F=A}}await D$(F);break;case"failed":case"completed":return J}}}async upload(T,S,$){let f=await this._client.files.create({file:S,purpose:"assistants"},$);return this.create(T,{file_id:f.id},$)}async uploadAndPoll(T,S,$){let f=await this.upload(T,S,$);return await this.poll(T,f.id,$)}}class Rf extends PT{}AM.VectorStoreFilesPage=Rf;class DJ extends i{create(T,S,$){return this._client.post(`/vector_stores/${T}/file_batches`,{body:S,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}retrieve(T,S,$){return this._client.get(`/vector_stores/${T}/file_batches/${S}`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}cancel(T,S,$){return this._client.post(`/vector_stores/${T}/file_batches/${S}/cancel`,{...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}async createAndPoll(T,S,$){let f=await this.create(T,S);return await this.poll(T,f.id,$)}listFiles(T,S,$={},f){if(LT($))return this.listFiles(T,S,{},$);return this._client.getAPIList(`/vector_stores/${T}/file_batches/${S}/files`,Rf,{query:$,...f,headers:{"OpenAI-Beta":"assistants=v2",...f?.headers}})}async poll(T,S,$){let f={...$?.headers,"X-Stainless-Poll-Helper":"true"};if($?.pollIntervalMs)f["X-Stainless-Custom-Poll-Interval"]=$.pollIntervalMs.toString();while(!0){let{data:M,response:J}=await this.retrieve(T,S,{...$,headers:f}).withResponse();switch(M.status){case"in_progress":let F=5000;if($?.pollIntervalMs)F=$.pollIntervalMs;else{let W=J.headers.get("openai-poll-after-ms");if(W){let A=parseInt(W);if(!isNaN(A))F=A}}await D$(F);break;case"failed":case"cancelled":case"completed":return M}}}async uploadAndPoll(T,{files:S,fileIds:$=[]},f){if(S==null||S.length==0)throw new Error("No \`files\` provided to process. If you've already uploaded files you should use \`.createAndPoll()\` instead");let M=f?.maxConcurrency??5,J=Math.min(M,S.length),F=this._client,W=S.values(),A=[...$];async function k(y){for(let K of y){let G=await F.files.create({file:K,purpose:"assistants"},f);A.push(G.id)}}let X=Array(J).fill(W).map(k);return await iX(X),await this.createAndPoll(T,{file_ids:A})}}class B$ extends i{constructor(){super(...arguments);this.files=new AM(this._client),this.fileBatches=new DJ(this._client)}create(T,S){return this._client.post("/vector_stores",{body:T,...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers}})}retrieve(T,S){return this._client.get(`/vector_stores/${T}`,{...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers}})}update(T,S,$){return this._client.post(`/vector_stores/${T}`,{body:S,...$,headers:{"OpenAI-Beta":"assistants=v2",...$?.headers}})}list(T={},S){if(LT(T))return this.list({},T);return this._client.getAPIList("/vector_stores",EJ,{query:T,...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers}})}del(T,S){return this._client.delete(`/vector_stores/${T}`,{...S,headers:{"OpenAI-Beta":"assistants=v2",...S?.headers}})}}class EJ extends PT{}B$.VectorStoresPage=EJ;B$.Files=AM;B$.VectorStoreFilesPage=Rf;B$.FileBatches=DJ;class $$ extends i{constructor(){super(...arguments);this.vectorStores=new B$(this._client),this.chat=new YJ(this._client),this.assistants=new TM(this._client),this.threads=new V$(this._client)}}$$.VectorStores=B$;$$.VectorStoresPage=EJ;$$.Assistants=TM;$$.AssistantsPage=FJ;$$.Threads=V$;class kM extends i{create(T,S){return this._client.post("/completions",{body:T,...S,stream:T.stream??!1})}}class XM extends i{create(T,S){return this._client.post("/embeddings",{body:T,...S})}}class Of extends i{create(T,S){return this._client.post("/files",vS({body:T,...S}))}retrieve(T,S){return this._client.get(`/files/${T}`,S)}list(T={},S){if(LT(T))return this.list({},T);return this._client.getAPIList("/files",yM,{query:T,...S})}del(T,S){return this._client.delete(`/files/${T}`,S)}content(T,S){return this._client.get(`/files/${T}/content`,{...S,__binaryResponse:!0})}retrieveContent(T,S){return this._client.get(`/files/${T}/content`,{...S,headers:{Accept:"application/json",...S?.headers}})}async waitForProcessing(T,{pollInterval:S=5000,maxWait:$=1800000}={}){let f=new Set(["processed","error","deleted"]),M=Date.now(),J=await this.retrieve(T);while(!J.status||!f.has(J.status))if(await D$(S),J=await this.retrieve(T),Date.now()-M>$)throw new Ff({message:`Giving up on waiting for file ${T} to finish processing after ${$} milliseconds.`});return J}}class yM extends PT{}Of.FileObjectsPage=yM;class KM extends i{list(T,S={},$){if(LT(S))return this.list(T,{},S);return this._client.getAPIList(`/fine_tuning/jobs/${T}/checkpoints`,QJ,{query:S,...$})}}class QJ extends PT{}KM.FineTuningJobCheckpointsPage=QJ;class L$ extends i{constructor(){super(...arguments);this.checkpoints=new KM(this._client)}create(T,S){return this._client.post("/fine_tuning/jobs",{body:T,...S})}retrieve(T,S){return this._client.get(`/fine_tuning/jobs/${T}`,S)}list(T={},S){if(LT(T))return this.list({},T);return this._client.getAPIList("/fine_tuning/jobs",UJ,{query:T,...S})}cancel(T,S){return this._client.post(`/fine_tuning/jobs/${T}/cancel`,S)}listEvents(T,S={},$){if(LT(S))return this.listEvents(T,{},S);return this._client.getAPIList(`/fine_tuning/jobs/${T}/events`,VJ,{query:S,...$})}}class UJ extends PT{}class VJ extends PT{}L$.FineTuningJobsPage=UJ;L$.FineTuningJobEventsPage=VJ;L$.Checkpoints=KM;L$.FineTuningJobCheckpointsPage=QJ;class N$ extends i{constructor(){super(...arguments);this.jobs=new L$(this._client)}}N$.Jobs=L$;N$.FineTuningJobsPage=UJ;N$.FineTuningJobEventsPage=VJ;class wM extends i{createVariation(T,S){return this._client.post("/images/variations",vS({body:T,...S}))}edit(T,S){return this._client.post("/images/edits",vS({body:T,...S}))}generate(T,S){return this._client.post("/images/generations",{body:T,...S})}}class Gf extends i{retrieve(T,S){return this._client.get(`/models/${T}`,S)}list(T){return this._client.getAPIList("/models",YM,T)}del(T,S){return this._client.delete(`/models/${T}`,S)}}class YM extends Z0{}Gf.ModelsPage=YM;class RM extends i{create(T,S){return this._client.post("/moderations",{body:T,...S})}}class BJ extends i{create(T,S,$){return this._client.post(`/uploads/${T}/parts`,vS({body:S,...$}))}}class zf extends i{constructor(){super(...arguments);this.parts=new BJ(this._client)}create(T,S){return this._client.post("/uploads",{body:T,...S})}cancel(T,S){return this._client.post(`/uploads/${T}/cancel`,S)}complete(T,S,$){return this._client.post(`/uploads/${T}/complete`,{body:S,...$})}}zf.Parts=BJ;var lX;class RT extends q0{constructor({baseURL:T=TJ("OPENAI_BASE_URL"),apiKey:S=TJ("OPENAI_API_KEY"),organization:$=TJ("OPENAI_ORG_ID")??null,project:f=TJ("OPENAI_PROJECT_ID")??null,...M}={}){if(S===void 0)throw new $T("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");let J={apiKey:S,organization:$,project:f,...M,baseURL:T||"https://api.openai.com/v1"};if(!J.dangerouslyAllowBrowser&&LX())throw new $T("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n");super({baseURL:J.baseURL,timeout:J.timeout??600000,httpAgent:J.httpAgent,maxRetries:J.maxRetries,fetch:J.fetch});this.completions=new kM(this),this.chat=new Af(this),this.embeddings=new XM(this),this.files=new Of(this),this.images=new wM(this),this.audio=new E$(this),this.moderations=new RM(this),this.models=new Gf(this),this.fineTuning=new N$(this),this.beta=new $$(this),this.batches=new kf(this),this.uploads=new zf(this),this._options=J,this.apiKey=S,this.organization=$,this.project=f}defaultQuery(){return this._options.defaultQuery}defaultHeaders(T){return{...super.defaultHeaders(T),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project,...this._options.defaultHeaders}}authHeaders(T){return{Authorization:`Bearer ${this.apiKey}`}}stringifyQuery(T){return D0(T,{arrayFormat:"brackets"})}}lX=RT;RT.OpenAI=lX;RT.DEFAULT_TIMEOUT=600000;RT.OpenAIError=$T;RT.APIError=gT;RT.APIConnectionError=Jf;RT.APIConnectionTimeoutError=Ff;RT.APIUserAbortError=SS;RT.NotFoundError=UF;RT.ConflictError=VF;RT.RateLimitError=LF;RT.BadRequestError=DF;RT.AuthenticationError=EF;RT.InternalServerError=NF;RT.PermissionDeniedError=QF;RT.UnprocessableEntityError=BF;RT.toFile=j0;RT.fileFromPath=HF;RT.Completions=kM;RT.Chat=Af;RT.Embeddings=XM;RT.Files=Of;RT.FileObjectsPage=yM;RT.Images=wM;RT.Audio=E$;RT.Moderations=RM;RT.Models=Gf;RT.ModelsPage=YM;RT.FineTuning=N$;RT.Beta=$$;RT.Batches=kf;RT.BatchesPage=sf;RT.Uploads=zf;var uX=RT;import{createHash as l6}from"crypto";import*as aT from"fs";import*as C$ from"path";function u6(T){let S=T.replace(d6,"-");if(S.length<=64)return S;let $=l6("sha256").update(T).digest("hex");return S.slice(-64)+"+"+$}var d6=/[^a-zA-Z0-9\-._]/g;class T1{mode;baseDir;filenameCache=new Map;filesTouched=new Map;constructor(T="off",S=C$.join(process.cwd(),".varmint")){this.mode=T,this.baseDir=S}read(T,S,$){let f=C$.join(this.baseDir,`${T}/${S}.input.json`);if(!aT.existsSync(f))throw new Error(`Squirrel: input file for key "${T}" does not exist`);let M=aT.readFileSync(f,"utf-8"),J=JSON.stringify($,null,"\t");if(J!==M)throw new Error(`Squirrel: the content of the cached input file ${f} does not match the input provided.\n\nProvided:\n${J}\n\nCached:\n${M}`);let F=C$.join(this.baseDir,`${T}/${S}.output.json`);return JSON.parse(aT.readFileSync(F,"utf-8"))}async write(T,S,$,f){let M=C$.join(this.baseDir,T),J=C$.join(M,`${S}.input.json`),F=C$.join(M,`${S}.output.json`),W=JSON.stringify($,null,"\t");if(!aT.existsSync(this.baseDir))aT.mkdirSync(this.baseDir);if(!aT.existsSync(M))aT.mkdirSync(M);if(aT.writeFileSync(J,W),aT.existsSync(F))aT.unlinkSync(F);let A=await f(...$);return aT.writeFileSync(F,JSON.stringify(A,null,"\t")),A}add(T,S){return{flush:()=>{this.flush(T)},for:($)=>{if(this.mode!=="off"&&!this.filesTouched.has(T))this.filesTouched.set(T,new Set);return{get:async(...f)=>{let M=$;if(this.mode!=="off"){let J=this.filenameCache.get($);if(!J)J=u6($),this.filenameCache.set($,M),M=J;this.filesTouched.get(T)?.add(M)}switch(this.mode){case"off":return S(...f);case"read":return this.read(T,M,f);case"write":return this.write(T,M,f,S);case"read-write":try{return this.read(T,M,f)}catch(J){if(J instanceof Error)return this.write(T,M,f,S);throw J}}}}}}}flush(...T){for(let[S,$]of this.filesTouched.entries())if(T.length===0||T.includes(S)){let f=C$.join(this.baseDir,S),M=aT.readdirSync(f);for(let J of M){let F=J.replace(".input.json","").replace(".output.json","");if(!$.has(F))console.log(`\uD83D\uDCA5 Flushing ${F}`),aT.unlinkSync(C$.join(f,J))}}}}function a6(T,...S){let[$,f,M,J]=S,F=[{role:"user",content:SX(f)},{role:"user",content:$}],W=J.at(-1);if(W)F.push({role:"user",content:["Oops! That didn't work. Here's what was returned last time:",JSON.stringify(W.response,null,2),"Here's the error message:",W.error.toString()].join(`