aegiscode 4.0.4 → 4.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/bin/cli.js +2 -2
  2. package/package.json +1 -1
package/bin/cli.js CHANGED
@@ -312,11 +312,11 @@ ${e}
312
312
  `||I===`
313
313
  `&&c[G-1]!=="\r"?`\r
314
314
  `:I),mS=TUI});var DUI,sS,dpI=L(()=>{DUI=l=>String(l).replace(/\r/g,"%0D").replace(/\n/g,"%0A").replace(/"/g,"%22"),sS=DUI});var qUI,ip,WS=L(()=>{qUI=l=>typeof l=="function",ip=qUI});var J2,NS=L(()=>{WS();J2=l=>!!(l&&typeof l=="object"&&ip(l.constructor)&&l[Symbol.toStringTag]==="File"&&ip(l.stream)&&l.name!=null&&l.size!=null&&l.lastModified!=null)});var bpI,pS=L(()=>{WS();bpI=l=>!!(l&&ip(l.constructor)&&l[Symbol.toStringTag]==="FormData"&&ip(l.append)&&ip(l.getAll)&&ip(l.entries)&&ip(l[Symbol.iterator]))});var qw,Se,B3,jo,Pw,U3,_w,L2,$w,IE,f3,hS,PUI,O3,npI=L(()=>{epI();tpI();apI();dpI();NS();pS();qw=function(l,I,G,c,e){if(c==="m")throw new TypeError("Private method is not writable");if(c==="a"&&!e)throw new TypeError("Private accessor was defined without a setter");if(typeof I=="function"?l!==I||!e:!I.has(l))throw new TypeError("Cannot write private member to an object whose class did not declare it");return c==="a"?e.call(l,G):e?e.value=G:I.set(l,G),G},Se=function(l,I,G,c){if(G==="a"&&!c)throw new TypeError("Private accessor was defined without a getter");if(typeof I=="function"?l!==I||!c:!I.has(l))throw new TypeError("Cannot read private member from an object whose class did not declare it");return G==="m"?c:G==="a"?c.call(l):c?c.value:I.get(l)},PUI={enableAdditionalHeaders:!1},O3=class{constructor(I,G,c){if(B3.add(this),jo.set(this,`\r
