@maincode-ai/matilda-code 0.18.9 → 0.19.0

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 (37) hide show
  1. package/README.md +0 -45
  2. package/chunks/{agent-GOOWZ6F7.js → agent-HQXJVWNV.js} +1 -1
  3. package/chunks/{agent-headless-FYT55CO3.js → agent-headless-JEQDQMD2.js} +1 -1
  4. package/chunks/{chunk-ZVKKN3WG.js → chunk-FHR4PQU4.js} +452 -452
  5. package/chunks/{chunk-IKFBSJXC.js → chunk-FZBNVQAK.js} +1 -1
  6. package/chunks/{chunk-T2NMK26P.js → chunk-KPVNVGPT.js} +1 -1
  7. package/chunks/{chunk-Q6C5K3YY.js → chunk-RIOYZMYO.js} +13 -13
  8. package/chunks/{chunk-VO2JBUPW.js → chunk-UCPCZNLX.js} +3 -3
  9. package/chunks/{chunk-Y2KRIHZQ.js → chunk-XOTRZSKL.js} +1 -1
  10. package/chunks/{computer-use-C5L6IOR4.js → computer-use-JEQXCG32.js} +1 -1
  11. package/chunks/{contextCommand-WKBZJUDM.js → contextCommand-N6WO7T6Y.js} +1 -1
  12. package/chunks/{edit-KBE2WJ4H.js → edit-HKSB4XDS.js} +1 -1
  13. package/chunks/{enter-worktree-EZHACH2E.js → enter-worktree-75VMHNQL.js} +1 -1
  14. package/chunks/{enterPlanMode-B4G2S3YT.js → enterPlanMode-DFXAPB2C.js} +1 -1
  15. package/chunks/{exit-worktree-OKQCXWIJ.js → exit-worktree-H5O6VDZ4.js} +1 -1
  16. package/chunks/{exitPlanMode-5TI7J32L.js → exitPlanMode-AUYIUGMB.js} +1 -1
  17. package/chunks/{geminiContentGenerator-IXUUFSPV.js → geminiContentGenerator-W22MIORO.js} +1 -1
  18. package/chunks/{glob-UINEPTF2.js → glob-QJNBNWZR.js} +1 -1
  19. package/chunks/{grep-L7R7NTYF.js → grep-MMFCVW2R.js} +1 -1
  20. package/chunks/{matildaAgentContentGenerator-P353UXQ5.js → matildaAgentContentGenerator-SF2SKGQZ.js} +1 -1
  21. package/chunks/{matildaContentGenerator-4PRNXQFW.js → matildaContentGenerator-KBHUJJSD.js} +1 -1
  22. package/chunks/{monitor-DHVRPWRA.js → monitor-J5QDRKDF.js} +1 -1
  23. package/chunks/{notebook-edit-6JEN5B2C.js → notebook-edit-3JCVXLO7.js} +1 -1
  24. package/chunks/{openaiContentGenerator-JUAQWWZW.js → openaiContentGenerator-JZSNF4UJ.js} +1 -1
  25. package/chunks/{ripGrep-IFQZBMJM.js → ripGrep-6G4YGFS7.js} +1 -1
  26. package/chunks/{scheduler-GMYLGHRU.js → scheduler-AJOK5IA2.js} +1 -1
  27. package/chunks/{serve-BZCBBVYK.js → serve-VOKMKJM2.js} +1 -1
  28. package/chunks/{shell-NBSDEF4X.js → shell-6WBO3IXW.js} +1 -1
  29. package/chunks/{src-V45EBAJO.js → src-2ZZ5NI3R.js} +1 -1
  30. package/chunks/{team-create-HINAUE7Q.js → team-create-QIVBHWVZ.js} +1 -1
  31. package/chunks/{web-search-JYSAVXQZ.js → web-search-3F5JHEJW.js} +1 -1
  32. package/chunks/{workflow-RL4VXOAN.js → workflow-6UA4CJQT.js} +2 -2
  33. package/chunks/{write-file-736524BJ.js → write-file-3AXYXY35.js} +1 -1
  34. package/cli.js +376 -375
  35. package/package.json +3 -3
  36. /package/chunks/{tree-sitter-TRLHGFF6.js → tree-sitter-SJW2MKGF.js} +0 -0
  37. /package/chunks/{tree-sitter-bash-5CI7UGKF.js → tree-sitter-bash-XNCMPQBK.js} +0 -0
