@whoz-oss/coday-server 0.63.0 → 0.63.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/server.js +2 -2
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@whoz-oss/coday-server",
3
- "version": "0.63.0",
3
+ "version": "0.63.2",
4
4
  "repository": "https://github.com/whoz-oss/coday",
5
5
  "type": "module",
6
6
  "main": "server/server.js",
package/server.js CHANGED
@@ -673,7 +673,7 @@ stderr: ${b5(u.stderr,c)}`:"",d=`An error occurred while executing the command:
673
673
  `)}</messages>
674
674
 
675
675
  Generate a short title for this conversation between <conversation-name></conversation-name> tags, and without introduction nor line jumps.
676
- `;try{let i=await e.getAiClient().complete(n,{maxTokens:300,temperature:1}),a=i.match(/<conversation-name>([\s\S]*?)<\/conversation-name>/);return a&&a[1]?a[1].trim().replace(/^["']|["']$/g,"").replace(/\.$/,"").trim():i.trim()||`Thread ${new Date().toISOString().split("T")[0]}`}catch(i){return console.error("Error generating thread name:",i),`Thread ${new Date().toISOString().split("T")[0]}`}}function nt(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t}function se(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)}var OF=function(){let{crypto:r}=globalThis;if(r?.randomUUID)return OF=r.randomUUID.bind(r),r.randomUUID();let e=new Uint8Array(1),t=r?()=>r.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^t()&15>>+n/4).toString(16))};function K5(r){return typeof r=="object"&&r!==null&&("name"in r&&r.name==="AbortError"||"message"in r&&String(r.message).includes("FetchRequestCanceledException"))}var Y5=r=>{if(r instanceof Error)return r;if(typeof r=="object"&&r!==null){try{if(Object.prototype.toString.call(r)==="[object Error]"){let e=new Error(r.message,r.cause?{cause:r.cause}:{});return r.stack&&(e.stack=r.stack),r.cause&&!e.cause&&(e.cause=r.cause),r.name&&(e.name=r.name),e}}catch{}try{return new Error(JSON.stringify(r))}catch{}}return new Error(r)};var ze=class extends Error{},Kn=class r extends ze{constructor(e,t,n,i){super(`${r.makeMessage(e,t,n)}`),this.status=e,this.headers=i,this.requestID=i?.get("x-request-id"),this.error=t;let a=t;this.code=a?.code,this.param=a?.param,this.type=a?.type}static makeMessage(e,t,n){let i=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&i?`${e} ${i}`:e?`${e} status code (no body)`:i||"(no status code or body)"}static generate(e,t,n,i){if(!e||!i)return new l2({message:n,cause:Y5(t)});let a=t?.error;return e===400?new ah(e,a,n,i):e===401?new oh(e,a,n,i):e===403?new sh(e,a,n,i):e===404?new ch(e,a,n,i):e===409?new uh(e,a,n,i):e===422?new lh(e,a,n,i):e===429?new fh(e,a,n,i):e>=500?new ph(e,a,n,i):new r(e,a,n,i)}},Bn=class extends Kn{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},l2=class extends Kn{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},f2=class extends l2{constructor({message:e}={}){super({message:e??"Request timed out."})}},ah=class extends Kn{},oh=class extends Kn{},sh=class extends Kn{},ch=class extends Kn{},uh=class extends Kn{},lh=class extends Kn{},fh=class extends Kn{},ph=class extends Kn{},dh=class extends ze{constructor(){super("Could not parse response content as the length limit was reached")}},hh=class extends ze{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},gc=class extends Error{constructor(e){super(e)}};var _tt=/^[a-z][a-z0-9+.-]*:/i,Kue=r=>_tt.test(r),Ji=r=>(Ji=Array.isArray,Ji(r)),IF=Ji;function $F(r){return typeof r!="object"?{}:r??{}}function Yue(r){if(!r)return!0;for(let e in r)return!1;return!0}function Xue(r,e){return Object.prototype.hasOwnProperty.call(r,e)}function X5(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}var Que=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new ze(`${r} must be an integer`);if(e<0)throw new ze(`${r} must be a positive integer`);return e};var ele=r=>{try{return JSON.parse(r)}catch{return}};var vc=r=>new Promise(e=>setTimeout(e,r));var p2="6.10.0";var ile=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Stt(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var ktt=()=>{let r=Stt();if(r==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":p2,"X-Stainless-OS":rle(Deno.build.os),"X-Stainless-Arch":tle(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":p2,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(r==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":p2,"X-Stainless-OS":rle(globalThis.process.platform??"unknown"),"X-Stainless-Arch":tle(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Ett();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":p2,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":p2,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Ett(){if(typeof navigator>"u"||!navigator)return null;let r=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:t}of r){let n=t.exec(navigator.userAgent);if(n){let i=n[1]||0,a=n[2]||0,o=n[3]||0;return{browser:e,version:`${i}.${a}.${o}`}}}return null}var tle=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",rle=r=>(r=r.toLowerCase(),r.includes("ios")?"iOS":r==="android"?"Android":r==="darwin"?"MacOS":r==="win32"?"Windows":r==="freebsd"?"FreeBSD":r==="openbsd"?"OpenBSD":r==="linux"?"Linux":r?`Other:${r}`:"Unknown"),nle,ale=()=>nle??(nle=ktt());function ole(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function RF(...r){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...r)}function i_(r){let e=Symbol.asyncIterator in r?r[Symbol.asyncIterator]():r[Symbol.iterator]();return RF({start(){},async pull(t){let{done:n,value:i}=await e.next();n?t.close():t.enqueue(i)},async cancel(){await e.return?.()}})}function jF(r){if(r[Symbol.asyncIterator])return r;let e=r.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function sle(r){if(r===null||typeof r!="object")return;if(r[Symbol.asyncIterator]){await r[Symbol.asyncIterator]().return?.();return}let e=r.getReader(),t=e.cancel();e.releaseLock(),await t}var cle=({headers:r,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var a_="RFC3986",FF=r=>String(r),o_={RFC1738:r=>String(r).replace(/%20/g,"+"),RFC3986:FF},NF="RFC1738";var s_=(r,e)=>(s_=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),s_(r,e)),bc=(()=>{let r=[];for(let e=0;e<256;++e)r.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return r})();var MF=1024,ule=(r,e,t,n,i)=>{if(r.length===0)return r;let a=r;if(typeof r=="symbol"?a=Symbol.prototype.toString.call(r):typeof r!="string"&&(a=String(r)),t==="iso-8859-1")return escape(a).replace(/%u[0-9a-f]{4}/gi,function(s){return"%26%23"+parseInt(s.slice(2),16)+"%3B"});let o="";for(let s=0;s<a.length;s+=MF){let c=a.length>=MF?a.slice(s,s+MF):a,u=[];for(let l=0;l<c.length;++l){let f=c.charCodeAt(l);if(f===45||f===46||f===95||f===126||f>=48&&f<=57||f>=65&&f<=90||f>=97&&f<=122||i===NF&&(f===40||f===41)){u[u.length]=c.charAt(l);continue}if(f<128){u[u.length]=bc[f];continue}if(f<2048){u[u.length]=bc[192|f>>6]+bc[128|f&63];continue}if(f<55296||f>=57344){u[u.length]=bc[224|f>>12]+bc[128|f>>6&63]+bc[128|f&63];continue}l+=1,f=65536+((f&1023)<<10|c.charCodeAt(l)&1023),u[u.length]=bc[240|f>>18]+bc[128|f>>12&63]+bc[128|f>>6&63]+bc[128|f&63]}o+=u.join("")}return o};function lle(r){return!r||typeof r!="object"?!1:!!(r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer(r))}function LF(r,e){if(Ji(r)){let t=[];for(let n=0;n<r.length;n+=1)t.push(e(r[n]));return t}return e(r)}var ple={brackets(r){return String(r)+"[]"},comma:"comma",indices(r,e){return String(r)+"["+e+"]"},repeat(r){return String(r)}},dle=function(r,e){Array.prototype.push.apply(r,Ji(e)?e:[e])},fle,Yn={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:ule,encodeValuesOnly:!1,format:a_,formatter:FF,indices:!1,serializeDate(r){return(fle??(fle=Function.prototype.call.bind(Date.prototype.toISOString)))(r)},skipNulls:!1,strictNullHandling:!1};function Ttt(r){return typeof r=="string"||typeof r=="number"||typeof r=="boolean"||typeof r=="symbol"||typeof r=="bigint"}var qF={};function hle(r,e,t,n,i,a,o,s,c,u,l,f,d,p,m,h,g,v){let b=r,x=v,A=0,k=!1;for(;(x=x.get(qF))!==void 0&&!k;){let _=x.get(r);if(A+=1,typeof _<"u"){if(_===A)throw new RangeError("Cyclic object value");k=!0}typeof x.get(qF)>"u"&&(A=0)}if(typeof u=="function"?b=u(e,b):b instanceof Date?b=d?.(b):t==="comma"&&Ji(b)&&(b=LF(b,function(_){return _ instanceof Date?d?.(_):_})),b===null){if(a)return c&&!h?c(e,Yn.encoder,g,"key",p):e;b=""}if(Ttt(b)||lle(b)){if(c){let _=h?e:c(e,Yn.encoder,g,"key",p);return[m?.(_)+"="+m?.(c(b,Yn.encoder,g,"value",p))]}return[m?.(e)+"="+m?.(String(b))]}let E=[];if(typeof b>"u")return E;let R;if(t==="comma"&&Ji(b))h&&c&&(b=LF(b,c)),R=[{value:b.length>0?b.join(",")||null:void 0}];else if(Ji(u))R=u;else{let _=Object.keys(b);R=l?_.sort(l):_}let I=s?String(e).replace(/\./g,"%2E"):String(e),w=n&&Ji(b)&&b.length===1?I+"[]":I;if(i&&Ji(b)&&b.length===0)return w+"[]";for(let _=0;_<R.length;++_){let y=R[_],T=typeof y=="object"&&typeof y.value<"u"?y.value:b[y];if(o&&T===null)continue;let P=f&&s?y.replace(/\./g,"%2E"):y,C=Ji(b)?typeof t=="function"?t(w,P):w:w+(f?"."+P:"["+P+"]");v.set(r,A);let D=new WeakMap;D.set(qF,v),dle(E,hle(T,C,t,n,i,a,o,s,t==="comma"&&h&&Ji(b)?null:c,u,l,f,d,p,m,h,g,D))}return E}function Dtt(r=Yn){if(typeof r.allowEmptyArrays<"u"&&typeof r.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof r.encodeDotInKeys<"u"&&typeof r.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(r.encoder!==null&&typeof r.encoder<"u"&&typeof r.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=r.charset||Yn.charset;if(typeof r.charset<"u"&&r.charset!=="utf-8"&&r.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=a_;if(typeof r.format<"u"){if(!s_(o_,r.format))throw new TypeError("Unknown format option provided.");t=r.format}let n=o_[t],i=Yn.filter;(typeof r.filter=="function"||Ji(r.filter))&&(i=r.filter);let a;if(r.arrayFormat&&r.arrayFormat in ple?a=r.arrayFormat:"indices"in r?a=r.indices?"indices":"repeat":a=Yn.arrayFormat,"commaRoundTrip"in r&&typeof r.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let o=typeof r.allowDots>"u"?r.encodeDotInKeys?!0:Yn.allowDots:!!r.allowDots;return{addQueryPrefix:typeof r.addQueryPrefix=="boolean"?r.addQueryPrefix:Yn.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof r.allowEmptyArrays=="boolean"?!!r.allowEmptyArrays:Yn.allowEmptyArrays,arrayFormat:a,charset:e,charsetSentinel:typeof r.charsetSentinel=="boolean"?r.charsetSentinel:Yn.charsetSentinel,commaRoundTrip:!!r.commaRoundTrip,delimiter:typeof r.delimiter>"u"?Yn.delimiter:r.delimiter,encode:typeof r.encode=="boolean"?r.encode:Yn.encode,encodeDotInKeys:typeof r.encodeDotInKeys=="boolean"?r.encodeDotInKeys:Yn.encodeDotInKeys,encoder:typeof r.encoder=="function"?r.encoder:Yn.encoder,encodeValuesOnly:typeof r.encodeValuesOnly=="boolean"?r.encodeValuesOnly:Yn.encodeValuesOnly,filter:i,format:t,formatter:n,serializeDate:typeof r.serializeDate=="function"?r.serializeDate:Yn.serializeDate,skipNulls:typeof r.skipNulls=="boolean"?r.skipNulls:Yn.skipNulls,sort:typeof r.sort=="function"?r.sort:null,strictNullHandling:typeof r.strictNullHandling=="boolean"?r.strictNullHandling:Yn.strictNullHandling}}function zF(r,e={}){let t=r,n=Dtt(e),i,a;typeof n.filter=="function"?(a=n.filter,t=a("",t)):Ji(n.filter)&&(a=n.filter,i=a);let o=[];if(typeof t!="object"||t===null)return"";let s=ple[n.arrayFormat],c=s==="comma"&&n.commaRoundTrip;i||(i=Object.keys(t)),n.sort&&i.sort(n.sort);let u=new WeakMap;for(let d=0;d<i.length;++d){let p=i[d];n.skipNulls&&t[p]===null||dle(o,hle(t[p],p,s,c,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,u))}let l=o.join(n.delimiter),f=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?f+="utf8=%26%2310003%3B&":f+="utf8=%E2%9C%93&"),l.length>0?f+l:""}function vle(r){let e=0;for(let i of r)e+=i.length;let t=new Uint8Array(e),n=0;for(let i of r)t.set(i,n),n+=i.length;return t}var mle;function mh(r){let e;return(mle??(e=new globalThis.TextEncoder,mle=e.encode.bind(e)))(r)}var gle;function UF(r){let e;return(gle??(e=new globalThis.TextDecoder,gle=e.decode.bind(e)))(r)}var lo,fo,cp=class{constructor(){lo.set(this,void 0),fo.set(this,void 0),nt(this,lo,new Uint8Array,"f"),nt(this,fo,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?mh(e):e;nt(this,lo,vle([se(this,lo,"f"),t]),"f");let n=[],i;for(;(i=Ott(se(this,lo,"f"),se(this,fo,"f")))!=null;){if(i.carriage&&se(this,fo,"f")==null){nt(this,fo,i.index,"f");continue}if(se(this,fo,"f")!=null&&(i.index!==se(this,fo,"f")+1||i.carriage)){n.push(UF(se(this,lo,"f").subarray(0,se(this,fo,"f")-1))),nt(this,lo,se(this,lo,"f").subarray(se(this,fo,"f")),"f"),nt(this,fo,null,"f");continue}let a=se(this,fo,"f")!==null?i.preceding-1:i.preceding,o=UF(se(this,lo,"f").subarray(0,a));n.push(o),nt(this,lo,se(this,lo,"f").subarray(i.index),"f"),nt(this,fo,null,"f")}return n}flush(){return se(this,lo,"f").length?this.decode(`
676
+ `;try{let i=await e.getAiClient().complete(n,{maxTokens:300,temperature:1}),a=i.match(/<conversation-name>([\s\S]*?)<\/conversation-name>/);return a&&a[1]?a[1].trim().replace(/^["']|["']$/g,"").replace(/\.$/,"").trim():i.trim()||`Thread ${new Date().toISOString().split("T")[0]}`}catch(i){return console.error("Error generating thread name:",i),`Thread ${new Date().toISOString().split("T")[0]}`}}function nt(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t}function se(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)}var OF=function(){let{crypto:r}=globalThis;if(r?.randomUUID)return OF=r.randomUUID.bind(r),r.randomUUID();let e=new Uint8Array(1),t=r?()=>r.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^t()&15>>+n/4).toString(16))};function K5(r){return typeof r=="object"&&r!==null&&("name"in r&&r.name==="AbortError"||"message"in r&&String(r.message).includes("FetchRequestCanceledException"))}var Y5=r=>{if(r instanceof Error)return r;if(typeof r=="object"&&r!==null){try{if(Object.prototype.toString.call(r)==="[object Error]"){let e=new Error(r.message,r.cause?{cause:r.cause}:{});return r.stack&&(e.stack=r.stack),r.cause&&!e.cause&&(e.cause=r.cause),r.name&&(e.name=r.name),e}}catch{}try{return new Error(JSON.stringify(r))}catch{}}return new Error(r)};var ze=class extends Error{},Kn=class r extends ze{constructor(e,t,n,i){super(`${r.makeMessage(e,t,n)}`),this.status=e,this.headers=i,this.requestID=i?.get("x-request-id"),this.error=t;let a=t;this.code=a?.code,this.param=a?.param,this.type=a?.type}static makeMessage(e,t,n){let i=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&i?`${e} ${i}`:e?`${e} status code (no body)`:i||"(no status code or body)"}static generate(e,t,n,i){if(!e||!i)return new l2({message:n,cause:Y5(t)});let a=t?.error;return e===400?new ah(e,a,n,i):e===401?new oh(e,a,n,i):e===403?new sh(e,a,n,i):e===404?new ch(e,a,n,i):e===409?new uh(e,a,n,i):e===422?new lh(e,a,n,i):e===429?new fh(e,a,n,i):e>=500?new ph(e,a,n,i):new r(e,a,n,i)}},Bn=class extends Kn{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},l2=class extends Kn{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},f2=class extends l2{constructor({message:e}={}){super({message:e??"Request timed out."})}},ah=class extends Kn{},oh=class extends Kn{},sh=class extends Kn{},ch=class extends Kn{},uh=class extends Kn{},lh=class extends Kn{},fh=class extends Kn{},ph=class extends Kn{},dh=class extends ze{constructor(){super("Could not parse response content as the length limit was reached")}},hh=class extends ze{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},gc=class extends Error{constructor(e){super(e)}};var _tt=/^[a-z][a-z0-9+.-]*:/i,Kue=r=>_tt.test(r),Ji=r=>(Ji=Array.isArray,Ji(r)),IF=Ji;function $F(r){return typeof r!="object"?{}:r??{}}function Yue(r){if(!r)return!0;for(let e in r)return!1;return!0}function Xue(r,e){return Object.prototype.hasOwnProperty.call(r,e)}function X5(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}var Que=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new ze(`${r} must be an integer`);if(e<0)throw new ze(`${r} must be a positive integer`);return e};var ele=r=>{try{return JSON.parse(r)}catch{return}};var vc=r=>new Promise(e=>setTimeout(e,r));var p2="6.16.0";var ile=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Stt(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var ktt=()=>{let r=Stt();if(r==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":p2,"X-Stainless-OS":rle(Deno.build.os),"X-Stainless-Arch":tle(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":p2,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(r==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":p2,"X-Stainless-OS":rle(globalThis.process.platform??"unknown"),"X-Stainless-Arch":tle(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Ett();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":p2,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":p2,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Ett(){if(typeof navigator>"u"||!navigator)return null;let r=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:t}of r){let n=t.exec(navigator.userAgent);if(n){let i=n[1]||0,a=n[2]||0,o=n[3]||0;return{browser:e,version:`${i}.${a}.${o}`}}}return null}var tle=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",rle=r=>(r=r.toLowerCase(),r.includes("ios")?"iOS":r==="android"?"Android":r==="darwin"?"MacOS":r==="win32"?"Windows":r==="freebsd"?"FreeBSD":r==="openbsd"?"OpenBSD":r==="linux"?"Linux":r?`Other:${r}`:"Unknown"),nle,ale=()=>nle??(nle=ktt());function ole(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function RF(...r){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...r)}function i_(r){let e=Symbol.asyncIterator in r?r[Symbol.asyncIterator]():r[Symbol.iterator]();return RF({start(){},async pull(t){let{done:n,value:i}=await e.next();n?t.close():t.enqueue(i)},async cancel(){await e.return?.()}})}function jF(r){if(r[Symbol.asyncIterator])return r;let e=r.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function sle(r){if(r===null||typeof r!="object")return;if(r[Symbol.asyncIterator]){await r[Symbol.asyncIterator]().return?.();return}let e=r.getReader(),t=e.cancel();e.releaseLock(),await t}var cle=({headers:r,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var a_="RFC3986",FF=r=>String(r),o_={RFC1738:r=>String(r).replace(/%20/g,"+"),RFC3986:FF},NF="RFC1738";var s_=(r,e)=>(s_=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),s_(r,e)),bc=(()=>{let r=[];for(let e=0;e<256;++e)r.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return r})();var MF=1024,ule=(r,e,t,n,i)=>{if(r.length===0)return r;let a=r;if(typeof r=="symbol"?a=Symbol.prototype.toString.call(r):typeof r!="string"&&(a=String(r)),t==="iso-8859-1")return escape(a).replace(/%u[0-9a-f]{4}/gi,function(s){return"%26%23"+parseInt(s.slice(2),16)+"%3B"});let o="";for(let s=0;s<a.length;s+=MF){let c=a.length>=MF?a.slice(s,s+MF):a,u=[];for(let l=0;l<c.length;++l){let f=c.charCodeAt(l);if(f===45||f===46||f===95||f===126||f>=48&&f<=57||f>=65&&f<=90||f>=97&&f<=122||i===NF&&(f===40||f===41)){u[u.length]=c.charAt(l);continue}if(f<128){u[u.length]=bc[f];continue}if(f<2048){u[u.length]=bc[192|f>>6]+bc[128|f&63];continue}if(f<55296||f>=57344){u[u.length]=bc[224|f>>12]+bc[128|f>>6&63]+bc[128|f&63];continue}l+=1,f=65536+((f&1023)<<10|c.charCodeAt(l)&1023),u[u.length]=bc[240|f>>18]+bc[128|f>>12&63]+bc[128|f>>6&63]+bc[128|f&63]}o+=u.join("")}return o};function lle(r){return!r||typeof r!="object"?!1:!!(r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer(r))}function LF(r,e){if(Ji(r)){let t=[];for(let n=0;n<r.length;n+=1)t.push(e(r[n]));return t}return e(r)}var ple={brackets(r){return String(r)+"[]"},comma:"comma",indices(r,e){return String(r)+"["+e+"]"},repeat(r){return String(r)}},dle=function(r,e){Array.prototype.push.apply(r,Ji(e)?e:[e])},fle,Yn={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:ule,encodeValuesOnly:!1,format:a_,formatter:FF,indices:!1,serializeDate(r){return(fle??(fle=Function.prototype.call.bind(Date.prototype.toISOString)))(r)},skipNulls:!1,strictNullHandling:!1};function Ttt(r){return typeof r=="string"||typeof r=="number"||typeof r=="boolean"||typeof r=="symbol"||typeof r=="bigint"}var qF={};function hle(r,e,t,n,i,a,o,s,c,u,l,f,d,p,m,h,g,v){let b=r,x=v,A=0,k=!1;for(;(x=x.get(qF))!==void 0&&!k;){let _=x.get(r);if(A+=1,typeof _<"u"){if(_===A)throw new RangeError("Cyclic object value");k=!0}typeof x.get(qF)>"u"&&(A=0)}if(typeof u=="function"?b=u(e,b):b instanceof Date?b=d?.(b):t==="comma"&&Ji(b)&&(b=LF(b,function(_){return _ instanceof Date?d?.(_):_})),b===null){if(a)return c&&!h?c(e,Yn.encoder,g,"key",p):e;b=""}if(Ttt(b)||lle(b)){if(c){let _=h?e:c(e,Yn.encoder,g,"key",p);return[m?.(_)+"="+m?.(c(b,Yn.encoder,g,"value",p))]}return[m?.(e)+"="+m?.(String(b))]}let E=[];if(typeof b>"u")return E;let R;if(t==="comma"&&Ji(b))h&&c&&(b=LF(b,c)),R=[{value:b.length>0?b.join(",")||null:void 0}];else if(Ji(u))R=u;else{let _=Object.keys(b);R=l?_.sort(l):_}let I=s?String(e).replace(/\./g,"%2E"):String(e),w=n&&Ji(b)&&b.length===1?I+"[]":I;if(i&&Ji(b)&&b.length===0)return w+"[]";for(let _=0;_<R.length;++_){let y=R[_],T=typeof y=="object"&&typeof y.value<"u"?y.value:b[y];if(o&&T===null)continue;let P=f&&s?y.replace(/\./g,"%2E"):y,C=Ji(b)?typeof t=="function"?t(w,P):w:w+(f?"."+P:"["+P+"]");v.set(r,A);let D=new WeakMap;D.set(qF,v),dle(E,hle(T,C,t,n,i,a,o,s,t==="comma"&&h&&Ji(b)?null:c,u,l,f,d,p,m,h,g,D))}return E}function Dtt(r=Yn){if(typeof r.allowEmptyArrays<"u"&&typeof r.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof r.encodeDotInKeys<"u"&&typeof r.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(r.encoder!==null&&typeof r.encoder<"u"&&typeof r.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=r.charset||Yn.charset;if(typeof r.charset<"u"&&r.charset!=="utf-8"&&r.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=a_;if(typeof r.format<"u"){if(!s_(o_,r.format))throw new TypeError("Unknown format option provided.");t=r.format}let n=o_[t],i=Yn.filter;(typeof r.filter=="function"||Ji(r.filter))&&(i=r.filter);let a;if(r.arrayFormat&&r.arrayFormat in ple?a=r.arrayFormat:"indices"in r?a=r.indices?"indices":"repeat":a=Yn.arrayFormat,"commaRoundTrip"in r&&typeof r.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let o=typeof r.allowDots>"u"?r.encodeDotInKeys?!0:Yn.allowDots:!!r.allowDots;return{addQueryPrefix:typeof r.addQueryPrefix=="boolean"?r.addQueryPrefix:Yn.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof r.allowEmptyArrays=="boolean"?!!r.allowEmptyArrays:Yn.allowEmptyArrays,arrayFormat:a,charset:e,charsetSentinel:typeof r.charsetSentinel=="boolean"?r.charsetSentinel:Yn.charsetSentinel,commaRoundTrip:!!r.commaRoundTrip,delimiter:typeof r.delimiter>"u"?Yn.delimiter:r.delimiter,encode:typeof r.encode=="boolean"?r.encode:Yn.encode,encodeDotInKeys:typeof r.encodeDotInKeys=="boolean"?r.encodeDotInKeys:Yn.encodeDotInKeys,encoder:typeof r.encoder=="function"?r.encoder:Yn.encoder,encodeValuesOnly:typeof r.encodeValuesOnly=="boolean"?r.encodeValuesOnly:Yn.encodeValuesOnly,filter:i,format:t,formatter:n,serializeDate:typeof r.serializeDate=="function"?r.serializeDate:Yn.serializeDate,skipNulls:typeof r.skipNulls=="boolean"?r.skipNulls:Yn.skipNulls,sort:typeof r.sort=="function"?r.sort:null,strictNullHandling:typeof r.strictNullHandling=="boolean"?r.strictNullHandling:Yn.strictNullHandling}}function zF(r,e={}){let t=r,n=Dtt(e),i,a;typeof n.filter=="function"?(a=n.filter,t=a("",t)):Ji(n.filter)&&(a=n.filter,i=a);let o=[];if(typeof t!="object"||t===null)return"";let s=ple[n.arrayFormat],c=s==="comma"&&n.commaRoundTrip;i||(i=Object.keys(t)),n.sort&&i.sort(n.sort);let u=new WeakMap;for(let d=0;d<i.length;++d){let p=i[d];n.skipNulls&&t[p]===null||dle(o,hle(t[p],p,s,c,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,u))}let l=o.join(n.delimiter),f=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?f+="utf8=%26%2310003%3B&":f+="utf8=%E2%9C%93&"),l.length>0?f+l:""}function vle(r){let e=0;for(let i of r)e+=i.length;let t=new Uint8Array(e),n=0;for(let i of r)t.set(i,n),n+=i.length;return t}var mle;function mh(r){let e;return(mle??(e=new globalThis.TextEncoder,mle=e.encode.bind(e)))(r)}var gle;function UF(r){let e;return(gle??(e=new globalThis.TextDecoder,gle=e.decode.bind(e)))(r)}var lo,fo,cp=class{constructor(){lo.set(this,void 0),fo.set(this,void 0),nt(this,lo,new Uint8Array,"f"),nt(this,fo,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?mh(e):e;nt(this,lo,vle([se(this,lo,"f"),t]),"f");let n=[],i;for(;(i=Ott(se(this,lo,"f"),se(this,fo,"f")))!=null;){if(i.carriage&&se(this,fo,"f")==null){nt(this,fo,i.index,"f");continue}if(se(this,fo,"f")!=null&&(i.index!==se(this,fo,"f")+1||i.carriage)){n.push(UF(se(this,lo,"f").subarray(0,se(this,fo,"f")-1))),nt(this,lo,se(this,lo,"f").subarray(se(this,fo,"f")),"f"),nt(this,fo,null,"f");continue}let a=se(this,fo,"f")!==null?i.preceding-1:i.preceding,o=UF(se(this,lo,"f").subarray(0,a));n.push(o),nt(this,lo,se(this,lo,"f").subarray(i.index),"f"),nt(this,fo,null,"f")}return n}flush(){return se(this,lo,"f").length?this.decode(`
677
677
  `):[]}};lo=new WeakMap,fo=new WeakMap;cp.NEWLINE_CHARS=new Set([`
678
678
  `,"\r"]);cp.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Ott(r,e){for(let i=e??0;i<r.length;i++){if(r[i]===10)return{preceding:i,index:i+1,carriage:!1};if(r[i]===13)return{preceding:i,index:i+1,carriage:!0}}return null}function ble(r){for(let n=0;n<r.length-1;n++){if(r[n]===10&&r[n+1]===10||r[n]===13&&r[n+1]===13)return n+2;if(r[n]===13&&r[n+1]===10&&n+3<r.length&&r[n+2]===13&&r[n+3]===10)return n+4}return-1}var u_={off:0,error:200,warn:300,info:400,debug:500},BF=(r,e,t)=>{if(r){if(Xue(u_,r))return r;$n(t).warn(`${e} was set to ${JSON.stringify(r)}, expected one of ${JSON.stringify(Object.keys(u_))}`)}};function Q5(){}function c_(r,e,t){return!e||u_[r]>u_[t]?Q5:e[r].bind(e)}var Itt={error:Q5,warn:Q5,info:Q5,debug:Q5},yle=new WeakMap;function $n(r){let e=r.logger,t=r.logLevel??"off";if(!e)return Itt;let n=yle.get(e);if(n&&n[0]===t)return n[1];let i={error:c_("error",e,t),warn:c_("warn",e,t),info:c_("info",e,t),debug:c_("debug",e,t)};return yle.set(e,[t,i]),i}var wu=r=>(r.options&&(r.options={...r.options},delete r.options.headers),r.headers&&(r.headers=Object.fromEntries((r.headers instanceof Headers?[...r.headers]:Object.entries(r.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in r&&(r.retryOfRequestLogID&&(r.retryOf=r.retryOfRequestLogID),delete r.retryOfRequestLogID),r);var e6,yc=class r{constructor(e,t,n){this.iterator=e,e6.set(this,void 0),this.controller=t,nt(this,e6,n,"f")}static fromSSEResponse(e,t,n){let i=!1,a=n?$n(n):console;async function*o(){if(i)throw new ze("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let s=!1;try{for await(let c of $tt(e,t))if(!s){if(c.data.startsWith("[DONE]")){s=!0;continue}if(c.event===null||!c.event.startsWith("thread.")){let u;try{u=JSON.parse(c.data)}catch(l){throw a.error("Could not parse message into JSON:",c.data),a.error("From chunk:",c.raw),l}if(u&&u.error)throw new Kn(void 0,u.error,void 0,e.headers);yield u}else{let u;try{u=JSON.parse(c.data)}catch(l){throw console.error("Could not parse message into JSON:",c.data),console.error("From chunk:",c.raw),l}if(c.event=="error")throw new Kn(void 0,u.error,u.message,void 0);yield{event:c.event,data:u}}}s=!0}catch(c){if(K5(c))return;throw c}finally{s||t.abort()}}return new r(o,t,n)}static fromReadableStream(e,t,n){let i=!1;async function*a(){let s=new cp,c=jF(e);for await(let u of c)for(let l of s.decode(u))yield l;for(let u of s.flush())yield u}async function*o(){if(i)throw new ze("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let s=!1;try{for await(let c of a())s||c&&(yield JSON.parse(c));s=!0}catch(c){if(K5(c))return;throw c}finally{s||t.abort()}}return new r(o,t,n)}[(e6=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],n=this.iterator(),i=a=>({next:()=>{if(a.length===0){let o=n.next();e.push(o),t.push(o)}return a.shift()}});return[new r(()=>i(e),this.controller,se(this,e6,"f")),new r(()=>i(t),this.controller,se(this,e6,"f"))]}toReadableStream(){let e=this,t;return RF({async start(){t=e[Symbol.asyncIterator]()},async pull(n){try{let{value:i,done:a}=await t.next();if(a)return n.close();let o=mh(JSON.stringify(i)+`
679
679
  `);n.enqueue(o)}catch(i){n.error(i)}},async cancel(){await t.return?.()}})}};async function*$tt(r,e){if(!r.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new ze("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new ze("Attempted to iterate over a response with no body");let t=new HF,n=new cp,i=jF(r.body);for await(let a of Rtt(i))for(let o of n.decode(a)){let s=t.decode(o);s&&(yield s)}for(let a of n.flush()){let o=t.decode(a);o&&(yield o)}}async function*Rtt(r){let e=new Uint8Array;for await(let t of r){if(t==null)continue;let n=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?mh(t):t,i=new Uint8Array(e.length+n.length);i.set(e),i.set(n,e.length),e=i;let a;for(;(a=ble(e))!==-1;)yield e.slice(0,a),e=e.slice(a)}e.length>0&&(yield e)}var HF=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let a={event:this.event,data:this.data.join(`
@@ -686,7 +686,7 @@ ${f}`)}return o},ve=Btt(Ele);var lp=class extends _e{list(e,t={},n){return this.
686
686
  ${__(r)}`);if(E==null)throw new ze(`missing choices[${f}].tool_calls[${A}].type
687
687
  ${__(r)}`);if(_==null)throw new ze(`missing choices[${f}].tool_calls[${A}].function.name
688
688
  ${__(r)}`);if(w==null)throw new ze(`missing choices[${f}].tool_calls[${A}].function.arguments
689
- ${__(r)}`);return{...I,id:R,type:E,function:{...y,name:_,arguments:w}}})}}:{...p,message:{...v,content:m,role:b,refusal:u.refusal??null},finish_reason:l,index:f,logprobs:d}}),created:i,model:a,object:"chat.completion",...o?{system_fingerprint:o}:{}};return Ale(c,e)}function __(r){return JSON.stringify(r)}var d6=class r extends pp{static fromReadableStream(e){let t=new r(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,n){let i=new r(t),a={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return i._run(()=>i._runTools(e,t,a)),i}};var Eu=class extends _e{constructor(){super(...arguments),this.messages=new lp(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(ve`/chat/completions/${e}`,t)}update(e,t,n){return this._client.post(ve`/chat/completions/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/chat/completions",Mt,{query:e,...t})}delete(e,t){return this._client.delete(ve`/chat/completions/${e}`,t)}parse(e,t){return Dle(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(n=>s6(n,e))}runTools(e,t){return e.stream?d6.runTools(this._client,e,t):p6.runTools(this._client,e,t)}stream(e,t){return pp.createChatCompletion(this._client,e,t)}};Eu.Messages=lp;var m2=class extends _e{constructor(){super(...arguments),this.completions=new Eu(this._client)}};m2.Completions=Eu;var jle=Symbol("brand.privateNullableHeaders");function*Qtt(r){if(!r)return;if(jle in r){let{values:n,nulls:i}=r;yield*n.entries();for(let a of i)yield[a,null];return}let e=!1,t;r instanceof Headers?t=r.entries():IF(r)?t=r:(e=!0,t=Object.entries(r??{}));for(let n of t){let i=n[0];if(typeof i!="string")throw new TypeError("expected header name to be a string");let a=IF(n[1])?n[1]:[n[1]],o=!1;for(let s of a)s!==void 0&&(e&&!o&&(o=!0,yield[i,null]),yield[i,s])}}var Pe=r=>{let e=new Headers,t=new Set;for(let n of r){let i=new Set;for(let[a,o]of Qtt(n)){let s=a.toLowerCase();i.has(s)||(e.delete(a),i.add(s)),o===null?(e.delete(a),t.add(s)):(e.append(a,o),t.delete(s))}}return{[jle]:!0,values:e,nulls:t}};var wh=class extends _e{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:Pe([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}};var _h=class extends _e{create(e,t){return this._client.post("/audio/transcriptions",po({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}};var Sh=class extends _e{create(e,t){return this._client.post("/audio/translations",po({body:e,...t,__metadata:{model:e.model}},this._client))}};var wc=class extends _e{constructor(){super(...arguments),this.transcriptions=new _h(this._client),this.translations=new Sh(this._client),this.speech=new wh(this._client)}};wc.Transcriptions=_h;wc.Translations=Sh;wc.Speech=wh;var dp=class extends _e{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(ve`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",Mt,{query:e,...t})}cancel(e,t){return this._client.post(ve`/batches/${e}/cancel`,t)}};var kh=class extends _e{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:Pe([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(ve`/assistants/${e}`,{...t,headers:Pe([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,n){return this._client.post(ve`/assistants/${e}`,{body:t,...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",Mt,{query:e,...t,headers:Pe([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(ve`/assistants/${e}`,{...t,headers:Pe([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};var Eh=class extends _e{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:Pe([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};var Ah=class extends _e{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:Pe([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};var g2=class extends _e{constructor(){super(...arguments),this.sessions=new Eh(this._client),this.transcriptionSessions=new Ah(this._client)}};g2.Sessions=Eh;g2.TranscriptionSessions=Ah;var Ch=class extends _e{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:Pe([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}cancel(e,t){return this._client.post(ve`/chatkit/sessions/${e}/cancel`,{...t,headers:Pe([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}};var Th=class extends _e{retrieve(e,t){return this._client.get(ve`/chatkit/threads/${e}`,{...t,headers:Pe([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}list(e={},t){return this._client.getAPIList("/chatkit/threads",_u,{query:e,...t,headers:Pe([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}delete(e,t){return this._client.delete(ve`/chatkit/threads/${e}`,{...t,headers:Pe([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}listItems(e,t={},n){return this._client.getAPIList(ve`/chatkit/threads/${e}/items`,_u,{query:t,...n,headers:Pe([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers])})}};var v2=class extends _e{constructor(){super(...arguments),this.sessions=new Ch(this._client),this.threads=new Th(this._client)}};v2.Sessions=Ch;v2.Threads=Th;var Dh=class extends _e{create(e,t,n){return this._client.post(ve`/threads/${e}/messages`,{body:t,...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,t,n){let{thread_id:i}=t;return this._client.get(ve`/threads/${i}/messages/${e}`,{...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,t,n){let{thread_id:i,...a}=t;return this._client.post(ve`/threads/${i}/messages/${e}`,{body:a,...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,t={},n){return this._client.getAPIList(ve`/threads/${e}/messages`,Mt,{query:t,...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,t,n){let{thread_id:i}=t;return this._client.delete(ve`/threads/${i}/messages/${e}`,{...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};var Ph=class extends _e{retrieve(e,t,n){let{thread_id:i,run_id:a,...o}=t;return this._client.get(ve`/threads/${i}/runs/${a}/steps/${e}`,{query:o,...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,t,n){let{thread_id:i,...a}=t;return this._client.getAPIList(ve`/threads/${i}/runs/${e}/steps`,Mt,{query:a,...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};var Fle=r=>{if(typeof Buffer<"u"){let e=Buffer.from(r,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(r),t=e.length,n=new Uint8Array(t);for(let i=0;i<t;i++)n[i]=e.charCodeAt(i);return Array.from(new Float32Array(n.buffer))}};var b2=r=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[r]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(r)?.trim()};var Ii,mp,pN,_c,S_,Ss,gp,Oh,hp,A_,ho,k_,E_,g6,h6,m6,Nle,Mle,Lle,qle,zle,Ule,Ble,Au=class extends d2{constructor(){super(...arguments),Ii.add(this),pN.set(this,[]),_c.set(this,{}),S_.set(this,{}),Ss.set(this,void 0),gp.set(this,void 0),Oh.set(this,void 0),hp.set(this,void 0),A_.set(this,void 0),ho.set(this,void 0),k_.set(this,void 0),E_.set(this,void 0),g6.set(this,void 0)}[(pN=new WeakMap,_c=new WeakMap,S_=new WeakMap,Ss=new WeakMap,gp=new WeakMap,Oh=new WeakMap,hp=new WeakMap,A_=new WeakMap,ho=new WeakMap,k_=new WeakMap,E_=new WeakMap,g6=new WeakMap,Ii=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on("event",i=>{let a=t.shift();a?a.resolve(i):e.push(i)}),this.on("end",()=>{n=!0;for(let i of t)i.resolve(void 0);t.length=0}),this.on("abort",i=>{n=!0;for(let a of t)a.reject(i);t.length=0}),this.on("error",i=>{n=!0;for(let a of t)a.reject(i);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((a,o)=>t.push({resolve:a,reject:o})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new mp;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){let n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),this._connected();let i=yc.fromReadableStream(e,this.controller);for await(let a of i)se(this,Ii,"m",h6).call(this,a);if(i.controller.signal?.aborted)throw new Bn;return this._addRun(se(this,Ii,"m",m6).call(this))}toReadableStream(){return new yc(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,i){let a=new mp;return a._run(()=>a._runToolAssistantStream(e,t,n,{...i,headers:{...i?.headers,"X-Stainless-Helper-Method":"stream"}})),a}async _createToolAssistantStream(e,t,n,i){let a=i?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));let o={...n,stream:!0},s=await e.submitToolOutputs(t,o,{...i,signal:this.controller.signal});this._connected();for await(let c of s)se(this,Ii,"m",h6).call(this,c);if(s.controller.signal?.aborted)throw new Bn;return this._addRun(se(this,Ii,"m",m6).call(this))}static createThreadAssistantStream(e,t,n){let i=new mp;return i._run(()=>i._threadAssistantStream(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),i}static createAssistantStream(e,t,n,i){let a=new mp;return a._run(()=>a._runAssistantStream(e,t,n,{...i,headers:{...i?.headers,"X-Stainless-Helper-Method":"stream"}})),a}currentEvent(){return se(this,k_,"f")}currentRun(){return se(this,E_,"f")}currentMessageSnapshot(){return se(this,Ss,"f")}currentRunStepSnapshot(){return se(this,g6,"f")}async finalRunSteps(){return await this.done(),Object.values(se(this,_c,"f"))}async finalMessages(){return await this.done(),Object.values(se(this,S_,"f"))}async finalRun(){if(await this.done(),!se(this,gp,"f"))throw Error("Final run was not received.");return se(this,gp,"f")}async _createThreadAssistantStream(e,t,n){let i=n?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));let a={...t,stream:!0},o=await e.createAndRun(a,{...n,signal:this.controller.signal});this._connected();for await(let s of o)se(this,Ii,"m",h6).call(this,s);if(o.controller.signal?.aborted)throw new Bn;return this._addRun(se(this,Ii,"m",m6).call(this))}async _createAssistantStream(e,t,n,i){let a=i?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));let o={...n,stream:!0},s=await e.create(t,o,{...i,signal:this.controller.signal});this._connected();for await(let c of s)se(this,Ii,"m",h6).call(this,c);if(s.controller.signal?.aborted)throw new Bn;return this._addRun(se(this,Ii,"m",m6).call(this))}static accumulateDelta(e,t){for(let[n,i]of Object.entries(t)){if(!e.hasOwnProperty(n)){e[n]=i;continue}let a=e[n];if(a==null){e[n]=i;continue}if(n==="index"||n==="type"){e[n]=i;continue}if(typeof a=="string"&&typeof i=="string")a+=i;else if(typeof a=="number"&&typeof i=="number")a+=i;else if(X5(a)&&X5(i))a=this.accumulateDelta(a,i);else if(Array.isArray(a)&&Array.isArray(i)){if(a.every(o=>typeof o=="string"||typeof o=="number")){a.push(...i);continue}for(let o of i){if(!X5(o))throw new Error(`Expected array delta entry to be an object but got: ${o}`);let s=o.index;if(s==null)throw console.error(o),new Error("Expected array delta entry to have an `index` property");if(typeof s!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${s}`);let c=a[s];c==null?a.push(o):a[s]=this.accumulateDelta(c,o)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${i}, accValue: ${a}`);e[n]=a}return e}_addRun(e){return e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,i){return await this._createAssistantStream(t,e,n,i)}async _runToolAssistantStream(e,t,n,i){return await this._createToolAssistantStream(t,e,n,i)}};mp=Au,h6=function(e){if(!this.ended)switch(nt(this,k_,e,"f"),se(this,Ii,"m",Lle).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":se(this,Ii,"m",Ble).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":se(this,Ii,"m",Mle).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":se(this,Ii,"m",Nle).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},m6=function(){if(this.ended)throw new ze("stream has ended, this shouldn't happen");if(!se(this,gp,"f"))throw Error("Final run has not been received");return se(this,gp,"f")},Nle=function(e){let[t,n]=se(this,Ii,"m",zle).call(this,e,se(this,Ss,"f"));nt(this,Ss,t,"f"),se(this,S_,"f")[t.id]=t;for(let i of n){let a=t.content[i.index];a?.type=="text"&&this._emit("textCreated",a.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(let i of e.data.delta.content){if(i.type=="text"&&i.text){let a=i.text,o=t.content[i.index];if(o&&o.type=="text")this._emit("textDelta",a,o.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(i.index!=se(this,Oh,"f")){if(se(this,hp,"f"))switch(se(this,hp,"f").type){case"text":this._emit("textDone",se(this,hp,"f").text,se(this,Ss,"f"));break;case"image_file":this._emit("imageFileDone",se(this,hp,"f").image_file,se(this,Ss,"f"));break}nt(this,Oh,i.index,"f")}nt(this,hp,t.content[i.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(se(this,Oh,"f")!==void 0){let i=e.data.content[se(this,Oh,"f")];if(i)switch(i.type){case"image_file":this._emit("imageFileDone",i.image_file,se(this,Ss,"f"));break;case"text":this._emit("textDone",i.text,se(this,Ss,"f"));break}}se(this,Ss,"f")&&this._emit("messageDone",e.data),nt(this,Ss,void 0,"f")}},Mle=function(e){let t=se(this,Ii,"m",qle).call(this,e);switch(nt(this,g6,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let n=e.data.delta;if(n.step_details&&n.step_details.type=="tool_calls"&&n.step_details.tool_calls&&t.step_details.type=="tool_calls")for(let a of n.step_details.tool_calls)a.index==se(this,A_,"f")?this._emit("toolCallDelta",a,t.step_details.tool_calls[a.index]):(se(this,ho,"f")&&this._emit("toolCallDone",se(this,ho,"f")),nt(this,A_,a.index,"f"),nt(this,ho,t.step_details.tool_calls[a.index],"f"),se(this,ho,"f")&&this._emit("toolCallCreated",se(this,ho,"f")));this._emit("runStepDelta",e.data.delta,t);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":nt(this,g6,void 0,"f"),e.data.step_details.type=="tool_calls"&&se(this,ho,"f")&&(this._emit("toolCallDone",se(this,ho,"f")),nt(this,ho,void 0,"f")),this._emit("runStepDone",e.data,t);break;case"thread.run.step.in_progress":break}},Lle=function(e){se(this,pN,"f").push(e),this._emit("event",e)},qle=function(e){switch(e.event){case"thread.run.step.created":return se(this,_c,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=se(this,_c,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let n=e.data;if(n.delta){let i=mp.accumulateDelta(t,n.delta);se(this,_c,"f")[e.data.id]=i}return se(this,_c,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":se(this,_c,"f")[e.data.id]=e.data;break}if(se(this,_c,"f")[e.data.id])return se(this,_c,"f")[e.data.id];throw new Error("No snapshot available")},zle=function(e,t){let n=[];switch(e.event){case"thread.message.created":return[e.data,n];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let i=e.data;if(i.delta.content)for(let a of i.delta.content)if(a.index in t.content){let o=t.content[a.index];t.content[a.index]=se(this,Ii,"m",Ule).call(this,a,o)}else t.content[a.index]=a,n.push(a);return[t,n];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,n];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Ule=function(e,t){return mp.accumulateDelta(t,e)},Ble=function(e){switch(nt(this,E_,e.data,"f"),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":nt(this,gp,e.data,"f"),se(this,ho,"f")&&(this._emit("toolCallDone",se(this,ho,"f")),nt(this,ho,void 0,"f"));break;case"thread.run.cancelling":break}};var vp=class extends _e{constructor(){super(...arguments),this.steps=new Ph(this._client)}create(e,t,n){let{include:i,...a}=t;return this._client.post(ve`/threads/${e}/runs`,{query:{include:i},body:a,...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:t.stream??!1})}retrieve(e,t,n){let{thread_id:i}=t;return this._client.get(ve`/threads/${i}/runs/${e}`,{...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,t,n){let{thread_id:i,...a}=t;return this._client.post(ve`/threads/${i}/runs/${e}`,{body:a,...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,t={},n){return this._client.getAPIList(ve`/threads/${e}/runs`,Mt,{query:t,...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}cancel(e,t,n){let{thread_id:i}=t;return this._client.post(ve`/threads/${i}/runs/${e}/cancel`,{...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async createAndPoll(e,t,n){let i=await this.create(e,t,n);return await this.poll(i.id,{thread_id:e},n)}createAndStream(e,t,n){return Au.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){let i=Pe([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:a,response:o}=await this.retrieve(e,t,{...n,headers:{...n?.headers,...i}}).withResponse();switch(a.status){case"queued":case"in_progress":case"cancelling":let s=5e3;if(n?.pollIntervalMs)s=n.pollIntervalMs;else{let c=o.headers.get("openai-poll-after-ms");if(c){let u=parseInt(c);isNaN(u)||(s=u)}}await vc(s);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return a}}}stream(e,t,n){return Au.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n){let{thread_id:i,...a}=t;return this._client.post(ve`/threads/${i}/runs/${e}/submit_tool_outputs`,{body:a,...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:t.stream??!1})}async submitToolOutputsAndPoll(e,t,n){let i=await this.submitToolOutputs(e,t,n);return await this.poll(i.id,t,n)}submitToolOutputsStream(e,t,n){return Au.createToolAssistantStream(e,this._client.beta.threads.runs,t,n)}};vp.Steps=Ph;var y2=class extends _e{constructor(){super(...arguments),this.runs=new vp(this._client),this.messages=new Dh(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:Pe([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(ve`/threads/${e}`,{...t,headers:Pe([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,n){return this._client.post(ve`/threads/${e}`,{body:t,...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,t){return this._client.delete(ve`/threads/${e}`,{...t,headers:Pe([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:Pe([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1})}async createAndRunPoll(e,t){let n=await this.createAndRun(e,t);return await this.runs.poll(n.id,{thread_id:n.thread_id},t)}createAndRunStream(e,t){return Au.createThreadAssistantStream(e,this._client.beta.threads,t)}};y2.Runs=vp;y2.Messages=Dh;var ks=class extends _e{constructor(){super(...arguments),this.realtime=new g2(this._client),this.chatkit=new v2(this._client),this.assistants=new kh(this._client),this.threads=new y2(this._client)}};ks.Realtime=g2;ks.ChatKit=v2;ks.Assistants=kh;ks.Threads=y2;var bp=class extends _e{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}};var Ih=class extends _e{retrieve(e,t,n){let{container_id:i}=t;return this._client.get(ve`/containers/${i}/files/${e}/content`,{...n,headers:Pe([{Accept:"application/binary"},n?.headers]),__binaryResponse:!0})}};var yp=class extends _e{constructor(){super(...arguments),this.content=new Ih(this._client)}create(e,t,n){return this._client.post(ve`/containers/${e}/files`,po({body:t,...n},this._client))}retrieve(e,t,n){let{container_id:i}=t;return this._client.get(ve`/containers/${i}/files/${e}`,n)}list(e,t={},n){return this._client.getAPIList(ve`/containers/${e}/files`,Mt,{query:t,...n})}delete(e,t,n){let{container_id:i}=t;return this._client.delete(ve`/containers/${i}/files/${e}`,{...n,headers:Pe([{Accept:"*/*"},n?.headers])})}};yp.Content=Ih;var x2=class extends _e{constructor(){super(...arguments),this.files=new yp(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(ve`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",Mt,{query:e,...t})}delete(e,t){return this._client.delete(ve`/containers/${e}`,{...t,headers:Pe([{Accept:"*/*"},t?.headers])})}};x2.Files=yp;var $h=class extends _e{create(e,t,n){let{include:i,...a}=t;return this._client.post(ve`/conversations/${e}/items`,{query:{include:i},body:a,...n})}retrieve(e,t,n){let{conversation_id:i,...a}=t;return this._client.get(ve`/conversations/${i}/items/${e}`,{query:a,...n})}list(e,t={},n){return this._client.getAPIList(ve`/conversations/${e}/items`,_u,{query:t,...n})}delete(e,t,n){let{conversation_id:i}=t;return this._client.delete(ve`/conversations/${i}/items/${e}`,n)}};var w2=class extends _e{constructor(){super(...arguments),this.items=new $h(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t})}retrieve(e,t){return this._client.get(ve`/conversations/${e}`,t)}update(e,t,n){return this._client.post(ve`/conversations/${e}`,{body:t,...n})}delete(e,t){return this._client.delete(ve`/conversations/${e}`,t)}};w2.Items=$h;var xp=class extends _e{create(e,t){let n=!!e.encoding_format,i=n?e.encoding_format:"base64";n&&$n(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let a=this._client.post("/embeddings",{body:{...e,encoding_format:i},...t});return n?a:($n(this._client).debug("embeddings/decoding base64 embeddings from base64"),a._thenUnwrap(o=>(o&&o.data&&o.data.forEach(s=>{let c=s.embedding;s.embedding=Fle(c)}),o)))}};var Rh=class extends _e{retrieve(e,t,n){let{eval_id:i,run_id:a}=t;return this._client.get(ve`/evals/${i}/runs/${a}/output_items/${e}`,n)}list(e,t,n){let{eval_id:i,...a}=t;return this._client.getAPIList(ve`/evals/${i}/runs/${e}/output_items`,Mt,{query:a,...n})}};var wp=class extends _e{constructor(){super(...arguments),this.outputItems=new Rh(this._client)}create(e,t,n){return this._client.post(ve`/evals/${e}/runs`,{body:t,...n})}retrieve(e,t,n){let{eval_id:i}=t;return this._client.get(ve`/evals/${i}/runs/${e}`,n)}list(e,t={},n){return this._client.getAPIList(ve`/evals/${e}/runs`,Mt,{query:t,...n})}delete(e,t,n){let{eval_id:i}=t;return this._client.delete(ve`/evals/${i}/runs/${e}`,n)}cancel(e,t,n){let{eval_id:i}=t;return this._client.post(ve`/evals/${i}/runs/${e}`,n)}};wp.OutputItems=Rh;var _2=class extends _e{constructor(){super(...arguments),this.runs=new wp(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(ve`/evals/${e}`,t)}update(e,t,n){return this._client.post(ve`/evals/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/evals",Mt,{query:e,...t})}delete(e,t){return this._client.delete(ve`/evals/${e}`,t)}};_2.Runs=wp;var _p=class extends _e{create(e,t){return this._client.post("/files",po({body:e,...t},this._client))}retrieve(e,t){return this._client.get(ve`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",Mt,{query:e,...t})}delete(e,t){return this._client.delete(ve`/files/${e}`,t)}content(e,t){return this._client.get(ve`/files/${e}/content`,{...t,headers:Pe([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:n=1800*1e3}={}){let i=new Set(["processed","error","deleted"]),a=Date.now(),o=await this.retrieve(e);for(;!o.status||!i.has(o.status);)if(await vc(t),o=await this.retrieve(e),Date.now()-a>n)throw new f2({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return o}};var jh=class extends _e{};var Fh=class extends _e{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}};var Sp=class extends _e{constructor(){super(...arguments),this.graders=new Fh(this._client)}};Sp.Graders=Fh;var Nh=class extends _e{create(e,t,n){return this._client.getAPIList(ve`/fine_tuning/checkpoints/${e}/permissions`,xc,{body:t,method:"post",...n})}retrieve(e,t={},n){return this._client.get(ve`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...n})}delete(e,t,n){let{fine_tuned_model_checkpoint:i}=t;return this._client.delete(ve`/fine_tuning/checkpoints/${i}/permissions/${e}`,n)}};var kp=class extends _e{constructor(){super(...arguments),this.permissions=new Nh(this._client)}};kp.Permissions=Nh;var Mh=class extends _e{list(e,t={},n){return this._client.getAPIList(ve`/fine_tuning/jobs/${e}/checkpoints`,Mt,{query:t,...n})}};var Ep=class extends _e{constructor(){super(...arguments),this.checkpoints=new Mh(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(ve`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",Mt,{query:e,...t})}cancel(e,t){return this._client.post(ve`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},n){return this._client.getAPIList(ve`/fine_tuning/jobs/${e}/events`,Mt,{query:t,...n})}pause(e,t){return this._client.post(ve`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(ve`/fine_tuning/jobs/${e}/resume`,t)}};Ep.Checkpoints=Mh;var Es=class extends _e{constructor(){super(...arguments),this.methods=new jh(this._client),this.jobs=new Ep(this._client),this.checkpoints=new kp(this._client),this.alpha=new Sp(this._client)}};Es.Methods=jh;Es.Jobs=Ep;Es.Checkpoints=kp;Es.Alpha=Sp;var Lh=class extends _e{};var S2=class extends _e{constructor(){super(...arguments),this.graderModels=new Lh(this._client)}};S2.GraderModels=Lh;var Ap=class extends _e{createVariation(e,t){return this._client.post("/images/variations",po({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",po({body:e,...t,stream:e.stream??!1},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1})}};var Cp=class extends _e{retrieve(e,t){return this._client.get(ve`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",xc,e)}delete(e,t){return this._client.delete(ve`/models/${e}`,t)}};var Tp=class extends _e{create(e,t){return this._client.post("/moderations",{body:e,...t})}};var qh=class extends _e{accept(e,t,n){return this._client.post(ve`/realtime/calls/${e}/accept`,{body:t,...n,headers:Pe([{Accept:"*/*"},n?.headers])})}hangup(e,t){return this._client.post(ve`/realtime/calls/${e}/hangup`,{...t,headers:Pe([{Accept:"*/*"},t?.headers])})}refer(e,t,n){return this._client.post(ve`/realtime/calls/${e}/refer`,{body:t,...n,headers:Pe([{Accept:"*/*"},n?.headers])})}reject(e,t={},n){return this._client.post(ve`/realtime/calls/${e}/reject`,{body:t,...n,headers:Pe([{Accept:"*/*"},n?.headers])})}};var zh=class extends _e{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t})}};var Cu=class extends _e{constructor(){super(...arguments),this.clientSecrets=new zh(this._client),this.calls=new qh(this._client)}};Cu.ClientSecrets=zh;Cu.Calls=qh;function Hle(r,e){return!e||!Prt(e)?{...r,output_parsed:null,output:r.output.map(t=>t.type==="function_call"?{...t,parsed_arguments:null}:t.type==="message"?{...t,content:t.content.map(n=>({...n,parsed:null}))}:t)}:dN(r,e)}function dN(r,e){let t=r.output.map(i=>{if(i.type==="function_call")return{...i,parsed_arguments:$rt(e,i)};if(i.type==="message"){let a=i.content.map(o=>o.type==="output_text"?{...o,parsed:Drt(e,o.text)}:o);return{...i,content:a}}return i}),n=Object.assign({},r,{output:t});return Object.getOwnPropertyDescriptor(r,"output_text")||C_(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(let i of n.output)if(i.type==="message"){for(let a of i.content)if(a.type==="output_text"&&a.parsed!==null)return a.parsed}return null}}),n}function Drt(r,e){return r.text?.format?.type!=="json_schema"?null:"$parseRaw"in r.text?.format?(r.text?.format).$parseRaw(e):JSON.parse(e)}function Prt(r){return!!o6(r.text?.format)}function Ort(r){return r?.$brand==="auto-parseable-tool"}function Irt(r,e){return r.find(t=>t.type==="function"&&t.name===e)}function $rt(r,e){let t=Irt(r.tools??[],e.name);return{...e,...e,parsed_arguments:Ort(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function C_(r){let e=[];for(let t of r.output)if(t.type==="message")for(let n of t.content)n.type==="output_text"&&e.push(n.text);r.output_text=e.join("")}var Uh,T_,k2,D_,Wle,Vle,Zle,Gle,P_=class r extends d2{constructor(e){super(),Uh.add(this),T_.set(this,void 0),k2.set(this,void 0),D_.set(this,void 0),nt(this,T_,e,"f")}static createResponse(e,t,n){let i=new r(t);return i._run(()=>i._createOrRetrieveResponse(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),i}async _createOrRetrieveResponse(e,t,n){let i=n?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort())),se(this,Uh,"m",Wle).call(this);let a,o=null;"response_id"in t?(a=await e.responses.retrieve(t.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),o=t.starting_after??null):a=await e.responses.create({...t,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(let s of a)se(this,Uh,"m",Vle).call(this,s,o);if(a.controller.signal?.aborted)throw new Bn;return se(this,Uh,"m",Zle).call(this)}[(T_=new WeakMap,k2=new WeakMap,D_=new WeakMap,Uh=new WeakSet,Wle=function(){this.ended||nt(this,k2,void 0,"f")},Vle=function(t,n){if(this.ended)return;let i=(o,s)=>{(n==null||s.sequence_number>n)&&this._emit(o,s)},a=se(this,Uh,"m",Gle).call(this,t);switch(i("event",t),t.type){case"response.output_text.delta":{let o=a.output[t.output_index];if(!o)throw new ze(`missing output at index ${t.output_index}`);if(o.type==="message"){let s=o.content[t.content_index];if(!s)throw new ze(`missing content at index ${t.content_index}`);if(s.type!=="output_text")throw new ze(`expected content to be 'output_text', got ${s.type}`);i("response.output_text.delta",{...t,snapshot:s.text})}break}case"response.function_call_arguments.delta":{let o=a.output[t.output_index];if(!o)throw new ze(`missing output at index ${t.output_index}`);o.type==="function_call"&&i("response.function_call_arguments.delta",{...t,snapshot:o.arguments});break}default:i(t.type,t);break}},Zle=function(){if(this.ended)throw new ze("stream has ended, this shouldn't happen");let t=se(this,k2,"f");if(!t)throw new ze("request ended without sending any events");nt(this,k2,void 0,"f");let n=Rrt(t,se(this,T_,"f"));return nt(this,D_,n,"f"),n},Gle=function(t){let n=se(this,k2,"f");if(!n){if(t.type!=="response.created")throw new ze(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return n=nt(this,k2,t.response,"f"),n}switch(t.type){case"response.output_item.added":{n.output.push(t.item);break}case"response.content_part.added":{let i=n.output[t.output_index];if(!i)throw new ze(`missing output at index ${t.output_index}`);let a=i.type,o=t.part;a==="message"&&o.type!=="reasoning_text"?i.content.push(o):a==="reasoning"&&o.type==="reasoning_text"&&(i.content||(i.content=[]),i.content.push(o));break}case"response.output_text.delta":{let i=n.output[t.output_index];if(!i)throw new ze(`missing output at index ${t.output_index}`);if(i.type==="message"){let a=i.content[t.content_index];if(!a)throw new ze(`missing content at index ${t.content_index}`);if(a.type!=="output_text")throw new ze(`expected content to be 'output_text', got ${a.type}`);a.text+=t.delta}break}case"response.function_call_arguments.delta":{let i=n.output[t.output_index];if(!i)throw new ze(`missing output at index ${t.output_index}`);i.type==="function_call"&&(i.arguments+=t.delta);break}case"response.reasoning_text.delta":{let i=n.output[t.output_index];if(!i)throw new ze(`missing output at index ${t.output_index}`);if(i.type==="reasoning"){let a=i.content?.[t.content_index];if(!a)throw new ze(`missing content at index ${t.content_index}`);if(a.type!=="reasoning_text")throw new ze(`expected content to be 'reasoning_text', got ${a.type}`);a.text+=t.delta}break}case"response.completed":{nt(this,k2,t.response,"f");break}}return n},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on("event",i=>{let a=t.shift();a?a.resolve(i):e.push(i)}),this.on("end",()=>{n=!0;for(let i of t)i.resolve(void 0);t.length=0}),this.on("abort",i=>{n=!0;for(let a of t)a.reject(i);t.length=0}),this.on("error",i=>{n=!0;for(let a of t)a.reject(i);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((a,o)=>t.push({resolve:a,reject:o})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=se(this,D_,"f");if(!e)throw new ze("stream ended without producing a ChatCompletion");return e}};function Rrt(r,e){return Hle(r,e)}var Bh=class extends _e{list(e,t={},n){return this._client.getAPIList(ve`/responses/${e}/input_items`,Mt,{query:t,...n})}};var Hh=class extends _e{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t})}};var Tu=class extends _e{constructor(){super(...arguments),this.inputItems=new Bh(this._client),this.inputTokens=new Hh(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(n=>("object"in n&&n.object==="response"&&C_(n),n))}retrieve(e,t={},n){return this._client.get(ve`/responses/${e}`,{query:t,...n,stream:t?.stream??!1})._thenUnwrap(i=>("object"in i&&i.object==="response"&&C_(i),i))}delete(e,t){return this._client.delete(ve`/responses/${e}`,{...t,headers:Pe([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(n=>dN(n,e))}stream(e,t){return P_.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(ve`/responses/${e}/cancel`,t)}compact(e={},t){return this._client.post("/responses/compact",{body:e,...t})}};Tu.InputItems=Bh;Tu.InputTokens=Hh;var Wh=class extends _e{create(e,t,n){return this._client.post(ve`/uploads/${e}/parts`,po({body:t,...n},this._client))}};var E2=class extends _e{constructor(){super(...arguments),this.parts=new Wh(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(ve`/uploads/${e}/cancel`,t)}complete(e,t,n){return this._client.post(ve`/uploads/${e}/complete`,{body:t,...n})}};E2.Parts=Wh;var Jle=async r=>{let e=await Promise.allSettled(r),t=e.filter(i=>i.status==="rejected");if(t.length){for(let i of t)console.error(i.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}let n=[];for(let i of e)i.status==="fulfilled"&&n.push(i.value);return n};var Vh=class extends _e{create(e,t,n){return this._client.post(ve`/vector_stores/${e}/file_batches`,{body:t,...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,t,n){let{vector_store_id:i}=t;return this._client.get(ve`/vector_stores/${i}/file_batches/${e}`,{...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}cancel(e,t,n){let{vector_store_id:i}=t;return this._client.post(ve`/vector_stores/${i}/file_batches/${e}/cancel`,{...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async createAndPoll(e,t,n){let i=await this.create(e,t);return await this.poll(e,i.id,n)}listFiles(e,t,n){let{vector_store_id:i,...a}=t;return this._client.getAPIList(ve`/vector_stores/${i}/file_batches/${e}/files`,Mt,{query:a,...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async poll(e,t,n){let i=Pe([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:a,response:o}=await this.retrieve(t,{vector_store_id:e},{...n,headers:i}).withResponse();switch(a.status){case"in_progress":let s=5e3;if(n?.pollIntervalMs)s=n.pollIntervalMs;else{let c=o.headers.get("openai-poll-after-ms");if(c){let u=parseInt(c);isNaN(u)||(s=u)}}await vc(s);break;case"failed":case"cancelled":case"completed":return a}}}async uploadAndPoll(e,{files:t,fileIds:n=[]},i){if(t==null||t.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let a=i?.maxConcurrency??5,o=Math.min(a,t.length),s=this._client,c=t.values(),u=[...n];async function l(d){for(let p of d){let m=await s.files.create({file:p,purpose:"assistants"},i);u.push(m.id)}}let f=Array(o).fill(c).map(l);return await Jle(f),await this.createAndPoll(e,{file_ids:u})}};var Zh=class extends _e{create(e,t,n){return this._client.post(ve`/vector_stores/${e}/files`,{body:t,...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,t,n){let{vector_store_id:i}=t;return this._client.get(ve`/vector_stores/${i}/files/${e}`,{...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,t,n){let{vector_store_id:i,...a}=t;return this._client.post(ve`/vector_stores/${i}/files/${e}`,{body:a,...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,t={},n){return this._client.getAPIList(ve`/vector_stores/${e}/files`,Mt,{query:t,...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,t,n){let{vector_store_id:i}=t;return this._client.delete(ve`/vector_stores/${i}/files/${e}`,{...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async createAndPoll(e,t,n){let i=await this.create(e,t,n);return await this.poll(e,i.id,n)}async poll(e,t,n){let i=Pe([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let a=await this.retrieve(t,{vector_store_id:e},{...n,headers:i}).withResponse(),o=a.data;switch(o.status){case"in_progress":let s=5e3;if(n?.pollIntervalMs)s=n.pollIntervalMs;else{let c=a.response.headers.get("openai-poll-after-ms");if(c){let u=parseInt(c);isNaN(u)||(s=u)}}await vc(s);break;case"failed":case"completed":return o}}}async upload(e,t,n){let i=await this._client.files.create({file:t,purpose:"assistants"},n);return this.create(e,{file_id:i.id},n)}async uploadAndPoll(e,t,n){let i=await this.upload(e,t,n);return await this.poll(e,i.id,n)}content(e,t,n){let{vector_store_id:i}=t;return this._client.getAPIList(ve`/vector_stores/${i}/files/${e}/content`,xc,{...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};var Du=class extends _e{constructor(){super(...arguments),this.files=new Zh(this._client),this.fileBatches=new Vh(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:Pe([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(ve`/vector_stores/${e}`,{...t,headers:Pe([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,n){return this._client.post(ve`/vector_stores/${e}`,{body:t,...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",Mt,{query:e,...t,headers:Pe([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(ve`/vector_stores/${e}`,{...t,headers:Pe([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,n){return this._client.getAPIList(ve`/vector_stores/${e}/search`,xc,{body:t,method:"post",...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};Du.Files=Zh;Du.FileBatches=Vh;var Dp=class extends _e{create(e,t){return this._client.post("/videos",JF({body:e,...t},this._client))}retrieve(e,t){return this._client.get(ve`/videos/${e}`,t)}list(e={},t){return this._client.getAPIList("/videos",_u,{query:e,...t})}delete(e,t){return this._client.delete(ve`/videos/${e}`,t)}downloadContent(e,t={},n){return this._client.get(ve`/videos/${e}/content`,{query:t,...n,headers:Pe([{Accept:"application/binary"},n?.headers]),__binaryResponse:!0})}remix(e,t,n){return this._client.post(ve`/videos/${e}/remix`,JF({body:t,...n},this._client))}};var Gh,Kle,O_,Pp=class extends _e{constructor(){super(...arguments),Gh.add(this)}async unwrap(e,t,n=this._client.webhookSecret,i=300){return await this.verifySignature(e,t,n,i),JSON.parse(e)}async verifySignature(e,t,n=this._client.webhookSecret,i=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");se(this,Gh,"m",Kle).call(this,n);let a=Pe([t]).values,o=se(this,Gh,"m",O_).call(this,a,"webhook-signature"),s=se(this,Gh,"m",O_).call(this,a,"webhook-timestamp"),c=se(this,Gh,"m",O_).call(this,a,"webhook-id"),u=parseInt(s,10);if(isNaN(u))throw new gc("Invalid webhook timestamp format");let l=Math.floor(Date.now()/1e3);if(l-u>i)throw new gc("Webhook timestamp is too old");if(u>l+i)throw new gc("Webhook timestamp is too new");let f=o.split(" ").map(h=>h.startsWith("v1,")?h.substring(3):h),d=n.startsWith("whsec_")?Buffer.from(n.replace("whsec_",""),"base64"):Buffer.from(n,"utf-8"),p=c?`${c}.${s}.${e}`:`${s}.${e}`,m=await crypto.subtle.importKey("raw",d,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let h of f)try{let g=Buffer.from(h,"base64");if(await crypto.subtle.verify("HMAC",m,g,new TextEncoder().encode(p)))return}catch{continue}throw new gc("The given webhook signature does not match the expected signature")}};Gh=new WeakSet,Kle=function(e){if(typeof e!="string"||e.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},O_=function(e,t){if(!e)throw new Error("Headers are required");let n=e.get(t);if(n==null)throw new Error(`Missing required header: ${t}`);return n};var hN,mN,I_,Yle,Ct=class{constructor({baseURL:e=b2("OPENAI_BASE_URL"),apiKey:t=b2("OPENAI_API_KEY"),organization:n=b2("OPENAI_ORG_ID")??null,project:i=b2("OPENAI_PROJECT_ID")??null,webhookSecret:a=b2("OPENAI_WEBHOOK_SECRET")??null,...o}={}){if(hN.add(this),I_.set(this,void 0),this.completions=new bp(this),this.chat=new m2(this),this.embeddings=new xp(this),this.files=new _p(this),this.images=new Ap(this),this.audio=new wc(this),this.moderations=new Tp(this),this.models=new Cp(this),this.fineTuning=new Es(this),this.graders=new S2(this),this.vectorStores=new Du(this),this.webhooks=new Pp(this),this.beta=new ks(this),this.batches=new dp(this),this.uploads=new E2(this),this.responses=new Tu(this),this.realtime=new Cu(this),this.conversations=new w2(this),this.evals=new _2(this),this.containers=new x2(this),this.videos=new Dp(this),t===void 0)throw new ze("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");let s={apiKey:t,organization:n,project:i,webhookSecret:a,...o,baseURL:e||"https://api.openai.com/v1"};if(!s.dangerouslyAllowBrowser&&ile())throw new ze(`It looks like you're running in a browser-like environment.
689
+ ${__(r)}`);return{...I,id:R,type:E,function:{...y,name:_,arguments:w}}})}}:{...p,message:{...v,content:m,role:b,refusal:u.refusal??null},finish_reason:l,index:f,logprobs:d}}),created:i,model:a,object:"chat.completion",...o?{system_fingerprint:o}:{}};return Ale(c,e)}function __(r){return JSON.stringify(r)}var d6=class r extends pp{static fromReadableStream(e){let t=new r(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,n){let i=new r(t),a={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return i._run(()=>i._runTools(e,t,a)),i}};var Eu=class extends _e{constructor(){super(...arguments),this.messages=new lp(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(ve`/chat/completions/${e}`,t)}update(e,t,n){return this._client.post(ve`/chat/completions/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/chat/completions",Mt,{query:e,...t})}delete(e,t){return this._client.delete(ve`/chat/completions/${e}`,t)}parse(e,t){return Dle(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(n=>s6(n,e))}runTools(e,t){return e.stream?d6.runTools(this._client,e,t):p6.runTools(this._client,e,t)}stream(e,t){return pp.createChatCompletion(this._client,e,t)}};Eu.Messages=lp;var m2=class extends _e{constructor(){super(...arguments),this.completions=new Eu(this._client)}};m2.Completions=Eu;var jle=Symbol("brand.privateNullableHeaders");function*Qtt(r){if(!r)return;if(jle in r){let{values:n,nulls:i}=r;yield*n.entries();for(let a of i)yield[a,null];return}let e=!1,t;r instanceof Headers?t=r.entries():IF(r)?t=r:(e=!0,t=Object.entries(r??{}));for(let n of t){let i=n[0];if(typeof i!="string")throw new TypeError("expected header name to be a string");let a=IF(n[1])?n[1]:[n[1]],o=!1;for(let s of a)s!==void 0&&(e&&!o&&(o=!0,yield[i,null]),yield[i,s])}}var Pe=r=>{let e=new Headers,t=new Set;for(let n of r){let i=new Set;for(let[a,o]of Qtt(n)){let s=a.toLowerCase();i.has(s)||(e.delete(a),i.add(s)),o===null?(e.delete(a),t.add(s)):(e.append(a,o),t.delete(s))}}return{[jle]:!0,values:e,nulls:t}};var wh=class extends _e{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:Pe([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}};var _h=class extends _e{create(e,t){return this._client.post("/audio/transcriptions",po({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}};var Sh=class extends _e{create(e,t){return this._client.post("/audio/translations",po({body:e,...t,__metadata:{model:e.model}},this._client))}};var wc=class extends _e{constructor(){super(...arguments),this.transcriptions=new _h(this._client),this.translations=new Sh(this._client),this.speech=new wh(this._client)}};wc.Transcriptions=_h;wc.Translations=Sh;wc.Speech=wh;var dp=class extends _e{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(ve`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",Mt,{query:e,...t})}cancel(e,t){return this._client.post(ve`/batches/${e}/cancel`,t)}};var kh=class extends _e{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:Pe([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(ve`/assistants/${e}`,{...t,headers:Pe([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,n){return this._client.post(ve`/assistants/${e}`,{body:t,...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",Mt,{query:e,...t,headers:Pe([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(ve`/assistants/${e}`,{...t,headers:Pe([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};var Eh=class extends _e{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:Pe([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};var Ah=class extends _e{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:Pe([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};var g2=class extends _e{constructor(){super(...arguments),this.sessions=new Eh(this._client),this.transcriptionSessions=new Ah(this._client)}};g2.Sessions=Eh;g2.TranscriptionSessions=Ah;var Ch=class extends _e{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:Pe([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}cancel(e,t){return this._client.post(ve`/chatkit/sessions/${e}/cancel`,{...t,headers:Pe([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}};var Th=class extends _e{retrieve(e,t){return this._client.get(ve`/chatkit/threads/${e}`,{...t,headers:Pe([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}list(e={},t){return this._client.getAPIList("/chatkit/threads",_u,{query:e,...t,headers:Pe([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}delete(e,t){return this._client.delete(ve`/chatkit/threads/${e}`,{...t,headers:Pe([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}listItems(e,t={},n){return this._client.getAPIList(ve`/chatkit/threads/${e}/items`,_u,{query:t,...n,headers:Pe([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers])})}};var v2=class extends _e{constructor(){super(...arguments),this.sessions=new Ch(this._client),this.threads=new Th(this._client)}};v2.Sessions=Ch;v2.Threads=Th;var Dh=class extends _e{create(e,t,n){return this._client.post(ve`/threads/${e}/messages`,{body:t,...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,t,n){let{thread_id:i}=t;return this._client.get(ve`/threads/${i}/messages/${e}`,{...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,t,n){let{thread_id:i,...a}=t;return this._client.post(ve`/threads/${i}/messages/${e}`,{body:a,...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,t={},n){return this._client.getAPIList(ve`/threads/${e}/messages`,Mt,{query:t,...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,t,n){let{thread_id:i}=t;return this._client.delete(ve`/threads/${i}/messages/${e}`,{...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};var Ph=class extends _e{retrieve(e,t,n){let{thread_id:i,run_id:a,...o}=t;return this._client.get(ve`/threads/${i}/runs/${a}/steps/${e}`,{query:o,...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,t,n){let{thread_id:i,...a}=t;return this._client.getAPIList(ve`/threads/${i}/runs/${e}/steps`,Mt,{query:a,...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};var Fle=r=>{if(typeof Buffer<"u"){let e=Buffer.from(r,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(r),t=e.length,n=new Uint8Array(t);for(let i=0;i<t;i++)n[i]=e.charCodeAt(i);return Array.from(new Float32Array(n.buffer))}};var b2=r=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[r]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(r)?.trim()};var Ii,mp,pN,_c,S_,Ss,gp,Oh,hp,A_,ho,k_,E_,g6,h6,m6,Nle,Mle,Lle,qle,zle,Ule,Ble,Au=class extends d2{constructor(){super(...arguments),Ii.add(this),pN.set(this,[]),_c.set(this,{}),S_.set(this,{}),Ss.set(this,void 0),gp.set(this,void 0),Oh.set(this,void 0),hp.set(this,void 0),A_.set(this,void 0),ho.set(this,void 0),k_.set(this,void 0),E_.set(this,void 0),g6.set(this,void 0)}[(pN=new WeakMap,_c=new WeakMap,S_=new WeakMap,Ss=new WeakMap,gp=new WeakMap,Oh=new WeakMap,hp=new WeakMap,A_=new WeakMap,ho=new WeakMap,k_=new WeakMap,E_=new WeakMap,g6=new WeakMap,Ii=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on("event",i=>{let a=t.shift();a?a.resolve(i):e.push(i)}),this.on("end",()=>{n=!0;for(let i of t)i.resolve(void 0);t.length=0}),this.on("abort",i=>{n=!0;for(let a of t)a.reject(i);t.length=0}),this.on("error",i=>{n=!0;for(let a of t)a.reject(i);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((a,o)=>t.push({resolve:a,reject:o})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new mp;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){let n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),this._connected();let i=yc.fromReadableStream(e,this.controller);for await(let a of i)se(this,Ii,"m",h6).call(this,a);if(i.controller.signal?.aborted)throw new Bn;return this._addRun(se(this,Ii,"m",m6).call(this))}toReadableStream(){return new yc(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,i){let a=new mp;return a._run(()=>a._runToolAssistantStream(e,t,n,{...i,headers:{...i?.headers,"X-Stainless-Helper-Method":"stream"}})),a}async _createToolAssistantStream(e,t,n,i){let a=i?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));let o={...n,stream:!0},s=await e.submitToolOutputs(t,o,{...i,signal:this.controller.signal});this._connected();for await(let c of s)se(this,Ii,"m",h6).call(this,c);if(s.controller.signal?.aborted)throw new Bn;return this._addRun(se(this,Ii,"m",m6).call(this))}static createThreadAssistantStream(e,t,n){let i=new mp;return i._run(()=>i._threadAssistantStream(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),i}static createAssistantStream(e,t,n,i){let a=new mp;return a._run(()=>a._runAssistantStream(e,t,n,{...i,headers:{...i?.headers,"X-Stainless-Helper-Method":"stream"}})),a}currentEvent(){return se(this,k_,"f")}currentRun(){return se(this,E_,"f")}currentMessageSnapshot(){return se(this,Ss,"f")}currentRunStepSnapshot(){return se(this,g6,"f")}async finalRunSteps(){return await this.done(),Object.values(se(this,_c,"f"))}async finalMessages(){return await this.done(),Object.values(se(this,S_,"f"))}async finalRun(){if(await this.done(),!se(this,gp,"f"))throw Error("Final run was not received.");return se(this,gp,"f")}async _createThreadAssistantStream(e,t,n){let i=n?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));let a={...t,stream:!0},o=await e.createAndRun(a,{...n,signal:this.controller.signal});this._connected();for await(let s of o)se(this,Ii,"m",h6).call(this,s);if(o.controller.signal?.aborted)throw new Bn;return this._addRun(se(this,Ii,"m",m6).call(this))}async _createAssistantStream(e,t,n,i){let a=i?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));let o={...n,stream:!0},s=await e.create(t,o,{...i,signal:this.controller.signal});this._connected();for await(let c of s)se(this,Ii,"m",h6).call(this,c);if(s.controller.signal?.aborted)throw new Bn;return this._addRun(se(this,Ii,"m",m6).call(this))}static accumulateDelta(e,t){for(let[n,i]of Object.entries(t)){if(!e.hasOwnProperty(n)){e[n]=i;continue}let a=e[n];if(a==null){e[n]=i;continue}if(n==="index"||n==="type"){e[n]=i;continue}if(typeof a=="string"&&typeof i=="string")a+=i;else if(typeof a=="number"&&typeof i=="number")a+=i;else if(X5(a)&&X5(i))a=this.accumulateDelta(a,i);else if(Array.isArray(a)&&Array.isArray(i)){if(a.every(o=>typeof o=="string"||typeof o=="number")){a.push(...i);continue}for(let o of i){if(!X5(o))throw new Error(`Expected array delta entry to be an object but got: ${o}`);let s=o.index;if(s==null)throw console.error(o),new Error("Expected array delta entry to have an `index` property");if(typeof s!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${s}`);let c=a[s];c==null?a.push(o):a[s]=this.accumulateDelta(c,o)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${i}, accValue: ${a}`);e[n]=a}return e}_addRun(e){return e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,i){return await this._createAssistantStream(t,e,n,i)}async _runToolAssistantStream(e,t,n,i){return await this._createToolAssistantStream(t,e,n,i)}};mp=Au,h6=function(e){if(!this.ended)switch(nt(this,k_,e,"f"),se(this,Ii,"m",Lle).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":se(this,Ii,"m",Ble).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":se(this,Ii,"m",Mle).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":se(this,Ii,"m",Nle).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},m6=function(){if(this.ended)throw new ze("stream has ended, this shouldn't happen");if(!se(this,gp,"f"))throw Error("Final run has not been received");return se(this,gp,"f")},Nle=function(e){let[t,n]=se(this,Ii,"m",zle).call(this,e,se(this,Ss,"f"));nt(this,Ss,t,"f"),se(this,S_,"f")[t.id]=t;for(let i of n){let a=t.content[i.index];a?.type=="text"&&this._emit("textCreated",a.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(let i of e.data.delta.content){if(i.type=="text"&&i.text){let a=i.text,o=t.content[i.index];if(o&&o.type=="text")this._emit("textDelta",a,o.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(i.index!=se(this,Oh,"f")){if(se(this,hp,"f"))switch(se(this,hp,"f").type){case"text":this._emit("textDone",se(this,hp,"f").text,se(this,Ss,"f"));break;case"image_file":this._emit("imageFileDone",se(this,hp,"f").image_file,se(this,Ss,"f"));break}nt(this,Oh,i.index,"f")}nt(this,hp,t.content[i.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(se(this,Oh,"f")!==void 0){let i=e.data.content[se(this,Oh,"f")];if(i)switch(i.type){case"image_file":this._emit("imageFileDone",i.image_file,se(this,Ss,"f"));break;case"text":this._emit("textDone",i.text,se(this,Ss,"f"));break}}se(this,Ss,"f")&&this._emit("messageDone",e.data),nt(this,Ss,void 0,"f")}},Mle=function(e){let t=se(this,Ii,"m",qle).call(this,e);switch(nt(this,g6,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let n=e.data.delta;if(n.step_details&&n.step_details.type=="tool_calls"&&n.step_details.tool_calls&&t.step_details.type=="tool_calls")for(let a of n.step_details.tool_calls)a.index==se(this,A_,"f")?this._emit("toolCallDelta",a,t.step_details.tool_calls[a.index]):(se(this,ho,"f")&&this._emit("toolCallDone",se(this,ho,"f")),nt(this,A_,a.index,"f"),nt(this,ho,t.step_details.tool_calls[a.index],"f"),se(this,ho,"f")&&this._emit("toolCallCreated",se(this,ho,"f")));this._emit("runStepDelta",e.data.delta,t);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":nt(this,g6,void 0,"f"),e.data.step_details.type=="tool_calls"&&se(this,ho,"f")&&(this._emit("toolCallDone",se(this,ho,"f")),nt(this,ho,void 0,"f")),this._emit("runStepDone",e.data,t);break;case"thread.run.step.in_progress":break}},Lle=function(e){se(this,pN,"f").push(e),this._emit("event",e)},qle=function(e){switch(e.event){case"thread.run.step.created":return se(this,_c,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=se(this,_c,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let n=e.data;if(n.delta){let i=mp.accumulateDelta(t,n.delta);se(this,_c,"f")[e.data.id]=i}return se(this,_c,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":se(this,_c,"f")[e.data.id]=e.data;break}if(se(this,_c,"f")[e.data.id])return se(this,_c,"f")[e.data.id];throw new Error("No snapshot available")},zle=function(e,t){let n=[];switch(e.event){case"thread.message.created":return[e.data,n];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let i=e.data;if(i.delta.content)for(let a of i.delta.content)if(a.index in t.content){let o=t.content[a.index];t.content[a.index]=se(this,Ii,"m",Ule).call(this,a,o)}else t.content[a.index]=a,n.push(a);return[t,n];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,n];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Ule=function(e,t){return mp.accumulateDelta(t,e)},Ble=function(e){switch(nt(this,E_,e.data,"f"),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":nt(this,gp,e.data,"f"),se(this,ho,"f")&&(this._emit("toolCallDone",se(this,ho,"f")),nt(this,ho,void 0,"f"));break;case"thread.run.cancelling":break}};var vp=class extends _e{constructor(){super(...arguments),this.steps=new Ph(this._client)}create(e,t,n){let{include:i,...a}=t;return this._client.post(ve`/threads/${e}/runs`,{query:{include:i},body:a,...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:t.stream??!1})}retrieve(e,t,n){let{thread_id:i}=t;return this._client.get(ve`/threads/${i}/runs/${e}`,{...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,t,n){let{thread_id:i,...a}=t;return this._client.post(ve`/threads/${i}/runs/${e}`,{body:a,...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,t={},n){return this._client.getAPIList(ve`/threads/${e}/runs`,Mt,{query:t,...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}cancel(e,t,n){let{thread_id:i}=t;return this._client.post(ve`/threads/${i}/runs/${e}/cancel`,{...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async createAndPoll(e,t,n){let i=await this.create(e,t,n);return await this.poll(i.id,{thread_id:e},n)}createAndStream(e,t,n){return Au.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){let i=Pe([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:a,response:o}=await this.retrieve(e,t,{...n,headers:{...n?.headers,...i}}).withResponse();switch(a.status){case"queued":case"in_progress":case"cancelling":let s=5e3;if(n?.pollIntervalMs)s=n.pollIntervalMs;else{let c=o.headers.get("openai-poll-after-ms");if(c){let u=parseInt(c);isNaN(u)||(s=u)}}await vc(s);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return a}}}stream(e,t,n){return Au.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n){let{thread_id:i,...a}=t;return this._client.post(ve`/threads/${i}/runs/${e}/submit_tool_outputs`,{body:a,...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:t.stream??!1})}async submitToolOutputsAndPoll(e,t,n){let i=await this.submitToolOutputs(e,t,n);return await this.poll(i.id,t,n)}submitToolOutputsStream(e,t,n){return Au.createToolAssistantStream(e,this._client.beta.threads.runs,t,n)}};vp.Steps=Ph;var y2=class extends _e{constructor(){super(...arguments),this.runs=new vp(this._client),this.messages=new Dh(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:Pe([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(ve`/threads/${e}`,{...t,headers:Pe([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,n){return this._client.post(ve`/threads/${e}`,{body:t,...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,t){return this._client.delete(ve`/threads/${e}`,{...t,headers:Pe([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:Pe([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1})}async createAndRunPoll(e,t){let n=await this.createAndRun(e,t);return await this.runs.poll(n.id,{thread_id:n.thread_id},t)}createAndRunStream(e,t){return Au.createThreadAssistantStream(e,this._client.beta.threads,t)}};y2.Runs=vp;y2.Messages=Dh;var ks=class extends _e{constructor(){super(...arguments),this.realtime=new g2(this._client),this.chatkit=new v2(this._client),this.assistants=new kh(this._client),this.threads=new y2(this._client)}};ks.Realtime=g2;ks.ChatKit=v2;ks.Assistants=kh;ks.Threads=y2;var bp=class extends _e{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}};var Ih=class extends _e{retrieve(e,t,n){let{container_id:i}=t;return this._client.get(ve`/containers/${i}/files/${e}/content`,{...n,headers:Pe([{Accept:"application/binary"},n?.headers]),__binaryResponse:!0})}};var yp=class extends _e{constructor(){super(...arguments),this.content=new Ih(this._client)}create(e,t,n){return this._client.post(ve`/containers/${e}/files`,po({body:t,...n},this._client))}retrieve(e,t,n){let{container_id:i}=t;return this._client.get(ve`/containers/${i}/files/${e}`,n)}list(e,t={},n){return this._client.getAPIList(ve`/containers/${e}/files`,Mt,{query:t,...n})}delete(e,t,n){let{container_id:i}=t;return this._client.delete(ve`/containers/${i}/files/${e}`,{...n,headers:Pe([{Accept:"*/*"},n?.headers])})}};yp.Content=Ih;var x2=class extends _e{constructor(){super(...arguments),this.files=new yp(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(ve`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",Mt,{query:e,...t})}delete(e,t){return this._client.delete(ve`/containers/${e}`,{...t,headers:Pe([{Accept:"*/*"},t?.headers])})}};x2.Files=yp;var $h=class extends _e{create(e,t,n){let{include:i,...a}=t;return this._client.post(ve`/conversations/${e}/items`,{query:{include:i},body:a,...n})}retrieve(e,t,n){let{conversation_id:i,...a}=t;return this._client.get(ve`/conversations/${i}/items/${e}`,{query:a,...n})}list(e,t={},n){return this._client.getAPIList(ve`/conversations/${e}/items`,_u,{query:t,...n})}delete(e,t,n){let{conversation_id:i}=t;return this._client.delete(ve`/conversations/${i}/items/${e}`,n)}};var w2=class extends _e{constructor(){super(...arguments),this.items=new $h(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t})}retrieve(e,t){return this._client.get(ve`/conversations/${e}`,t)}update(e,t,n){return this._client.post(ve`/conversations/${e}`,{body:t,...n})}delete(e,t){return this._client.delete(ve`/conversations/${e}`,t)}};w2.Items=$h;var xp=class extends _e{create(e,t){let n=!!e.encoding_format,i=n?e.encoding_format:"base64";n&&$n(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let a=this._client.post("/embeddings",{body:{...e,encoding_format:i},...t});return n?a:($n(this._client).debug("embeddings/decoding base64 embeddings from base64"),a._thenUnwrap(o=>(o&&o.data&&o.data.forEach(s=>{let c=s.embedding;s.embedding=Fle(c)}),o)))}};var Rh=class extends _e{retrieve(e,t,n){let{eval_id:i,run_id:a}=t;return this._client.get(ve`/evals/${i}/runs/${a}/output_items/${e}`,n)}list(e,t,n){let{eval_id:i,...a}=t;return this._client.getAPIList(ve`/evals/${i}/runs/${e}/output_items`,Mt,{query:a,...n})}};var wp=class extends _e{constructor(){super(...arguments),this.outputItems=new Rh(this._client)}create(e,t,n){return this._client.post(ve`/evals/${e}/runs`,{body:t,...n})}retrieve(e,t,n){let{eval_id:i}=t;return this._client.get(ve`/evals/${i}/runs/${e}`,n)}list(e,t={},n){return this._client.getAPIList(ve`/evals/${e}/runs`,Mt,{query:t,...n})}delete(e,t,n){let{eval_id:i}=t;return this._client.delete(ve`/evals/${i}/runs/${e}`,n)}cancel(e,t,n){let{eval_id:i}=t;return this._client.post(ve`/evals/${i}/runs/${e}`,n)}};wp.OutputItems=Rh;var _2=class extends _e{constructor(){super(...arguments),this.runs=new wp(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(ve`/evals/${e}`,t)}update(e,t,n){return this._client.post(ve`/evals/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/evals",Mt,{query:e,...t})}delete(e,t){return this._client.delete(ve`/evals/${e}`,t)}};_2.Runs=wp;var _p=class extends _e{create(e,t){return this._client.post("/files",po({body:e,...t},this._client))}retrieve(e,t){return this._client.get(ve`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",Mt,{query:e,...t})}delete(e,t){return this._client.delete(ve`/files/${e}`,t)}content(e,t){return this._client.get(ve`/files/${e}/content`,{...t,headers:Pe([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:n=1800*1e3}={}){let i=new Set(["processed","error","deleted"]),a=Date.now(),o=await this.retrieve(e);for(;!o.status||!i.has(o.status);)if(await vc(t),o=await this.retrieve(e),Date.now()-a>n)throw new f2({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return o}};var jh=class extends _e{};var Fh=class extends _e{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}};var Sp=class extends _e{constructor(){super(...arguments),this.graders=new Fh(this._client)}};Sp.Graders=Fh;var Nh=class extends _e{create(e,t,n){return this._client.getAPIList(ve`/fine_tuning/checkpoints/${e}/permissions`,xc,{body:t,method:"post",...n})}retrieve(e,t={},n){return this._client.get(ve`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...n})}delete(e,t,n){let{fine_tuned_model_checkpoint:i}=t;return this._client.delete(ve`/fine_tuning/checkpoints/${i}/permissions/${e}`,n)}};var kp=class extends _e{constructor(){super(...arguments),this.permissions=new Nh(this._client)}};kp.Permissions=Nh;var Mh=class extends _e{list(e,t={},n){return this._client.getAPIList(ve`/fine_tuning/jobs/${e}/checkpoints`,Mt,{query:t,...n})}};var Ep=class extends _e{constructor(){super(...arguments),this.checkpoints=new Mh(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(ve`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",Mt,{query:e,...t})}cancel(e,t){return this._client.post(ve`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},n){return this._client.getAPIList(ve`/fine_tuning/jobs/${e}/events`,Mt,{query:t,...n})}pause(e,t){return this._client.post(ve`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(ve`/fine_tuning/jobs/${e}/resume`,t)}};Ep.Checkpoints=Mh;var Es=class extends _e{constructor(){super(...arguments),this.methods=new jh(this._client),this.jobs=new Ep(this._client),this.checkpoints=new kp(this._client),this.alpha=new Sp(this._client)}};Es.Methods=jh;Es.Jobs=Ep;Es.Checkpoints=kp;Es.Alpha=Sp;var Lh=class extends _e{};var S2=class extends _e{constructor(){super(...arguments),this.graderModels=new Lh(this._client)}};S2.GraderModels=Lh;var Ap=class extends _e{createVariation(e,t){return this._client.post("/images/variations",po({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",po({body:e,...t,stream:e.stream??!1},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1})}};var Cp=class extends _e{retrieve(e,t){return this._client.get(ve`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",xc,e)}delete(e,t){return this._client.delete(ve`/models/${e}`,t)}};var Tp=class extends _e{create(e,t){return this._client.post("/moderations",{body:e,...t})}};var qh=class extends _e{accept(e,t,n){return this._client.post(ve`/realtime/calls/${e}/accept`,{body:t,...n,headers:Pe([{Accept:"*/*"},n?.headers])})}hangup(e,t){return this._client.post(ve`/realtime/calls/${e}/hangup`,{...t,headers:Pe([{Accept:"*/*"},t?.headers])})}refer(e,t,n){return this._client.post(ve`/realtime/calls/${e}/refer`,{body:t,...n,headers:Pe([{Accept:"*/*"},n?.headers])})}reject(e,t={},n){return this._client.post(ve`/realtime/calls/${e}/reject`,{body:t,...n,headers:Pe([{Accept:"*/*"},n?.headers])})}};var zh=class extends _e{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t})}};var Cu=class extends _e{constructor(){super(...arguments),this.clientSecrets=new zh(this._client),this.calls=new qh(this._client)}};Cu.ClientSecrets=zh;Cu.Calls=qh;function Hle(r,e){return!e||!Prt(e)?{...r,output_parsed:null,output:r.output.map(t=>t.type==="function_call"?{...t,parsed_arguments:null}:t.type==="message"?{...t,content:t.content.map(n=>({...n,parsed:null}))}:t)}:dN(r,e)}function dN(r,e){let t=r.output.map(i=>{if(i.type==="function_call")return{...i,parsed_arguments:$rt(e,i)};if(i.type==="message"){let a=i.content.map(o=>o.type==="output_text"?{...o,parsed:Drt(e,o.text)}:o);return{...i,content:a}}return i}),n=Object.assign({},r,{output:t});return Object.getOwnPropertyDescriptor(r,"output_text")||C_(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(let i of n.output)if(i.type==="message"){for(let a of i.content)if(a.type==="output_text"&&a.parsed!==null)return a.parsed}return null}}),n}function Drt(r,e){return r.text?.format?.type!=="json_schema"?null:"$parseRaw"in r.text?.format?(r.text?.format).$parseRaw(e):JSON.parse(e)}function Prt(r){return!!o6(r.text?.format)}function Ort(r){return r?.$brand==="auto-parseable-tool"}function Irt(r,e){return r.find(t=>t.type==="function"&&t.name===e)}function $rt(r,e){let t=Irt(r.tools??[],e.name);return{...e,...e,parsed_arguments:Ort(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function C_(r){let e=[];for(let t of r.output)if(t.type==="message")for(let n of t.content)n.type==="output_text"&&e.push(n.text);r.output_text=e.join("")}var Uh,T_,k2,D_,Wle,Vle,Zle,Gle,P_=class r extends d2{constructor(e){super(),Uh.add(this),T_.set(this,void 0),k2.set(this,void 0),D_.set(this,void 0),nt(this,T_,e,"f")}static createResponse(e,t,n){let i=new r(t);return i._run(()=>i._createOrRetrieveResponse(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),i}async _createOrRetrieveResponse(e,t,n){let i=n?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort())),se(this,Uh,"m",Wle).call(this);let a,o=null;"response_id"in t?(a=await e.responses.retrieve(t.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),o=t.starting_after??null):a=await e.responses.create({...t,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(let s of a)se(this,Uh,"m",Vle).call(this,s,o);if(a.controller.signal?.aborted)throw new Bn;return se(this,Uh,"m",Zle).call(this)}[(T_=new WeakMap,k2=new WeakMap,D_=new WeakMap,Uh=new WeakSet,Wle=function(){this.ended||nt(this,k2,void 0,"f")},Vle=function(t,n){if(this.ended)return;let i=(o,s)=>{(n==null||s.sequence_number>n)&&this._emit(o,s)},a=se(this,Uh,"m",Gle).call(this,t);switch(i("event",t),t.type){case"response.output_text.delta":{let o=a.output[t.output_index];if(!o)throw new ze(`missing output at index ${t.output_index}`);if(o.type==="message"){let s=o.content[t.content_index];if(!s)throw new ze(`missing content at index ${t.content_index}`);if(s.type!=="output_text")throw new ze(`expected content to be 'output_text', got ${s.type}`);i("response.output_text.delta",{...t,snapshot:s.text})}break}case"response.function_call_arguments.delta":{let o=a.output[t.output_index];if(!o)throw new ze(`missing output at index ${t.output_index}`);o.type==="function_call"&&i("response.function_call_arguments.delta",{...t,snapshot:o.arguments});break}default:i(t.type,t);break}},Zle=function(){if(this.ended)throw new ze("stream has ended, this shouldn't happen");let t=se(this,k2,"f");if(!t)throw new ze("request ended without sending any events");nt(this,k2,void 0,"f");let n=Rrt(t,se(this,T_,"f"));return nt(this,D_,n,"f"),n},Gle=function(t){let n=se(this,k2,"f");if(!n){if(t.type!=="response.created")throw new ze(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return n=nt(this,k2,t.response,"f"),n}switch(t.type){case"response.output_item.added":{n.output.push(t.item);break}case"response.content_part.added":{let i=n.output[t.output_index];if(!i)throw new ze(`missing output at index ${t.output_index}`);let a=i.type,o=t.part;a==="message"&&o.type!=="reasoning_text"?i.content.push(o):a==="reasoning"&&o.type==="reasoning_text"&&(i.content||(i.content=[]),i.content.push(o));break}case"response.output_text.delta":{let i=n.output[t.output_index];if(!i)throw new ze(`missing output at index ${t.output_index}`);if(i.type==="message"){let a=i.content[t.content_index];if(!a)throw new ze(`missing content at index ${t.content_index}`);if(a.type!=="output_text")throw new ze(`expected content to be 'output_text', got ${a.type}`);a.text+=t.delta}break}case"response.function_call_arguments.delta":{let i=n.output[t.output_index];if(!i)throw new ze(`missing output at index ${t.output_index}`);i.type==="function_call"&&(i.arguments+=t.delta);break}case"response.reasoning_text.delta":{let i=n.output[t.output_index];if(!i)throw new ze(`missing output at index ${t.output_index}`);if(i.type==="reasoning"){let a=i.content?.[t.content_index];if(!a)throw new ze(`missing content at index ${t.content_index}`);if(a.type!=="reasoning_text")throw new ze(`expected content to be 'reasoning_text', got ${a.type}`);a.text+=t.delta}break}case"response.completed":{nt(this,k2,t.response,"f");break}}return n},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on("event",i=>{let a=t.shift();a?a.resolve(i):e.push(i)}),this.on("end",()=>{n=!0;for(let i of t)i.resolve(void 0);t.length=0}),this.on("abort",i=>{n=!0;for(let a of t)a.reject(i);t.length=0}),this.on("error",i=>{n=!0;for(let a of t)a.reject(i);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((a,o)=>t.push({resolve:a,reject:o})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=se(this,D_,"f");if(!e)throw new ze("stream ended without producing a ChatCompletion");return e}};function Rrt(r,e){return Hle(r,e)}var Bh=class extends _e{list(e,t={},n){return this._client.getAPIList(ve`/responses/${e}/input_items`,Mt,{query:t,...n})}};var Hh=class extends _e{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t})}};var Tu=class extends _e{constructor(){super(...arguments),this.inputItems=new Bh(this._client),this.inputTokens=new Hh(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(n=>("object"in n&&n.object==="response"&&C_(n),n))}retrieve(e,t={},n){return this._client.get(ve`/responses/${e}`,{query:t,...n,stream:t?.stream??!1})._thenUnwrap(i=>("object"in i&&i.object==="response"&&C_(i),i))}delete(e,t){return this._client.delete(ve`/responses/${e}`,{...t,headers:Pe([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(n=>dN(n,e))}stream(e,t){return P_.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(ve`/responses/${e}/cancel`,t)}compact(e,t){return this._client.post("/responses/compact",{body:e,...t})}};Tu.InputItems=Bh;Tu.InputTokens=Hh;var Wh=class extends _e{create(e,t,n){return this._client.post(ve`/uploads/${e}/parts`,po({body:t,...n},this._client))}};var E2=class extends _e{constructor(){super(...arguments),this.parts=new Wh(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(ve`/uploads/${e}/cancel`,t)}complete(e,t,n){return this._client.post(ve`/uploads/${e}/complete`,{body:t,...n})}};E2.Parts=Wh;var Jle=async r=>{let e=await Promise.allSettled(r),t=e.filter(i=>i.status==="rejected");if(t.length){for(let i of t)console.error(i.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}let n=[];for(let i of e)i.status==="fulfilled"&&n.push(i.value);return n};var Vh=class extends _e{create(e,t,n){return this._client.post(ve`/vector_stores/${e}/file_batches`,{body:t,...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,t,n){let{vector_store_id:i}=t;return this._client.get(ve`/vector_stores/${i}/file_batches/${e}`,{...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}cancel(e,t,n){let{vector_store_id:i}=t;return this._client.post(ve`/vector_stores/${i}/file_batches/${e}/cancel`,{...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async createAndPoll(e,t,n){let i=await this.create(e,t);return await this.poll(e,i.id,n)}listFiles(e,t,n){let{vector_store_id:i,...a}=t;return this._client.getAPIList(ve`/vector_stores/${i}/file_batches/${e}/files`,Mt,{query:a,...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async poll(e,t,n){let i=Pe([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:a,response:o}=await this.retrieve(t,{vector_store_id:e},{...n,headers:i}).withResponse();switch(a.status){case"in_progress":let s=5e3;if(n?.pollIntervalMs)s=n.pollIntervalMs;else{let c=o.headers.get("openai-poll-after-ms");if(c){let u=parseInt(c);isNaN(u)||(s=u)}}await vc(s);break;case"failed":case"cancelled":case"completed":return a}}}async uploadAndPoll(e,{files:t,fileIds:n=[]},i){if(t==null||t.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let a=i?.maxConcurrency??5,o=Math.min(a,t.length),s=this._client,c=t.values(),u=[...n];async function l(d){for(let p of d){let m=await s.files.create({file:p,purpose:"assistants"},i);u.push(m.id)}}let f=Array(o).fill(c).map(l);return await Jle(f),await this.createAndPoll(e,{file_ids:u})}};var Zh=class extends _e{create(e,t,n){return this._client.post(ve`/vector_stores/${e}/files`,{body:t,...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,t,n){let{vector_store_id:i}=t;return this._client.get(ve`/vector_stores/${i}/files/${e}`,{...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,t,n){let{vector_store_id:i,...a}=t;return this._client.post(ve`/vector_stores/${i}/files/${e}`,{body:a,...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,t={},n){return this._client.getAPIList(ve`/vector_stores/${e}/files`,Mt,{query:t,...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,t,n){let{vector_store_id:i}=t;return this._client.delete(ve`/vector_stores/${i}/files/${e}`,{...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async createAndPoll(e,t,n){let i=await this.create(e,t,n);return await this.poll(e,i.id,n)}async poll(e,t,n){let i=Pe([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let a=await this.retrieve(t,{vector_store_id:e},{...n,headers:i}).withResponse(),o=a.data;switch(o.status){case"in_progress":let s=5e3;if(n?.pollIntervalMs)s=n.pollIntervalMs;else{let c=a.response.headers.get("openai-poll-after-ms");if(c){let u=parseInt(c);isNaN(u)||(s=u)}}await vc(s);break;case"failed":case"completed":return o}}}async upload(e,t,n){let i=await this._client.files.create({file:t,purpose:"assistants"},n);return this.create(e,{file_id:i.id},n)}async uploadAndPoll(e,t,n){let i=await this.upload(e,t,n);return await this.poll(e,i.id,n)}content(e,t,n){let{vector_store_id:i}=t;return this._client.getAPIList(ve`/vector_stores/${i}/files/${e}/content`,xc,{...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};var Du=class extends _e{constructor(){super(...arguments),this.files=new Zh(this._client),this.fileBatches=new Vh(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:Pe([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(ve`/vector_stores/${e}`,{...t,headers:Pe([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,n){return this._client.post(ve`/vector_stores/${e}`,{body:t,...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",Mt,{query:e,...t,headers:Pe([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(ve`/vector_stores/${e}`,{...t,headers:Pe([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,n){return this._client.getAPIList(ve`/vector_stores/${e}/search`,xc,{body:t,method:"post",...n,headers:Pe([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};Du.Files=Zh;Du.FileBatches=Vh;var Dp=class extends _e{create(e,t){return this._client.post("/videos",JF({body:e,...t},this._client))}retrieve(e,t){return this._client.get(ve`/videos/${e}`,t)}list(e={},t){return this._client.getAPIList("/videos",_u,{query:e,...t})}delete(e,t){return this._client.delete(ve`/videos/${e}`,t)}downloadContent(e,t={},n){return this._client.get(ve`/videos/${e}/content`,{query:t,...n,headers:Pe([{Accept:"application/binary"},n?.headers]),__binaryResponse:!0})}remix(e,t,n){return this._client.post(ve`/videos/${e}/remix`,JF({body:t,...n},this._client))}};var Gh,Kle,O_,Pp=class extends _e{constructor(){super(...arguments),Gh.add(this)}async unwrap(e,t,n=this._client.webhookSecret,i=300){return await this.verifySignature(e,t,n,i),JSON.parse(e)}async verifySignature(e,t,n=this._client.webhookSecret,i=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");se(this,Gh,"m",Kle).call(this,n);let a=Pe([t]).values,o=se(this,Gh,"m",O_).call(this,a,"webhook-signature"),s=se(this,Gh,"m",O_).call(this,a,"webhook-timestamp"),c=se(this,Gh,"m",O_).call(this,a,"webhook-id"),u=parseInt(s,10);if(isNaN(u))throw new gc("Invalid webhook timestamp format");let l=Math.floor(Date.now()/1e3);if(l-u>i)throw new gc("Webhook timestamp is too old");if(u>l+i)throw new gc("Webhook timestamp is too new");let f=o.split(" ").map(h=>h.startsWith("v1,")?h.substring(3):h),d=n.startsWith("whsec_")?Buffer.from(n.replace("whsec_",""),"base64"):Buffer.from(n,"utf-8"),p=c?`${c}.${s}.${e}`:`${s}.${e}`,m=await crypto.subtle.importKey("raw",d,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let h of f)try{let g=Buffer.from(h,"base64");if(await crypto.subtle.verify("HMAC",m,g,new TextEncoder().encode(p)))return}catch{continue}throw new gc("The given webhook signature does not match the expected signature")}};Gh=new WeakSet,Kle=function(e){if(typeof e!="string"||e.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},O_=function(e,t){if(!e)throw new Error("Headers are required");let n=e.get(t);if(n==null)throw new Error(`Missing required header: ${t}`);return n};var hN,mN,I_,Yle,Ct=class{constructor({baseURL:e=b2("OPENAI_BASE_URL"),apiKey:t=b2("OPENAI_API_KEY"),organization:n=b2("OPENAI_ORG_ID")??null,project:i=b2("OPENAI_PROJECT_ID")??null,webhookSecret:a=b2("OPENAI_WEBHOOK_SECRET")??null,...o}={}){if(hN.add(this),I_.set(this,void 0),this.completions=new bp(this),this.chat=new m2(this),this.embeddings=new xp(this),this.files=new _p(this),this.images=new Ap(this),this.audio=new wc(this),this.moderations=new Tp(this),this.models=new Cp(this),this.fineTuning=new Es(this),this.graders=new S2(this),this.vectorStores=new Du(this),this.webhooks=new Pp(this),this.beta=new ks(this),this.batches=new dp(this),this.uploads=new E2(this),this.responses=new Tu(this),this.realtime=new Cu(this),this.conversations=new w2(this),this.evals=new _2(this),this.containers=new x2(this),this.videos=new Dp(this),t===void 0)throw new ze("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");let s={apiKey:t,organization:n,project:i,webhookSecret:a,...o,baseURL:e||"https://api.openai.com/v1"};if(!s.dangerouslyAllowBrowser&&ile())throw new ze(`It looks like you're running in a browser-like environment.
690
690
 
691
691
  This is disabled by default, as it risks exposing your secret API credentials to attackers.
692
692
  If you understand the risks and have appropriate mitigations in place,