315
- `),Pw.set(this,void 0),U3.set(this,void 0),_w.set(this,"-".repeat(2)),L2.set(this,new TextEncoder),$w.set(this,void 0),IE.set(this,void 0),f3.set(this,void 0),!bpI(I))throw new TypeError("Expected first argument to be a FormData instance.");let e;if(ZS(G)?c=G:e=G,e||(e=cpI()),typeof e!="string")throw new TypeError("Expected boundary argument to be a string.");if(c&&!ZS(c))throw new TypeError("Expected options argument to be an object.");qw(this,IE,I,"f"),qw(this,f3,{...PUI,...c},"f"),qw(this,Pw,Se(this,L2,"f").encode(Se(this,jo,"f")),"f"),qw(this,U3,Se(this,Pw,"f").byteLength,"f"),this.boundary=`form-data-boundary-${e}`,this.contentType=`multipart/form-data; boundary=${this.boundary}`,qw(this,$w,Se(this,L2,"f").encode(`${Se(this,_w,"f")}${this.boundary}${Se(this,_w,"f")}${Se(this,jo,"f").repeat(2)}`),"f"),this.contentLength=String(this.getContentLength()),this.headers=Object.freeze({"Content-Type":this.contentType,"Content-Length":this.contentLength}),Object.defineProperties(this,{boundary:{writable:!1,configurable:!1},contentType:{writable:!1,configurable:!1},contentLength:{writable:!1,configurable:!1},headers:{writable:!1,configurable:!1}})}getContentLength(){let I=0;for(let[G,c]of Se(this,IE,"f")){let e=J2(c)?c:Se(this,L2,"f").encode(mS(c));I+=Se(this,B3,"m",hS).call(this,G,e).byteLength,I+=J2(e)?e.size:e.byteLength,I+=Se(this,U3,"f")}return I+Se(this,$w,"f").byteLength}*values(){for(let[I,G]of Se(this,IE,"f").entries()){let c=J2(G)?G:Se(this,L2,"f").encode(mS(G));yield Se(this,B3,"m",hS).call(this,I,c),yield c,yield Se(this,Pw,"f")}yield Se(this,$w,"f")}async*encode(){for(let I of this.values())J2(I)?yield*I.stream():yield I}[(jo=new WeakMap,Pw=new WeakMap,U3=new WeakMap,_w=new WeakMap,L2=new WeakMap,$w=new WeakMap,IE=new WeakMap,f3=new WeakMap,B3=new WeakSet,hS=function(G,c){let e="";return e+=`${Se(this,_w,"f")}${this.boundary}${Se(this,jo,"f")}`,e+=`Content-Disposition: form-data; name="${sS(G)}"`,J2(c)&&(e+=`; filename="${sS(c.name)}"${Se(this,jo,"f")}`,e+=`Content-Type: ${c.type||"application/octet-stream"}`),Se(this,f3,"f").enableAdditionalHeaders===!0&&(e+=`${Se(this,jo,"f")}Content-Length: ${J2(c)?c.size:c.byteLength}`),Se(this,L2,"f").encode(`${e}${Se(this,jo,"f").repeat(2)}`)},Symbol.iterator)](){return this.values()}[Symbol.asyncIterator](){return this.encode()}}});var ZpI=L(()=>{});var mpI=L(()=>{});var spI=L(()=>{npI();ZpI();mpI();NS();pS()});var M3,WpI=L(()=>{M3=class{constructor(I){this.body=I}get[Symbol.toStringTag](){return"MultipartBody"}}});var ppI=mI((S0l,NpI)=>{if(!globalThis.DOMException)try{let{MessageChannel:l}=Jl("worker_threads"),I=new l().port1,G=new ArrayBuffer;I.postMessage(G,[G,G])}catch(l){l.constructor.name==="DOMException"&&(globalThis.DOMException=l.constructor)}NpI.exports=globalThis.DOMException});function $UI(l){if(_UI(l)!=="object")return!1;let I=Object.getPrototypeOf(l);return I==null?!0:(I.constructor&&I.constructor.toString())===Object.toString()}var _UI,hpI,opI=L(()=>{_UI=l=>Object.prototype.toString.call(l).slice(8,-1).toLowerCase();hpI=$UI});var rpI={};Ic(rpI,{fileFromPath:()=>tfI,fileFromPathSync:()=>efI,isFile:()=>Pj});import{statSync as IfI,createReadStream as lfI,promises as ipI}from"fs";import{basename as GfI}from"path";function VpI(l,{mtimeMs:I,size:G},c,e={}){let t;hpI(c)?[e,t]=[c,void 0]:t=c;let a=new oS({path:l,size:G,lastModified:I});return t||(t=a.name),new es([a],t,{...e,lastModified:a.lastModified})}function efI(l,I,G={}){let c=IfI(l);return VpI(l,c,I,G)}async function tfI(l,I,G){let c=await ipI.stat(l);return VpI(l,c,I,G)}var YpI,upI,UF,k2,lE,cfI,oS,RpI=L(()=>{YpI=MI(ppI(),1);Bw();opI();_j();upI=function(l,I,G,c,e){if(c==="m")throw new TypeError("Private method is not writable");if(c==="a"&&!e)throw new TypeError("Private accessor was defined without a setter");if(typeof I=="function"?l!==I||!e:!I.has(l))throw new TypeError("Cannot write private member to an object whose class did not declare it");return c==="a"?e.call(l,G):e?e.value=G:I.set(l,G),G},UF=function(l,I,G,c){if(G==="a"&&!c)throw new TypeError("Private accessor was defined without a getter");if(typeof I=="function"?l!==I||!c:!I.has(l))throw new TypeError("Cannot read private member from an object whose class did not declare it");return G==="m"?c:G==="a"?c.call(l):c?c.value:I.get(l)},cfI="The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.",oS=class l{constructor(I){k2.set(this,void 0),lE.set(this,void 0),upI(this,k2,I.path,"f"),upI(this,lE,I.start||0,"f"),this.name=GfI(UF(this,k2,"f")),this.size=I.size,this.lastModified=I.lastModified}slice(I,G){return new l({path:UF(this,k2,"f"),lastModified:this.lastModified,size:G-I,start:I})}async*stream(){let{mtimeMs:I}=await ipI.stat(UF(this,k2,"f"));if(I>this.lastModified)throw new YpI.default(cfI,"NotReadableError");this.size&&(yield*lfI(UF(this,k2,"f"),{start:UF(this,lE,"f"),end:UF(this,lE,"f")+this.size-1}))}get[(k2=new WeakMap,lE=new WeakMap,Symbol.toStringTag)](){return"File"}}});import{ReadStream as afI}from"node:fs";import{Readable as dfI}from"node:stream";import{ReadableStream as bfI}from"node:stream/web";async function nfI(l,...I){let{fileFromPath:G}=await Promise.resolve().then(()=>(RpI(),rpI));return FpI||(console.warn(`fileFromPath is deprecated; use fs.createReadStream(${JSON.stringify(l)}) instead`),FpI=!0),await G(l,...I)}async function sfI(l,I){let G=new O3(l),c=dfI.from(G),e=new M3(c),t={...I.headers,...G.headers,"Content-Length":G.contentLength};return{...I,body:e,headers:t}}function XpI(){return typeof AbortController>"u"&&(globalThis.AbortController=QpI.AbortController),{kind:"node",fetch:So.default,Request:So.Request,Response:So.Response,Headers:So.Headers,FormData:A3,Blob:FW,File:es,ReadableStream:bfI,getMultipartRequestOptions:sfI,getDefaultAgent:l=>l.startsWith("https")?mfI:ZfI,fileFromPath:nfI,isFsReadStream:l=>l instanceof afI}}var So,uS,QpI,FpI,ZfI,mfI,HpI=L(()=>{So=MI(PsI(),1);vNI();uS=MI(fNI(),1),QpI=MI(lpI(),1);spI();WpI();FpI=!1;ZfI=new uS.default({keepAlive:!0,timeout:300*1e3}),mfI=new uS.default.HttpsAgent({keepAlive:!0,timeout:300*1e3})});var vpI=L(()=>{HpI()});var iS,GE=L(()=>{bj();vpI();bj();iS=()=>{R2||ssI(XpI(),{auto:!0})};iS()});var zl,Na,Tt,Ko,To,cE,eE,tE,aE,dE,bE,nE,ZE,fF,OF,Bn=L(()=>{dc();zl=class extends Error{},Na=class l extends zl{constructor(I,G,c,e){super(`${l.makeMessage(I,G,c)}`),this.status=I,this.headers=e,this.request_id=e?.["x-request-id"],this.error=G;let t=G;this.code=t?.code,this.param=t?.param,this.type=t?.type}static makeMessage(I,G,c){let e=G?.message?typeof G.message=="string"?G.message:JSON.stringify(G.message):G?JSON.stringify(G):c;return I&&e?`${I} ${e}`:I?`${I} status code (no body)`:e||"(no status code or body)"}static generate(I,G,c,e){if(!I||!e)return new Ko({message:c,cause:j3(G)});let t=G?.error;return I===400?new cE(I,t,c,e):I===401?new eE(I,t,c,e):I===403?new tE(I,t,c,e):I===404?new aE(I,t,c,e):I===409?new dE(I,t,c,e):I===422?new bE(I,t,c,e):I===429?new nE(I,t,c,e):I>=500?new ZE(I,t,c,e):new l(I,t,c,e)}},Tt=class extends Na{constructor({message:I}={}){super(void 0,void 0,I||"Request was aborted.",void 0)}},Ko=class extends Na{constructor({message:I,cause:G}){super(void 0,void 0,I||"Connection error.",void 0),G&&(this.cause=G)}},To=class extends Ko{constructor({message:I}={}){super({message:I??"Request timed out."})}},cE=class extends Na{},eE=class extends Na{},tE=class extends Na{},aE=class extends Na{},dE=class extends Na{},bE=class extends Na{},nE=class extends Na{},ZE=class extends Na{},fF=class extends zl{constructor(){super("Could not parse response content as the length limit was reached")}},OF=class extends zl{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}});function pfI(l,I){for(let e=I??0;e<l.length;e++){if(l[e]===10)return{preceding:e,index:e+1,carriage:!1};if(l[e]===13)return{preceding:e,index:e+1,carriage:!0}}return null}function wpI(l){for(let c=0;c<l.length-1;c++){if(l[c]===10&&l[c+1]===10||l[c]===13&&l[c+1]===13)return c+2;if(l[c]===13&&l[c+1]===10&&c+3<l.length&&l[c+2]===13&&l[c+3]===10)return c+4}return-1}var S3,z2,Un,x2,EpI=L(()=>{Bn();S3=function(l,I,G,c,e){if(c==="m")throw new TypeError("Private method is not writable");if(c==="a"&&!e)throw new TypeError("Private accessor was defined without a setter");if(typeof I=="function"?l!==I||!e:!I.has(l))throw new TypeError("Cannot write private member to an object whose class did not declare it");return c==="a"?e.call(l,G):e?e.value=G:I.set(l,G),G},z2=function(l,I,G,c){if(G==="a"&&!c)throw new TypeError("Private accessor was defined without a getter");if(typeof I=="function"?l!==I||!c:!I.has(l))throw new TypeError("Cannot read private member from an object whose class did not declare it");return G==="m"?c:G==="a"?c.call(l):c?c.value:I.get(l)},x2=class{constructor(){Un.set(this,void 0),this.buffer=new Uint8Array,S3(this,Un,null,"f")}decode(I){if(I==null)return[];let G=I instanceof ArrayBuffer?new Uint8Array(I):typeof I=="string"?new TextEncoder().encode(I):I,c=new Uint8Array(this.buffer.length+G.length);c.set(this.buffer),c.set(G,this.buffer.length),this.buffer=c;let e=[],t;for(;(t=pfI(this.buffer,z2(this,Un,"f")))!=null;){if(t.carriage&&z2(this,Un,"f")==null){S3(this,Un,t.index,"f");continue}if(z2(this,Un,"f")!=null&&(t.index!==z2(this,Un,"f")+1||t.carriage)){e.push(this.decodeText(this.buffer.slice(0,z2(this,Un,"f")-1))),this.buffer=this.buffer.slice(z2(this,Un,"f")),S3(this,Un,null,"f");continue}let a=z2(this,Un,"f")!==null?t.preceding-1:t.preceding,n=this.decodeText(this.buffer.slice(0,a));e.push(n),this.buffer=this.buffer.slice(t.index),S3(this,Un,null,"f")}return e}decodeText(I){if(I==null)return"";if(typeof I=="string")return I;if(typeof Buffer<"u"){if(I instanceof Buffer)return I.toString();if(I instanceof Uint8Array)return Buffer.from(I).toString();throw new zl(`Unexpected: received non-Uint8Array (${I.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<"u"){if(I instanceof Uint8Array||I instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(I);throw new zl(`Unexpected: received non-Uint8Array/ArrayBuffer (${I.constructor.name}) in a web platform. Please report this error.`)}throw new zl("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){return this.buffer.length?this.decode(`
315
+ `),Pw.set(this,void 0),U3.set(this,void 0),_w.set(this,"-".repeat(2)),L2.set(this,new TextEncoder),$w.set(this,void 0),IE.set(this,void 0),f3.set(this,void 0),!bpI(I))throw new TypeError("Expected first argument to be a FormData instance.");let e;if(ZS(G)?c=G:e=G,e||(e=cpI()),typeof e!="string")throw new TypeError("Expected boundary argument to be a string.");if(c&&!ZS(c))throw new TypeError("Expected options argument to be an object.");qw(this,IE,I,"f"),qw(this,f3,{...PUI,...c},"f"),qw(this,Pw,Se(this,L2,"f").encode(Se(this,jo,"f")),"f"),qw(this,U3,Se(this,Pw,"f").byteLength,"f"),this.boundary=`form-data-boundary-${e}`,this.contentType=`multipart/form-data; boundary=${this.boundary}`,qw(this,$w,Se(this,L2,"f").encode(`${Se(this,_w,"f")}${this.boundary}${Se(this,_w,"f")}${Se(this,jo,"f").repeat(2)}`),"f"),this.contentLength=String(this.getContentLength()),this.headers=Object.freeze({"Content-Type":this.contentType,"Content-Length":this.contentLength}),Object.defineProperties(this,{boundary:{writable:!1,configurable:!1},contentType:{writable:!1,configurable:!1},contentLength:{writable:!1,configurable:!1},headers:{writable:!1,configurable:!1}})}getContentLength(){let I=0;for(let[G,c]of Se(this,IE,"f")){let e=J2(c)?c:Se(this,L2,"f").encode(mS(c));I+=Se(this,B3,"m",hS).call(this,G,e).byteLength,I+=J2(e)?e.size:e.byteLength,I+=Se(this,U3,"f")}return I+Se(this,$w,"f").byteLength}*values(){for(let[I,G]of Se(this,IE,"f").entries()){let c=J2(G)?G:Se(this,L2,"f").encode(mS(G));yield Se(this,B3,"m",hS).call(this,I,c),yield c,yield Se(this,Pw,"f")}yield Se(this,$w,"f")}async*encode(){for(let I of this.values())J2(I)?yield*I.stream():yield I}[(jo=new WeakMap,Pw=new WeakMap,U3=new WeakMap,_w=new WeakMap,L2=new WeakMap,$w=new WeakMap,IE=new WeakMap,f3=new WeakMap,B3=new WeakSet,hS=function(G,c){let e="";return e+=`${Se(this,_w,"f")}${this.boundary}${Se(this,jo,"f")}`,e+=`Content-Disposition: form-data; name="${sS(G)}"`,J2(c)&&(e+=`; filename="${sS(c.name)}"${Se(this,jo,"f")}`,e+=`Content-Type: ${c.type||"application/octet-stream"}`),Se(this,f3,"f").enableAdditionalHeaders===!0&&(e+=`${Se(this,jo,"f")}Content-Length: ${J2(c)?c.size:c.byteLength}`),Se(this,L2,"f").encode(`${e}${Se(this,jo,"f").repeat(2)}`)},Symbol.iterator)](){return this.values()}[Symbol.asyncIterator](){return this.encode()}}});var ZpI=L(()=>{});var mpI=L(()=>{});var spI=L(()=>{npI();ZpI();mpI();NS();pS()});var M3,WpI=L(()=>{M3=class{constructor(I){this.body=I}get[Symbol.toStringTag](){return"MultipartBody"}}});var ppI=mI((S0l,NpI)=>{if(!globalThis.DOMException)try{let{MessageChannel:l}=Jl("worker_threads"),I=new l().port1,G=new ArrayBuffer;I.postMessage(G,[G,G])}catch(l){l.constructor.name==="DOMException"&&(globalThis.DOMException=l.constructor)}NpI.exports=globalThis.DOMException});function $UI(l){if(_UI(l)!=="object")return!1;let I=Object.getPrototypeOf(l);return I==null?!0:(I.constructor&&I.constructor.toString())===Object.toString()}var _UI,hpI,opI=L(()=>{_UI=l=>Object.prototype.toString.call(l).slice(8,-1).toLowerCase();hpI=$UI});var rpI={};Ic(rpI,{fileFromPath:()=>tfI,fileFromPathSync:()=>efI,isFile:()=>Pj});import{statSync as IfI,createReadStream as lfI,promises as ipI}from"fs";import{basename as GfI}from"path";function VpI(l,{mtimeMs:I,size:G},c,e={}){let t;hpI(c)?[e,t]=[c,void 0]:t=c;let a=new oS({path:l,size:G,lastModified:I});return t||(t=a.name),new es([a],t,{...e,lastModified:a.lastModified})}function efI(l,I,G={}){let c=IfI(l);return VpI(l,c,I,G)}async function tfI(l,I,G){let c=await ipI.stat(l);return VpI(l,c,I,G)}var YpI,upI,UF,k2,lE,cfI,oS,RpI=L(()=>{YpI=MI(ppI(),1);Bw();opI();_j();upI=function(l,I,G,c,e){if(c==="m")throw new TypeError("Private method is not writable");if(c==="a"&&!e)throw new TypeError("Private accessor was defined without a setter");if(typeof I=="function"?l!==I||!e:!I.has(l))throw new TypeError("Cannot write private member to an object whose class did not declare it");return c==="a"?e.call(l,G):e?e.value=G:I.set(l,G),G},UF=function(l,I,G,c){if(G==="a"&&!c)throw new TypeError("Private accessor was defined without a getter");if(typeof I=="function"?l!==I||!c:!I.has(l))throw new TypeError("Cannot read private member from an object whose class did not declare it");return G==="m"?c:G==="a"?c.call(l):c?c.value:I.get(l)},cfI="The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.",oS=class l{constructor(I){k2.set(this,void 0),lE.set(this,void 0),upI(this,k2,I.path,"f"),upI(this,lE,I.start||0,"f"),this.name=GfI(UF(this,k2,"f")),this.size=I.size,this.lastModified=I.lastModified}slice(I,G){return new l({path:UF(this,k2,"f"),lastModified:this.lastModified,size:G-I,start:I})}async*stream(){let{mtimeMs:I}=await ipI.stat(UF(this,k2,"f"));if(I>this.lastModified)throw new YpI.default(cfI,"NotReadableError");this.size&&(yield*lfI(UF(this,k2,"f"),{start:UF(this,lE,"f"),end:UF(this,lE,"f")+this.size-1}))}get[(k2=new WeakMap,lE=new WeakMap,Symbol.toStringTag)](){return"File"}}});import{ReadStream as afI}from"node:fs";import{Readable as dfI}from"node:stream";import{ReadableStream as bfI}from"node:stream/web";async function nfI(l,...I){let{fileFromPath:G}=await Promise.resolve().then(()=>(RpI(),rpI));return FpI||(console.warn(`fileFromPath is deprecated; use fs.createReadStream(${JSON.stringify(l)}) instead`),FpI=!0),await G(l,...I)}async function sfI(l,I){let G=new O3(l),c=dfI.from(G),e=new M3(c),t={...I.headers,...G.headers,"Content-Length":G.contentLength};return{...I,body:e,headers:t}}function XpI(){return typeof AbortController>"u"&&(globalThis.AbortController=QpI.AbortController),{kind:"node",fetch:So.default,Request:So.Request,Response:So.Response,Headers:So.Headers,FormData:A3,Blob:FW,File:es,ReadableStream:bfI,getMultipartRequestOptions:sfI,getDefaultAgent:l=>l.startsWith("https")?mfI:ZfI,fileFromPath:nfI,isFsReadStream:l=>l instanceof afI}}var So,uS,QpI,FpI,ZfI,mfI,HpI=L(()=>{So=MI(PsI(),1);vNI();uS=MI(fNI(),1),QpI=MI(lpI(),1);spI();WpI();FpI=!1;ZfI=new uS.default({keepAlive:!0,timeout:60*1e3}),mfI=new uS.default.HttpsAgent({keepAlive:!0,timeout:60*1e3})});var vpI=L(()=>{HpI()});var iS,GE=L(()=>{bj();vpI();bj();iS=()=>{R2||ssI(XpI(),{auto:!0})};iS()});var zl,Na,Tt,Ko,To,cE,eE,tE,aE,dE,bE,nE,ZE,fF,OF,Bn=L(()=>{dc();zl=class extends Error{},Na=class l extends zl{constructor(I,G,c,e){super(`${l.makeMessage(I,G,c)}`),this.status=I,this.headers=e,this.request_id=e?.["x-request-id"],this.error=G;let t=G;this.code=t?.code,this.param=t?.param,this.type=t?.type}static makeMessage(I,G,c){let e=G?.message?typeof G.message=="string"?G.message:JSON.stringify(G.message):G?JSON.stringify(G):c;return I&&e?`${I} ${e}`:I?`${I} status code (no body)`:e||"(no status code or body)"}static generate(I,G,c,e){if(!I||!e)return new Ko({message:c,cause:j3(G)});let t=G?.error;return I===400?new cE(I,t,c,e):I===401?new eE(I,t,c,e):I===403?new tE(I,t,c,e):I===404?new aE(I,t,c,e):I===409?new dE(I,t,c,e):I===422?new bE(I,t,c,e):I===429?new nE(I,t,c,e):I>=500?new ZE(I,t,c,e):new l(I,t,c,e)}},Tt=class extends Na{constructor({message:I}={}){super(void 0,void 0,I||"Request was aborted.",void 0)}},Ko=class extends Na{constructor({message:I,cause:G}){super(void 0,void 0,I||"Connection error.",void 0),G&&(this.cause=G)}},To=class extends Ko{constructor({message:I}={}){super({message:I??"Request timed out."})}},cE=class extends Na{},eE=class extends Na{},tE=class extends Na{},aE=class extends Na{},dE=class extends Na{},bE=class extends Na{},nE=class extends Na{},ZE=class extends Na{},fF=class extends zl{constructor(){super("Could not parse response content as the length limit was reached")}},OF=class extends zl{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}});function pfI(l,I){for(let e=I??0;e<l.length;e++){if(l[e]===10)return{preceding:e,index:e+1,carriage:!1};if(l[e]===13)return{preceding:e,index:e+1,carriage:!0}}return null}function wpI(l){for(let c=0;c<l.length-1;c++){if(l[c]===10&&l[c+1]===10||l[c]===13&&l[c+1]===13)return c+2;if(l[c]===13&&l[c+1]===10&&c+3<l.length&&l[c+2]===13&&l[c+3]===10)return c+4}return-1}var S3,z2,Un,x2,EpI=L(()=>{Bn();S3=function(l,I,G,c,e){if(c==="m")throw new TypeError("Private method is not writable");if(c==="a"&&!e)throw new TypeError("Private accessor was defined without a setter");if(typeof I=="function"?l!==I||!e:!I.has(l))throw new TypeError("Cannot write private member to an object whose class did not declare it");return c==="a"?e.call(l,G):e?e.value=G:I.set(l,G),G},z2=function(l,I,G,c){if(G==="a"&&!c)throw new TypeError("Private accessor was defined without a getter");if(typeof I=="function"?l!==I||!c:!I.has(l))throw new TypeError("Cannot read private member from an object whose class did not declare it");return G==="m"?c:G==="a"?c.call(l):c?c.value:I.get(l)},x2=class{constructor(){Un.set(this,void 0),this.buffer=new Uint8Array,S3(this,Un,null,"f")}decode(I){if(I==null)return[];let G=I instanceof ArrayBuffer?new Uint8Array(I):typeof I=="string"?new TextEncoder().encode(I):I,c=new Uint8Array(this.buffer.length+G.length);c.set(this.buffer),c.set(G,this.buffer.length),this.buffer=c;let e=[],t;for(;(t=pfI(this.buffer,z2(this,Un,"f")))!=null;){if(t.carriage&&z2(this,Un,"f")==null){S3(this,Un,t.index,"f");continue}if(z2(this,Un,"f")!=null&&(t.index!==z2(this,Un,"f")+1||t.carriage)){e.push(this.decodeText(this.buffer.slice(0,z2(this,Un,"f")-1))),this.buffer=this.buffer.slice(z2(this,Un,"f")),S3(this,Un,null,"f");continue}let a=z2(this,Un,"f")!==null?t.preceding-1:t.preceding,n=this.decodeText(this.buffer.slice(0,a));e.push(n),this.buffer=this.buffer.slice(t.index),S3(this,Un,null,"f")}return e}decodeText(I){if(I==null)return"";if(typeof I=="string")return I;if(typeof Buffer<"u"){if(I instanceof Buffer)return I.toString();if(I instanceof Uint8Array)return Buffer.from(I).toString();throw new zl(`Unexpected: received non-Uint8Array (${I.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<"u"){if(I instanceof Uint8Array||I instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(I);throw new zl(`Unexpected: received non-Uint8Array/ArrayBuffer (${I.constructor.name}) in a web platform. Please report this error.`)}throw new zl("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){return this.buffer.length?this.decode(`
316
316
  `):[]}};Un=new WeakMap;x2.NEWLINE_CHARS=new Set([`
317
317
  `,"\r"]);x2.NEWLINE_REGEXP=/\r\n|[\n\r]/g});function YS(l){if(l[Symbol.asyncIterator])return l;let I=l.getReader();return{async next(){try{let G=await I.read();return G?.done&&I.releaseLock(),G}catch(G){throw I.releaseLock(),G}},async return(){let G=I.cancel();return I.releaseLock(),await G,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}var gpI=L(()=>{});async function*hfI(l,I){if(!l.body)throw I.abort(),new zl("Attempted to iterate over a response with no body");let G=new VS,c=new x2,e=YS(l.body);for await(let t of ofI(e))for(let a of c.decode(t)){let n=G.decode(a);n&&(yield n)}for(let t of c.flush()){let a=G.decode(t);a&&(yield a)}}async function*ofI(l){let I=new Uint8Array;for await(let G of l){if(G==null)continue;let c=G instanceof ArrayBuffer?new Uint8Array(G):typeof G=="string"?new TextEncoder().encode(G):G,e=new Uint8Array(I.length+c.length);e.set(I),e.set(c,I.length),I=e;let t;for(;(t=wpI(I))!==-1;)yield I.slice(0,t),I=I.slice(t)}I.length>0&&(yield I)}function ufI(l,I){let G=l.indexOf(I);return G!==-1?[l.substring(0,G),I,l.substring(G+I.length)]:[l,"",""]}var vW,VS,K3=L(()=>{GE();Bn();EpI();gpI();dc();Bn();vW=class l{constructor(I,G){this.iterator=I,this.controller=G}static fromSSEResponse(I,G){let c=!1;async function*e(){if(c)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");c=!0;let t=!1;try{for await(let a of hfI(I,G))if(!t){if(a.data.startsWith("[DONE]")){t=!0;continue}if(a.event===null||a.event.startsWith("response.")||a.event.startsWith("transcript.")){let n;try{n=JSON.parse(a.data)}catch(Z){throw console.error("Could not parse message into JSON:",a.data),console.error("From chunk:",a.raw),Z}if(n&&n.error)throw new Na(void 0,n.error,void 0,rS(I.headers));yield n}else{let n;try{n=JSON.parse(a.data)}catch(Z){throw console.error("Could not parse message into JSON:",a.data),console.error("From chunk:",a.raw),Z}if(a.event=="error")throw new Na(void 0,n.error,n.message,void 0);yield{event:a.event,data:n}}}t=!0}catch(a){if(a instanceof Error&&a.name==="AbortError")return;throw a}finally{t||G.abort()}}return new l(e,G)}static fromReadableStream(I,G){let c=!1;async function*e(){let a=new x2,n=YS(I);for await(let Z of n)for(let W of a.decode(Z))yield W;for(let Z of a.flush())yield Z}async function*t(){if(c)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");c=!0;let a=!1;try{for await(let n of e())a||n&&(yield JSON.parse(n));a=!0}catch(n){if(n instanceof Error&&n.name==="AbortError")return;throw n}finally{a||G.abort()}}return new l(t,G)}[Symbol.asyncIterator](){return this.iterator()}tee(){let I=[],G=[],c=this.iterator(),e=t=>({next:()=>{if(t.length===0){let a=c.next();I.push(a),G.push(a)}return t.shift()}});return[new l(()=>e(I),this.controller),new l(()=>e(G),this.controller)]}toReadableStream(){let I=this,G,c=new TextEncoder;return new ej({async start(){G=I[Symbol.asyncIterator]()},async pull(e){try{let{value:t,done:a}=await G.next();if(a)return e.close();let n=c.encode(JSON.stringify(t)+`
318
318
  `);e.enqueue(n)}catch(t){e.error(t)}},async cancel(){await G.return?.()}})}};VS=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(I){if(I.endsWith("\r")&&(I=I.substring(0,I.length-1)),!I){if(!this.event&&!this.data.length)return null;let t={event:this.event,data:this.data.join(`
319
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],t}if(this.chunks.push(I),I.startsWith(":"))return null;let[G,c,e]=ufI(I,":");return e.startsWith(" ")&&(e=e.substring(1)),G==="event"?this.event=e:G==="data"&&this.data.push(e),null}}});async function QS(l,I,G){if(l=await l,ApI(l))return l;if(ypI(l)){let e=await l.blob();I||(I=new URL(l.url).pathname.split(/[\\/]/).pop()??"unknown_file");let t=mE(e)?[await e.arrayBuffer()]:[e];return new S4(t,I,G)}let c=await YfI(l);if(I||(I=rfI(l)??"unknown_file"),!G?.type){let e=c[0]?.type;typeof e=="string"&&(G={...G,type:e})}return new S4(c,I,G)}async function YfI(l){let I=[];if(typeof l=="string"||ArrayBuffer.isView(l)||l instanceof ArrayBuffer)I.push(l);else if(mE(l))I.push(await l.arrayBuffer());else if(RfI(l))for await(let G of l)I.push(G);else throw new Error(`Unexpected data type: ${typeof l}; constructor: ${l?.constructor?.name}; props: ${VfI(l)}`);return I}function VfI(l){return`[${Object.getOwnPropertyNames(l).map(G=>`"${G}"`).join(", ")}]`}function rfI(l){return RS(l.name)||RS(l.filename)||RS(l.path)?.split(/[\\/]/).pop()}var ypI,ApI,mE,ifI,RS,RfI,XS,Ob,CpI,FS,T3=L(()=>{GE();GE();ypI=l=>l!=null&&typeof l=="object"&&typeof l.url=="string"&&typeof l.blob=="function",ApI=l=>l!=null&&typeof l=="object"&&typeof l.name=="string"&&typeof l.lastModified=="number"&&mE(l),mE=l=>l!=null&&typeof l=="object"&&typeof l.size=="number"&&typeof l.type=="string"&&typeof l.text=="function"&&typeof l.slice=="function"&&typeof l.arrayBuffer=="function",ifI=l=>ApI(l)||ypI(l)||dj(l);RS=l=>{if(typeof l=="string")return l;if(typeof Buffer<"u"&&l instanceof Buffer)return String(l)},RfI=l=>l!=null&&typeof l=="object"&&typeof l[Symbol.asyncIterator]=="function",XS=l=>l&&typeof l=="object"&&l.body&&l[Symbol.toStringTag]==="MultipartBody",Ob=async l=>{let I=await CpI(l.body);return tj(I,l)},CpI=async l=>{let I=new cj;return await Promise.all(Object.entries(l||{}).map(([G,c])=>FS(I,G,c))),I},FS=async(l,I,G)=>{if(G!==void 0){if(G==null)throw new TypeError(`Received null for "${I}"; to pass null in FormData, you must use the string 'null'`);if(typeof G=="string"||typeof G=="number"||typeof G=="boolean")l.append(I,String(G));else if(ifI(G)){let c=await QS(G);l.append(I,c)}else if(Array.isArray(G))await Promise.all(G.map(c=>FS(l,I+"[]",c)));else if(typeof G=="object")await Promise.all(Object.entries(G).map(([c,e])=>FS(l,`${I}[${c}]`,e)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${G} instead`)}}});async function BpI(l){let{response:I}=l;if(l.options.stream)return Yp("response",I.status,I.url,I.headers,I.body),l.options.__streamClass?l.options.__streamClass.fromSSEResponse(I,l.controller):vW.fromSSEResponse(I,l.controller);if(I.status===204)return null;if(l.options.__binaryResponse)return I;let c=I.headers.get("content-type")?.split(";")[0]?.trim();if(c?.includes("application/json")||c?.endsWith("+json")){let a=await I.json();return Yp("response",I.status,I.url,I.headers,a),UpI(a,I)}let t=await I.text();return Yp("response",I.status,I.url,I.headers,t),t}function UpI(l,I){return!l||typeof l!="object"||Array.isArray(l)?l:Object.defineProperty(l,"_request_id",{value:I.headers.get("x-request-id"),enumerable:!1})}function wfI(){if(typeof navigator>"u"||!navigator)return null;let l=[{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:I,pattern:G}of l){let c=G.exec(navigator.userAgent);if(c){let e=c[1]||0,t=c[2]||0,a=c[3]||0;return{browser:I,version:`${e}.${t}.${a}`}}}return null}function fpI(l){if(!l)return!0;for(let I in l)return!1;return!0}function OpI(l,I){return Object.prototype.hasOwnProperty.call(l,I)}function zpI(l,I){for(let G in I){if(!OpI(I,G))continue;let c=G.toLowerCase();if(!c)continue;let e=I[G];e===null?delete l[c]:e!==void 0&&(l[c]=e)}}function Yp(l,...I){if(typeof process<"u"&&process?.env?.DEBUG==="true"){let G=I.map(c=>{if(!c)return c;if(c.headers){let t={...c,headers:{...c.headers}};for(let a in c.headers)xpI.has(a.toLowerCase())&&(t.headers[a]="REDACTED");return t}let e=null;for(let t in c)xpI.has(t.toLowerCase())&&(e??(e={...c}),e[t]="REDACTED");return e??c});console.log(`OpenAI:DEBUG:${l}`,...G)}}function NE(l){return l!=null&&typeof l=="object"&&!Array.isArray(l)}var QfI,XfI,D3,P3,_3,sE,vS,rS,HfI,XG,vfI,JpI,LpI,kpI,EfI,gfI,yfI,AfI,Vp,HS,j3,WE,xpI,CfI,MpI,JfI,q3,jpI,dc=L(()=>{ZsI();K3();Bn();GE();T3();T3();QfI=function(l,I,G,c,e){if(c==="m")throw new TypeError("Private method is not writable");if(c==="a"&&!e)throw new TypeError("Private accessor was defined without a setter");if(typeof I=="function"?l!==I||!e:!I.has(l))throw new TypeError("Cannot write private member to an object whose class did not declare it");return c==="a"?e.call(l,G):e?e.value=G:I.set(l,G),G},XfI=function(l,I,G,c){if(G==="a"&&!c)throw new TypeError("Private accessor was defined without a getter");if(typeof I=="function"?l!==I||!c:!I.has(l))throw new TypeError("Cannot read private member from an object whose class did not declare it");return G==="m"?c:G==="a"?c.call(l):c?c.value:I.get(l)};iS();P3=class l extends Promise{constructor(I,G=BpI){super(c=>{c(null)}),this.responsePromise=I,this.parseResponse=G}_thenUnwrap(I){return new l(this.responsePromise,async G=>UpI(I(await this.parseResponse(G),G),G.response))}asResponse(){return this.responsePromise.then(I=>I.response)}async withResponse(){let[I,G]=await Promise.all([this.parse(),this.asResponse()]);return{data:I,response:G,request_id:G.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),this.parsedPromise}then(I,G){return this.parse().then(I,G)}catch(I){return this.parse().catch(I)}finally(I){return this.parse().finally(I)}},_3=class{constructor({baseURL:I,maxRetries:G=2,timeout:c=6e5,httpAgent:e,fetch:t}){this.baseURL=I,this.maxRetries=HS("maxRetries",G),this.timeout=HS("timeout",c),this.httpAgent=e,this.fetch=t??Gj}authHeaders(I){return{}}defaultHeaders(I){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...EfI(),...this.authHeaders(I)}}validateHeaders(I,G){}defaultIdempotencyKey(){return`stainless-node-retry-${CfI()}`}get(I,G){return this.methodRequest("get",I,G)}post(I,G){return this.methodRequest("post",I,G)}patch(I,G){return this.methodRequest("patch",I,G)}put(I,G){return this.methodRequest("put",I,G)}delete(I,G){return this.methodRequest("delete",I,G)}methodRequest(I,G,c){return this.request(Promise.resolve(c).then(async e=>{let t=e&&mE(e?.body)?new DataView(await e.body.arrayBuffer()):e?.body instanceof DataView?e.body:e?.body instanceof ArrayBuffer?new DataView(e.body):e&&ArrayBuffer.isView(e?.body)?new DataView(e.body.buffer):e?.body;return{method:I,path:G,...e,body:t}}))}getAPIList(I,G,c){return this.requestAPIList(G,{method:"get",path:I,...c})}calculateContentLength(I){if(typeof I=="string"){if(typeof Buffer<"u")return Buffer.byteLength(I,"utf8").toString();if(typeof TextEncoder<"u")return new TextEncoder().encode(I).length.toString()}else if(ArrayBuffer.isView(I))return I.byteLength.toString();return null}buildRequest(I,{retryCount:G=0}={}){let c={...I},{method:e,path:t,query:a,headers:n={}}=c,Z=ArrayBuffer.isView(c.body)||c.__binaryRequest&&typeof c.body=="string"?c.body:XS(c.body)?c.body.body:c.body?JSON.stringify(c.body,null,2):null,W=this.calculateContentLength(Z),p=this.buildURL(t,a);"timeout"in c&&HS("timeout",c.timeout),c.timeout=c.timeout??this.timeout;let h=c.httpAgent??this.httpAgent??aj(p),o=c.timeout+1e3;typeof h?.options?.timeout=="number"&&o>(h.options.timeout??0)&&(h.options.timeout=o),this.idempotencyHeader&&e!=="get"&&(I.idempotencyKey||(I.idempotencyKey=this.defaultIdempotencyKey()),n[this.idempotencyHeader]=I.idempotencyKey);let Y=this.buildHeaders({options:c,headers:n,contentLength:W,retryCount:G});return{req:{method:e,...Z&&{body:Z},headers:Y,...h&&{agent:h},signal:c.signal??null},url:p,timeout:c.timeout}}buildHeaders({options:I,headers:G,contentLength:c,retryCount:e}){let t={};c&&(t["content-length"]=c);let a=this.defaultHeaders(I);return zpI(t,a),zpI(t,G),XS(I.body)&&R2!=="node"&&delete t["content-type"],q3(a,"x-stainless-retry-count")===void 0&&q3(G,"x-stainless-retry-count")===void 0&&(t["x-stainless-retry-count"]=String(e)),q3(a,"x-stainless-timeout")===void 0&&q3(G,"x-stainless-timeout")===void 0&&I.timeout&&(t["x-stainless-timeout"]=String(Math.trunc(I.timeout/1e3))),this.validateHeaders(t,G),t}async prepareOptions(I){}async prepareRequest(I,{url:G,options:c}){}parseHeaders(I){return I?Symbol.iterator in I?Object.fromEntries(Array.from(I).map(G=>[...G])):{...I}:{}}makeStatusError(I,G,c,e){return Na.generate(I,G,c,e)}request(I,G=null){return new P3(this.makeRequest(I,G))}async makeRequest(I,G){let c=await I,e=c.maxRetries??this.maxRetries;G==null&&(G=e),await this.prepareOptions(c);let{req:t,url:a,timeout:n}=this.buildRequest(c,{retryCount:e-G});if(await this.prepareRequest(t,{url:a,options:c}),Yp("request",a,c,t.headers),c.signal?.aborted)throw new Tt;let Z=new AbortController,W=await this.fetchWithTimeout(a,t,n,Z).catch(j3);if(W instanceof Error){if(c.signal?.aborted)throw new Tt;if(G)return this.retryRequest(c,G);throw W.name==="AbortError"?new To:new Ko({cause:W})}let p=rS(W.headers);if(!W.ok){if(G&&this.shouldRetry(W)){let X=`retrying, ${G} attempts remaining`;return Yp(`response (error; ${X})`,W.status,a,p),this.retryRequest(c,G,p)}let h=await W.text().catch(X=>j3(X).message),o=gfI(h),Y=o?void 0:h;throw Yp(`response (error; ${G?"(error; no more retries left)":"(error; not retryable)"})`,W.status,a,p,Y),this.makeStatusError(W.status,o,Y,p)}return{response:W,options:c,controller:Z}}requestAPIList(I,G){let c=this.makeRequest(G,null);return new vS(this,c,I)}buildURL(I,G){let c=AfI(I)?new URL(I):new URL(this.baseURL+(this.baseURL.endsWith("/")&&I.startsWith("/")?I.slice(1):I)),e=this.defaultQuery();return fpI(e)||(G={...e,...G}),typeof G=="object"&&G&&!Array.isArray(G)&&(c.search=this.stringifyQuery(G)),c.toString()}stringifyQuery(I){return Object.entries(I).filter(([G,c])=>typeof c<"u").map(([G,c])=>{if(typeof c=="string"||typeof c=="number"||typeof c=="boolean")return`${encodeURIComponent(G)}=${encodeURIComponent(c)}`;if(c===null)return`${encodeURIComponent(G)}=`;throw new zl(`Cannot stringify type ${typeof c}; 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(I,G,c,e){let{signal:t,...a}=G||{};t&&t.addEventListener("abort",()=>e.abort());let n=setTimeout(()=>e.abort(),c),Z={signal:e.signal,...a};return Z.method&&(Z.method=Z.method.toUpperCase()),this.fetch.call(void 0,I,Z).finally(()=>{clearTimeout(n)})}shouldRetry(I){let G=I.headers.get("x-should-retry");return G==="true"?!0:G==="false"?!1:I.status===408||I.status===409||I.status===429||I.status>=500}async retryRequest(I,G,c){let e,t=c?.["retry-after-ms"];if(t){let n=parseFloat(t);Number.isNaN(n)||(e=n)}let a=c?.["retry-after"];if(a&&!e){let n=parseFloat(a);Number.isNaN(n)?e=Date.parse(a)-Date.now():e=n*1e3}if(!(e&&0<=e&&e<60*1e3)){let n=I.maxRetries??this.maxRetries;e=this.calculateDefaultRetryTimeoutMillis(G,n)}return await Vp(e),this.makeRequest(I,G-1)}calculateDefaultRetryTimeoutMillis(I,G){let t=G-I,a=Math.min(.5*Math.pow(2,t),8),n=1-Math.random()*.25;return a*n*1e3}getUserAgent(){return`${this.constructor.name}/JS ${r2}`}},sE=class{constructor(I,G,c,e){D3.set(this,void 0),QfI(this,D3,I,"f"),this.options=e,this.response=G,this.body=c}hasNextPage(){return this.getPaginatedItems().length?this.nextPageInfo()!=null:!1}async getNextPage(){let I=this.nextPageInfo();if(!I)throw new zl("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");let G={...this.options};if("params"in I&&typeof G.query=="object")G.query={...G.query,...I.params};else if("url"in I){let c=[...Object.entries(G.query||{}),...I.url.searchParams.entries()];for(let[e,t]of c)I.url.searchParams.set(e,t);G.query=void 0,G.path=I.url.toString()}return await XfI(this,D3,"f").requestAPIList(this.constructor,G)}async*iterPages(){let I=this;for(yield I;I.hasNextPage();)I=await I.getNextPage(),yield I}async*[(D3=new WeakMap,Symbol.asyncIterator)](){for await(let I of this.iterPages())for(let G of I.getPaginatedItems())yield G}},vS=class extends P3{constructor(I,G,c){super(G,async e=>new c(I,e.response,await BpI(e),e.options))}async*[Symbol.asyncIterator](){let I=await this;for await(let G of I)yield G}},rS=l=>new Proxy(Object.fromEntries(l.entries()),{get(I,G){let c=G.toString();return I[c.toLowerCase()]||I[c]}}),HfI={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__metadata:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},XG=l=>typeof l=="object"&&l!==null&&!fpI(l)&&Object.keys(l).every(I=>OpI(HfI,I)),vfI=()=>{if(typeof Deno<"u"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":r2,"X-Stainless-OS":LpI(Deno.build.os),"X-Stainless-Arch":JpI(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":r2,"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<"u"?process:0)==="[object process]")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":r2,"X-Stainless-OS":LpI(process.platform),"X-Stainless-Arch":JpI(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};let l=wfI();return l?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":r2,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${l.browser}`,"X-Stainless-Runtime-Version":l.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":r2,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};JpI=l=>l==="x32"?"x32":l==="x86_64"||l==="x64"?"x64":l==="arm"?"arm":l==="aarch64"||l==="arm64"?"arm64":l?`other:${l}`:"unknown",LpI=l=>(l=l.toLowerCase(),l.includes("ios")?"iOS":l==="android"?"Android":l==="darwin"?"MacOS":l==="win32"?"Windows":l==="freebsd"?"FreeBSD":l==="openbsd"?"OpenBSD":l==="linux"?"Linux":l?`Other:${l}`:"Unknown"),EfI=()=>kpI??(kpI=vfI()),gfI=l=>{try{return JSON.parse(l)}catch{return}},yfI=/^[a-z][a-z0-9+.-]*:/i,AfI=l=>yfI.test(l),Vp=l=>new Promise(I=>setTimeout(I,l)),HS=(l,I)=>{if(typeof I!="number"||!Number.isInteger(I))throw new zl(`${l} must be an integer`);if(I<0)throw new zl(`${l} must be a positive integer`);return I},j3=l=>{if(l instanceof Error)return l;if(typeof l=="object"&&l!==null)try{return new Error(JSON.stringify(l))}catch{}return new Error(l)},WE=l=>{if(typeof process<"u")return process.env?.[l]?.trim()??void 0;if(typeof Deno<"u")return Deno.env?.get?.(l)?.trim()};xpI=new Set(["authorization","api-key"]);CfI=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,l=>{let I=Math.random()*16|0;return(l==="x"?I:I&3|8).toString(16)}),MpI=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u",JfI=l=>typeof l?.get=="function",q3=(l,I)=>{let G=I.toLowerCase();if(JfI(l)){let c=I[0]?.toUpperCase()+I.substring(1).replace(/([^\w])(\w)/g,(e,t,a)=>t+a.toUpperCase());for(let e of[I,G,I.toUpperCase(),c]){let t=l.get(e);if(t)return t}}for(let[c,e]of Object.entries(l))if(c.toLowerCase()===G)return Array.isArray(e)?(e.length<=1||console.warn(`Received ${e.length} entries for the ${I} header, using the first entry.`),e[0]):e},jpI=l=>{if(typeof Buffer<"u"){let I=Buffer.from(l,"base64");return Array.from(new Float32Array(I.buffer,I.byteOffset,I.length/Float32Array.BYTES_PER_ELEMENT))}else{let I=atob(l),G=I.length,c=new Uint8Array(G);for(let e=0;e<G;e++)c[e]=I.charCodeAt(e);return Array.from(new Float32Array(c.buffer))}}});var wW,lc,Dt=L(()=>{dc();wW=class extends sE{constructor(I,G,c,e){super(I,G,c,e),this.data=c.data||[],this.object=c.object}getPaginatedItems(){return this.data??[]}nextPageParams(){return null}nextPageInfo(){return null}},lc=class extends sE{constructor(I,G,c,e){super(I,G,c,e),this.data=c.data||[],this.has_more=c.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageParams(){let I=this.nextPageInfo();if(!I)return null;if("params"in I)return I.params;let G=Object.fromEntries(I.url.searchParams);return Object.keys(G).length?G:null}nextPageInfo(){let I=this.getPaginatedItems();if(!I.length)return null;let G=I[I.length-1]?.id;return G?{params:{after:G}}:null}}});var cl,aG=L(()=>{cl=class{constructor(I){this._client=I}}});var MF,wS=L(()=>{aG();dc();pE();MF=class extends cl{list(I,G={},c){return XG(G)?this.list(I,{},G):this._client.getAPIList(`/chat/completions/${I}/messages`,$3,{query:G,...c})}}});var Do,qo,$3,pE=L(()=>{aG();dc();wS();wS();Dt();Do=class extends cl{constructor(){super(...arguments),this.messages=new MF(this._client)}create(I,G){return this._client.post("/chat/completions",{body:I,...G,stream:I.stream??!1})}retrieve(I,G){return this._client.get(`/chat/completions/${I}`,G)}update(I,G,c){return this._client.post(`/chat/completions/${I}`,{body:G,...c})}list(I={},G){return XG(I)?this.list({},I):this._client.getAPIList("/chat/completions",qo,{query:I,...G})}del(I,G){return this._client.delete(`/chat/completions/${I}`,G)}},qo=class extends lc{},$3=class extends lc{};Do.ChatCompletionsPage=qo;Do.Messages=MF});var Rp,ES=L(()=>{aG();pE();pE();Rp=class extends cl{constructor(){super(...arguments),this.completions=new Do(this._client)}};Rp.Completions=Do;Rp.ChatCompletionsPage=qo});var SpI=L(()=>{ES()});var KpI=L(()=>{});var jF,gS=L(()=>{aG();jF=class extends cl{create(I,G){return this._client.post("/audio/speech",{body:I,...G,headers:{Accept:"application/octet-stream",...G?.headers},__binaryResponse:!0})}}});var SF,yS=L(()=>{aG();dc();SF=class extends cl{create(I,G){return this._client.post("/audio/transcriptions",Ob({body:I,...G,stream:I.stream??!1,__metadata:{model:I.model}}))}}});var KF,AS=L(()=>{aG();dc();KF=class extends cl{create(I,G){return this._client.post("/audio/translations",Ob({body:I,...G,__metadata:{model:I.model}}))}}});var EW,CS=L(()=>{aG();gS();gS();yS();yS();AS();AS();EW=class extends cl{constructor(){super(...arguments),this.transcriptions=new SF(this._client),this.translations=new KF(this._client),this.speech=new jF(this._client)}};EW.Transcriptions=SF;EW.Translations=KF;EW.Speech=jF});var Po,B2,JS=L(()=>{aG();dc();Dt();Po=class extends cl{create(I,G){return this._client.post("/batches",{body:I,...G})}retrieve(I,G){return this._client.get(`/batches/${I}`,G)}list(I={},G){return XG(I)?this.list({},I):this._client.getAPIList("/batches",B2,{query:I,...G})}cancel(I,G){return this._client.post(`/batches/${I}/cancel`,G)}},B2=class extends lc{};Po.BatchesPage=B2});var as,dt,LS,IL,lL,hE,oE,GL,uE,Fp,iE,cL,eL,TF,TpI,_o,tL=L(()=>{Bn();as=function(l,I,G,c,e){if(c==="m")throw new TypeError("Private method is not writable");if(c==="a"&&!e)throw new TypeError("Private accessor was defined without a setter");if(typeof I=="function"?l!==I||!e:!I.has(l))throw new TypeError("Cannot write private member to an object whose class did not declare it");return c==="a"?e.call(l,G):e?e.value=G:I.set(l,G),G},dt=function(l,I,G,c){if(G==="a"&&!c)throw new TypeError("Private accessor was defined without a getter");if(typeof I=="function"?l!==I||!c:!I.has(l))throw new TypeError("Cannot read private member from an object whose class did not declare it");return G==="m"?c:G==="a"?c.call(l):c?c.value:I.get(l)},_o=class{constructor(){LS.add(this),this.controller=new AbortController,IL.set(this,void 0),lL.set(this,()=>{}),hE.set(this,()=>{}),oE.set(this,void 0),GL.set(this,()=>{}),uE.set(this,()=>{}),Fp.set(this,{}),iE.set(this,!1),cL.set(this,!1),eL.set(this,!1),TF.set(this,!1),as(this,IL,new Promise((I,G)=>{as(this,lL,I,"f"),as(this,hE,G,"f")}),"f"),as(this,oE,new Promise((I,G)=>{as(this,GL,I,"f"),as(this,uE,G,"f")}),"f"),dt(this,IL,"f").catch(()=>{}),dt(this,oE,"f").catch(()=>{})}_run(I){setTimeout(()=>{I().then(()=>{this._emitFinal(),this._emit("end")},dt(this,LS,"m",TpI).bind(this))},0)}_connected(){this.ended||(dt(this,lL,"f").call(this),this._emit("connect"))}get ended(){return dt(this,iE,"f")}get errored(){return dt(this,cL,"f")}get aborted(){return dt(this,eL,"f")}abort(){this.controller.abort()}on(I,G){return(dt(this,Fp,"f")[I]||(dt(this,Fp,"f")[I]=[])).push({listener:G}),this}off(I,G){let c=dt(this,Fp,"f")[I];if(!c)return this;let e=c.findIndex(t=>t.listener===G);return e>=0&&c.splice(e,1),this}once(I,G){return(dt(this,Fp,"f")[I]||(dt(this,Fp,"f")[I]=[])).push({listener:G,once:!0}),this}emitted(I){return new Promise((G,c)=>{as(this,TF,!0,"f"),I!=="error"&&this.once("error",c),this.once(I,G)})}async done(){as(this,TF,!0,"f"),await dt(this,oE,"f")}_emit(I,...G){if(dt(this,iE,"f"))return;I==="end"&&(as(this,iE,!0,"f"),dt(this,GL,"f").call(this));let c=dt(this,Fp,"f")[I];if(c&&(dt(this,Fp,"f")[I]=c.filter(e=>!e.once),c.forEach(({listener:e})=>e(...G))),I==="abort"){let e=G[0];!dt(this,TF,"f")&&!c?.length&&Promise.reject(e),dt(this,hE,"f").call(this,e),dt(this,uE,"f").call(this,e),this._emit("end");return}if(I==="error"){let e=G[0];!dt(this,TF,"f")&&!c?.length&&Promise.reject(e),dt(this,hE,"f").call(this,e),dt(this,uE,"f").call(this,e),this._emit("end")}}_emitFinal(){}};IL=new WeakMap,lL=new WeakMap,hE=new WeakMap,oE=new WeakMap,GL=new WeakMap,uE=new WeakMap,Fp=new WeakMap,iE=new WeakMap,cL=new WeakMap,eL=new WeakMap,TF=new WeakMap,LS=new WeakSet,TpI=function(I){if(as(this,cL,!0,"f"),I instanceof Error&&I.name==="AbortError"&&(I=new Tt),I instanceof Tt)return as(this,eL,!0,"f"),this._emit("abort",I);if(I instanceof zl)return this._emit("error",I);if(I instanceof Error){let G=new zl(I.message);return G.cause=I,this._emit("error",G)}return this._emit("error",new zl(String(I)))}});var Kl,fn,cd,kS,gW,aL,ds,f2,DF,U2,nL,On,dL,bL,rE,YE,VE,DpI,qpI,PpI,_pI,$pI,IhI,lhI,yW,zS=L(()=>{dc();K3();Bn();tL();Kl=function(l,I,G,c){if(G==="a"&&!c)throw new TypeError("Private accessor was defined without a getter");if(typeof I=="function"?l!==I||!c:!I.has(l))throw new TypeError("Cannot read private member from an object whose class did not declare it");return G==="m"?c:G==="a"?c.call(l):c?c.value:I.get(l)},fn=function(l,I,G,c,e){if(c==="m")throw new TypeError("Private method is not writable");if(c==="a"&&!e)throw new TypeError("Private accessor was defined without a setter");if(typeof I=="function"?l!==I||!e:!I.has(l))throw new TypeError("Cannot write private member to an object whose class did not declare it");return c==="a"?e.call(l,G):e?e.value=G:I.set(l,G),G},yW=class l extends _o{constructor(){super(...arguments),cd.add(this),kS.set(this,[]),gW.set(this,{}),aL.set(this,{}),ds.set(this,void 0),f2.set(this,void 0),DF.set(this,void 0),U2.set(this,void 0),nL.set(this,void 0),On.set(this,void 0),dL.set(this,void 0),bL.set(this,void 0),rE.set(this,void 0)}[(kS=new WeakMap,gW=new WeakMap,aL=new WeakMap,ds=new WeakMap,f2=new WeakMap,DF=new WeakMap,U2=new WeakMap,nL=new WeakMap,On=new WeakMap,dL=new WeakMap,bL=new WeakMap,rE=new WeakMap,cd=new WeakSet,Symbol.asyncIterator)](){let I=[],G=[],c=!1;return this.on("event",e=>{let t=G.shift();t?t.resolve(e):I.push(e)}),this.on("end",()=>{c=!0;for(let e of G)e.resolve(void 0);G.length=0}),this.on("abort",e=>{c=!0;for(let t of G)t.reject(e);G.length=0}),this.on("error",e=>{c=!0;for(let t of G)t.reject(e);G.length=0}),{next:async()=>I.length?{value:I.shift(),done:!1}:c?{value:void 0,done:!0}:new Promise((t,a)=>G.push({resolve:t,reject:a})).then(t=>t?{value:t,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(I){let G=new l;return G._run(()=>G._fromReadableStream(I)),G}async _fromReadableStream(I,G){let c=G?.signal;c&&(c.aborted&&this.controller.abort(),c.addEventListener("abort",()=>this.controller.abort())),this._connected();let e=vW.fromReadableStream(I,this.controller);for await(let t of e)Kl(this,cd,"m",YE).call(this,t);if(e.controller.signal?.aborted)throw new Tt;return this._addRun(Kl(this,cd,"m",VE).call(this))}toReadableStream(){return new vW(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(I,G,c,e,t){let a=new l;return a._run(()=>a._runToolAssistantStream(I,G,c,e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"stream"}})),a}async _createToolAssistantStream(I,G,c,e,t){let a=t?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));let n={...e,stream:!0},Z=await I.submitToolOutputs(G,c,n,{...t,signal:this.controller.signal});this._connected();for await(let W of Z)Kl(this,cd,"m",YE).call(this,W);if(Z.controller.signal?.aborted)throw new Tt;return this._addRun(Kl(this,cd,"m",VE).call(this))}static createThreadAssistantStream(I,G,c){let e=new l;return e._run(()=>e._threadAssistantStream(I,G,{...c,headers:{...c?.headers,"X-Stainless-Helper-Method":"stream"}})),e}static createAssistantStream(I,G,c,e){let t=new l;return t._run(()=>t._runAssistantStream(I,G,c,{...e,headers:{...e?.headers,"X-Stainless-Helper-Method":"stream"}})),t}currentEvent(){return Kl(this,dL,"f")}currentRun(){return Kl(this,bL,"f")}currentMessageSnapshot(){return Kl(this,ds,"f")}currentRunStepSnapshot(){return Kl(this,rE,"f")}async finalRunSteps(){return await this.done(),Object.values(Kl(this,gW,"f"))}async finalMessages(){return await this.done(),Object.values(Kl(this,aL,"f"))}async finalRun(){if(await this.done(),!Kl(this,f2,"f"))throw Error("Final run was not received.");return Kl(this,f2,"f")}async _createThreadAssistantStream(I,G,c){let e=c?.signal;e&&(e.aborted&&this.controller.abort(),e.addEventListener("abort",()=>this.controller.abort()));let t={...G,stream:!0},a=await I.createAndRun(t,{...c,signal:this.controller.signal});this._connected();for await(let n of a)Kl(this,cd,"m",YE).call(this,n);if(a.controller.signal?.aborted)throw new Tt;return this._addRun(Kl(this,cd,"m",VE).call(this))}async _createAssistantStream(I,G,c,e){let t=e?.signal;t&&(t.aborted&&this.controller.abort(),t.addEventListener("abort",()=>this.controller.abort()));let a={...c,stream:!0},n=await I.create(G,a,{...e,signal:this.controller.signal});this._connected();for await(let Z of n)Kl(this,cd,"m",YE).call(this,Z);if(n.controller.signal?.aborted)throw new Tt;return this._addRun(Kl(this,cd,"m",VE).call(this))}static accumulateDelta(I,G){for(let[c,e]of Object.entries(G)){if(!I.hasOwnProperty(c)){I[c]=e;continue}let t=I[c];if(t==null){I[c]=e;continue}if(c==="index"||c==="type"){I[c]=e;continue}if(typeof t=="string"&&typeof e=="string")t+=e;else if(typeof t=="number"&&typeof e=="number")t+=e;else if(NE(t)&&NE(e))t=this.accumulateDelta(t,e);else if(Array.isArray(t)&&Array.isArray(e)){if(t.every(a=>typeof a=="string"||typeof a=="number")){t.push(...e);continue}for(let a of e){if(!NE(a))throw new Error(`Expected array delta entry to be an object but got: ${a}`);let n=a.index;if(n==null)throw console.error(a),new Error("Expected array delta entry to have an `index` property");if(typeof n!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${n}`);let Z=t[n];Z==null?t.push(a):t[n]=this.accumulateDelta(Z,a)}continue}else throw Error(`Unhandled record type: ${c}, deltaValue: ${e}, accValue: ${t}`);I[c]=t}return I}_addRun(I){return I}async _threadAssistantStream(I,G,c){return await this._createThreadAssistantStream(G,I,c)}async _runAssistantStream(I,G,c,e){return await this._createAssistantStream(G,I,c,e)}async _runToolAssistantStream(I,G,c,e,t){return await this._createToolAssistantStream(c,I,G,e,t)}};YE=function(I){if(!this.ended)switch(fn(this,dL,I,"f"),Kl(this,cd,"m",PpI).call(this,I),I.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":Kl(this,cd,"m",lhI).call(this,I);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":Kl(this,cd,"m",qpI).call(this,I);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":Kl(this,cd,"m",DpI).call(this,I);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},VE=function(){if(this.ended)throw new zl("stream has ended, this shouldn't happen");if(!Kl(this,f2,"f"))throw Error("Final run has not been received");return Kl(this,f2,"f")},DpI=function(I){let[G,c]=Kl(this,cd,"m",$pI).call(this,I,Kl(this,ds,"f"));fn(this,ds,G,"f"),Kl(this,aL,"f")[G.id]=G;for(let e of c){let t=G.content[e.index];t?.type=="text"&&this._emit("textCreated",t.text)}switch(I.event){case"thread.message.created":this._emit("messageCreated",I.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",I.data.delta,G),I.data.delta.content)for(let e of I.data.delta.content){if(e.type=="text"&&e.text){let t=e.text,a=G.content[e.index];if(a&&a.type=="text")this._emit("textDelta",t,a.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(e.index!=Kl(this,DF,"f")){if(Kl(this,U2,"f"))switch(Kl(this,U2,"f").type){case"text":this._emit("textDone",Kl(this,U2,"f").text,Kl(this,ds,"f"));break;case"image_file":this._emit("imageFileDone",Kl(this,U2,"f").image_file,Kl(this,ds,"f"));break}fn(this,DF,e.index,"f")}fn(this,U2,G.content[e.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(Kl(this,DF,"f")!==void 0){let e=I.data.content[Kl(this,DF,"f")];if(e)switch(e.type){case"image_file":this._emit("imageFileDone",e.image_file,Kl(this,ds,"f"));break;case"text":this._emit("textDone",e.text,Kl(this,ds,"f"));break}}Kl(this,ds,"f")&&this._emit("messageDone",I.data),fn(this,ds,void 0,"f")}},qpI=function(I){let G=Kl(this,cd,"m",_pI).call(this,I);switch(fn(this,rE,G,"f"),I.event){case"thread.run.step.created":this._emit("runStepCreated",I.data);break;case"thread.run.step.delta":let c=I.data.delta;if(c.step_details&&c.step_details.type=="tool_calls"&&c.step_details.tool_calls&&G.step_details.type=="tool_calls")for(let t of c.step_details.tool_calls)t.index==Kl(this,nL,"f")?this._emit("toolCallDelta",t,G.step_details.tool_calls[t.index]):(Kl(this,On,"f")&&this._emit("toolCallDone",Kl(this,On,"f")),fn(this,nL,t.index,"f"),fn(this,On,G.step_details.tool_calls[t.index],"f"),Kl(this,On,"f")&&this._emit("toolCallCreated",Kl(this,On,"f")));this._emit("runStepDelta",I.data.delta,G);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":fn(this,rE,void 0,"f"),I.data.step_details.type=="tool_calls"&&Kl(this,On,"f")&&(this._emit("toolCallDone",Kl(this,On,"f")),fn(this,On,void 0,"f")),this._emit("runStepDone",I.data,G);break;case"thread.run.step.in_progress":break}},PpI=function(I){Kl(this,kS,"f").push(I),this._emit("event",I)},_pI=function(I){switch(I.event){case"thread.run.step.created":return Kl(this,gW,"f")[I.data.id]=I.data,I.data;case"thread.run.step.delta":let G=Kl(this,gW,"f")[I.data.id];if(!G)throw Error("Received a RunStepDelta before creation of a snapshot");let c=I.data;if(c.delta){let e=yW.accumulateDelta(G,c.delta);Kl(this,gW,"f")[I.data.id]=e}return Kl(this,gW,"f")[I.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":Kl(this,gW,"f")[I.data.id]=I.data;break}if(Kl(this,gW,"f")[I.data.id])return Kl(this,gW,"f")[I.data.id];throw new Error("No snapshot available")},$pI=function(I,G){let c=[];switch(I.event){case"thread.message.created":return[I.data,c];case"thread.message.delta":if(!G)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let e=I.data;if(e.delta.content)for(let t of e.delta.content)if(t.index in G.content){let a=G.content[t.index];G.content[t.index]=Kl(this,cd,"m",IhI).call(this,t,a)}else G.content[t.index]=t,c.push(t);return[G,c];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(G)return[G,c];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},IhI=function(I,G){return yW.accumulateDelta(G,I)},lhI=function(I){switch(fn(this,bL,I.data,"f"),I.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":fn(this,f2,I.data,"f"),Kl(this,On,"f")&&(this._emit("toolCallDone",Kl(this,On,"f")),fn(this,On,void 0,"f"));break;case"thread.run.cancelling":break}}});var O2,qF,xS=L(()=>{aG();dc();Dt();O2=class extends cl{create(I,G){return this._client.post("/assistants",{body:I,...G,headers:{"OpenAI-Beta":"assistants=v2",...G?.headers}})}retrieve(I,G){return this._client.get(`/assistants/${I}`,{...G,headers:{"OpenAI-Beta":"assistants=v2",...G?.headers}})}update(I,G,c){return this._client.post(`/assistants/${I}`,{body:G,...c,headers:{"OpenAI-Beta":"assistants=v2",...c?.headers}})}list(I={},G){return XG(I)?this.list({},I):this._client.getAPIList("/assistants",qF,{query:I,...G,headers:{"OpenAI-Beta":"assistants=v2",...G?.headers}})}del(I,G){return this._client.delete(`/assistants/${I}`,{...G,headers:{"OpenAI-Beta":"assistants=v2",...G?.headers}})}},qF=class extends lc{};O2.AssistantsPage=qF});function BS(l){return typeof l.parse=="function"}var GhI=L(()=>{});var $o,US,fS,OS=L(()=>{$o=l=>l?.role==="assistant",US=l=>l?.role==="function",fS=l=>l?.role==="tool"});function RE(l){return l?.$brand==="auto-parseable-response-format"}function M2(l){return l?.$brand==="auto-parseable-tool"}function chI(l,I){return!I||!MS(I)?{...l,choices:l.choices.map(G=>({...G,message:{...G.message,parsed:null,...G.message.tool_calls?{tool_calls:G.message.tool_calls}:void 0}}))}:FE(l,I)}function FE(l,I){let G=l.choices.map(c=>{if(c.finish_reason==="length")throw new fF;if(c.finish_reason==="content_filter")throw new OF;return{...c,message:{...c.message,...c.message.tool_calls?{tool_calls:c.message.tool_calls?.map(e=>OfI(I,e))??void 0}:void 0,parsed:c.message.content&&!c.message.refusal?ffI(I,c.message.content):null}}});return{...l,choices:G}}function ffI(l,I){return l.response_format?.type!=="json_schema"?null:l.response_format?.type==="json_schema"?"$parseRaw"in l.response_format?l.response_format.$parseRaw(I):JSON.parse(I):null}function OfI(l,I){let G=l.tools?.find(c=>c.function?.name===I.function.name);return{...I,function:{...I.function,parsed_arguments:M2(G)?G.$parseRaw(I.function.arguments):G?.function.strict?JSON.parse(I.function.arguments):null}}}function ehI(l,I){if(!l)return!1;let G=l.tools?.find(c=>c.function?.name===I.function.name);return M2(G)||G?.function.strict||!1}function MS(l){return RE(l.response_format)?!0:l.tools?.some(I=>M2(I)||I.type==="function"&&I.function.strict===!0)??!1}function thI(l){for(let I of l??[]){if(I.type!=="function")throw new zl(`Currently only \`function\` tool types support auto-parsing; Received \`${I.type}\``);if(I.function.strict!==!0)throw new zl(`The \`${I.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var QE=L(()=>{Bn()});var Mb,vd,jS,ZL,SS,KS,TS,dhI,DS,ahI,PF,qS=L(()=>{Bn();GhI();OS();tL();QE();Mb=function(l,I,G,c){if(G==="a"&&!c)throw new TypeError("Private accessor was defined without a getter");if(typeof I=="function"?l!==I||!c:!I.has(l))throw new TypeError("Cannot read private member from an object whose class did not declare it");return G==="m"?c:G==="a"?c.call(l):c?c.value:I.get(l)},ahI=10,PF=class extends _o{constructor(){super(...arguments),vd.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(I){this._chatCompletions.push(I),this._emit("chatCompletion",I);let G=I.choices[0]?.message;return G&&this._addMessage(G),I}_addMessage(I,G=!0){if("content"in I||(I.content=null),this.messages.push(I),G){if(this._emit("message",I),(US(I)||fS(I))&&I.content)this._emit("functionCallResult",I.content);else if($o(I)&&I.function_call)this._emit("functionCall",I.function_call);else if($o(I)&&I.tool_calls)for(let c of I.tool_calls)c.type==="function"&&this._emit("functionCall",c.function)}}async finalChatCompletion(){await this.done();let I=this._chatCompletions[this._chatCompletions.length-1];if(!I)throw new zl("stream ended without producing a ChatCompletion");return I}async finalContent(){return await this.done(),Mb(this,vd,"m",jS).call(this)}async finalMessage(){return await this.done(),Mb(this,vd,"m",ZL).call(this)}async finalFunctionCall(){return await this.done(),Mb(this,vd,"m",SS).call(this)}async finalFunctionCallResult(){return await this.done(),Mb(this,vd,"m",KS).call(this)}async totalUsage(){return await this.done(),Mb(this,vd,"m",TS).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let I=this._chatCompletions[this._chatCompletions.length-1];I&&this._emit("finalChatCompletion",I);let G=Mb(this,vd,"m",ZL).call(this);G&&this._emit("finalMessage",G);let c=Mb(this,vd,"m",jS).call(this);c&&this._emit("finalContent",c);let e=Mb(this,vd,"m",SS).call(this);e&&this._emit("finalFunctionCall",e);let t=Mb(this,vd,"m",KS).call(this);t!=null&&this._emit("finalFunctionCallResult",t),this._chatCompletions.some(a=>a.usage)&&this._emit("totalUsage",Mb(this,vd,"m",TS).call(this))}async _createChatCompletion(I,G,c){let e=c?.signal;e&&(e.aborted&&this.controller.abort(),e.addEventListener("abort",()=>this.controller.abort())),Mb(this,vd,"m",dhI).call(this,G);let t=await I.chat.completions.create({...G,stream:!1},{...c,signal:this.controller.signal});return this._connected(),this._addChatCompletion(FE(t,G))}async _runChatCompletion(I,G,c){for(let e of G.messages)this._addMessage(e,!1);return await this._createChatCompletion(I,G,c)}async _runFunctions(I,G,c){let e="function",{function_call:t="auto",stream:a,...n}=G,Z=typeof t!="string"&&t?.name,{maxChatCompletions:W=ahI}=c||{},p={};for(let o of G.functions)p[o.name||o.function.name]=o;let h=G.functions.map(o=>({name:o.name||o.function.name,parameters:o.parameters,description:o.description}));for(let o of G.messages)this._addMessage(o,!1);for(let o=0;o<W;++o){let F=(await this._createChatCompletion(I,{...n,function_call:t,functions:h,messages:[...this.messages]},c)).choices[0]?.message;if(!F)throw new zl("missing message in ChatCompletion response");if(!F.function_call)return;let{name:R,arguments:X}=F.function_call,v=p[R];if(v){if(Z&&Z!==R){let y=`Invalid function_call: ${JSON.stringify(R)}. ${JSON.stringify(Z)} requested. Please try again`;this._addMessage({role:e,name:R,content:y});continue}}else{let y=`Invalid function_call: ${JSON.stringify(R)}. Available options are: ${h.map(k=>JSON.stringify(k.name)).join(", ")}. Please try again`;this._addMessage({role:e,name:R,content:y});continue}let g;try{g=BS(v)?await v.parse(X):X}catch(y){this._addMessage({role:e,name:R,content:y instanceof Error?y.message:String(y)});continue}let C=await v.function(g,this),A=Mb(this,vd,"m",DS).call(this,C);if(this._addMessage({role:e,name:R,content:A}),Z)return}}async _runTools(I,G,c){let e="tool",{tool_choice:t="auto",stream:a,...n}=G,Z=typeof t!="string"&&t?.function?.name,{maxChatCompletions:W=ahI}=c||{},p=G.tools.map(Y=>{if(M2(Y)){if(!Y.$callback)throw new zl("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:Y.$callback,name:Y.function.name,description:Y.function.description||"",parameters:Y.function.parameters,parse:Y.$parseRaw,strict:!0}}}return Y}),h={};for(let Y of p)Y.type==="function"&&(h[Y.function.name||Y.function.function.name]=Y.function);let o="tools"in G?p.map(Y=>Y.type==="function"?{type:"function",function:{name:Y.function.name||Y.function.function.name,parameters:Y.function.parameters,description:Y.function.description,strict:Y.function.strict}}:Y):void 0;for(let Y of G.messages)this._addMessage(Y,!1);for(let Y=0;Y<W;++Y){let R=(await this._createChatCompletion(I,{...n,tool_choice:t,tools:o,messages:[...this.messages]},c)).choices[0]?.message;if(!R)throw new zl("missing message in ChatCompletion response");if(!R.tool_calls?.length)return;for(let X of R.tool_calls){if(X.type!=="function")continue;let v=X.id,{name:g,arguments:C}=X.function,A=h[g];if(A){if(Z&&Z!==g){let U=`Invalid tool_call: ${JSON.stringify(g)}. ${JSON.stringify(Z)} requested. Please try again`;this._addMessage({role:e,tool_call_id:v,content:U});continue}}else{let U=`Invalid tool_call: ${JSON.stringify(g)}. Available options are: ${Object.keys(h).map(z=>JSON.stringify(z)).join(", ")}. Please try again`;this._addMessage({role:e,tool_call_id:v,content:U});continue}let y;try{y=BS(A)?await A.parse(C):C}catch(U){let z=U instanceof Error?U.message:String(U);this._addMessage({role:e,tool_call_id:v,content:z});continue}let k=await A.function(y,this),S=Mb(this,vd,"m",DS).call(this,k);if(this._addMessage({role:e,tool_call_id:v,content:S}),Z)return}}}};vd=new WeakSet,jS=function(){return Mb(this,vd,"m",ZL).call(this).content??null},ZL=function(){let I=this.messages.length;for(;I-- >0;){let G=this.messages[I];if($o(G)){let{function_call:c,...e}=G,t={...e,content:G.content??null,refusal:G.refusal??null};return c&&(t.function_call=c),t}}throw new zl("stream ended without producing a ChatCompletionMessage with role=assistant")},SS=function(){for(let I=this.messages.length-1;I>=0;I--){let G=this.messages[I];if($o(G)&&G?.function_call)return G.function_call;if($o(G)&&G?.tool_calls?.length)return G.tool_calls.at(-1)?.function}},KS=function(){for(let I=this.messages.length-1;I>=0;I--){let G=this.messages[I];if(US(G)&&G.content!=null||fS(G)&&G.content!=null&&typeof G.content=="string"&&this.messages.some(c=>c.role==="assistant"&&c.tool_calls?.some(e=>e.type==="function"&&e.id===G.tool_call_id)))return G.content}},TS=function(){let I={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:G}of this._chatCompletions)G&&(I.completion_tokens+=G.completion_tokens,I.prompt_tokens+=G.prompt_tokens,I.total_tokens+=G.total_tokens);return I},dhI=function(I){if(I.n!=null&&I.n>1)throw new zl("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},DS=function(I){return typeof I=="string"?I:I===void 0?"undefined":JSON.stringify(I)}});var XE,bhI=L(()=>{qS();OS();XE=class l extends PF{static runFunctions(I,G,c){let e=new l,t={...c,headers:{...c?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return e._run(()=>e._runFunctions(I,G,t)),e}static runTools(I,G,c){let e=new l,t={...c,headers:{...c?.headers,"X-Stainless-Helper-Method":"runTools"}};return e._run(()=>e._runTools(I,G,t)),e}_addMessage(I,G=!0){super._addMessage(I,G),$o(I)&&I.content&&this._emit("content",I.content)}}});function MfI(l,I=ka.ALL){if(typeof l!="string")throw new TypeError(`expecting str, got ${typeof l}`);if(!l.trim())throw new Error(`${l} is empty`);return jfI(l.trim(),I)}var ka,PS,_S,jfI,$S,nhI=L(()=>{ka={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},PS=class extends Error{},_S=class extends Error{};jfI=(l,I)=>{let G=l.length,c=0,e=o=>{throw new PS(`${o} at position ${c}`)},t=o=>{throw new _S(`${o} at position ${c}`)},a=()=>(h(),c>=G&&e("Unexpected end of input"),l[c]==='"'?n():l[c]==="{"?Z():l[c]==="["?W():l.substring(c,c+4)==="null"||ka.NULL&I&&G-c<4&&"null".startsWith(l.substring(c))?(c+=4,null):l.substring(c,c+4)==="true"||ka.BOOL&I&&G-c<4&&"true".startsWith(l.substring(c))?(c+=4,!0):l.substring(c,c+5)==="false"||ka.BOOL&I&&G-c<5&&"false".startsWith(l.substring(c))?(c+=5,!1):l.substring(c,c+8)==="Infinity"||ka.INFINITY&I&&G-c<8&&"Infinity".startsWith(l.substring(c))?(c+=8,1/0):l.substring(c,c+9)==="-Infinity"||ka.MINUS_INFINITY&I&&1<G-c&&G-c<9&&"-Infinity".startsWith(l.substring(c))?(c+=9,-1/0):l.substring(c,c+3)==="NaN"||ka.NAN&I&&G-c<3&&"NaN".startsWith(l.substring(c))?(c+=3,NaN):p()),n=()=>{let o=c,Y=!1;for(c++;c<G&&(l[c]!=='"'||Y&&l[c-1]==="\\");)Y=l[c]==="\\"?!Y:!1,c++;if(l.charAt(c)=='"')try{return JSON.parse(l.substring(o,++c-Number(Y)))}catch(F){t(String(F))}else if(ka.STR&I)try{return JSON.parse(l.substring(o,c-Number(Y))+'"')}catch{return JSON.parse(l.substring(o,l.lastIndexOf("\\"))+'"')}e("Unterminated string literal")},Z=()=>{c++,h();let o={};try{for(;l[c]!=="}";){if(h(),c>=G&&ka.OBJ&I)return o;let Y=n();h(),c++;try{let F=a();Object.defineProperty(o,Y,{value:F,writable:!0,enumerable:!0,configurable:!0})}catch(F){if(ka.OBJ&I)return o;throw F}h(),l[c]===","&&c++}}catch{if(ka.OBJ&I)return o;e("Expected '}' at end of object")}return c++,o},W=()=>{c++;let o=[];try{for(;l[c]!=="]";)o.push(a()),h(),l[c]===","&&c++}catch{if(ka.ARR&I)return o;e("Expected ']' at end of array")}return c++,o},p=()=>{if(c===0){l==="-"&&ka.NUM&I&&e("Not sure what '-' is");try{return JSON.parse(l)}catch(Y){if(ka.NUM&I)try{return l[l.length-1]==="."?JSON.parse(l.substring(0,l.lastIndexOf("."))):JSON.parse(l.substring(0,l.lastIndexOf("e")))}catch{}t(String(Y))}}let o=c;for(l[c]==="-"&&c++;l[c]&&!",]}".includes(l[c]);)c++;c==G&&!(ka.NUM&I)&&e("Unterminated number literal");try{return JSON.parse(l.substring(o,c))}catch{l.substring(o,c)==="-"&&ka.NUM&I&&e("Not sure what '-' is");try{return JSON.parse(l.substring(o,l.lastIndexOf("e")))}catch(F){t(String(F))}}},h=()=>{for(;c<G&&`
319
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],t}if(this.chunks.push(I),I.startsWith(":"))return null;let[G,c,e]=ufI(I,":");return e.startsWith(" ")&&(e=e.substring(1)),G==="event"?this.event=e:G==="data"&&this.data.push(e),null}}});async function QS(l,I,G){if(l=await l,ApI(l))return l;if(ypI(l)){let e=await l.blob();I||(I=new URL(l.url).pathname.split(/[\\/]/).pop()??"unknown_file");let t=mE(e)?[await e.arrayBuffer()]:[e];return new S4(t,I,G)}let c=await YfI(l);if(I||(I=rfI(l)??"unknown_file"),!G?.type){let e=c[0]?.type;typeof e=="string"&&(G={...G,type:e})}return new S4(c,I,G)}async function YfI(l){let I=[];if(typeof l=="string"||ArrayBuffer.isView(l)||l instanceof ArrayBuffer)I.push(l);else if(mE(l))I.push(await l.arrayBuffer());else if(RfI(l))for await(let G of l)I.push(G);else throw new Error(`Unexpected data type: ${typeof l}; constructor: ${l?.constructor?.name}; props: ${VfI(l)}`);return I}function VfI(l){return`[${Object.getOwnPropertyNames(l).map(G=>`"${G}"`).join(", ")}]`}function rfI(l){return RS(l.name)||RS(l.filename)||RS(l.path)?.split(/[\\/]/).pop()}var ypI,ApI,mE,ifI,RS,RfI,XS,Ob,CpI,FS,T3=L(()=>{GE();GE();ypI=l=>l!=null&&typeof l=="object"&&typeof l.url=="string"&&typeof l.blob=="function",ApI=l=>l!=null&&typeof l=="object"&&typeof l.name=="string"&&typeof l.lastModified=="number"&&mE(l),mE=l=>l!=null&&typeof l=="object"&&typeof l.size=="number"&&typeof l.type=="string"&&typeof l.text=="function"&&typeof l.slice=="function"&&typeof l.arrayBuffer=="function",ifI=l=>ApI(l)||ypI(l)||dj(l);RS=l=>{if(typeof l=="string")return l;if(typeof Buffer<"u"&&l instanceof Buffer)return String(l)},RfI=l=>l!=null&&typeof l=="object"&&typeof l[Symbol.asyncIterator]=="function",XS=l=>l&&typeof l=="object"&&l.body&&l[Symbol.toStringTag]==="MultipartBody",Ob=async l=>{let I=await CpI(l.body);return tj(I,l)},CpI=async l=>{let I=new cj;return await Promise.all(Object.entries(l||{}).map(([G,c])=>FS(I,G,c))),I},FS=async(l,I,G)=>{if(G!==void 0){if(G==null)throw new TypeError(`Received null for "${I}"; to pass null in FormData, you must use the string 'null'`);if(typeof G=="string"||typeof G=="number"||typeof G=="boolean")l.append(I,String(G));else if(ifI(G)){let c=await QS(G);l.append(I,c)}else if(Array.isArray(G))await Promise.all(G.map(c=>FS(l,I+"[]",c)));else if(typeof G=="object")await Promise.all(Object.entries(G).map(([c,e])=>FS(l,`${I}[${c}]`,e)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${G} instead`)}}});async function BpI(l){let{response:I}=l;if(l.options.stream)return Yp("response",I.status,I.url,I.headers,I.body),l.options.__streamClass?l.options.__streamClass.fromSSEResponse(I,l.controller):vW.fromSSEResponse(I,l.controller);if(I.status===204)return null;if(l.options.__binaryResponse)return I;let c=I.headers.get("content-type")?.split(";")[0]?.trim();if(c?.includes("application/json")||c?.endsWith("+json")){let a=await I.json();return Yp("response",I.status,I.url,I.headers,a),UpI(a,I)}let t=await I.text();return Yp("response",I.status,I.url,I.headers,t),t}function UpI(l,I){return!l||typeof l!="object"||Array.isArray(l)?l:Object.defineProperty(l,"_request_id",{value:I.headers.get("x-request-id"),enumerable:!1})}function wfI(){if(typeof navigator>"u"||!navigator)return null;let l=[{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:I,pattern:G}of l){let c=G.exec(navigator.userAgent);if(c){let e=c[1]||0,t=c[2]||0,a=c[3]||0;return{browser:I,version:`${e}.${t}.${a}`}}}return null}function fpI(l){if(!l)return!0;for(let I in l)return!1;return!0}function OpI(l,I){return Object.prototype.hasOwnProperty.call(l,I)}function zpI(l,I){for(let G in I){if(!OpI(I,G))continue;let c=G.toLowerCase();if(!c)continue;let e=I[G];e===null?delete l[c]:e!==void 0&&(l[c]=e)}}function Yp(l,...I){if(typeof process<"u"&&process?.env?.DEBUG==="true"){let G=I.map(c=>{if(!c)return c;if(c.headers){let t={...c,headers:{...c.headers}};for(let a in c.headers)xpI.has(a.toLowerCase())&&(t.headers[a]="REDACTED");return t}let e=null;for(let t in c)xpI.has(t.toLowerCase())&&(e??(e={...c}),e[t]="REDACTED");return e??c});console.log(`OpenAI:DEBUG:${l}`,...G)}}function NE(l){return l!=null&&typeof l=="object"&&!Array.isArray(l)}var QfI,XfI,D3,P3,_3,sE,vS,rS,HfI,XG,vfI,JpI,LpI,kpI,EfI,gfI,yfI,AfI,Vp,HS,j3,WE,xpI,CfI,MpI,JfI,q3,jpI,dc=L(()=>{ZsI();K3();Bn();GE();T3();T3();QfI=function(l,I,G,c,e){if(c==="m")throw new TypeError("Private method is not writable");if(c==="a"&&!e)throw new TypeError("Private accessor was defined without a setter");if(typeof I=="function"?l!==I||!e:!I.has(l))throw new TypeError("Cannot write private member to an object whose class did not declare it");return c==="a"?e.call(l,G):e?e.value=G:I.set(l,G),G},XfI=function(l,I,G,c){if(G==="a"&&!c)throw new TypeError("Private accessor was defined without a getter");if(typeof I=="function"?l!==I||!c:!I.has(l))throw new TypeError("Cannot read private member from an object whose class did not declare it");return G==="m"?c:G==="a"?c.call(l):c?c.value:I.get(l)};iS();P3=class l extends Promise{constructor(I,G=BpI){super(c=>{c(null)}),this.responsePromise=I,this.parseResponse=G}_thenUnwrap(I){return new l(this.responsePromise,async G=>UpI(I(await this.parseResponse(G),G),G.response))}asResponse(){return this.responsePromise.then(I=>I.response)}async withResponse(){let[I,G]=await Promise.all([this.parse(),this.asResponse()]);return{data:I,response:G,request_id:G.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),this.parsedPromise}then(I,G){return this.parse().then(I,G)}catch(I){return this.parse().catch(I)}finally(I){return this.parse().finally(I)}},_3=class{constructor({baseURL:I,maxRetries:G=3,timeout:c=6e5,httpAgent:e,fetch:t}){this.baseURL=I,this.maxRetries=HS("maxRetries",G),this.timeout=HS("timeout",c),this.httpAgent=e,this.fetch=t??Gj}authHeaders(I){return{}}defaultHeaders(I){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...EfI(),...this.authHeaders(I)}}validateHeaders(I,G){}defaultIdempotencyKey(){return`stainless-node-retry-${CfI()}`}get(I,G){return this.methodRequest("get",I,G)}post(I,G){return this.methodRequest("post",I,G)}patch(I,G){return this.methodRequest("patch",I,G)}put(I,G){return this.methodRequest("put",I,G)}delete(I,G){return this.methodRequest("delete",I,G)}methodRequest(I,G,c){return this.request(Promise.resolve(c).then(async e=>{let t=e&&mE(e?.body)?new DataView(await e.body.arrayBuffer()):e?.body instanceof DataView?e.body:e?.body instanceof ArrayBuffer?new DataView(e.body):e&&ArrayBuffer.isView(e?.body)?new DataView(e.body.buffer):e?.body;return{method:I,path:G,...e,body:t}}))}getAPIList(I,G,c){return this.requestAPIList(G,{method:"get",path:I,...c})}calculateContentLength(I){if(typeof I=="string"){if(typeof Buffer<"u")return Buffer.byteLength(I,"utf8").toString();if(typeof TextEncoder<"u")return new TextEncoder().encode(I).length.toString()}else if(ArrayBuffer.isView(I))return I.byteLength.toString();return null}buildRequest(I,{retryCount:G=0}={}){let c={...I},{method:e,path:t,query:a,headers:n={}}=c,Z=ArrayBuffer.isView(c.body)||c.__binaryRequest&&typeof c.body=="string"?c.body:XS(c.body)?c.body.body:c.body?JSON.stringify(c.body,null,2):null,W=this.calculateContentLength(Z),p=this.buildURL(t,a);"timeout"in c&&HS("timeout",c.timeout),c.timeout=c.timeout??this.timeout;let h=c.httpAgent??this.httpAgent??aj(p),o=c.timeout+1e3;typeof h?.options?.timeout=="number"&&o>(h.options.timeout??0)&&(h.options.timeout=o),this.idempotencyHeader&&e!=="get"&&(I.idempotencyKey||(I.idempotencyKey=this.defaultIdempotencyKey()),n[this.idempotencyHeader]=I.idempotencyKey);let Y=this.buildHeaders({options:c,headers:n,contentLength:W,retryCount:G});return{req:{method:e,...Z&&{body:Z},headers:Y,...h&&{agent:h},signal:c.signal??null},url:p,timeout:c.timeout}}buildHeaders({options:I,headers:G,contentLength:c,retryCount:e}){let t={};c&&(t["content-length"]=c);let a=this.defaultHeaders(I);return zpI(t,a),zpI(t,G),XS(I.body)&&R2!=="node"&&delete t["content-type"],q3(a,"x-stainless-retry-count")===void 0&&q3(G,"x-stainless-retry-count")===void 0&&(t["x-stainless-retry-count"]=String(e)),q3(a,"x-stainless-timeout")===void 0&&q3(G,"x-stainless-timeout")===void 0&&I.timeout&&(t["x-stainless-timeout"]=String(Math.trunc(I.timeout/1e3))),this.validateHeaders(t,G),t}async prepareOptions(I){}async prepareRequest(I,{url:G,options:c}){}parseHeaders(I){return I?Symbol.iterator in I?Object.fromEntries(Array.from(I).map(G=>[...G])):{...I}:{}}makeStatusError(I,G,c,e){return Na.generate(I,G,c,e)}request(I,G=null){return new P3(this.makeRequest(I,G))}async makeRequest(I,G){let c=await I,e=c.maxRetries??this.maxRetries;G==null&&(G=e),await this.prepareOptions(c);let{req:t,url:a,timeout:n}=this.buildRequest(c,{retryCount:e-G});if(await this.prepareRequest(t,{url:a,options:c}),Yp("request",a,c,t.headers),c.signal?.aborted)throw new Tt;let Z=new AbortController,W=await this.fetchWithTimeout(a,t,n,Z).catch(j3);if(W instanceof Error){if(c.signal?.aborted)throw new Tt;if(G)return this.retryRequest(c,G);throw W.name==="AbortError"?new To:new Ko({cause:W})}let p=rS(W.headers);if(!W.ok){if(G&&this.shouldRetry(W)){let X=`retrying, ${G} attempts remaining`;return Yp(`response (error; ${X})`,W.status,a,p),this.retryRequest(c,G,p)}let h=await W.text().catch(X=>j3(X).message),o=gfI(h),Y=o?void 0:h;throw Yp(`response (error; ${G?"(error; no more retries left)":"(error; not retryable)"})`,W.status,a,p,Y),this.makeStatusError(W.status,o,Y,p)}return{response:W,options:c,controller:Z}}requestAPIList(I,G){let c=this.makeRequest(G,null);return new vS(this,c,I)}buildURL(I,G){let c=AfI(I)?new URL(I):new URL(this.baseURL+(this.baseURL.endsWith("/")&&I.startsWith("/")?I.slice(1):I)),e=this.defaultQuery();return fpI(e)||(G={...e,...G}),typeof G=="object"&&G&&!Array.isArray(G)&&(c.search=this.stringifyQuery(G)),c.toString()}stringifyQuery(I){return Object.entries(I).filter(([G,c])=>typeof c<"u").map(([G,c])=>{if(typeof c=="string"||typeof c=="number"||typeof c=="boolean")return`${encodeURIComponent(G)}=${encodeURIComponent(c)}`;if(c===null)return`${encodeURIComponent(G)}=`;throw new zl(`Cannot stringify type ${typeof c}; 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(I,G,c,e){let{signal:t,...a}=G||{};t&&t.addEventListener("abort",()=>e.abort());let n=setTimeout(()=>e.abort(),c),Z={signal:e.signal,...a};return Z.method&&(Z.method=Z.method.toUpperCase()),this.fetch.call(void 0,I,Z).finally(()=>{clearTimeout(n)})}shouldRetry(I){let G=I.headers.get("x-should-retry");return G==="true"?!0:G==="false"?!1:I.status===408||I.status===409||I.status===429||I.status>=500}async retryRequest(I,G,c){let e,t=c?.["retry-after-ms"];if(t){let n=parseFloat(t);Number.isNaN(n)||(e=n)}let a=c?.["retry-after"];if(a&&!e){let n=parseFloat(a);Number.isNaN(n)?e=Date.parse(a)-Date.now():e=n*1e3}if(!(e&&0<=e&&e<60*1e3)){let n=I.maxRetries??this.maxRetries;e=this.calculateDefaultRetryTimeoutMillis(G,n)}return await Vp(e),this.makeRequest(I,G-1)}calculateDefaultRetryTimeoutMillis(I,G){let t=G-I,a=Math.min(.5*Math.pow(2,t),8),n=1-Math.random()*.25;return a*n*1e3}getUserAgent(){return`${this.constructor.name}/JS ${r2}`}},sE=class{constructor(I,G,c,e){D3.set(this,void 0),QfI(this,D3,I,"f"),this.options=e,this.response=G,this.body=c}hasNextPage(){return this.getPaginatedItems().length?this.nextPageInfo()!=null:!1}async getNextPage(){let I=this.nextPageInfo();if(!I)throw new zl("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");let G={...this.options};if("params"in I&&typeof G.query=="object")G.query={...G.query,...I.params};else if("url"in I){let c=[...Object.entries(G.query||{}),...I.url.searchParams.entries()];for(let[e,t]of c)I.url.searchParams.set(e,t);G.query=void 0,G.path=I.url.toString()}return await XfI(this,D3,"f").requestAPIList(this.constructor,G)}async*iterPages(){let I=this;for(yield I;I.hasNextPage();)I=await I.getNextPage(),yield I}async*[(D3=new WeakMap,Symbol.asyncIterator)](){for await(let I of this.iterPages())for(let G of I.getPaginatedItems())yield G}},vS=class extends P3{constructor(I,G,c){super(G,async e=>new c(I,e.response,await BpI(e),e.options))}async*[Symbol.asyncIterator](){let I=await this;for await(let G of I)yield G}},rS=l=>new Proxy(Object.fromEntries(l.entries()),{get(I,G){let c=G.toString();return I[c.toLowerCase()]||I[c]}}),HfI={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__metadata:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},XG=l=>typeof l=="object"&&l!==null&&!fpI(l)&&Object.keys(l).every(I=>OpI(HfI,I)),vfI=()=>{if(typeof Deno<"u"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":r2,"X-Stainless-OS":LpI(Deno.build.os),"X-Stainless-Arch":JpI(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":r2,"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<"u"?process:0)==="[object process]")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":r2,"X-Stainless-OS":LpI(process.platform),"X-Stainless-Arch":JpI(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};let l=wfI();return l?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":r2,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${l.browser}`,"X-Stainless-Runtime-Version":l.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":r2,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};JpI=l=>l==="x32"?"x32":l==="x86_64"||l==="x64"?"x64":l==="arm"?"arm":l==="aarch64"||l==="arm64"?"arm64":l?`other:${l}`:"unknown",LpI=l=>(l=l.toLowerCase(),l.includes("ios")?"iOS":l==="android"?"Android":l==="darwin"?"MacOS":l==="win32"?"Windows":l==="freebsd"?"FreeBSD":l==="openbsd"?"OpenBSD":l==="linux"?"Linux":l?`Other:${l}`:"Unknown"),EfI=()=>kpI??(kpI=vfI()),gfI=l=>{try{return JSON.parse(l)}catch{return}},yfI=/^[a-z][a-z0-9+.-]*:/i,AfI=l=>yfI.test(l),Vp=l=>new Promise(I=>setTimeout(I,l)),HS=(l,I)=>{if(typeof I!="number"||!Number.isInteger(I))throw new zl(`${l} must be an integer`);if(I<0)throw new zl(`${l} must be a positive integer`);return I},j3=l=>{if(l instanceof Error)return l;if(typeof l=="object"&&l!==null)try{return new Error(JSON.stringify(l))}catch{}return new Error(l)},WE=l=>{if(typeof process<"u")return process.env?.[l]?.trim()??void 0;if(typeof Deno<"u")return Deno.env?.get?.(l)?.trim()};xpI=new Set(["authorization","api-key"]);CfI=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,l=>{let I=Math.random()*16|0;return(l==="x"?I:I&3|8).toString(16)}),MpI=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u",JfI=l=>typeof l?.get=="function",q3=(l,I)=>{let G=I.toLowerCase();if(JfI(l)){let c=I[0]?.toUpperCase()+I.substring(1).replace(/([^\w])(\w)/g,(e,t,a)=>t+a.toUpperCase());for(let e of[I,G,I.toUpperCase(),c]){let t=l.get(e);if(t)return t}}for(let[c,e]of Object.entries(l))if(c.toLowerCase()===G)return Array.isArray(e)?(e.length<=1||console.warn(`Received ${e.length} entries for the ${I} header, using the first entry.`),e[0]):e},jpI=l=>{if(typeof Buffer<"u"){let I=Buffer.from(l,"base64");return Array.from(new Float32Array(I.buffer,I.byteOffset,I.length/Float32Array.BYTES_PER_ELEMENT))}else{let I=atob(l),G=I.length,c=new Uint8Array(G);for(let e=0;e<G;e++)c[e]=I.charCodeAt(e);return Array.from(new Float32Array(c.buffer))}}});var wW,lc,Dt=L(()=>{dc();wW=class extends sE{constructor(I,G,c,e){super(I,G,c,e),this.data=c.data||[],this.object=c.object}getPaginatedItems(){return this.data??[]}nextPageParams(){return null}nextPageInfo(){return null}},lc=class extends sE{constructor(I,G,c,e){super(I,G,c,e),this.data=c.data||[],this.has_more=c.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageParams(){let I=this.nextPageInfo();if(!I)return null;if("params"in I)return I.params;let G=Object.fromEntries(I.url.searchParams);return Object.keys(G).length?G:null}nextPageInfo(){let I=this.getPaginatedItems();if(!I.length)return null;let G=I[I.length-1]?.id;return G?{params:{after:G}}:null}}});var cl,aG=L(()=>{cl=class{constructor(I){this._client=I}}});var MF,wS=L(()=>{aG();dc();pE();MF=class extends cl{list(I,G={},c){return XG(G)?this.list(I,{},G):this._client.getAPIList(`/chat/completions/${I}/messages`,$3,{query:G,...c})}}});var Do,qo,$3,pE=L(()=>{aG();dc();wS();wS();Dt();Do=class extends cl{constructor(){super(...arguments),this.messages=new MF(this._client)}create(I,G){return this._client.post("/chat/completions",{body:I,...G,stream:I.stream??!1})}retrieve(I,G){return this._client.get(`/chat/completions/${I}`,G)}update(I,G,c){return this._client.post(`/chat/completions/${I}`,{body:G,...c})}list(I={},G){return XG(I)?this.list({},I):this._client.getAPIList("/chat/completions",qo,{query:I,...G})}del(I,G){return this._client.delete(`/chat/completions/${I}`,G)}},qo=class extends lc{},$3=class extends lc{};Do.ChatCompletionsPage=qo;Do.Messages=MF});var Rp,ES=L(()=>{aG();pE();pE();Rp=class extends cl{constructor(){super(...arguments),this.completions=new Do(this._client)}};Rp.Completions=Do;Rp.ChatCompletionsPage=qo});var SpI=L(()=>{ES()});var KpI=L(()=>{});var jF,gS=L(()=>{aG();jF=class extends cl{create(I,G){return this._client.post("/audio/speech",{body:I,...G,headers:{Accept:"application/octet-stream",...G?.headers},__binaryResponse:!0})}}});var SF,yS=L(()=>{aG();dc();SF=class extends cl{create(I,G){return this._client.post("/audio/transcriptions",Ob({body:I,...G,stream:I.stream??!1,__metadata:{model:I.model}}))}}});var KF,AS=L(()=>{aG();dc();KF=class extends cl{create(I,G){return this._client.post("/audio/translations",Ob({body:I,...G,__metadata:{model:I.model}}))}}});var EW,CS=L(()=>{aG();gS();gS();yS();yS();AS();AS();EW=class extends cl{constructor(){super(...arguments),this.transcriptions=new SF(this._client),this.translations=new KF(this._client),this.speech=new jF(this._client)}};EW.Transcriptions=SF;EW.Translations=KF;EW.Speech=jF});var Po,B2,JS=L(()=>{aG();dc();Dt();Po=class extends cl{create(I,G){return this._client.post("/batches",{body:I,...G})}retrieve(I,G){return this._client.get(`/batches/${I}`,G)}list(I={},G){return XG(I)?this.list({},I):this._client.getAPIList("/batches",B2,{query:I,...G})}cancel(I,G){return this._client.post(`/batches/${I}/cancel`,G)}},B2=class extends lc{};Po.BatchesPage=B2});var as,dt,LS,IL,lL,hE,oE,GL,uE,Fp,iE,cL,eL,TF,TpI,_o,tL=L(()=>{Bn();as=function(l,I,G,c,e){if(c==="m")throw new TypeError("Private method is not writable");if(c==="a"&&!e)throw new TypeError("Private accessor was defined without a setter");if(typeof I=="function"?l!==I||!e:!I.has(l))throw new TypeError("Cannot write private member to an object whose class did not declare it");return c==="a"?e.call(l,G):e?e.value=G:I.set(l,G),G},dt=function(l,I,G,c){if(G==="a"&&!c)throw new TypeError("Private accessor was defined without a getter");if(typeof I=="function"?l!==I||!c:!I.has(l))throw new TypeError("Cannot read private member from an object whose class did not declare it");return G==="m"?c:G==="a"?c.call(l):c?c.value:I.get(l)},_o=class{constructor(){LS.add(this),this.controller=new AbortController,IL.set(this,void 0),lL.set(this,()=>{}),hE.set(this,()=>{}),oE.set(this,void 0),GL.set(this,()=>{}),uE.set(this,()=>{}),Fp.set(this,{}),iE.set(this,!1),cL.set(this,!1),eL.set(this,!1),TF.set(this,!1),as(this,IL,new Promise((I,G)=>{as(this,lL,I,"f"),as(this,hE,G,"f")}),"f"),as(this,oE,new Promise((I,G)=>{as(this,GL,I,"f"),as(this,uE,G,"f")}),"f"),dt(this,IL,"f").catch(()=>{}),dt(this,oE,"f").catch(()=>{})}_run(I){setTimeout(()=>{I().then(()=>{this._emitFinal(),this._emit("end")},dt(this,LS,"m",TpI).bind(this))},0)}_connected(){this.ended||(dt(this,lL,"f").call(this),this._emit("connect"))}get ended(){return dt(this,iE,"f")}get errored(){return dt(this,cL,"f")}get aborted(){return dt(this,eL,"f")}abort(){this.controller.abort()}on(I,G){return(dt(this,Fp,"f")[I]||(dt(this,Fp,"f")[I]=[])).push({listener:G}),this}off(I,G){let c=dt(this,Fp,"f")[I];if(!c)return this;let e=c.findIndex(t=>t.listener===G);return e>=0&&c.splice(e,1),this}once(I,G){return(dt(this,Fp,"f")[I]||(dt(this,Fp,"f")[I]=[])).push({listener:G,once:!0}),this}emitted(I){return new Promise((G,c)=>{as(this,TF,!0,"f"),I!=="error"&&this.once("error",c),this.once(I,G)})}async done(){as(this,TF,!0,"f"),await dt(this,oE,"f")}_emit(I,...G){if(dt(this,iE,"f"))return;I==="end"&&(as(this,iE,!0,"f"),dt(this,GL,"f").call(this));let c=dt(this,Fp,"f")[I];if(c&&(dt(this,Fp,"f")[I]=c.filter(e=>!e.once),c.forEach(({listener:e})=>e(...G))),I==="abort"){let e=G[0];!dt(this,TF,"f")&&!c?.length&&Promise.reject(e),dt(this,hE,"f").call(this,e),dt(this,uE,"f").call(this,e),this._emit("end");return}if(I==="error"){let e=G[0];!dt(this,TF,"f")&&!c?.length&&Promise.reject(e),dt(this,hE,"f").call(this,e),dt(this,uE,"f").call(this,e),this._emit("end")}}_emitFinal(){}};IL=new WeakMap,lL=new WeakMap,hE=new WeakMap,oE=new WeakMap,GL=new WeakMap,uE=new WeakMap,Fp=new WeakMap,iE=new WeakMap,cL=new WeakMap,eL=new WeakMap,TF=new WeakMap,LS=new WeakSet,TpI=function(I){if(as(this,cL,!0,"f"),I instanceof Error&&I.name==="AbortError"&&(I=new Tt),I instanceof Tt)return as(this,eL,!0,"f"),this._emit("abort",I);if(I instanceof zl)return this._emit("error",I);if(I instanceof Error){let G=new zl(I.message);return G.cause=I,this._emit("error",G)}return this._emit("error",new zl(String(I)))}});var Kl,fn,cd,kS,gW,aL,ds,f2,DF,U2,nL,On,dL,bL,rE,YE,VE,DpI,qpI,PpI,_pI,$pI,IhI,lhI,yW,zS=L(()=>{dc();K3();Bn();tL();Kl=function(l,I,G,c){if(G==="a"&&!c)throw new TypeError("Private accessor was defined without a getter");if(typeof I=="function"?l!==I||!c:!I.has(l))throw new TypeError("Cannot read private member from an object whose class did not declare it");return G==="m"?c:G==="a"?c.call(l):c?c.value:I.get(l)},fn=function(l,I,G,c,e){if(c==="m")throw new TypeError("Private method is not writable");if(c==="a"&&!e)throw new TypeError("Private accessor was defined without a setter");if(typeof I=="function"?l!==I||!e:!I.has(l))throw new TypeError("Cannot write private member to an object whose class did not declare it");return c==="a"?e.call(l,G):e?e.value=G:I.set(l,G),G},yW=class l extends _o{constructor(){super(...arguments),cd.add(this),kS.set(this,[]),gW.set(this,{}),aL.set(this,{}),ds.set(this,void 0),f2.set(this,void 0),DF.set(this,void 0),U2.set(this,void 0),nL.set(this,void 0),On.set(this,void 0),dL.set(this,void 0),bL.set(this,void 0),rE.set(this,void 0)}[(kS=new WeakMap,gW=new WeakMap,aL=new WeakMap,ds=new WeakMap,f2=new WeakMap,DF=new WeakMap,U2=new WeakMap,nL=new WeakMap,On=new WeakMap,dL=new WeakMap,bL=new WeakMap,rE=new WeakMap,cd=new WeakSet,Symbol.asyncIterator)](){let I=[],G=[],c=!1;return this.on("event",e=>{let t=G.shift();t?t.resolve(e):I.push(e)}),this.on("end",()=>{c=!0;for(let e of G)e.resolve(void 0);G.length=0}),this.on("abort",e=>{c=!0;for(let t of G)t.reject(e);G.length=0}),this.on("error",e=>{c=!0;for(let t of G)t.reject(e);G.length=0}),{next:async()=>I.length?{value:I.shift(),done:!1}:c?{value:void 0,done:!0}:new Promise((t,a)=>G.push({resolve:t,reject:a})).then(t=>t?{value:t,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(I){let G=new l;return G._run(()=>G._fromReadableStream(I)),G}async _fromReadableStream(I,G){let c=G?.signal;c&&(c.aborted&&this.controller.abort(),c.addEventListener("abort",()=>this.controller.abort())),this._connected();let e=vW.fromReadableStream(I,this.controller);for await(let t of e)Kl(this,cd,"m",YE).call(this,t);if(e.controller.signal?.aborted)throw new Tt;return this._addRun(Kl(this,cd,"m",VE).call(this))}toReadableStream(){return new vW(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(I,G,c,e,t){let a=new l;return a._run(()=>a._runToolAssistantStream(I,G,c,e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"stream"}})),a}async _createToolAssistantStream(I,G,c,e,t){let a=t?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));let n={...e,stream:!0},Z=await I.submitToolOutputs(G,c,n,{...t,signal:this.controller.signal});this._connected();for await(let W of Z)Kl(this,cd,"m",YE).call(this,W);if(Z.controller.signal?.aborted)throw new Tt;return this._addRun(Kl(this,cd,"m",VE).call(this))}static createThreadAssistantStream(I,G,c){let e=new l;return e._run(()=>e._threadAssistantStream(I,G,{...c,headers:{...c?.headers,"X-Stainless-Helper-Method":"stream"}})),e}static createAssistantStream(I,G,c,e){let t=new l;return t._run(()=>t._runAssistantStream(I,G,c,{...e,headers:{...e?.headers,"X-Stainless-Helper-Method":"stream"}})),t}currentEvent(){return Kl(this,dL,"f")}currentRun(){return Kl(this,bL,"f")}currentMessageSnapshot(){return Kl(this,ds,"f")}currentRunStepSnapshot(){return Kl(this,rE,"f")}async finalRunSteps(){return await this.done(),Object.values(Kl(this,gW,"f"))}async finalMessages(){return await this.done(),Object.values(Kl(this,aL,"f"))}async finalRun(){if(await this.done(),!Kl(this,f2,"f"))throw Error("Final run was not received.");return Kl(this,f2,"f")}async _createThreadAssistantStream(I,G,c){let e=c?.signal;e&&(e.aborted&&this.controller.abort(),e.addEventListener("abort",()=>this.controller.abort()));let t={...G,stream:!0},a=await I.createAndRun(t,{...c,signal:this.controller.signal});this._connected();for await(let n of a)Kl(this,cd,"m",YE).call(this,n);if(a.controller.signal?.aborted)throw new Tt;return this._addRun(Kl(this,cd,"m",VE).call(this))}async _createAssistantStream(I,G,c,e){let t=e?.signal;t&&(t.aborted&&this.controller.abort(),t.addEventListener("abort",()=>this.controller.abort()));let a={...c,stream:!0},n=await I.create(G,a,{...e,signal:this.controller.signal});this._connected();for await(let Z of n)Kl(this,cd,"m",YE).call(this,Z);if(n.controller.signal?.aborted)throw new Tt;return this._addRun(Kl(this,cd,"m",VE).call(this))}static accumulateDelta(I,G){for(let[c,e]of Object.entries(G)){if(!I.hasOwnProperty(c)){I[c]=e;continue}let t=I[c];if(t==null){I[c]=e;continue}if(c==="index"||c==="type"){I[c]=e;continue}if(typeof t=="string"&&typeof e=="string")t+=e;else if(typeof t=="number"&&typeof e=="number")t+=e;else if(NE(t)&&NE(e))t=this.accumulateDelta(t,e);else if(Array.isArray(t)&&Array.isArray(e)){if(t.every(a=>typeof a=="string"||typeof a=="number")){t.push(...e);continue}for(let a of e){if(!NE(a))throw new Error(`Expected array delta entry to be an object but got: ${a}`);let n=a.index;if(n==null)throw console.error(a),new Error("Expected array delta entry to have an `index` property");if(typeof n!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${n}`);let Z=t[n];Z==null?t.push(a):t[n]=this.accumulateDelta(Z,a)}continue}else throw Error(`Unhandled record type: ${c}, deltaValue: ${e}, accValue: ${t}`);I[c]=t}return I}_addRun(I){return I}async _threadAssistantStream(I,G,c){return await this._createThreadAssistantStream(G,I,c)}async _runAssistantStream(I,G,c,e){return await this._createAssistantStream(G,I,c,e)}async _runToolAssistantStream(I,G,c,e,t){return await this._createToolAssistantStream(c,I,G,e,t)}};YE=function(I){if(!this.ended)switch(fn(this,dL,I,"f"),Kl(this,cd,"m",PpI).call(this,I),I.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":Kl(this,cd,"m",lhI).call(this,I);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":Kl(this,cd,"m",qpI).call(this,I);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":Kl(this,cd,"m",DpI).call(this,I);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},VE=function(){if(this.ended)throw new zl("stream has ended, this shouldn't happen");if(!Kl(this,f2,"f"))throw Error("Final run has not been received");return Kl(this,f2,"f")},DpI=function(I){let[G,c]=Kl(this,cd,"m",$pI).call(this,I,Kl(this,ds,"f"));fn(this,ds,G,"f"),Kl(this,aL,"f")[G.id]=G;for(let e of c){let t=G.content[e.index];t?.type=="text"&&this._emit("textCreated",t.text)}switch(I.event){case"thread.message.created":this._emit("messageCreated",I.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",I.data.delta,G),I.data.delta.content)for(let e of I.data.delta.content){if(e.type=="text"&&e.text){let t=e.text,a=G.content[e.index];if(a&&a.type=="text")this._emit("textDelta",t,a.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(e.index!=Kl(this,DF,"f")){if(Kl(this,U2,"f"))switch(Kl(this,U2,"f").type){case"text":this._emit("textDone",Kl(this,U2,"f").text,Kl(this,ds,"f"));break;case"image_file":this._emit("imageFileDone",Kl(this,U2,"f").image_file,Kl(this,ds,"f"));break}fn(this,DF,e.index,"f")}fn(this,U2,G.content[e.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(Kl(this,DF,"f")!==void 0){let e=I.data.content[Kl(this,DF,"f")];if(e)switch(e.type){case"image_file":this._emit("imageFileDone",e.image_file,Kl(this,ds,"f"));break;case"text":this._emit("textDone",e.text,Kl(this,ds,"f"));break}}Kl(this,ds,"f")&&this._emit("messageDone",I.data),fn(this,ds,void 0,"f")}},qpI=function(I){let G=Kl(this,cd,"m",_pI).call(this,I);switch(fn(this,rE,G,"f"),I.event){case"thread.run.step.created":this._emit("runStepCreated",I.data);break;case"thread.run.step.delta":let c=I.data.delta;if(c.step_details&&c.step_details.type=="tool_calls"&&c.step_details.tool_calls&&G.step_details.type=="tool_calls")for(let t of c.step_details.tool_calls)t.index==Kl(this,nL,"f")?this._emit("toolCallDelta",t,G.step_details.tool_calls[t.index]):(Kl(this,On,"f")&&this._emit("toolCallDone",Kl(this,On,"f")),fn(this,nL,t.index,"f"),fn(this,On,G.step_details.tool_calls[t.index],"f"),Kl(this,On,"f")&&this._emit("toolCallCreated",Kl(this,On,"f")));this._emit("runStepDelta",I.data.delta,G);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":fn(this,rE,void 0,"f"),I.data.step_details.type=="tool_calls"&&Kl(this,On,"f")&&(this._emit("toolCallDone",Kl(this,On,"f")),fn(this,On,void 0,"f")),this._emit("runStepDone",I.data,G);break;case"thread.run.step.in_progress":break}},PpI=function(I){Kl(this,kS,"f").push(I),this._emit("event",I)},_pI=function(I){switch(I.event){case"thread.run.step.created":return Kl(this,gW,"f")[I.data.id]=I.data,I.data;case"thread.run.step.delta":let G=Kl(this,gW,"f")[I.data.id];if(!G)throw Error("Received a RunStepDelta before creation of a snapshot");let c=I.data;if(c.delta){let e=yW.accumulateDelta(G,c.delta);Kl(this,gW,"f")[I.data.id]=e}return Kl(this,gW,"f")[I.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":Kl(this,gW,"f")[I.data.id]=I.data;break}if(Kl(this,gW,"f")[I.data.id])return Kl(this,gW,"f")[I.data.id];throw new Error("No snapshot available")},$pI=function(I,G){let c=[];switch(I.event){case"thread.message.created":return[I.data,c];case"thread.message.delta":if(!G)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let e=I.data;if(e.delta.content)for(let t of e.delta.content)if(t.index in G.content){let a=G.content[t.index];G.content[t.index]=Kl(this,cd,"m",IhI).call(this,t,a)}else G.content[t.index]=t,c.push(t);return[G,c];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(G)return[G,c];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},IhI=function(I,G){return yW.accumulateDelta(G,I)},lhI=function(I){switch(fn(this,bL,I.data,"f"),I.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":fn(this,f2,I.data,"f"),Kl(this,On,"f")&&(this._emit("toolCallDone",Kl(this,On,"f")),fn(this,On,void 0,"f"));break;case"thread.run.cancelling":break}}});var O2,qF,xS=L(()=>{aG();dc();Dt();O2=class extends cl{create(I,G){return this._client.post("/assistants",{body:I,...G,headers:{"OpenAI-Beta":"assistants=v2",...G?.headers}})}retrieve(I,G){return this._client.get(`/assistants/${I}`,{...G,headers:{"OpenAI-Beta":"assistants=v2",...G?.headers}})}update(I,G,c){return this._client.post(`/assistants/${I}`,{body:G,...c,headers:{"OpenAI-Beta":"assistants=v2",...c?.headers}})}list(I={},G){return XG(I)?this.list({},I):this._client.getAPIList("/assistants",qF,{query:I,...G,headers:{"OpenAI-Beta":"assistants=v2",...G?.headers}})}del(I,G){return this._client.delete(`/assistants/${I}`,{...G,headers:{"OpenAI-Beta":"assistants=v2",...G?.headers}})}},qF=class extends lc{};O2.AssistantsPage=qF});function BS(l){return typeof l.parse=="function"}var GhI=L(()=>{});var $o,US,fS,OS=L(()=>{$o=l=>l?.role==="assistant",US=l=>l?.role==="function",fS=l=>l?.role==="tool"});function RE(l){return l?.$brand==="auto-parseable-response-format"}function M2(l){return l?.$brand==="auto-parseable-tool"}function chI(l,I){return!I||!MS(I)?{...l,choices:l.choices.map(G=>({...G,message:{...G.message,parsed:null,...G.message.tool_calls?{tool_calls:G.message.tool_calls}:void 0}}))}:FE(l,I)}function FE(l,I){let G=l.choices.map(c=>{if(c.finish_reason==="length")throw new fF;if(c.finish_reason==="content_filter")throw new OF;return{...c,message:{...c.message,...c.message.tool_calls?{tool_calls:c.message.tool_calls?.map(e=>OfI(I,e))??void 0}:void 0,parsed:c.message.content&&!c.message.refusal?ffI(I,c.message.content):null}}});return{...l,choices:G}}function ffI(l,I){return l.response_format?.type!=="json_schema"?null:l.response_format?.type==="json_schema"?"$parseRaw"in l.response_format?l.response_format.$parseRaw(I):JSON.parse(I):null}function OfI(l,I){let G=l.tools?.find(c=>c.function?.name===I.function.name);return{...I,function:{...I.function,parsed_arguments:M2(G)?G.$parseRaw(I.function.arguments):G?.function.strict?JSON.parse(I.function.arguments):null}}}function ehI(l,I){if(!l)return!1;let G=l.tools?.find(c=>c.function?.name===I.function.name);return M2(G)||G?.function.strict||!1}function MS(l){return RE(l.response_format)?!0:l.tools?.some(I=>M2(I)||I.type==="function"&&I.function.strict===!0)??!1}function thI(l){for(let I of l??[]){if(I.type!=="function")throw new zl(`Currently only \`function\` tool types support auto-parsing; Received \`${I.type}\``);if(I.function.strict!==!0)throw new zl(`The \`${I.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var QE=L(()=>{Bn()});var Mb,vd,jS,ZL,SS,KS,TS,dhI,DS,ahI,PF,qS=L(()=>{Bn();GhI();OS();tL();QE();Mb=function(l,I,G,c){if(G==="a"&&!c)throw new TypeError("Private accessor was defined without a getter");if(typeof I=="function"?l!==I||!c:!I.has(l))throw new TypeError("Cannot read private member from an object whose class did not declare it");return G==="m"?c:G==="a"?c.call(l):c?c.value:I.get(l)},ahI=10,PF=class extends _o{constructor(){super(...arguments),vd.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(I){this._chatCompletions.push(I),this._emit("chatCompletion",I);let G=I.choices[0]?.message;return G&&this._addMessage(G),I}_addMessage(I,G=!0){if("content"in I||(I.content=null),this.messages.push(I),G){if(this._emit("message",I),(US(I)||fS(I))&&I.content)this._emit("functionCallResult",I.content);else if($o(I)&&I.function_call)this._emit("functionCall",I.function_call);else if($o(I)&&I.tool_calls)for(let c of I.tool_calls)c.type==="function"&&this._emit("functionCall",c.function)}}async finalChatCompletion(){await this.done();let I=this._chatCompletions[this._chatCompletions.length-1];if(!I)throw new zl("stream ended without producing a ChatCompletion");return I}async finalContent(){return await this.done(),Mb(this,vd,"m",jS).call(this)}async finalMessage(){return await this.done(),Mb(this,vd,"m",ZL).call(this)}async finalFunctionCall(){return await this.done(),Mb(this,vd,"m",SS).call(this)}async finalFunctionCallResult(){return await this.done(),Mb(this,vd,"m",KS).call(this)}async totalUsage(){return await this.done(),Mb(this,vd,"m",TS).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let I=this._chatCompletions[this._chatCompletions.length-1];I&&this._emit("finalChatCompletion",I);let G=Mb(this,vd,"m",ZL).call(this);G&&this._emit("finalMessage",G);let c=Mb(this,vd,"m",jS).call(this);c&&this._emit("finalContent",c);let e=Mb(this,vd,"m",SS).call(this);e&&this._emit("finalFunctionCall",e);let t=Mb(this,vd,"m",KS).call(this);t!=null&&this._emit("finalFunctionCallResult",t),this._chatCompletions.some(a=>a.usage)&&this._emit("totalUsage",Mb(this,vd,"m",TS).call(this))}async _createChatCompletion(I,G,c){let e=c?.signal;e&&(e.aborted&&this.controller.abort(),e.addEventListener("abort",()=>this.controller.abort())),Mb(this,vd,"m",dhI).call(this,G);let t=await I.chat.completions.create({...G,stream:!1},{...c,signal:this.controller.signal});return this._connected(),this._addChatCompletion(FE(t,G))}async _runChatCompletion(I,G,c){for(let e of G.messages)this._addMessage(e,!1);return await this._createChatCompletion(I,G,c)}async _runFunctions(I,G,c){let e="function",{function_call:t="auto",stream:a,...n}=G,Z=typeof t!="string"&&t?.name,{maxChatCompletions:W=ahI}=c||{},p={};for(let o of G.functions)p[o.name||o.function.name]=o;let h=G.functions.map(o=>({name:o.name||o.function.name,parameters:o.parameters,description:o.description}));for(let o of G.messages)this._addMessage(o,!1);for(let o=0;o<W;++o){let F=(await this._createChatCompletion(I,{...n,function_call:t,functions:h,messages:[...this.messages]},c)).choices[0]?.message;if(!F)throw new zl("missing message in ChatCompletion response");if(!F.function_call)return;let{name:R,arguments:X}=F.function_call,v=p[R];if(v){if(Z&&Z!==R){let y=`Invalid function_call: ${JSON.stringify(R)}. ${JSON.stringify(Z)} requested. Please try again`;this._addMessage({role:e,name:R,content:y});continue}}else{let y=`Invalid function_call: ${JSON.stringify(R)}. Available options are: ${h.map(k=>JSON.stringify(k.name)).join(", ")}. Please try again`;this._addMessage({role:e,name:R,content:y});continue}let g;try{g=BS(v)?await v.parse(X):X}catch(y){this._addMessage({role:e,name:R,content:y instanceof Error?y.message:String(y)});continue}let C=await v.function(g,this),A=Mb(this,vd,"m",DS).call(this,C);if(this._addMessage({role:e,name:R,content:A}),Z)return}}async _runTools(I,G,c){let e="tool",{tool_choice:t="auto",stream:a,...n}=G,Z=typeof t!="string"&&t?.function?.name,{maxChatCompletions:W=ahI}=c||{},p=G.tools.map(Y=>{if(M2(Y)){if(!Y.$callback)throw new zl("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:Y.$callback,name:Y.function.name,description:Y.function.description||"",parameters:Y.function.parameters,parse:Y.$parseRaw,strict:!0}}}return Y}),h={};for(let Y of p)Y.type==="function"&&(h[Y.function.name||Y.function.function.name]=Y.function);let o="tools"in G?p.map(Y=>Y.type==="function"?{type:"function",function:{name:Y.function.name||Y.function.function.name,parameters:Y.function.parameters,description:Y.function.description,strict:Y.function.strict}}:Y):void 0;for(let Y of G.messages)this._addMessage(Y,!1);for(let Y=0;Y<W;++Y){let R=(await this._createChatCompletion(I,{...n,tool_choice:t,tools:o,messages:[...this.messages]},c)).choices[0]?.message;if(!R)throw new zl("missing message in ChatCompletion response");if(!R.tool_calls?.length)return;for(let X of R.tool_calls){if(X.type!=="function")continue;let v=X.id,{name:g,arguments:C}=X.function,A=h[g];if(A){if(Z&&Z!==g){let U=`Invalid tool_call: ${JSON.stringify(g)}. ${JSON.stringify(Z)} requested. Please try again`;this._addMessage({role:e,tool_call_id:v,content:U});continue}}else{let U=`Invalid tool_call: ${JSON.stringify(g)}. Available options are: ${Object.keys(h).map(z=>JSON.stringify(z)).join(", ")}. Please try again`;this._addMessage({role:e,tool_call_id:v,content:U});continue}let y;try{y=BS(A)?await A.parse(C):C}catch(U){let z=U instanceof Error?U.message:String(U);this._addMessage({role:e,tool_call_id:v,content:z});continue}let k=await A.function(y,this),S=Mb(this,vd,"m",DS).call(this,k);if(this._addMessage({role:e,tool_call_id:v,content:S}),Z)return}}}};vd=new WeakSet,jS=function(){return Mb(this,vd,"m",ZL).call(this).content??null},ZL=function(){let I=this.messages.length;for(;I-- >0;){let G=this.messages[I];if($o(G)){let{function_call:c,...e}=G,t={...e,content:G.content??null,refusal:G.refusal??null};return c&&(t.function_call=c),t}}throw new zl("stream ended without producing a ChatCompletionMessage with role=assistant")},SS=function(){for(let I=this.messages.length-1;I>=0;I--){let G=this.messages[I];if($o(G)&&G?.function_call)return G.function_call;if($o(G)&&G?.tool_calls?.length)return G.tool_calls.at(-1)?.function}},KS=function(){for(let I=this.messages.length-1;I>=0;I--){let G=this.messages[I];if(US(G)&&G.content!=null||fS(G)&&G.content!=null&&typeof G.content=="string"&&this.messages.some(c=>c.role==="assistant"&&c.tool_calls?.some(e=>e.type==="function"&&e.id===G.tool_call_id)))return G.content}},TS=function(){let I={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:G}of this._chatCompletions)G&&(I.completion_tokens+=G.completion_tokens,I.prompt_tokens+=G.prompt_tokens,I.total_tokens+=G.total_tokens);return I},dhI=function(I){if(I.n!=null&&I.n>1)throw new zl("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},DS=function(I){return typeof I=="string"?I:I===void 0?"undefined":JSON.stringify(I)}});var XE,bhI=L(()=>{qS();OS();XE=class l extends PF{static runFunctions(I,G,c){let e=new l,t={...c,headers:{...c?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return e._run(()=>e._runFunctions(I,G,t)),e}static runTools(I,G,c){let e=new l,t={...c,headers:{...c?.headers,"X-Stainless-Helper-Method":"runTools"}};return e._run(()=>e._runTools(I,G,t)),e}_addMessage(I,G=!0){super._addMessage(I,G),$o(I)&&I.content&&this._emit("content",I.content)}}});function MfI(l,I=ka.ALL){if(typeof l!="string")throw new TypeError(`expecting str, got ${typeof l}`);if(!l.trim())throw new Error(`${l} is empty`);return jfI(l.trim(),I)}var ka,PS,_S,jfI,$S,nhI=L(()=>{ka={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},PS=class extends Error{},_S=class extends Error{};jfI=(l,I)=>{let G=l.length,c=0,e=o=>{throw new PS(`${o} at position ${c}`)},t=o=>{throw new _S(`${o} at position ${c}`)},a=()=>(h(),c>=G&&e("Unexpected end of input"),l[c]==='"'?n():l[c]==="{"?Z():l[c]==="["?W():l.substring(c,c+4)==="null"||ka.NULL&I&&G-c<4&&"null".startsWith(l.substring(c))?(c+=4,null):l.substring(c,c+4)==="true"||ka.BOOL&I&&G-c<4&&"true".startsWith(l.substring(c))?(c+=4,!0):l.substring(c,c+5)==="false"||ka.BOOL&I&&G-c<5&&"false".startsWith(l.substring(c))?(c+=5,!1):l.substring(c,c+8)==="Infinity"||ka.INFINITY&I&&G-c<8&&"Infinity".startsWith(l.substring(c))?(c+=8,1/0):l.substring(c,c+9)==="-Infinity"||ka.MINUS_INFINITY&I&&1<G-c&&G-c<9&&"-Infinity".startsWith(l.substring(c))?(c+=9,-1/0):l.substring(c,c+3)==="NaN"||ka.NAN&I&&G-c<3&&"NaN".startsWith(l.substring(c))?(c+=3,NaN):p()),n=()=>{let o=c,Y=!1;for(c++;c<G&&(l[c]!=='"'||Y&&l[c-1]==="\\");)Y=l[c]==="\\"?!Y:!1,c++;if(l.charAt(c)=='"')try{return JSON.parse(l.substring(o,++c-Number(Y)))}catch(F){t(String(F))}else if(ka.STR&I)try{return JSON.parse(l.substring(o,c-Number(Y))+'"')}catch{return JSON.parse(l.substring(o,l.lastIndexOf("\\"))+'"')}e("Unterminated string literal")},Z=()=>{c++,h();let o={};try{for(;l[c]!=="}";){if(h(),c>=G&&ka.OBJ&I)return o;let Y=n();h(),c++;try{let F=a();Object.defineProperty(o,Y,{value:F,writable:!0,enumerable:!0,configurable:!0})}catch(F){if(ka.OBJ&I)return o;throw F}h(),l[c]===","&&c++}}catch{if(ka.OBJ&I)return o;e("Expected '}' at end of object")}return c++,o},W=()=>{c++;let o=[];try{for(;l[c]!=="]";)o.push(a()),h(),l[c]===","&&c++}catch{if(ka.ARR&I)return o;e("Expected ']' at end of array")}return c++,o},p=()=>{if(c===0){l==="-"&&ka.NUM&I&&e("Not sure what '-' is");try{return JSON.parse(l)}catch(Y){if(ka.NUM&I)try{return l[l.length-1]==="."?JSON.parse(l.substring(0,l.lastIndexOf("."))):JSON.parse(l.substring(0,l.lastIndexOf("e")))}catch{}t(String(Y))}}let o=c;for(l[c]==="-"&&c++;l[c]&&!",]}".includes(l[c]);)c++;c==G&&!(ka.NUM&I)&&e("Unterminated number literal");try{return JSON.parse(l.substring(o,c))}catch{l.substring(o,c)==="-"&&ka.NUM&I&&e("Not sure what '-' is");try{return JSON.parse(l.substring(o,l.lastIndexOf("e")))}catch(F){t(String(F))}}},h=()=>{for(;c<G&&`
320
320
  \r `.includes(l[c]);)c++};return a()},$S=l=>MfI(l,ka.ALL^ka.NUM)});function SfI(l,I){let{id:G,choices:c,created:e,model:t,system_fingerprint:a,...n}=l,Z={...n,id:G,choices:c.map(({message:W,finish_reason:p,index:h,logprobs:o,...Y})=>{if(!p)throw new zl(`missing finish_reason for choice ${h}`);let{content:F=null,function_call:R,tool_calls:X,...v}=W,g=W.role;if(!g)throw new zl(`missing role for choice ${h}`);if(R){let{arguments:C,name:A}=R;if(C==null)throw new zl(`missing function_call.arguments for choice ${h}`);if(!A)throw new zl(`missing function_call.name for choice ${h}`);return{...Y,message:{content:F,function_call:{arguments:C,name:A},role:g,refusal:W.refusal??null},finish_reason:p,index:h,logprobs:o}}return X?{...Y,index:h,finish_reason:p,logprobs:o,message:{...v,role:g,content:F,refusal:W.refusal??null,tool_calls:X.map((C,A)=>{let{function:y,type:k,id:S,...U}=C,{arguments:z,name:T,...j}=y||{};if(S==null)throw new zl(`missing choices[${h}].tool_calls[${A}].id
321
321
  ${WL(l)}`);if(k==null)throw new zl(`missing choices[${h}].tool_calls[${A}].type
322
322
  ${WL(l)}`);if(T==null)throw new zl(`missing choices[${h}].tool_calls[${A}].function.name
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "aegiscode",
3
- "version": "4.0.4",
3
+ "version": "4.0.5",
4
4
  "description": "AEGIS CLI — AI-powered coding assistant",
5
5
  "type": "module",
6
6
  "bin": {