@maincode-ai/matilda-code 0.21.2 → 0.21.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -0
- package/chunks/{agent-B4THN25M.js → agent-WBKEN3MM.js} +1 -1
- package/chunks/{agent-headless-CR55Q5QA.js → agent-headless-OJM6RWIA.js} +1 -1
- package/chunks/{anthropicContentGenerator-GW3P6NLQ.js → anthropicContentGenerator-EFVV6ZTA.js} +1 -1
- package/chunks/{chunk-CFBZKYFB.js → chunk-6QP5C76Y.js} +52 -52
- package/chunks/{chunk-MAQJCFZU.js → chunk-7LNKXNEZ.js} +526 -517
- package/chunks/{chunk-GIIMOLLN.js → chunk-C2ZWB2NT.js} +1 -1
- package/chunks/{chunk-NUJ63BIE.js → chunk-DBSJNFFU.js} +1 -1
- package/chunks/{chunk-SS5WUOSJ.js → chunk-FT76AZPN.js} +1 -1
- package/chunks/chunk-FU2PKCG5.js +108 -0
- package/chunks/{chunk-QEUJHX22.js → chunk-IZ6YBZWM.js} +13 -13
- package/chunks/{chunk-M3G4PG2T.js → chunk-JDXISO3F.js} +4 -4
- package/chunks/chunk-MJEXA2MA.js +8 -0
- package/chunks/chunk-MTMU7JYZ.js +11 -0
- package/chunks/chunk-SDTWBD62.js +8 -0
- package/chunks/{chunk-JEDNTIM3.js → chunk-ZYW5GLYY.js} +1 -1
- package/chunks/{computer-use-STZBQBFP.js → computer-use-MCXFHFTP.js} +1 -1
- package/chunks/{contextCommand-LB5MHXJY.js → contextCommand-G4LS5GW6.js} +1 -1
- package/chunks/edit-KNZAPSGJ.js +39 -0
- package/chunks/{enter-worktree-V6TA7IPP.js → enter-worktree-LJ66TFYR.js} +1 -1
- package/chunks/{enterPlanMode-KQCLOC2K.js → enterPlanMode-P6EIGU3Y.js} +1 -1
- package/chunks/{exit-worktree-B3SWF6PM.js → exit-worktree-QVQ3TLW5.js} +1 -1
- package/chunks/{exitPlanMode-7OHF37SX.js → exitPlanMode-I7SGPSG4.js} +1 -1
- package/chunks/{geminiContentGenerator-6VRAJ3BI.js → geminiContentGenerator-SBVCQ423.js} +1 -1
- package/chunks/{glob-ZAZPTZD5.js → glob-F5YOX6YA.js} +1 -1
- package/chunks/{grep-DNYRXQWA.js → grep-UOIHSM5U.js} +1 -1
- package/chunks/{matildaAgentContentGenerator-S26H4H3W.js → matildaAgentContentGenerator-EIQI4YCP.js} +10 -10
- package/chunks/{matildaContentGenerator-UFATU4UK.js → matildaContentGenerator-QMMGDPIK.js} +1 -1
- package/chunks/{monitor-HQXCJQ3M.js → monitor-GDKHPTET.js} +1 -1
- package/chunks/notebook-edit-LWH7H4WX.js +17 -0
- package/chunks/{openaiContentGenerator-XAPZXISY.js → openaiContentGenerator-TNZ6SB7H.js} +1 -1
- package/chunks/{read-file-HEVXSNSO.js → read-file-URGJTANM.js} +1 -1
- package/chunks/{ripGrep-BNBRX7HQ.js → ripGrep-SL4ICAX6.js} +1 -1
- package/chunks/{scheduler-3K7OROFK.js → scheduler-EX674HYK.js} +1 -1
- package/chunks/{serve-MBVRWSOA.js → serve-FZ4FTA5D.js} +7 -7
- package/chunks/{shell-3YF6VEDO.js → shell-LLU55LCI.js} +1 -1
- package/chunks/{skill-4GKPLUND.js → skill-KSYY6BM6.js} +1 -1
- package/chunks/src-UXJDJ3RJ.js +3 -0
- package/chunks/{symbol-search-WVNUJRET.js → symbol-search-3A66G4MP.js} +1 -1
- package/chunks/{team-create-2LLJKRSY.js → team-create-7PFAVYVV.js} +1 -1
- package/chunks/{tool-search-47TA6SG4.js → tool-search-7D46IF5G.js} +1 -1
- package/chunks/{update-goal-6WDBMJ2I.js → update-goal-EUJYH23K.js} +1 -1
- package/chunks/{web-fetch-QP42GV23.js → web-fetch-UGTFUOQN.js} +1 -1
- package/chunks/{workflow-EIZTKOPX.js → workflow-2TGFLD2R.js} +2 -2
- package/chunks/write-file-DQ6NYEJ7.js +15 -0
- package/cli.js +443 -444
- package/package.json +2 -2
- package/sandbox-macos-restrictive-open.sb +22 -2
- package/chunks/chunk-I55PXD4N.js +0 -10
- package/chunks/chunk-KFULPF66.js +0 -107
- package/chunks/chunk-OCXGNAAT.js +0 -8
- package/chunks/chunk-RBG4ERTN.js +0 -11
- package/chunks/chunk-XJDC3ZQZ.js +0 -8
- package/chunks/edit-EP7HIW5W.js +0 -39
- package/chunks/notebook-edit-S63FQCCF.js +0 -17
- package/chunks/src-4XJIGVTS.js +0 -3
- package/chunks/write-file-YT7UT6TX.js +0 -15
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{a as is}from"./chunk-QCIDUZV6.js";import{c as yr,f as Te}from"./chunk-S4K76QPI.js";import{M as Yn,N as Qn,O as qt,Q as Zn,R as Cr,S as es,a as Jn,g as ve,h as Xn,la as os}from"./chunk-KFULPF66.js";import{a as ss}from"./chunk-DC7LAFZZ.js";import{a as qn,g as Vn,k as Kn,l as hr,o as ts,t as rs,v as ns}from"./chunk-QLEJOI4X.js";import{e as Hn}from"./chunk-4J6DC24J.js";import{b as gr,c as _r,f as zn,n as br}from"./chunk-XJDC3ZQZ.js";import{b as en}from"./chunk-ESSYHTAZ.js";import{Y as me,b as Wn}from"./chunk-QWBNNEV2.js";import{b as a}from"./chunk-GZPNIYVZ.js";a();a();a();a();a();a();a();a();function A(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 tn=function(){let{crypto:n}=globalThis;if(n?.randomUUID)return tn=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 Jt(n){return typeof n=="object"&&n!==null&&("name"in n&&n.name==="AbortError"||"message"in n&&String(n.message).includes("FetchRequestCanceledException"))}var Xt=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 y=class extends Error{},$=class n extends y{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:Xt(t)});let o=t?.error;return e===400?new it(e,o,r,s):e===401?new at(e,o,r,s):e===403?new lt(e,o,r,s):e===404?new ct(e,o,r,s):e===409?new ut(e,o,r,s):e===422?new ft(e,o,r,s):e===429?new pt(e,o,r,s):e>=500?new dt(e,o,r,s):new n(e,o,r,s)}},k=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."})}},it=class extends ${},at=class extends ${},lt=class extends ${},ct=class extends ${},ut=class extends ${},ft=class extends ${},pt=class extends ${},dt=class extends ${},mt=class extends y{constructor(){super("Could not parse response content as the length limit was reached")}},ht=class extends y{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 ho=/^[a-z][a-z0-9+.-]*:/i,as=n=>ho.test(n),W=n=>(W=Array.isArray,W(n)),rn=W;function ls(n){return typeof n!="object"?{}:n??{}}function cs(n){if(!n)return!0;for(let e in n)return!1;return!0}function us(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function Vt(n){return n!=null&&typeof n=="object"&&!Array.isArray(n)}var fs=(n,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new y(`${n} must be an integer`);if(e<0)throw new y(`${n} must be a positive integer`);return e};var ps=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 gs=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function go(){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 _o=()=>{let n=go();if(n==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":ms(Deno.build.os),"X-Stainless-Arch":ds(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":ms(globalThis.process.platform??"unknown"),"X-Stainless-Arch":ds(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=bo();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 bo(){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 ds=n=>n==="x32"?"x32":n==="x86_64"||n==="x64"?"x64":n==="arm"?"arm":n==="aarch64"||n==="arm64"?"arm64":n?`other:${n}`:"unknown",ms=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"),hs,_s=()=>hs??(hs=_o());a();function bs(){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 nn(...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 wr(n){let e=Symbol.asyncIterator in n?n[Symbol.asyncIterator]():n[Symbol.iterator]();return nn({start(){},async pull(t){let{done:r,value:s}=await e.next();r?t.close():t.enqueue(s)},async cancel(){await e.return?.()}})}function sn(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 ys=({headers:n,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});a();a();var Ar="RFC3986",on=n=>String(n),xr={RFC1738:n=>String(n).replace(/%20/g,"+"),RFC3986:on},an="RFC1738";a();a();var Ir=(n,e)=>(Ir=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Ir(n,e)),te=(()=>{let n=[];for(let e=0;e<256;++e)n.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return n})();var ln=1024,ws=(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+=ln){let u=o.length>=ln?o.slice(l,l+ln):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===an&&(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 As(n){return!n||typeof n!="object"?!1:!!(n.constructor&&n.constructor.isBuffer&&n.constructor.isBuffer(n))}function cn(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 Is={brackets(n){return String(n)+"[]"},comma:"comma",indices(n,e){return String(n)+"["+e+"]"},repeat(n){return String(n)}},Ps=function(n,e){Array.prototype.push.apply(n,W(e)?e:[e])},xs,N={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:ws,encodeValuesOnly:!1,format:Ar,formatter:on,indices:!1,serializeDate(n){return(xs??(xs=Function.prototype.call.bind(Date.prototype.toISOString)))(n)},skipNulls:!1,strictNullHandling:!1};function wo(n){return typeof n=="string"||typeof n=="number"||typeof n=="boolean"||typeof n=="symbol"||typeof n=="bigint"}var un={};function Rs(n,e,t,r,s,o,i,l,u,d,g,p,b,f,x,C,P,O){let w=n,U=O,S=0,J=!1;for(;(U=U.get(un))!==void 0&&!J;){let T=U.get(n);if(S+=1,typeof T<"u"){if(T===S)throw new RangeError("Cyclic object value");J=!0}typeof U.get(un)>"u"&&(S=0)}if(typeof d=="function"?w=d(e,w):w instanceof Date?w=b?.(w):t==="comma"&&W(w)&&(w=cn(w,function(T){return T instanceof Date?b?.(T):T})),w===null){if(o)return u&&!C?u(e,N.encoder,P,"key",f):e;w=""}if(wo(w)||As(w)){if(u){let T=C?e:u(e,N.encoder,P,"key",f);return[x?.(T)+"="+x?.(u(w,N.encoder,P,"value",f))]}return[x?.(e)+"="+x?.(String(w))]}let H=[];if(typeof w>"u")return H;let E;if(t==="comma"&&W(w))C&&u&&(w=cn(w,u)),E=[{value:w.length>0?w.join(",")||null:void 0}];else if(W(d))E=d;else{let T=Object.keys(w);E=g?T.sort(g):T}let D=l?String(e).replace(/\./g,"%2E"):String(e),j=r&&W(w)&&w.length===1?D+"[]":D;if(s&&W(w)&&w.length===0)return j+"[]";for(let T=0;T<E.length;++T){let M=E[T],Gn=typeof M=="object"&&typeof M.value<"u"?M.value:w[M];if(i&&Gn===null)continue;let Zr=p&&l?M.replace(/\./g,"%2E"):M,po=W(w)?typeof t=="function"?t(j,Zr):j:j+(p?"."+Zr:"["+Zr+"]");O.set(n,S);let Bn=new WeakMap;Bn.set(un,O),Ps(H,Rs(Gn,po,t,r,s,o,i,l,t==="comma"&&C&&W(w)?null:u,d,g,p,b,f,x,C,P,Bn))}return H}function Ao(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=Ar;if(typeof n.format<"u"){if(!Ir(xr,n.format))throw new TypeError("Unknown format option provided.");t=n.format}let r=xr[t],s=N.filter;(typeof n.filter=="function"||W(n.filter))&&(s=n.filter);let o;if(n.arrayFormat&&n.arrayFormat in Is?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 fn(n,e={}){let t=n,r=Ao(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=Is[r.arrayFormat],u=l==="comma"&&r.commaRoundTrip;s||(s=Object.keys(t)),r.sort&&s.sort(r.sort);let d=new WeakMap;for(let b=0;b<s.length;++b){let f=s[b];r.skipNulls&&t[f]===null||Ps(i,Rs(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 Es(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 Os;function gt(n){let e;return(Os??(e=new globalThis.TextEncoder,Os=e.encode.bind(e)))(n)}var Ss;function pn(n){let e;return(Ss??(e=new globalThis.TextDecoder,Ss=e.decode.bind(e)))(n)}var X,V,ke=class{constructor(){X.set(this,void 0),V.set(this,void 0),A(this,X,new Uint8Array,"f"),A(this,V,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?gt(e):e;A(this,X,Es([c(this,X,"f"),t]),"f");let r=[],s;for(;(s=Io(c(this,X,"f"),c(this,V,"f")))!=null;){if(s.carriage&&c(this,V,"f")==null){A(this,V,s.index,"f");continue}if(c(this,V,"f")!=null&&(s.index!==c(this,V,"f")+1||s.carriage)){r.push(pn(c(this,X,"f").subarray(0,c(this,V,"f")-1))),A(this,X,c(this,X,"f").subarray(c(this,V,"f")),"f"),A(this,V,null,"f");continue}let o=c(this,V,"f")!==null?s.preceding-1:s.preceding,i=pn(c(this,X,"f").subarray(0,o));r.push(i),A(this,X,c(this,X,"f").subarray(s.index),"f"),A(this,V,null,"f")}return r}flush(){return c(this,X,"f").length?this.decode(`
|
|
3
|
+
import{a as ls}from"./chunk-QCIDUZV6.js";import{c as yr,f as Te}from"./chunk-S4K76QPI.js";import{M as Zn,N as es,O as qt,Q as ts,R as Cr,S as rs,a as Vn,g as ve,h as Kn,la as as}from"./chunk-FU2PKCG5.js";import{a as is}from"./chunk-DC7LAFZZ.js";import{a as Xn,g as zn,k as Yn,l as mr,o as ns,t as ss,v as os}from"./chunk-QLEJOI4X.js";import{e as Jn}from"./chunk-4J6DC24J.js";import{b as gr,c as _r,f as Qn,n as br}from"./chunk-SDTWBD62.js";import{b as rn}from"./chunk-ESSYHTAZ.js";import{Y as he,b as qn,p as tn}from"./chunk-QWBNNEV2.js";import{b as a}from"./chunk-GZPNIYVZ.js";a();a();a();a();a();a();a();a();function A(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 nn=function(){let{crypto:n}=globalThis;if(n?.randomUUID)return nn=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 Jt(n){return typeof n=="object"&&n!==null&&("name"in n&&n.name==="AbortError"||"message"in n&&String(n.message).includes("FetchRequestCanceledException"))}var Xt=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 y=class extends Error{},$=class n extends y{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 me({message:r,cause:Xt(t)});let o=t?.error;return e===400?new it(e,o,r,s):e===401?new at(e,o,r,s):e===403?new lt(e,o,r,s):e===404?new ct(e,o,r,s):e===409?new ut(e,o,r,s):e===422?new ft(e,o,r,s):e===429?new pt(e,o,r,s):e>=500?new dt(e,o,r,s):new n(e,o,r,s)}},k=class extends ${constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},me=class extends ${constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},ge=class extends me{constructor({message:e}={}){super({message:e??"Request timed out."})}},it=class extends ${},at=class extends ${},lt=class extends ${},ct=class extends ${},ut=class extends ${},ft=class extends ${},pt=class extends ${},dt=class extends ${},ht=class extends y{constructor(){super("Could not parse response content as the length limit was reached")}},mt=class extends y{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 go=/^[a-z][a-z0-9+.-]*:/i,cs=n=>go.test(n),W=n=>(W=Array.isArray,W(n)),sn=W;function us(n){return typeof n!="object"?{}:n??{}}function fs(n){if(!n)return!0;for(let e in n)return!1;return!0}function ps(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function Vt(n){return n!=null&&typeof n=="object"&&!Array.isArray(n)}var ds=(n,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new y(`${n} must be an integer`);if(e<0)throw new y(`${n} must be a positive integer`);return e};var hs=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 bs=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function _o(){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 bo=()=>{let n=_o();if(n==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":gs(Deno.build.os),"X-Stainless-Arch":ms(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":gs(globalThis.process.platform??"unknown"),"X-Stainless-Arch":ms(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Co();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 Co(){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 ms=n=>n==="x32"?"x32":n==="x86_64"||n==="x64"?"x64":n==="arm"?"arm":n==="aarch64"||n==="arm64"?"arm64":n?`other:${n}`:"unknown",gs=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"),_s,Cs=()=>_s??(_s=bo());a();function ys(){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 on(...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 wr(n){let e=Symbol.asyncIterator in n?n[Symbol.asyncIterator]():n[Symbol.iterator]();return on({start(){},async pull(t){let{done:r,value:s}=await e.next();r?t.close():t.enqueue(s)},async cancel(){await e.return?.()}})}function an(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 ws(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 As=({headers:n,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});a();a();var Ar="RFC3986",ln=n=>String(n),xr={RFC1738:n=>String(n).replace(/%20/g,"+"),RFC3986:ln},cn="RFC1738";a();a();var Ir=(n,e)=>(Ir=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Ir(n,e)),te=(()=>{let n=[];for(let e=0;e<256;++e)n.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return n})();var un=1024,xs=(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+=un){let u=o.length>=un?o.slice(l,l+un):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===cn&&(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 Is(n){return!n||typeof n!="object"?!1:!!(n.constructor&&n.constructor.isBuffer&&n.constructor.isBuffer(n))}function fn(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 Rs={brackets(n){return String(n)+"[]"},comma:"comma",indices(n,e){return String(n)+"["+e+"]"},repeat(n){return String(n)}},Os=function(n,e){Array.prototype.push.apply(n,W(e)?e:[e])},Ps,N={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:xs,encodeValuesOnly:!1,format:Ar,formatter:ln,indices:!1,serializeDate(n){return(Ps??(Ps=Function.prototype.call.bind(Date.prototype.toISOString)))(n)},skipNulls:!1,strictNullHandling:!1};function Ao(n){return typeof n=="string"||typeof n=="number"||typeof n=="boolean"||typeof n=="symbol"||typeof n=="bigint"}var pn={};function Ss(n,e,t,r,s,o,i,l,u,d,g,p,b,f,x,C,P,O){let w=n,U=O,S=0,J=!1;for(;(U=U.get(pn))!==void 0&&!J;){let T=U.get(n);if(S+=1,typeof T<"u"){if(T===S)throw new RangeError("Cyclic object value");J=!0}typeof U.get(pn)>"u"&&(S=0)}if(typeof d=="function"?w=d(e,w):w instanceof Date?w=b?.(w):t==="comma"&&W(w)&&(w=fn(w,function(T){return T instanceof Date?b?.(T):T})),w===null){if(o)return u&&!C?u(e,N.encoder,P,"key",f):e;w=""}if(Ao(w)||Is(w)){if(u){let T=C?e:u(e,N.encoder,P,"key",f);return[x?.(T)+"="+x?.(u(w,N.encoder,P,"value",f))]}return[x?.(e)+"="+x?.(String(w))]}let H=[];if(typeof w>"u")return H;let E;if(t==="comma"&&W(w))C&&u&&(w=fn(w,u)),E=[{value:w.length>0?w.join(",")||null:void 0}];else if(W(d))E=d;else{let T=Object.keys(w);E=g?T.sort(g):T}let D=l?String(e).replace(/\./g,"%2E"):String(e),G=r&&W(w)&&w.length===1?D+"[]":D;if(s&&W(w)&&w.length===0)return G+"[]";for(let T=0;T<E.length;++T){let M=E[T],Wn=typeof M=="object"&&typeof M.value<"u"?M.value:w[M];if(i&&Wn===null)continue;let en=p&&l?M.replace(/\./g,"%2E"):M,ho=W(w)?typeof t=="function"?t(G,en):G:G+(p?"."+en:"["+en+"]");O.set(n,S);let Hn=new WeakMap;Hn.set(pn,O),Os(H,Ss(Wn,ho,t,r,s,o,i,l,t==="comma"&&C&&W(w)?null:u,d,g,p,b,f,x,C,P,Hn))}return H}function xo(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=Ar;if(typeof n.format<"u"){if(!Ir(xr,n.format))throw new TypeError("Unknown format option provided.");t=n.format}let r=xr[t],s=N.filter;(typeof n.filter=="function"||W(n.filter))&&(s=n.filter);let o;if(n.arrayFormat&&n.arrayFormat in Rs?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 dn(n,e={}){let t=n,r=xo(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=Rs[r.arrayFormat],u=l==="comma"&&r.commaRoundTrip;s||(s=Object.keys(t)),r.sort&&s.sort(r.sort);let d=new WeakMap;for(let b=0;b<s.length;++b){let f=s[b];r.skipNulls&&t[f]===null||Os(i,Ss(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 Ts(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 Es;function gt(n){let e;return(Es??(e=new globalThis.TextEncoder,Es=e.encode.bind(e)))(n)}var vs;function hn(n){let e;return(vs??(e=new globalThis.TextDecoder,vs=e.decode.bind(e)))(n)}var X,V,ke=class{constructor(){X.set(this,void 0),V.set(this,void 0),A(this,X,new Uint8Array,"f"),A(this,V,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?gt(e):e;A(this,X,Ts([c(this,X,"f"),t]),"f");let r=[],s;for(;(s=Po(c(this,X,"f"),c(this,V,"f")))!=null;){if(s.carriage&&c(this,V,"f")==null){A(this,V,s.index,"f");continue}if(c(this,V,"f")!=null&&(s.index!==c(this,V,"f")+1||s.carriage)){r.push(hn(c(this,X,"f").subarray(0,c(this,V,"f")-1))),A(this,X,c(this,X,"f").subarray(c(this,V,"f")),"f"),A(this,V,null,"f");continue}let o=c(this,V,"f")!==null?s.preceding-1:s.preceding,i=hn(c(this,X,"f").subarray(0,o));r.push(i),A(this,X,c(this,X,"f").subarray(s.index),"f"),A(this,V,null,"f")}return r}flush(){return c(this,X,"f").length?this.decode(`
|
|
4
4
|
`):[]}};X=new WeakMap,V=new WeakMap;ke.NEWLINE_CHARS=new Set([`
|
|
5
|
-
`,"\r"]);ke.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function
|
|
6
|
-
`);r.enqueue(i)}catch(s){r.error(s)}},async cancel(){await t.return?.()}})}};async function*
|
|
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]=
|
|
5
|
+
`,"\r"]);ke.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 ks(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 Rr={off:0,error:200,warn:300,info:400,debug:500},mn=(n,e,t)=>{if(n){if(ps(Rr,n))return n;v(t).warn(`${e} was set to ${JSON.stringify(n)}, expected one of ${JSON.stringify(Object.keys(Rr))}`)}};function Kt(){}function Pr(n,e,t){return!e||Rr[n]>Rr[t]?Kt:e[n].bind(e)}var Ro={error:Kt,warn:Kt,info:Kt,debug:Kt},Ms=new WeakMap;function v(n){let e=n.logger,t=n.logLevel??"off";if(!e)return Ro;let r=Ms.get(e);if(r&&r[0]===t)return r[1];let s={error:Pr("error",e,t),warn:Pr("warn",e,t),info:Pr("info",e,t),debug:Pr("debug",e,t)};return Ms.set(e,[t,s]),s}var le=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 zt,re=class n{constructor(e,t,r){this.iterator=e,zt.set(this,void 0),this.controller=t,A(this,zt,r,"f")}static fromSSEResponse(e,t,r){let s=!1,o=r?v(r):console;async function*i(){if(s)throw new y("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let l=!1;try{for await(let u of Oo(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(Jt(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 ke,u=an(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 y("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(Jt(u))return;throw u}finally{l||t.abort()}}return new n(i,t,r)}[(zt=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,zt,"f")),new n(()=>s(t),this.controller,c(this,zt,"f"))]}toReadableStream(){let e=this,t;return on({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=gt(JSON.stringify(s)+`
|
|
6
|
+
`);r.enqueue(i)}catch(s){r.error(s)}},async cancel(){await t.return?.()}})}};async function*Oo(n,e){if(!n.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new y("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 y("Attempted to iterate over a response with no body");let t=new gn,r=new ke,s=an(n.body);for await(let o of So(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*So(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"?gt(t):t,s=new Uint8Array(e.length+r.length);s.set(e),s.set(r,e.length),e=s;let o;for(;(o=ks(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var gn=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]=Eo(e,":");return s.startsWith(" ")&&(s=s.substring(1)),t==="event"?this.event=s:t==="data"&&this.data.push(s),null}};function Eo(n,e){let t=n.indexOf(e);return t!==-1?[n.substring(0,t),e,n.substring(t+e.length)]:[n,"",""]}async function Or(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 _n(p,t)}return await t.text()})();return v(n).debug(`[${r}] response parsed`,le({retryOfRequestLogID:s,url:t.url,status:t.status,body:i,durationMs:Date.now()-o})),i}function _n(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 Yt,Me=class n extends Promise{constructor(e,t,r=Or){super(s=>{s(null)}),this.responsePromise=t,this.parseResponse=r,Yt.set(this,void 0),A(this,Yt,e,"f")}_thenUnwrap(e){return new n(c(this,Yt,"f"),this.responsePromise,async(t,r)=>_n(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,Yt,"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)}};Yt=new WeakMap;var Sr,Er=class{constructor(e,t,r,s){Sr.set(this,void 0),A(this,Sr,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 y("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await c(this,Sr,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Sr=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},Qt=class extends Me{constructor(e,t,r){super(e,t,async(s,o)=>new r(s,o.response,await Or(s,o),o.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},ne=class extends Er{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}},R=class extends Er{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:{...us(this.options.query),after:t}}:null}};a();a();a();var Cn=()=>{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 _t(n,e,t){return Cn(),new File(n,e??"unknown_file",t)}function Zt(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 yn=n=>n!=null&&typeof n=="object"&&typeof n[Symbol.asyncIterator]=="function";var K=async(n,e)=>({...n,body:await ko(n.body,e)}),$s=new WeakMap;function To(n){let e=typeof n=="function"?n:n.fetch,t=$s.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 $s.set(e,r),r}var ko=async(n,e)=>{if(!await To(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])=>bn(t,r,s))),t},Mo=n=>n instanceof Blob&&"name"in n;var bn=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,_t([await t.blob()],Zt(t)));else if(yn(t))n.append(e,_t([await new Response(wr(t)).blob()],Zt(t)));else if(Mo(t))n.append(e,t,Zt(t));else if(Array.isArray(t))await Promise.all(t.map(r=>bn(n,e+"[]",r)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([r,s])=>bn(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 Ns=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",$o=n=>n!=null&&typeof n=="object"&&typeof n.name=="string"&&typeof n.lastModified=="number"&&Ns(n),No=n=>n!=null&&typeof n=="object"&&typeof n.url=="string"&&typeof n.blob=="function";async function vr(n,e,t){if(Cn(),n=await n,$o(n))return n instanceof File?n:_t([await n.arrayBuffer()],n.name);if(No(n)){let s=await n.blob();return e||(e=new URL(n.url).pathname.split(/[\\/]/).pop()),_t(await wn(s),e,t)}let r=await wn(n);if(e||(e=Zt(n)),!t?.type){let s=r.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof s=="string"&&(t={...t,type:s})}return _t(r,e,t)}async function wn(n){let e=[];if(typeof n=="string"||ArrayBuffer.isView(n)||n instanceof ArrayBuffer)e.push(n);else if(Ns(n))e.push(n instanceof Blob?n:await n.arrayBuffer());else if(yn(n))for await(let t of n)e.push(...await wn(t));else{let t=n?.constructor?.name;throw new Error(`Unexpected data type: ${typeof n}${t?`; constructor: ${t}`:""}${Lo(n)}`)}return e}function Lo(n){return typeof n!="object"||n===null?"":`; props: [${Object.getOwnPropertyNames(n).map(t=>`"${t}"`).join(", ")}]`}a();a();a();a();var m=class{constructor(e){this._client=e}};a();a();a();function Fs(n){return n.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var Ls=Object.freeze(Object.create(null)),Uo=(n=Fs)=>function(t,...r){if(t.length===1)return t[0];let s=!1,o=[],i=t.reduce((g,p,b)=>{/[?#]/.test(p)&&(s=!0);let f=r[b],x=(s?encodeURIComponent:n)(""+f);return b!==r.length&&(f==null||typeof f=="object"&&f.toString===Object.getPrototypeOf(Object.getPrototypeOf(f.hasOwnProperty??Ls)??Ls)?.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+(b===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((b,f)=>{let x=" ".repeat(f.start-g),C="^".repeat(f.length);return g=f.start+f.length,b+x+C},"");throw new y(`Path parameters result in path with invalid segments:
|
|
8
8
|
${o.map(b=>b.error).join(`
|
|
9
9
|
`)}
|
|
10
10
|
${i}
|
|
11
|
-
${p}`)}return i},m=Fo(Ns);var $e=class extends h{list(e,t={},r){return this._client.getAPIList(m`/chat/completions/${e}/messages`,R,{query:t,...r})}};a();a();a();a();function Ls(n){return typeof n.parse=="function"}a();var bt=n=>n?.role==="assistant",yn=n=>n?.role==="tool";a();var wn,Tr,kr,er,tr,Mr,rr,ce,nr,$r,Nr,Ct,Fs,be=class{constructor(){wn.add(this),this.controller=new AbortController,Tr.set(this,void 0),kr.set(this,()=>{}),er.set(this,()=>{}),tr.set(this,void 0),Mr.set(this,()=>{}),rr.set(this,()=>{}),ce.set(this,{}),nr.set(this,!1),$r.set(this,!1),Nr.set(this,!1),Ct.set(this,!1),A(this,Tr,new Promise((e,t)=>{A(this,kr,e,"f"),A(this,er,t,"f")}),"f"),A(this,tr,new Promise((e,t)=>{A(this,Mr,e,"f"),A(this,rr,t,"f")}),"f"),c(this,Tr,"f").catch(()=>{}),c(this,tr,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},c(this,wn,"m",Fs).bind(this))},0)}_connected(){this.ended||(c(this,kr,"f").call(this),this._emit("connect"))}get ended(){return c(this,nr,"f")}get errored(){return c(this,$r,"f")}get aborted(){return c(this,Nr,"f")}abort(){this.controller.abort()}on(e,t){return(c(this,ce,"f")[e]||(c(this,ce,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=c(this,ce,"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,ce,"f")[e]||(c(this,ce,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{A(this,Ct,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,t)})}async done(){A(this,Ct,!0,"f"),await c(this,tr,"f")}_emit(e,...t){if(c(this,nr,"f"))return;e==="end"&&(A(this,nr,!0,"f"),c(this,Mr,"f").call(this));let r=c(this,ce,"f")[e];if(r&&(c(this,ce,"f")[e]=r.filter(s=>!s.once),r.forEach(({listener:s})=>s(...t))),e==="abort"){let s=t[0];!c(this,Ct,"f")&&!r?.length&&Promise.reject(s),c(this,er,"f").call(this,s),c(this,rr,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=t[0];!c(this,Ct,"f")&&!r?.length&&Promise.reject(s),c(this,er,"f").call(this,s),c(this,rr,"f").call(this,s),this._emit("end")}}_emitFinal(){}};Tr=new WeakMap,kr=new WeakMap,er=new WeakMap,tr=new WeakMap,Mr=new WeakMap,rr=new WeakMap,ce=new WeakMap,nr=new WeakMap,$r=new WeakMap,Nr=new WeakMap,Ct=new WeakMap,wn=new WeakSet,Fs=function(e){if(A(this,$r,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new k),e instanceof k)return A(this,Nr,!0,"f"),this._emit("abort",e);if(e instanceof y)return this._emit("error",e);if(e instanceof Error){let t=new y(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new y(String(e)))};a();function sr(n){return n?.$brand==="auto-parseable-response-format"}function Ne(n){return n?.$brand==="auto-parseable-tool"}function Us(n,e){return!e||!An(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}}))}:or(n,e)}function or(n,e){let t=n.choices.map(r=>{if(r.finish_reason==="length")throw new mt;if(r.finish_reason==="content_filter")throw new ht;return{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:r.message.tool_calls?.map(s=>Go(e,s))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?jo(e,r.message.content):null}}});return{...n,choices:t}}function jo(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 Go(n,e){let t=n.tools?.find(r=>r.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:Ne(t)?t.$parseRaw(e.function.arguments):t?.function.strict?JSON.parse(e.function.arguments):null}}}function Ds(n,e){if(!n)return!1;let t=n.tools?.find(r=>r.function?.name===e.function.name);return Ne(t)||t?.function.strict||!1}function An(n){return sr(n.response_format)?!0:n.tools?.some(e=>Ne(e)||e.type==="function"&&e.function.strict===!0)??!1}function js(n){for(let e of n??[]){if(e.type!=="function")throw new y(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new y(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var q,xn,Lr,In,Pn,Rn,Gs,Bs,Bo=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),yn(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(bt(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 y("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),c(this,q,"m",xn).call(this)}async finalMessage(){return await this.done(),c(this,q,"m",Lr).call(this)}async finalFunctionToolCall(){return await this.done(),c(this,q,"m",In).call(this)}async finalFunctionToolCallResult(){return await this.done(),c(this,q,"m",Pn).call(this)}async totalUsage(){return await this.done(),c(this,q,"m",Rn).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",Lr).call(this);t&&this._emit("finalMessage",t);let r=c(this,q,"m",xn).call(this);r&&this._emit("finalContent",r);let s=c(this,q,"m",In).call(this);s&&this._emit("finalFunctionToolCall",s);let o=c(this,q,"m",Pn).call(this);o!=null&&this._emit("finalFunctionToolCallResult",o),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",c(this,q,"m",Rn).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",Gs).call(this,t);let o=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(or(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=Bo}=r||{},g=t.tools.map(f=>{if(Ne(f)){if(!f.$callback)throw new y("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 b="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 C=(await this._createChatCompletion(e,{...l,tool_choice:o,tools:b,messages:[...this.messages]},r)).choices[0]?.message;if(!C)throw new y("missing message in ChatCompletion response");if(!C.tool_calls?.length)return;for(let P of C.tool_calls){if(P.type!=="function")continue;let O=P.id,{name:w,arguments:U}=P.function,S=p[w];if(S){if(u&&u!==w){let D=`Invalid tool_call: ${JSON.stringify(w)}. ${JSON.stringify(u)} requested. Please try again`;this._addMessage({role:s,tool_call_id:O,content:D});continue}}else{let D=`Invalid tool_call: ${JSON.stringify(w)}. Available options are: ${Object.keys(p).map(j=>JSON.stringify(j)).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:O,content:D});continue}let J;try{J=Ls(S)?await S.parse(U):U}catch(D){let j=D instanceof Error?D.message:String(D);this._addMessage({role:s,tool_call_id:O,content:j});continue}let H=await S.function(J,this),E=c(this,q,"m",Bs).call(this,H);if(this._addMessage({role:s,tool_call_id:O,content:E}),u)return}}}};q=new WeakSet,xn=function(){return c(this,q,"m",Lr).call(this).content??null},Lr=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(bt(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new y("stream ended without producing a ChatCompletionMessage with role=assistant")},In=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(bt(t)&&t?.tool_calls?.length)return t.tool_calls.at(-1)?.function}},Pn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(yn(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}},Rn=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},Gs=function(e){if(e.n!=null&&e.n>1)throw new y("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Bs=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var ir=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),bt(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},On=class extends Error{},Sn=class extends Error{};function Wo(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 Ho(n.trim(),e)}var Ho=(n,e)=>{let t=n.length,r=0,s=b=>{throw new On(`${b} at position ${r}`)},o=b=>{throw new Sn(`${b} 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 b=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(b,++r-Number(f)))}catch(x){o(String(x))}else if(G.STR&e)try{return JSON.parse(n.substring(b,r-Number(f))+'"')}catch{return JSON.parse(n.substring(b,n.lastIndexOf("\\"))+'"')}s("Unterminated string literal")},u=()=>{r++,p();let b={};try{for(;n[r]!=="}";){if(p(),r>=t&&G.OBJ&e)return b;let f=l();p(),r++;try{let x=i();Object.defineProperty(b,f,{value:x,writable:!0,enumerable:!0,configurable:!0})}catch(x){if(G.OBJ&e)return b;throw x}p(),n[r]===","&&r++}}catch{if(G.OBJ&e)return b;s("Expected '}' at end of object")}return r++,b},d=()=>{r++;let b=[];try{for(;n[r]!=="]";)b.push(i()),p(),n[r]===","&&r++}catch{if(G.ARR&e)return b;s("Expected ']' at end of array")}return r++,b},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 b=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(b,r))}catch{n.substring(b,r)==="-"&&G.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(n.substring(b,n.lastIndexOf("e")))}catch(x){o(String(x))}}},p=()=>{for(;r<t&&`
|
|
12
|
-
\r `.includes(n[r]);)r++};return i()},
|
|
11
|
+
${p}`)}return i},h=Uo(Fs);var $e=class extends m{list(e,t={},r){return this._client.getAPIList(h`/chat/completions/${e}/messages`,R,{query:t,...r})}};a();a();a();a();function Us(n){return typeof n.parse=="function"}a();var bt=n=>n?.role==="assistant",An=n=>n?.role==="tool";a();var xn,Tr,kr,er,tr,Mr,rr,ce,nr,$r,Nr,Ct,Ds,be=class{constructor(){xn.add(this),this.controller=new AbortController,Tr.set(this,void 0),kr.set(this,()=>{}),er.set(this,()=>{}),tr.set(this,void 0),Mr.set(this,()=>{}),rr.set(this,()=>{}),ce.set(this,{}),nr.set(this,!1),$r.set(this,!1),Nr.set(this,!1),Ct.set(this,!1),A(this,Tr,new Promise((e,t)=>{A(this,kr,e,"f"),A(this,er,t,"f")}),"f"),A(this,tr,new Promise((e,t)=>{A(this,Mr,e,"f"),A(this,rr,t,"f")}),"f"),c(this,Tr,"f").catch(()=>{}),c(this,tr,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},c(this,xn,"m",Ds).bind(this))},0)}_connected(){this.ended||(c(this,kr,"f").call(this),this._emit("connect"))}get ended(){return c(this,nr,"f")}get errored(){return c(this,$r,"f")}get aborted(){return c(this,Nr,"f")}abort(){this.controller.abort()}on(e,t){return(c(this,ce,"f")[e]||(c(this,ce,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=c(this,ce,"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,ce,"f")[e]||(c(this,ce,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{A(this,Ct,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,t)})}async done(){A(this,Ct,!0,"f"),await c(this,tr,"f")}_emit(e,...t){if(c(this,nr,"f"))return;e==="end"&&(A(this,nr,!0,"f"),c(this,Mr,"f").call(this));let r=c(this,ce,"f")[e];if(r&&(c(this,ce,"f")[e]=r.filter(s=>!s.once),r.forEach(({listener:s})=>s(...t))),e==="abort"){let s=t[0];!c(this,Ct,"f")&&!r?.length&&Promise.reject(s),c(this,er,"f").call(this,s),c(this,rr,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=t[0];!c(this,Ct,"f")&&!r?.length&&Promise.reject(s),c(this,er,"f").call(this,s),c(this,rr,"f").call(this,s),this._emit("end")}}_emitFinal(){}};Tr=new WeakMap,kr=new WeakMap,er=new WeakMap,tr=new WeakMap,Mr=new WeakMap,rr=new WeakMap,ce=new WeakMap,nr=new WeakMap,$r=new WeakMap,Nr=new WeakMap,Ct=new WeakMap,xn=new WeakSet,Ds=function(e){if(A(this,$r,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new k),e instanceof k)return A(this,Nr,!0,"f"),this._emit("abort",e);if(e instanceof y)return this._emit("error",e);if(e instanceof Error){let t=new y(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new y(String(e)))};a();function sr(n){return n?.$brand==="auto-parseable-response-format"}function Ne(n){return n?.$brand==="auto-parseable-tool"}function Gs(n,e){return!e||!In(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}}))}:or(n,e)}function or(n,e){let t=n.choices.map(r=>{if(r.finish_reason==="length")throw new ht;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=>Bo(e,s))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?jo(e,r.message.content):null}}});return{...n,choices:t}}function jo(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 Bo(n,e){let t=n.tools?.find(r=>r.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:Ne(t)?t.$parseRaw(e.function.arguments):t?.function.strict?JSON.parse(e.function.arguments):null}}}function js(n,e){if(!n)return!1;let t=n.tools?.find(r=>r.function?.name===e.function.name);return Ne(t)||t?.function.strict||!1}function In(n){return sr(n.response_format)?!0:n.tools?.some(e=>Ne(e)||e.type==="function"&&e.function.strict===!0)??!1}function Bs(n){for(let e of n??[]){if(e.type!=="function")throw new y(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new y(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var q,Pn,Lr,Rn,On,Sn,Ws,Hs,Wo=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),An(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(bt(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 y("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),c(this,q,"m",Pn).call(this)}async finalMessage(){return await this.done(),c(this,q,"m",Lr).call(this)}async finalFunctionToolCall(){return await this.done(),c(this,q,"m",Rn).call(this)}async finalFunctionToolCallResult(){return await this.done(),c(this,q,"m",On).call(this)}async totalUsage(){return await this.done(),c(this,q,"m",Sn).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",Lr).call(this);t&&this._emit("finalMessage",t);let r=c(this,q,"m",Pn).call(this);r&&this._emit("finalContent",r);let s=c(this,q,"m",Rn).call(this);s&&this._emit("finalFunctionToolCall",s);let o=c(this,q,"m",On).call(this);o!=null&&this._emit("finalFunctionToolCallResult",o),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",c(this,q,"m",Sn).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",Ws).call(this,t);let o=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(or(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=Wo}=r||{},g=t.tools.map(f=>{if(Ne(f)){if(!f.$callback)throw new y("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 b="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 C=(await this._createChatCompletion(e,{...l,tool_choice:o,tools:b,messages:[...this.messages]},r)).choices[0]?.message;if(!C)throw new y("missing message in ChatCompletion response");if(!C.tool_calls?.length)return;for(let P of C.tool_calls){if(P.type!=="function")continue;let O=P.id,{name:w,arguments:U}=P.function,S=p[w];if(S){if(u&&u!==w){let D=`Invalid tool_call: ${JSON.stringify(w)}. ${JSON.stringify(u)} requested. Please try again`;this._addMessage({role:s,tool_call_id:O,content:D});continue}}else{let D=`Invalid tool_call: ${JSON.stringify(w)}. Available options are: ${Object.keys(p).map(G=>JSON.stringify(G)).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:O,content:D});continue}let J;try{J=Us(S)?await S.parse(U):U}catch(D){let G=D instanceof Error?D.message:String(D);this._addMessage({role:s,tool_call_id:O,content:G});continue}let H=await S.function(J,this),E=c(this,q,"m",Hs).call(this,H);if(this._addMessage({role:s,tool_call_id:O,content:E}),u)return}}}};q=new WeakSet,Pn=function(){return c(this,q,"m",Lr).call(this).content??null},Lr=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(bt(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new y("stream ended without producing a ChatCompletionMessage with role=assistant")},Rn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(bt(t)&&t?.tool_calls?.length)return t.tool_calls.at(-1)?.function}},On=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(An(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}},Sn=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},Ws=function(e){if(e.n!=null&&e.n>1)throw new y("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Hs=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var ir=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),bt(e)&&e.content&&this._emit("content",e.content)}};a();a();a();a();var j={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},En=class extends Error{},vn=class extends Error{};function Ho(n,e=j.ALL){if(typeof n!="string")throw new TypeError(`expecting str, got ${typeof n}`);if(!n.trim())throw new Error(`${n} is empty`);return qo(n.trim(),e)}var qo=(n,e)=>{let t=n.length,r=0,s=b=>{throw new En(`${b} at position ${r}`)},o=b=>{throw new vn(`${b} 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"||j.NULL&e&&t-r<4&&"null".startsWith(n.substring(r))?(r+=4,null):n.substring(r,r+4)==="true"||j.BOOL&e&&t-r<4&&"true".startsWith(n.substring(r))?(r+=4,!0):n.substring(r,r+5)==="false"||j.BOOL&e&&t-r<5&&"false".startsWith(n.substring(r))?(r+=5,!1):n.substring(r,r+8)==="Infinity"||j.INFINITY&e&&t-r<8&&"Infinity".startsWith(n.substring(r))?(r+=8,1/0):n.substring(r,r+9)==="-Infinity"||j.MINUS_INFINITY&e&&1<t-r&&t-r<9&&"-Infinity".startsWith(n.substring(r))?(r+=9,-1/0):n.substring(r,r+3)==="NaN"||j.NAN&e&&t-r<3&&"NaN".startsWith(n.substring(r))?(r+=3,NaN):g()),l=()=>{let b=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(b,++r-Number(f)))}catch(x){o(String(x))}else if(j.STR&e)try{return JSON.parse(n.substring(b,r-Number(f))+'"')}catch{return JSON.parse(n.substring(b,n.lastIndexOf("\\"))+'"')}s("Unterminated string literal")},u=()=>{r++,p();let b={};try{for(;n[r]!=="}";){if(p(),r>=t&&j.OBJ&e)return b;let f=l();p(),r++;try{let x=i();Object.defineProperty(b,f,{value:x,writable:!0,enumerable:!0,configurable:!0})}catch(x){if(j.OBJ&e)return b;throw x}p(),n[r]===","&&r++}}catch{if(j.OBJ&e)return b;s("Expected '}' at end of object")}return r++,b},d=()=>{r++;let b=[];try{for(;n[r]!=="]";)b.push(i()),p(),n[r]===","&&r++}catch{if(j.ARR&e)return b;s("Expected ']' at end of array")}return r++,b},g=()=>{if(r===0){n==="-"&&j.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(n)}catch(f){if(j.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 b=r;for(n[r]==="-"&&r++;n[r]&&!",]}".includes(n[r]);)r++;r==t&&!(j.NUM&e)&&s("Unterminated number literal");try{return JSON.parse(n.substring(b,r))}catch{n.substring(b,r)==="-"&&j.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(n.substring(b,n.lastIndexOf("e")))}catch(x){o(String(x))}}},p=()=>{for(;r<t&&`
|
|
12
|
+
\r `.includes(n[r]);)r++};return i()},Tn=n=>Ho(n,j.ALL^j.NUM);var L,ue,wt,Ce,kn,Fr,Mn,$n,Nn,Ur,Ln,qs,Le=class n extends yt{constructor(e){super(),L.add(this),ue.set(this,void 0),wt.set(this,void 0),Ce.set(this,void 0),A(this,ue,e,"f"),A(this,wt,[],"f")}get currentChatCompletionSnapshot(){return c(this,Ce,"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,L,"m",kn).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,L,"m",Mn).call(this,i);if(o.controller.signal?.aborted)throw new k;return this._addChatCompletion(c(this,L,"m",Ur).call(this))}async _fromReadableStream(e,t){let r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),c(this,L,"m",kn).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,L,"m",Ur).call(this)),c(this,L,"m",Mn).call(this,i),o=i.id;if(s.controller.signal?.aborted)throw new k;return this._addChatCompletion(c(this,L,"m",Ur).call(this))}[(ue=new WeakMap,wt=new WeakMap,Ce=new WeakMap,L=new WeakSet,kn=function(){this.ended||A(this,Ce,void 0,"f")},Fr=function(t){let r=c(this,wt,"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,wt,"f")[t.index]=r,r)},Mn=function(t){if(this.ended)return;let r=c(this,L,"m",qs).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,L,"m",Fr).call(this,o);o.finish_reason&&(c(this,L,"m",Nn).call(this,o),i.current_tool_call_index!=null&&c(this,L,"m",$n).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,L,"m",Nn).call(this,o),i.current_tool_call_index!=null&&c(this,L,"m",$n).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))}}},$n=function(t,r){if(c(this,L,"m",Fr).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,ue,"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:Ne(i)?i.$parseRaw(o.function.arguments):i?.function.strict?JSON.parse(o.function.arguments):null})}else o.type},Nn=function(t){let r=c(this,L,"m",Fr).call(this,t);if(t.message.content&&!r.content_done){r.content_done=!0;let s=c(this,L,"m",Ln).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}))},Ur=function(){if(this.ended)throw new y("stream has ended, this shouldn't happen");let t=c(this,Ce,"f");if(!t)throw new y("request ended without sending any chunks");return A(this,Ce,void 0,"f"),A(this,wt,[],"f"),Jo(t,c(this,ue,"f"))},Ln=function(){let t=c(this,ue,"f")?.response_format;return sr(t)?t:null},qs=function(t){var r,s,o,i;let l=c(this,Ce,"f"),{choices:u,...d}=t;l?Object.assign(l,d):l=A(this,Ce,{...d,choices:[]},"f");for(let{delta:g,finish_reason:p,index:b,logprobs:f=null,...x}of t.choices){let C=l.choices[b];if(C||(C=l.choices[b]={finish_reason:p,index:b,message:{},logprobs:f,...x}),f)if(!C.logprobs)C.logprobs=Object.assign({},f);else{let{content:H,refusal:E,...D}=f;Object.assign(C.logprobs,D),H&&((r=C.logprobs).content??(r.content=[]),C.logprobs.content.push(...H)),E&&((s=C.logprobs).refusal??(s.refusal=[]),C.logprobs.refusal.push(...E))}if(p&&(C.finish_reason=p,c(this,ue,"f")&&In(c(this,ue,"f")))){if(p==="length")throw new ht;if(p==="content_filter")throw new mt}if(Object.assign(C,x),!g)continue;let{content:P,refusal:O,function_call:w,role:U,tool_calls:S,...J}=g;if(Object.assign(C.message,J),O&&(C.message.refusal=(C.message.refusal||"")+O),U&&(C.message.role=U),w&&(C.message.function_call?(w.name&&(C.message.function_call.name=w.name),w.arguments&&((o=C.message.function_call).arguments??(o.arguments=""),C.message.function_call.arguments+=w.arguments)):C.message.function_call=w),P&&(C.message.content=(C.message.content||"")+P,!C.message.refusal&&c(this,L,"m",Ln).call(this)&&(C.message.parsed=Tn(C.message.content))),S){C.message.tool_calls||(C.message.tool_calls=[]);for(let{index:H,id:E,type:D,function:G,...T}of S){let M=(i=C.message.tool_calls)[H]??(i[H]={});Object.assign(M,T),E&&(M.id=E),D&&(M.type=D),G&&(M.function??(M.function={name:G.name??"",arguments:""})),G?.name&&(M.function.name=G.name),G?.arguments&&(M.function.arguments+=G.arguments,js(c(this,ue,"f"),M)&&(M.function.parsed_arguments=Tn(M.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 Jo(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:b,...f})=>{if(!g)throw new y(`missing finish_reason for choice ${p}`);let{content:x=null,function_call:C,tool_calls:P,...O}=d,w=d.role;if(!w)throw new y(`missing role for choice ${p}`);if(C){let{arguments:U,name:S}=C;if(U==null)throw new y(`missing function_call.arguments for choice ${p}`);if(!S)throw new y(`missing function_call.name for choice ${p}`);return{...f,message:{content:x,function_call:{arguments:U,name:S},role:w,refusal:d.refusal??null},finish_reason:g,index:p,logprobs:b}}return P?{...f,index:p,finish_reason:g,logprobs:b,message:{...O,role:w,content:x,refusal:d.refusal??null,tool_calls:P.map((U,S)=>{let{function:J,type:H,id:E,...D}=U,{arguments:G,name:T,...M}=J||{};if(E==null)throw new y(`missing choices[${p}].tool_calls[${S}].id
|
|
13
13
|
${Dr(n)}`);if(H==null)throw new y(`missing choices[${p}].tool_calls[${S}].type
|
|
14
14
|
${Dr(n)}`);if(T==null)throw new y(`missing choices[${p}].tool_calls[${S}].function.name
|
|
15
|
-
${Dr(n)}`);if(
|
|
16
|
-
${Dr(n)}`);return{...D,id:E,type:H,function:{...M,name:T,arguments:j}}})}}:{...f,message:{...O,content:x,role:w,refusal:d.refusal??null},finish_reason:g,index:p,logprobs:b}}),created:s,model:o,object:"chat.completion",...i?{system_fingerprint:i}:{}};return Us(u,e)}function Dr(n){return JSON.stringify(n)}var ar=class n extends Le{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 fe=class extends h{constructor(){super(...arguments),this.messages=new $e(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",R,{query:e,...t})}delete(e,t){return this._client.delete(m`/chat/completions/${e}`,t)}parse(e,t){return js(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(r=>or(r,e))}runTools(e,t){return e.stream?ar.runTools(this._client,e,t):ir.runTools(this._client,e,t)}stream(e,t){return Le.createChatCompletion(this._client,e,t)}};fe.Messages=$e;var ye=class extends h{constructor(){super(...arguments),this.completions=new fe(this._client)}};ye.Completions=fe;a();a();a();a();a();var Hs=Symbol("brand.privateNullableHeaders");function*Xo(n){if(!n)return;if(Hs 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():rn(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=rn(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 Xo(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{[Hs]:!0,values:e,nulls:t}};var At=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 xt=class extends h{create(e,t){return this._client.post("/audio/transcriptions",K({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}};a();var It=class extends h{create(e,t){return this._client.post("/audio/translations",K({body:e,...t,__metadata:{model:e.model}},this._client))}};var se=class extends h{constructor(){super(...arguments),this.transcriptions=new xt(this._client),this.translations=new It(this._client),this.speech=new At(this._client)}};se.Transcriptions=xt;se.Translations=It;se.Speech=At;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",R,{query:e,...t})}cancel(e,t){return this._client.post(m`/batches/${e}/cancel`,t)}};a();a();var Pt=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",R,{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 Rt=class extends h{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};a();var Ot=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 Rt(this._client),this.transcriptionSessions=new Ot(this._client)}};we.Sessions=Rt;we.TranscriptionSessions=Ot;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`,R,{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 Et=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`,R,{query:o,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};a();a();a();var qs=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,De,Nn,oe,jr,Y,je,vt,Ue,Wr,z,Gr,Br,ur,lr,cr,Js,Xs,Vs,Ks,zs,Ys,Qs,pe=class extends be{constructor(){super(...arguments),B.add(this),Nn.set(this,[]),oe.set(this,{}),jr.set(this,{}),Y.set(this,void 0),je.set(this,void 0),vt.set(this,void 0),Ue.set(this,void 0),Wr.set(this,void 0),z.set(this,void 0),Gr.set(this,void 0),Br.set(this,void 0),ur.set(this,void 0)}[(Nn=new WeakMap,oe=new WeakMap,jr=new WeakMap,Y=new WeakMap,je=new WeakMap,vt=new WeakMap,Ue=new WeakMap,Wr=new WeakMap,z=new WeakMap,Gr=new WeakMap,Br=new WeakMap,ur=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 De;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",lr).call(this,o);if(s.controller.signal?.aborted)throw new k;return this._addRun(c(this,B,"m",cr).call(this))}toReadableStream(){return new re(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,s){let o=new De;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",lr).call(this,u);if(l.controller.signal?.aborted)throw new k;return this._addRun(c(this,B,"m",cr).call(this))}static createThreadAssistantStream(e,t,r){let s=new De;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 De;return o._run(()=>o._runAssistantStream(e,t,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return c(this,Gr,"f")}currentRun(){return c(this,Br,"f")}currentMessageSnapshot(){return c(this,Y,"f")}currentRunStepSnapshot(){return c(this,ur,"f")}async finalRunSteps(){return await this.done(),Object.values(c(this,oe,"f"))}async finalMessages(){return await this.done(),Object.values(c(this,jr,"f"))}async finalRun(){if(await this.done(),!c(this,je,"f"))throw Error("Final run was not received.");return c(this,je,"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",lr).call(this,l);if(i.controller.signal?.aborted)throw new k;return this._addRun(c(this,B,"m",cr).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",lr).call(this,u);if(l.controller.signal?.aborted)throw new k;return this._addRun(c(this,B,"m",cr).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(Vt(o)&&Vt(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(!Vt(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)}};De=pe,lr=function(e){if(!this.ended)switch(A(this,Gr,e,"f"),c(this,B,"m",Vs).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",Qs).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",Xs).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",Js).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},cr=function(){if(this.ended)throw new y("stream has ended, this shouldn't happen");if(!c(this,je,"f"))throw Error("Final run has not been received");return c(this,je,"f")},Js=function(e){let[t,r]=c(this,B,"m",zs).call(this,e,c(this,Y,"f"));A(this,Y,t,"f"),c(this,jr,"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,vt,"f")){if(c(this,Ue,"f"))switch(c(this,Ue,"f").type){case"text":this._emit("textDone",c(this,Ue,"f").text,c(this,Y,"f"));break;case"image_file":this._emit("imageFileDone",c(this,Ue,"f").image_file,c(this,Y,"f"));break}A(this,vt,s.index,"f")}A(this,Ue,t.content[s.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(c(this,vt,"f")!==void 0){let s=e.data.content[c(this,vt,"f")];if(s)switch(s.type){case"image_file":this._emit("imageFileDone",s.image_file,c(this,Y,"f"));break;case"text":this._emit("textDone",s.text,c(this,Y,"f"));break}}c(this,Y,"f")&&this._emit("messageDone",e.data),A(this,Y,void 0,"f")}},Xs=function(e){let t=c(this,B,"m",Ks).call(this,e);switch(A(this,ur,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,Wr,"f")?this._emit("toolCallDelta",o,t.step_details.tool_calls[o.index]):(c(this,z,"f")&&this._emit("toolCallDone",c(this,z,"f")),A(this,Wr,o.index,"f"),A(this,z,t.step_details.tool_calls[o.index],"f"),c(this,z,"f")&&this._emit("toolCallCreated",c(this,z,"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":A(this,ur,void 0,"f"),e.data.step_details.type=="tool_calls"&&c(this,z,"f")&&(this._emit("toolCallDone",c(this,z,"f")),A(this,z,void 0,"f")),this._emit("runStepDone",e.data,t);break;case"thread.run.step.in_progress":break}},Vs=function(e){c(this,Nn,"f").push(e),this._emit("event",e)},Ks=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=De.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")},zs=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",Ys).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")},Ys=function(e,t){return De.accumulateDelta(t,e)},Qs=function(e){switch(A(this,Br,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":A(this,je,e.data,"f"),c(this,z,"f")&&(this._emit("toolCallDone",c(this,z,"f")),A(this,z,void 0,"f"));break;case"thread.run.cancelling":break}};var Ge=class extends h{constructor(){super(...arguments),this.steps=new Et(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`,R,{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 pe.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 pe.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 pe.createToolAssistantStream(e,this._client.beta.threads.runs,t,r)}};Ge.Steps=Et;var xe=class extends h{constructor(){super(...arguments),this.runs=new Ge(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 pe.createThreadAssistantStream(e,this._client.beta.threads,t)}};xe.Runs=Ge;xe.Messages=St;var ie=class extends h{constructor(){super(...arguments),this.realtime=new we(this._client),this.assistants=new Pt(this._client),this.threads=new xe(this._client)}};ie.Realtime=we;ie.Assistants=Pt;ie.Threads=xe;a();var Be=class extends h{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}};a();a();a();var Tt=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 We=class extends h{constructor(){super(...arguments),this.content=new Tt(this._client)}create(e,t,r){return this._client.post(m`/containers/${e}/files`,K({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`,R,{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])})}};We.Content=Tt;var Ie=class extends h{constructor(){super(...arguments),this.files=new We(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",R,{query:e,...t})}delete(e,t){return this._client.delete(m`/containers/${e}`,{...t,headers:_([{Accept:"*/*"},t?.headers])})}};Ie.Files=We;a();var He=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=qs(u)}),i)))}};a();a();a();var kt=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`,R,{query:o,...r})}};var qe=class extends h{constructor(){super(...arguments),this.outputItems=new kt(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`,R,{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)}};qe.OutputItems=kt;var Pe=class extends h{constructor(){super(...arguments),this.runs=new qe(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",R,{query:e,...t})}delete(e,t){return this._client.delete(m`/evals/${e}`,t)}};Pe.Runs=qe;a();var Je=class extends h{create(e,t){return this._client.post("/files",K({body:e,...t},this._client))}retrieve(e,t){return this._client.get(m`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",R,{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 $t=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 $t(this._client)}};Xe.Graders=$t;a();a();var Nt=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 Ve=class extends h{constructor(){super(...arguments),this.permissions=new Nt(this._client)}};Ve.Permissions=Nt;a();a();var Lt=class extends h{list(e,t={},r){return this._client.getAPIList(m`/fine_tuning/jobs/${e}/checkpoints`,R,{query:t,...r})}};var Ke=class extends h{constructor(){super(...arguments),this.checkpoints=new Lt(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",R,{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`,R,{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)}};Ke.Checkpoints=Lt;var Q=class extends h{constructor(){super(...arguments),this.methods=new Mt(this._client),this.jobs=new Ke(this._client),this.checkpoints=new Ve(this._client),this.alpha=new Xe(this._client)}};Q.Methods=Mt;Q.Jobs=Ke;Q.Checkpoints=Ve;Q.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",K({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",K({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 Ye=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 Zs(n,e){return!e||!bi(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)}:Ln(n,e)}function Ln(n,e){let t=n.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:wi(e,s)};if(s.type==="message"){let o=s.content.map(i=>i.type==="output_text"?{...i,parsed:_i(e,i.text)}:i);return{...s,content:o}}return s}),r=Object.assign({},n,{output:t});return Object.getOwnPropertyDescriptor(n,"output_text")||Hr(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 _i(n,e){return n.text?.format?.type!=="json_schema"?null:"$parseRaw"in n.text?.format?(n.text?.format).$parseRaw(e):JSON.parse(e)}function bi(n){return!!sr(n.text?.format)}function Ci(n){return n?.$brand==="auto-parseable-tool"}function yi(n,e){return n.find(t=>t.type==="function"&&t.name===e)}function wi(n,e){let t=yi(n.tools??[],e.name);return{...e,...e,parsed_arguments:Ci(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function Hr(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 Ut,qr,Oe,Jr,eo,to,ro,no,Xr=class n extends be{constructor(e){super(),Ut.add(this),qr.set(this,void 0),Oe.set(this,void 0),Jr.set(this,void 0),A(this,qr,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,Ut,"m",eo).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,Ut,"m",to).call(this,l,i);if(o.controller.signal?.aborted)throw new k;return c(this,Ut,"m",ro).call(this)}[(qr=new WeakMap,Oe=new WeakMap,Jr=new WeakMap,Ut=new WeakSet,eo=function(){this.ended||A(this,Oe,void 0,"f")},to=function(t,r){if(this.ended)return;let s=(i,l)=>{(r==null||l.sequence_number>r)&&this._emit(i,l)},o=c(this,Ut,"m",no).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 y(`missing output at index ${t.output_index}`);if(i.type==="message"){let l=i.content[t.content_index];if(!l)throw new y(`missing content at index ${t.content_index}`);if(l.type!=="output_text")throw new y(`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 y(`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}},ro=function(){if(this.ended)throw new y("stream has ended, this shouldn't happen");let t=c(this,Oe,"f");if(!t)throw new y("request ended without sending any events");A(this,Oe,void 0,"f");let r=Ai(t,c(this,qr,"f"));return A(this,Jr,r,"f"),r},no=function(t){let r=c(this,Oe,"f");if(!r){if(t.type!=="response.created")throw new y(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return r=A(this,Oe,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 y(`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 y(`missing output at index ${t.output_index}`);if(s.type==="message"){let o=s.content[t.content_index];if(!o)throw new y(`missing content at index ${t.content_index}`);if(o.type!=="output_text")throw new y(`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 y(`missing output at index ${t.output_index}`);s.type==="function_call"&&(s.arguments+=t.delta);break}case"response.completed":{A(this,Oe,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 y("stream ended without producing a ChatCompletion");return e}};function Ai(n,e){return Zs(n,e)}a();var Dt=class extends h{list(e,t={},r){return this._client.getAPIList(m`/responses/${e}/input_items`,R,{query:t,...r})}};var Se=class extends h{constructor(){super(...arguments),this.inputItems=new Dt(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"&&Hr(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"&&Hr(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=>Ln(r,e))}stream(e,t){return Xr.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(m`/responses/${e}/cancel`,t)}};Se.InputItems=Dt;a();a();var jt=class extends h{create(e,t,r){return this._client.post(m`/uploads/${e}/parts`,K({body:t,...r},this._client))}};var Ee=class extends h{constructor(){super(...arguments),this.parts=new jt(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=jt;a();a();a();var so=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 Gt=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`,R,{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(b){for(let f of b){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 so(p),await this.createAndPoll(e,{file_ids:d})}};a();var Bt=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`,R,{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 de=class extends h{constructor(){super(...arguments),this.files=new Bt(this._client),this.fileBatches=new Gt(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",R,{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])})}};de.Files=Bt;de.FileBatches=Gt;a();var Wt,oo,Vr,Ze=class extends h{constructor(){super(...arguments),Wt.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,Wt,"m",oo).call(this,r);let o=_([t]).values,i=c(this,Wt,"m",Vr).call(this,o,"webhook-signature"),l=c(this,Wt,"m",Vr).call(this,o,"webhook-timestamp"),u=c(this,Wt,"m",Vr).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(C=>C.startsWith("v1,")?C.substring(3):C),b=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",b,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let C of p)try{let P=Buffer.from(C,"base64");if(await crypto.subtle.verify("HMAC",x,P,new TextEncoder().encode(f)))return}catch{continue}throw new Z("The given webhook signature does not match the expected signature")}};Wt=new WeakSet,oo=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")},Vr=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 Fn,Un,Kr,io,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(Fn.add(this),Kr.set(this,void 0),this.completions=new Be(this),this.chat=new ye(this),this.embeddings=new He(this),this.files=new Je(this),this.images=new ze(this),this.audio=new se(this),this.moderations=new Qe(this),this.models=new Ye(this),this.fineTuning=new Q(this),this.graders=new Re(this),this.vectorStores=new de(this),this.webhooks=new Ze(this),this.beta=new ie(this),this.batches=new Fe(this),this.uploads=new Ee(this),this.responses=new Se(this),this.evals=new Pe(this),this.containers=new Ie(this),t===void 0)throw new y("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&&gs())throw new y(`It looks like you're running in a browser-like environment.
|
|
15
|
+
${Dr(n)}`);if(G==null)throw new y(`missing choices[${p}].tool_calls[${S}].function.arguments
|
|
16
|
+
${Dr(n)}`);return{...D,id:E,type:H,function:{...M,name:T,arguments:G}}})}}:{...f,message:{...O,content:x,role:w,refusal:d.refusal??null},finish_reason:g,index:p,logprobs:b}}),created:s,model:o,object:"chat.completion",...i?{system_fingerprint:i}:{}};return Gs(u,e)}function Dr(n){return JSON.stringify(n)}var ar=class n extends Le{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 fe=class extends m{constructor(){super(...arguments),this.messages=new $e(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(h`/chat/completions/${e}`,t)}update(e,t,r){return this._client.post(h`/chat/completions/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/chat/completions",R,{query:e,...t})}delete(e,t){return this._client.delete(h`/chat/completions/${e}`,t)}parse(e,t){return Bs(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(r=>or(r,e))}runTools(e,t){return e.stream?ar.runTools(this._client,e,t):ir.runTools(this._client,e,t)}stream(e,t){return Le.createChatCompletion(this._client,e,t)}};fe.Messages=$e;var ye=class extends m{constructor(){super(...arguments),this.completions=new fe(this._client)}};ye.Completions=fe;a();a();a();a();a();var Js=Symbol("brand.privateNullableHeaders");function*Vo(n){if(!n)return;if(Js 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():sn(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=sn(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 Vo(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{[Js]:!0,values:e,nulls:t}};var At=class extends m{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:_([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}};a();var xt=class extends m{create(e,t){return this._client.post("/audio/transcriptions",K({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}};a();var It=class extends m{create(e,t){return this._client.post("/audio/translations",K({body:e,...t,__metadata:{model:e.model}},this._client))}};var se=class extends m{constructor(){super(...arguments),this.transcriptions=new xt(this._client),this.translations=new It(this._client),this.speech=new At(this._client)}};se.Transcriptions=xt;se.Translations=It;se.Speech=At;a();var Fe=class extends m{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(h`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",R,{query:e,...t})}cancel(e,t){return this._client.post(h`/batches/${e}/cancel`,t)}};a();a();var Pt=class extends m{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(h`/assistants/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(h`/assistants/${e}`,{body:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",R,{query:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(h`/assistants/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};a();a();var Rt=class extends m{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};a();var Ot=class extends m{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};var we=class extends m{constructor(){super(...arguments),this.sessions=new Rt(this._client),this.transcriptionSessions=new Ot(this._client)}};we.Sessions=Rt;we.TranscriptionSessions=Ot;a();a();var St=class extends m{create(e,t,r){return this._client.post(h`/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(h`/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(h`/threads/${s}/messages/${e}`,{body:o,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(h`/threads/${e}/messages`,R,{query:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){let{thread_id:s}=t;return this._client.delete(h`/threads/${s}/messages/${e}`,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};a();a();var Et=class extends m{retrieve(e,t,r){let{thread_id:s,run_id:o,...i}=t;return this._client.get(h`/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(h`/threads/${s}/runs/${e}/steps`,R,{query:o,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};a();a();a();var Xs=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,De,Fn,oe,Gr,Y,Ge,vt,Ue,Wr,z,jr,Br,ur,lr,cr,Vs,Ks,zs,Ys,Qs,Zs,eo,pe=class extends be{constructor(){super(...arguments),B.add(this),Fn.set(this,[]),oe.set(this,{}),Gr.set(this,{}),Y.set(this,void 0),Ge.set(this,void 0),vt.set(this,void 0),Ue.set(this,void 0),Wr.set(this,void 0),z.set(this,void 0),jr.set(this,void 0),Br.set(this,void 0),ur.set(this,void 0)}[(Fn=new WeakMap,oe=new WeakMap,Gr=new WeakMap,Y=new WeakMap,Ge=new WeakMap,vt=new WeakMap,Ue=new WeakMap,Wr=new WeakMap,z=new WeakMap,jr=new WeakMap,Br=new WeakMap,ur=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 De;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",lr).call(this,o);if(s.controller.signal?.aborted)throw new k;return this._addRun(c(this,B,"m",cr).call(this))}toReadableStream(){return new re(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,s){let o=new De;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",lr).call(this,u);if(l.controller.signal?.aborted)throw new k;return this._addRun(c(this,B,"m",cr).call(this))}static createThreadAssistantStream(e,t,r){let s=new De;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 De;return o._run(()=>o._runAssistantStream(e,t,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return c(this,jr,"f")}currentRun(){return c(this,Br,"f")}currentMessageSnapshot(){return c(this,Y,"f")}currentRunStepSnapshot(){return c(this,ur,"f")}async finalRunSteps(){return await this.done(),Object.values(c(this,oe,"f"))}async finalMessages(){return await this.done(),Object.values(c(this,Gr,"f"))}async finalRun(){if(await this.done(),!c(this,Ge,"f"))throw Error("Final run was not received.");return c(this,Ge,"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",lr).call(this,l);if(i.controller.signal?.aborted)throw new k;return this._addRun(c(this,B,"m",cr).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",lr).call(this,u);if(l.controller.signal?.aborted)throw new k;return this._addRun(c(this,B,"m",cr).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(Vt(o)&&Vt(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(!Vt(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)}};De=pe,lr=function(e){if(!this.ended)switch(A(this,jr,e,"f"),c(this,B,"m",zs).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",eo).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",Ks).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",Vs).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},cr=function(){if(this.ended)throw new y("stream has ended, this shouldn't happen");if(!c(this,Ge,"f"))throw Error("Final run has not been received");return c(this,Ge,"f")},Vs=function(e){let[t,r]=c(this,B,"m",Qs).call(this,e,c(this,Y,"f"));A(this,Y,t,"f"),c(this,Gr,"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,vt,"f")){if(c(this,Ue,"f"))switch(c(this,Ue,"f").type){case"text":this._emit("textDone",c(this,Ue,"f").text,c(this,Y,"f"));break;case"image_file":this._emit("imageFileDone",c(this,Ue,"f").image_file,c(this,Y,"f"));break}A(this,vt,s.index,"f")}A(this,Ue,t.content[s.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(c(this,vt,"f")!==void 0){let s=e.data.content[c(this,vt,"f")];if(s)switch(s.type){case"image_file":this._emit("imageFileDone",s.image_file,c(this,Y,"f"));break;case"text":this._emit("textDone",s.text,c(this,Y,"f"));break}}c(this,Y,"f")&&this._emit("messageDone",e.data),A(this,Y,void 0,"f")}},Ks=function(e){let t=c(this,B,"m",Ys).call(this,e);switch(A(this,ur,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,Wr,"f")?this._emit("toolCallDelta",o,t.step_details.tool_calls[o.index]):(c(this,z,"f")&&this._emit("toolCallDone",c(this,z,"f")),A(this,Wr,o.index,"f"),A(this,z,t.step_details.tool_calls[o.index],"f"),c(this,z,"f")&&this._emit("toolCallCreated",c(this,z,"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":A(this,ur,void 0,"f"),e.data.step_details.type=="tool_calls"&&c(this,z,"f")&&(this._emit("toolCallDone",c(this,z,"f")),A(this,z,void 0,"f")),this._emit("runStepDone",e.data,t);break;case"thread.run.step.in_progress":break}},zs=function(e){c(this,Fn,"f").push(e),this._emit("event",e)},Ys=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=De.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")},Qs=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",Zs).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")},Zs=function(e,t){return De.accumulateDelta(t,e)},eo=function(e){switch(A(this,Br,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":A(this,Ge,e.data,"f"),c(this,z,"f")&&(this._emit("toolCallDone",c(this,z,"f")),A(this,z,void 0,"f"));break;case"thread.run.cancelling":break}};var je=class extends m{constructor(){super(...arguments),this.steps=new Et(this._client)}create(e,t,r){let{include:s,...o}=t;return this._client.post(h`/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(h`/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(h`/threads/${s}/runs/${e}`,{body:o,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(h`/threads/${e}/runs`,R,{query:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){let{thread_id:s}=t;return this._client.post(h`/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 pe.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 pe.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r){let{thread_id:s,...o}=t;return this._client.post(h`/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 pe.createToolAssistantStream(e,this._client.beta.threads.runs,t,r)}};je.Steps=Et;var xe=class extends m{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(h`/threads/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(h`/threads/${e}`,{body:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t){return this._client.delete(h`/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 pe.createThreadAssistantStream(e,this._client.beta.threads,t)}};xe.Runs=je;xe.Messages=St;var ie=class extends m{constructor(){super(...arguments),this.realtime=new we(this._client),this.assistants=new Pt(this._client),this.threads=new xe(this._client)}};ie.Realtime=we;ie.Assistants=Pt;ie.Threads=xe;a();var Be=class extends m{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}};a();a();a();var Tt=class extends m{retrieve(e,t,r){let{container_id:s}=t;return this._client.get(h`/containers/${s}/files/${e}/content`,{...r,headers:_([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}};var We=class extends m{constructor(){super(...arguments),this.content=new Tt(this._client)}create(e,t,r){return this._client.post(h`/containers/${e}/files`,K({body:t,...r},this._client))}retrieve(e,t,r){let{container_id:s}=t;return this._client.get(h`/containers/${s}/files/${e}`,r)}list(e,t={},r){return this._client.getAPIList(h`/containers/${e}/files`,R,{query:t,...r})}delete(e,t,r){let{container_id:s}=t;return this._client.delete(h`/containers/${s}/files/${e}`,{...r,headers:_([{Accept:"*/*"},r?.headers])})}};We.Content=Tt;var Ie=class extends m{constructor(){super(...arguments),this.files=new We(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(h`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",R,{query:e,...t})}delete(e,t){return this._client.delete(h`/containers/${e}`,{...t,headers:_([{Accept:"*/*"},t?.headers])})}};Ie.Files=We;a();var He=class extends m{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=Xs(u)}),i)))}};a();a();a();var kt=class extends m{retrieve(e,t,r){let{eval_id:s,run_id:o}=t;return this._client.get(h`/evals/${s}/runs/${o}/output_items/${e}`,r)}list(e,t,r){let{eval_id:s,...o}=t;return this._client.getAPIList(h`/evals/${s}/runs/${e}/output_items`,R,{query:o,...r})}};var qe=class extends m{constructor(){super(...arguments),this.outputItems=new kt(this._client)}create(e,t,r){return this._client.post(h`/evals/${e}/runs`,{body:t,...r})}retrieve(e,t,r){let{eval_id:s}=t;return this._client.get(h`/evals/${s}/runs/${e}`,r)}list(e,t={},r){return this._client.getAPIList(h`/evals/${e}/runs`,R,{query:t,...r})}delete(e,t,r){let{eval_id:s}=t;return this._client.delete(h`/evals/${s}/runs/${e}`,r)}cancel(e,t,r){let{eval_id:s}=t;return this._client.post(h`/evals/${s}/runs/${e}`,r)}};qe.OutputItems=kt;var Pe=class extends m{constructor(){super(...arguments),this.runs=new qe(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(h`/evals/${e}`,t)}update(e,t,r){return this._client.post(h`/evals/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/evals",R,{query:e,...t})}delete(e,t){return this._client.delete(h`/evals/${e}`,t)}};Pe.Runs=qe;a();var Je=class extends m{create(e,t){return this._client.post("/files",K({body:e,...t},this._client))}retrieve(e,t){return this._client.get(h`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",R,{query:e,...t})}delete(e,t){return this._client.delete(h`/files/${e}`,t)}content(e,t){return this._client.get(h`/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 m{};a();a();var $t=class extends m{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 m{constructor(){super(...arguments),this.graders=new $t(this._client)}};Xe.Graders=$t;a();a();var Nt=class extends m{create(e,t,r){return this._client.getAPIList(h`/fine_tuning/checkpoints/${e}/permissions`,ne,{body:t,method:"post",...r})}retrieve(e,t={},r){return this._client.get(h`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...r})}delete(e,t,r){let{fine_tuned_model_checkpoint:s}=t;return this._client.delete(h`/fine_tuning/checkpoints/${s}/permissions/${e}`,r)}};var Ve=class extends m{constructor(){super(...arguments),this.permissions=new Nt(this._client)}};Ve.Permissions=Nt;a();a();var Lt=class extends m{list(e,t={},r){return this._client.getAPIList(h`/fine_tuning/jobs/${e}/checkpoints`,R,{query:t,...r})}};var Ke=class extends m{constructor(){super(...arguments),this.checkpoints=new Lt(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(h`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",R,{query:e,...t})}cancel(e,t){return this._client.post(h`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},r){return this._client.getAPIList(h`/fine_tuning/jobs/${e}/events`,R,{query:t,...r})}pause(e,t){return this._client.post(h`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(h`/fine_tuning/jobs/${e}/resume`,t)}};Ke.Checkpoints=Lt;var Q=class extends m{constructor(){super(...arguments),this.methods=new Mt(this._client),this.jobs=new Ke(this._client),this.checkpoints=new Ve(this._client),this.alpha=new Xe(this._client)}};Q.Methods=Mt;Q.Jobs=Ke;Q.Checkpoints=Ve;Q.Alpha=Xe;a();a();var Ft=class extends m{};var Re=class extends m{constructor(){super(...arguments),this.graderModels=new Ft(this._client)}};Re.GraderModels=Ft;a();var ze=class extends m{createVariation(e,t){return this._client.post("/images/variations",K({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",K({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 Ye=class extends m{retrieve(e,t){return this._client.get(h`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",ne,e)}delete(e,t){return this._client.delete(h`/models/${e}`,t)}};a();var Qe=class extends m{create(e,t){return this._client.post("/moderations",{body:e,...t})}};a();a();function to(n,e){return!e||!Ci(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)}:Un(n,e)}function Un(n,e){let t=n.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:Ai(e,s)};if(s.type==="message"){let o=s.content.map(i=>i.type==="output_text"?{...i,parsed:bi(e,i.text)}:i);return{...s,content:o}}return s}),r=Object.assign({},n,{output:t});return Object.getOwnPropertyDescriptor(n,"output_text")||Hr(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 bi(n,e){return n.text?.format?.type!=="json_schema"?null:"$parseRaw"in n.text?.format?(n.text?.format).$parseRaw(e):JSON.parse(e)}function Ci(n){return!!sr(n.text?.format)}function yi(n){return n?.$brand==="auto-parseable-tool"}function wi(n,e){return n.find(t=>t.type==="function"&&t.name===e)}function Ai(n,e){let t=wi(n.tools??[],e.name);return{...e,...e,parsed_arguments:yi(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function Hr(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 Ut,qr,Oe,Jr,ro,no,so,oo,Xr=class n extends be{constructor(e){super(),Ut.add(this),qr.set(this,void 0),Oe.set(this,void 0),Jr.set(this,void 0),A(this,qr,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,Ut,"m",ro).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,Ut,"m",no).call(this,l,i);if(o.controller.signal?.aborted)throw new k;return c(this,Ut,"m",so).call(this)}[(qr=new WeakMap,Oe=new WeakMap,Jr=new WeakMap,Ut=new WeakSet,ro=function(){this.ended||A(this,Oe,void 0,"f")},no=function(t,r){if(this.ended)return;let s=(i,l)=>{(r==null||l.sequence_number>r)&&this._emit(i,l)},o=c(this,Ut,"m",oo).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 y(`missing output at index ${t.output_index}`);if(i.type==="message"){let l=i.content[t.content_index];if(!l)throw new y(`missing content at index ${t.content_index}`);if(l.type!=="output_text")throw new y(`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 y(`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}},so=function(){if(this.ended)throw new y("stream has ended, this shouldn't happen");let t=c(this,Oe,"f");if(!t)throw new y("request ended without sending any events");A(this,Oe,void 0,"f");let r=xi(t,c(this,qr,"f"));return A(this,Jr,r,"f"),r},oo=function(t){let r=c(this,Oe,"f");if(!r){if(t.type!=="response.created")throw new y(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return r=A(this,Oe,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 y(`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 y(`missing output at index ${t.output_index}`);if(s.type==="message"){let o=s.content[t.content_index];if(!o)throw new y(`missing content at index ${t.content_index}`);if(o.type!=="output_text")throw new y(`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 y(`missing output at index ${t.output_index}`);s.type==="function_call"&&(s.arguments+=t.delta);break}case"response.completed":{A(this,Oe,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 y("stream ended without producing a ChatCompletion");return e}};function xi(n,e){return to(n,e)}a();var Dt=class extends m{list(e,t={},r){return this._client.getAPIList(h`/responses/${e}/input_items`,R,{query:t,...r})}};var Se=class extends m{constructor(){super(...arguments),this.inputItems=new Dt(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"&&Hr(r),r))}retrieve(e,t={},r){return this._client.get(h`/responses/${e}`,{query:t,...r,stream:t?.stream??!1})._thenUnwrap(s=>("object"in s&&s.object==="response"&&Hr(s),s))}delete(e,t){return this._client.delete(h`/responses/${e}`,{...t,headers:_([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(r=>Un(r,e))}stream(e,t){return Xr.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(h`/responses/${e}/cancel`,t)}};Se.InputItems=Dt;a();a();var Gt=class extends m{create(e,t,r){return this._client.post(h`/uploads/${e}/parts`,K({body:t,...r},this._client))}};var Ee=class extends m{constructor(){super(...arguments),this.parts=new Gt(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(h`/uploads/${e}/cancel`,t)}complete(e,t,r){return this._client.post(h`/uploads/${e}/complete`,{body:t,...r})}};Ee.Parts=Gt;a();a();a();var io=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 m{create(e,t,r){return this._client.post(h`/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(h`/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(h`/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(h`/vector_stores/${s}/file_batches/${e}/files`,R,{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(b){for(let f of b){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 io(p),await this.createAndPoll(e,{file_ids:d})}};a();var Bt=class extends m{create(e,t,r){return this._client.post(h`/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(h`/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(h`/vector_stores/${s}/files/${e}`,{body:o,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(h`/vector_stores/${e}/files`,R,{query:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){let{vector_store_id:s}=t;return this._client.delete(h`/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(h`/vector_stores/${s}/files/${e}/content`,ne,{...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};var de=class extends m{constructor(){super(...arguments),this.files=new Bt(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(h`/vector_stores/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(h`/vector_stores/${e}`,{body:t,...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",R,{query:e,...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(h`/vector_stores/${e}`,{...t,headers:_([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,r){return this._client.getAPIList(h`/vector_stores/${e}/search`,ne,{body:t,method:"post",...r,headers:_([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};de.Files=Bt;de.FileBatches=jt;a();var Wt,ao,Vr,Ze=class extends m{constructor(){super(...arguments),Wt.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,Wt,"m",ao).call(this,r);let o=_([t]).values,i=c(this,Wt,"m",Vr).call(this,o,"webhook-signature"),l=c(this,Wt,"m",Vr).call(this,o,"webhook-timestamp"),u=c(this,Wt,"m",Vr).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(C=>C.startsWith("v1,")?C.substring(3):C),b=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",b,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let C of p)try{let P=Buffer.from(C,"base64");if(await crypto.subtle.verify("HMAC",x,P,new TextEncoder().encode(f)))return}catch{continue}throw new Z("The given webhook signature does not match the expected signature")}};Wt=new WeakSet,ao=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")},Vr=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 Dn,Gn,Kr,lo,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(Dn.add(this),Kr.set(this,void 0),this.completions=new Be(this),this.chat=new ye(this),this.embeddings=new He(this),this.files=new Je(this),this.images=new ze(this),this.audio=new se(this),this.moderations=new Qe(this),this.models=new Ye(this),this.fineTuning=new Q(this),this.graders=new Re(this),this.vectorStores=new de(this),this.webhooks=new Ze(this),this.beta=new ie(this),this.batches=new Fe(this),this.uploads=new Ee(this),this.responses=new Se(this),this.evals=new Pe(this),this.containers=new Ie(this),t===void 0)throw new y("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&&bs())throw new y(`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,15 +22,15 @@ 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??Un.DEFAULT_TIMEOUT,this.logger=l.logger??console;let u="warn";this.logLevel=u,this.logLevel=dn(l.logLevel,"ClientOptions.logLevel",this)??dn(Ae("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??u,this.fetchOptions=l.fetchOptions,this.maxRetries=l.maxRetries??2,this.fetch=l.fetch??bs(),A(this,Kr,ys,"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 fn(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${_e}`}defaultIdempotencyKey(){return`stainless-node-retry-${tn()}`}makeStatusError(e,t,r,s){return $.generate(e,t,r,s)}buildURL(e,t,r){let s=!c(this,Fn,"m",io).call(this)&&r||this.baseURL,o=as(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return cs(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`,le({retryOfRequestLogID:r,method:s.method,url:l,options:s,headers:i.headers})),s.signal?.aborted)throw new k;let b=new AbortController,f=await this.fetchWithTimeout(l,i,u,b).catch(Xt),x=Date.now();if(f instanceof Error){let O=`retrying, ${t} attempts remaining`;if(s.signal?.aborted)throw new k;let w=Jt(f)||/timed? ?out/i.test(String(f)+("cause"in f?String(f.cause):""));if(t)return v(this).info(`[${d}] connection ${w?"timed out":"failed"} - ${O}`),v(this).debug(`[${d}] connection ${w?"timed out":"failed"} (${O})`,le({retryOfRequestLogID:r,url:l,durationMs:x-p,message:f.message})),this.retryRequest(s,t,r??d);throw v(this).info(`[${d}] connection ${w?"timed out":"failed"} - error; no more retries left`),v(this).debug(`[${d}] connection ${w?"timed out":"failed"} (error; no more retries left)`,le({retryOfRequestLogID:r,url:l,durationMs:x-p,message:f.message})),w?new ge:new he({cause:f})}let C=[...f.headers.entries()].filter(([O])=>O==="x-request-id").map(([O,w])=>", "+O+": "+JSON.stringify(w)).join(""),P=`[${d}${g}${C}] ${i.method} ${l} ${f.ok?"succeeded":"failed"} with status ${f.status} in ${x-p}ms`;if(!f.ok){let O=await this.shouldRetry(f);if(t&&O){let E=`retrying, ${t} attempts remaining`;return await Cs(f.body),v(this).info(`${P} - ${E}`),v(this).debug(`[${d}] response error (${E})`,le({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,durationMs:x-p})),this.retryRequest(s,t,r??d,f.headers)}let w=O?"error; no more retries left":"error; not retryable";v(this).info(`${P} - ${w}`);let U=await f.text().catch(E=>Xt(E).message),S=ps(U),J=S?void 0:U;throw v(this).debug(`[${d}] response error (${w})`,le({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,message:J,durationMs:Date.now()-p})),this.makeStatusError(f.status,S,J,f.headers)}return v(this).info(P),v(this).debug(`[${d}] response start`,le({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,durationMs:x-p})),{response:f,options:s,controller:b,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 Qt(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&&fs("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))}:{},..._s(),"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:wr(e)}:c(this,Kr,"f").call(this,{body:e,headers:r})}};Un=I,Kr=new WeakMap,Fn=new WeakSet,io=function(){return this.baseURL!=="https://api.openai.com/v1"};I.OpenAI=Un;I.DEFAULT_TIMEOUT=6e5;I.OpenAIError=y;I.APIError=$;I.APIConnectionError=he;I.APIConnectionTimeoutError=ge;I.APIUserAbortError=k;I.NotFoundError=ct;I.ConflictError=ut;I.RateLimitError=pt;I.BadRequestError=it;I.AuthenticationError=at;I.InternalServerError=dt;I.PermissionDeniedError=lt;I.UnprocessableEntityError=ft;I.InvalidWebhookSignatureError=Z;I.toFile=vr;I.Completions=Be;I.Chat=ye;I.Embeddings=He;I.Files=Je;I.Images=ze;I.Audio=se;I.Moderations=Qe;I.Models=Ye;I.FineTuning=Q;I.Graders=Re;I.VectorStores=de;I.Webhooks=Ze;I.Beta=ie;I.Batches=Fe;I.Uploads=Ee;I.Responses=Se;I.Evals=Pe;I.Containers=Ie;a();function Si(n){return n.toLowerCase().includes("matilda3")}function Ei(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 F=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};for(let[o,i]of Object.entries(r??{}))zn(o)||(s[o]=i);return s}buildClient(){let{apiKey:e,baseUrl:t,timeout:r=6e5,maxRetries:s=3}=this.contentGeneratorConfig,o=this.buildHeaders(),i=yr("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=Si(e.model)?s.messages.map(Ei):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=ns(e.model,"output"),s=rs(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 Ht=class extends F{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 vi=me("MatildaOpenAICompatibleProvider"),ae=class n extends F{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=hr?.endsWith("/")?hr.slice(0,-1):hr,u=!!(l&&s.toLowerCase()===l.toLowerCase());return l&&!i&&!u&&vi.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??{}))!Qn(o)&&o.toLowerCase()!=="x-stainless-retry-count"&&(s[o]=i);return qt(this.contentGeneratorConfig)&&Object.assign(s,Yn(this.cliConfig)),s}buildClient(){let{apiKey:e,baseUrl:t=Kn,timeout:r=6e5,maxRetries:s=3}=this.contentGeneratorConfig,o=this.buildHeaders(),i=yr("openai",this.cliConfig.getProxy()),l=i?.fetch??globalThis.fetch,u=qt(this.contentGeneratorConfig)?async(d,g)=>{let p=new Headers(d instanceof Request?d.headers:void 0);new Headers(g?.headers).forEach((C,P)=>{p.set(P,C)});let b=p.has(gr)||p.has(_r),f=br(),x=b||Object.keys(f).length>0;if(x){p.delete(gr),p.delete(_r);for(let[P,O]of Object.entries(f))p.set(P,O);let C=p.get("x-stainless-retry-count");p.has(gr)&&C!==null&&/^[1-9][0-9]*$/.test(C)&&p.set(_r,"retry")}this.cliConfig.getChannel()===void 0&&Zn({authStage:"inference_started",authOutcome:"started"},{baseUrl:t,token:e}).catch(()=>{});try{let C=await l(d,x?{...g,headers:p}:g);return es({baseUrl:this.contentGeneratorConfig.baseUrl,token:this.contentGeneratorConfig.apiKey}).catch(()=>{}),C}catch(C){throw Cr(C,{cliConfig:this.cliConfig,proxyConfigured:!!this.cliConfig.getProxy()}),C}}:void 0;return new I({apiKey:e,baseURL:t,timeout:r,maxRetries:s,defaultHeaders:o,...i||{},...u?{fetch:u}:{}})}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 zr(n){if(n.role!=="assistant")return n;let e=n;return typeof e.reasoning_content=="string"?n:{...e,reasoning_content:""}}function fr(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 Ti(n){return fr(n)?!0:(n.model??"").toLowerCase().includes("deepseek")}var et=class extends F{constructor(e,t){super(e,t)}static isDeepSeekProvider=Ti;static isDeepSeekHostname=fr;buildRequest(e,t){let r=super.buildRequest(e,t),s=fr(this.contentGeneratorConfig)?Mi(r):r;if(!s.messages?.length)return s;let o=s.messages.map(i=>{let l=ki(i);return zr(l)});return{...s,messages:o}}getDefaultGenerationConfig(){return{temperature:0}}};function ki(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??Gn.DEFAULT_TIMEOUT,this.logger=l.logger??console;let u="warn";this.logLevel=u,this.logLevel=mn(l.logLevel,"ClientOptions.logLevel",this)??mn(Ae("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??u,this.fetchOptions=l.fetchOptions,this.maxRetries=l.maxRetries??2,this.fetch=l.fetch??ys(),A(this,Kr,As,"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 dn(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${_e}`}defaultIdempotencyKey(){return`stainless-node-retry-${nn()}`}makeStatusError(e,t,r,s){return $.generate(e,t,r,s)}buildURL(e,t,r){let s=!c(this,Dn,"m",lo).call(this)&&r||this.baseURL,o=cs(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return fs(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`,le({retryOfRequestLogID:r,method:s.method,url:l,options:s,headers:i.headers})),s.signal?.aborted)throw new k;let b=new AbortController,f=await this.fetchWithTimeout(l,i,u,b).catch(Xt),x=Date.now();if(f instanceof Error){let O=`retrying, ${t} attempts remaining`;if(s.signal?.aborted)throw new k;let w=Jt(f)||/timed? ?out/i.test(String(f)+("cause"in f?String(f.cause):""));if(t)return v(this).info(`[${d}] connection ${w?"timed out":"failed"} - ${O}`),v(this).debug(`[${d}] connection ${w?"timed out":"failed"} (${O})`,le({retryOfRequestLogID:r,url:l,durationMs:x-p,message:f.message})),this.retryRequest(s,t,r??d);throw v(this).info(`[${d}] connection ${w?"timed out":"failed"} - error; no more retries left`),v(this).debug(`[${d}] connection ${w?"timed out":"failed"} (error; no more retries left)`,le({retryOfRequestLogID:r,url:l,durationMs:x-p,message:f.message})),w?new ge:new me({cause:f})}let C=[...f.headers.entries()].filter(([O])=>O==="x-request-id").map(([O,w])=>", "+O+": "+JSON.stringify(w)).join(""),P=`[${d}${g}${C}] ${i.method} ${l} ${f.ok?"succeeded":"failed"} with status ${f.status} in ${x-p}ms`;if(!f.ok){let O=await this.shouldRetry(f);if(t&&O){let E=`retrying, ${t} attempts remaining`;return await ws(f.body),v(this).info(`${P} - ${E}`),v(this).debug(`[${d}] response error (${E})`,le({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,durationMs:x-p})),this.retryRequest(s,t,r??d,f.headers)}let w=O?"error; no more retries left":"error; not retryable";v(this).info(`${P} - ${w}`);let U=await f.text().catch(E=>Xt(E).message),S=hs(U),J=S?void 0:U;throw v(this).debug(`[${d}] response error (${w})`,le({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,message:J,durationMs:Date.now()-p})),this.makeStatusError(f.status,S,J,f.headers)}return v(this).info(P),v(this).debug(`[${d}] response start`,le({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,durationMs:x-p})),{response:f,options:s,controller:b,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 Qt(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&&ds("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))}:{},...Cs(),"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:wr(e)}:c(this,Kr,"f").call(this,{body:e,headers:r})}};Gn=I,Kr=new WeakMap,Dn=new WeakSet,lo=function(){return this.baseURL!=="https://api.openai.com/v1"};I.OpenAI=Gn;I.DEFAULT_TIMEOUT=6e5;I.OpenAIError=y;I.APIError=$;I.APIConnectionError=me;I.APIConnectionTimeoutError=ge;I.APIUserAbortError=k;I.NotFoundError=ct;I.ConflictError=ut;I.RateLimitError=pt;I.BadRequestError=it;I.AuthenticationError=at;I.InternalServerError=dt;I.PermissionDeniedError=lt;I.UnprocessableEntityError=ft;I.InvalidWebhookSignatureError=Z;I.toFile=vr;I.Completions=Be;I.Chat=ye;I.Embeddings=He;I.Files=Je;I.Images=ze;I.Audio=se;I.Moderations=Qe;I.Models=Ye;I.FineTuning=Q;I.Graders=Re;I.VectorStores=de;I.Webhooks=Ze;I.Beta=ie;I.Batches=Fe;I.Uploads=Ee;I.Responses=Se;I.Evals=Pe;I.Containers=Ie;a();function Ei(n){return n.toLowerCase().includes("matilda3")}function vi(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 F=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};for(let[o,i]of Object.entries(r??{}))Qn(o)||(s[o]=i);return s}buildClient(){let{apiKey:e,baseUrl:t,timeout:r=6e5,maxRetries:s=3}=this.contentGeneratorConfig,o=this.buildHeaders(),i=yr("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=Ei(e.model)?s.messages.map(vi):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=os(e.model,"output"),s=ss(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 Ht=class extends F{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 Ti=he("MatildaOpenAICompatibleProvider"),ae=class n extends F{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=mr?.endsWith("/")?mr.slice(0,-1):mr,u=!!(l&&s.toLowerCase()===l.toLowerCase());return l&&!i&&!u&&Ti.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??{}))!es(o)&&o.toLowerCase()!=="x-stainless-retry-count"&&(s[o]=i);return qt(this.contentGeneratorConfig)&&Object.assign(s,Zn(this.cliConfig)),s}buildClient(){let{apiKey:e,baseUrl:t=Yn,timeout:r=6e5,maxRetries:s=3}=this.contentGeneratorConfig,o=this.buildHeaders(),i=yr("openai",this.cliConfig.getProxy()),l=i?.fetch??globalThis.fetch,u=qt(this.contentGeneratorConfig)?async(d,g)=>{let p=new Headers(d instanceof Request?d.headers:void 0);new Headers(g?.headers).forEach((C,P)=>{p.set(P,C)});let b=p.has(gr)||p.has(_r),f=br(),x=b||Object.keys(f).length>0;if(x){p.delete(gr),p.delete(_r);for(let[P,O]of Object.entries(f))p.set(P,O);let C=p.get("x-stainless-retry-count");p.has(gr)&&C!==null&&/^[1-9][0-9]*$/.test(C)&&p.set(_r,"retry")}this.cliConfig.getChannel()===void 0&&ts({authStage:"inference_started",authOutcome:"started"},{baseUrl:t,token:e}).catch(()=>{});try{let C=await l(d,x?{...g,headers:p}:g);return rs({baseUrl:this.contentGeneratorConfig.baseUrl,token:this.contentGeneratorConfig.apiKey}).catch(()=>{}),C}catch(C){throw Cr(C,{cliConfig:this.cliConfig,proxyConfigured:!!this.cliConfig.getProxy()}),C}}:void 0;return new I({apiKey:e,baseURL:t,timeout:r,maxRetries:s,defaultHeaders:o,...i||{},...u?{fetch:u}:{}})}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 zr(n){if(n.role!=="assistant")return n;let e=n;return typeof e.reasoning_content=="string"?n:{...e,reasoning_content:""}}function fr(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 ki(n){return fr(n)?!0:(n.model??"").toLowerCase().includes("deepseek")}var et=class extends F{constructor(e,t){super(e,t)}static isDeepSeekProvider=ki;static isDeepSeekHostname=fr;buildRequest(e,t){let r=super.buildRequest(e,t),s=fr(this.contentGeneratorConfig)?$i(r):r;if(!s.messages?.length)return s;let o=s.messages.map(i=>{let l=Mi(i);return zr(l)});return{...s,messages:o}}getDefaultGenerationConfig(){return{temperature:0}}};function Mi(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
|
|
28
|
-
`,Qr=class extends Error{constructor(e){super(e),this.name="StreamContentError"}},pr=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?
|
|
29
|
-
`):""}sanitizeMatildaUserContent(e){let r=e.replace(/<system-reminder>[\s\S]*?<\/system-reminder>\s*/g,"").trim();if(r.length<=
|
|
27
|
+
`);return{...n,content:t}}function $i(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 tt=class extends F{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 Ni=["api.minimaxi.com","api.minimax.io"],Li=[".minimaxi.com",".minimax.io"],rt=class extends F{static isMiniMaxProvider(e){if(!e.baseUrl)return!1;try{let t=new URL(e.baseUrl).hostname.toLowerCase();return Ni.includes(t)?!0:Li.some(r=>t.endsWith(r))}catch{return!1}}getResponseParsingOptions(){return{taggedThinkingTags:!0}}};a();var co="api.mistral.ai",Fi=["mistral","mixtral","codestral","ministral","pixtral","magistral","devstral"];function Ui(n){let e=n.baseUrl??"";if(!e)return!1;try{let t=new URL(e).hostname.toLowerCase();return t===co||t.endsWith(`.${co}`)}catch{return!1}}function Di(n){if(Ui(n))return!0;let e=n.model?.toLowerCase()??"";return Fi.some(t=>e.includes(t))}var nt=class extends F{static isMistralProvider=Di;buildRequest(e,t){let r=super.buildRequest(e,t);return{...r,messages:r.messages.map(Gi)}}};function Gi(n){if(!("reasoning_content"in n))return n;let e={...n};return delete e.reasoning_content,e}a();function ji(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 st=class extends F{constructor(e,t){super(e,t)}static isMiMoProvider=ji;buildRequest(e,t){let r=super.buildRequest(e,t);return r.messages?.length?{...r,messages:r.messages.map(zr)}:r}getRequestContextOverrides(){return{splitToolMedia:this.contentGeneratorConfig.splitToolMedia??!0}}};a();a();var Bi=he("STREAMING_TOOL_CALL_PARSER"),Yr=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 P=this.buffers.get(e),O=this.depths.get(e),w=this.toolCallMeta.get(e);if(P.trim()&&O===0&&w?.id&&w.id!==r)try{JSON.parse(P),o=this.findNextAvailableIndex()}catch{}}this.idToIndexMap.set(r,o)}else if(this.buffers.has(e)){let P=this.buffers.get(e);if(this.depths.get(e)>0||!P.trim())o=e;else try{JSON.parse(P),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),Bi.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),b=l+t;this.buffers.set(o,b);let f=u,x=g,C=p;for(let P of t)x||(P==="{"||P==="["?f++:(P==="}"||P==="]")&&f--),P==='"'&&!C&&(x=!x),C=P==="\\"&&!C;if(this.depths.set(o,f),this.inStrings.set(o,x),this.escapes.set(o,C),f===0&&b.trim().length>0)try{return{complete:!0,value:JSON.parse(b)}}catch(P){if(x)try{return{complete:!0,value:JSON.parse(b+'"'),repaired:!0}}catch{}return{complete:!1,error:P instanceof Error?P:new Error(String(P))}}return{complete:!1}}getToolCallMeta(e){return this.toolCallMeta.get(e)||{}}getCompletedToolCalls(){return this.collectCompletedToolCalls({allowJsonRepair:!0})}getStrictCompletedToolCalls(){return this.collectCompletedToolCalls({allowJsonRepair:!1})}collectCompletedToolCalls({allowJsonRepair:e}){let t=[],r=new Set;for(let[s,o]of this.buffers.entries()){let i=this.toolCallMeta.get(s);if(i?.name){let l=this.depths.get(s)||0,u=this.inStrings.get(s)||!1;if(l>0||u)continue;if(i.id){if(r.has(i.id))continue;r.add(i.id)}let d;if(!o.trim())d={};else try{d=JSON.parse(o)}catch{if(!e)continue;let g=Xn(o,null);if(!g||typeof g!="object")continue;d=g}t.push({id:i.id,name:i.name,args:d,index:s})}}return t}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,t]of this.buffers.entries()){let r=this.toolCallMeta.get(e),s=this.depths.get(e)||0,o=this.inStrings.get(e)||!1;if(s>0||o)return!0;if(!r?.name&&t.trim())try{JSON.parse(t)}catch{return!0}}return!1}};var uo=16e3,fo=`[Earlier content omitted to fit Matilda Core external API limits]
|
|
28
|
+
`,Qr=class extends Error{constructor(e){super(e),this.name="StreamContentError"}},pr=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?rn(o):void 0,l=this.reportedOperationHeaders();try{let u=await this.client.chat.completions.create(r,{signal:i?.signal,...l?{headers:l}:{}});return ve.convertOpenAIResponseToGemini(u,s)}finally{i?.abort()}})}async executeStream(e,t){return this.executeWithErrorHandling(e,t,!0,async(r,s)=>{let o=e.config?.abortSignal,i=o?rn(o):void 0,l=this.reportedOperationHeaders(),u;try{u=await this.client.chat.completions.create(r,{signal:i?.signal,...l?{headers:l}:{}})}catch(b){throw i?.abort(),b}if(!i)return this.processStreamWithLogging(u,s,e);let d=i,g=this.processStreamWithLogging(u,s,e);async function*p(){try{yield*g}finally{d.abort()}}return p()})}reportedOperationHeaders(){if(!qt(this.contentGeneratorConfig))return;let e=br();return Object.keys(e).length>0?e:void 0}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 Qr(g)}let u=ve.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)}if(!o&&!i){let l=ve.flushOpenAIStreamToGemini(t);l&&(yield l,i=!0)}o&&!i&&(yield o)}catch(l){if(l instanceof Qr)throw Te(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 Jn;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=ve.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 ve.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,b=(r.model??"").toLowerCase();if(ae.isMatildaCompatibleProvider(this.contentGeneratorConfig)&&(b.startsWith("matilda")||b==="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,fr(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,t=(this.contentGeneratorConfig.baseUrl??"").toLowerCase().replace(/\/+$/,"");if(e==="matilda-code"||t.endsWith("/api/v1/code"))return!1;if(e==="matilda-core")return!0;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<=uo)return r;let s=uo-fo.length;return`${fo}${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 Kn.getStore()?.(i),zn.recordOpenAIWireRequest(i),await s(i,o)}catch(i){return await this.handleError(i,o,e)}}async handleError(e,t,r){this.config.errorHandler.handle(Te(e),t,r)}createRequestContext(e,t){let r=e.model||this.contentGeneratorConfig.model,s=this.config.provider.getRequestContextOverrides?.()??{},o=t?new Yr:void 0,i=this.config.provider.getResponseParsingOptions?.(),l=t&&i?.taggedThinkingTags?new Vn: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 Wi=he("OPENAI_ERROR"),dr=class{constructor(e=()=>!1){this.shouldSuppressLogging=e}handle(e,t,r){let s=Te(e),o=this.isTimeoutError(s),i=this.buildErrorMessage(s,t,o);throw this.shouldSuppressErrorLogging(s,r)||Wi.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(`
|
|
33
|
-
`)}`}};var
|
|
33
|
+
`)}`}};var po=he("OPENAI"),ot=class{pipeline;constructor(e,t,r){let s={cliConfig:t,provider:r,contentGeneratorConfig:e,errorHandler:new dr((o,i)=>this.shouldSuppressErrorLogging(o,i))};this.pipeline=new pr(s)}shouldSuppressErrorLogging(e,t){return!!(qn(e)&&t.config?.abortSignal?.aborted)}async generateContent(e,t){return this.pipeline.execute(e,t)}async generateContentStream(e,t){return this.pipeline.executeStream(e,t)}async countTokens(e){try{return{totalTokens:(await new ls().calculateTokens(e)).totalTokens}}catch(t){po.warn("Failed to calculate tokens with new tokenizer, falling back to simple method:",t);let r=JSON.stringify(e.contents);return{totalTokens:Math.ceil(r.length/4)}}}async embedContent(e){let t="";Array.isArray(e.contents)?t=e.contents.map(r=>typeof r=="string"?r:"parts"in r&&r.parts?r.parts.map(s=>typeof s=="string"?s:"text"in s&&s.text||"").join(" "):"").join(" "):e.contents&&(typeof e.contents=="string"?t=e.contents:"parts"in e.contents&&e.contents.parts&&(t=e.contents.parts.map(r=>typeof r=="string"?r:"text"in r?r.text:"").join(" ")));try{return{embeddings:[{values:(await this.pipeline.client.embeddings.create({model:"text-embedding-ada-002",input:t})).data[0].embedding}]}}catch(r){let s=Te(r);throw po.error("OpenAI API Embedding Error:",s),new Error(`OpenAI API error: ${s instanceof Error?s.message:String(s)}`)}}useSummarizedThinking(){return!1}};a();var hr=class extends ot{contentGeneratorConfig;cliConfig;channel;constructor(e,t,r){super(e,t,r),this.contentGeneratorConfig=e,this.cliConfig=t,this.channel=t.getChannel?.()}shouldSuppressErrorLogging(e,t){return Zr(e)?!0:super.shouldSuppressErrorLogging(e,t)}async generateContent(e,t){return this.withTokenRefresh(()=>super.generateContent(e,t))}async generateContentStream(e,t){let r=()=>super.generateContentStream(e,t),s=await this.withTokenRefresh(r);return this.iterateWithAuthRetry(s,r)}async*iterateWithAuthRetry(e,t){let r=!1;try{for await(let s of e)r=!0,yield s;return}catch(s){if(!Zr(s))throw s;if(r)throw new tn("Matilda session expired while the response was streaming. Run /auth to reconnect.");await this.applyValidToken({forceRefresh:!0}),yield*await t()}}async embedContent(e){return this.withTokenRefresh(()=>super.embedContent(e))}async applyValidToken(e){let t;try{t=await as({baseUrl:this.contentGeneratorConfig.baseUrl,fallbackAccessToken:this.contentGeneratorConfig.apiKey,forceRefresh:e?.forceRefresh,channel:this.channel})}catch(r){throw Cr(r,{cliConfig:this.cliConfig,proxyConfigured:!!this.cliConfig.getProxy?.()}),r}t&&(this.contentGeneratorConfig.apiKey=t,this.pipeline.client.apiKey=t,process.env[is]=t)}async withTokenRefresh(e){await this.applyValidToken();try{return await e()}catch(t){if(!Zr(t))throw t;await this.applyValidToken({forceRefresh:!0});try{return await e()}catch(r){throw Zr(r)?new tn("Matilda session expired and could not be refreshed. Run /auth to reconnect."):r}}}};function Zr(n){if(!n)return!1;let e=n instanceof Error?n.message.toLowerCase():String(n).toLowerCase(),t=n,r=t?.status||t?.code||t?.statusCode;return r===401||r===403||r==="401"||r==="403"||e.includes("unauthorized")||e.includes("forbidden")||e.includes("invalid api key")||e.includes("invalid access token")||e.includes("token expired")||e.includes("authentication")||e.includes("access denied")||e.includes("token")&&e.includes("expired")}function m_(n,e){let t=Hi(n,e);return ae.isMatildaCompatibleProvider(n)?new hr(n,e,t):new ot(n,e,t)}function Hi(n,e){let t=n||e.getContentGeneratorConfig();return ae.isMatildaCompatibleProvider(t)?new ae(n,e):et.isDeepSeekProvider(t)?new et(n,e):st.isMiMoProvider(t)?new st(n,e):tt.isOpenRouterProvider(t)?new tt(n,e):Ht.isModelScopeProvider(t)?new Ht(n,e):rt.isMiniMaxProvider(t)?new rt(n,e):nt.isMistralProvider(t)?new nt(n,e):new F(n,e)}export{ae as a,et as b,tt as c,rt as d,nt as e,st as f,pr as g,dr as h,ot as i,hr as j,m_ as k,Hi as l};
|
|
34
34
|
/**
|
|
35
35
|
* @license
|
|
36
36
|
* Copyright 2025 Matilda
|