@fmdzc/cli-ai 3.1.1 → 3.1.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/dist/anthropic-TJJHMK4P.js +47 -0
- package/dist/chunk-BAM5DR4L.js +2 -0
- package/dist/chunk-DYGVT5PG.js +27 -0
- package/dist/chunk-KWCGINWB.js +2 -0
- package/dist/chunk-QPVTJWSV.js +2 -0
- package/dist/cli.js +54 -0
- package/dist/clipboardy-2ZYXPDO4.js +7 -0
- package/dist/devtools-32J76P22.js +8 -0
- package/dist/execa-HQCA4V7K.js +44 -0
- package/dist/index.js +76 -75
- package/dist/openai-IPOZE2MF.js +30 -0
- package/dist/openrouter-2JMS534N.js +42 -0
- package/package.json +2 -3
- package/dist/index.d.ts +0 -2
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);
|
|
2
|
+
import{a as qr,b as Wr,c as $s,d as ks,e as Ts}from"./chunk-DYGVT5PG.js";import{m as fr,n as Wt}from"./chunk-BAM5DR4L.js";import"./chunk-QPVTJWSV.js";function g(s,e,t,r,n){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?n.call(s,t):n?n.value=t:e.set(s,t),t}function a(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)}var Hr=function(){let{crypto:s}=globalThis;if(s?.randomUUID)return Hr=s.randomUUID.bind(s),s.randomUUID();let e=new Uint8Array(1),t=s?()=>s.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^t()&15>>+r/4).toString(16))};function Ht(s){return typeof s=="object"&&s!==null&&("name"in s&&s.name==="AbortError"||"message"in s&&String(s.message).includes("FetchRequestCanceledException"))}var Jt=s=>{if(s instanceof Error)return s;if(typeof s=="object"&&s!==null){try{if(Object.prototype.toString.call(s)==="[object Error]"){let e=new Error(s.message,s.cause?{cause:s.cause}:{});return s.stack&&(e.stack=s.stack),s.cause&&!e.cause&&(e.cause=s.cause),s.name&&(e.name=s.name),e}}catch{}try{return new Error(JSON.stringify(s))}catch{}}return new Error(s)};var _=class extends Error{},T=class s extends _{constructor(e,t,r,n){super(`${s.makeMessage(e,t,r)}`),this.status=e,this.headers=n,this.requestID=n?.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 n=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,r,n){if(!e||!n)return new pe({message:r,cause:Jt(t)});let o=t?.error;return e===400?new Ze(e,o,r,n):e===401?new et(e,o,r,n):e===403?new tt(e,o,r,n):e===404?new rt(e,o,r,n):e===409?new st(e,o,r,n):e===422?new nt(e,o,r,n):e===429?new ot(e,o,r,n):e>=500?new it(e,o,r,n):new s(e,o,r,n)}},$=class extends T{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},pe=class extends T{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},me=class extends pe{constructor({message:e}={}){super({message:e??"Request timed out."})}},Ze=class extends T{},et=class extends T{},tt=class extends T{},rt=class extends T{},st=class extends T{},nt=class extends T{},ot=class extends T{},it=class extends T{},at=class extends _{constructor(){super("Could not parse response content as the length limit was reached")}},lt=class extends _{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},Y=class extends Error{constructor(e){super(e)}};var jn=/^[a-z][a-z0-9+.-]*:/i,Fs=s=>jn.test(s),D=s=>(D=Array.isArray,D(s)),Jr=D;function Xr(s){return typeof s!="object"?{}:s??{}}function Ns(s){if(!s)return!0;for(let e in s)return!1;return!0}function Ms(s,e){return Object.prototype.hasOwnProperty.call(s,e)}function Xt(s){return s!=null&&typeof s=="object"&&!Array.isArray(s)}var Ls=(s,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new _(`${s} must be an integer`);if(e<0)throw new _(`${s} must be a positive integer`);return e};var Bs=s=>{try{return JSON.parse(s)}catch{return}};var Z=s=>new Promise(e=>setTimeout(e,s));var _e="6.16.0";var qs=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Dn(){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 qn=()=>{let s=Dn();if(s==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":js(Deno.build.os),"X-Stainless-Arch":Us(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(s==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_e,"X-Stainless-OS":js(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Us(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Wn();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 Wn(){if(typeof navigator>"u"||!navigator)return null;let s=[{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 s){let r=t.exec(navigator.userAgent);if(r){let n=r[1]||0,o=r[2]||0,i=r[3]||0;return{browser:e,version:`${n}.${o}.${i}`}}}return null}var Us=s=>s==="x32"?"x32":s==="x86_64"||s==="x64"?"x64":s==="arm"?"arm":s==="aarch64"||s==="arm64"?"arm64":s?`other:${s}`:"unknown",js=s=>(s=s.toLowerCase(),s.includes("ios")?"iOS":s==="android"?"Android":s==="darwin"?"MacOS":s==="win32"?"Windows":s==="freebsd"?"FreeBSD":s==="openbsd"?"OpenBSD":s==="linux"?"Linux":s?`Other:${s}`:"Unknown"),Ds,Ws=()=>Ds??(Ds=qn());function Hs(){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 Kr(...s){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(...s)}function hr(s){let e=Symbol.asyncIterator in s?s[Symbol.asyncIterator]():s[Symbol.iterator]();return Kr({start(){},async pull(t){let{done:r,value:n}=await e.next();r?t.close():t.enqueue(n)},async cancel(){await e.return?.()}})}function Vr(s){if(s[Symbol.asyncIterator])return s;let e=s.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 Js(s){if(s===null||typeof s!="object")return;if(s[Symbol.asyncIterator]){await s[Symbol.asyncIterator]().return?.();return}let e=s.getReader(),t=e.cancel();e.releaseLock(),await t}var Xs=({headers:s,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var dr="RFC3986",Gr=s=>String(s),pr={RFC1738:s=>String(s).replace(/%20/g,"+"),RFC3986:Gr},zr="RFC1738";var mr=(s,e)=>(mr=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),mr(s,e)),ee=(()=>{let s=[];for(let e=0;e<256;++e)s.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return s})();var Qr=1024,Ks=(s,e,t,r,n)=>{if(s.length===0)return s;let o=s;if(typeof s=="symbol"?o=Symbol.prototype.toString.call(s):typeof s!="string"&&(o=String(s)),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+=Qr){let h=o.length>=Qr?o.slice(l,l+Qr):o,m=[];for(let b=0;b<h.length;++b){let d=h.charCodeAt(b);if(d===45||d===46||d===95||d===126||d>=48&&d<=57||d>=65&&d<=90||d>=97&&d<=122||n===zr&&(d===40||d===41)){m[m.length]=h.charAt(b);continue}if(d<128){m[m.length]=ee[d];continue}if(d<2048){m[m.length]=ee[192|d>>6]+ee[128|d&63];continue}if(d<55296||d>=57344){m[m.length]=ee[224|d>>12]+ee[128|d>>6&63]+ee[128|d&63];continue}b+=1,d=65536+((d&1023)<<10|h.charCodeAt(b)&1023),m[m.length]=ee[240|d>>18]+ee[128|d>>12&63]+ee[128|d>>6&63]+ee[128|d&63]}i+=m.join("")}return i};function Vs(s){return!s||typeof s!="object"?!1:!!(s.constructor&&s.constructor.isBuffer&&s.constructor.isBuffer(s))}function Yr(s,e){if(D(s)){let t=[];for(let r=0;r<s.length;r+=1)t.push(e(s[r]));return t}return e(s)}var zs={brackets(s){return String(s)+"[]"},comma:"comma",indices(s,e){return String(s)+"["+e+"]"},repeat(s){return String(s)}},Qs=function(s,e){Array.prototype.push.apply(s,D(e)?e:[e])},Gs,F={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Ks,encodeValuesOnly:!1,format:dr,formatter:Gr,indices:!1,serializeDate(s){return(Gs??(Gs=Function.prototype.call.bind(Date.prototype.toISOString)))(s)},skipNulls:!1,strictNullHandling:!1};function Xn(s){return typeof s=="string"||typeof s=="number"||typeof s=="boolean"||typeof s=="symbol"||typeof s=="bigint"}var Zr={};function Ys(s,e,t,r,n,o,i,l,h,m,b,d,w,f,P,x,O,R){let y=s,M=R,S=0,H=!1;for(;(M=M.get(Zr))!==void 0&&!H;){let v=M.get(s);if(S+=1,typeof v<"u"){if(v===S)throw new RangeError("Cyclic object value");H=!0}typeof M.get(Zr)>"u"&&(S=0)}if(typeof m=="function"?y=m(e,y):y instanceof Date?y=w?.(y):t==="comma"&&D(y)&&(y=Yr(y,function(v){return v instanceof Date?w?.(v):v})),y===null){if(o)return h&&!x?h(e,F.encoder,O,"key",f):e;y=""}if(Xn(y)||Vs(y)){if(h){let v=x?e:h(e,F.encoder,O,"key",f);return[P?.(v)+"="+P?.(h(y,F.encoder,O,"value",f))]}return[P?.(e)+"="+P?.(String(y))]}let q=[];if(typeof y>"u")return q;let C;if(t==="comma"&&D(y))x&&h&&(y=Yr(y,h)),C=[{value:y.length>0?y.join(",")||null:void 0}];else if(D(m))C=m;else{let v=Object.keys(y);C=b?v.sort(b):v}let L=l?String(e).replace(/\./g,"%2E"):String(e),B=r&&D(y)&&y.length===1?L+"[]":L;if(n&&D(y)&&y.length===0)return B+"[]";for(let v=0;v<C.length;++v){let k=C[v],Os=typeof k=="object"&&typeof k.value<"u"?k.value:y[k];if(i&&Os===null)continue;let Dr=d&&l?k.replace(/\./g,"%2E"):k,Bn=D(y)?typeof t=="function"?t(B,Dr):B:B+(d?"."+Dr:"["+Dr+"]");R.set(s,S);let vs=new WeakMap;vs.set(Zr,R),Qs(q,Ys(Os,Bn,t,r,n,o,i,l,t==="comma"&&x&&D(y)?null:h,m,b,d,w,f,P,x,O,vs))}return q}function Kn(s=F){if(typeof s.allowEmptyArrays<"u"&&typeof s.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof s.encodeDotInKeys<"u"&&typeof s.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(s.encoder!==null&&typeof s.encoder<"u"&&typeof s.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=s.charset||F.charset;if(typeof s.charset<"u"&&s.charset!=="utf-8"&&s.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=dr;if(typeof s.format<"u"){if(!mr(pr,s.format))throw new TypeError("Unknown format option provided.");t=s.format}let r=pr[t],n=F.filter;(typeof s.filter=="function"||D(s.filter))&&(n=s.filter);let o;if(s.arrayFormat&&s.arrayFormat in zs?o=s.arrayFormat:"indices"in s?o=s.indices?"indices":"repeat":o=F.arrayFormat,"commaRoundTrip"in s&&typeof s.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let i=typeof s.allowDots>"u"?s.encodeDotInKeys?!0:F.allowDots:!!s.allowDots;return{addQueryPrefix:typeof s.addQueryPrefix=="boolean"?s.addQueryPrefix:F.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof s.allowEmptyArrays=="boolean"?!!s.allowEmptyArrays:F.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof s.charsetSentinel=="boolean"?s.charsetSentinel:F.charsetSentinel,commaRoundTrip:!!s.commaRoundTrip,delimiter:typeof s.delimiter>"u"?F.delimiter:s.delimiter,encode:typeof s.encode=="boolean"?s.encode:F.encode,encodeDotInKeys:typeof s.encodeDotInKeys=="boolean"?s.encodeDotInKeys:F.encodeDotInKeys,encoder:typeof s.encoder=="function"?s.encoder:F.encoder,encodeValuesOnly:typeof s.encodeValuesOnly=="boolean"?s.encodeValuesOnly:F.encodeValuesOnly,filter:n,format:t,formatter:r,serializeDate:typeof s.serializeDate=="function"?s.serializeDate:F.serializeDate,skipNulls:typeof s.skipNulls=="boolean"?s.skipNulls:F.skipNulls,sort:typeof s.sort=="function"?s.sort:null,strictNullHandling:typeof s.strictNullHandling=="boolean"?s.strictNullHandling:F.strictNullHandling}}function es(s,e={}){let t=s,r=Kn(e),n,o;typeof r.filter=="function"?(o=r.filter,t=o("",t)):D(r.filter)&&(o=r.filter,n=o);let i=[];if(typeof t!="object"||t===null)return"";let l=zs[r.arrayFormat],h=l==="comma"&&r.commaRoundTrip;n||(n=Object.keys(t)),r.sort&&n.sort(r.sort);let m=new WeakMap;for(let w=0;w<n.length;++w){let f=n[w];r.skipNulls&&t[f]===null||Qs(i,Ys(t[f],f,l,h,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,m))}let b=i.join(r.delimiter),d=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),b.length>0?d+b:""}function tn(s){let e=0;for(let n of s)e+=n.length;let t=new Uint8Array(e),r=0;for(let n of s)t.set(n,r),r+=n.length;return t}var Zs;function ct(s){let e;return(Zs??(e=new globalThis.TextEncoder,Zs=e.encode.bind(e)))(s)}var en;function ts(s){let e;return(en??(e=new globalThis.TextDecoder,en=e.decode.bind(e)))(s)}var J,X,ve=class{constructor(){J.set(this,void 0),X.set(this,void 0),g(this,J,new Uint8Array,"f"),g(this,X,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?ct(e):e;g(this,J,tn([a(this,J,"f"),t]),"f");let r=[],n;for(;(n=Gn(a(this,J,"f"),a(this,X,"f")))!=null;){if(n.carriage&&a(this,X,"f")==null){g(this,X,n.index,"f");continue}if(a(this,X,"f")!=null&&(n.index!==a(this,X,"f")+1||n.carriage)){r.push(ts(a(this,J,"f").subarray(0,a(this,X,"f")-1))),g(this,J,a(this,J,"f").subarray(a(this,X,"f")),"f"),g(this,X,null,"f");continue}let o=a(this,X,"f")!==null?n.preceding-1:n.preceding,i=ts(a(this,J,"f").subarray(0,o));r.push(i),g(this,J,a(this,J,"f").subarray(n.index),"f"),g(this,X,null,"f")}return r}flush(){return a(this,J,"f").length?this.decode(`
|
|
3
|
+
`):[]}};J=new WeakMap,X=new WeakMap;ve.NEWLINE_CHARS=new Set([`
|
|
4
|
+
`,"\r"]);ve.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Gn(s,e){for(let n=e??0;n<s.length;n++){if(s[n]===10)return{preceding:n,index:n+1,carriage:!1};if(s[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function rn(s){for(let r=0;r<s.length-1;r++){if(s[r]===10&&s[r+1]===10||s[r]===13&&s[r+1]===13)return r+2;if(s[r]===13&&s[r+1]===10&&r+3<s.length&&s[r+2]===13&&s[r+3]===10)return r+4}return-1}var gr={off:0,error:200,warn:300,info:400,debug:500},rs=(s,e,t)=>{if(s){if(Ms(gr,s))return s;E(t).warn(`${e} was set to ${JSON.stringify(s)}, expected one of ${JSON.stringify(Object.keys(gr))}`)}};function Kt(){}function _r(s,e,t){return!e||gr[s]>gr[t]?Kt:e[s].bind(e)}var zn={error:Kt,warn:Kt,info:Kt,debug:Kt},sn=new WeakMap;function E(s){let e=s.logger,t=s.logLevel??"off";if(!e)return zn;let r=sn.get(e);if(r&&r[0]===t)return r[1];let n={error:_r("error",e,t),warn:_r("warn",e,t),info:_r("info",e,t),debug:_r("debug",e,t)};return sn.set(e,[t,n]),n}var oe=s=>(s.options&&(s.options={...s.options},delete s.options.headers),s.headers&&(s.headers=Object.fromEntries((s.headers instanceof Headers?[...s.headers]:Object.entries(s.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in s&&(s.retryOfRequestLogID&&(s.retryOf=s.retryOfRequestLogID),delete s.retryOfRequestLogID),s);var Vt,te=class s{constructor(e,t,r){this.iterator=e,Vt.set(this,void 0),this.controller=t,g(this,Vt,r,"f")}static fromSSEResponse(e,t,r){let n=!1,o=r?E(r):console;async function*i(){if(n)throw new _("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let l=!1;try{for await(let h of Qn(e,t))if(!l){if(h.data.startsWith("[DONE]")){l=!0;continue}if(h.event===null||!h.event.startsWith("thread.")){let m;try{m=JSON.parse(h.data)}catch(b){throw o.error("Could not parse message into JSON:",h.data),o.error("From chunk:",h.raw),b}if(m&&m.error)throw new T(void 0,m.error,void 0,e.headers);yield m}else{let m;try{m=JSON.parse(h.data)}catch(b){throw console.error("Could not parse message into JSON:",h.data),console.error("From chunk:",h.raw),b}if(h.event=="error")throw new T(void 0,m.error,m.message,void 0);yield{event:h.event,data:m}}}l=!0}catch(h){if(Ht(h))return;throw h}finally{l||t.abort()}}return new s(i,t,r)}static fromReadableStream(e,t,r){let n=!1;async function*o(){let l=new ve,h=Vr(e);for await(let m of h)for(let b of l.decode(m))yield b;for(let m of l.flush())yield m}async function*i(){if(n)throw new _("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let l=!1;try{for await(let h of o())l||h&&(yield JSON.parse(h));l=!0}catch(h){if(Ht(h))return;throw h}finally{l||t.abort()}}return new s(i,t,r)}[(Vt=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),n=o=>({next:()=>{if(o.length===0){let i=r.next();e.push(i),t.push(i)}return o.shift()}});return[new s(()=>n(e),this.controller,a(this,Vt,"f")),new s(()=>n(t),this.controller,a(this,Vt,"f"))]}toReadableStream(){let e=this,t;return Kr({async start(){t=e[Symbol.asyncIterator]()},async pull(r){try{let{value:n,done:o}=await t.next();if(o)return r.close();let i=ct(JSON.stringify(n)+`
|
|
5
|
+
`);r.enqueue(i)}catch(n){r.error(n)}},async cancel(){await t.return?.()}})}};async function*Qn(s,e){if(!s.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new _("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 _("Attempted to iterate over a response with no body");let t=new ss,r=new ve,n=Vr(s.body);for await(let o of Yn(n))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*Yn(s){let e=new Uint8Array;for await(let t of s){if(t==null)continue;let r=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?ct(t):t,n=new Uint8Array(e.length+r.length);n.set(e),n.set(r,e.length),e=n;let o;for(;(o=rn(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var ss=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(`
|
|
6
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,n]=Zn(e,":");return n.startsWith(" ")&&(n=n.substring(1)),t==="event"?this.event=n:t==="data"&&this.data.push(n),null}};function Zn(s,e){let t=s.indexOf(e);return t!==-1?[s.substring(0,t),e,s.substring(t+e.length)]:[s,"",""]}async function yr(s,e){let{response:t,requestLogID:r,retryOfRequestLogID:n,startTime:o}=e,i=await(async()=>{if(e.options.stream)return E(s).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,s):te.fromSSEResponse(t,e.controller,s);if(t.status===204)return null;if(e.options.__binaryResponse)return t;let h=t.headers.get("content-type")?.split(";")[0]?.trim();if(h?.includes("application/json")||h?.endsWith("+json")){let d=await t.json();return ns(d,t)}return await t.text()})();return E(s).debug(`[${r}] response parsed`,oe({retryOfRequestLogID:n,url:t.url,status:t.status,body:i,durationMs:Date.now()-o})),i}function ns(s,e){return!s||typeof s!="object"||Array.isArray(s)?s:Object.defineProperty(s,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var Gt,$e=class s extends Promise{constructor(e,t,r=yr){super(n=>{n(null)}),this.responsePromise=t,this.parseResponse=r,Gt.set(this,void 0),g(this,Gt,e,"f")}_thenUnwrap(e){return new s(a(this,Gt,"f"),this.responsePromise,async(t,r)=>ns(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(a(this,Gt,"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)}};Gt=new WeakMap;var br,zt=class{constructor(e,t,r,n){br.set(this,void 0),g(this,br,e,"f"),this.options=n,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 _("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await a(this,br,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(br=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},Qt=class extends $e{constructor(e,t,r){super(e,t,async(n,o)=>new r(n,o.response,await yr(n,o),o.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},re=class extends zt{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},I=class extends zt{constructor(e,t,r,n){super(e,t,r,n),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:{...Xr(this.options.query),after:t}}:null}},ie=class extends zt{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.has_more||!1,this.last_id=r.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...Xr(this.options.query),after:e}}:null}};var as=()=>{if(typeof File>"u"){let{process:s}=globalThis,e=typeof s?.versions?.node=="string"&&parseInt(s.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 ut(s,e,t){return as(),new File(s,e??"unknown_file",t)}function Yt(s){return(typeof s=="object"&&s!==null&&("name"in s&&s.name&&String(s.name)||"url"in s&&s.url&&String(s.url)||"filename"in s&&s.filename&&String(s.filename)||"path"in s&&s.path&&String(s.path))||"").split(/[\\/]/).pop()||void 0}var wr=s=>s!=null&&typeof s=="object"&&typeof s[Symbol.asyncIterator]=="function",ls=async(s,e)=>os(s.body)?{...s,body:await on(s.body,e)}:s,K=async(s,e)=>({...s,body:await on(s.body,e)}),nn=new WeakMap;function to(s){let e=typeof s=="function"?s:s.fetch,t=nn.get(e);if(t)return t;let r=(async()=>{try{let n="Response"in e?e.Response:(await e("data:,")).constructor,o=new FormData;return o.toString()!==await new n(o).text()}catch{return!0}})();return nn.set(e,r),r}var on=async(s,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(s||{}).map(([r,n])=>is(t,r,n))),t},an=s=>s instanceof Blob&&"name"in s,ro=s=>typeof s=="object"&&s!==null&&(s instanceof Response||wr(s)||an(s)),os=s=>{if(ro(s))return!0;if(Array.isArray(s))return s.some(os);if(s&&typeof s=="object"){for(let e in s)if(os(s[e]))return!0}return!1},is=async(s,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")s.append(e,String(t));else if(t instanceof Response)s.append(e,ut([await t.blob()],Yt(t)));else if(wr(t))s.append(e,ut([await new Response(hr(t)).blob()],Yt(t)));else if(an(t))s.append(e,t,Yt(t));else if(Array.isArray(t))await Promise.all(t.map(r=>is(s,e+"[]",r)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([r,n])=>is(s,`${e}[${r}]`,n)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}};var ln=s=>s!=null&&typeof s=="object"&&typeof s.size=="number"&&typeof s.type=="string"&&typeof s.text=="function"&&typeof s.slice=="function"&&typeof s.arrayBuffer=="function",so=s=>s!=null&&typeof s=="object"&&typeof s.name=="string"&&typeof s.lastModified=="number"&&ln(s),no=s=>s!=null&&typeof s=="object"&&typeof s.url=="string"&&typeof s.blob=="function";async function xr(s,e,t){if(as(),s=await s,so(s))return s instanceof File?s:ut([await s.arrayBuffer()],s.name);if(no(s)){let n=await s.blob();return e||(e=new URL(s.url).pathname.split(/[\\/]/).pop()),ut(await cs(n),e,t)}let r=await cs(s);if(e||(e=Yt(s)),!t?.type){let n=r.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof n=="string"&&(t={...t,type:n})}return ut(r,e,t)}async function cs(s){let e=[];if(typeof s=="string"||ArrayBuffer.isView(s)||s instanceof ArrayBuffer)e.push(s);else if(ln(s))e.push(s instanceof Blob?s:await s.arrayBuffer());else if(wr(s))for await(let t of s)e.push(...await cs(t));else{let t=s?.constructor?.name;throw new Error(`Unexpected data type: ${typeof s}${t?`; constructor: ${t}`:""}${oo(s)}`)}return e}function oo(s){return typeof s!="object"||s===null?"":`; props: [${Object.getOwnPropertyNames(s).map(t=>`"${t}"`).join(", ")}]`}var u=class{constructor(e){this._client=e}};function un(s){return s.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var cn=Object.freeze(Object.create(null)),ao=(s=un)=>function(t,...r){if(t.length===1)return t[0];let n=!1,o=[],i=t.reduce((b,d,w)=>{/[?#]/.test(d)&&(n=!0);let f=r[w],P=(n?encodeURIComponent:s)(""+f);return w!==r.length&&(f==null||typeof f=="object"&&f.toString===Object.getPrototypeOf(Object.getPrototypeOf(f.hasOwnProperty??cn)??cn)?.toString)&&(P=f+"",o.push({start:b.length+d.length,length:P.length,error:`Value of type ${Object.prototype.toString.call(f).slice(8,-1)} is not a valid path parameter`})),b+d+(w===r.length?"":P)},""),l=i.split(/[?#]/,1)[0],h=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,m;for(;(m=h.exec(l))!==null;)o.push({start:m.index,length:m[0].length,error:`Value "${m[0]}" can't be safely passed as a path parameter`});if(o.sort((b,d)=>b.start-d.start),o.length>0){let b=0,d=o.reduce((w,f)=>{let P=" ".repeat(f.start-b),x="^".repeat(f.length);return b=f.start+f.length,w+P+x},"");throw new _(`Path parameters result in path with invalid segments:
|
|
7
|
+
${o.map(w=>w.error).join(`
|
|
8
|
+
`)}
|
|
9
|
+
${i}
|
|
10
|
+
${d}`)}return i},c=ao(un);var ke=class extends u{list(e,t={},r){return this._client.getAPIList(c`/chat/completions/${e}/messages`,I,{query:t,...r})}};function Zt(s){return s!==void 0&&"function"in s&&s.function!==void 0}function er(s){return s?.$brand==="auto-parseable-response-format"}function Te(s){return s?.$brand==="auto-parseable-tool"}function fn(s,e){return!e||!us(e)?{...s,choices:s.choices.map(t=>(dn(t.message.tool_calls),{...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:tr(s,e)}function tr(s,e){let t=s.choices.map(r=>{if(r.finish_reason==="length")throw new at;if(r.finish_reason==="content_filter")throw new lt;return dn(r.message.tool_calls),{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:r.message.tool_calls?.map(n=>fo(e,n))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?uo(e,r.message.content):null}}});return{...s,choices:t}}function uo(s,e){return s.response_format?.type!=="json_schema"?null:s.response_format?.type==="json_schema"?"$parseRaw"in s.response_format?s.response_format.$parseRaw(e):JSON.parse(e):null}function fo(s,e){let t=s.tools?.find(r=>Zt(r)&&r.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:Te(t)?t.$parseRaw(e.function.arguments):t?.function.strict?JSON.parse(e.function.arguments):null}}}function hn(s,e){if(!s||!("tools"in s)||!s.tools)return!1;let t=s.tools?.find(r=>Zt(r)&&r.function?.name===e.function.name);return Zt(t)&&(Te(t)||t?.function.strict||!1)}function us(s){return er(s.response_format)?!0:s.tools?.some(e=>Te(e)||e.type==="function"&&e.function.strict===!0)??!1}function dn(s){for(let e of s||[])if(e.type!=="function")throw new _(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function pn(s){for(let e of s??[]){if(e.type!=="function")throw new _(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new _(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var ft=s=>s?.role==="assistant",fs=s=>s?.role==="tool";var hs,Ar,Ir,rr,sr,Pr,nr,ae,or,Rr,Sr,ht,mn,ge=class{constructor(){hs.add(this),this.controller=new AbortController,Ar.set(this,void 0),Ir.set(this,()=>{}),rr.set(this,()=>{}),sr.set(this,void 0),Pr.set(this,()=>{}),nr.set(this,()=>{}),ae.set(this,{}),or.set(this,!1),Rr.set(this,!1),Sr.set(this,!1),ht.set(this,!1),g(this,Ar,new Promise((e,t)=>{g(this,Ir,e,"f"),g(this,rr,t,"f")}),"f"),g(this,sr,new Promise((e,t)=>{g(this,Pr,e,"f"),g(this,nr,t,"f")}),"f"),a(this,Ar,"f").catch(()=>{}),a(this,sr,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},a(this,hs,"m",mn).bind(this))},0)}_connected(){this.ended||(a(this,Ir,"f").call(this),this._emit("connect"))}get ended(){return a(this,or,"f")}get errored(){return a(this,Rr,"f")}get aborted(){return a(this,Sr,"f")}abort(){this.controller.abort()}on(e,t){return(a(this,ae,"f")[e]||(a(this,ae,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=a(this,ae,"f")[e];if(!r)return this;let n=r.findIndex(o=>o.listener===t);return n>=0&&r.splice(n,1),this}once(e,t){return(a(this,ae,"f")[e]||(a(this,ae,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{g(this,ht,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,t)})}async done(){g(this,ht,!0,"f"),await a(this,sr,"f")}_emit(e,...t){if(a(this,or,"f"))return;e==="end"&&(g(this,or,!0,"f"),a(this,Pr,"f").call(this));let r=a(this,ae,"f")[e];if(r&&(a(this,ae,"f")[e]=r.filter(n=>!n.once),r.forEach(({listener:n})=>n(...t))),e==="abort"){let n=t[0];!a(this,ht,"f")&&!r?.length&&Promise.reject(n),a(this,rr,"f").call(this,n),a(this,nr,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=t[0];!a(this,ht,"f")&&!r?.length&&Promise.reject(n),a(this,rr,"f").call(this,n),a(this,nr,"f").call(this,n),this._emit("end")}}_emitFinal(){}};Ar=new WeakMap,Ir=new WeakMap,rr=new WeakMap,sr=new WeakMap,Pr=new WeakMap,nr=new WeakMap,ae=new WeakMap,or=new WeakMap,Rr=new WeakMap,Sr=new WeakMap,ht=new WeakMap,hs=new WeakSet,mn=function(e){if(g(this,Rr,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new $),e instanceof $)return g(this,Sr,!0,"f"),this._emit("abort",e);if(e instanceof _)return this._emit("error",e);if(e instanceof Error){let t=new _(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new _(String(e)))};function _n(s){return typeof s.parse=="function"}var W,ds,Cr,ps,ms,_s,gn,yn,ho=10,dt=class extends ge{constructor(){super(...arguments),W.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),fs(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(ft(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 _("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),a(this,W,"m",ds).call(this)}async finalMessage(){return await this.done(),a(this,W,"m",Cr).call(this)}async finalFunctionToolCall(){return await this.done(),a(this,W,"m",ps).call(this)}async finalFunctionToolCallResult(){return await this.done(),a(this,W,"m",ms).call(this)}async totalUsage(){return await this.done(),a(this,W,"m",_s).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let t=a(this,W,"m",Cr).call(this);t&&this._emit("finalMessage",t);let r=a(this,W,"m",ds).call(this);r&&this._emit("finalContent",r);let n=a(this,W,"m",ps).call(this);n&&this._emit("finalFunctionToolCall",n);let o=a(this,W,"m",ms).call(this);o!=null&&this._emit("finalFunctionToolCallResult",o),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",a(this,W,"m",_s).call(this))}async _createChatCompletion(e,t,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),a(this,W,"m",gn).call(this,t);let o=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(tr(o,t))}async _runChatCompletion(e,t,r){for(let n of t.messages)this._addMessage(n,!1);return await this._createChatCompletion(e,t,r)}async _runTools(e,t,r){let n="tool",{tool_choice:o="auto",stream:i,...l}=t,h=typeof o!="string"&&o.type==="function"&&o?.function?.name,{maxChatCompletions:m=ho}=r||{},b=t.tools.map(f=>{if(Te(f)){if(!f.$callback)throw new _("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}),d={};for(let f of b)f.type==="function"&&(d[f.function.name||f.function.function.name]=f.function);let w="tools"in t?b.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<m;++f){let x=(await this._createChatCompletion(e,{...l,tool_choice:o,tools:w,messages:[...this.messages]},r)).choices[0]?.message;if(!x)throw new _("missing message in ChatCompletion response");if(!x.tool_calls?.length)return;for(let O of x.tool_calls){if(O.type!=="function")continue;let R=O.id,{name:y,arguments:M}=O.function,S=d[y];if(S){if(h&&h!==y){let L=`Invalid tool_call: ${JSON.stringify(y)}. ${JSON.stringify(h)} requested. Please try again`;this._addMessage({role:n,tool_call_id:R,content:L});continue}}else{let L=`Invalid tool_call: ${JSON.stringify(y)}. Available options are: ${Object.keys(d).map(B=>JSON.stringify(B)).join(", ")}. Please try again`;this._addMessage({role:n,tool_call_id:R,content:L});continue}let H;try{H=_n(S)?await S.parse(M):M}catch(L){let B=L instanceof Error?L.message:String(L);this._addMessage({role:n,tool_call_id:R,content:B});continue}let q=await S.function(H,this),C=a(this,W,"m",yn).call(this,q);if(this._addMessage({role:n,tool_call_id:R,content:C}),h)return}}}};W=new WeakSet,ds=function(){return a(this,W,"m",Cr).call(this).content??null},Cr=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(ft(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new _("stream ended without producing a ChatCompletionMessage with role=assistant")},ps=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(ft(t)&&t?.tool_calls?.length)return t.tool_calls.filter(r=>r.type==="function").at(-1)?.function}},ms=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(fs(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(r=>r.role==="assistant"&&r.tool_calls?.some(n=>n.type==="function"&&n.id===t.tool_call_id)))return t.content}},_s=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},gn=function(e){if(e.n!=null&&e.n>1)throw new _("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},yn=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var ir=class s extends dt{static runTools(e,t,r){let n=new s,o={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,t,o)),n}_addMessage(e,t=!0){super._addMessage(e,t),ft(e)&&e.content&&this._emit("content",e.content)}};var U={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},gs=class extends Error{},ys=class extends Error{};function po(s,e=U.ALL){if(typeof s!="string")throw new TypeError(`expecting str, got ${typeof s}`);if(!s.trim())throw new Error(`${s} is empty`);return mo(s.trim(),e)}var mo=(s,e)=>{let t=s.length,r=0,n=w=>{throw new gs(`${w} at position ${r}`)},o=w=>{throw new ys(`${w} at position ${r}`)},i=()=>(d(),r>=t&&n("Unexpected end of input"),s[r]==='"'?l():s[r]==="{"?h():s[r]==="["?m():s.substring(r,r+4)==="null"||U.NULL&e&&t-r<4&&"null".startsWith(s.substring(r))?(r+=4,null):s.substring(r,r+4)==="true"||U.BOOL&e&&t-r<4&&"true".startsWith(s.substring(r))?(r+=4,!0):s.substring(r,r+5)==="false"||U.BOOL&e&&t-r<5&&"false".startsWith(s.substring(r))?(r+=5,!1):s.substring(r,r+8)==="Infinity"||U.INFINITY&e&&t-r<8&&"Infinity".startsWith(s.substring(r))?(r+=8,1/0):s.substring(r,r+9)==="-Infinity"||U.MINUS_INFINITY&e&&1<t-r&&t-r<9&&"-Infinity".startsWith(s.substring(r))?(r+=9,-1/0):s.substring(r,r+3)==="NaN"||U.NAN&e&&t-r<3&&"NaN".startsWith(s.substring(r))?(r+=3,NaN):b()),l=()=>{let w=r,f=!1;for(r++;r<t&&(s[r]!=='"'||f&&s[r-1]==="\\");)f=s[r]==="\\"?!f:!1,r++;if(s.charAt(r)=='"')try{return JSON.parse(s.substring(w,++r-Number(f)))}catch(P){o(String(P))}else if(U.STR&e)try{return JSON.parse(s.substring(w,r-Number(f))+'"')}catch{return JSON.parse(s.substring(w,s.lastIndexOf("\\"))+'"')}n("Unterminated string literal")},h=()=>{r++,d();let w={};try{for(;s[r]!=="}";){if(d(),r>=t&&U.OBJ&e)return w;let f=l();d(),r++;try{let P=i();Object.defineProperty(w,f,{value:P,writable:!0,enumerable:!0,configurable:!0})}catch(P){if(U.OBJ&e)return w;throw P}d(),s[r]===","&&r++}}catch{if(U.OBJ&e)return w;n("Expected '}' at end of object")}return r++,w},m=()=>{r++;let w=[];try{for(;s[r]!=="]";)w.push(i()),d(),s[r]===","&&r++}catch{if(U.ARR&e)return w;n("Expected ']' at end of array")}return r++,w},b=()=>{if(r===0){s==="-"&&U.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(s)}catch(f){if(U.NUM&e)try{return s[s.length-1]==="."?JSON.parse(s.substring(0,s.lastIndexOf("."))):JSON.parse(s.substring(0,s.lastIndexOf("e")))}catch{}o(String(f))}}let w=r;for(s[r]==="-"&&r++;s[r]&&!",]}".includes(s[r]);)r++;r==t&&!(U.NUM&e)&&n("Unterminated number literal");try{return JSON.parse(s.substring(w,r))}catch{s.substring(w,r)==="-"&&U.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(s.substring(w,s.lastIndexOf("e")))}catch(P){o(String(P))}}},d=()=>{for(;r<t&&`
|
|
11
|
+
\r `.includes(s[r]);)r++};return i()},bs=s=>po(s,U.ALL^U.NUM);var N,le,pt,ye,ws,Er,xs,As,Is,Or,Ps,bn,Fe=class s extends dt{constructor(e){super(),N.add(this),le.set(this,void 0),pt.set(this,void 0),ye.set(this,void 0),g(this,le,e,"f"),g(this,pt,[],"f")}get currentChatCompletionSnapshot(){return a(this,ye,"f")}static fromReadableStream(e){let t=new s(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){let n=new s(t);return n._run(()=>n._runChatCompletion(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createChatCompletion(e,t,r){super._createChatCompletion;let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),a(this,N,"m",ws).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)a(this,N,"m",xs).call(this,i);if(o.controller.signal?.aborted)throw new $;return this._addChatCompletion(a(this,N,"m",Or).call(this))}async _fromReadableStream(e,t){let r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),a(this,N,"m",ws).call(this),this._connected();let n=te.fromReadableStream(e,this.controller),o;for await(let i of n)o&&o!==i.id&&this._addChatCompletion(a(this,N,"m",Or).call(this)),a(this,N,"m",xs).call(this,i),o=i.id;if(n.controller.signal?.aborted)throw new $;return this._addChatCompletion(a(this,N,"m",Or).call(this))}[(le=new WeakMap,pt=new WeakMap,ye=new WeakMap,N=new WeakSet,ws=function(){this.ended||g(this,ye,void 0,"f")},Er=function(t){let r=a(this,pt,"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},a(this,pt,"f")[t.index]=r,r)},xs=function(t){if(this.ended)return;let r=a(this,N,"m",bn).call(this,t);this._emit("chunk",t,r);for(let n of t.choices){let o=r.choices[n.index];n.delta.content!=null&&o.message?.role==="assistant"&&o.message?.content&&(this._emit("content",n.delta.content,o.message.content),this._emit("content.delta",{delta:n.delta.content,snapshot:o.message.content,parsed:o.message.parsed})),n.delta.refusal!=null&&o.message?.role==="assistant"&&o.message?.refusal&&this._emit("refusal.delta",{delta:n.delta.refusal,snapshot:o.message.refusal}),n.logprobs?.content!=null&&o.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:n.logprobs?.content,snapshot:o.logprobs?.content??[]}),n.logprobs?.refusal!=null&&o.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:n.logprobs?.refusal,snapshot:o.logprobs?.refusal??[]});let i=a(this,N,"m",Er).call(this,o);o.finish_reason&&(a(this,N,"m",Is).call(this,o),i.current_tool_call_index!=null&&a(this,N,"m",As).call(this,o,i.current_tool_call_index));for(let l of n.delta.tool_calls??[])i.current_tool_call_index!==l.index&&(a(this,N,"m",Is).call(this,o),i.current_tool_call_index!=null&&a(this,N,"m",As).call(this,o,i.current_tool_call_index)),i.current_tool_call_index=l.index;for(let l of n.delta.tool_calls??[]){let h=o.message.tool_calls?.[l.index];h?.type&&(h?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:h.function?.name,index:l.index,arguments:h.function.arguments,parsed_arguments:h.function.parsed_arguments,arguments_delta:l.function?.arguments??""}):(h?.type,void 0))}}},As=function(t,r){if(a(this,N,"m",Er).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=a(this,le,"f")?.tools?.find(l=>Zt(l)&&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:Te(i)?i.$parseRaw(o.function.arguments):i?.function.strict?JSON.parse(o.function.arguments):null})}else o.type},Is=function(t){let r=a(this,N,"m",Er).call(this,t);if(t.message.content&&!r.content_done){r.content_done=!0;let n=a(this,N,"m",Ps).call(this);this._emit("content.done",{content:t.message.content,parsed:n?n.$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}))},Or=function(){if(this.ended)throw new _("stream has ended, this shouldn't happen");let t=a(this,ye,"f");if(!t)throw new _("request ended without sending any chunks");return g(this,ye,void 0,"f"),g(this,pt,[],"f"),_o(t,a(this,le,"f"))},Ps=function(){let t=a(this,le,"f")?.response_format;return er(t)?t:null},bn=function(t){var r,n,o,i;let l=a(this,ye,"f"),{choices:h,...m}=t;l?Object.assign(l,m):l=g(this,ye,{...m,choices:[]},"f");for(let{delta:b,finish_reason:d,index:w,logprobs:f=null,...P}of t.choices){let x=l.choices[w];if(x||(x=l.choices[w]={finish_reason:d,index:w,message:{},logprobs:f,...P}),f)if(!x.logprobs)x.logprobs=Object.assign({},f);else{let{content:q,refusal:C,...L}=f;Object.assign(x.logprobs,L),q&&((r=x.logprobs).content??(r.content=[]),x.logprobs.content.push(...q)),C&&((n=x.logprobs).refusal??(n.refusal=[]),x.logprobs.refusal.push(...C))}if(d&&(x.finish_reason=d,a(this,le,"f")&&us(a(this,le,"f")))){if(d==="length")throw new at;if(d==="content_filter")throw new lt}if(Object.assign(x,P),!b)continue;let{content:O,refusal:R,function_call:y,role:M,tool_calls:S,...H}=b;if(Object.assign(x.message,H),R&&(x.message.refusal=(x.message.refusal||"")+R),M&&(x.message.role=M),y&&(x.message.function_call?(y.name&&(x.message.function_call.name=y.name),y.arguments&&((o=x.message.function_call).arguments??(o.arguments=""),x.message.function_call.arguments+=y.arguments)):x.message.function_call=y),O&&(x.message.content=(x.message.content||"")+O,!x.message.refusal&&a(this,N,"m",Ps).call(this)&&(x.message.parsed=bs(x.message.content))),S){x.message.tool_calls||(x.message.tool_calls=[]);for(let{index:q,id:C,type:L,function:B,...v}of S){let k=(i=x.message.tool_calls)[q]??(i[q]={});Object.assign(k,v),C&&(k.id=C),L&&(k.type=L),B&&(k.function??(k.function={name:B.name??"",arguments:""})),B?.name&&(k.function.name=B.name),B?.arguments&&(k.function.arguments+=B.arguments,hn(a(this,le,"f"),k)&&(k.function.parsed_arguments=bs(k.function.arguments)))}}}return l},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("chunk",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{r=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{r=!0;for(let o of t)o.reject(n);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 te(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function _o(s,e){let{id:t,choices:r,created:n,model:o,system_fingerprint:i,...l}=s,h={...l,id:t,choices:r.map(({message:m,finish_reason:b,index:d,logprobs:w,...f})=>{if(!b)throw new _(`missing finish_reason for choice ${d}`);let{content:P=null,function_call:x,tool_calls:O,...R}=m,y=m.role;if(!y)throw new _(`missing role for choice ${d}`);if(x){let{arguments:M,name:S}=x;if(M==null)throw new _(`missing function_call.arguments for choice ${d}`);if(!S)throw new _(`missing function_call.name for choice ${d}`);return{...f,message:{content:P,function_call:{arguments:M,name:S},role:y,refusal:m.refusal??null},finish_reason:b,index:d,logprobs:w}}return O?{...f,index:d,finish_reason:b,logprobs:w,message:{...R,role:y,content:P,refusal:m.refusal??null,tool_calls:O.map((M,S)=>{let{function:H,type:q,id:C,...L}=M,{arguments:B,name:v,...k}=H||{};if(C==null)throw new _(`missing choices[${d}].tool_calls[${S}].id
|
|
12
|
+
${vr(s)}`);if(q==null)throw new _(`missing choices[${d}].tool_calls[${S}].type
|
|
13
|
+
${vr(s)}`);if(v==null)throw new _(`missing choices[${d}].tool_calls[${S}].function.name
|
|
14
|
+
${vr(s)}`);if(B==null)throw new _(`missing choices[${d}].tool_calls[${S}].function.arguments
|
|
15
|
+
${vr(s)}`);return{...L,id:C,type:q,function:{...k,name:v,arguments:B}}})}}:{...f,message:{...R,content:P,role:y,refusal:m.refusal??null},finish_reason:b,index:d,logprobs:w}}),created:n,model:o,object:"chat.completion",...i?{system_fingerprint:i}:{}};return fn(h,e)}function vr(s){return JSON.stringify(s)}var ar=class s extends Fe{static fromReadableStream(e){let t=new s(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,r){let n=new s(t),o={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,t,o)),n}};var ce=class extends u{constructor(){super(...arguments),this.messages=new ke(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(c`/chat/completions/${e}`,t)}update(e,t,r){return this._client.post(c`/chat/completions/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/chat/completions",I,{query:e,...t})}delete(e,t){return this._client.delete(c`/chat/completions/${e}`,t)}parse(e,t){return pn(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(r=>tr(r,e))}runTools(e,t){return e.stream?ar.runTools(this._client,e,t):ir.runTools(this._client,e,t)}stream(e,t){return Fe.createChatCompletion(this._client,e,t)}};ce.Messages=ke;var be=class extends u{constructor(){super(...arguments),this.completions=new ce(this._client)}};be.Completions=ce;var wn=Symbol("brand.privateNullableHeaders");function*yo(s){if(!s)return;if(wn in s){let{values:r,nulls:n}=s;yield*r.entries();for(let o of n)yield[o,null];return}let e=!1,t;s instanceof Headers?t=s.entries():Jr(s)?t=s:(e=!0,t=Object.entries(s??{}));for(let r of t){let n=r[0];if(typeof n!="string")throw new TypeError("expected header name to be a string");let o=Jr(r[1])?r[1]:[r[1]],i=!1;for(let l of o)l!==void 0&&(e&&!i&&(i=!0,yield[n,null]),yield[n,l])}}var p=s=>{let e=new Headers,t=new Set;for(let r of s){let n=new Set;for(let[o,i]of yo(r)){let l=o.toLowerCase();n.has(l)||(e.delete(o),n.add(l)),i===null?(e.delete(o),t.add(l)):(e.append(o,i),t.delete(l))}}return{[wn]:!0,values:e,nulls:t}};var mt=class extends u{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:p([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}};var _t=class extends u{create(e,t){return this._client.post("/audio/transcriptions",K({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}};var gt=class extends u{create(e,t){return this._client.post("/audio/translations",K({body:e,...t,__metadata:{model:e.model}},this._client))}};var se=class extends u{constructor(){super(...arguments),this.transcriptions=new _t(this._client),this.translations=new gt(this._client),this.speech=new mt(this._client)}};se.Transcriptions=_t;se.Translations=gt;se.Speech=mt;var Ne=class extends u{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(c`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",I,{query:e,...t})}cancel(e,t){return this._client.post(c`/batches/${e}/cancel`,t)}};var yt=class extends u{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(c`/assistants/${e}`,{...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(c`/assistants/${e}`,{body:t,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",I,{query:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(c`/assistants/${e}`,{...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};var bt=class extends u{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};var wt=class extends u{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};var we=class extends u{constructor(){super(...arguments),this.sessions=new bt(this._client),this.transcriptionSessions=new wt(this._client)}};we.Sessions=bt;we.TranscriptionSessions=wt;var xt=class extends u{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:p([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}cancel(e,t){return this._client.post(c`/chatkit/sessions/${e}/cancel`,{...t,headers:p([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}};var At=class extends u{retrieve(e,t){return this._client.get(c`/chatkit/threads/${e}`,{...t,headers:p([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}list(e={},t){return this._client.getAPIList("/chatkit/threads",ie,{query:e,...t,headers:p([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}delete(e,t){return this._client.delete(c`/chatkit/threads/${e}`,{...t,headers:p([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}listItems(e,t={},r){return this._client.getAPIList(c`/chatkit/threads/${e}/items`,ie,{query:t,...r,headers:p([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}};var xe=class extends u{constructor(){super(...arguments),this.sessions=new xt(this._client),this.threads=new At(this._client)}};xe.Sessions=xt;xe.Threads=At;var It=class extends u{create(e,t,r){return this._client.post(c`/threads/${e}/messages`,{body:t,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{thread_id:n}=t;return this._client.get(c`/threads/${n}/messages/${e}`,{...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{thread_id:n,...o}=t;return this._client.post(c`/threads/${n}/messages/${e}`,{body:o,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(c`/threads/${e}/messages`,I,{query:t,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){let{thread_id:n}=t;return this._client.delete(c`/threads/${n}/messages/${e}`,{...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};var Pt=class extends u{retrieve(e,t,r){let{thread_id:n,run_id:o,...i}=t;return this._client.get(c`/threads/${n}/runs/${o}/steps/${e}`,{query:i,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t,r){let{thread_id:n,...o}=t;return this._client.getAPIList(c`/threads/${n}/runs/${e}/steps`,I,{query:o,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};var xn=s=>{if(typeof Buffer<"u"){let e=Buffer.from(s,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(s),t=e.length,r=new Uint8Array(t);for(let n=0;n<t;n++)r[n]=e.charCodeAt(n);return Array.from(new Float32Array(r.buffer))}};var Ae=s=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[s]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(s)?.trim()};var j,Le,Rs,ne,$r,G,Be,Rt,Me,Fr,V,kr,Tr,ur,lr,cr,An,In,Pn,Rn,Sn,Cn,En,ue=class extends ge{constructor(){super(...arguments),j.add(this),Rs.set(this,[]),ne.set(this,{}),$r.set(this,{}),G.set(this,void 0),Be.set(this,void 0),Rt.set(this,void 0),Me.set(this,void 0),Fr.set(this,void 0),V.set(this,void 0),kr.set(this,void 0),Tr.set(this,void 0),ur.set(this,void 0)}[(Rs=new WeakMap,ne=new WeakMap,$r=new WeakMap,G=new WeakMap,Be=new WeakMap,Rt=new WeakMap,Me=new WeakMap,Fr=new WeakMap,V=new WeakMap,kr=new WeakMap,Tr=new WeakMap,ur=new WeakMap,j=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{r=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{r=!0;for(let o of t)o.reject(n);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 Le;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 n=te.fromReadableStream(e,this.controller);for await(let o of n)a(this,j,"m",lr).call(this,o);if(n.controller.signal?.aborted)throw new $;return this._addRun(a(this,j,"m",cr).call(this))}toReadableStream(){return new te(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,n){let o=new Le;return o._run(()=>o._runToolAssistantStream(e,t,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createToolAssistantStream(e,t,r,n){let o=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let i={...r,stream:!0},l=await e.submitToolOutputs(t,i,{...n,signal:this.controller.signal});this._connected();for await(let h of l)a(this,j,"m",lr).call(this,h);if(l.controller.signal?.aborted)throw new $;return this._addRun(a(this,j,"m",cr).call(this))}static createThreadAssistantStream(e,t,r){let n=new Le;return n._run(()=>n._threadAssistantStream(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}static createAssistantStream(e,t,r,n){let o=new Le;return o._run(()=>o._runAssistantStream(e,t,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return a(this,kr,"f")}currentRun(){return a(this,Tr,"f")}currentMessageSnapshot(){return a(this,G,"f")}currentRunStepSnapshot(){return a(this,ur,"f")}async finalRunSteps(){return await this.done(),Object.values(a(this,ne,"f"))}async finalMessages(){return await this.done(),Object.values(a(this,$r,"f"))}async finalRun(){if(await this.done(),!a(this,Be,"f"))throw Error("Final run was not received.");return a(this,Be,"f")}async _createThreadAssistantStream(e,t,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.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)a(this,j,"m",lr).call(this,l);if(i.controller.signal?.aborted)throw new $;return this._addRun(a(this,j,"m",cr).call(this))}async _createAssistantStream(e,t,r,n){let o=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let i={...r,stream:!0},l=await e.create(t,i,{...n,signal:this.controller.signal});this._connected();for await(let h of l)a(this,j,"m",lr).call(this,h);if(l.controller.signal?.aborted)throw new $;return this._addRun(a(this,j,"m",cr).call(this))}static accumulateDelta(e,t){for(let[r,n]of Object.entries(t)){if(!e.hasOwnProperty(r)){e[r]=n;continue}let o=e[r];if(o==null){e[r]=n;continue}if(r==="index"||r==="type"){e[r]=n;continue}if(typeof o=="string"&&typeof n=="string")o+=n;else if(typeof o=="number"&&typeof n=="number")o+=n;else if(Xt(o)&&Xt(n))o=this.accumulateDelta(o,n);else if(Array.isArray(o)&&Array.isArray(n)){if(o.every(i=>typeof i=="string"||typeof i=="number")){o.push(...n);continue}for(let i of n){if(!Xt(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);let l=i.index;if(l==null)throw console.error(i),new Error("Expected array delta entry to have an `index` property");if(typeof l!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${l}`);let h=o[l];h==null?o.push(i):o[l]=this.accumulateDelta(h,i)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${n}, 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,n){return await this._createAssistantStream(t,e,r,n)}async _runToolAssistantStream(e,t,r,n){return await this._createToolAssistantStream(t,e,r,n)}};Le=ue,lr=function(e){if(!this.ended)switch(g(this,kr,e,"f"),a(this,j,"m",Pn).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":a(this,j,"m",En).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":a(this,j,"m",In).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":a(this,j,"m",An).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 _("stream has ended, this shouldn't happen");if(!a(this,Be,"f"))throw Error("Final run has not been received");return a(this,Be,"f")},An=function(e){let[t,r]=a(this,j,"m",Sn).call(this,e,a(this,G,"f"));g(this,G,t,"f"),a(this,$r,"f")[t.id]=t;for(let n of r){let o=t.content[n.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 n of e.data.delta.content){if(n.type=="text"&&n.text){let o=n.text,i=t.content[n.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(n.index!=a(this,Rt,"f")){if(a(this,Me,"f"))switch(a(this,Me,"f").type){case"text":this._emit("textDone",a(this,Me,"f").text,a(this,G,"f"));break;case"image_file":this._emit("imageFileDone",a(this,Me,"f").image_file,a(this,G,"f"));break}g(this,Rt,n.index,"f")}g(this,Me,t.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(a(this,Rt,"f")!==void 0){let n=e.data.content[a(this,Rt,"f")];if(n)switch(n.type){case"image_file":this._emit("imageFileDone",n.image_file,a(this,G,"f"));break;case"text":this._emit("textDone",n.text,a(this,G,"f"));break}}a(this,G,"f")&&this._emit("messageDone",e.data),g(this,G,void 0,"f")}},In=function(e){let t=a(this,j,"m",Rn).call(this,e);switch(g(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==a(this,Fr,"f")?this._emit("toolCallDelta",o,t.step_details.tool_calls[o.index]):(a(this,V,"f")&&this._emit("toolCallDone",a(this,V,"f")),g(this,Fr,o.index,"f"),g(this,V,t.step_details.tool_calls[o.index],"f"),a(this,V,"f")&&this._emit("toolCallCreated",a(this,V,"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":g(this,ur,void 0,"f"),e.data.step_details.type=="tool_calls"&&a(this,V,"f")&&(this._emit("toolCallDone",a(this,V,"f")),g(this,V,void 0,"f")),this._emit("runStepDone",e.data,t);break;case"thread.run.step.in_progress":break}},Pn=function(e){a(this,Rs,"f").push(e),this._emit("event",e)},Rn=function(e){switch(e.event){case"thread.run.step.created":return a(this,ne,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=a(this,ne,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){let n=Le.accumulateDelta(t,r.delta);a(this,ne,"f")[e.data.id]=n}return a(this,ne,"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":a(this,ne,"f")[e.data.id]=e.data;break}if(a(this,ne,"f")[e.data.id])return a(this,ne,"f")[e.data.id];throw new Error("No snapshot available")},Sn=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 n=e.data;if(n.delta.content)for(let o of n.delta.content)if(o.index in t.content){let i=t.content[o.index];t.content[o.index]=a(this,j,"m",Cn).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")},Cn=function(e,t){return Le.accumulateDelta(t,e)},En=function(e){switch(g(this,Tr,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":g(this,Be,e.data,"f"),a(this,V,"f")&&(this._emit("toolCallDone",a(this,V,"f")),g(this,V,void 0,"f"));break;case"thread.run.cancelling":break}};var Ue=class extends u{constructor(){super(...arguments),this.steps=new Pt(this._client)}create(e,t,r){let{include:n,...o}=t;return this._client.post(c`/threads/${e}/runs`,{query:{include:n},body:o,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1})}retrieve(e,t,r){let{thread_id:n}=t;return this._client.get(c`/threads/${n}/runs/${e}`,{...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{thread_id:n,...o}=t;return this._client.post(c`/threads/${n}/runs/${e}`,{body:o,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(c`/threads/${e}/runs`,I,{query:t,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){let{thread_id:n}=t;return this._client.post(c`/threads/${n}/runs/${e}/cancel`,{...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let n=await this.create(e,t,r);return await this.poll(n.id,{thread_id:e},r)}createAndStream(e,t,r){return ue.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){let n=p([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,...n}}).withResponse();switch(o.status){case"queued":case"in_progress":case"cancelling":let l=5e3;if(r?.pollIntervalMs)l=r.pollIntervalMs;else{let h=i.headers.get("openai-poll-after-ms");if(h){let m=parseInt(h);isNaN(m)||(l=m)}}await Z(l);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return o}}}stream(e,t,r){return ue.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r){let{thread_id:n,...o}=t;return this._client.post(c`/threads/${n}/runs/${e}/submit_tool_outputs`,{body:o,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1})}async submitToolOutputsAndPoll(e,t,r){let n=await this.submitToolOutputs(e,t,r);return await this.poll(n.id,t,r)}submitToolOutputsStream(e,t,r){return ue.createToolAssistantStream(e,this._client.beta.threads.runs,t,r)}};Ue.Steps=Pt;var Ie=class extends u{constructor(){super(...arguments),this.runs=new Ue(this._client),this.messages=new It(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(c`/threads/${e}`,{...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(c`/threads/${e}`,{body:t,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t){return this._client.delete(c`/threads/${e}`,{...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:p([{"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 ue.createThreadAssistantStream(e,this._client.beta.threads,t)}};Ie.Runs=Ue;Ie.Messages=It;var z=class extends u{constructor(){super(...arguments),this.realtime=new we(this._client),this.chatkit=new xe(this._client),this.assistants=new yt(this._client),this.threads=new Ie(this._client)}};z.Realtime=we;z.ChatKit=xe;z.Assistants=yt;z.Threads=Ie;var je=class extends u{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}};var St=class extends u{retrieve(e,t,r){let{container_id:n}=t;return this._client.get(c`/containers/${n}/files/${e}/content`,{...r,headers:p([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}};var De=class extends u{constructor(){super(...arguments),this.content=new St(this._client)}create(e,t,r){return this._client.post(c`/containers/${e}/files`,K({body:t,...r},this._client))}retrieve(e,t,r){let{container_id:n}=t;return this._client.get(c`/containers/${n}/files/${e}`,r)}list(e,t={},r){return this._client.getAPIList(c`/containers/${e}/files`,I,{query:t,...r})}delete(e,t,r){let{container_id:n}=t;return this._client.delete(c`/containers/${n}/files/${e}`,{...r,headers:p([{Accept:"*/*"},r?.headers])})}};De.Content=St;var Pe=class extends u{constructor(){super(...arguments),this.files=new De(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(c`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",I,{query:e,...t})}delete(e,t){return this._client.delete(c`/containers/${e}`,{...t,headers:p([{Accept:"*/*"},t?.headers])})}};Pe.Files=De;var Ct=class extends u{create(e,t,r){let{include:n,...o}=t;return this._client.post(c`/conversations/${e}/items`,{query:{include:n},body:o,...r})}retrieve(e,t,r){let{conversation_id:n,...o}=t;return this._client.get(c`/conversations/${n}/items/${e}`,{query:o,...r})}list(e,t={},r){return this._client.getAPIList(c`/conversations/${e}/items`,ie,{query:t,...r})}delete(e,t,r){let{conversation_id:n}=t;return this._client.delete(c`/conversations/${n}/items/${e}`,r)}};var Re=class extends u{constructor(){super(...arguments),this.items=new Ct(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t})}retrieve(e,t){return this._client.get(c`/conversations/${e}`,t)}update(e,t,r){return this._client.post(c`/conversations/${e}`,{body:t,...r})}delete(e,t){return this._client.delete(c`/conversations/${e}`,t)}};Re.Items=Ct;var qe=class extends u{create(e,t){let r=!!e.encoding_format,n=r?e.encoding_format:"base64";r&&E(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let o=this._client.post("/embeddings",{body:{...e,encoding_format:n},...t});return r?o:(E(this._client).debug("embeddings/decoding base64 embeddings from base64"),o._thenUnwrap(i=>(i&&i.data&&i.data.forEach(l=>{let h=l.embedding;l.embedding=xn(h)}),i)))}};var Et=class extends u{retrieve(e,t,r){let{eval_id:n,run_id:o}=t;return this._client.get(c`/evals/${n}/runs/${o}/output_items/${e}`,r)}list(e,t,r){let{eval_id:n,...o}=t;return this._client.getAPIList(c`/evals/${n}/runs/${e}/output_items`,I,{query:o,...r})}};var We=class extends u{constructor(){super(...arguments),this.outputItems=new Et(this._client)}create(e,t,r){return this._client.post(c`/evals/${e}/runs`,{body:t,...r})}retrieve(e,t,r){let{eval_id:n}=t;return this._client.get(c`/evals/${n}/runs/${e}`,r)}list(e,t={},r){return this._client.getAPIList(c`/evals/${e}/runs`,I,{query:t,...r})}delete(e,t,r){let{eval_id:n}=t;return this._client.delete(c`/evals/${n}/runs/${e}`,r)}cancel(e,t,r){let{eval_id:n}=t;return this._client.post(c`/evals/${n}/runs/${e}`,r)}};We.OutputItems=Et;var Se=class extends u{constructor(){super(...arguments),this.runs=new We(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(c`/evals/${e}`,t)}update(e,t,r){return this._client.post(c`/evals/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/evals",I,{query:e,...t})}delete(e,t){return this._client.delete(c`/evals/${e}`,t)}};Se.Runs=We;var He=class extends u{create(e,t){return this._client.post("/files",K({body:e,...t},this._client))}retrieve(e,t){return this._client.get(c`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",I,{query:e,...t})}delete(e,t){return this._client.delete(c`/files/${e}`,t)}content(e,t){return this._client.get(c`/files/${e}/content`,{...t,headers:p([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:r=1800*1e3}={}){let n=new Set(["processed","error","deleted"]),o=Date.now(),i=await this.retrieve(e);for(;!i.status||!n.has(i.status);)if(await Z(t),i=await this.retrieve(e),Date.now()-o>r)throw new me({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return i}};var Ot=class extends u{};var vt=class extends u{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 Je=class extends u{constructor(){super(...arguments),this.graders=new vt(this._client)}};Je.Graders=vt;var $t=class extends u{create(e,t,r){return this._client.getAPIList(c`/fine_tuning/checkpoints/${e}/permissions`,re,{body:t,method:"post",...r})}retrieve(e,t={},r){return this._client.get(c`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...r})}delete(e,t,r){let{fine_tuned_model_checkpoint:n}=t;return this._client.delete(c`/fine_tuning/checkpoints/${n}/permissions/${e}`,r)}};var Xe=class extends u{constructor(){super(...arguments),this.permissions=new $t(this._client)}};Xe.Permissions=$t;var kt=class extends u{list(e,t={},r){return this._client.getAPIList(c`/fine_tuning/jobs/${e}/checkpoints`,I,{query:t,...r})}};var Ke=class extends u{constructor(){super(...arguments),this.checkpoints=new kt(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(c`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",I,{query:e,...t})}cancel(e,t){return this._client.post(c`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},r){return this._client.getAPIList(c`/fine_tuning/jobs/${e}/events`,I,{query:t,...r})}pause(e,t){return this._client.post(c`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(c`/fine_tuning/jobs/${e}/resume`,t)}};Ke.Checkpoints=kt;var Q=class extends u{constructor(){super(...arguments),this.methods=new Ot(this._client),this.jobs=new Ke(this._client),this.checkpoints=new Xe(this._client),this.alpha=new Je(this._client)}};Q.Methods=Ot;Q.Jobs=Ke;Q.Checkpoints=Xe;Q.Alpha=Je;var Tt=class extends u{};var Ce=class extends u{constructor(){super(...arguments),this.graderModels=new Tt(this._client)}};Ce.GraderModels=Tt;var Ve=class extends u{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})}};var Ge=class extends u{retrieve(e,t){return this._client.get(c`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",re,e)}delete(e,t){return this._client.delete(c`/models/${e}`,t)}};var ze=class extends u{create(e,t){return this._client.post("/moderations",{body:e,...t})}};var Ft=class extends u{accept(e,t,r){return this._client.post(c`/realtime/calls/${e}/accept`,{body:t,...r,headers:p([{Accept:"*/*"},r?.headers])})}hangup(e,t){return this._client.post(c`/realtime/calls/${e}/hangup`,{...t,headers:p([{Accept:"*/*"},t?.headers])})}refer(e,t,r){return this._client.post(c`/realtime/calls/${e}/refer`,{body:t,...r,headers:p([{Accept:"*/*"},r?.headers])})}reject(e,t={},r){return this._client.post(c`/realtime/calls/${e}/reject`,{body:t,...r,headers:p([{Accept:"*/*"},r?.headers])})}};var Nt=class extends u{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t})}};var fe=class extends u{constructor(){super(...arguments),this.clientSecrets=new Nt(this._client),this.calls=new Ft(this._client)}};fe.ClientSecrets=Nt;fe.Calls=Ft;function On(s,e){return!e||!Go(e)?{...s,output_parsed:null,output:s.output.map(t=>t.type==="function_call"?{...t,parsed_arguments:null}:t.type==="message"?{...t,content:t.content.map(r=>({...r,parsed:null}))}:t)}:Ss(s,e)}function Ss(s,e){let t=s.output.map(n=>{if(n.type==="function_call")return{...n,parsed_arguments:Yo(e,n)};if(n.type==="message"){let o=n.content.map(i=>i.type==="output_text"?{...i,parsed:Vo(e,i.text)}:i);return{...n,content:o}}return n}),r=Object.assign({},s,{output:t});return Object.getOwnPropertyDescriptor(s,"output_text")||Nr(r),Object.defineProperty(r,"output_parsed",{enumerable:!0,get(){for(let n of r.output)if(n.type==="message"){for(let o of n.content)if(o.type==="output_text"&&o.parsed!==null)return o.parsed}return null}}),r}function Vo(s,e){return s.text?.format?.type!=="json_schema"?null:"$parseRaw"in s.text?.format?(s.text?.format).$parseRaw(e):JSON.parse(e)}function Go(s){return!!er(s.text?.format)}function zo(s){return s?.$brand==="auto-parseable-tool"}function Qo(s,e){return s.find(t=>t.type==="function"&&t.name===e)}function Yo(s,e){let t=Qo(s.tools??[],e.name);return{...e,...e,parsed_arguments:zo(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function Nr(s){let e=[];for(let t of s.output)if(t.type==="message")for(let r of t.content)r.type==="output_text"&&e.push(r.text);s.output_text=e.join("")}var Mt,Mr,Ee,Lr,vn,$n,kn,Tn,Br=class s extends ge{constructor(e){super(),Mt.add(this),Mr.set(this,void 0),Ee.set(this,void 0),Lr.set(this,void 0),g(this,Mr,e,"f")}static createResponse(e,t,r){let n=new s(t);return n._run(()=>n._createOrRetrieveResponse(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createOrRetrieveResponse(e,t,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),a(this,Mt,"m",vn).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)a(this,Mt,"m",$n).call(this,l,i);if(o.controller.signal?.aborted)throw new $;return a(this,Mt,"m",kn).call(this)}[(Mr=new WeakMap,Ee=new WeakMap,Lr=new WeakMap,Mt=new WeakSet,vn=function(){this.ended||g(this,Ee,void 0,"f")},$n=function(t,r){if(this.ended)return;let n=(i,l)=>{(r==null||l.sequence_number>r)&&this._emit(i,l)},o=a(this,Mt,"m",Tn).call(this,t);switch(n("event",t),t.type){case"response.output_text.delta":{let i=o.output[t.output_index];if(!i)throw new _(`missing output at index ${t.output_index}`);if(i.type==="message"){let l=i.content[t.content_index];if(!l)throw new _(`missing content at index ${t.content_index}`);if(l.type!=="output_text")throw new _(`expected content to be 'output_text', got ${l.type}`);n("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 _(`missing output at index ${t.output_index}`);i.type==="function_call"&&n("response.function_call_arguments.delta",{...t,snapshot:i.arguments});break}default:n(t.type,t);break}},kn=function(){if(this.ended)throw new _("stream has ended, this shouldn't happen");let t=a(this,Ee,"f");if(!t)throw new _("request ended without sending any events");g(this,Ee,void 0,"f");let r=Zo(t,a(this,Mr,"f"));return g(this,Lr,r,"f"),r},Tn=function(t){let r=a(this,Ee,"f");if(!r){if(t.type!=="response.created")throw new _(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return r=g(this,Ee,t.response,"f"),r}switch(t.type){case"response.output_item.added":{r.output.push(t.item);break}case"response.content_part.added":{let n=r.output[t.output_index];if(!n)throw new _(`missing output at index ${t.output_index}`);let o=n.type,i=t.part;o==="message"&&i.type!=="reasoning_text"?n.content.push(i):o==="reasoning"&&i.type==="reasoning_text"&&(n.content||(n.content=[]),n.content.push(i));break}case"response.output_text.delta":{let n=r.output[t.output_index];if(!n)throw new _(`missing output at index ${t.output_index}`);if(n.type==="message"){let o=n.content[t.content_index];if(!o)throw new _(`missing content at index ${t.content_index}`);if(o.type!=="output_text")throw new _(`expected content to be 'output_text', got ${o.type}`);o.text+=t.delta}break}case"response.function_call_arguments.delta":{let n=r.output[t.output_index];if(!n)throw new _(`missing output at index ${t.output_index}`);n.type==="function_call"&&(n.arguments+=t.delta);break}case"response.reasoning_text.delta":{let n=r.output[t.output_index];if(!n)throw new _(`missing output at index ${t.output_index}`);if(n.type==="reasoning"){let o=n.content?.[t.content_index];if(!o)throw new _(`missing content at index ${t.content_index}`);if(o.type!=="reasoning_text")throw new _(`expected content to be 'reasoning_text', got ${o.type}`);o.text+=t.delta}break}case"response.completed":{g(this,Ee,t.response,"f");break}}return r},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{r=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{r=!0;for(let o of t)o.reject(n);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=a(this,Lr,"f");if(!e)throw new _("stream ended without producing a ChatCompletion");return e}};function Zo(s,e){return On(s,e)}var Lt=class extends u{list(e,t={},r){return this._client.getAPIList(c`/responses/${e}/input_items`,I,{query:t,...r})}};var Bt=class extends u{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t})}};var he=class extends u{constructor(){super(...arguments),this.inputItems=new Lt(this._client),this.inputTokens=new Bt(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"&&Nr(r),r))}retrieve(e,t={},r){return this._client.get(c`/responses/${e}`,{query:t,...r,stream:t?.stream??!1})._thenUnwrap(n=>("object"in n&&n.object==="response"&&Nr(n),n))}delete(e,t){return this._client.delete(c`/responses/${e}`,{...t,headers:p([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(r=>Ss(r,e))}stream(e,t){return Br.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(c`/responses/${e}/cancel`,t)}compact(e,t){return this._client.post("/responses/compact",{body:e,...t})}};he.InputItems=Lt;he.InputTokens=Bt;var Ut=class extends u{create(e,t,r){return this._client.post(c`/uploads/${e}/parts`,K({body:t,...r},this._client))}};var Oe=class extends u{constructor(){super(...arguments),this.parts=new Ut(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(c`/uploads/${e}/cancel`,t)}complete(e,t,r){return this._client.post(c`/uploads/${e}/complete`,{body:t,...r})}};Oe.Parts=Ut;var Fn=async s=>{let e=await Promise.allSettled(s),t=e.filter(n=>n.status==="rejected");if(t.length){for(let n of t)console.error(n.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}let r=[];for(let n of e)n.status==="fulfilled"&&r.push(n.value);return r};var jt=class extends u{create(e,t,r){return this._client.post(c`/vector_stores/${e}/file_batches`,{body:t,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{vector_store_id:n}=t;return this._client.get(c`/vector_stores/${n}/file_batches/${e}`,{...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){let{vector_store_id:n}=t;return this._client.post(c`/vector_stores/${n}/file_batches/${e}/cancel`,{...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let n=await this.create(e,t);return await this.poll(e,n.id,r)}listFiles(e,t,r){let{vector_store_id:n,...o}=t;return this._client.getAPIList(c`/vector_stores/${n}/file_batches/${e}/files`,I,{query:o,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async poll(e,t,r){let n=p([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:n}).withResponse();switch(o.status){case"in_progress":let l=5e3;if(r?.pollIntervalMs)l=r.pollIntervalMs;else{let h=i.headers.get("openai-poll-after-ms");if(h){let m=parseInt(h);isNaN(m)||(l=m)}}await Z(l);break;case"failed":case"cancelled":case"completed":return o}}}async uploadAndPoll(e,{files:t,fileIds:r=[]},n){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=n?.maxConcurrency??5,i=Math.min(o,t.length),l=this._client,h=t.values(),m=[...r];async function b(w){for(let f of w){let P=await l.files.create({file:f,purpose:"assistants"},n);m.push(P.id)}}let d=Array(i).fill(h).map(b);return await Fn(d),await this.createAndPoll(e,{file_ids:m})}};var Dt=class extends u{create(e,t,r){return this._client.post(c`/vector_stores/${e}/files`,{body:t,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{vector_store_id:n}=t;return this._client.get(c`/vector_stores/${n}/files/${e}`,{...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{vector_store_id:n,...o}=t;return this._client.post(c`/vector_stores/${n}/files/${e}`,{body:o,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(c`/vector_stores/${e}/files`,I,{query:t,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){let{vector_store_id:n}=t;return this._client.delete(c`/vector_stores/${n}/files/${e}`,{...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let n=await this.create(e,t,r);return await this.poll(e,n.id,r)}async poll(e,t,r){let n=p([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:n}).withResponse(),i=o.data;switch(i.status){case"in_progress":let l=5e3;if(r?.pollIntervalMs)l=r.pollIntervalMs;else{let h=o.response.headers.get("openai-poll-after-ms");if(h){let m=parseInt(h);isNaN(m)||(l=m)}}await Z(l);break;case"failed":case"completed":return i}}}async upload(e,t,r){let n=await this._client.files.create({file:t,purpose:"assistants"},r);return this.create(e,{file_id:n.id},r)}async uploadAndPoll(e,t,r){let n=await this.upload(e,t,r);return await this.poll(e,n.id,r)}content(e,t,r){let{vector_store_id:n}=t;return this._client.getAPIList(c`/vector_stores/${n}/files/${e}/content`,re,{...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};var de=class extends u{constructor(){super(...arguments),this.files=new Dt(this._client),this.fileBatches=new jt(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(c`/vector_stores/${e}`,{...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(c`/vector_stores/${e}`,{body:t,...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",I,{query:e,...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(c`/vector_stores/${e}`,{...t,headers:p([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,r){return this._client.getAPIList(c`/vector_stores/${e}/search`,re,{body:t,method:"post",...r,headers:p([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};de.Files=Dt;de.FileBatches=jt;var Qe=class extends u{create(e,t){return this._client.post("/videos",ls({body:e,...t},this._client))}retrieve(e,t){return this._client.get(c`/videos/${e}`,t)}list(e={},t){return this._client.getAPIList("/videos",ie,{query:e,...t})}delete(e,t){return this._client.delete(c`/videos/${e}`,t)}downloadContent(e,t={},r){return this._client.get(c`/videos/${e}/content`,{query:t,...r,headers:p([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}remix(e,t,r){return this._client.post(c`/videos/${e}/remix`,ls({body:t,...r},this._client))}};var qt,Nn,Ur,Ye=class extends u{constructor(){super(...arguments),qt.add(this)}async unwrap(e,t,r=this._client.webhookSecret,n=300){return await this.verifySignature(e,t,r,n),JSON.parse(e)}async verifySignature(e,t,r=this._client.webhookSecret,n=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");a(this,qt,"m",Nn).call(this,r);let o=p([t]).values,i=a(this,qt,"m",Ur).call(this,o,"webhook-signature"),l=a(this,qt,"m",Ur).call(this,o,"webhook-timestamp"),h=a(this,qt,"m",Ur).call(this,o,"webhook-id"),m=parseInt(l,10);if(isNaN(m))throw new Y("Invalid webhook timestamp format");let b=Math.floor(Date.now()/1e3);if(b-m>n)throw new Y("Webhook timestamp is too old");if(m>b+n)throw new Y("Webhook timestamp is too new");let d=i.split(" ").map(x=>x.startsWith("v1,")?x.substring(3):x),w=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),f=h?`${h}.${l}.${e}`:`${l}.${e}`,P=await crypto.subtle.importKey("raw",w,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let x of d)try{let O=Buffer.from(x,"base64");if(await crypto.subtle.verify("HMAC",P,O,new TextEncoder().encode(f)))return}catch{continue}throw new Y("The given webhook signature does not match the expected signature")}};qt=new WeakSet,Nn=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")},Ur=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 Cs,Es,jr,Mn,A=class{constructor({baseURL:e=Ae("OPENAI_BASE_URL"),apiKey:t=Ae("OPENAI_API_KEY"),organization:r=Ae("OPENAI_ORG_ID")??null,project:n=Ae("OPENAI_PROJECT_ID")??null,webhookSecret:o=Ae("OPENAI_WEBHOOK_SECRET")??null,...i}={}){if(Cs.add(this),jr.set(this,void 0),this.completions=new je(this),this.chat=new be(this),this.embeddings=new qe(this),this.files=new He(this),this.images=new Ve(this),this.audio=new se(this),this.moderations=new ze(this),this.models=new Ge(this),this.fineTuning=new Q(this),this.graders=new Ce(this),this.vectorStores=new de(this),this.webhooks=new Ye(this),this.beta=new z(this),this.batches=new Ne(this),this.uploads=new Oe(this),this.responses=new he(this),this.realtime=new fe(this),this.conversations=new Re(this),this.evals=new Se(this),this.containers=new Pe(this),this.videos=new Qe(this),t===void 0)throw new _("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");let l={apiKey:t,organization:r,project:n,webhookSecret:o,...i,baseURL:e||"https://api.openai.com/v1"};if(!l.dangerouslyAllowBrowser&&qs())throw new _(`It looks like you're running in a browser-like environment.
|
|
16
|
+
|
|
17
|
+
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
18
|
+
If you understand the risks and have appropriate mitigations in place,
|
|
19
|
+
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
20
|
+
|
|
21
|
+
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
22
|
+
|
|
23
|
+
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
24
|
+
`);this.baseURL=l.baseURL,this.timeout=l.timeout??Es.DEFAULT_TIMEOUT,this.logger=l.logger??console;let h="warn";this.logLevel=h,this.logLevel=rs(l.logLevel,"ClientOptions.logLevel",this)??rs(Ae("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??h,this.fetchOptions=l.fetchOptions,this.maxRetries=l.maxRetries??2,this.fetch=l.fetch??Hs(),g(this,jr,Xs,"f"),this._options=l,this.apiKey=typeof t=="string"?t:"Missing Key",this.organization=r,this.project=n,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 p([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return es(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${_e}`}defaultIdempotencyKey(){return`stainless-node-retry-${Hr()}`}makeStatusError(e,t,r,n){return T.generate(e,t,r,n)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!="function")return!1;let t;try{t=await e()}catch(r){throw r instanceof _?r:new _(`Failed to get token from 'apiKey' function: ${r.message}`,{cause:r})}if(typeof t!="string"||!t)throw new _(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,r){let n=!a(this,Cs,"m",Mn).call(this)&&r||this.baseURL,o=Fs(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return Ns(i)||(t={...i,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(o.search=this.stringifyQuery(t)),o.toString()}async prepareOptions(e){await this._callApiKey()}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(n=>({method:e,path:t,...n})))}request(e,t=null){return new $e(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){let n=await e,o=n.maxRetries??this.maxRetries;t==null&&(t=o),await this.prepareOptions(n);let{req:i,url:l,timeout:h}=await this.buildRequest(n,{retryCount:o-t});await this.prepareRequest(i,{url:l,options:n});let m="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),b=r===void 0?"":`, retryOf: ${r}`,d=Date.now();if(E(this).debug(`[${m}] sending request`,oe({retryOfRequestLogID:r,method:n.method,url:l,options:n,headers:i.headers})),n.signal?.aborted)throw new $;let w=new AbortController,f=await this.fetchWithTimeout(l,i,h,w).catch(Jt),P=Date.now();if(f instanceof globalThis.Error){let R=`retrying, ${t} attempts remaining`;if(n.signal?.aborted)throw new $;let y=Ht(f)||/timed? ?out/i.test(String(f)+("cause"in f?String(f.cause):""));if(t)return E(this).info(`[${m}] connection ${y?"timed out":"failed"} - ${R}`),E(this).debug(`[${m}] connection ${y?"timed out":"failed"} (${R})`,oe({retryOfRequestLogID:r,url:l,durationMs:P-d,message:f.message})),this.retryRequest(n,t,r??m);throw E(this).info(`[${m}] connection ${y?"timed out":"failed"} - error; no more retries left`),E(this).debug(`[${m}] connection ${y?"timed out":"failed"} (error; no more retries left)`,oe({retryOfRequestLogID:r,url:l,durationMs:P-d,message:f.message})),y?new me:new pe({cause:f})}let x=[...f.headers.entries()].filter(([R])=>R==="x-request-id").map(([R,y])=>", "+R+": "+JSON.stringify(y)).join(""),O=`[${m}${b}${x}] ${i.method} ${l} ${f.ok?"succeeded":"failed"} with status ${f.status} in ${P-d}ms`;if(!f.ok){let R=await this.shouldRetry(f);if(t&&R){let C=`retrying, ${t} attempts remaining`;return await Js(f.body),E(this).info(`${O} - ${C}`),E(this).debug(`[${m}] response error (${C})`,oe({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,durationMs:P-d})),this.retryRequest(n,t,r??m,f.headers)}let y=R?"error; no more retries left":"error; not retryable";E(this).info(`${O} - ${y}`);let M=await f.text().catch(C=>Jt(C).message),S=Bs(M),H=S?void 0:M;throw E(this).debug(`[${m}] response error (${y})`,oe({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,message:H,durationMs:Date.now()-d})),this.makeStatusError(f.status,S,H,f.headers)}return E(this).info(O),E(this).debug(`[${m}] response start`,oe({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,durationMs:P-d})),{response:f,options:n,controller:w,requestLogID:m,retryOfRequestLogID:r,startTime:d}}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,n){let{signal:o,method:i,...l}=t||{};o&&o.addEventListener("abort",()=>n.abort());let h=setTimeout(()=>n.abort(),r),m=globalThis.ReadableStream&&l.body instanceof globalThis.ReadableStream||typeof l.body=="object"&&l.body!==null&&Symbol.asyncIterator in l.body,b={signal:n.signal,...m?{duplex:"half"}:{},method:"GET",...l};i&&(b.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,b)}finally{clearTimeout(h)}}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,n){let o,i=n?.get("retry-after-ms");if(i){let h=parseFloat(i);Number.isNaN(h)||(o=h)}let l=n?.get("retry-after");if(l&&!o){let h=parseFloat(l);Number.isNaN(h)?o=Date.parse(l)-Date.now():o=h*1e3}if(!(o&&0<=o&&o<60*1e3)){let h=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(t,h)}return await Z(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:n,path:o,query:i,defaultBaseURL:l}=r,h=this.buildURL(o,i,l);"timeout"in r&&Ls("timeout",r.timeout),r.timeout=r.timeout??this.timeout;let{bodyHeaders:m,body:b}=this.buildBody({options:r}),d=await this.buildHeaders({options:e,method:n,bodyHeaders:m,retryCount:t});return{req:{method:n,headers:d,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&b instanceof globalThis.ReadableStream&&{duplex:"half"},...b&&{body:b},...this.fetchOptions??{},...r.fetchOptions??{}},url:h,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:n}){let o={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let i=p([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(n),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Ws(),"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=p([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:hr(e)}:a(this,jr,"f").call(this,{body:e,headers:r})}};Es=A,jr=new WeakMap,Cs=new WeakSet,Mn=function(){return this.baseURL!=="https://api.openai.com/v1"};A.OpenAI=Es;A.DEFAULT_TIMEOUT=6e5;A.OpenAIError=_;A.APIError=T;A.APIConnectionError=pe;A.APIConnectionTimeoutError=me;A.APIUserAbortError=$;A.NotFoundError=rt;A.ConflictError=st;A.RateLimitError=ot;A.BadRequestError=Ze;A.AuthenticationError=et;A.InternalServerError=it;A.PermissionDeniedError=tt;A.UnprocessableEntityError=nt;A.InvalidWebhookSignatureError=Y;A.toFile=xr;A.Completions=je;A.Chat=be;A.Embeddings=qe;A.Files=He;A.Images=Ve;A.Audio=se;A.Moderations=ze;A.Models=Ge;A.FineTuning=Q;A.Graders=Ce;A.VectorStores=de;A.Webhooks=Ye;A.Beta=z;A.Batches=Ne;A.Uploads=Oe;A.Responses=he;A.Realtime=fe;A.Conversations=Re;A.Evals=Se;A.Containers=Pe;A.Videos=Qe;var Ln=class{client;model;constructor(e,t){this.client=new A({apiKey:e}),this.model=t}async generateCommand(e,t){for(let r=0;r<Wt.maxAttempts;r++)try{let o=(await this.client.chat.completions.create({model:this.model,max_tokens:fr,messages:[{role:"system",content:qr(t.shell)},{role:"user",content:Wr(e,t)}]})).choices[0]?.message?.content;if(!o)throw new Error("No content in AI response");return{success:!0,data:$s(o)}}catch(n){if(r===Wt.maxAttempts-1)return{success:!1,error:n instanceof Error?n:new Error(String(n))};let o=Math.min(Wt.baseDelayMs*Math.pow(2,r),Wt.maxDelayMs);await Ts(o)}return{success:!1,error:new Error("Unexpected error")}}async generateAlternatives(e,t,r,n){let o=`${Wr(e,t)}
|
|
25
|
+
|
|
26
|
+
Generate ${n} ALTERNATIVE commands (different approaches).
|
|
27
|
+
Exclude: ${r}
|
|
28
|
+
|
|
29
|
+
Output JSON array: [{ "command": "...", "risk": "low|medium|high" }, ...]`;try{let l=(await this.client.chat.completions.create({model:this.model,max_tokens:fr*2,messages:[{role:"system",content:qr(t.shell)},{role:"user",content:o}]})).choices[0]?.message?.content;if(!l)throw new Error("No content in AI response");return{success:!0,data:ks(l)}}catch(i){return{success:!1,error:i instanceof Error?i:new Error(String(i))}}}async explainCommand(e){try{let r=(await this.client.chat.completions.create({model:this.model,max_tokens:fr,messages:[{role:"user",content:`Explain this command briefly (2-3 sentences max):
|
|
30
|
+
${e}`}]})).choices[0]?.message?.content;if(!r)throw new Error("No content in AI response");return{success:!0,data:r.trim()}}catch(t){return{success:!1,error:t instanceof Error?t:new Error(String(t))}}}};export{Ln as OpenAIProvider};
|