@@ -1,19 +1,19 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{a as Kn}from"./chunk-QCIDUZV6.js";import{a as Jn,b as Vn,c as zn}from"./chunk-R6YTDM76.js";import{c as mr,f as ve}from"./chunk-S4K76QPI.js";import{a as jn,b as st,c as Gn}from"./chunk-IKFBSJXC.js";import{a as Vr,e as Bn,j as Wn,o as Hn,q as qn,s as Xn,t as dr}from"./chunk-LN2DRVOB.js";import{e as Dn}from"./chunk-4J6DC24J.js";import{b as zr}from"./chunk-ESSYHTAZ.js";import{Y as me,b as Un}from"./chunk-QWBNNEV2.js";import{b as a}from"./chunk-GZPNIYVZ.js";a();a();a();a();a();a();a();a();function w(n,e,t,r,s){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?s.call(n,t):s?s.value=t:e.set(n,t),t}function c(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)}a();var Kr=function(){let{crypto:n}=globalThis;if(n?.randomUUID)return Kr=n.randomUUID.bind(n),n.randomUUID();let e=new Uint8Array(1),t=n?()=>n.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^t()&15>>+r/4).toString(16))};a();a();a();function Ht(n){return typeof n=="object"&&n!==null&&("name"in n&&n.name==="AbortError"||"message"in n&&String(n.message).includes("FetchRequestCanceledException"))}var qt=n=>{if(n instanceof Error)return n;if(typeof n=="object"&&n!==null){try{if(Object.prototype.toString.call(n)==="[object Error]"){let e=new Error(n.message,n.cause?{cause:n.cause}:{});return n.stack&&(e.stack=n.stack),n.cause&&!e.cause&&(e.cause=n.cause),n.name&&(e.name=n.name),e}}catch{}try{return new Error(JSON.stringify(n))}catch{}}return new Error(n)};var b=class extends Error{},$=class n extends b{constructor(e,t,r,s){super(`${n.makeMessage(e,t,r)}`),this.status=e,this.headers=s,this.requestID=s?.get("x-request-id"),this.error=t;let o=t;this.code=o?.code,this.param=o?.param,this.type=o?.type}static makeMessage(e,t,r){let s=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,t,r,s){if(!e||!s)return new he({message:r,cause:qt(t)});let o=t?.error;return e===400?new ot(e,o,r,s):e===401?new it(e,o,r,s):e===403?new at(e,o,r,s):e===404?new lt(e,o,r,s):e===409?new ct(e,o,r,s):e===422?new ut(e,o,r,s):e===429?new ft(e,o,r,s):e>=500?new pt(e,o,r,s):new n(e,o,r,s)}},M=class extends ${constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},he=class extends ${constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},ge=class extends he{constructor({message:e}={}){super({message:e??"Request timed out."})}},ot=class extends ${},it=class extends ${},at=class extends ${},lt=class extends ${},ct=class extends ${},ut=class extends ${},ft=class extends ${},pt=class extends ${},dt=class extends b{constructor(){super("Could not parse response content as the length limit was reached")}},mt=class extends b{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},Z=class extends Error{constructor(e){super(e)}};var no=/^[a-z][a-z0-9+.-]*:/i,Qn=n=>no.test(n),W=n=>(W=Array.isArray,W(n)),Qr=W;function Yn(n){return typeof n!="object"?{}:n??{}}function Zn(n){if(!n)return!0;for(let e in n)return!1;return!0}function es(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function Xt(n){return n!=null&&typeof n=="object"&&!Array.isArray(n)}var ts=(n,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new b(`${n} must be an integer`);if(e<0)throw new b(`${n} must be a positive integer`);return e};var rs=n=>{try{return JSON.parse(n)}catch{return}};a();var ee=n=>new Promise(e=>setTimeout(e,n));a();a();var _e="5.11.0";var is=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function so(){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 oo=()=>{let n=so();if(n==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":ss(Deno.build.os),"X-Stainless-Arch":ns(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":_e,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(n==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":ss(globalThis.process.platform??"unknown"),"X-Stainless-Arch":ns(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=io();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"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":_e,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function io(){if(typeof navigator>"u"||!navigator)return null;let n=[{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 n){let r=t.exec(navigator.userAgent);if(r){let s=r[1]||0,o=r[2]||0,i=r[3]||0;return{browser:e,version:`${s}.${o}.${i}`}}}return null}var ns=n=>n==="x32"?"x32":n==="x86_64"||n==="x64"?"x64":n==="arm"?"arm":n==="aarch64"||n==="arm64"?"arm64":n?`other:${n}`:"unknown",ss=n=>(n=n.toLowerCase(),n.includes("ios")?"iOS":n==="android"?"Android":n==="darwin"?"MacOS":n==="win32"?"Windows":n==="freebsd"?"FreeBSD":n==="openbsd"?"OpenBSD":n==="linux"?"Linux":n?`Other:${n}`:"Unknown"),os,as=()=>os??(os=oo());a();function ls(){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 Yr(...n){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(...n)}function hr(n){let e=Symbol.asyncIterator in n?n[Symbol.asyncIterator]():n[Symbol.iterator]();return Yr({start(){},async pull(t){let{done:r,value:s}=await e.next();r?t.close():t.enqueue(s)},async cancel(){await e.return?.()}})}function Zr(n){if(n[Symbol.asyncIterator])return n;let e=n.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 cs(n){if(n===null||typeof n!="object")return;if(n[Symbol.asyncIterator]){await n[Symbol.asyncIterator]().return?.();return}let e=n.getReader(),t=e.cancel();e.releaseLock(),await t}a();var us=({headers:n,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});a();a();var gr="RFC3986",en=n=>String(n),_r={RFC1738:n=>String(n).replace(/%20/g,"+"),RFC3986:en},tn="RFC1738";a();a();var br=(n,e)=>(br=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),br(n,e)),te=(()=>{let n=[];for(let e=0;e<256;++e)n.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return n})();var rn=1024,fs=(n,e,t,r,s)=>{if(n.length===0)return n;let o=n;if(typeof n=="symbol"?o=Symbol.prototype.toString.call(n):typeof n!="string"&&(o=String(n)),t==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(l){return"%26%23"+parseInt(l.slice(2),16)+"%3B"});let i="";for(let l=0;l<o.length;l+=rn){let u=o.length>=rn?o.slice(l,l+rn):o,p=[];for(let g=0;g<u.length;++g){let m=u.charCodeAt(g);if(m===45||m===46||m===95||m===126||m>=48&&m<=57||m>=65&&m<=90||m>=97&&m<=122||s===tn&&(m===40||m===41)){p[p.length]=u.charAt(g);continue}if(m<128){p[p.length]=te[m];continue}if(m<2048){p[p.length]=te[192|m>>6]+te[128|m&63];continue}if(m<55296||m>=57344){p[p.length]=te[224|m>>12]+te[128|m>>6&63]+te[128|m&63];continue}g+=1,m=65536+((m&1023)<<10|u.charCodeAt(g)&1023),p[p.length]=te[240|m>>18]+te[128|m>>12&63]+te[128|m>>6&63]+te[128|m&63]}i+=p.join("")}return i};function ps(n){return!n||typeof n!="object"?!1:!!(n.constructor&&n.constructor.isBuffer&&n.constructor.isBuffer(n))}function nn(n,e){if(W(n)){let t=[];for(let r=0;r<n.length;r+=1)t.push(e(n[r]));return t}return e(n)}var ms={brackets(n){return String(n)+"[]"},comma:"comma",indices(n,e){return String(n)+"["+e+"]"},repeat(n){return String(n)}},hs=function(n,e){Array.prototype.push.apply(n,W(e)?e:[e])},ds,N={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:fs,encodeValuesOnly:!1,format:gr,formatter:en,indices:!1,serializeDate(n){return(ds??(ds=Function.prototype.call.bind(Date.prototype.toISOString)))(n)},skipNulls:!1,strictNullHandling:!1};function co(n){return typeof n=="string"||typeof n=="number"||typeof n=="boolean"||typeof n=="symbol"||typeof n=="bigint"}var sn={};function gs(n,e,t,r,s,o,i,l,u,p,g,m,y,f,x,A,R,S){let C=n,U=S,O=0,X=!1;for(;(U=U.get(sn))!==void 0&&!X;){let T=U.get(n);if(O+=1,typeof T<"u"){if(T===O)throw new RangeError("Cyclic object value");X=!0}typeof U.get(sn)>"u"&&(O=0)}if(typeof p=="function"?C=p(e,C):C instanceof Date?C=y?.(C):t==="comma"&&W(C)&&(C=nn(C,function(T){return T instanceof Date?y?.(T):T})),C===null){if(o)return u&&!A?u(e,N.encoder,R,"key",f):e;C=""}if(co(C)||ps(C)){if(u){let T=A?e:u(e,N.encoder,R,"key",f);return[x?.(T)+"="+x?.(u(C,N.encoder,R,"value",f))]}return[x?.(e)+"="+x?.(String(C))]}let H=[];if(typeof C>"u")return H;let E;if(t==="comma"&&W(C))A&&u&&(C=nn(C,u)),E=[{value:C.length>0?C.join(",")||null:void 0}];else if(W(p))E=p;else{let T=Object.keys(C);E=g?T.sort(g):T}let D=l?String(e).replace(/\./g,"%2E"):String(e),j=r&&W(C)&&C.length===1?D+"[]":D;if(s&&W(C)&&C.length===0)return j+"[]";for(let T=0;T<E.length;++T){let k=E[T],Fn=typeof k=="object"&&typeof k.value<"u"?k.value:C[k];if(i&&Fn===null)continue;let Jr=m&&l?k.replace(/\./g,"%2E"):k,to=W(C)?typeof t=="function"?t(j,Jr):j:j+(m?"."+Jr:"["+Jr+"]");S.set(n,O);let Ln=new WeakMap;Ln.set(sn,S),hs(H,gs(Fn,to,t,r,s,o,i,l,t==="comma"&&A&&W(C)?null:u,p,g,m,y,f,x,A,R,Ln))}return H}function uo(n=N){if(typeof n.allowEmptyArrays<"u"&&typeof n.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof n.encodeDotInKeys<"u"&&typeof n.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(n.encoder!==null&&typeof n.encoder<"u"&&typeof n.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=n.charset||N.charset;if(typeof n.charset<"u"&&n.charset!=="utf-8"&&n.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=gr;if(typeof n.format<"u"){if(!br(_r,n.format))throw new TypeError("Unknown format option provided.");t=n.format}let r=_r[t],s=N.filter;(typeof n.filter=="function"||W(n.filter))&&(s=n.filter);let o;if(n.arrayFormat&&n.arrayFormat in ms?o=n.arrayFormat:"indices"in n?o=n.indices?"indices":"repeat":o=N.arrayFormat,"commaRoundTrip"in n&&typeof n.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let i=typeof n.allowDots>"u"?n.encodeDotInKeys?!0:N.allowDots:!!n.allowDots;return{addQueryPrefix:typeof n.addQueryPrefix=="boolean"?n.addQueryPrefix:N.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof n.allowEmptyArrays=="boolean"?!!n.allowEmptyArrays:N.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof n.charsetSentinel=="boolean"?n.charsetSentinel:N.charsetSentinel,commaRoundTrip:!!n.commaRoundTrip,delimiter:typeof n.delimiter>"u"?N.delimiter:n.delimiter,encode:typeof n.encode=="boolean"?n.encode:N.encode,encodeDotInKeys:typeof n.encodeDotInKeys=="boolean"?n.encodeDotInKeys:N.encodeDotInKeys,encoder:typeof n.encoder=="function"?n.encoder:N.encoder,encodeValuesOnly:typeof n.encodeValuesOnly=="boolean"?n.encodeValuesOnly:N.encodeValuesOnly,filter:s,format:t,formatter:r,serializeDate:typeof n.serializeDate=="function"?n.serializeDate:N.serializeDate,skipNulls:typeof n.skipNulls=="boolean"?n.skipNulls:N.skipNulls,sort:typeof n.sort=="function"?n.sort:null,strictNullHandling:typeof n.strictNullHandling=="boolean"?n.strictNullHandling:N.strictNullHandling}}function on(n,e={}){let t=n,r=uo(e),s,o;typeof r.filter=="function"?(o=r.filter,t=o("",t)):W(r.filter)&&(o=r.filter,s=o);let i=[];if(typeof t!="object"||t===null)return"";let l=ms[r.arrayFormat],u=l==="comma"&&r.commaRoundTrip;s||(s=Object.keys(t)),r.sort&&s.sort(r.sort);let p=new WeakMap;for(let y=0;y<s.length;++y){let f=s[y];r.skipNulls&&t[f]===null||hs(i,gs(t[f],f,l,u,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,p))}let g=i.join(r.delimiter),m=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?m+="utf8=%26%2310003%3B&":m+="utf8=%E2%9C%93&"),g.length>0?m+g:""}a();a();a();a();a();function ys(n){let e=0;for(let s of n)e+=s.length;let t=new Uint8Array(e),r=0;for(let s of n)t.set(s,r),r+=s.length;return t}var _s;function ht(n){let e;return(_s??(e=new globalThis.TextEncoder,_s=e.encode.bind(e)))(n)}var bs;function an(n){let e;return(bs??(e=new globalThis.TextDecoder,bs=e.decode.bind(e)))(n)}var J,V,Te=class{constructor(){J.set(this,void 0),V.set(this,void 0),w(this,J,new Uint8Array,"f"),w(this,V,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?ht(e):e;w(this,J,ys([c(this,J,"f"),t]),"f");let r=[],s;for(;(s=po(c(this,J,"f"),c(this,V,"f")))!=null;){if(s.carriage&&c(this,V,"f")==null){w(this,V,s.index,"f");continue}if(c(this,V,"f")!=null&&(s.index!==c(this,V,"f")+1||s.carriage)){r.push(an(c(this,J,"f").subarray(0,c(this,V,"f")-1))),w(this,J,c(this,J,"f").subarray(c(this,V,"f")),"f"),w(this,V,null,"f");continue}let o=c(this,V,"f")!==null?s.preceding-1:s.preceding,i=an(c(this,J,"f").subarray(0,o));r.push(i),w(this,J,c(this,J,"f").subarray(s.index),"f"),w(this,V,null,"f")}return r}flush(){return c(this,J,"f").length?this.decode(`
3
+ import{a as Kn}from"./chunk-QCIDUZV6.js";import{a as Jn,b as Vn,c as zn}from"./chunk-R6YTDM76.js";import{c as mr,f as ve}from"./chunk-S4K76QPI.js";import{a as jn,b as st,c as Gn}from"./chunk-FZBNVQAK.js";import{a as Vr,e as Bn,j as Wn,o as Hn,q as qn,s as Xn,t as dr}from"./chunk-LN2DRVOB.js";import{e as Dn}from"./chunk-4J6DC24J.js";import{b as zr}from"./chunk-ESSYHTAZ.js";import{Y as me,b as Un}from"./chunk-QWBNNEV2.js";import{b as a}from"./chunk-GZPNIYVZ.js";a();a();a();a();a();a();a();a();function w(n,e,t,r,s){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?s.call(n,t):s?s.value=t:e.set(n,t),t}function c(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)}a();var Kr=function(){let{crypto:n}=globalThis;if(n?.randomUUID)return Kr=n.randomUUID.bind(n),n.randomUUID();let e=new Uint8Array(1),t=n?()=>n.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^t()&15>>+r/4).toString(16))};a();a();a();function Ht(n){return typeof n=="object"&&n!==null&&("name"in n&&n.name==="AbortError"||"message"in n&&String(n.message).includes("FetchRequestCanceledException"))}var qt=n=>{if(n instanceof Error)return n;if(typeof n=="object"&&n!==null){try{if(Object.prototype.toString.call(n)==="[object Error]"){let e=new Error(n.message,n.cause?{cause:n.cause}:{});return n.stack&&(e.stack=n.stack),n.cause&&!e.cause&&(e.cause=n.cause),n.name&&(e.name=n.name),e}}catch{}try{return new Error(JSON.stringify(n))}catch{}}return new Error(n)};var b=class extends Error{},$=class n extends b{constructor(e,t,r,s){super(`${n.makeMessage(e,t,r)}`),this.status=e,this.headers=s,this.requestID=s?.get("x-request-id"),this.error=t;let o=t;this.code=o?.code,this.param=o?.param,this.type=o?.type}static makeMessage(e,t,r){let s=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,t,r,s){if(!e||!s)return new he({message:r,cause:qt(t)});let o=t?.error;return e===400?new ot(e,o,r,s):e===401?new it(e,o,r,s):e===403?new at(e,o,r,s):e===404?new lt(e,o,r,s):e===409?new ct(e,o,r,s):e===422?new ut(e,o,r,s):e===429?new ft(e,o,r,s):e>=500?new pt(e,o,r,s):new n(e,o,r,s)}},M=class extends ${constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},he=class extends ${constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},ge=class extends he{constructor({message:e}={}){super({message:e??"Request timed out."})}},ot=class extends ${},it=class extends ${},at=class extends ${},lt=class extends ${},ct=class extends ${},ut=class extends ${},ft=class extends ${},pt=class extends ${},dt=class extends b{constructor(){super("Could not parse response content as the length limit was reached")}},mt=class extends b{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},Z=class extends Error{constructor(e){super(e)}};var no=/^[a-z][a-z0-9+.-]*:/i,Qn=n=>no.test(n),W=n=>(W=Array.isArray,W(n)),Qr=W;function Yn(n){return typeof n!="object"?{}:n??{}}function Zn(n){if(!n)return!0;for(let e in n)return!1;return!0}function es(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function Xt(n){return n!=null&&typeof n=="object"&&!Array.isArray(n)}var ts=(n,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new b(`${n} must be an integer`);if(e<0)throw new b(`${n} must be a positive integer`);return e};var rs=n=>{try{return JSON.parse(n)}catch{return}};a();var ee=n=>new Promise(e=>setTimeout(e,n));a();a();var _e="5.11.0";var is=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function so(){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 oo=()=>{let n=so();if(n==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":ss(Deno.build.os),"X-Stainless-Arch":ns(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":_e,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(n==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":ss(globalThis.process.platform??"unknown"),"X-Stainless-Arch":ns(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=io();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"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":_e,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function io(){if(typeof navigator>"u"||!navigator)return null;let n=[{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 n){let r=t.exec(navigator.userAgent);if(r){let s=r[1]||0,o=r[2]||0,i=r[3]||0;return{browser:e,version:`${s}.${o}.${i}`}}}return null}var ns=n=>n==="x32"?"x32":n==="x86_64"||n==="x64"?"x64":n==="arm"?"arm":n==="aarch64"||n==="arm64"?"arm64":n?`other:${n}`:"unknown",ss=n=>(n=n.toLowerCase(),n.includes("ios")?"iOS":n==="android"?"Android":n==="darwin"?"MacOS":n==="win32"?"Windows":n==="freebsd"?"FreeBSD":n==="openbsd"?"OpenBSD":n==="linux"?"Linux":n?`Other:${n}`:"Unknown"),os,as=()=>os??(os=oo());a();function ls(){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 Yr(...n){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(...n)}function hr(n){let e=Symbol.asyncIterator in n?n[Symbol.asyncIterator]():n[Symbol.iterator]();return Yr({start(){},async pull(t){let{done:r,value:s}=await e.next();r?t.close():t.enqueue(s)},async cancel(){await e.return?.()}})}function Zr(n){if(n[Symbol.asyncIterator])return n;let e=n.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 cs(n){if(n===null||typeof n!="object")return;if(n[Symbol.asyncIterator]){await n[Symbol.asyncIterator]().return?.();return}let e=n.getReader(),t=e.cancel();e.releaseLock(),await t}a();var us=({headers:n,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});a();a();var gr="RFC3986",en=n=>String(n),_r={RFC1738:n=>String(n).replace(/%20/g,"+"),RFC3986:en},tn="RFC1738";a();a();var br=(n,e)=>(br=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),br(n,e)),te=(()=>{let n=[];for(let e=0;e<256;++e)n.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return n})();var rn=1024,fs=(n,e,t,r,s)=>{if(n.length===0)return n;let o=n;if(typeof n=="symbol"?o=Symbol.prototype.toString.call(n):typeof n!="string"&&(o=String(n)),t==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(l){return"%26%23"+parseInt(l.slice(2),16)+"%3B"});let i="";for(let l=0;l<o.length;l+=rn){let u=o.length>=rn?o.slice(l,l+rn):o,d=[];for(let g=0;g<u.length;++g){let p=u.charCodeAt(g);if(p===45||p===46||p===95||p===126||p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122||s===tn&&(p===40||p===41)){d[d.length]=u.charAt(g);continue}if(p<128){d[d.length]=te[p];continue}if(p<2048){d[d.length]=te[192|p>>6]+te[128|p&63];continue}if(p<55296||p>=57344){d[d.length]=te[224|p>>12]+te[128|p>>6&63]+te[128|p&63];continue}g+=1,p=65536+((p&1023)<<10|u.charCodeAt(g)&1023),d[d.length]=te[240|p>>18]+te[128|p>>12&63]+te[128|p>>6&63]+te[128|p&63]}i+=d.join("")}return i};function ps(n){return!n||typeof n!="object"?!1:!!(n.constructor&&n.constructor.isBuffer&&n.constructor.isBuffer(n))}function nn(n,e){if(W(n)){let t=[];for(let r=0;r<n.length;r+=1)t.push(e(n[r]));return t}return e(n)}var ms={brackets(n){return String(n)+"[]"},comma:"comma",indices(n,e){return String(n)+"["+e+"]"},repeat(n){return String(n)}},hs=function(n,e){Array.prototype.push.apply(n,W(e)?e:[e])},ds,N={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:fs,encodeValuesOnly:!1,format:gr,formatter:en,indices:!1,serializeDate(n){return(ds??(ds=Function.prototype.call.bind(Date.prototype.toISOString)))(n)},skipNulls:!1,strictNullHandling:!1};function co(n){return typeof n=="string"||typeof n=="number"||typeof n=="boolean"||typeof n=="symbol"||typeof n=="bigint"}var sn={};function gs(n,e,t,r,s,o,i,l,u,d,g,p,y,f,x,A,R,S){let C=n,U=S,O=0,X=!1;for(;(U=U.get(sn))!==void 0&&!X;){let T=U.get(n);if(O+=1,typeof T<"u"){if(T===O)throw new RangeError("Cyclic object value");X=!0}typeof U.get(sn)>"u"&&(O=0)}if(typeof d=="function"?C=d(e,C):C instanceof Date?C=y?.(C):t==="comma"&&W(C)&&(C=nn(C,function(T){return T instanceof Date?y?.(T):T})),C===null){if(o)return u&&!A?u(e,N.encoder,R,"key",f):e;C=""}if(co(C)||ps(C)){if(u){let T=A?e:u(e,N.encoder,R,"key",f);return[x?.(T)+"="+x?.(u(C,N.encoder,R,"value",f))]}return[x?.(e)+"="+x?.(String(C))]}let H=[];if(typeof C>"u")return H;let E;if(t==="comma"&&W(C))A&&u&&(C=nn(C,u)),E=[{value:C.length>0?C.join(",")||null:void 0}];else if(W(d))E=d;else{let T=Object.keys(C);E=g?T.sort(g):T}let D=l?String(e).replace(/\./g,"%2E"):String(e),j=r&&W(C)&&C.length===1?D+"[]":D;if(s&&W(C)&&C.length===0)return j+"[]";for(let T=0;T<E.length;++T){let k=E[T],Fn=typeof k=="object"&&typeof k.value<"u"?k.value:C[k];if(i&&Fn===null)continue;let Jr=p&&l?k.replace(/\./g,"%2E"):k,to=W(C)?typeof t=="function"?t(j,Jr):j:j+(p?"."+Jr:"["+Jr+"]");S.set(n,O);let Ln=new WeakMap;Ln.set(sn,S),hs(H,gs(Fn,to,t,r,s,o,i,l,t==="comma"&&A&&W(C)?null:u,d,g,p,y,f,x,A,R,Ln))}return H}function uo(n=N){if(typeof n.allowEmptyArrays<"u"&&typeof n.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof n.encodeDotInKeys<"u"&&typeof n.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(n.encoder!==null&&typeof n.encoder<"u"&&typeof n.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=n.charset||N.charset;if(typeof n.charset<"u"&&n.charset!=="utf-8"&&n.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=gr;if(typeof n.format<"u"){if(!br(_r,n.format))throw new TypeError("Unknown format option provided.");t=n.format}let r=_r[t],s=N.filter;(typeof n.filter=="function"||W(n.filter))&&(s=n.filter);let o;if(n.arrayFormat&&n.arrayFormat in ms?o=n.arrayFormat:"indices"in n?o=n.indices?"indices":"repeat":o=N.arrayFormat,"commaRoundTrip"in n&&typeof n.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let i=typeof n.allowDots>"u"?n.encodeDotInKeys?!0:N.allowDots:!!n.allowDots;return{addQueryPrefix:typeof n.addQueryPrefix=="boolean"?n.addQueryPrefix:N.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof n.allowEmptyArrays=="boolean"?!!n.allowEmptyArrays:N.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof n.charsetSentinel=="boolean"?n.charsetSentinel:N.charsetSentinel,commaRoundTrip:!!n.commaRoundTrip,delimiter:typeof n.delimiter>"u"?N.delimiter:n.delimiter,encode:typeof n.encode=="boolean"?n.encode:N.encode,encodeDotInKeys:typeof n.encodeDotInKeys=="boolean"?n.encodeDotInKeys:N.encodeDotInKeys,encoder:typeof n.encoder=="function"?n.encoder:N.encoder,encodeValuesOnly:typeof n.encodeValuesOnly=="boolean"?n.encodeValuesOnly:N.encodeValuesOnly,filter:s,format:t,formatter:r,serializeDate:typeof n.serializeDate=="function"?n.serializeDate:N.serializeDate,skipNulls:typeof n.skipNulls=="boolean"?n.skipNulls:N.skipNulls,sort:typeof n.sort=="function"?n.sort:null,strictNullHandling:typeof n.strictNullHandling=="boolean"?n.strictNullHandling:N.strictNullHandling}}function on(n,e={}){let t=n,r=uo(e),s,o;typeof r.filter=="function"?(o=r.filter,t=o("",t)):W(r.filter)&&(o=r.filter,s=o);let i=[];if(typeof t!="object"||t===null)return"";let l=ms[r.arrayFormat],u=l==="comma"&&r.commaRoundTrip;s||(s=Object.keys(t)),r.sort&&s.sort(r.sort);let d=new WeakMap;for(let y=0;y<s.length;++y){let f=s[y];r.skipNulls&&t[f]===null||hs(i,gs(t[f],f,l,u,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,d))}let g=i.join(r.delimiter),p=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?p+="utf8=%26%2310003%3B&":p+="utf8=%E2%9C%93&"),g.length>0?p+g:""}a();a();a();a();a();function ys(n){let e=0;for(let s of n)e+=s.length;let t=new Uint8Array(e),r=0;for(let s of n)t.set(s,r),r+=s.length;return t}var _s;function ht(n){let e;return(_s??(e=new globalThis.TextEncoder,_s=e.encode.bind(e)))(n)}var bs;function an(n){let e;return(bs??(e=new globalThis.TextDecoder,bs=e.decode.bind(e)))(n)}var J,V,Te=class{constructor(){J.set(this,void 0),V.set(this,void 0),w(this,J,new Uint8Array,"f"),w(this,V,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?ht(e):e;w(this,J,ys([c(this,J,"f"),t]),"f");let r=[],s;for(;(s=po(c(this,J,"f"),c(this,V,"f")))!=null;){if(s.carriage&&c(this,V,"f")==null){w(this,V,s.index,"f");continue}if(c(this,V,"f")!=null&&(s.index!==c(this,V,"f")+1||s.carriage)){r.push(an(c(this,J,"f").subarray(0,c(this,V,"f")-1))),w(this,J,c(this,J,"f").subarray(c(this,V,"f")),"f"),w(this,V,null,"f");continue}let o=c(this,V,"f")!==null?s.preceding-1:s.preceding,i=an(c(this,J,"f").subarray(0,o));r.push(i),w(this,J,c(this,J,"f").subarray(s.index),"f"),w(this,V,null,"f")}return r}flush(){return c(this,J,"f").length?this.decode(`
4
4
  `):[]}};J=new WeakMap,V=new WeakMap;Te.NEWLINE_CHARS=new Set([`
5
- `,"\r"]);Te.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function po(n,e){for(let s=e??0;s<n.length;s++){if(n[s]===10)return{preceding:s,index:s+1,carriage:!1};if(n[s]===13)return{preceding:s,index:s+1,carriage:!0}}return null}function Cs(n){for(let r=0;r<n.length-1;r++){if(n[r]===10&&n[r+1]===10||n[r]===13&&n[r+1]===13)return r+2;if(n[r]===13&&n[r+1]===10&&r+3<n.length&&n[r+2]===13&&n[r+3]===10)return r+4}return-1}a();var Cr={off:0,error:200,warn:300,info:400,debug:500},ln=(n,e,t)=>{if(n){if(es(Cr,n))return n;v(t).warn(`${e} was set to ${JSON.stringify(n)}, expected one of ${JSON.stringify(Object.keys(Cr))}`)}};function Jt(){}function yr(n,e,t){return!e||Cr[n]>Cr[t]?Jt:e[n].bind(e)}var mo={error:Jt,warn:Jt,info:Jt,debug:Jt},ws=new WeakMap;function v(n){let e=n.logger,t=n.logLevel??"off";if(!e)return mo;let r=ws.get(e);if(r&&r[0]===t)return r[1];let s={error:yr("error",e,t),warn:yr("warn",e,t),info:yr("info",e,t),debug:yr("debug",e,t)};return ws.set(e,[t,s]),s}var ae=n=>(n.options&&(n.options={...n.options},delete n.options.headers),n.headers&&(n.headers=Object.fromEntries((n.headers instanceof Headers?[...n.headers]:Object.entries(n.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in n&&(n.retryOfRequestLogID&&(n.retryOf=n.retryOfRequestLogID),delete n.retryOfRequestLogID),n);var Vt,re=class n{constructor(e,t,r){this.iterator=e,Vt.set(this,void 0),this.controller=t,w(this,Vt,r,"f")}static fromSSEResponse(e,t,r){let s=!1,o=r?v(r):console;async function*i(){if(s)throw new b("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let l=!1;try{for await(let u of ho(e,t))if(!l){if(u.data.startsWith("[DONE]")){l=!0;continue}if(u.event===null||!u.event.startsWith("thread.")){let p;try{p=JSON.parse(u.data)}catch(g){throw o.error("Could not parse message into JSON:",u.data),o.error("From chunk:",u.raw),g}if(p&&p.error)throw new $(void 0,p.error,void 0,e.headers);yield p}else{let p;try{p=JSON.parse(u.data)}catch(g){throw console.error("Could not parse message into JSON:",u.data),console.error("From chunk:",u.raw),g}if(u.event=="error")throw new $(void 0,p.error,p.message,void 0);yield{event:u.event,data:p}}}l=!0}catch(u){if(Ht(u))return;throw u}finally{l||t.abort()}}return new n(i,t,r)}static fromReadableStream(e,t,r){let s=!1;async function*o(){let l=new Te,u=Zr(e);for await(let p of u)for(let g of l.decode(p))yield g;for(let p of l.flush())yield p}async function*i(){if(s)throw new b("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let l=!1;try{for await(let u of o())l||u&&(yield JSON.parse(u));l=!0}catch(u){if(Ht(u))return;throw u}finally{l||t.abort()}}return new n(i,t,r)}[(Vt=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),s=o=>({next:()=>{if(o.length===0){let i=r.next();e.push(i),t.push(i)}return o.shift()}});return[new n(()=>s(e),this.controller,c(this,Vt,"f")),new n(()=>s(t),this.controller,c(this,Vt,"f"))]}toReadableStream(){let e=this,t;return Yr({async start(){t=e[Symbol.asyncIterator]()},async pull(r){try{let{value:s,done:o}=await t.next();if(o)return r.close();let i=ht(JSON.stringify(s)+`
5
+ `,"\r"]);Te.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function po(n,e){for(let s=e??0;s<n.length;s++){if(n[s]===10)return{preceding:s,index:s+1,carriage:!1};if(n[s]===13)return{preceding:s,index:s+1,carriage:!0}}return null}function Cs(n){for(let r=0;r<n.length-1;r++){if(n[r]===10&&n[r+1]===10||n[r]===13&&n[r+1]===13)return r+2;if(n[r]===13&&n[r+1]===10&&r+3<n.length&&n[r+2]===13&&n[r+3]===10)return r+4}return-1}a();var Cr={off:0,error:200,warn:300,info:400,debug:500},ln=(n,e,t)=>{if(n){if(es(Cr,n))return n;v(t).warn(`${e} was set to ${JSON.stringify(n)}, expected one of ${JSON.stringify(Object.keys(Cr))}`)}};function Jt(){}function yr(n,e,t){return!e||Cr[n]>Cr[t]?Jt:e[n].bind(e)}var mo={error:Jt,warn:Jt,info:Jt,debug:Jt},ws=new WeakMap;function v(n){let e=n.logger,t=n.logLevel??"off";if(!e)return mo;let r=ws.get(e);if(r&&r[0]===t)return r[1];let s={error:yr("error",e,t),warn:yr("warn",e,t),info:yr("info",e,t),debug:yr("debug",e,t)};return ws.set(e,[t,s]),s}var ae=n=>(n.options&&(n.options={...n.options},delete n.options.headers),n.headers&&(n.headers=Object.fromEntries((n.headers instanceof Headers?[...n.headers]:Object.entries(n.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in n&&(n.retryOfRequestLogID&&(n.retryOf=n.retryOfRequestLogID),delete n.retryOfRequestLogID),n);var Vt,re=class n{constructor(e,t,r){this.iterator=e,Vt.set(this,void 0),this.controller=t,w(this,Vt,r,"f")}static fromSSEResponse(e,t,r){let s=!1,o=r?v(r):console;async function*i(){if(s)throw new b("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let l=!1;try{for await(let u of ho(e,t))if(!l){if(u.data.startsWith("[DONE]")){l=!0;continue}if(u.event===null||!u.event.startsWith("thread.")){let d;try{d=JSON.parse(u.data)}catch(g){throw o.error("Could not parse message into JSON:",u.data),o.error("From chunk:",u.raw),g}if(d&&d.error)throw new $(void 0,d.error,void 0,e.headers);yield d}else{let d;try{d=JSON.parse(u.data)}catch(g){throw console.error("Could not parse message into JSON:",u.data),console.error("From chunk:",u.raw),g}if(u.event=="error")throw new $(void 0,d.error,d.message,void 0);yield{event:u.event,data:d}}}l=!0}catch(u){if(Ht(u))return;throw u}finally{l||t.abort()}}return new n(i,t,r)}static fromReadableStream(e,t,r){let s=!1;async function*o(){let l=new Te,u=Zr(e);for await(let d of u)for(let g of l.decode(d))yield g;for(let d of l.flush())yield d}async function*i(){if(s)throw new b("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let l=!1;try{for await(let u of o())l||u&&(yield JSON.parse(u));l=!0}catch(u){if(Ht(u))return;throw u}finally{l||t.abort()}}return new n(i,t,r)}[(Vt=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),s=o=>({next:()=>{if(o.length===0){let i=r.next();e.push(i),t.push(i)}return o.shift()}});return[new n(()=>s(e),this.controller,c(this,Vt,"f")),new n(()=>s(t),this.controller,c(this,Vt,"f"))]}toReadableStream(){let e=this,t;return Yr({async start(){t=e[Symbol.asyncIterator]()},async pull(r){try{let{value:s,done:o}=await t.next();if(o)return r.close();let i=ht(JSON.stringify(s)+`
6
6
  `);r.enqueue(i)}catch(s){r.error(s)}},async cancel(){await t.return?.()}})}};async function*ho(n,e){if(!n.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new b("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 b("Attempted to iterate over a response with no body");let t=new cn,r=new Te,s=Zr(n.body);for await(let o of go(s))for(let i of r.decode(o)){let l=t.decode(i);l&&(yield l)}for(let o of r.flush()){let i=t.decode(o);i&&(yield i)}}async function*go(n){let e=new Uint8Array;for await(let t of n){if(t==null)continue;let r=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?ht(t):t,s=new Uint8Array(e.length+r.length);s.set(e),s.set(r,e.length),e=s;let o;for(;(o=Cs(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var cn=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 o={event:this.event,data:this.data.join(`
7
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,s]=_o(e,":");return s.startsWith(" ")&&(s=s.substring(1)),t==="event"?this.event=s:t==="data"&&this.data.push(s),null}};function _o(n,e){let t=n.indexOf(e);return t!==-1?[n.substring(0,t),e,n.substring(t+e.length)]:[n,"",""]}async function wr(n,e){let{response:t,requestLogID:r,retryOfRequestLogID:s,startTime:o}=e,i=await(async()=>{if(e.options.stream)return v(n).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,n):re.fromSSEResponse(t,e.controller,n);if(t.status===204)return null;if(e.options.__binaryResponse)return t;let u=t.headers.get("content-type")?.split(";")[0]?.trim();if(u?.includes("application/json")||u?.endsWith("+json")){let m=await t.json();return un(m,t)}return await t.text()})();return v(n).debug(`[${r}] response parsed`,ae({retryOfRequestLogID:s,url:t.url,status:t.status,body:i,durationMs:Date.now()-o})),i}function un(n,e){return!n||typeof n!="object"||Array.isArray(n)?n:Object.defineProperty(n,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}a();var zt,Me=class n extends Promise{constructor(e,t,r=wr){super(s=>{s(null)}),this.responsePromise=t,this.parseResponse=r,zt.set(this,void 0),w(this,zt,e,"f")}_thenUnwrap(e){return new n(c(this,zt,"f"),this.responsePromise,async(t,r)=>un(e(await this.parseResponse(t,r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(c(this,zt,"f"),e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};zt=new WeakMap;var Ar,xr=class{constructor(e,t,r,s){Ar.set(this,void 0),w(this,Ar,e,"f"),this.options=s,this.response=t,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new b("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await c(this,Ar,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Ar=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},Kt=class extends Me{constructor(e,t,r){super(e,t,async(s,o)=>new r(s,o.response,await wr(s,o),o.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},ne=class extends xr{constructor(e,t,r,s){super(e,t,r,s),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},P=class extends xr{constructor(e,t,r,s){super(e,t,r,s),this.data=r.data||[],this.has_more=r.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...Yn(this.options.query),after:t}}:null}};a();a();a();var pn=()=>{if(typeof File>"u"){let{process:n}=globalThis,e=typeof n?.versions?.node=="string"&&parseInt(n.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function gt(n,e,t){return pn(),new File(n,e??"unknown_file",t)}function Qt(n){return(typeof n=="object"&&n!==null&&("name"in n&&n.name&&String(n.name)||"url"in n&&n.url&&String(n.url)||"filename"in n&&n.filename&&String(n.filename)||"path"in n&&n.path&&String(n.path))||"").split(/[\\/]/).pop()||void 0}var dn=n=>n!=null&&typeof n=="object"&&typeof n[Symbol.asyncIterator]=="function";var z=async(n,e)=>({...n,body:await Co(n.body,e)}),As=new WeakMap;function yo(n){let e=typeof n=="function"?n:n.fetch,t=As.get(e);if(t)return t;let r=(async()=>{try{let s="Response"in e?e.Response:(await e("data:,")).constructor,o=new FormData;return o.toString()!==await new s(o).text()}catch{return!0}})();return As.set(e,r),r}var Co=async(n,e)=>{if(!await yo(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let t=new FormData;return await Promise.all(Object.entries(n||{}).map(([r,s])=>fn(t,r,s))),t},wo=n=>n instanceof Blob&&"name"in n;var fn=async(n,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")n.append(e,String(t));else if(t instanceof Response)n.append(e,gt([await t.blob()],Qt(t)));else if(dn(t))n.append(e,gt([await new Response(hr(t)).blob()],Qt(t)));else if(wo(t))n.append(e,t,Qt(t));else if(Array.isArray(t))await Promise.all(t.map(r=>fn(n,e+"[]",r)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([r,s])=>fn(n,`${e}[${r}]`,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}};var xs=n=>n!=null&&typeof n=="object"&&typeof n.size=="number"&&typeof n.type=="string"&&typeof n.text=="function"&&typeof n.slice=="function"&&typeof n.arrayBuffer=="function",Ao=n=>n!=null&&typeof n=="object"&&typeof n.name=="string"&&typeof n.lastModified=="number"&&xs(n),xo=n=>n!=null&&typeof n=="object"&&typeof n.url=="string"&&typeof n.blob=="function";async function Ir(n,e,t){if(pn(),n=await n,Ao(n))return n instanceof File?n:gt([await n.arrayBuffer()],n.name);if(xo(n)){let s=await n.blob();return e||(e=new URL(n.url).pathname.split(/[\\/]/).pop()),gt(await mn(s),e,t)}let r=await mn(n);if(e||(e=Qt(n)),!t?.type){let s=r.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof s=="string"&&(t={...t,type:s})}return gt(r,e,t)}async function mn(n){let e=[];if(typeof n=="string"||ArrayBuffer.isView(n)||n instanceof ArrayBuffer)e.push(n);else if(xs(n))e.push(n instanceof Blob?n:await n.arrayBuffer());else if(dn(n))for await(let t of n)e.push(...await mn(t));else{let t=n?.constructor?.name;throw new Error(`Unexpected data type: ${typeof n}${t?`; constructor: ${t}`:""}${Io(n)}`)}return e}function Io(n){return typeof n!="object"||n===null?"":`; props: [${Object.getOwnPropertyNames(n).map(t=>`"${t}"`).join(", ")}]`}a();a();a();a();var h=class{constructor(e){this._client=e}};a();a();a();function Ps(n){return n.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var Is=Object.freeze(Object.create(null)),Ro=(n=Ps)=>function(t,...r){if(t.length===1)return t[0];let s=!1,o=[],i=t.reduce((g,m,y)=>{/[?#]/.test(m)&&(s=!0);let f=r[y],x=(s?encodeURIComponent:n)(""+f);return y!==r.length&&(f==null||typeof f=="object"&&f.toString===Object.getPrototypeOf(Object.getPrototypeOf(f.hasOwnProperty??Is)??Is)?.toString)&&(x=f+"",o.push({start:g.length+m.length,length:x.length,error:`Value of type ${Object.prototype.toString.call(f).slice(8,-1)} is not a valid path parameter`})),g+m+(y===r.length?"":x)},""),l=i.split(/[?#]/,1)[0],u=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,p;for(;(p=u.exec(l))!==null;)o.push({start:p.index,length:p[0].length,error:`Value "${p[0]}" can't be safely passed as a path parameter`});if(o.sort((g,m)=>g.start-m.start),o.length>0){let g=0,m=o.reduce((y,f)=>{let x=" ".repeat(f.start-g),A="^".repeat(f.length);return g=f.start+f.length,y+x+A},"");throw new b(`Path parameters result in path with invalid segments:
7
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,s]=_o(e,":");return s.startsWith(" ")&&(s=s.substring(1)),t==="event"?this.event=s:t==="data"&&this.data.push(s),null}};function _o(n,e){let t=n.indexOf(e);return t!==-1?[n.substring(0,t),e,n.substring(t+e.length)]:[n,"",""]}async function wr(n,e){let{response:t,requestLogID:r,retryOfRequestLogID:s,startTime:o}=e,i=await(async()=>{if(e.options.stream)return v(n).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,n):re.fromSSEResponse(t,e.controller,n);if(t.status===204)return null;if(e.options.__binaryResponse)return t;let u=t.headers.get("content-type")?.split(";")[0]?.trim();if(u?.includes("application/json")||u?.endsWith("+json")){let p=await t.json();return un(p,t)}return await t.text()})();return v(n).debug(`[${r}] response parsed`,ae({retryOfRequestLogID:s,url:t.url,status:t.status,body:i,durationMs:Date.now()-o})),i}function un(n,e){return!n||typeof n!="object"||Array.isArray(n)?n:Object.defineProperty(n,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}a();var zt,Me=class n extends Promise{constructor(e,t,r=wr){super(s=>{s(null)}),this.responsePromise=t,this.parseResponse=r,zt.set(this,void 0),w(this,zt,e,"f")}_thenUnwrap(e){return new n(c(this,zt,"f"),this.responsePromise,async(t,r)=>un(e(await this.parseResponse(t,r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(c(this,zt,"f"),e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};zt=new WeakMap;var Ar,xr=class{constructor(e,t,r,s){Ar.set(this,void 0),w(this,Ar,e,"f"),this.options=s,this.response=t,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new b("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await c(this,Ar,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Ar=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},Kt=class extends Me{constructor(e,t,r){super(e,t,async(s,o)=>new r(s,o.response,await wr(s,o),o.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},ne=class extends xr{constructor(e,t,r,s){super(e,t,r,s),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},P=class extends xr{constructor(e,t,r,s){super(e,t,r,s),this.data=r.data||[],this.has_more=r.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...Yn(this.options.query),after:t}}:null}};a();a();a();var pn=()=>{if(typeof File>"u"){let{process:n}=globalThis,e=typeof n?.versions?.node=="string"&&parseInt(n.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function gt(n,e,t){return pn(),new File(n,e??"unknown_file",t)}function Qt(n){return(typeof n=="object"&&n!==null&&("name"in n&&n.name&&String(n.name)||"url"in n&&n.url&&String(n.url)||"filename"in n&&n.filename&&String(n.filename)||"path"in n&&n.path&&String(n.path))||"").split(/[\\/]/).pop()||void 0}var dn=n=>n!=null&&typeof n=="object"&&typeof n[Symbol.asyncIterator]=="function";var z=async(n,e)=>({...n,body:await Co(n.body,e)}),As=new WeakMap;function yo(n){let e=typeof n=="function"?n:n.fetch,t=As.get(e);if(t)return t;let r=(async()=>{try{let s="Response"in e?e.Response:(await e("data:,")).constructor,o=new FormData;return o.toString()!==await new s(o).text()}catch{return!0}})();return As.set(e,r),r}var Co=async(n,e)=>{if(!await yo(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let t=new FormData;return await Promise.all(Object.entries(n||{}).map(([r,s])=>fn(t,r,s))),t},wo=n=>n instanceof Blob&&"name"in n;var fn=async(n,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")n.append(e,String(t));else if(t instanceof Response)n.append(e,gt([await t.blob()],Qt(t)));else if(dn(t))n.append(e,gt([await new Response(hr(t)).blob()],Qt(t)));else if(wo(t))n.append(e,t,Qt(t));else if(Array.isArray(t))await Promise.all(t.map(r=>fn(n,e+"[]",r)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([r,s])=>fn(n,`${e}[${r}]`,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}};var xs=n=>n!=null&&typeof n=="object"&&typeof n.size=="number"&&typeof n.type=="string"&&typeof n.text=="function"&&typeof n.slice=="function"&&typeof n.arrayBuffer=="function",Ao=n=>n!=null&&typeof n=="object"&&typeof n.name=="string"&&typeof n.lastModified=="number"&&xs(n),xo=n=>n!=null&&typeof n=="object"&&typeof n.url=="string"&&typeof n.blob=="function";async function Ir(n,e,t){if(pn(),n=await n,Ao(n))return n instanceof File?n:gt([await n.arrayBuffer()],n.name);if(xo(n)){let s=await n.blob();return e||(e=new URL(n.url).pathname.split(/[\\/]/).pop()),gt(await mn(s),e,t)}let r=await mn(n);if(e||(e=Qt(n)),!t?.type){let s=r.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof s=="string"&&(t={...t,type:s})}return gt(r,e,t)}async function mn(n){let e=[];if(typeof n=="string"||ArrayBuffer.isView(n)||n instanceof ArrayBuffer)e.push(n);else if(xs(n))e.push(n instanceof Blob?n:await n.arrayBuffer());else if(dn(n))for await(let t of n)e.push(...await mn(t));else{let t=n?.constructor?.name;throw new Error(`Unexpected data type: ${typeof n}${t?`; constructor: ${t}`:""}${Io(n)}`)}return e}function Io(n){return typeof n!="object"||n===null?"":`; props: [${Object.getOwnPropertyNames(n).map(t=>`"${t}"`).join(", ")}]`}a();a();a();a();var h=class{constructor(e){this._client=e}};a();a();a();function Ps(n){return n.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var Is=Object.freeze(Object.create(null)),Ro=(n=Ps)=>function(t,...r){if(t.length===1)return t[0];let s=!1,o=[],i=t.reduce((g,p,y)=>{/[?#]/.test(p)&&(s=!0);let f=r[y],x=(s?encodeURIComponent:n)(""+f);return y!==r.length&&(f==null||typeof f=="object"&&f.toString===Object.getPrototypeOf(Object.getPrototypeOf(f.hasOwnProperty??Is)??Is)?.toString)&&(x=f+"",o.push({start:g.length+p.length,length:x.length,error:`Value of type ${Object.prototype.toString.call(f).slice(8,-1)} is not a valid path parameter`})),g+p+(y===r.length?"":x)},""),l=i.split(/[?#]/,1)[0],u=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,d;for(;(d=u.exec(l))!==null;)o.push({start:d.index,length:d[0].length,error:`Value "${d[0]}" can't be safely passed as a path parameter`});if(o.sort((g,p)=>g.start-p.start),o.length>0){let g=0,p=o.reduce((y,f)=>{let x=" ".repeat(f.start-g),A="^".repeat(f.length);return g=f.start+f.length,y+x+A},"");throw new b(`Path parameters result in path with invalid segments:
8
8
  ${o.map(y=>y.error).join(`
9
9
  `)}
10
10
  ${i}
11
- ${m}`)}return i},d=Ro(Ps);var ke=class extends h{list(e,t={},r){return this._client.getAPIList(d`/chat/completions/${e}/messages`,P,{query:t,...r})}};a();a();a();a();function Rs(n){return typeof n.parse=="function"}a();var _t=n=>n?.role==="assistant",hn=n=>n?.role==="tool";a();var gn,Pr,Rr,Yt,Zt,Sr,er,le,tr,Or,Er,bt,Ss,be=class{constructor(){gn.add(this),this.controller=new AbortController,Pr.set(this,void 0),Rr.set(this,()=>{}),Yt.set(this,()=>{}),Zt.set(this,void 0),Sr.set(this,()=>{}),er.set(this,()=>{}),le.set(this,{}),tr.set(this,!1),Or.set(this,!1),Er.set(this,!1),bt.set(this,!1),w(this,Pr,new Promise((e,t)=>{w(this,Rr,e,"f"),w(this,Yt,t,"f")}),"f"),w(this,Zt,new Promise((e,t)=>{w(this,Sr,e,"f"),w(this,er,t,"f")}),"f"),c(this,Pr,"f").catch(()=>{}),c(this,Zt,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},c(this,gn,"m",Ss).bind(this))},0)}_connected(){this.ended||(c(this,Rr,"f").call(this),this._emit("connect"))}get ended(){return c(this,tr,"f")}get errored(){return c(this,Or,"f")}get aborted(){return c(this,Er,"f")}abort(){this.controller.abort()}on(e,t){return(c(this,le,"f")[e]||(c(this,le,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=c(this,le,"f")[e];if(!r)return this;let s=r.findIndex(o=>o.listener===t);return s>=0&&r.splice(s,1),this}once(e,t){return(c(this,le,"f")[e]||(c(this,le,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{w(this,bt,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,t)})}async done(){w(this,bt,!0,"f"),await c(this,Zt,"f")}_emit(e,...t){if(c(this,tr,"f"))return;e==="end"&&(w(this,tr,!0,"f"),c(this,Sr,"f").call(this));let r=c(this,le,"f")[e];if(r&&(c(this,le,"f")[e]=r.filter(s=>!s.once),r.forEach(({listener:s})=>s(...t))),e==="abort"){let s=t[0];!c(this,bt,"f")&&!r?.length&&Promise.reject(s),c(this,Yt,"f").call(this,s),c(this,er,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=t[0];!c(this,bt,"f")&&!r?.length&&Promise.reject(s),c(this,Yt,"f").call(this,s),c(this,er,"f").call(this,s),this._emit("end")}}_emitFinal(){}};Pr=new WeakMap,Rr=new WeakMap,Yt=new WeakMap,Zt=new WeakMap,Sr=new WeakMap,er=new WeakMap,le=new WeakMap,tr=new WeakMap,Or=new WeakMap,Er=new WeakMap,bt=new WeakMap,gn=new WeakSet,Ss=function(e){if(w(this,Or,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new M),e instanceof M)return w(this,Er,!0,"f"),this._emit("abort",e);if(e instanceof b)return this._emit("error",e);if(e instanceof Error){let t=new b(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new b(String(e)))};a();function rr(n){return n?.$brand==="auto-parseable-response-format"}function $e(n){return n?.$brand==="auto-parseable-tool"}function Os(n,e){return!e||!_n(e)?{...n,choices:n.choices.map(t=>({...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:nr(n,e)}function nr(n,e){let t=n.choices.map(r=>{if(r.finish_reason==="length")throw new dt;if(r.finish_reason==="content_filter")throw new mt;return{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:r.message.tool_calls?.map(s=>vo(e,s))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?Eo(e,r.message.content):null}}});return{...n,choices:t}}function Eo(n,e){return n.response_format?.type!=="json_schema"?null:n.response_format?.type==="json_schema"?"$parseRaw"in n.response_format?n.response_format.$parseRaw(e):JSON.parse(e):null}function vo(n,e){let t=n.tools?.find(r=>r.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:$e(t)?t.$parseRaw(e.function.arguments):t?.function.strict?JSON.parse(e.function.arguments):null}}}function Es(n,e){if(!n)return!1;let t=n.tools?.find(r=>r.function?.name===e.function.name);return $e(t)||t?.function.strict||!1}function _n(n){return rr(n.response_format)?!0:n.tools?.some(e=>$e(e)||e.type==="function"&&e.function.strict===!0)??!1}function vs(n){for(let e of n??[]){if(e.type!=="function")throw new b(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new b(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var q,bn,vr,yn,Cn,wn,Ts,Ms,To=10,yt=class extends be{constructor(){super(...arguments),q.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);let t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t){if(this._emit("message",e),hn(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(_t(e)&&e.tool_calls)for(let r of e.tool_calls)r.type==="function"&&this._emit("functionToolCall",r.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new b("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),c(this,q,"m",bn).call(this)}async finalMessage(){return await this.done(),c(this,q,"m",vr).call(this)}async finalFunctionToolCall(){return await this.done(),c(this,q,"m",yn).call(this)}async finalFunctionToolCallResult(){return await this.done(),c(this,q,"m",Cn).call(this)}async totalUsage(){return await this.done(),c(this,q,"m",wn).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let t=c(this,q,"m",vr).call(this);t&&this._emit("finalMessage",t);let r=c(this,q,"m",bn).call(this);r&&this._emit("finalContent",r);let s=c(this,q,"m",yn).call(this);s&&this._emit("finalFunctionToolCall",s);let o=c(this,q,"m",Cn).call(this);o!=null&&this._emit("finalFunctionToolCallResult",o),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",c(this,q,"m",wn).call(this))}async _createChatCompletion(e,t,r){let s=r?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),c(this,q,"m",Ts).call(this,t);let o=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(nr(o,t))}async _runChatCompletion(e,t,r){for(let s of t.messages)this._addMessage(s,!1);return await this._createChatCompletion(e,t,r)}async _runTools(e,t,r){let s="tool",{tool_choice:o="auto",stream:i,...l}=t,u=typeof o!="string"&&o?.function?.name,{maxChatCompletions:p=To}=r||{},g=t.tools.map(f=>{if($e(f)){if(!f.$callback)throw new b("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:f.$callback,name:f.function.name,description:f.function.description||"",parameters:f.function.parameters,parse:f.$parseRaw,strict:!0}}}return f}),m={};for(let f of g)f.type==="function"&&(m[f.function.name||f.function.function.name]=f.function);let y="tools"in t?g.map(f=>f.type==="function"?{type:"function",function:{name:f.function.name||f.function.function.name,parameters:f.function.parameters,description:f.function.description,strict:f.function.strict}}:f):void 0;for(let f of t.messages)this._addMessage(f,!1);for(let f=0;f<p;++f){let A=(await this._createChatCompletion(e,{...l,tool_choice:o,tools:y,messages:[...this.messages]},r)).choices[0]?.message;if(!A)throw new b("missing message in ChatCompletion response");if(!A.tool_calls?.length)return;for(let R of A.tool_calls){if(R.type!=="function")continue;let S=R.id,{name:C,arguments:U}=R.function,O=m[C];if(O){if(u&&u!==C){let D=`Invalid tool_call: ${JSON.stringify(C)}. ${JSON.stringify(u)} requested. Please try again`;this._addMessage({role:s,tool_call_id:S,content:D});continue}}else{let D=`Invalid tool_call: ${JSON.stringify(C)}. Available options are: ${Object.keys(m).map(j=>JSON.stringify(j)).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:S,content:D});continue}let X;try{X=Rs(O)?await O.parse(U):U}catch(D){let j=D instanceof Error?D.message:String(D);this._addMessage({role:s,tool_call_id:S,content:j});continue}let H=await O.function(X,this),E=c(this,q,"m",Ms).call(this,H);if(this._addMessage({role:s,tool_call_id:S,content:E}),u)return}}}};q=new WeakSet,bn=function(){return c(this,q,"m",vr).call(this).content??null},vr=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(_t(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new b("stream ended without producing a ChatCompletionMessage with role=assistant")},yn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(_t(t)&&t?.tool_calls?.length)return t.tool_calls.at(-1)?.function}},Cn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(hn(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(r=>r.role==="assistant"&&r.tool_calls?.some(s=>s.type==="function"&&s.id===t.tool_call_id)))return t.content}},wn=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},Ts=function(e){if(e.n!=null&&e.n>1)throw new b("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Ms=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var sr=class n extends yt{static runTools(e,t,r){let s=new n,o={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,o)),s}_addMessage(e,t=!0){super._addMessage(e,t),_t(e)&&e.content&&this._emit("content",e.content)}};a();a();a();a();var G={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511},An=class extends Error{},xn=class extends Error{};function Mo(n,e=G.ALL){if(typeof n!="string")throw new TypeError(`expecting str, got ${typeof n}`);if(!n.trim())throw new Error(`${n} is empty`);return ko(n.trim(),e)}var ko=(n,e)=>{let t=n.length,r=0,s=y=>{throw new An(`${y} at position ${r}`)},o=y=>{throw new xn(`${y} at position ${r}`)},i=()=>(m(),r>=t&&s("Unexpected end of input"),n[r]==='"'?l():n[r]==="{"?u():n[r]==="["?p():n.substring(r,r+4)==="null"||G.NULL&e&&t-r<4&&"null".startsWith(n.substring(r))?(r+=4,null):n.substring(r,r+4)==="true"||G.BOOL&e&&t-r<4&&"true".startsWith(n.substring(r))?(r+=4,!0):n.substring(r,r+5)==="false"||G.BOOL&e&&t-r<5&&"false".startsWith(n.substring(r))?(r+=5,!1):n.substring(r,r+8)==="Infinity"||G.INFINITY&e&&t-r<8&&"Infinity".startsWith(n.substring(r))?(r+=8,1/0):n.substring(r,r+9)==="-Infinity"||G.MINUS_INFINITY&e&&1<t-r&&t-r<9&&"-Infinity".startsWith(n.substring(r))?(r+=9,-1/0):n.substring(r,r+3)==="NaN"||G.NAN&e&&t-r<3&&"NaN".startsWith(n.substring(r))?(r+=3,NaN):g()),l=()=>{let y=r,f=!1;for(r++;r<t&&(n[r]!=='"'||f&&n[r-1]==="\\");)f=n[r]==="\\"?!f:!1,r++;if(n.charAt(r)=='"')try{return JSON.parse(n.substring(y,++r-Number(f)))}catch(x){o(String(x))}else if(G.STR&e)try{return JSON.parse(n.substring(y,r-Number(f))+'"')}catch{return JSON.parse(n.substring(y,n.lastIndexOf("\\"))+'"')}s("Unterminated string literal")},u=()=>{r++,m();let y={};try{for(;n[r]!=="}";){if(m(),r>=t&&G.OBJ&e)return y;let f=l();m(),r++;try{let x=i();Object.defineProperty(y,f,{value:x,writable:!0,enumerable:!0,configurable:!0})}catch(x){if(G.OBJ&e)return y;throw x}m(),n[r]===","&&r++}}catch{if(G.OBJ&e)return y;s("Expected '}' at end of object")}return r++,y},p=()=>{r++;let y=[];try{for(;n[r]!=="]";)y.push(i()),m(),n[r]===","&&r++}catch{if(G.ARR&e)return y;s("Expected ']' at end of array")}return r++,y},g=()=>{if(r===0){n==="-"&&G.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(n)}catch(f){if(G.NUM&e)try{return n[n.length-1]==="."?JSON.parse(n.substring(0,n.lastIndexOf("."))):JSON.parse(n.substring(0,n.lastIndexOf("e")))}catch{}o(String(f))}}let y=r;for(n[r]==="-"&&r++;n[r]&&!",]}".includes(n[r]);)r++;r==t&&!(G.NUM&e)&&s("Unterminated number literal");try{return JSON.parse(n.substring(y,r))}catch{n.substring(y,r)==="-"&&G.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(n.substring(y,n.lastIndexOf("e")))}catch(x){o(String(x))}}},m=()=>{for(;r<t&&`
12
- \r `.includes(n[r]);)r++};return i()},In=n=>Mo(n,G.ALL^G.NUM);var F,ce,Ct,ye,Pn,Tr,Rn,Sn,On,Mr,En,ks,Ne=class n extends yt{constructor(e){super(),F.add(this),ce.set(this,void 0),Ct.set(this,void 0),ye.set(this,void 0),w(this,ce,e,"f"),w(this,Ct,[],"f")}get currentChatCompletionSnapshot(){return c(this,ye,"f")}static fromReadableStream(e){let t=new n(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){let s=new n(t);return s._run(()=>s._runChatCompletion(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createChatCompletion(e,t,r){super._createChatCompletion;let s=r?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),c(this,F,"m",Pn).call(this);let o=await e.chat.completions.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let i of o)c(this,F,"m",Rn).call(this,i);if(o.controller.signal?.aborted)throw new M;return this._addChatCompletion(c(this,F,"m",Mr).call(this))}async _fromReadableStream(e,t){let r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),c(this,F,"m",Pn).call(this),this._connected();let s=re.fromReadableStream(e,this.controller),o;for await(let i of s)o&&o!==i.id&&this._addChatCompletion(c(this,F,"m",Mr).call(this)),c(this,F,"m",Rn).call(this,i),o=i.id;if(s.controller.signal?.aborted)throw new M;return this._addChatCompletion(c(this,F,"m",Mr).call(this))}[(ce=new WeakMap,Ct=new WeakMap,ye=new WeakMap,F=new WeakSet,Pn=function(){this.ended||w(this,ye,void 0,"f")},Tr=function(t){let r=c(this,Ct,"f")[t.index];return r||(r={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},c(this,Ct,"f")[t.index]=r,r)},Rn=function(t){if(this.ended)return;let r=c(this,F,"m",ks).call(this,t);this._emit("chunk",t,r);for(let s of t.choices){let o=r.choices[s.index];s.delta.content!=null&&o.message?.role==="assistant"&&o.message?.content&&(this._emit("content",s.delta.content,o.message.content),this._emit("content.delta",{delta:s.delta.content,snapshot:o.message.content,parsed:o.message.parsed})),s.delta.refusal!=null&&o.message?.role==="assistant"&&o.message?.refusal&&this._emit("refusal.delta",{delta:s.delta.refusal,snapshot:o.message.refusal}),s.logprobs?.content!=null&&o.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:s.logprobs?.content,snapshot:o.logprobs?.content??[]}),s.logprobs?.refusal!=null&&o.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:s.logprobs?.refusal,snapshot:o.logprobs?.refusal??[]});let i=c(this,F,"m",Tr).call(this,o);o.finish_reason&&(c(this,F,"m",On).call(this,o),i.current_tool_call_index!=null&&c(this,F,"m",Sn).call(this,o,i.current_tool_call_index));for(let l of s.delta.tool_calls??[])i.current_tool_call_index!==l.index&&(c(this,F,"m",On).call(this,o),i.current_tool_call_index!=null&&c(this,F,"m",Sn).call(this,o,i.current_tool_call_index)),i.current_tool_call_index=l.index;for(let l of s.delta.tool_calls??[]){let u=o.message.tool_calls?.[l.index];u?.type&&(u?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:u.function?.name,index:l.index,arguments:u.function.arguments,parsed_arguments:u.function.parsed_arguments,arguments_delta:l.function?.arguments??""}):(u?.type,void 0))}}},Sn=function(t,r){if(c(this,F,"m",Tr).call(this,t).done_tool_calls.has(r))return;let o=t.message.tool_calls?.[r];if(!o)throw new Error("no tool call snapshot");if(!o.type)throw new Error("tool call snapshot missing `type`");if(o.type==="function"){let i=c(this,ce,"f")?.tools?.find(l=>l.type==="function"&&l.function.name===o.function.name);this._emit("tool_calls.function.arguments.done",{name:o.function.name,index:r,arguments:o.function.arguments,parsed_arguments:$e(i)?i.$parseRaw(o.function.arguments):i?.function.strict?JSON.parse(o.function.arguments):null})}else o.type},On=function(t){let r=c(this,F,"m",Tr).call(this,t);if(t.message.content&&!r.content_done){r.content_done=!0;let s=c(this,F,"m",En).call(this);this._emit("content.done",{content:t.message.content,parsed:s?s.$parseRaw(t.message.content):null})}t.message.refusal&&!r.refusal_done&&(r.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal})),t.logprobs?.content&&!r.logprobs_content_done&&(r.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content})),t.logprobs?.refusal&&!r.logprobs_refusal_done&&(r.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},Mr=function(){if(this.ended)throw new b("stream has ended, this shouldn't happen");let t=c(this,ye,"f");if(!t)throw new b("request ended without sending any chunks");return w(this,ye,void 0,"f"),w(this,Ct,[],"f"),$o(t,c(this,ce,"f"))},En=function(){let t=c(this,ce,"f")?.response_format;return rr(t)?t:null},ks=function(t){var r,s,o,i;let l=c(this,ye,"f"),{choices:u,...p}=t;l?Object.assign(l,p):l=w(this,ye,{...p,choices:[]},"f");for(let{delta:g,finish_reason:m,index:y,logprobs:f=null,...x}of t.choices){let A=l.choices[y];if(A||(A=l.choices[y]={finish_reason:m,index:y,message:{},logprobs:f,...x}),f)if(!A.logprobs)A.logprobs=Object.assign({},f);else{let{content:H,refusal:E,...D}=f;Object.assign(A.logprobs,D),H&&((r=A.logprobs).content??(r.content=[]),A.logprobs.content.push(...H)),E&&((s=A.logprobs).refusal??(s.refusal=[]),A.logprobs.refusal.push(...E))}if(m&&(A.finish_reason=m,c(this,ce,"f")&&_n(c(this,ce,"f")))){if(m==="length")throw new dt;if(m==="content_filter")throw new mt}if(Object.assign(A,x),!g)continue;let{content:R,refusal:S,function_call:C,role:U,tool_calls:O,...X}=g;if(Object.assign(A.message,X),S&&(A.message.refusal=(A.message.refusal||"")+S),U&&(A.message.role=U),C&&(A.message.function_call?(C.name&&(A.message.function_call.name=C.name),C.arguments&&((o=A.message.function_call).arguments??(o.arguments=""),A.message.function_call.arguments+=C.arguments)):A.message.function_call=C),R&&(A.message.content=(A.message.content||"")+R,!A.message.refusal&&c(this,F,"m",En).call(this)&&(A.message.parsed=In(A.message.content))),O){A.message.tool_calls||(A.message.tool_calls=[]);for(let{index:H,id:E,type:D,function:j,...T}of O){let k=(i=A.message.tool_calls)[H]??(i[H]={});Object.assign(k,T),E&&(k.id=E),D&&(k.type=D),j&&(k.function??(k.function={name:j.name??"",arguments:""})),j?.name&&(k.function.name=j.name),j?.arguments&&(k.function.arguments+=j.arguments,Es(c(this,ce,"f"),k)&&(k.function.parsed_arguments=In(k.function.arguments)))}}}return l},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("chunk",s=>{let o=t.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{r=!0;for(let o of t)o.reject(s);t.length=0}),this.on("error",s=>{r=!0;for(let o of t)o.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,i)=>t.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new re(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function $o(n,e){let{id:t,choices:r,created:s,model:o,system_fingerprint:i,...l}=n,u={...l,id:t,choices:r.map(({message:p,finish_reason:g,index:m,logprobs:y,...f})=>{if(!g)throw new b(`missing finish_reason for choice ${m}`);let{content:x=null,function_call:A,tool_calls:R,...S}=p,C=p.role;if(!C)throw new b(`missing role for choice ${m}`);if(A){let{arguments:U,name:O}=A;if(U==null)throw new b(`missing function_call.arguments for choice ${m}`);if(!O)throw new b(`missing function_call.name for choice ${m}`);return{...f,message:{content:x,function_call:{arguments:U,name:O},role:C,refusal:p.refusal??null},finish_reason:g,index:m,logprobs:y}}return R?{...f,index:m,finish_reason:g,logprobs:y,message:{...S,role:C,content:x,refusal:p.refusal??null,tool_calls:R.map((U,O)=>{let{function:X,type:H,id:E,...D}=U,{arguments:j,name:T,...k}=X||{};if(E==null)throw new b(`missing choices[${m}].tool_calls[${O}].id
13
- ${kr(n)}`);if(H==null)throw new b(`missing choices[${m}].tool_calls[${O}].type
14
- ${kr(n)}`);if(T==null)throw new b(`missing choices[${m}].tool_calls[${O}].function.name
15
- ${kr(n)}`);if(j==null)throw new b(`missing choices[${m}].tool_calls[${O}].function.arguments
16
- ${kr(n)}`);return{...D,id:E,type:H,function:{...k,name:T,arguments:j}}})}}:{...f,message:{...S,content:x,role:C,refusal:p.refusal??null},finish_reason:g,index:m,logprobs:y}}),created:s,model:o,object:"chat.completion",...i?{system_fingerprint:i}:{}};return Os(u,e)}function kr(n){return JSON.stringify(n)}var or=class n extends Ne{static fromReadableStream(e){let t=new n(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,r){let s=new n(t),o={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,o)),s}};var ue=class extends h{constructor(){super(...arguments),this.messages=new ke(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(d`/chat/completions/${e}`,t)}update(e,t,r){return this._client.post(d`/chat/completions/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/chat/completions",P,{query:e,...t})}delete(e,t){return this._client.delete(d`/chat/completions/${e}`,t)}parse(e,t){return vs(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(r=>nr(r,e))}runTools(e,t){return e.stream?or.runTools(this._client,e,t):sr.runTools(this._client,e,t)}stream(e,t){return Ne.createChatCompletion(this._client,e,t)}};ue.Messages=ke;var Ce=class extends h{constructor(){super(...arguments),this.completions=new ue(this._client)}};Ce.Completions=ue;a();a();a();a();a();var $s=Symbol("brand.privateNullableHeaders");function*Fo(n){if(!n)return;if($s in n){let{values:r,nulls:s}=n;yield*r.entries();for(let o of s)yield[o,null];return}let e=!1,t;n instanceof Headers?t=n.entries():Qr(n)?t=n:(e=!0,t=Object.entries(n??{}));for(let r of t){let s=r[0];if(typeof s!="string")throw new TypeError("expected header name to be a string");let o=Qr(r[1])?r[1]:[r[1]],i=!1;for(let l of o)l!==void 0&&(e&&!i&&(i=!0,yield[s,null]),yield[s,l])}}var _=n=>{let e=new Headers,t=new Set;for(let r of n){let s=new Set;for(let[o,i]of Fo(r)){let l=o.toLowerCase();s.has(l)||(e.delete(o),s.add(l)),i===null?(e.delete(o),t.add(l)):(e.append(o,i),t.delete(l))}}return{[$s]:!0,values:e,nulls:t}};var wt=class extends h{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:_([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}};a();var At=class extends h{create(e,t){return this._client.post("/audio/transcriptions",z({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}};a();var xt=class extends h{create(e,t){return this._client.post("/audio/translations",z({body:e,...t,__metadata:{model:e.model}},this._client))}};var se=class extends h{constructor(){super(...arguments),this.transcriptions=new At(this._client),this.translations=new xt(this._client),this.speech=new wt(this._client)}};se.Transcriptions=At;se.Translations=xt;se.Speech=wt;a();var Fe=class extends h{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(d`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",P,{query:e,...t})}cancel(e,t){return this._client.post(d`/batches/${e}/cancel`,t)}};a();a();var It=class extends h{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(d`/assistants/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(d`/assistants/${e}`,{body:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",P,{query:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(d`/assistants/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};a();a();var Pt=class extends h{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};a();var Rt=class extends h{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};var we=class extends h{constructor(){super(...arguments),this.sessions=new Pt(this._client),this.transcriptionSessions=new Rt(this._client)}};we.Sessions=Pt;we.TranscriptionSessions=Rt;a();a();var St=class extends h{create(e,t,r){return this._client.post(d`/threads/${e}/messages`,{body:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{thread_id:s}=t;return this._client.get(d`/threads/${s}/messages/${e}`,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{thread_id:s,...o}=t;return this._client.post(d`/threads/${s}/messages/${e}`,{body:o,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(d`/threads/${e}/messages`,P,{query:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){let{thread_id:s}=t;return this._client.delete(d`/threads/${s}/messages/${e}`,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};a();a();var Ot=class extends h{retrieve(e,t,r){let{thread_id:s,run_id:o,...i}=t;return this._client.get(d`/threads/${s}/runs/${o}/steps/${e}`,{query:i,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t,r){let{thread_id:s,...o}=t;return this._client.getAPIList(d`/threads/${s}/runs/${e}/steps`,P,{query:o,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};a();a();a();var Ns=n=>{if(typeof Buffer<"u"){let e=Buffer.from(n,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(n),t=e.length,r=new Uint8Array(t);for(let s=0;s<t;s++)r[s]=e.charCodeAt(s);return Array.from(new Float32Array(r.buffer))}};a();var Ae=n=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[n]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(n)?.trim()};var B,Ue,vn,oe,$r,Q,De,Et,Le,Lr,K,Nr,Fr,lr,ir,ar,Fs,Ls,Us,Ds,js,Gs,Bs,fe=class extends be{constructor(){super(...arguments),B.add(this),vn.set(this,[]),oe.set(this,{}),$r.set(this,{}),Q.set(this,void 0),De.set(this,void 0),Et.set(this,void 0),Le.set(this,void 0),Lr.set(this,void 0),K.set(this,void 0),Nr.set(this,void 0),Fr.set(this,void 0),lr.set(this,void 0)}[(vn=new WeakMap,oe=new WeakMap,$r=new WeakMap,Q=new WeakMap,De=new WeakMap,Et=new WeakMap,Le=new WeakMap,Lr=new WeakMap,K=new WeakMap,Nr=new WeakMap,Fr=new WeakMap,lr=new WeakMap,B=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",s=>{let o=t.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{r=!0;for(let o of t)o.reject(s);t.length=0}),this.on("error",s=>{r=!0;for(let o of t)o.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,i)=>t.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new Ue;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){let r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),this._connected();let s=re.fromReadableStream(e,this.controller);for await(let o of s)c(this,B,"m",ir).call(this,o);if(s.controller.signal?.aborted)throw new M;return this._addRun(c(this,B,"m",ar).call(this))}toReadableStream(){return new re(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,s){let o=new Ue;return o._run(()=>o._runToolAssistantStream(e,t,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createToolAssistantStream(e,t,r,s){let o=s?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let i={...r,stream:!0},l=await e.submitToolOutputs(t,i,{...s,signal:this.controller.signal});this._connected();for await(let u of l)c(this,B,"m",ir).call(this,u);if(l.controller.signal?.aborted)throw new M;return this._addRun(c(this,B,"m",ar).call(this))}static createThreadAssistantStream(e,t,r){let s=new Ue;return s._run(()=>s._threadAssistantStream(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}static createAssistantStream(e,t,r,s){let o=new Ue;return o._run(()=>o._runAssistantStream(e,t,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return c(this,Nr,"f")}currentRun(){return c(this,Fr,"f")}currentMessageSnapshot(){return c(this,Q,"f")}currentRunStepSnapshot(){return c(this,lr,"f")}async finalRunSteps(){return await this.done(),Object.values(c(this,oe,"f"))}async finalMessages(){return await this.done(),Object.values(c(this,$r,"f"))}async finalRun(){if(await this.done(),!c(this,De,"f"))throw Error("Final run was not received.");return c(this,De,"f")}async _createThreadAssistantStream(e,t,r){let s=r?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));let o={...t,stream:!0},i=await e.createAndRun(o,{...r,signal:this.controller.signal});this._connected();for await(let l of i)c(this,B,"m",ir).call(this,l);if(i.controller.signal?.aborted)throw new M;return this._addRun(c(this,B,"m",ar).call(this))}async _createAssistantStream(e,t,r,s){let o=s?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let i={...r,stream:!0},l=await e.create(t,i,{...s,signal:this.controller.signal});this._connected();for await(let u of l)c(this,B,"m",ir).call(this,u);if(l.controller.signal?.aborted)throw new M;return this._addRun(c(this,B,"m",ar).call(this))}static accumulateDelta(e,t){for(let[r,s]of Object.entries(t)){if(!e.hasOwnProperty(r)){e[r]=s;continue}let o=e[r];if(o==null){e[r]=s;continue}if(r==="index"||r==="type"){e[r]=s;continue}if(typeof o=="string"&&typeof s=="string")o+=s;else if(typeof o=="number"&&typeof s=="number")o+=s;else if(Xt(o)&&Xt(s))o=this.accumulateDelta(o,s);else if(Array.isArray(o)&&Array.isArray(s)){if(o.every(i=>typeof i=="string"||typeof i=="number")){o.push(...s);continue}for(let i of s){if(!Xt(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);let l=i.index;if(l==null)throw console.error(i),new Error("Expected array delta entry to have an `index` property");if(typeof l!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${l}`);let u=o[l];u==null?o.push(i):o[l]=this.accumulateDelta(u,i)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${s}, accValue: ${o}`);e[r]=o}return e}_addRun(e){return e}async _threadAssistantStream(e,t,r){return await this._createThreadAssistantStream(t,e,r)}async _runAssistantStream(e,t,r,s){return await this._createAssistantStream(t,e,r,s)}async _runToolAssistantStream(e,t,r,s){return await this._createToolAssistantStream(t,e,r,s)}};Ue=fe,ir=function(e){if(!this.ended)switch(w(this,Nr,e,"f"),c(this,B,"m",Us).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":c(this,B,"m",Bs).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":c(this,B,"m",Ls).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":c(this,B,"m",Fs).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},ar=function(){if(this.ended)throw new b("stream has ended, this shouldn't happen");if(!c(this,De,"f"))throw Error("Final run has not been received");return c(this,De,"f")},Fs=function(e){let[t,r]=c(this,B,"m",js).call(this,e,c(this,Q,"f"));w(this,Q,t,"f"),c(this,$r,"f")[t.id]=t;for(let s of r){let o=t.content[s.index];o?.type=="text"&&this._emit("textCreated",o.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 s of e.data.delta.content){if(s.type=="text"&&s.text){let o=s.text,i=t.content[s.index];if(i&&i.type=="text")this._emit("textDelta",o,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(s.index!=c(this,Et,"f")){if(c(this,Le,"f"))switch(c(this,Le,"f").type){case"text":this._emit("textDone",c(this,Le,"f").text,c(this,Q,"f"));break;case"image_file":this._emit("imageFileDone",c(this,Le,"f").image_file,c(this,Q,"f"));break}w(this,Et,s.index,"f")}w(this,Le,t.content[s.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(c(this,Et,"f")!==void 0){let s=e.data.content[c(this,Et,"f")];if(s)switch(s.type){case"image_file":this._emit("imageFileDone",s.image_file,c(this,Q,"f"));break;case"text":this._emit("textDone",s.text,c(this,Q,"f"));break}}c(this,Q,"f")&&this._emit("messageDone",e.data),w(this,Q,void 0,"f")}},Ls=function(e){let t=c(this,B,"m",Ds).call(this,e);switch(w(this,lr,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let r=e.data.delta;if(r.step_details&&r.step_details.type=="tool_calls"&&r.step_details.tool_calls&&t.step_details.type=="tool_calls")for(let o of r.step_details.tool_calls)o.index==c(this,Lr,"f")?this._emit("toolCallDelta",o,t.step_details.tool_calls[o.index]):(c(this,K,"f")&&this._emit("toolCallDone",c(this,K,"f")),w(this,Lr,o.index,"f"),w(this,K,t.step_details.tool_calls[o.index],"f"),c(this,K,"f")&&this._emit("toolCallCreated",c(this,K,"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":w(this,lr,void 0,"f"),e.data.step_details.type=="tool_calls"&&c(this,K,"f")&&(this._emit("toolCallDone",c(this,K,"f")),w(this,K,void 0,"f")),this._emit("runStepDone",e.data,t);break;case"thread.run.step.in_progress":break}},Us=function(e){c(this,vn,"f").push(e),this._emit("event",e)},Ds=function(e){switch(e.event){case"thread.run.step.created":return c(this,oe,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=c(this,oe,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){let s=Ue.accumulateDelta(t,r.delta);c(this,oe,"f")[e.data.id]=s}return c(this,oe,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":c(this,oe,"f")[e.data.id]=e.data;break}if(c(this,oe,"f")[e.data.id])return c(this,oe,"f")[e.data.id];throw new Error("No snapshot available")},js=function(e,t){let r=[];switch(e.event){case"thread.message.created":return[e.data,r];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let s=e.data;if(s.delta.content)for(let o of s.delta.content)if(o.index in t.content){let i=t.content[o.index];t.content[o.index]=c(this,B,"m",Gs).call(this,o,i)}else t.content[o.index]=o,r.push(o);return[t,r];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,r];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Gs=function(e,t){return Ue.accumulateDelta(t,e)},Bs=function(e){switch(w(this,Fr,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":w(this,De,e.data,"f"),c(this,K,"f")&&(this._emit("toolCallDone",c(this,K,"f")),w(this,K,void 0,"f"));break;case"thread.run.cancelling":break}};var je=class extends h{constructor(){super(...arguments),this.steps=new Ot(this._client)}create(e,t,r){let{include:s,...o}=t;return this._client.post(d`/threads/${e}/runs`,{query:{include:s},body:o,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1})}retrieve(e,t,r){let{thread_id:s}=t;return this._client.get(d`/threads/${s}/runs/${e}`,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{thread_id:s,...o}=t;return this._client.post(d`/threads/${s}/runs/${e}`,{body:o,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(d`/threads/${e}/runs`,P,{query:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){let{thread_id:s}=t;return this._client.post(d`/threads/${s}/runs/${e}/cancel`,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let s=await this.create(e,t,r);return await this.poll(s.id,{thread_id:e},r)}createAndStream(e,t,r){return fe.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){let s=_([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:i}=await this.retrieve(e,t,{...r,headers:{...r?.headers,...s}}).withResponse();switch(o.status){case"queued":case"in_progress":case"cancelling":let l=5e3;if(r?.pollIntervalMs)l=r.pollIntervalMs;else{let u=i.headers.get("openai-poll-after-ms");if(u){let p=parseInt(u);isNaN(p)||(l=p)}}await ee(l);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return o}}}stream(e,t,r){return fe.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r){let{thread_id:s,...o}=t;return this._client.post(d`/threads/${s}/runs/${e}/submit_tool_outputs`,{body:o,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1})}async submitToolOutputsAndPoll(e,t,r){let s=await this.submitToolOutputs(e,t,r);return await this.poll(s.id,t,r)}submitToolOutputsStream(e,t,r){return fe.createToolAssistantStream(e,this._client.beta.threads.runs,t,r)}};je.Steps=Ot;var xe=class extends h{constructor(){super(...arguments),this.runs=new je(this._client),this.messages=new St(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(d`/threads/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(d`/threads/${e}`,{body:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t){return this._client.delete(d`/threads/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1})}async createAndRunPoll(e,t){let r=await this.createAndRun(e,t);return await this.runs.poll(r.id,{thread_id:r.thread_id},t)}createAndRunStream(e,t){return fe.createThreadAssistantStream(e,this._client.beta.threads,t)}};xe.Runs=je;xe.Messages=St;var ie=class extends h{constructor(){super(...arguments),this.realtime=new we(this._client),this.assistants=new It(this._client),this.threads=new xe(this._client)}};ie.Realtime=we;ie.Assistants=It;ie.Threads=xe;a();var Ge=class extends h{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}};a();a();a();var vt=class extends h{retrieve(e,t,r){let{container_id:s}=t;return this._client.get(d`/containers/${s}/files/${e}/content`,{...r,headers:_([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}};var Be=class extends h{constructor(){super(...arguments),this.content=new vt(this._client)}create(e,t,r){return this._client.post(d`/containers/${e}/files`,z({body:t,...r},this._client))}retrieve(e,t,r){let{container_id:s}=t;return this._client.get(d`/containers/${s}/files/${e}`,r)}list(e,t={},r){return this._client.getAPIList(d`/containers/${e}/files`,P,{query:t,...r})}delete(e,t,r){let{container_id:s}=t;return this._client.delete(d`/containers/${s}/files/${e}`,{...r,headers:_([{Accept:"*/*"},r?.headers])})}};Be.Content=vt;var Ie=class extends h{constructor(){super(...arguments),this.files=new Be(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(d`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",P,{query:e,...t})}delete(e,t){return this._client.delete(d`/containers/${e}`,{...t,headers:_([{Accept:"*/*"},t?.headers])})}};Ie.Files=Be;a();var We=class extends h{create(e,t){let r=!!e.encoding_format,s=r?e.encoding_format:"base64";r&&v(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let o=this._client.post("/embeddings",{body:{...e,encoding_format:s},...t});return r?o:(v(this._client).debug("embeddings/decoding base64 embeddings from base64"),o._thenUnwrap(i=>(i&&i.data&&i.data.forEach(l=>{let u=l.embedding;l.embedding=Ns(u)}),i)))}};a();a();a();var Tt=class extends h{retrieve(e,t,r){let{eval_id:s,run_id:o}=t;return this._client.get(d`/evals/${s}/runs/${o}/output_items/${e}`,r)}list(e,t,r){let{eval_id:s,...o}=t;return this._client.getAPIList(d`/evals/${s}/runs/${e}/output_items`,P,{query:o,...r})}};var He=class extends h{constructor(){super(...arguments),this.outputItems=new Tt(this._client)}create(e,t,r){return this._client.post(d`/evals/${e}/runs`,{body:t,...r})}retrieve(e,t,r){let{eval_id:s}=t;return this._client.get(d`/evals/${s}/runs/${e}`,r)}list(e,t={},r){return this._client.getAPIList(d`/evals/${e}/runs`,P,{query:t,...r})}delete(e,t,r){let{eval_id:s}=t;return this._client.delete(d`/evals/${s}/runs/${e}`,r)}cancel(e,t,r){let{eval_id:s}=t;return this._client.post(d`/evals/${s}/runs/${e}`,r)}};He.OutputItems=Tt;var Pe=class extends h{constructor(){super(...arguments),this.runs=new He(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(d`/evals/${e}`,t)}update(e,t,r){return this._client.post(d`/evals/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/evals",P,{query:e,...t})}delete(e,t){return this._client.delete(d`/evals/${e}`,t)}};Pe.Runs=He;a();var qe=class extends h{create(e,t){return this._client.post("/files",z({body:e,...t},this._client))}retrieve(e,t){return this._client.get(d`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",P,{query:e,...t})}delete(e,t){return this._client.delete(d`/files/${e}`,t)}content(e,t){return this._client.get(d`/files/${e}/content`,{...t,headers:_([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:r=30*60*1e3}={}){let s=new Set(["processed","error","deleted"]),o=Date.now(),i=await this.retrieve(e);for(;!i.status||!s.has(i.status);)if(await ee(t),i=await this.retrieve(e),Date.now()-o>r)throw new ge({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return i}};a();a();var Mt=class extends h{};a();a();var kt=class extends h{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 Xe=class extends h{constructor(){super(...arguments),this.graders=new kt(this._client)}};Xe.Graders=kt;a();a();var $t=class extends h{create(e,t,r){return this._client.getAPIList(d`/fine_tuning/checkpoints/${e}/permissions`,ne,{body:t,method:"post",...r})}retrieve(e,t={},r){return this._client.get(d`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...r})}delete(e,t,r){let{fine_tuned_model_checkpoint:s}=t;return this._client.delete(d`/fine_tuning/checkpoints/${s}/permissions/${e}`,r)}};var Je=class extends h{constructor(){super(...arguments),this.permissions=new $t(this._client)}};Je.Permissions=$t;a();a();var Nt=class extends h{list(e,t={},r){return this._client.getAPIList(d`/fine_tuning/jobs/${e}/checkpoints`,P,{query:t,...r})}};var Ve=class extends h{constructor(){super(...arguments),this.checkpoints=new Nt(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(d`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",P,{query:e,...t})}cancel(e,t){return this._client.post(d`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},r){return this._client.getAPIList(d`/fine_tuning/jobs/${e}/events`,P,{query:t,...r})}pause(e,t){return this._client.post(d`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(d`/fine_tuning/jobs/${e}/resume`,t)}};Ve.Checkpoints=Nt;var Y=class extends h{constructor(){super(...arguments),this.methods=new Mt(this._client),this.jobs=new Ve(this._client),this.checkpoints=new Je(this._client),this.alpha=new Xe(this._client)}};Y.Methods=Mt;Y.Jobs=Ve;Y.Checkpoints=Je;Y.Alpha=Xe;a();a();var Ft=class extends h{};var Re=class extends h{constructor(){super(...arguments),this.graderModels=new Ft(this._client)}};Re.GraderModels=Ft;a();var ze=class extends h{createVariation(e,t){return this._client.post("/images/variations",z({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",z({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})}};a();var Ke=class extends h{retrieve(e,t){return this._client.get(d`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",ne,e)}delete(e,t){return this._client.delete(d`/models/${e}`,t)}};a();var Qe=class extends h{create(e,t){return this._client.post("/moderations",{body:e,...t})}};a();a();function Ws(n,e){return!e||!ai(e)?{...n,output_parsed:null,output:n.output.map(t=>t.type==="function_call"?{...t,parsed_arguments:null}:t.type==="message"?{...t,content:t.content.map(r=>({...r,parsed:null}))}:t)}:Tn(n,e)}function Tn(n,e){let t=n.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:ui(e,s)};if(s.type==="message"){let o=s.content.map(i=>i.type==="output_text"?{...i,parsed:ii(e,i.text)}:i);return{...s,content:o}}return s}),r=Object.assign({},n,{output:t});return Object.getOwnPropertyDescriptor(n,"output_text")||Ur(r),Object.defineProperty(r,"output_parsed",{enumerable:!0,get(){for(let s of r.output)if(s.type==="message"){for(let o of s.content)if(o.type==="output_text"&&o.parsed!==null)return o.parsed}return null}}),r}function ii(n,e){return n.text?.format?.type!=="json_schema"?null:"$parseRaw"in n.text?.format?(n.text?.format).$parseRaw(e):JSON.parse(e)}function ai(n){return!!rr(n.text?.format)}function li(n){return n?.$brand==="auto-parseable-tool"}function ci(n,e){return n.find(t=>t.type==="function"&&t.name===e)}function ui(n,e){let t=ci(n.tools??[],e.name);return{...e,...e,parsed_arguments:li(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function Ur(n){let e=[];for(let t of n.output)if(t.type==="message")for(let r of t.content)r.type==="output_text"&&e.push(r.text);n.output_text=e.join("")}a();var Lt,Dr,Se,jr,Hs,qs,Xs,Js,Gr=class n extends be{constructor(e){super(),Lt.add(this),Dr.set(this,void 0),Se.set(this,void 0),jr.set(this,void 0),w(this,Dr,e,"f")}static createResponse(e,t,r){let s=new n(t);return s._run(()=>s._createOrRetrieveResponse(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createOrRetrieveResponse(e,t,r){let s=r?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),c(this,Lt,"m",Hs).call(this);let o,i=null;"response_id"in t?(o=await e.responses.retrieve(t.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),i=t.starting_after??null):o=await e.responses.create({...t,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(let l of o)c(this,Lt,"m",qs).call(this,l,i);if(o.controller.signal?.aborted)throw new M;return c(this,Lt,"m",Xs).call(this)}[(Dr=new WeakMap,Se=new WeakMap,jr=new WeakMap,Lt=new WeakSet,Hs=function(){this.ended||w(this,Se,void 0,"f")},qs=function(t,r){if(this.ended)return;let s=(i,l)=>{(r==null||l.sequence_number>r)&&this._emit(i,l)},o=c(this,Lt,"m",Js).call(this,t);switch(s("event",t),t.type){case"response.output_text.delta":{let i=o.output[t.output_index];if(!i)throw new b(`missing output at index ${t.output_index}`);if(i.type==="message"){let l=i.content[t.content_index];if(!l)throw new b(`missing content at index ${t.content_index}`);if(l.type!=="output_text")throw new b(`expected content to be 'output_text', got ${l.type}`);s("response.output_text.delta",{...t,snapshot:l.text})}break}case"response.function_call_arguments.delta":{let i=o.output[t.output_index];if(!i)throw new b(`missing output at index ${t.output_index}`);i.type==="function_call"&&s("response.function_call_arguments.delta",{...t,snapshot:i.arguments});break}default:s(t.type,t);break}},Xs=function(){if(this.ended)throw new b("stream has ended, this shouldn't happen");let t=c(this,Se,"f");if(!t)throw new b("request ended without sending any events");w(this,Se,void 0,"f");let r=fi(t,c(this,Dr,"f"));return w(this,jr,r,"f"),r},Js=function(t){let r=c(this,Se,"f");if(!r){if(t.type!=="response.created")throw new b(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return r=w(this,Se,t.response,"f"),r}switch(t.type){case"response.output_item.added":{r.output.push(t.item);break}case"response.content_part.added":{let s=r.output[t.output_index];if(!s)throw new b(`missing output at index ${t.output_index}`);s.type==="message"&&s.content.push(t.part);break}case"response.output_text.delta":{let s=r.output[t.output_index];if(!s)throw new b(`missing output at index ${t.output_index}`);if(s.type==="message"){let o=s.content[t.content_index];if(!o)throw new b(`missing content at index ${t.content_index}`);if(o.type!=="output_text")throw new b(`expected content to be 'output_text', got ${o.type}`);o.text+=t.delta}break}case"response.function_call_arguments.delta":{let s=r.output[t.output_index];if(!s)throw new b(`missing output at index ${t.output_index}`);s.type==="function_call"&&(s.arguments+=t.delta);break}case"response.completed":{w(this,Se,t.response,"f");break}}return r},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",s=>{let o=t.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{r=!0;for(let o of t)o.reject(s);t.length=0}),this.on("error",s=>{r=!0;for(let o of t)o.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,i)=>t.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=c(this,jr,"f");if(!e)throw new b("stream ended without producing a ChatCompletion");return e}};function fi(n,e){return Ws(n,e)}a();var Ut=class extends h{list(e,t={},r){return this._client.getAPIList(d`/responses/${e}/input_items`,P,{query:t,...r})}};var Oe=class extends h{constructor(){super(...arguments),this.inputItems=new Ut(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(r=>("object"in r&&r.object==="response"&&Ur(r),r))}retrieve(e,t={},r){return this._client.get(d`/responses/${e}`,{query:t,...r,stream:t?.stream??!1})._thenUnwrap(s=>("object"in s&&s.object==="response"&&Ur(s),s))}delete(e,t){return this._client.delete(d`/responses/${e}`,{...t,headers:_([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(r=>Tn(r,e))}stream(e,t){return Gr.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(d`/responses/${e}/cancel`,t)}};Oe.InputItems=Ut;a();a();var Dt=class extends h{create(e,t,r){return this._client.post(d`/uploads/${e}/parts`,z({body:t,...r},this._client))}};var Ee=class extends h{constructor(){super(...arguments),this.parts=new Dt(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(d`/uploads/${e}/cancel`,t)}complete(e,t,r){return this._client.post(d`/uploads/${e}/complete`,{body:t,...r})}};Ee.Parts=Dt;a();a();a();var Vs=async n=>{let e=await Promise.allSettled(n),t=e.filter(s=>s.status==="rejected");if(t.length){for(let s of t)console.error(s.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}let r=[];for(let s of e)s.status==="fulfilled"&&r.push(s.value);return r};var jt=class extends h{create(e,t,r){return this._client.post(d`/vector_stores/${e}/file_batches`,{body:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{vector_store_id:s}=t;return this._client.get(d`/vector_stores/${s}/file_batches/${e}`,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){let{vector_store_id:s}=t;return this._client.post(d`/vector_stores/${s}/file_batches/${e}/cancel`,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let s=await this.create(e,t);return await this.poll(e,s.id,r)}listFiles(e,t,r){let{vector_store_id:s,...o}=t;return this._client.getAPIList(d`/vector_stores/${s}/file_batches/${e}/files`,P,{query:o,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async poll(e,t,r){let s=_([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:i}=await this.retrieve(t,{vector_store_id:e},{...r,headers:s}).withResponse();switch(o.status){case"in_progress":let l=5e3;if(r?.pollIntervalMs)l=r.pollIntervalMs;else{let u=i.headers.get("openai-poll-after-ms");if(u){let p=parseInt(u);isNaN(p)||(l=p)}}await ee(l);break;case"failed":case"cancelled":case"completed":return o}}}async uploadAndPoll(e,{files:t,fileIds:r=[]},s){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 o=s?.maxConcurrency??5,i=Math.min(o,t.length),l=this._client,u=t.values(),p=[...r];async function g(y){for(let f of y){let x=await l.files.create({file:f,purpose:"assistants"},s);p.push(x.id)}}let m=Array(i).fill(u).map(g);return await Vs(m),await this.createAndPoll(e,{file_ids:p})}};a();var Gt=class extends h{create(e,t,r){return this._client.post(d`/vector_stores/${e}/files`,{body:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{vector_store_id:s}=t;return this._client.get(d`/vector_stores/${s}/files/${e}`,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{vector_store_id:s,...o}=t;return this._client.post(d`/vector_stores/${s}/files/${e}`,{body:o,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(d`/vector_stores/${e}/files`,P,{query:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){let{vector_store_id:s}=t;return this._client.delete(d`/vector_stores/${s}/files/${e}`,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let s=await this.create(e,t,r);return await this.poll(e,s.id,r)}async poll(e,t,r){let s=_([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let o=await this.retrieve(t,{vector_store_id:e},{...r,headers:s}).withResponse(),i=o.data;switch(i.status){case"in_progress":let l=5e3;if(r?.pollIntervalMs)l=r.pollIntervalMs;else{let u=o.response.headers.get("openai-poll-after-ms");if(u){let p=parseInt(u);isNaN(p)||(l=p)}}await ee(l);break;case"failed":case"completed":return i}}}async upload(e,t,r){let s=await this._client.files.create({file:t,purpose:"assistants"},r);return this.create(e,{file_id:s.id},r)}async uploadAndPoll(e,t,r){let s=await this.upload(e,t,r);return await this.poll(e,s.id,r)}content(e,t,r){let{vector_store_id:s}=t;return this._client.getAPIList(d`/vector_stores/${s}/files/${e}/content`,ne,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};var pe=class extends h{constructor(){super(...arguments),this.files=new Gt(this._client),this.fileBatches=new jt(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(d`/vector_stores/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(d`/vector_stores/${e}`,{body:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",P,{query:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(d`/vector_stores/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,r){return this._client.getAPIList(d`/vector_stores/${e}/search`,ne,{body:t,method:"post",...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};pe.Files=Gt;pe.FileBatches=jt;a();var Bt,zs,Br,Ye=class extends h{constructor(){super(...arguments),Bt.add(this)}async unwrap(e,t,r=this._client.webhookSecret,s=300){return await this.verifySignature(e,t,r,s),JSON.parse(e)}async verifySignature(e,t,r=this._client.webhookSecret,s=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");c(this,Bt,"m",zs).call(this,r);let o=_([t]).values,i=c(this,Bt,"m",Br).call(this,o,"webhook-signature"),l=c(this,Bt,"m",Br).call(this,o,"webhook-timestamp"),u=c(this,Bt,"m",Br).call(this,o,"webhook-id"),p=parseInt(l,10);if(isNaN(p))throw new Z("Invalid webhook timestamp format");let g=Math.floor(Date.now()/1e3);if(g-p>s)throw new Z("Webhook timestamp is too old");if(p>g+s)throw new Z("Webhook timestamp is too new");let m=i.split(" ").map(A=>A.startsWith("v1,")?A.substring(3):A),y=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),f=u?`${u}.${l}.${e}`:`${l}.${e}`,x=await crypto.subtle.importKey("raw",y,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let A of m)try{let R=Buffer.from(A,"base64");if(await crypto.subtle.verify("HMAC",x,R,new TextEncoder().encode(f)))return}catch{continue}throw new Z("The given webhook signature does not match the expected signature")}};Bt=new WeakSet,zs=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")},Br=function(e,t){if(!e)throw new Error("Headers are required");let r=e.get(t);if(r==null)throw new Error(`Missing required header: ${t}`);return r};var Mn,kn,Wr,Ks,I=class{constructor({baseURL:e=Ae("OPENAI_BASE_URL"),apiKey:t=Ae("OPENAI_API_KEY"),organization:r=Ae("OPENAI_ORG_ID")??null,project:s=Ae("OPENAI_PROJECT_ID")??null,webhookSecret:o=Ae("OPENAI_WEBHOOK_SECRET")??null,...i}={}){if(Mn.add(this),Wr.set(this,void 0),this.completions=new Ge(this),this.chat=new Ce(this),this.embeddings=new We(this),this.files=new qe(this),this.images=new ze(this),this.audio=new se(this),this.moderations=new Qe(this),this.models=new Ke(this),this.fineTuning=new Y(this),this.graders=new Re(this),this.vectorStores=new pe(this),this.webhooks=new Ye(this),this.beta=new ie(this),this.batches=new Fe(this),this.uploads=new Ee(this),this.responses=new Oe(this),this.evals=new Pe(this),this.containers=new Ie(this),t===void 0)throw new b("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");let l={apiKey:t,organization:r,project:s,webhookSecret:o,...i,baseURL:e||"https://api.openai.com/v1"};if(!l.dangerouslyAllowBrowser&&is())throw new b(`It looks like you're running in a browser-like environment.
11
+ ${p}`)}return i},m=Ro(Ps);var ke=class extends h{list(e,t={},r){return this._client.getAPIList(m`/chat/completions/${e}/messages`,P,{query:t,...r})}};a();a();a();a();function Rs(n){return typeof n.parse=="function"}a();var _t=n=>n?.role==="assistant",hn=n=>n?.role==="tool";a();var gn,Pr,Rr,Yt,Zt,Sr,er,le,tr,Or,Er,bt,Ss,be=class{constructor(){gn.add(this),this.controller=new AbortController,Pr.set(this,void 0),Rr.set(this,()=>{}),Yt.set(this,()=>{}),Zt.set(this,void 0),Sr.set(this,()=>{}),er.set(this,()=>{}),le.set(this,{}),tr.set(this,!1),Or.set(this,!1),Er.set(this,!1),bt.set(this,!1),w(this,Pr,new Promise((e,t)=>{w(this,Rr,e,"f"),w(this,Yt,t,"f")}),"f"),w(this,Zt,new Promise((e,t)=>{w(this,Sr,e,"f"),w(this,er,t,"f")}),"f"),c(this,Pr,"f").catch(()=>{}),c(this,Zt,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},c(this,gn,"m",Ss).bind(this))},0)}_connected(){this.ended||(c(this,Rr,"f").call(this),this._emit("connect"))}get ended(){return c(this,tr,"f")}get errored(){return c(this,Or,"f")}get aborted(){return c(this,Er,"f")}abort(){this.controller.abort()}on(e,t){return(c(this,le,"f")[e]||(c(this,le,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=c(this,le,"f")[e];if(!r)return this;let s=r.findIndex(o=>o.listener===t);return s>=0&&r.splice(s,1),this}once(e,t){return(c(this,le,"f")[e]||(c(this,le,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{w(this,bt,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,t)})}async done(){w(this,bt,!0,"f"),await c(this,Zt,"f")}_emit(e,...t){if(c(this,tr,"f"))return;e==="end"&&(w(this,tr,!0,"f"),c(this,Sr,"f").call(this));let r=c(this,le,"f")[e];if(r&&(c(this,le,"f")[e]=r.filter(s=>!s.once),r.forEach(({listener:s})=>s(...t))),e==="abort"){let s=t[0];!c(this,bt,"f")&&!r?.length&&Promise.reject(s),c(this,Yt,"f").call(this,s),c(this,er,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=t[0];!c(this,bt,"f")&&!r?.length&&Promise.reject(s),c(this,Yt,"f").call(this,s),c(this,er,"f").call(this,s),this._emit("end")}}_emitFinal(){}};Pr=new WeakMap,Rr=new WeakMap,Yt=new WeakMap,Zt=new WeakMap,Sr=new WeakMap,er=new WeakMap,le=new WeakMap,tr=new WeakMap,Or=new WeakMap,Er=new WeakMap,bt=new WeakMap,gn=new WeakSet,Ss=function(e){if(w(this,Or,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new M),e instanceof M)return w(this,Er,!0,"f"),this._emit("abort",e);if(e instanceof b)return this._emit("error",e);if(e instanceof Error){let t=new b(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new b(String(e)))};a();function rr(n){return n?.$brand==="auto-parseable-response-format"}function $e(n){return n?.$brand==="auto-parseable-tool"}function Os(n,e){return!e||!_n(e)?{...n,choices:n.choices.map(t=>({...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:nr(n,e)}function nr(n,e){let t=n.choices.map(r=>{if(r.finish_reason==="length")throw new dt;if(r.finish_reason==="content_filter")throw new mt;return{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:r.message.tool_calls?.map(s=>vo(e,s))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?Eo(e,r.message.content):null}}});return{...n,choices:t}}function Eo(n,e){return n.response_format?.type!=="json_schema"?null:n.response_format?.type==="json_schema"?"$parseRaw"in n.response_format?n.response_format.$parseRaw(e):JSON.parse(e):null}function vo(n,e){let t=n.tools?.find(r=>r.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:$e(t)?t.$parseRaw(e.function.arguments):t?.function.strict?JSON.parse(e.function.arguments):null}}}function Es(n,e){if(!n)return!1;let t=n.tools?.find(r=>r.function?.name===e.function.name);return $e(t)||t?.function.strict||!1}function _n(n){return rr(n.response_format)?!0:n.tools?.some(e=>$e(e)||e.type==="function"&&e.function.strict===!0)??!1}function vs(n){for(let e of n??[]){if(e.type!=="function")throw new b(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new b(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var q,bn,vr,yn,Cn,wn,Ts,Ms,To=10,yt=class extends be{constructor(){super(...arguments),q.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);let t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t){if(this._emit("message",e),hn(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(_t(e)&&e.tool_calls)for(let r of e.tool_calls)r.type==="function"&&this._emit("functionToolCall",r.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new b("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),c(this,q,"m",bn).call(this)}async finalMessage(){return await this.done(),c(this,q,"m",vr).call(this)}async finalFunctionToolCall(){return await this.done(),c(this,q,"m",yn).call(this)}async finalFunctionToolCallResult(){return await this.done(),c(this,q,"m",Cn).call(this)}async totalUsage(){return await this.done(),c(this,q,"m",wn).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let t=c(this,q,"m",vr).call(this);t&&this._emit("finalMessage",t);let r=c(this,q,"m",bn).call(this);r&&this._emit("finalContent",r);let s=c(this,q,"m",yn).call(this);s&&this._emit("finalFunctionToolCall",s);let o=c(this,q,"m",Cn).call(this);o!=null&&this._emit("finalFunctionToolCallResult",o),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",c(this,q,"m",wn).call(this))}async _createChatCompletion(e,t,r){let s=r?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),c(this,q,"m",Ts).call(this,t);let o=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(nr(o,t))}async _runChatCompletion(e,t,r){for(let s of t.messages)this._addMessage(s,!1);return await this._createChatCompletion(e,t,r)}async _runTools(e,t,r){let s="tool",{tool_choice:o="auto",stream:i,...l}=t,u=typeof o!="string"&&o?.function?.name,{maxChatCompletions:d=To}=r||{},g=t.tools.map(f=>{if($e(f)){if(!f.$callback)throw new b("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:f.$callback,name:f.function.name,description:f.function.description||"",parameters:f.function.parameters,parse:f.$parseRaw,strict:!0}}}return f}),p={};for(let f of g)f.type==="function"&&(p[f.function.name||f.function.function.name]=f.function);let y="tools"in t?g.map(f=>f.type==="function"?{type:"function",function:{name:f.function.name||f.function.function.name,parameters:f.function.parameters,description:f.function.description,strict:f.function.strict}}:f):void 0;for(let f of t.messages)this._addMessage(f,!1);for(let f=0;f<d;++f){let A=(await this._createChatCompletion(e,{...l,tool_choice:o,tools:y,messages:[...this.messages]},r)).choices[0]?.message;if(!A)throw new b("missing message in ChatCompletion response");if(!A.tool_calls?.length)return;for(let R of A.tool_calls){if(R.type!=="function")continue;let S=R.id,{name:C,arguments:U}=R.function,O=p[C];if(O){if(u&&u!==C){let D=`Invalid tool_call: ${JSON.stringify(C)}. ${JSON.stringify(u)} requested. Please try again`;this._addMessage({role:s,tool_call_id:S,content:D});continue}}else{let D=`Invalid tool_call: ${JSON.stringify(C)}. Available options are: ${Object.keys(p).map(j=>JSON.stringify(j)).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:S,content:D});continue}let X;try{X=Rs(O)?await O.parse(U):U}catch(D){let j=D instanceof Error?D.message:String(D);this._addMessage({role:s,tool_call_id:S,content:j});continue}let H=await O.function(X,this),E=c(this,q,"m",Ms).call(this,H);if(this._addMessage({role:s,tool_call_id:S,content:E}),u)return}}}};q=new WeakSet,bn=function(){return c(this,q,"m",vr).call(this).content??null},vr=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(_t(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new b("stream ended without producing a ChatCompletionMessage with role=assistant")},yn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(_t(t)&&t?.tool_calls?.length)return t.tool_calls.at(-1)?.function}},Cn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(hn(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(r=>r.role==="assistant"&&r.tool_calls?.some(s=>s.type==="function"&&s.id===t.tool_call_id)))return t.content}},wn=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},Ts=function(e){if(e.n!=null&&e.n>1)throw new b("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Ms=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var sr=class n extends yt{static runTools(e,t,r){let s=new n,o={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,o)),s}_addMessage(e,t=!0){super._addMessage(e,t),_t(e)&&e.content&&this._emit("content",e.content)}};a();a();a();a();var G={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511},An=class extends Error{},xn=class extends Error{};function Mo(n,e=G.ALL){if(typeof n!="string")throw new TypeError(`expecting str, got ${typeof n}`);if(!n.trim())throw new Error(`${n} is empty`);return ko(n.trim(),e)}var ko=(n,e)=>{let t=n.length,r=0,s=y=>{throw new An(`${y} at position ${r}`)},o=y=>{throw new xn(`${y} at position ${r}`)},i=()=>(p(),r>=t&&s("Unexpected end of input"),n[r]==='"'?l():n[r]==="{"?u():n[r]==="["?d():n.substring(r,r+4)==="null"||G.NULL&e&&t-r<4&&"null".startsWith(n.substring(r))?(r+=4,null):n.substring(r,r+4)==="true"||G.BOOL&e&&t-r<4&&"true".startsWith(n.substring(r))?(r+=4,!0):n.substring(r,r+5)==="false"||G.BOOL&e&&t-r<5&&"false".startsWith(n.substring(r))?(r+=5,!1):n.substring(r,r+8)==="Infinity"||G.INFINITY&e&&t-r<8&&"Infinity".startsWith(n.substring(r))?(r+=8,1/0):n.substring(r,r+9)==="-Infinity"||G.MINUS_INFINITY&e&&1<t-r&&t-r<9&&"-Infinity".startsWith(n.substring(r))?(r+=9,-1/0):n.substring(r,r+3)==="NaN"||G.NAN&e&&t-r<3&&"NaN".startsWith(n.substring(r))?(r+=3,NaN):g()),l=()=>{let y=r,f=!1;for(r++;r<t&&(n[r]!=='"'||f&&n[r-1]==="\\");)f=n[r]==="\\"?!f:!1,r++;if(n.charAt(r)=='"')try{return JSON.parse(n.substring(y,++r-Number(f)))}catch(x){o(String(x))}else if(G.STR&e)try{return JSON.parse(n.substring(y,r-Number(f))+'"')}catch{return JSON.parse(n.substring(y,n.lastIndexOf("\\"))+'"')}s("Unterminated string literal")},u=()=>{r++,p();let y={};try{for(;n[r]!=="}";){if(p(),r>=t&&G.OBJ&e)return y;let f=l();p(),r++;try{let x=i();Object.defineProperty(y,f,{value:x,writable:!0,enumerable:!0,configurable:!0})}catch(x){if(G.OBJ&e)return y;throw x}p(),n[r]===","&&r++}}catch{if(G.OBJ&e)return y;s("Expected '}' at end of object")}return r++,y},d=()=>{r++;let y=[];try{for(;n[r]!=="]";)y.push(i()),p(),n[r]===","&&r++}catch{if(G.ARR&e)return y;s("Expected ']' at end of array")}return r++,y},g=()=>{if(r===0){n==="-"&&G.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(n)}catch(f){if(G.NUM&e)try{return n[n.length-1]==="."?JSON.parse(n.substring(0,n.lastIndexOf("."))):JSON.parse(n.substring(0,n.lastIndexOf("e")))}catch{}o(String(f))}}let y=r;for(n[r]==="-"&&r++;n[r]&&!",]}".includes(n[r]);)r++;r==t&&!(G.NUM&e)&&s("Unterminated number literal");try{return JSON.parse(n.substring(y,r))}catch{n.substring(y,r)==="-"&&G.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(n.substring(y,n.lastIndexOf("e")))}catch(x){o(String(x))}}},p=()=>{for(;r<t&&`
12
+ \r `.includes(n[r]);)r++};return i()},In=n=>Mo(n,G.ALL^G.NUM);var F,ce,Ct,ye,Pn,Tr,Rn,Sn,On,Mr,En,ks,Ne=class n extends yt{constructor(e){super(),F.add(this),ce.set(this,void 0),Ct.set(this,void 0),ye.set(this,void 0),w(this,ce,e,"f"),w(this,Ct,[],"f")}get currentChatCompletionSnapshot(){return c(this,ye,"f")}static fromReadableStream(e){let t=new n(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){let s=new n(t);return s._run(()=>s._runChatCompletion(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createChatCompletion(e,t,r){super._createChatCompletion;let s=r?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),c(this,F,"m",Pn).call(this);let o=await e.chat.completions.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let i of o)c(this,F,"m",Rn).call(this,i);if(o.controller.signal?.aborted)throw new M;return this._addChatCompletion(c(this,F,"m",Mr).call(this))}async _fromReadableStream(e,t){let r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),c(this,F,"m",Pn).call(this),this._connected();let s=re.fromReadableStream(e,this.controller),o;for await(let i of s)o&&o!==i.id&&this._addChatCompletion(c(this,F,"m",Mr).call(this)),c(this,F,"m",Rn).call(this,i),o=i.id;if(s.controller.signal?.aborted)throw new M;return this._addChatCompletion(c(this,F,"m",Mr).call(this))}[(ce=new WeakMap,Ct=new WeakMap,ye=new WeakMap,F=new WeakSet,Pn=function(){this.ended||w(this,ye,void 0,"f")},Tr=function(t){let r=c(this,Ct,"f")[t.index];return r||(r={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},c(this,Ct,"f")[t.index]=r,r)},Rn=function(t){if(this.ended)return;let r=c(this,F,"m",ks).call(this,t);this._emit("chunk",t,r);for(let s of t.choices){let o=r.choices[s.index];s.delta.content!=null&&o.message?.role==="assistant"&&o.message?.content&&(this._emit("content",s.delta.content,o.message.content),this._emit("content.delta",{delta:s.delta.content,snapshot:o.message.content,parsed:o.message.parsed})),s.delta.refusal!=null&&o.message?.role==="assistant"&&o.message?.refusal&&this._emit("refusal.delta",{delta:s.delta.refusal,snapshot:o.message.refusal}),s.logprobs?.content!=null&&o.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:s.logprobs?.content,snapshot:o.logprobs?.content??[]}),s.logprobs?.refusal!=null&&o.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:s.logprobs?.refusal,snapshot:o.logprobs?.refusal??[]});let i=c(this,F,"m",Tr).call(this,o);o.finish_reason&&(c(this,F,"m",On).call(this,o),i.current_tool_call_index!=null&&c(this,F,"m",Sn).call(this,o,i.current_tool_call_index));for(let l of s.delta.tool_calls??[])i.current_tool_call_index!==l.index&&(c(this,F,"m",On).call(this,o),i.current_tool_call_index!=null&&c(this,F,"m",Sn).call(this,o,i.current_tool_call_index)),i.current_tool_call_index=l.index;for(let l of s.delta.tool_calls??[]){let u=o.message.tool_calls?.[l.index];u?.type&&(u?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:u.function?.name,index:l.index,arguments:u.function.arguments,parsed_arguments:u.function.parsed_arguments,arguments_delta:l.function?.arguments??""}):(u?.type,void 0))}}},Sn=function(t,r){if(c(this,F,"m",Tr).call(this,t).done_tool_calls.has(r))return;let o=t.message.tool_calls?.[r];if(!o)throw new Error("no tool call snapshot");if(!o.type)throw new Error("tool call snapshot missing `type`");if(o.type==="function"){let i=c(this,ce,"f")?.tools?.find(l=>l.type==="function"&&l.function.name===o.function.name);this._emit("tool_calls.function.arguments.done",{name:o.function.name,index:r,arguments:o.function.arguments,parsed_arguments:$e(i)?i.$parseRaw(o.function.arguments):i?.function.strict?JSON.parse(o.function.arguments):null})}else o.type},On=function(t){let r=c(this,F,"m",Tr).call(this,t);if(t.message.content&&!r.content_done){r.content_done=!0;let s=c(this,F,"m",En).call(this);this._emit("content.done",{content:t.message.content,parsed:s?s.$parseRaw(t.message.content):null})}t.message.refusal&&!r.refusal_done&&(r.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal})),t.logprobs?.content&&!r.logprobs_content_done&&(r.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content})),t.logprobs?.refusal&&!r.logprobs_refusal_done&&(r.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},Mr=function(){if(this.ended)throw new b("stream has ended, this shouldn't happen");let t=c(this,ye,"f");if(!t)throw new b("request ended without sending any chunks");return w(this,ye,void 0,"f"),w(this,Ct,[],"f"),$o(t,c(this,ce,"f"))},En=function(){let t=c(this,ce,"f")?.response_format;return rr(t)?t:null},ks=function(t){var r,s,o,i;let l=c(this,ye,"f"),{choices:u,...d}=t;l?Object.assign(l,d):l=w(this,ye,{...d,choices:[]},"f");for(let{delta:g,finish_reason:p,index:y,logprobs:f=null,...x}of t.choices){let A=l.choices[y];if(A||(A=l.choices[y]={finish_reason:p,index:y,message:{},logprobs:f,...x}),f)if(!A.logprobs)A.logprobs=Object.assign({},f);else{let{content:H,refusal:E,...D}=f;Object.assign(A.logprobs,D),H&&((r=A.logprobs).content??(r.content=[]),A.logprobs.content.push(...H)),E&&((s=A.logprobs).refusal??(s.refusal=[]),A.logprobs.refusal.push(...E))}if(p&&(A.finish_reason=p,c(this,ce,"f")&&_n(c(this,ce,"f")))){if(p==="length")throw new dt;if(p==="content_filter")throw new mt}if(Object.assign(A,x),!g)continue;let{content:R,refusal:S,function_call:C,role:U,tool_calls:O,...X}=g;if(Object.assign(A.message,X),S&&(A.message.refusal=(A.message.refusal||"")+S),U&&(A.message.role=U),C&&(A.message.function_call?(C.name&&(A.message.function_call.name=C.name),C.arguments&&((o=A.message.function_call).arguments??(o.arguments=""),A.message.function_call.arguments+=C.arguments)):A.message.function_call=C),R&&(A.message.content=(A.message.content||"")+R,!A.message.refusal&&c(this,F,"m",En).call(this)&&(A.message.parsed=In(A.message.content))),O){A.message.tool_calls||(A.message.tool_calls=[]);for(let{index:H,id:E,type:D,function:j,...T}of O){let k=(i=A.message.tool_calls)[H]??(i[H]={});Object.assign(k,T),E&&(k.id=E),D&&(k.type=D),j&&(k.function??(k.function={name:j.name??"",arguments:""})),j?.name&&(k.function.name=j.name),j?.arguments&&(k.function.arguments+=j.arguments,Es(c(this,ce,"f"),k)&&(k.function.parsed_arguments=In(k.function.arguments)))}}}return l},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("chunk",s=>{let o=t.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{r=!0;for(let o of t)o.reject(s);t.length=0}),this.on("error",s=>{r=!0;for(let o of t)o.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,i)=>t.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new re(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function $o(n,e){let{id:t,choices:r,created:s,model:o,system_fingerprint:i,...l}=n,u={...l,id:t,choices:r.map(({message:d,finish_reason:g,index:p,logprobs:y,...f})=>{if(!g)throw new b(`missing finish_reason for choice ${p}`);let{content:x=null,function_call:A,tool_calls:R,...S}=d,C=d.role;if(!C)throw new b(`missing role for choice ${p}`);if(A){let{arguments:U,name:O}=A;if(U==null)throw new b(`missing function_call.arguments for choice ${p}`);if(!O)throw new b(`missing function_call.name for choice ${p}`);return{...f,message:{content:x,function_call:{arguments:U,name:O},role:C,refusal:d.refusal??null},finish_reason:g,index:p,logprobs:y}}return R?{...f,index:p,finish_reason:g,logprobs:y,message:{...S,role:C,content:x,refusal:d.refusal??null,tool_calls:R.map((U,O)=>{let{function:X,type:H,id:E,...D}=U,{arguments:j,name:T,...k}=X||{};if(E==null)throw new b(`missing choices[${p}].tool_calls[${O}].id
13
+ ${kr(n)}`);if(H==null)throw new b(`missing choices[${p}].tool_calls[${O}].type
14
+ ${kr(n)}`);if(T==null)throw new b(`missing choices[${p}].tool_calls[${O}].function.name
15
+ ${kr(n)}`);if(j==null)throw new b(`missing choices[${p}].tool_calls[${O}].function.arguments
16
+ ${kr(n)}`);return{...D,id:E,type:H,function:{...k,name:T,arguments:j}}})}}:{...f,message:{...S,content:x,role:C,refusal:d.refusal??null},finish_reason:g,index:p,logprobs:y}}),created:s,model:o,object:"chat.completion",...i?{system_fingerprint:i}:{}};return Os(u,e)}function kr(n){return JSON.stringify(n)}var or=class n extends Ne{static fromReadableStream(e){let t=new n(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,r){let s=new n(t),o={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,o)),s}};var ue=class extends h{constructor(){super(...arguments),this.messages=new ke(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(m`/chat/completions/${e}`,t)}update(e,t,r){return this._client.post(m`/chat/completions/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/chat/completions",P,{query:e,...t})}delete(e,t){return this._client.delete(m`/chat/completions/${e}`,t)}parse(e,t){return vs(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(r=>nr(r,e))}runTools(e,t){return e.stream?or.runTools(this._client,e,t):sr.runTools(this._client,e,t)}stream(e,t){return Ne.createChatCompletion(this._client,e,t)}};ue.Messages=ke;var Ce=class extends h{constructor(){super(...arguments),this.completions=new ue(this._client)}};Ce.Completions=ue;a();a();a();a();a();var $s=Symbol("brand.privateNullableHeaders");function*Fo(n){if(!n)return;if($s in n){let{values:r,nulls:s}=n;yield*r.entries();for(let o of s)yield[o,null];return}let e=!1,t;n instanceof Headers?t=n.entries():Qr(n)?t=n:(e=!0,t=Object.entries(n??{}));for(let r of t){let s=r[0];if(typeof s!="string")throw new TypeError("expected header name to be a string");let o=Qr(r[1])?r[1]:[r[1]],i=!1;for(let l of o)l!==void 0&&(e&&!i&&(i=!0,yield[s,null]),yield[s,l])}}var _=n=>{let e=new Headers,t=new Set;for(let r of n){let s=new Set;for(let[o,i]of Fo(r)){let l=o.toLowerCase();s.has(l)||(e.delete(o),s.add(l)),i===null?(e.delete(o),t.add(l)):(e.append(o,i),t.delete(l))}}return{[$s]:!0,values:e,nulls:t}};var wt=class extends h{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:_([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}};a();var At=class extends h{create(e,t){return this._client.post("/audio/transcriptions",z({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}};a();var xt=class extends h{create(e,t){return this._client.post("/audio/translations",z({body:e,...t,__metadata:{model:e.model}},this._client))}};var se=class extends h{constructor(){super(...arguments),this.transcriptions=new At(this._client),this.translations=new xt(this._client),this.speech=new wt(this._client)}};se.Transcriptions=At;se.Translations=xt;se.Speech=wt;a();var Fe=class extends h{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(m`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",P,{query:e,...t})}cancel(e,t){return this._client.post(m`/batches/${e}/cancel`,t)}};a();a();var It=class extends h{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(m`/assistants/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(m`/assistants/${e}`,{body:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",P,{query:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(m`/assistants/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};a();a();var Pt=class extends h{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};a();var Rt=class extends h{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};var we=class extends h{constructor(){super(...arguments),this.sessions=new Pt(this._client),this.transcriptionSessions=new Rt(this._client)}};we.Sessions=Pt;we.TranscriptionSessions=Rt;a();a();var St=class extends h{create(e,t,r){return this._client.post(m`/threads/${e}/messages`,{body:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{thread_id:s}=t;return this._client.get(m`/threads/${s}/messages/${e}`,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{thread_id:s,...o}=t;return this._client.post(m`/threads/${s}/messages/${e}`,{body:o,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(m`/threads/${e}/messages`,P,{query:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){let{thread_id:s}=t;return this._client.delete(m`/threads/${s}/messages/${e}`,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};a();a();var Ot=class extends h{retrieve(e,t,r){let{thread_id:s,run_id:o,...i}=t;return this._client.get(m`/threads/${s}/runs/${o}/steps/${e}`,{query:i,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t,r){let{thread_id:s,...o}=t;return this._client.getAPIList(m`/threads/${s}/runs/${e}/steps`,P,{query:o,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};a();a();a();var Ns=n=>{if(typeof Buffer<"u"){let e=Buffer.from(n,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(n),t=e.length,r=new Uint8Array(t);for(let s=0;s<t;s++)r[s]=e.charCodeAt(s);return Array.from(new Float32Array(r.buffer))}};a();var Ae=n=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[n]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(n)?.trim()};var B,Ue,vn,oe,$r,Q,De,Et,Le,Lr,K,Nr,Fr,lr,ir,ar,Fs,Ls,Us,Ds,js,Gs,Bs,fe=class extends be{constructor(){super(...arguments),B.add(this),vn.set(this,[]),oe.set(this,{}),$r.set(this,{}),Q.set(this,void 0),De.set(this,void 0),Et.set(this,void 0),Le.set(this,void 0),Lr.set(this,void 0),K.set(this,void 0),Nr.set(this,void 0),Fr.set(this,void 0),lr.set(this,void 0)}[(vn=new WeakMap,oe=new WeakMap,$r=new WeakMap,Q=new WeakMap,De=new WeakMap,Et=new WeakMap,Le=new WeakMap,Lr=new WeakMap,K=new WeakMap,Nr=new WeakMap,Fr=new WeakMap,lr=new WeakMap,B=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",s=>{let o=t.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{r=!0;for(let o of t)o.reject(s);t.length=0}),this.on("error",s=>{r=!0;for(let o of t)o.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,i)=>t.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new Ue;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){let r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),this._connected();let s=re.fromReadableStream(e,this.controller);for await(let o of s)c(this,B,"m",ir).call(this,o);if(s.controller.signal?.aborted)throw new M;return this._addRun(c(this,B,"m",ar).call(this))}toReadableStream(){return new re(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,s){let o=new Ue;return o._run(()=>o._runToolAssistantStream(e,t,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createToolAssistantStream(e,t,r,s){let o=s?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let i={...r,stream:!0},l=await e.submitToolOutputs(t,i,{...s,signal:this.controller.signal});this._connected();for await(let u of l)c(this,B,"m",ir).call(this,u);if(l.controller.signal?.aborted)throw new M;return this._addRun(c(this,B,"m",ar).call(this))}static createThreadAssistantStream(e,t,r){let s=new Ue;return s._run(()=>s._threadAssistantStream(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}static createAssistantStream(e,t,r,s){let o=new Ue;return o._run(()=>o._runAssistantStream(e,t,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return c(this,Nr,"f")}currentRun(){return c(this,Fr,"f")}currentMessageSnapshot(){return c(this,Q,"f")}currentRunStepSnapshot(){return c(this,lr,"f")}async finalRunSteps(){return await this.done(),Object.values(c(this,oe,"f"))}async finalMessages(){return await this.done(),Object.values(c(this,$r,"f"))}async finalRun(){if(await this.done(),!c(this,De,"f"))throw Error("Final run was not received.");return c(this,De,"f")}async _createThreadAssistantStream(e,t,r){let s=r?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));let o={...t,stream:!0},i=await e.createAndRun(o,{...r,signal:this.controller.signal});this._connected();for await(let l of i)c(this,B,"m",ir).call(this,l);if(i.controller.signal?.aborted)throw new M;return this._addRun(c(this,B,"m",ar).call(this))}async _createAssistantStream(e,t,r,s){let o=s?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let i={...r,stream:!0},l=await e.create(t,i,{...s,signal:this.controller.signal});this._connected();for await(let u of l)c(this,B,"m",ir).call(this,u);if(l.controller.signal?.aborted)throw new M;return this._addRun(c(this,B,"m",ar).call(this))}static accumulateDelta(e,t){for(let[r,s]of Object.entries(t)){if(!e.hasOwnProperty(r)){e[r]=s;continue}let o=e[r];if(o==null){e[r]=s;continue}if(r==="index"||r==="type"){e[r]=s;continue}if(typeof o=="string"&&typeof s=="string")o+=s;else if(typeof o=="number"&&typeof s=="number")o+=s;else if(Xt(o)&&Xt(s))o=this.accumulateDelta(o,s);else if(Array.isArray(o)&&Array.isArray(s)){if(o.every(i=>typeof i=="string"||typeof i=="number")){o.push(...s);continue}for(let i of s){if(!Xt(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);let l=i.index;if(l==null)throw console.error(i),new Error("Expected array delta entry to have an `index` property");if(typeof l!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${l}`);let u=o[l];u==null?o.push(i):o[l]=this.accumulateDelta(u,i)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${s}, accValue: ${o}`);e[r]=o}return e}_addRun(e){return e}async _threadAssistantStream(e,t,r){return await this._createThreadAssistantStream(t,e,r)}async _runAssistantStream(e,t,r,s){return await this._createAssistantStream(t,e,r,s)}async _runToolAssistantStream(e,t,r,s){return await this._createToolAssistantStream(t,e,r,s)}};Ue=fe,ir=function(e){if(!this.ended)switch(w(this,Nr,e,"f"),c(this,B,"m",Us).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":c(this,B,"m",Bs).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":c(this,B,"m",Ls).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":c(this,B,"m",Fs).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},ar=function(){if(this.ended)throw new b("stream has ended, this shouldn't happen");if(!c(this,De,"f"))throw Error("Final run has not been received");return c(this,De,"f")},Fs=function(e){let[t,r]=c(this,B,"m",js).call(this,e,c(this,Q,"f"));w(this,Q,t,"f"),c(this,$r,"f")[t.id]=t;for(let s of r){let o=t.content[s.index];o?.type=="text"&&this._emit("textCreated",o.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 s of e.data.delta.content){if(s.type=="text"&&s.text){let o=s.text,i=t.content[s.index];if(i&&i.type=="text")this._emit("textDelta",o,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(s.index!=c(this,Et,"f")){if(c(this,Le,"f"))switch(c(this,Le,"f").type){case"text":this._emit("textDone",c(this,Le,"f").text,c(this,Q,"f"));break;case"image_file":this._emit("imageFileDone",c(this,Le,"f").image_file,c(this,Q,"f"));break}w(this,Et,s.index,"f")}w(this,Le,t.content[s.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(c(this,Et,"f")!==void 0){let s=e.data.content[c(this,Et,"f")];if(s)switch(s.type){case"image_file":this._emit("imageFileDone",s.image_file,c(this,Q,"f"));break;case"text":this._emit("textDone",s.text,c(this,Q,"f"));break}}c(this,Q,"f")&&this._emit("messageDone",e.data),w(this,Q,void 0,"f")}},Ls=function(e){let t=c(this,B,"m",Ds).call(this,e);switch(w(this,lr,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let r=e.data.delta;if(r.step_details&&r.step_details.type=="tool_calls"&&r.step_details.tool_calls&&t.step_details.type=="tool_calls")for(let o of r.step_details.tool_calls)o.index==c(this,Lr,"f")?this._emit("toolCallDelta",o,t.step_details.tool_calls[o.index]):(c(this,K,"f")&&this._emit("toolCallDone",c(this,K,"f")),w(this,Lr,o.index,"f"),w(this,K,t.step_details.tool_calls[o.index],"f"),c(this,K,"f")&&this._emit("toolCallCreated",c(this,K,"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":w(this,lr,void 0,"f"),e.data.step_details.type=="tool_calls"&&c(this,K,"f")&&(this._emit("toolCallDone",c(this,K,"f")),w(this,K,void 0,"f")),this._emit("runStepDone",e.data,t);break;case"thread.run.step.in_progress":break}},Us=function(e){c(this,vn,"f").push(e),this._emit("event",e)},Ds=function(e){switch(e.event){case"thread.run.step.created":return c(this,oe,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=c(this,oe,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){let s=Ue.accumulateDelta(t,r.delta);c(this,oe,"f")[e.data.id]=s}return c(this,oe,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":c(this,oe,"f")[e.data.id]=e.data;break}if(c(this,oe,"f")[e.data.id])return c(this,oe,"f")[e.data.id];throw new Error("No snapshot available")},js=function(e,t){let r=[];switch(e.event){case"thread.message.created":return[e.data,r];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let s=e.data;if(s.delta.content)for(let o of s.delta.content)if(o.index in t.content){let i=t.content[o.index];t.content[o.index]=c(this,B,"m",Gs).call(this,o,i)}else t.content[o.index]=o,r.push(o);return[t,r];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,r];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Gs=function(e,t){return Ue.accumulateDelta(t,e)},Bs=function(e){switch(w(this,Fr,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":w(this,De,e.data,"f"),c(this,K,"f")&&(this._emit("toolCallDone",c(this,K,"f")),w(this,K,void 0,"f"));break;case"thread.run.cancelling":break}};var je=class extends h{constructor(){super(...arguments),this.steps=new Ot(this._client)}create(e,t,r){let{include:s,...o}=t;return this._client.post(m`/threads/${e}/runs`,{query:{include:s},body:o,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1})}retrieve(e,t,r){let{thread_id:s}=t;return this._client.get(m`/threads/${s}/runs/${e}`,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{thread_id:s,...o}=t;return this._client.post(m`/threads/${s}/runs/${e}`,{body:o,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(m`/threads/${e}/runs`,P,{query:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){let{thread_id:s}=t;return this._client.post(m`/threads/${s}/runs/${e}/cancel`,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let s=await this.create(e,t,r);return await this.poll(s.id,{thread_id:e},r)}createAndStream(e,t,r){return fe.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){let s=_([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:i}=await this.retrieve(e,t,{...r,headers:{...r?.headers,...s}}).withResponse();switch(o.status){case"queued":case"in_progress":case"cancelling":let l=5e3;if(r?.pollIntervalMs)l=r.pollIntervalMs;else{let u=i.headers.get("openai-poll-after-ms");if(u){let d=parseInt(u);isNaN(d)||(l=d)}}await ee(l);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return o}}}stream(e,t,r){return fe.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r){let{thread_id:s,...o}=t;return this._client.post(m`/threads/${s}/runs/${e}/submit_tool_outputs`,{body:o,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1})}async submitToolOutputsAndPoll(e,t,r){let s=await this.submitToolOutputs(e,t,r);return await this.poll(s.id,t,r)}submitToolOutputsStream(e,t,r){return fe.createToolAssistantStream(e,this._client.beta.threads.runs,t,r)}};je.Steps=Ot;var xe=class extends h{constructor(){super(...arguments),this.runs=new je(this._client),this.messages=new St(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(m`/threads/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(m`/threads/${e}`,{body:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t){return this._client.delete(m`/threads/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1})}async createAndRunPoll(e,t){let r=await this.createAndRun(e,t);return await this.runs.poll(r.id,{thread_id:r.thread_id},t)}createAndRunStream(e,t){return fe.createThreadAssistantStream(e,this._client.beta.threads,t)}};xe.Runs=je;xe.Messages=St;var ie=class extends h{constructor(){super(...arguments),this.realtime=new we(this._client),this.assistants=new It(this._client),this.threads=new xe(this._client)}};ie.Realtime=we;ie.Assistants=It;ie.Threads=xe;a();var Ge=class extends h{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}};a();a();a();var vt=class extends h{retrieve(e,t,r){let{container_id:s}=t;return this._client.get(m`/containers/${s}/files/${e}/content`,{...r,headers:_([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}};var Be=class extends h{constructor(){super(...arguments),this.content=new vt(this._client)}create(e,t,r){return this._client.post(m`/containers/${e}/files`,z({body:t,...r},this._client))}retrieve(e,t,r){let{container_id:s}=t;return this._client.get(m`/containers/${s}/files/${e}`,r)}list(e,t={},r){return this._client.getAPIList(m`/containers/${e}/files`,P,{query:t,...r})}delete(e,t,r){let{container_id:s}=t;return this._client.delete(m`/containers/${s}/files/${e}`,{...r,headers:_([{Accept:"*/*"},r?.headers])})}};Be.Content=vt;var Ie=class extends h{constructor(){super(...arguments),this.files=new Be(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(m`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",P,{query:e,...t})}delete(e,t){return this._client.delete(m`/containers/${e}`,{...t,headers:_([{Accept:"*/*"},t?.headers])})}};Ie.Files=Be;a();var We=class extends h{create(e,t){let r=!!e.encoding_format,s=r?e.encoding_format:"base64";r&&v(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let o=this._client.post("/embeddings",{body:{...e,encoding_format:s},...t});return r?o:(v(this._client).debug("embeddings/decoding base64 embeddings from base64"),o._thenUnwrap(i=>(i&&i.data&&i.data.forEach(l=>{let u=l.embedding;l.embedding=Ns(u)}),i)))}};a();a();a();var Tt=class extends h{retrieve(e,t,r){let{eval_id:s,run_id:o}=t;return this._client.get(m`/evals/${s}/runs/${o}/output_items/${e}`,r)}list(e,t,r){let{eval_id:s,...o}=t;return this._client.getAPIList(m`/evals/${s}/runs/${e}/output_items`,P,{query:o,...r})}};var He=class extends h{constructor(){super(...arguments),this.outputItems=new Tt(this._client)}create(e,t,r){return this._client.post(m`/evals/${e}/runs`,{body:t,...r})}retrieve(e,t,r){let{eval_id:s}=t;return this._client.get(m`/evals/${s}/runs/${e}`,r)}list(e,t={},r){return this._client.getAPIList(m`/evals/${e}/runs`,P,{query:t,...r})}delete(e,t,r){let{eval_id:s}=t;return this._client.delete(m`/evals/${s}/runs/${e}`,r)}cancel(e,t,r){let{eval_id:s}=t;return this._client.post(m`/evals/${s}/runs/${e}`,r)}};He.OutputItems=Tt;var Pe=class extends h{constructor(){super(...arguments),this.runs=new He(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(m`/evals/${e}`,t)}update(e,t,r){return this._client.post(m`/evals/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/evals",P,{query:e,...t})}delete(e,t){return this._client.delete(m`/evals/${e}`,t)}};Pe.Runs=He;a();var qe=class extends h{create(e,t){return this._client.post("/files",z({body:e,...t},this._client))}retrieve(e,t){return this._client.get(m`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",P,{query:e,...t})}delete(e,t){return this._client.delete(m`/files/${e}`,t)}content(e,t){return this._client.get(m`/files/${e}/content`,{...t,headers:_([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:r=30*60*1e3}={}){let s=new Set(["processed","error","deleted"]),o=Date.now(),i=await this.retrieve(e);for(;!i.status||!s.has(i.status);)if(await ee(t),i=await this.retrieve(e),Date.now()-o>r)throw new ge({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return i}};a();a();var Mt=class extends h{};a();a();var kt=class extends h{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 Xe=class extends h{constructor(){super(...arguments),this.graders=new kt(this._client)}};Xe.Graders=kt;a();a();var $t=class extends h{create(e,t,r){return this._client.getAPIList(m`/fine_tuning/checkpoints/${e}/permissions`,ne,{body:t,method:"post",...r})}retrieve(e,t={},r){return this._client.get(m`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...r})}delete(e,t,r){let{fine_tuned_model_checkpoint:s}=t;return this._client.delete(m`/fine_tuning/checkpoints/${s}/permissions/${e}`,r)}};var Je=class extends h{constructor(){super(...arguments),this.permissions=new $t(this._client)}};Je.Permissions=$t;a();a();var Nt=class extends h{list(e,t={},r){return this._client.getAPIList(m`/fine_tuning/jobs/${e}/checkpoints`,P,{query:t,...r})}};var Ve=class extends h{constructor(){super(...arguments),this.checkpoints=new Nt(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(m`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",P,{query:e,...t})}cancel(e,t){return this._client.post(m`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},r){return this._client.getAPIList(m`/fine_tuning/jobs/${e}/events`,P,{query:t,...r})}pause(e,t){return this._client.post(m`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(m`/fine_tuning/jobs/${e}/resume`,t)}};Ve.Checkpoints=Nt;var Y=class extends h{constructor(){super(...arguments),this.methods=new Mt(this._client),this.jobs=new Ve(this._client),this.checkpoints=new Je(this._client),this.alpha=new Xe(this._client)}};Y.Methods=Mt;Y.Jobs=Ve;Y.Checkpoints=Je;Y.Alpha=Xe;a();a();var Ft=class extends h{};var Re=class extends h{constructor(){super(...arguments),this.graderModels=new Ft(this._client)}};Re.GraderModels=Ft;a();var ze=class extends h{createVariation(e,t){return this._client.post("/images/variations",z({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",z({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})}};a();var Ke=class extends h{retrieve(e,t){return this._client.get(m`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",ne,e)}delete(e,t){return this._client.delete(m`/models/${e}`,t)}};a();var Qe=class extends h{create(e,t){return this._client.post("/moderations",{body:e,...t})}};a();a();function Ws(n,e){return!e||!ai(e)?{...n,output_parsed:null,output:n.output.map(t=>t.type==="function_call"?{...t,parsed_arguments:null}:t.type==="message"?{...t,content:t.content.map(r=>({...r,parsed:null}))}:t)}:Tn(n,e)}function Tn(n,e){let t=n.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:ui(e,s)};if(s.type==="message"){let o=s.content.map(i=>i.type==="output_text"?{...i,parsed:ii(e,i.text)}:i);return{...s,content:o}}return s}),r=Object.assign({},n,{output:t});return Object.getOwnPropertyDescriptor(n,"output_text")||Ur(r),Object.defineProperty(r,"output_parsed",{enumerable:!0,get(){for(let s of r.output)if(s.type==="message"){for(let o of s.content)if(o.type==="output_text"&&o.parsed!==null)return o.parsed}return null}}),r}function ii(n,e){return n.text?.format?.type!=="json_schema"?null:"$parseRaw"in n.text?.format?(n.text?.format).$parseRaw(e):JSON.parse(e)}function ai(n){return!!rr(n.text?.format)}function li(n){return n?.$brand==="auto-parseable-tool"}function ci(n,e){return n.find(t=>t.type==="function"&&t.name===e)}function ui(n,e){let t=ci(n.tools??[],e.name);return{...e,...e,parsed_arguments:li(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function Ur(n){let e=[];for(let t of n.output)if(t.type==="message")for(let r of t.content)r.type==="output_text"&&e.push(r.text);n.output_text=e.join("")}a();var Lt,Dr,Se,jr,Hs,qs,Xs,Js,Gr=class n extends be{constructor(e){super(),Lt.add(this),Dr.set(this,void 0),Se.set(this,void 0),jr.set(this,void 0),w(this,Dr,e,"f")}static createResponse(e,t,r){let s=new n(t);return s._run(()=>s._createOrRetrieveResponse(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createOrRetrieveResponse(e,t,r){let s=r?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),c(this,Lt,"m",Hs).call(this);let o,i=null;"response_id"in t?(o=await e.responses.retrieve(t.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),i=t.starting_after??null):o=await e.responses.create({...t,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(let l of o)c(this,Lt,"m",qs).call(this,l,i);if(o.controller.signal?.aborted)throw new M;return c(this,Lt,"m",Xs).call(this)}[(Dr=new WeakMap,Se=new WeakMap,jr=new WeakMap,Lt=new WeakSet,Hs=function(){this.ended||w(this,Se,void 0,"f")},qs=function(t,r){if(this.ended)return;let s=(i,l)=>{(r==null||l.sequence_number>r)&&this._emit(i,l)},o=c(this,Lt,"m",Js).call(this,t);switch(s("event",t),t.type){case"response.output_text.delta":{let i=o.output[t.output_index];if(!i)throw new b(`missing output at index ${t.output_index}`);if(i.type==="message"){let l=i.content[t.content_index];if(!l)throw new b(`missing content at index ${t.content_index}`);if(l.type!=="output_text")throw new b(`expected content to be 'output_text', got ${l.type}`);s("response.output_text.delta",{...t,snapshot:l.text})}break}case"response.function_call_arguments.delta":{let i=o.output[t.output_index];if(!i)throw new b(`missing output at index ${t.output_index}`);i.type==="function_call"&&s("response.function_call_arguments.delta",{...t,snapshot:i.arguments});break}default:s(t.type,t);break}},Xs=function(){if(this.ended)throw new b("stream has ended, this shouldn't happen");let t=c(this,Se,"f");if(!t)throw new b("request ended without sending any events");w(this,Se,void 0,"f");let r=fi(t,c(this,Dr,"f"));return w(this,jr,r,"f"),r},Js=function(t){let r=c(this,Se,"f");if(!r){if(t.type!=="response.created")throw new b(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return r=w(this,Se,t.response,"f"),r}switch(t.type){case"response.output_item.added":{r.output.push(t.item);break}case"response.content_part.added":{let s=r.output[t.output_index];if(!s)throw new b(`missing output at index ${t.output_index}`);s.type==="message"&&s.content.push(t.part);break}case"response.output_text.delta":{let s=r.output[t.output_index];if(!s)throw new b(`missing output at index ${t.output_index}`);if(s.type==="message"){let o=s.content[t.content_index];if(!o)throw new b(`missing content at index ${t.content_index}`);if(o.type!=="output_text")throw new b(`expected content to be 'output_text', got ${o.type}`);o.text+=t.delta}break}case"response.function_call_arguments.delta":{let s=r.output[t.output_index];if(!s)throw new b(`missing output at index ${t.output_index}`);s.type==="function_call"&&(s.arguments+=t.delta);break}case"response.completed":{w(this,Se,t.response,"f");break}}return r},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",s=>{let o=t.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{r=!0;for(let o of t)o.reject(s);t.length=0}),this.on("error",s=>{r=!0;for(let o of t)o.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,i)=>t.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=c(this,jr,"f");if(!e)throw new b("stream ended without producing a ChatCompletion");return e}};function fi(n,e){return Ws(n,e)}a();var Ut=class extends h{list(e,t={},r){return this._client.getAPIList(m`/responses/${e}/input_items`,P,{query:t,...r})}};var Oe=class extends h{constructor(){super(...arguments),this.inputItems=new Ut(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(r=>("object"in r&&r.object==="response"&&Ur(r),r))}retrieve(e,t={},r){return this._client.get(m`/responses/${e}`,{query:t,...r,stream:t?.stream??!1})._thenUnwrap(s=>("object"in s&&s.object==="response"&&Ur(s),s))}delete(e,t){return this._client.delete(m`/responses/${e}`,{...t,headers:_([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(r=>Tn(r,e))}stream(e,t){return Gr.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(m`/responses/${e}/cancel`,t)}};Oe.InputItems=Ut;a();a();var Dt=class extends h{create(e,t,r){return this._client.post(m`/uploads/${e}/parts`,z({body:t,...r},this._client))}};var Ee=class extends h{constructor(){super(...arguments),this.parts=new Dt(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(m`/uploads/${e}/cancel`,t)}complete(e,t,r){return this._client.post(m`/uploads/${e}/complete`,{body:t,...r})}};Ee.Parts=Dt;a();a();a();var Vs=async n=>{let e=await Promise.allSettled(n),t=e.filter(s=>s.status==="rejected");if(t.length){for(let s of t)console.error(s.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}let r=[];for(let s of e)s.status==="fulfilled"&&r.push(s.value);return r};var jt=class extends h{create(e,t,r){return this._client.post(m`/vector_stores/${e}/file_batches`,{body:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{vector_store_id:s}=t;return this._client.get(m`/vector_stores/${s}/file_batches/${e}`,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){let{vector_store_id:s}=t;return this._client.post(m`/vector_stores/${s}/file_batches/${e}/cancel`,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let s=await this.create(e,t);return await this.poll(e,s.id,r)}listFiles(e,t,r){let{vector_store_id:s,...o}=t;return this._client.getAPIList(m`/vector_stores/${s}/file_batches/${e}/files`,P,{query:o,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async poll(e,t,r){let s=_([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:i}=await this.retrieve(t,{vector_store_id:e},{...r,headers:s}).withResponse();switch(o.status){case"in_progress":let l=5e3;if(r?.pollIntervalMs)l=r.pollIntervalMs;else{let u=i.headers.get("openai-poll-after-ms");if(u){let d=parseInt(u);isNaN(d)||(l=d)}}await ee(l);break;case"failed":case"cancelled":case"completed":return o}}}async uploadAndPoll(e,{files:t,fileIds:r=[]},s){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 o=s?.maxConcurrency??5,i=Math.min(o,t.length),l=this._client,u=t.values(),d=[...r];async function g(y){for(let f of y){let x=await l.files.create({file:f,purpose:"assistants"},s);d.push(x.id)}}let p=Array(i).fill(u).map(g);return await Vs(p),await this.createAndPoll(e,{file_ids:d})}};a();var Gt=class extends h{create(e,t,r){return this._client.post(m`/vector_stores/${e}/files`,{body:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{vector_store_id:s}=t;return this._client.get(m`/vector_stores/${s}/files/${e}`,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{vector_store_id:s,...o}=t;return this._client.post(m`/vector_stores/${s}/files/${e}`,{body:o,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(m`/vector_stores/${e}/files`,P,{query:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){let{vector_store_id:s}=t;return this._client.delete(m`/vector_stores/${s}/files/${e}`,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let s=await this.create(e,t,r);return await this.poll(e,s.id,r)}async poll(e,t,r){let s=_([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let o=await this.retrieve(t,{vector_store_id:e},{...r,headers:s}).withResponse(),i=o.data;switch(i.status){case"in_progress":let l=5e3;if(r?.pollIntervalMs)l=r.pollIntervalMs;else{let u=o.response.headers.get("openai-poll-after-ms");if(u){let d=parseInt(u);isNaN(d)||(l=d)}}await ee(l);break;case"failed":case"completed":return i}}}async upload(e,t,r){let s=await this._client.files.create({file:t,purpose:"assistants"},r);return this.create(e,{file_id:s.id},r)}async uploadAndPoll(e,t,r){let s=await this.upload(e,t,r);return await this.poll(e,s.id,r)}content(e,t,r){let{vector_store_id:s}=t;return this._client.getAPIList(m`/vector_stores/${s}/files/${e}/content`,ne,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};var pe=class extends h{constructor(){super(...arguments),this.files=new Gt(this._client),this.fileBatches=new jt(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(m`/vector_stores/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(m`/vector_stores/${e}`,{body:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",P,{query:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(m`/vector_stores/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,r){return this._client.getAPIList(m`/vector_stores/${e}/search`,ne,{body:t,method:"post",...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};pe.Files=Gt;pe.FileBatches=jt;a();var Bt,zs,Br,Ye=class extends h{constructor(){super(...arguments),Bt.add(this)}async unwrap(e,t,r=this._client.webhookSecret,s=300){return await this.verifySignature(e,t,r,s),JSON.parse(e)}async verifySignature(e,t,r=this._client.webhookSecret,s=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");c(this,Bt,"m",zs).call(this,r);let o=_([t]).values,i=c(this,Bt,"m",Br).call(this,o,"webhook-signature"),l=c(this,Bt,"m",Br).call(this,o,"webhook-timestamp"),u=c(this,Bt,"m",Br).call(this,o,"webhook-id"),d=parseInt(l,10);if(isNaN(d))throw new Z("Invalid webhook timestamp format");let g=Math.floor(Date.now()/1e3);if(g-d>s)throw new Z("Webhook timestamp is too old");if(d>g+s)throw new Z("Webhook timestamp is too new");let p=i.split(" ").map(A=>A.startsWith("v1,")?A.substring(3):A),y=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),f=u?`${u}.${l}.${e}`:`${l}.${e}`,x=await crypto.subtle.importKey("raw",y,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let A of p)try{let R=Buffer.from(A,"base64");if(await crypto.subtle.verify("HMAC",x,R,new TextEncoder().encode(f)))return}catch{continue}throw new Z("The given webhook signature does not match the expected signature")}};Bt=new WeakSet,zs=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")},Br=function(e,t){if(!e)throw new Error("Headers are required");let r=e.get(t);if(r==null)throw new Error(`Missing required header: ${t}`);return r};var Mn,kn,Wr,Ks,I=class{constructor({baseURL:e=Ae("OPENAI_BASE_URL"),apiKey:t=Ae("OPENAI_API_KEY"),organization:r=Ae("OPENAI_ORG_ID")??null,project:s=Ae("OPENAI_PROJECT_ID")??null,webhookSecret:o=Ae("OPENAI_WEBHOOK_SECRET")??null,...i}={}){if(Mn.add(this),Wr.set(this,void 0),this.completions=new Ge(this),this.chat=new Ce(this),this.embeddings=new We(this),this.files=new qe(this),this.images=new ze(this),this.audio=new se(this),this.moderations=new Qe(this),this.models=new Ke(this),this.fineTuning=new Y(this),this.graders=new Re(this),this.vectorStores=new pe(this),this.webhooks=new Ye(this),this.beta=new ie(this),this.batches=new Fe(this),this.uploads=new Ee(this),this.responses=new Oe(this),this.evals=new Pe(this),this.containers=new Ie(this),t===void 0)throw new b("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");let l={apiKey:t,organization:r,project:s,webhookSecret:o,...i,baseURL:e||"https://api.openai.com/v1"};if(!l.dangerouslyAllowBrowser&&is())throw new b(`It looks like you're running in a browser-like environment.
17
17
 
18
18
  This is disabled by default, as it risks exposing your secret API credentials to attackers.
19
19
  If you understand the risks and have appropriate mitigations in place,
@@ -22,11 +22,11 @@ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
22
22
  new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
23
23
 
24
24
  https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
25
- `);this.baseURL=l.baseURL,this.timeout=l.timeout??kn.DEFAULT_TIMEOUT,this.logger=l.logger??console;let u="warn";this.logLevel=u,this.logLevel=ln(l.logLevel,"ClientOptions.logLevel",this)??ln(Ae("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??u,this.fetchOptions=l.fetchOptions,this.maxRetries=l.maxRetries??2,this.fetch=l.fetch??ls(),w(this,Wr,us,"f"),this._options=l,this.apiKey=t,this.organization=r,this.project=s,this.webhookSecret=o}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){}async authHeaders(e){return _([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return on(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${_e}`}defaultIdempotencyKey(){return`stainless-node-retry-${Kr()}`}makeStatusError(e,t,r,s){return $.generate(e,t,r,s)}buildURL(e,t,r){let s=!c(this,Mn,"m",Ks).call(this)&&r||this.baseURL,o=Qn(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return Zn(i)||(t={...i,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(o.search=this.stringifyQuery(t)),o.toString()}async prepareOptions(e){}async prepareRequest(e,{url:t,options:r}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then(s=>({method:e,path:t,...s})))}request(e,t=null){return new Me(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){let s=await e,o=s.maxRetries??this.maxRetries;t==null&&(t=o),await this.prepareOptions(s);let{req:i,url:l,timeout:u}=await this.buildRequest(s,{retryCount:o-t});await this.prepareRequest(i,{url:l,options:s});let p="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),g=r===void 0?"":`, retryOf: ${r}`,m=Date.now();if(v(this).debug(`[${p}] sending request`,ae({retryOfRequestLogID:r,method:s.method,url:l,options:s,headers:i.headers})),s.signal?.aborted)throw new M;let y=new AbortController,f=await this.fetchWithTimeout(l,i,u,y).catch(qt),x=Date.now();if(f instanceof Error){let S=`retrying, ${t} attempts remaining`;if(s.signal?.aborted)throw new M;let C=Ht(f)||/timed? ?out/i.test(String(f)+("cause"in f?String(f.cause):""));if(t)return v(this).info(`[${p}] connection ${C?"timed out":"failed"} - ${S}`),v(this).debug(`[${p}] connection ${C?"timed out":"failed"} (${S})`,ae({retryOfRequestLogID:r,url:l,durationMs:x-m,message:f.message})),this.retryRequest(s,t,r??p);throw v(this).info(`[${p}] connection ${C?"timed out":"failed"} - error; no more retries left`),v(this).debug(`[${p}] connection ${C?"timed out":"failed"} (error; no more retries left)`,ae({retryOfRequestLogID:r,url:l,durationMs:x-m,message:f.message})),C?new ge:new he({cause:f})}let A=[...f.headers.entries()].filter(([S])=>S==="x-request-id").map(([S,C])=>", "+S+": "+JSON.stringify(C)).join(""),R=`[${p}${g}${A}] ${i.method} ${l} ${f.ok?"succeeded":"failed"} with status ${f.status} in ${x-m}ms`;if(!f.ok){let S=await this.shouldRetry(f);if(t&&S){let E=`retrying, ${t} attempts remaining`;return await cs(f.body),v(this).info(`${R} - ${E}`),v(this).debug(`[${p}] response error (${E})`,ae({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,durationMs:x-m})),this.retryRequest(s,t,r??p,f.headers)}let C=S?"error; no more retries left":"error; not retryable";v(this).info(`${R} - ${C}`);let U=await f.text().catch(E=>qt(E).message),O=rs(U),X=O?void 0:U;throw v(this).debug(`[${p}] response error (${C})`,ae({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,message:X,durationMs:Date.now()-m})),this.makeStatusError(f.status,O,X,f.headers)}return v(this).info(R),v(this).debug(`[${p}] response start`,ae({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,durationMs:x-m})),{response:f,options:s,controller:y,requestLogID:p,retryOfRequestLogID:r,startTime:m}}getAPIList(e,t,r){return this.requestAPIList(t,{method:"get",path:e,...r})}requestAPIList(e,t){let r=this.makeRequest(t,null,void 0);return new Kt(this,r,e)}async fetchWithTimeout(e,t,r,s){let{signal:o,method:i,...l}=t||{};o&&o.addEventListener("abort",()=>s.abort());let u=setTimeout(()=>s.abort(),r),p=globalThis.ReadableStream&&l.body instanceof globalThis.ReadableStream||typeof l.body=="object"&&l.body!==null&&Symbol.asyncIterator in l.body,g={signal:s.signal,...p?{duplex:"half"}:{},method:"GET",...l};i&&(g.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,g)}finally{clearTimeout(u)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,r,s){let o,i=s?.get("retry-after-ms");if(i){let u=parseFloat(i);Number.isNaN(u)||(o=u)}let l=s?.get("retry-after");if(l&&!o){let u=parseFloat(l);Number.isNaN(u)?o=Date.parse(l)-Date.now():o=u*1e3}if(!(o&&0<=o&&o<60*1e3)){let u=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(t,u)}return await ee(o),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){let o=t-e,i=Math.min(.5*Math.pow(2,o),8),l=1-Math.random()*.25;return i*l*1e3}async buildRequest(e,{retryCount:t=0}={}){let r={...e},{method:s,path:o,query:i,defaultBaseURL:l}=r,u=this.buildURL(o,i,l);"timeout"in r&&ts("timeout",r.timeout),r.timeout=r.timeout??this.timeout;let{bodyHeaders:p,body:g}=this.buildBody({options:r}),m=await this.buildHeaders({options:e,method:s,bodyHeaders:p,retryCount:t});return{req:{method:s,headers:m,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&g instanceof globalThis.ReadableStream&&{duplex:"half"},...g&&{body:g},...this.fetchOptions??{},...r.fetchOptions??{}},url:u,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:s}){let o={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let i=_([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...as(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(i),i.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let r=_([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&r.values.has("content-type")||e instanceof Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:hr(e)}:c(this,Wr,"f").call(this,{body:e,headers:r})}};kn=I,Wr=new WeakMap,Mn=new WeakSet,Ks=function(){return this.baseURL!=="https://api.openai.com/v1"};I.OpenAI=kn;I.DEFAULT_TIMEOUT=6e5;I.OpenAIError=b;I.APIError=$;I.APIConnectionError=he;I.APIConnectionTimeoutError=ge;I.APIUserAbortError=M;I.NotFoundError=lt;I.ConflictError=ct;I.RateLimitError=ft;I.BadRequestError=ot;I.AuthenticationError=it;I.InternalServerError=pt;I.PermissionDeniedError=at;I.UnprocessableEntityError=ut;I.InvalidWebhookSignatureError=Z;I.toFile=Ir;I.Completions=Ge;I.Chat=Ce;I.Embeddings=We;I.Files=qe;I.Images=ze;I.Audio=se;I.Moderations=Qe;I.Models=Ke;I.FineTuning=Y;I.Graders=Re;I.VectorStores=pe;I.Webhooks=Ye;I.Beta=ie;I.Batches=Fe;I.Uploads=Ee;I.Responses=Oe;I.Evals=Pe;I.Containers=Ie;a();function _i(n){return n.toLowerCase().includes("matilda3")}function bi(n){if(n.role!=="assistant")return n;let e=n;return typeof e.reasoning_content!="string"||e.reasoning_content.length===0||typeof e.reasoning=="string"?n:{...e,reasoning:e.reasoning_content}}var L=class{contentGeneratorConfig;cliConfig;constructor(e,t){this.cliConfig=t,this.contentGeneratorConfig=e}buildHeaders(){let t=`MatildaCode/${this.cliConfig.getCliVersion()||"unknown"} (${process.platform}; ${process.arch})`,{customHeaders:r}=this.contentGeneratorConfig,s={"User-Agent":t};return r?{...s,...r}:s}buildClient(){let{apiKey:e,baseUrl:t,timeout:r=12e4,maxRetries:s=3}=this.contentGeneratorConfig,o=this.buildHeaders(),i=mr("openai",this.cliConfig.getProxy());return new I({apiKey:e,baseURL:t,timeout:r,maxRetries:s,defaultHeaders:o,...i||{}})}buildRequest(e,t){let r=this.contentGeneratorConfig.extra_body,s=this.applyOutputTokenLimit(e),o=_i(e.model)?s.messages.map(bi):s.messages;return{...s,messages:o,...r||{}}}getDefaultGenerationConfig(){return{}}applyOutputTokenLimit(e){if(this.contentGeneratorConfig.samplingParams!==void 0)return e;let t=e.max_tokens,r=qn(e.model,"output"),s=Hn(e.model),o;if(t!=null)s?o=Math.min(t,r):o=t;else{let i=process.env.MATILDA_CODE_MAX_OUTPUT_TOKENS,l=i?parseInt(i,10):NaN;!isNaN(l)&&l>0?o=s?Math.min(l,r):l:o=Math.min(r,8e3)}return{...e,max_tokens:o}}};var Wt=class extends L{static isModelScopeProvider(e){return!!e.baseUrl?.includes("modelscope")}buildRequest(e,t){let r=super.buildRequest(e,t);return r.stream||delete r.stream_options,r}};a();var yi=me("MatildaOpenAICompatibleProvider"),de=class n extends L{constructor(e,t){super(e,t)}static isMatildaCompatibleProvider(e){let{authType:t,baseUrl:r}=e;if(t==="matilda-oauth"||!r)return!0;let s=r.endsWith("/")?r.slice(0,-1):r,o=null;try{o=new URL(s).hostname.toLowerCase()}catch{o=null}let i=o!==null&&(o==="matilda.maincode.com"||o.endsWith(".matilda.maincode.com")||o==="localhost"||o==="127.0.0.1"||o.endsWith(".matilda")||o==="core-api.matilda"),l=dr?.endsWith("/")?dr.slice(0,-1):dr,u=!!(l&&s.toLowerCase()===l.toLowerCase());return l&&!i&&!u&&yi.debug("MATILDA_COMPAT_PROXY_BASE_URL is configured but the request baseUrl does not match. Cache control helpers will be skipped."),i||u}buildHeaders(){let t=`MatildaCode/${this.cliConfig.getCliVersion()||"unknown"} (${process.platform}; ${process.arch})`,{customHeaders:r}=this.contentGeneratorConfig,s={"User-Agent":t};for(let[o,i]of Object.entries(r??{}))Vn(o)||(s[o]=i);return zn(this.contentGeneratorConfig)&&Object.assign(s,Jn(this.cliConfig)),s}buildClient(){let{apiKey:e,baseUrl:t=Xn,timeout:r=12e4,maxRetries:s=3}=this.contentGeneratorConfig,o=this.buildHeaders(),i=mr("openai",this.cliConfig.getProxy());return new I({apiKey:e,baseURL:t,timeout:r,maxRetries:s,defaultHeaders:o,...i||{}})}buildRequest(e,t){let r=e.messages,s=e.tools;if(this.shouldEnableCacheControl()){let{messages:l,tools:u}=this.addCacheControl(e,e.stream?"all":"system_only");r=l,s=u}let o=this.applyOutputTokenLimit(e),i=this.contentGeneratorConfig.extra_body;return this.isVisionModel(e.model)?{...o,messages:r,...s?{tools:s}:{},...this.buildMetadata(t)||{},vl_high_resolution_images:!0,...i||{}}:{...o,messages:r,...s?{tools:s}:{},...this.buildMetadata(t)||{},...i||{}}}buildMetadata(e){let t=this.cliConfig.getChannel?.();return{metadata:{sessionId:this.cliConfig.getSessionId?.(),promptId:e,...t?{channel:t}:{}}}}getDefaultGenerationConfig(){return{}}addCacheControl(e,t){let r=e.messages,s=r.findIndex(u=>u.role==="system"),o=r.length-1,i=r.length===0?r:r.map((u,p)=>!(p===s&&s!==-1||p===o&&t==="all")||!("content"in u)||u.content===null||u.content===void 0?u:{...u,content:this.addCacheControlToContent(u.content)}),l=t==="all"&&e.tools?.length?this.addCacheControlToTools(e.tools):e.tools;return{messages:i,tools:l}}addCacheControlToTools(e){if(e.length===0)return e;let t=[...e],r=e.length-1;return t[r]={...t[r],cache_control:{type:"ephemeral"}},t}addCacheControlToContent(e){let t=this.normalizeContentToArray(e);return this.addCacheControlToContentArray(t)}normalizeContentToArray(e){return typeof e=="string"?[{type:"text",text:e}]:[...e]}addCacheControlToContentArray(e){if(e.length===0)return e;let t=e[e.length-1];return e[e.length-1]={...t,cache_control:{type:"ephemeral"}},e}static VISION_MODEL_EXACT_MATCHES=new Set(["coder-model"]);static VISION_MODEL_PREFIX_PATTERNS=["matilda-vl","matilda3-vl-plus","matilda3.5-plus","matilda3.6-plus","matilda3.7-plus"];isVisionModel(e){if(!e)return!1;let t=e.toLowerCase();if(n.VISION_MODEL_EXACT_MATCHES.has(t))return!0;for(let r of n.VISION_MODEL_PREFIX_PATTERNS)if(t.startsWith(r))return!0;return!1}shouldEnableCacheControl(){return this.cliConfig.getContentGeneratorConfig()?.enableCacheControl!==!1}};a();a();function Hr(n){if(n.role!=="assistant")return n;let e=n;return typeof e.reasoning_content=="string"?n:{...e,reasoning_content:""}}function cr(n){let e=n.baseUrl??"";if(!e)return!1;try{let t=new URL(e).hostname.toLowerCase();return t==="api.deepseek.com"||t.endsWith(".api.deepseek.com")}catch{return!1}}function Ci(n){return cr(n)?!0:(n.model??"").toLowerCase().includes("deepseek")}var Ze=class extends L{constructor(e,t){super(e,t)}static isDeepSeekProvider=Ci;static isDeepSeekHostname=cr;buildRequest(e,t){let r=super.buildRequest(e,t),s=cr(this.contentGeneratorConfig)?Ai(r):r;if(!s.messages?.length)return s;let o=s.messages.map(i=>{let l=wi(i);return Hr(l)});return{...s,messages:o}}getDefaultGenerationConfig(){return{temperature:0}}};function wi(n){if(!("content"in n))return n;let{content:e}=n;if(typeof e=="string"||e===null||e===void 0||!Array.isArray(e))return n;let t=e.map(r=>typeof r=="string"?r:r.type==="text"?r.text??"":`[Unsupported content type: ${r.type}]`).join(`
25
+ `);this.baseURL=l.baseURL,this.timeout=l.timeout??kn.DEFAULT_TIMEOUT,this.logger=l.logger??console;let u="warn";this.logLevel=u,this.logLevel=ln(l.logLevel,"ClientOptions.logLevel",this)??ln(Ae("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??u,this.fetchOptions=l.fetchOptions,this.maxRetries=l.maxRetries??2,this.fetch=l.fetch??ls(),w(this,Wr,us,"f"),this._options=l,this.apiKey=t,this.organization=r,this.project=s,this.webhookSecret=o}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){}async authHeaders(e){return _([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return on(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${_e}`}defaultIdempotencyKey(){return`stainless-node-retry-${Kr()}`}makeStatusError(e,t,r,s){return $.generate(e,t,r,s)}buildURL(e,t,r){let s=!c(this,Mn,"m",Ks).call(this)&&r||this.baseURL,o=Qn(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return Zn(i)||(t={...i,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(o.search=this.stringifyQuery(t)),o.toString()}async prepareOptions(e){}async prepareRequest(e,{url:t,options:r}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then(s=>({method:e,path:t,...s})))}request(e,t=null){return new Me(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){let s=await e,o=s.maxRetries??this.maxRetries;t==null&&(t=o),await this.prepareOptions(s);let{req:i,url:l,timeout:u}=await this.buildRequest(s,{retryCount:o-t});await this.prepareRequest(i,{url:l,options:s});let d="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),g=r===void 0?"":`, retryOf: ${r}`,p=Date.now();if(v(this).debug(`[${d}] sending request`,ae({retryOfRequestLogID:r,method:s.method,url:l,options:s,headers:i.headers})),s.signal?.aborted)throw new M;let y=new AbortController,f=await this.fetchWithTimeout(l,i,u,y).catch(qt),x=Date.now();if(f instanceof Error){let S=`retrying, ${t} attempts remaining`;if(s.signal?.aborted)throw new M;let C=Ht(f)||/timed? ?out/i.test(String(f)+("cause"in f?String(f.cause):""));if(t)return v(this).info(`[${d}] connection ${C?"timed out":"failed"} - ${S}`),v(this).debug(`[${d}] connection ${C?"timed out":"failed"} (${S})`,ae({retryOfRequestLogID:r,url:l,durationMs:x-p,message:f.message})),this.retryRequest(s,t,r??d);throw v(this).info(`[${d}] connection ${C?"timed out":"failed"} - error; no more retries left`),v(this).debug(`[${d}] connection ${C?"timed out":"failed"} (error; no more retries left)`,ae({retryOfRequestLogID:r,url:l,durationMs:x-p,message:f.message})),C?new ge:new he({cause:f})}let A=[...f.headers.entries()].filter(([S])=>S==="x-request-id").map(([S,C])=>", "+S+": "+JSON.stringify(C)).join(""),R=`[${d}${g}${A}] ${i.method} ${l} ${f.ok?"succeeded":"failed"} with status ${f.status} in ${x-p}ms`;if(!f.ok){let S=await this.shouldRetry(f);if(t&&S){let E=`retrying, ${t} attempts remaining`;return await cs(f.body),v(this).info(`${R} - ${E}`),v(this).debug(`[${d}] response error (${E})`,ae({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,durationMs:x-p})),this.retryRequest(s,t,r??d,f.headers)}let C=S?"error; no more retries left":"error; not retryable";v(this).info(`${R} - ${C}`);let U=await f.text().catch(E=>qt(E).message),O=rs(U),X=O?void 0:U;throw v(this).debug(`[${d}] response error (${C})`,ae({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,message:X,durationMs:Date.now()-p})),this.makeStatusError(f.status,O,X,f.headers)}return v(this).info(R),v(this).debug(`[${d}] response start`,ae({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,durationMs:x-p})),{response:f,options:s,controller:y,requestLogID:d,retryOfRequestLogID:r,startTime:p}}getAPIList(e,t,r){return this.requestAPIList(t,{method:"get",path:e,...r})}requestAPIList(e,t){let r=this.makeRequest(t,null,void 0);return new Kt(this,r,e)}async fetchWithTimeout(e,t,r,s){let{signal:o,method:i,...l}=t||{};o&&o.addEventListener("abort",()=>s.abort());let u=setTimeout(()=>s.abort(),r),d=globalThis.ReadableStream&&l.body instanceof globalThis.ReadableStream||typeof l.body=="object"&&l.body!==null&&Symbol.asyncIterator in l.body,g={signal:s.signal,...d?{duplex:"half"}:{},method:"GET",...l};i&&(g.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,g)}finally{clearTimeout(u)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,r,s){let o,i=s?.get("retry-after-ms");if(i){let u=parseFloat(i);Number.isNaN(u)||(o=u)}let l=s?.get("retry-after");if(l&&!o){let u=parseFloat(l);Number.isNaN(u)?o=Date.parse(l)-Date.now():o=u*1e3}if(!(o&&0<=o&&o<60*1e3)){let u=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(t,u)}return await ee(o),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){let o=t-e,i=Math.min(.5*Math.pow(2,o),8),l=1-Math.random()*.25;return i*l*1e3}async buildRequest(e,{retryCount:t=0}={}){let r={...e},{method:s,path:o,query:i,defaultBaseURL:l}=r,u=this.buildURL(o,i,l);"timeout"in r&&ts("timeout",r.timeout),r.timeout=r.timeout??this.timeout;let{bodyHeaders:d,body:g}=this.buildBody({options:r}),p=await this.buildHeaders({options:e,method:s,bodyHeaders:d,retryCount:t});return{req:{method:s,headers:p,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&g instanceof globalThis.ReadableStream&&{duplex:"half"},...g&&{body:g},...this.fetchOptions??{},...r.fetchOptions??{}},url:u,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:s}){let o={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let i=_([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...as(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(i),i.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let r=_([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&r.values.has("content-type")||e instanceof Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:hr(e)}:c(this,Wr,"f").call(this,{body:e,headers:r})}};kn=I,Wr=new WeakMap,Mn=new WeakSet,Ks=function(){return this.baseURL!=="https://api.openai.com/v1"};I.OpenAI=kn;I.DEFAULT_TIMEOUT=6e5;I.OpenAIError=b;I.APIError=$;I.APIConnectionError=he;I.APIConnectionTimeoutError=ge;I.APIUserAbortError=M;I.NotFoundError=lt;I.ConflictError=ct;I.RateLimitError=ft;I.BadRequestError=ot;I.AuthenticationError=it;I.InternalServerError=pt;I.PermissionDeniedError=at;I.UnprocessableEntityError=ut;I.InvalidWebhookSignatureError=Z;I.toFile=Ir;I.Completions=Ge;I.Chat=Ce;I.Embeddings=We;I.Files=qe;I.Images=ze;I.Audio=se;I.Moderations=Qe;I.Models=Ke;I.FineTuning=Y;I.Graders=Re;I.VectorStores=pe;I.Webhooks=Ye;I.Beta=ie;I.Batches=Fe;I.Uploads=Ee;I.Responses=Oe;I.Evals=Pe;I.Containers=Ie;a();function _i(n){return n.toLowerCase().includes("matilda3")}function bi(n){if(n.role!=="assistant")return n;let e=n;return typeof e.reasoning_content!="string"||e.reasoning_content.length===0||typeof e.reasoning=="string"?n:{...e,reasoning:e.reasoning_content}}var L=class{contentGeneratorConfig;cliConfig;constructor(e,t){this.cliConfig=t,this.contentGeneratorConfig=e}buildHeaders(){let t=`MatildaCode/${this.cliConfig.getCliVersion()||"unknown"} (${process.platform}; ${process.arch})`,{customHeaders:r}=this.contentGeneratorConfig,s={"User-Agent":t};return r?{...s,...r}:s}buildClient(){let{apiKey:e,baseUrl:t,timeout:r=12e4,maxRetries:s=3}=this.contentGeneratorConfig,o=this.buildHeaders(),i=mr("openai",this.cliConfig.getProxy());return new I({apiKey:e,baseURL:t,timeout:r,maxRetries:s,defaultHeaders:o,...i||{}})}buildRequest(e,t){let r=this.contentGeneratorConfig.extra_body,s=this.applyOutputTokenLimit(e),o=_i(e.model)?s.messages.map(bi):s.messages;return{...s,messages:o,...r||{}}}getDefaultGenerationConfig(){return{}}applyOutputTokenLimit(e){if(this.contentGeneratorConfig.samplingParams!==void 0)return e;let t=e.max_tokens,r=qn(e.model,"output"),s=Hn(e.model),o;if(t!=null)s?o=Math.min(t,r):o=t;else{let i=process.env.MATILDA_CODE_MAX_OUTPUT_TOKENS,l=i?parseInt(i,10):NaN;!isNaN(l)&&l>0?o=s?Math.min(l,r):l:o=Math.min(r,8e3)}return{...e,max_tokens:o}}};var Wt=class extends L{static isModelScopeProvider(e){return!!e.baseUrl?.includes("modelscope")}buildRequest(e,t){let r=super.buildRequest(e,t);return r.stream||delete r.stream_options,r}};a();var yi=me("MatildaOpenAICompatibleProvider"),de=class n extends L{constructor(e,t){super(e,t)}static isMatildaCompatibleProvider(e){let{authType:t,baseUrl:r}=e;if(t==="matilda-oauth"||!r)return!0;let s=r.endsWith("/")?r.slice(0,-1):r,o=null;try{o=new URL(s).hostname.toLowerCase()}catch{o=null}let i=o!==null&&(o==="matilda.maincode.com"||o.endsWith(".matilda.maincode.com")||o==="localhost"||o==="127.0.0.1"||o.endsWith(".matilda")||o==="core-api.matilda"),l=dr?.endsWith("/")?dr.slice(0,-1):dr,u=!!(l&&s.toLowerCase()===l.toLowerCase());return l&&!i&&!u&&yi.debug("MATILDA_COMPAT_PROXY_BASE_URL is configured but the request baseUrl does not match. Cache control helpers will be skipped."),i||u}buildHeaders(){let t=`MatildaCode/${this.cliConfig.getCliVersion()||"unknown"} (${process.platform}; ${process.arch})`,{customHeaders:r}=this.contentGeneratorConfig,s={"User-Agent":t};for(let[o,i]of Object.entries(r??{}))Vn(o)||(s[o]=i);return zn(this.contentGeneratorConfig)&&Object.assign(s,Jn(this.cliConfig)),s}buildClient(){let{apiKey:e,baseUrl:t=Xn,timeout:r=12e4,maxRetries:s=3}=this.contentGeneratorConfig,o=this.buildHeaders(),i=mr("openai",this.cliConfig.getProxy());return new I({apiKey:e,baseURL:t,timeout:r,maxRetries:s,defaultHeaders:o,...i||{}})}buildRequest(e,t){let r=e.messages,s=e.tools;if(this.shouldEnableCacheControl()){let{messages:l,tools:u}=this.addCacheControl(e,e.stream?"all":"system_only");r=l,s=u}let o=this.applyOutputTokenLimit(e),i=this.contentGeneratorConfig.extra_body;return this.isVisionModel(e.model)?{...o,messages:r,...s?{tools:s}:{},...this.buildMetadata(t)||{},vl_high_resolution_images:!0,...i||{}}:{...o,messages:r,...s?{tools:s}:{},...this.buildMetadata(t)||{},...i||{}}}buildMetadata(e){let t=this.cliConfig.getChannel?.();return{metadata:{sessionId:this.cliConfig.getSessionId?.(),promptId:e,...t?{channel:t}:{}}}}getDefaultGenerationConfig(){return{}}addCacheControl(e,t){let r=e.messages,s=r.findIndex(u=>u.role==="system"),o=r.length-1,i=r.length===0?r:r.map((u,d)=>!(d===s&&s!==-1||d===o&&t==="all")||!("content"in u)||u.content===null||u.content===void 0?u:{...u,content:this.addCacheControlToContent(u.content)}),l=t==="all"&&e.tools?.length?this.addCacheControlToTools(e.tools):e.tools;return{messages:i,tools:l}}addCacheControlToTools(e){if(e.length===0)return e;let t=[...e],r=e.length-1;return t[r]={...t[r],cache_control:{type:"ephemeral"}},t}addCacheControlToContent(e){let t=this.normalizeContentToArray(e);return this.addCacheControlToContentArray(t)}normalizeContentToArray(e){return typeof e=="string"?[{type:"text",text:e}]:[...e]}addCacheControlToContentArray(e){if(e.length===0)return e;let t=e[e.length-1];return e[e.length-1]={...t,cache_control:{type:"ephemeral"}},e}static VISION_MODEL_EXACT_MATCHES=new Set(["coder-model"]);static VISION_MODEL_PREFIX_PATTERNS=["matilda-vl","matilda3-vl-plus","matilda3.5-plus","matilda3.6-plus","matilda3.7-plus"];isVisionModel(e){if(!e)return!1;let t=e.toLowerCase();if(n.VISION_MODEL_EXACT_MATCHES.has(t))return!0;for(let r of n.VISION_MODEL_PREFIX_PATTERNS)if(t.startsWith(r))return!0;return!1}shouldEnableCacheControl(){return this.cliConfig.getContentGeneratorConfig()?.enableCacheControl!==!1}};a();a();function Hr(n){if(n.role!=="assistant")return n;let e=n;return typeof e.reasoning_content=="string"?n:{...e,reasoning_content:""}}function cr(n){let e=n.baseUrl??"";if(!e)return!1;try{let t=new URL(e).hostname.toLowerCase();return t==="api.deepseek.com"||t.endsWith(".api.deepseek.com")}catch{return!1}}function Ci(n){return cr(n)?!0:(n.model??"").toLowerCase().includes("deepseek")}var Ze=class extends L{constructor(e,t){super(e,t)}static isDeepSeekProvider=Ci;static isDeepSeekHostname=cr;buildRequest(e,t){let r=super.buildRequest(e,t),s=cr(this.contentGeneratorConfig)?Ai(r):r;if(!s.messages?.length)return s;let o=s.messages.map(i=>{let l=wi(i);return Hr(l)});return{...s,messages:o}}getDefaultGenerationConfig(){return{temperature:0}}};function wi(n){if(!("content"in n))return n;let{content:e}=n;if(typeof e=="string"||e===null||e===void 0||!Array.isArray(e))return n;let t=e.map(r=>typeof r=="string"?r:r.type==="text"?r.text??"":`[Unsupported content type: ${r.type}]`).join(`
26
26
 
27
- `);return{...n,content:t}}function Ai(n){let e=n,t=e.reasoning,r=t?.effort;if(typeof r!="string"||!r)return n;let s={...e};if(typeof s.reasoning_effort!="string"||!s.reasoning_effort){let o=r;o==="low"||o==="medium"?o="high":o==="xhigh"&&(o="max"),s.reasoning_effort=o}if(t&&Object.keys(t).length===1)delete s.reasoning;else if(t){let{effort:o,...i}=t;s.reasoning=i}return s}a();var et=class extends L{constructor(e,t){super(e,t)}static isOpenRouterProvider(e){return(e.baseUrl||"").includes("openrouter.ai")}buildHeaders(){return{...super.buildHeaders(),"HTTP-Referer":"https://github.com/MaincodeHQ/matilda-code.git","X-OpenRouter-Title":"Matilda"}}};a();var xi=["api.minimaxi.com","api.minimax.io"],Ii=[".minimaxi.com",".minimax.io"],tt=class extends L{static isMiniMaxProvider(e){if(!e.baseUrl)return!1;try{let t=new URL(e.baseUrl).hostname.toLowerCase();return xi.includes(t)?!0:Ii.some(r=>t.endsWith(r))}catch{return!1}}getResponseParsingOptions(){return{taggedThinkingTags:!0}}};a();var Qs="api.mistral.ai",Pi=["mistral","mixtral","codestral","ministral","pixtral","magistral","devstral"];function Ri(n){let e=n.baseUrl??"";if(!e)return!1;try{let t=new URL(e).hostname.toLowerCase();return t===Qs||t.endsWith(`.${Qs}`)}catch{return!1}}function Si(n){if(Ri(n))return!0;let e=n.model?.toLowerCase()??"";return Pi.some(t=>e.includes(t))}var rt=class extends L{static isMistralProvider=Si;buildRequest(e,t){let r=super.buildRequest(e,t);return{...r,messages:r.messages.map(Oi)}}};function Oi(n){if(!("reasoning_content"in n))return n;let e={...n};return delete e.reasoning_content,e}a();function Ei(n){let e=n.baseUrl??"";if(e)try{let r=new URL(e).hostname.toLowerCase();if(r==="xiaomimimo.com"||r.endsWith(".xiaomimimo.com"))return!0}catch{}return(n.model??"").toLowerCase().startsWith("mimo-")}var nt=class extends L{constructor(e,t){super(e,t)}static isMiMoProvider=Ei;buildRequest(e,t){let r=super.buildRequest(e,t);return r.messages?.length?{...r,messages:r.messages.map(Hr)}:r}getRequestContextOverrides(){return{splitToolMedia:this.contentGeneratorConfig.splitToolMedia??!0}}};a();a();var vi=me("STREAMING_TOOL_CALL_PARSER"),qr=class{buffers=new Map;depths=new Map;inStrings=new Map;escapes=new Map;toolCallMeta=new Map;idToIndexMap=new Map;nextAvailableIndex=0;addChunk(e,t,r,s){let o=e,i=!!(r&&this.idToIndexMap.has(r));if(r)if(this.idToIndexMap.has(r))o=this.idToIndexMap.get(r);else{if(this.buffers.has(e)){let R=this.buffers.get(e),S=this.depths.get(e),C=this.toolCallMeta.get(e);if(R.trim()&&S===0&&C?.id&&C.id!==r)try{JSON.parse(R),o=this.findNextAvailableIndex()}catch{}}this.idToIndexMap.set(r,o)}else if(this.buffers.has(e)){let R=this.buffers.get(e);if(this.depths.get(e)>0||!R.trim())o=e;else try{JSON.parse(R),o=this.findMostRecentIncompleteIndex()}catch{o=e}}this.buffers.has(o)||(this.buffers.set(o,""),this.depths.set(o,0),this.inStrings.set(o,!1),this.escapes.set(o,!1),this.toolCallMeta.set(o,{}));let l=this.buffers.get(o),u=this.depths.get(o);if(i&&l.trim()&&u===0)try{return JSON.parse(l),vi.debug(`Ignoring replay chunk for completed toolCall id=${r}`),{complete:!1}}catch{}let p=this.toolCallMeta.get(o);r&&(p.id=r),s&&(p.name=s);let g=this.inStrings.get(o),m=this.escapes.get(o),y=l+t;this.buffers.set(o,y);let f=u,x=g,A=m;for(let R of t)x||(R==="{"||R==="["?f++:(R==="}"||R==="]")&&f--),R==='"'&&!A&&(x=!x),A=R==="\\"&&!A;if(this.depths.set(o,f),this.inStrings.set(o,x),this.escapes.set(o,A),f===0&&y.trim().length>0)try{return{complete:!0,value:JSON.parse(y)}}catch(R){if(x)try{return{complete:!0,value:JSON.parse(y+'"'),repaired:!0}}catch{}return{complete:!1,error:R instanceof Error?R:new Error(String(R))}}return{complete:!1}}getToolCallMeta(e){return this.toolCallMeta.get(e)||{}}getCompletedToolCalls(){let e=[],t=new Set;for(let[r,s]of this.buffers.entries()){let o=this.toolCallMeta.get(r);if(o?.name&&s.trim()){if(o.id){if(t.has(o.id))continue;t.add(o.id)}let i={};try{i=JSON.parse(s)}catch{if(this.inStrings.get(r))try{i=JSON.parse(s+'"')}catch{i=Vr(s,{})}else i=Vr(s,{})}e.push({id:o.id,name:o.name,args:i,index:r})}}return e}findNextAvailableIndex(){for(;this.buffers.has(this.nextAvailableIndex);){let e=this.buffers.get(this.nextAvailableIndex),t=this.depths.get(this.nextAvailableIndex),r=this.toolCallMeta.get(this.nextAvailableIndex);if(!e.trim()||t>0||!r?.id)return this.nextAvailableIndex;try{if(JSON.parse(e),t===0){this.nextAvailableIndex++;continue}}catch{return this.nextAvailableIndex}this.nextAvailableIndex++}return this.nextAvailableIndex++}findMostRecentIncompleteIndex(){let e=-1;for(let[t,r]of this.buffers.entries()){let s=this.depths.get(t);if(this.toolCallMeta.get(t)?.id&&(s>0||!r.trim()))e=Math.max(e,t);else if(r.trim())try{JSON.parse(r)}catch{e=Math.max(e,t)}}return e>=0?e:this.findNextAvailableIndex()}resetIndex(e){this.buffers.set(e,""),this.depths.set(e,0),this.inStrings.set(e,!1),this.escapes.set(e,!1),this.toolCallMeta.set(e,{})}reset(){this.buffers.clear(),this.depths.clear(),this.inStrings.clear(),this.escapes.clear(),this.toolCallMeta.clear(),this.idToIndexMap.clear(),this.nextAvailableIndex=0}getBuffer(e){return this.buffers.get(e)||""}getState(e){return{depth:this.depths.get(e)||0,inString:this.inStrings.get(e)||!1,escape:this.escapes.get(e)||!1}}hasIncompleteToolCalls(){for(let[e]of this.buffers.entries()){if(!this.toolCallMeta.get(e)?.name)continue;let r=this.depths.get(e)||0,s=this.inStrings.get(e)||!1;if(r>0||s)return!0}return!1}};var Ys=16e3,Zs=`[Earlier content omitted to fit Matilda Core external API limits]
28
- `,Xr=class extends Error{constructor(e){super(e),this.name="StreamContentError"}},ur=class{constructor(e){this.config=e;this.contentGeneratorConfig=e.contentGeneratorConfig,this.client=this.config.provider.buildClient()}client;contentGeneratorConfig;async execute(e,t){return this.executeWithErrorHandling(e,t,!1,async(r,s)=>{let o=e.config?.abortSignal,i=o?zr(o):void 0;try{let l=await this.client.chat.completions.create(r,{signal:i?.signal});return st.convertOpenAIResponseToGemini(l,s)}finally{i?.abort()}})}async executeStream(e,t){return this.executeWithErrorHandling(e,t,!0,async(r,s)=>{let o=e.config?.abortSignal,i=o?zr(o):void 0,l;try{l=await this.client.chat.completions.create(r,{signal:i?.signal})}catch(m){throw i?.abort(),m}if(!i)return this.processStreamWithLogging(l,s,e);let u=i,p=this.processStreamWithLogging(l,s,e);async function*g(){try{yield*p}finally{u.abort()}}return g()})}async*processStreamWithLogging(e,t,r){let s=[],o=null,i=!1;try{for await(let l of e){if(l.choices?.[0]?.finish_reason==="error_finish"){let g=l.choices?.[0]?.delta?.content?.trim()||"Unknown stream error";throw new Xr(g)}let u=st.convertOpenAIChunkToGemini(l,t);if(u.candidates?.[0]?.content?.parts?.length===0&&!u.candidates?.[0]?.finishReason&&!u.usageMetadata)continue;if(i){if(u.usageMetadata){let g=o;g&&(g.usageMetadata=u.usageMetadata)}s.push(u);continue}this.handleChunkMerging(u,s,g=>{o=g})&&(o?(yield o,i=!0):yield u)}o&&!i&&(yield o)}catch(l){if(l instanceof Xr)throw ve(l);await this.handleError(l,t,r)}}handleChunkMerging(e,t,r){let s=e.candidates?.[0]?.finishReason,o=t.length>0&&t[t.length-1].candidates?.[0]?.finishReason;if(s){if(o){let i=t[t.length-1];e.usageMetadata&&(i.usageMetadata=e.usageMetadata),r(i)}else t.push(e),r(e);return!1}else if(o){let i=t[t.length-1],l=new Dn;return l.candidates=i.candidates,e.usageMetadata?l.usageMetadata=e.usageMetadata:l.usageMetadata=i.usageMetadata,l.responseId=e.responseId,l.createTime=e.createTime,l.modelVersion=e.modelVersion,l.promptFeedback=e.promptFeedback,t[t.length-1]=l,r(l),!0}return t.push(e),!0}async buildRequest(e,t,r,s){let o=st.convertGeminiRequestToOpenAI(e,r),i=this.shouldUseMatildaCoreRequestProfile(),l=i?this.toMatildaCoreUserMessages(o):o,u={model:r.model,messages:l,...this.buildGenerateContentConfig(e)};s?(u.stream=!0,u.stream_options={include_usage:!0}):u.stream=!1,!i&&e.config?.tools&&e.config.tools.length>0&&(u.tools=await st.convertGeminiToolsToOpenAI(e.config.tools,this.contentGeneratorConfig.schemaCompliance??"auto"));let p=this.config.provider.buildRequest(u,t);if(e.config?.thinkingConfig?.includeThoughts===!1||this.contentGeneratorConfig.reasoning===!1){let m=p,y=(r.model??"").toLowerCase();de.isMatildaCompatibleProvider(this.contentGeneratorConfig)&&(y.startsWith("matilda")||y==="coder-model")&&(m.enable_thinking=!1),"reasoning"in m&&delete m.reasoning,"reasoning_effort"in m&&delete m.reasoning_effort,cr(this.contentGeneratorConfig)&&(m.thinking={type:"disabled"})}return p}toMatildaCoreUserMessages(e){let t=e.filter(r=>r.role==="user").map(r=>({role:"user",content:this.sanitizeMatildaUserContent(this.toPlainUserContent(r.content))})).filter(r=>r.content.trim().length>0);return t.length>0?t:[{role:"user",content:""}]}shouldUseMatildaCoreRequestProfile(){let e=this.contentGeneratorConfig.openAIRequestProfile;if(e==="matilda-core")return!0;if(e==="matilda-code")return!1;let t=(this.contentGeneratorConfig.baseUrl??"").toLowerCase().replace(/\/+$/,"");if(t.endsWith("/api/v1/code"))return!1;let r=this.contentGeneratorConfig.customHeaders??{};return Object.entries(r).some(([o,i])=>o.toLowerCase()==="x-matilda-client"&&i.toLowerCase()==="matilda-code")?!0:t==="https://matilda.maincode.com/api/v1"||t==="http://localhost:8080/api/v1"||t==="http://core-api.matilda:3001/api/v1"}toPlainUserContent(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>t.type==="text"?t.text:t.type==="image_url"?"[image omitted: Matilda Core OpenAI shim accepts text only]":"").filter(Boolean).join(`
29
- `):""}sanitizeMatildaUserContent(e){let r=e.replace(/<system-reminder>[\s\S]*?<\/system-reminder>\s*/g,"").trim();if(r.length<=Ys)return r;let s=Ys-Zs.length;return`${Zs}${r.slice(-s)}`}buildGenerateContentConfig(e){let t=this.config.provider.getDefaultGenerationConfig(),r=this.contentGeneratorConfig.samplingParams,s=(l,u)=>{let p=r?.[l],g=u?e.config?.[u]:void 0,m=u?t[u]:void 0;return p!==void 0?p:g!==void 0?g:m},o=(l,u,p)=>{let g=s(u,p);return g!==void 0?{[l]:g}:{}};if(r!==void 0){let l=e.config?.maxOutputTokens;return{...r,...l!==void 0&&r.max_tokens!==void 0?{max_tokens:l}:{}}}return{...o("temperature","temperature","temperature"),...o("top_p","top_p","topP"),...o("max_tokens","max_tokens","maxOutputTokens"),...o("top_k","top_k","topK"),...o("repetition_penalty","repetition_penalty"),...o("presence_penalty","presence_penalty","presencePenalty"),...o("frequency_penalty","frequency_penalty","frequencyPenalty"),...this.buildReasoningConfig(e)}}buildReasoningConfig(e){if(e.config?.thinkingConfig?.includeThoughts===!1)return{};let t=this.contentGeneratorConfig.reasoning;return t===!1||t===void 0?{}:{reasoning:t}}async executeWithErrorHandling(e,t,r,s){let o=this.createRequestContext(e,r);try{let i=await this.buildRequest(e,t,o,r);return Gn.getStore()?.(i),Bn.recordOpenAIWireRequest(i),await s(i,o)}catch(i){return await this.handleError(i,o,e)}}async handleError(e,t,r){this.config.errorHandler.handle(ve(e),t,r)}createRequestContext(e,t){let r=e.model||this.contentGeneratorConfig.model,s=this.config.provider.getRequestContextOverrides?.()??{},o=t?new qr:void 0,i=this.config.provider.getResponseParsingOptions?.(),l=t&&i?.taggedThinkingTags?new jn:void 0;return{model:r,modalities:this.contentGeneratorConfig.modalities??{},startTime:Date.now(),splitToolMedia:s.splitToolMedia??this.contentGeneratorConfig.splitToolMedia??!0,...o?{toolCallParser:o}:{},...i?{responseParsingOptions:i}:{},...l?{taggedThinkingParser:l}:{}}}};a();var Ti=me("OPENAI_ERROR"),fr=class{constructor(e=()=>!1){this.shouldSuppressLogging=e}handle(e,t,r){let s=ve(e),o=this.isTimeoutError(s),i=this.buildErrorMessage(s,t,o);throw this.shouldSuppressErrorLogging(s,r)||Ti.error("OpenAI API Error:",i),o?new Error(`${i}
27
+ `);return{...n,content:t}}function Ai(n){let e=n,t=e.reasoning,r=t?.effort;if(typeof r!="string"||!r)return n;let s={...e};if(typeof s.reasoning_effort!="string"||!s.reasoning_effort){let o=r;o==="low"||o==="medium"?o="high":o==="xhigh"&&(o="max"),s.reasoning_effort=o}if(t&&Object.keys(t).length===1)delete s.reasoning;else if(t){let{effort:o,...i}=t;s.reasoning=i}return s}a();var et=class extends L{constructor(e,t){super(e,t)}static isOpenRouterProvider(e){return(e.baseUrl||"").includes("openrouter.ai")}buildHeaders(){return{...super.buildHeaders(),"HTTP-Referer":"https://github.com/MaincodeHQ/matilda-code.git","X-OpenRouter-Title":"Matilda"}}};a();var xi=["api.minimaxi.com","api.minimax.io"],Ii=[".minimaxi.com",".minimax.io"],tt=class extends L{static isMiniMaxProvider(e){if(!e.baseUrl)return!1;try{let t=new URL(e.baseUrl).hostname.toLowerCase();return xi.includes(t)?!0:Ii.some(r=>t.endsWith(r))}catch{return!1}}getResponseParsingOptions(){return{taggedThinkingTags:!0}}};a();var Qs="api.mistral.ai",Pi=["mistral","mixtral","codestral","ministral","pixtral","magistral","devstral"];function Ri(n){let e=n.baseUrl??"";if(!e)return!1;try{let t=new URL(e).hostname.toLowerCase();return t===Qs||t.endsWith(`.${Qs}`)}catch{return!1}}function Si(n){if(Ri(n))return!0;let e=n.model?.toLowerCase()??"";return Pi.some(t=>e.includes(t))}var rt=class extends L{static isMistralProvider=Si;buildRequest(e,t){let r=super.buildRequest(e,t);return{...r,messages:r.messages.map(Oi)}}};function Oi(n){if(!("reasoning_content"in n))return n;let e={...n};return delete e.reasoning_content,e}a();function Ei(n){let e=n.baseUrl??"";if(e)try{let r=new URL(e).hostname.toLowerCase();if(r==="xiaomimimo.com"||r.endsWith(".xiaomimimo.com"))return!0}catch{}return(n.model??"").toLowerCase().startsWith("mimo-")}var nt=class extends L{constructor(e,t){super(e,t)}static isMiMoProvider=Ei;buildRequest(e,t){let r=super.buildRequest(e,t);return r.messages?.length?{...r,messages:r.messages.map(Hr)}:r}getRequestContextOverrides(){return{splitToolMedia:this.contentGeneratorConfig.splitToolMedia??!0}}};a();a();var vi=me("STREAMING_TOOL_CALL_PARSER"),qr=class{buffers=new Map;depths=new Map;inStrings=new Map;escapes=new Map;toolCallMeta=new Map;idToIndexMap=new Map;nextAvailableIndex=0;addChunk(e,t,r,s){let o=e,i=!!(r&&this.idToIndexMap.has(r));if(r)if(this.idToIndexMap.has(r))o=this.idToIndexMap.get(r);else{if(this.buffers.has(e)){let R=this.buffers.get(e),S=this.depths.get(e),C=this.toolCallMeta.get(e);if(R.trim()&&S===0&&C?.id&&C.id!==r)try{JSON.parse(R),o=this.findNextAvailableIndex()}catch{}}this.idToIndexMap.set(r,o)}else if(this.buffers.has(e)){let R=this.buffers.get(e);if(this.depths.get(e)>0||!R.trim())o=e;else try{JSON.parse(R),o=this.findMostRecentIncompleteIndex()}catch{o=e}}this.buffers.has(o)||(this.buffers.set(o,""),this.depths.set(o,0),this.inStrings.set(o,!1),this.escapes.set(o,!1),this.toolCallMeta.set(o,{}));let l=this.buffers.get(o),u=this.depths.get(o);if(i&&l.trim()&&u===0)try{return JSON.parse(l),vi.debug(`Ignoring replay chunk for completed toolCall id=${r}`),{complete:!1}}catch{}let d=this.toolCallMeta.get(o);r&&(d.id=r),s&&(d.name=s);let g=this.inStrings.get(o),p=this.escapes.get(o),y=l+t;this.buffers.set(o,y);let f=u,x=g,A=p;for(let R of t)x||(R==="{"||R==="["?f++:(R==="}"||R==="]")&&f--),R==='"'&&!A&&(x=!x),A=R==="\\"&&!A;if(this.depths.set(o,f),this.inStrings.set(o,x),this.escapes.set(o,A),f===0&&y.trim().length>0)try{return{complete:!0,value:JSON.parse(y)}}catch(R){if(x)try{return{complete:!0,value:JSON.parse(y+'"'),repaired:!0}}catch{}return{complete:!1,error:R instanceof Error?R:new Error(String(R))}}return{complete:!1}}getToolCallMeta(e){return this.toolCallMeta.get(e)||{}}getCompletedToolCalls(){let e=[],t=new Set;for(let[r,s]of this.buffers.entries()){let o=this.toolCallMeta.get(r);if(o?.name&&s.trim()){if(o.id){if(t.has(o.id))continue;t.add(o.id)}let i={};try{i=JSON.parse(s)}catch{if(this.inStrings.get(r))try{i=JSON.parse(s+'"')}catch{i=Vr(s,{})}else i=Vr(s,{})}e.push({id:o.id,name:o.name,args:i,index:r})}}return e}findNextAvailableIndex(){for(;this.buffers.has(this.nextAvailableIndex);){let e=this.buffers.get(this.nextAvailableIndex),t=this.depths.get(this.nextAvailableIndex),r=this.toolCallMeta.get(this.nextAvailableIndex);if(!e.trim()||t>0||!r?.id)return this.nextAvailableIndex;try{if(JSON.parse(e),t===0){this.nextAvailableIndex++;continue}}catch{return this.nextAvailableIndex}this.nextAvailableIndex++}return this.nextAvailableIndex++}findMostRecentIncompleteIndex(){let e=-1;for(let[t,r]of this.buffers.entries()){let s=this.depths.get(t);if(this.toolCallMeta.get(t)?.id&&(s>0||!r.trim()))e=Math.max(e,t);else if(r.trim())try{JSON.parse(r)}catch{e=Math.max(e,t)}}return e>=0?e:this.findNextAvailableIndex()}resetIndex(e){this.buffers.set(e,""),this.depths.set(e,0),this.inStrings.set(e,!1),this.escapes.set(e,!1),this.toolCallMeta.set(e,{})}reset(){this.buffers.clear(),this.depths.clear(),this.inStrings.clear(),this.escapes.clear(),this.toolCallMeta.clear(),this.idToIndexMap.clear(),this.nextAvailableIndex=0}getBuffer(e){return this.buffers.get(e)||""}getState(e){return{depth:this.depths.get(e)||0,inString:this.inStrings.get(e)||!1,escape:this.escapes.get(e)||!1}}hasIncompleteToolCalls(){for(let[e]of this.buffers.entries()){if(!this.toolCallMeta.get(e)?.name)continue;let r=this.depths.get(e)||0,s=this.inStrings.get(e)||!1;if(r>0||s)return!0}return!1}};var Ys=16e3,Zs=`[Earlier content omitted to fit Matilda Core external API limits]
28
+ `,Xr=class extends Error{constructor(e){super(e),this.name="StreamContentError"}},ur=class{constructor(e){this.config=e;this.contentGeneratorConfig=e.contentGeneratorConfig,this.client=this.config.provider.buildClient()}client;contentGeneratorConfig;async execute(e,t){return this.executeWithErrorHandling(e,t,!1,async(r,s)=>{let o=e.config?.abortSignal,i=o?zr(o):void 0;try{let l=await this.client.chat.completions.create(r,{signal:i?.signal});return st.convertOpenAIResponseToGemini(l,s)}finally{i?.abort()}})}async executeStream(e,t){return this.executeWithErrorHandling(e,t,!0,async(r,s)=>{let o=e.config?.abortSignal,i=o?zr(o):void 0,l;try{l=await this.client.chat.completions.create(r,{signal:i?.signal})}catch(p){throw i?.abort(),p}if(!i)return this.processStreamWithLogging(l,s,e);let u=i,d=this.processStreamWithLogging(l,s,e);async function*g(){try{yield*d}finally{u.abort()}}return g()})}async*processStreamWithLogging(e,t,r){let s=[],o=null,i=!1;try{for await(let l of e){if(l.choices?.[0]?.finish_reason==="error_finish"){let g=l.choices?.[0]?.delta?.content?.trim()||"Unknown stream error";throw new Xr(g)}let u=st.convertOpenAIChunkToGemini(l,t);if(u.candidates?.[0]?.content?.parts?.length===0&&!u.candidates?.[0]?.finishReason&&!u.usageMetadata)continue;if(i){if(u.usageMetadata){let g=o;g&&(g.usageMetadata=u.usageMetadata)}s.push(u);continue}this.handleChunkMerging(u,s,g=>{o=g})&&(o?(yield o,i=!0):yield u)}o&&!i&&(yield o)}catch(l){if(l instanceof Xr)throw ve(l);await this.handleError(l,t,r)}}handleChunkMerging(e,t,r){let s=e.candidates?.[0]?.finishReason,o=t.length>0&&t[t.length-1].candidates?.[0]?.finishReason;if(s){if(o){let i=t[t.length-1];e.usageMetadata&&(i.usageMetadata=e.usageMetadata),r(i)}else t.push(e),r(e);return!1}else if(o){let i=t[t.length-1],l=new Dn;return l.candidates=i.candidates,e.usageMetadata?l.usageMetadata=e.usageMetadata:l.usageMetadata=i.usageMetadata,l.responseId=e.responseId,l.createTime=e.createTime,l.modelVersion=e.modelVersion,l.promptFeedback=e.promptFeedback,t[t.length-1]=l,r(l),!0}return t.push(e),!0}async buildRequest(e,t,r,s){let o=st.convertGeminiRequestToOpenAI(e,r),i=this.shouldUseMatildaCoreRequestProfile(),l=i?this.toMatildaCoreUserMessages(o):o,u={model:r.model,messages:l,...this.buildGenerateContentConfig(e)};s?(u.stream=!0,u.stream_options={include_usage:!0}):u.stream=!1,!i&&e.config?.tools&&e.config.tools.length>0&&(u.tools=await st.convertGeminiToolsToOpenAI(e.config.tools,this.contentGeneratorConfig.schemaCompliance??"auto"));let d=this.config.provider.buildRequest(u,t);if(e.config?.thinkingConfig?.includeThoughts===!1||this.contentGeneratorConfig.reasoning===!1){let p=d,y=(r.model??"").toLowerCase();if(de.isMatildaCompatibleProvider(this.contentGeneratorConfig)&&(y.startsWith("matilda")||y==="coder-model")){p.enable_thinking=!1;let f=p.chat_template_kwargs;typeof f=="object"&&f!==null&&"enable_thinking"in f&&(p.chat_template_kwargs={...f,enable_thinking:!1})}"reasoning"in p&&delete p.reasoning,"reasoning_effort"in p&&delete p.reasoning_effort,cr(this.contentGeneratorConfig)&&(p.thinking={type:"disabled"})}return d}toMatildaCoreUserMessages(e){let t=e.filter(r=>r.role==="user").map(r=>({role:"user",content:this.sanitizeMatildaUserContent(this.toPlainUserContent(r.content))})).filter(r=>r.content.trim().length>0);return t.length>0?t:[{role:"user",content:""}]}shouldUseMatildaCoreRequestProfile(){let e=this.contentGeneratorConfig.openAIRequestProfile;if(e==="matilda-core")return!0;if(e==="matilda-code")return!1;let t=(this.contentGeneratorConfig.baseUrl??"").toLowerCase().replace(/\/+$/,"");if(t.endsWith("/api/v1/code"))return!1;let r=this.contentGeneratorConfig.customHeaders??{};return Object.entries(r).some(([o,i])=>o.toLowerCase()==="x-matilda-client"&&i.toLowerCase()==="matilda-code")?!0:t==="https://matilda.maincode.com/api/v1"||t==="http://localhost:8080/api/v1"||t==="http://core-api.matilda:3001/api/v1"}toPlainUserContent(e){return typeof e=="string"?e:Array.isArray(e)?e.map(t=>t.type==="text"?t.text:t.type==="image_url"?"[image omitted: Matilda Core OpenAI shim accepts text only]":"").filter(Boolean).join(`
29
+ `):""}sanitizeMatildaUserContent(e){let r=e.replace(/<system-reminder>[\s\S]*?<\/system-reminder>\s*/g,"").trim();if(r.length<=Ys)return r;let s=Ys-Zs.length;return`${Zs}${r.slice(-s)}`}buildGenerateContentConfig(e){let t=this.config.provider.getDefaultGenerationConfig(),r=this.contentGeneratorConfig.samplingParams,s=(l,u)=>{let d=r?.[l],g=u?e.config?.[u]:void 0,p=u?t[u]:void 0;return d!==void 0?d:g!==void 0?g:p},o=(l,u,d)=>{let g=s(u,d);return g!==void 0?{[l]:g}:{}};if(r!==void 0){let l=e.config?.maxOutputTokens;return{...r,...l!==void 0&&r.max_tokens!==void 0?{max_tokens:l}:{}}}return{...o("temperature","temperature","temperature"),...o("top_p","top_p","topP"),...o("max_tokens","max_tokens","maxOutputTokens"),...o("top_k","top_k","topK"),...o("repetition_penalty","repetition_penalty"),...o("presence_penalty","presence_penalty","presencePenalty"),...o("frequency_penalty","frequency_penalty","frequencyPenalty"),...this.buildReasoningConfig(e)}}buildReasoningConfig(e){if(e.config?.thinkingConfig?.includeThoughts===!1)return{};let t=this.contentGeneratorConfig.reasoning;return t===!1||t===void 0?{}:{reasoning:t}}async executeWithErrorHandling(e,t,r,s){let o=this.createRequestContext(e,r);try{let i=await this.buildRequest(e,t,o,r);return Gn.getStore()?.(i),Bn.recordOpenAIWireRequest(i),await s(i,o)}catch(i){return await this.handleError(i,o,e)}}async handleError(e,t,r){this.config.errorHandler.handle(ve(e),t,r)}createRequestContext(e,t){let r=e.model||this.contentGeneratorConfig.model,s=this.config.provider.getRequestContextOverrides?.()??{},o=t?new qr:void 0,i=this.config.provider.getResponseParsingOptions?.(),l=t&&i?.taggedThinkingTags?new jn:void 0;return{model:r,modalities:this.contentGeneratorConfig.modalities??{},startTime:Date.now(),splitToolMedia:s.splitToolMedia??this.contentGeneratorConfig.splitToolMedia??!0,...o?{toolCallParser:o}:{},...i?{responseParsingOptions:i}:{},...l?{taggedThinkingParser:l}:{}}}};a();var Ti=me("OPENAI_ERROR"),fr=class{constructor(e=()=>!1){this.shouldSuppressLogging=e}handle(e,t,r){let s=ve(e),o=this.isTimeoutError(s),i=this.buildErrorMessage(s,t,o);throw this.shouldSuppressErrorLogging(s,r)||Ti.error("OpenAI API Error:",i),o?new Error(`${i}
30
30
 
31
31
  ${this.getTimeoutTroubleshootingTips()}`):s}shouldSuppressErrorLogging(e,t){return this.shouldSuppressLogging(e,t)}isTimeoutError(e){if(!e)return!1;let t=e instanceof Error?e.message.toLowerCase():String(e).toLowerCase(),r=e?.code,s=e?.type;return t.includes("timeout")||t.includes("timed out")||t.includes("connection timeout")||t.includes("request timeout")||t.includes("read timeout")||t.includes("etimedout")||t.includes("esockettimedout")||r==="ETIMEDOUT"||r==="ESOCKETTIMEDOUT"||s==="timeout"||t.includes("request timed out")||t.includes("deadline exceeded")}buildErrorMessage(e,t,r){let s=Math.round((Date.now()-t.startTime)/1e3);return r?`Request timeout after ${s}s. Try reducing input length or increasing timeout in config.`:e instanceof Error?e.message:String(e)}getTimeoutTroubleshootingTips(){return`Troubleshooting tips:
32
32
  ${["- Reduce input length or complexity","- Increase timeout in config: contentGenerator.timeout","- Check network connectivity"].join(`