3 lines
102 KiB
JavaScript
3 lines
102 KiB
JavaScript
!function(e){"function"==typeof define&&define.amd?define(e):e()}((function(){"use strict";const e={actualMode:"autocomplete"},t=["logs","title","cursor","typing","mouseover","infinite","timeout","history","includeImages"],s=document.querySelector("#mode").querySelectorAll("button");function n(e,t,s,n){return new(s||(s=Promise))((function(r,o){function i(e){try{l(n.next(e))}catch(e){o(e)}}function a(e){try{l(n.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(i,a)}l((n=n.apply(e,t||[])).next())}))}function r(e,t,s,n,r){if("function"==typeof t||!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,s),s}function o(e,t,s,n){if("a"===s&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?n:"a"===s?n.call(e):n?n.value:t.get(e)}"function"==typeof SuppressedError&&SuppressedError;let i=function(){const{crypto:e}=globalThis;if(e?.randomUUID)return i=e.randomUUID.bind(e),e.randomUUID();const t=new Uint8Array(1),s=e?()=>e.getRandomValues(t)[0]:()=>255*Math.random()&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(e=>(+e^s()&15>>+e/4).toString(16)))};function a(e){return"object"==typeof e&&null!==e&&("name"in e&&"AbortError"===e.name||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}const l=e=>{if(e instanceof Error)return e;if("object"==typeof e&&null!==e){try{if("[object Error]"===Object.prototype.toString.call(e)){const t=new Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return new Error(JSON.stringify(e))}catch{}}return new Error(e)};class c extends Error{}class u extends c{constructor(e,t,s,n){super(`${u.makeMessage(e,t,s)}`),this.status=e,this.headers=n,this.requestID=n?.get("x-request-id"),this.error=t;const r=t;this.code=r?.code,this.param=r?.param,this.type=r?.type}static makeMessage(e,t,s){const n=t?.message?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):s;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,s,n){if(!e||!n)return new d({message:s,cause:l(t)});const r=t?.error;return 400===e?new p(e,r,s,n):401===e?new m(e,r,s,n):403===e?new g(e,r,s,n):404===e?new y(e,r,s,n):409===e?new w(e,r,s,n):422===e?new _(e,r,s,n):429===e?new b(e,r,s,n):e>=500?new v(e,r,s,n):new u(e,r,s,n)}}class h extends u{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class d extends u{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class f extends d{constructor({message:e}={}){super({message:e??"Request timed out."})}}class p extends u{}class m extends u{}class g extends u{}class y extends u{}class w extends u{}class _ extends u{}class b extends u{}class v extends u{}class x extends c{constructor(){super("Could not parse response content as the length limit was reached")}}class S extends c{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class $ extends Error{constructor(e){super(e)}}const A=/^[a-z][a-z0-9+.-]*:/i;let I=e=>(I=Array.isArray,I(e)),O=I;function k(e){return"object"!=typeof e?{}:e??{}}function R(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)}const E=e=>new Promise((t=>setTimeout(t,e))),P="5.23.2";const C=()=>{const e="undefined"!=typeof Deno&&null!=Deno.build?"deno":"undefined"!=typeof EdgeRuntime?"edge":"[object process]"===Object.prototype.toString.call(void 0!==globalThis.process?globalThis.process:0)?"node":"unknown";if("deno"===e)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":P,"X-Stainless-OS":q(Deno.build.os),"X-Stainless-Arch":T(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":"string"==typeof Deno.version?Deno.version:Deno.version?.deno??"unknown"};if("undefined"!=typeof EdgeRuntime)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":P,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if("node"===e)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":P,"X-Stainless-OS":q(globalThis.process.platform??"unknown"),"X-Stainless-Arch":T(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const t=function(){if("undefined"==typeof navigator||!navigator)return null;const e=[{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(const{key:t,pattern:s}of e){const e=s.exec(navigator.userAgent);if(e){return{browser:t,version:`${e[1]||0}.${e[2]||0}.${e[3]||0}`}}}return null}();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":P,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":P,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};const T=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",q=e=>(e=e.toLowerCase()).includes("ios")?"iOS":"android"===e?"Android":"darwin"===e?"MacOS":"win32"===e?"Windows":"freebsd"===e?"FreeBSD":"openbsd"===e?"OpenBSD":"linux"===e?"Linux":e?`Other:${e}`:"Unknown";let j;function M(...e){const t=globalThis.ReadableStream;if(void 0===t)throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function L(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return M({start(){},async pull(e){const{done:s,value:n}=await t.next();s?e.close():e.enqueue(n)},async cancel(){await(t.return?.())}})}function N(e){if(e[Symbol.asyncIterator])return e;const t=e.getReader();return{async next(){try{const e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){const e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}const D=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)}),W="RFC3986",B=e=>String(e),U={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:B};let F=(e,t)=>(F=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),F(e,t));const X=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),H=1024;function K(e,t){if(I(e)){const s=[];for(let n=0;n<e.length;n+=1)s.push(t(e[n]));return s}return t(e)}const J={brackets:e=>String(e)+"[]",comma:"comma",indices:(e,t)=>String(e)+"["+t+"]",repeat:e=>String(e)},V=function(e,t){Array.prototype.push.apply(e,I(t)?t:[t])};let z;const G={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:(e,t,s,n,r)=>{if(0===e.length)return e;let o=e;if("symbol"==typeof e?o=Symbol.prototype.toString.call(e):"string"!=typeof e&&(o=String(e)),"iso-8859-1"===s)return escape(o).replace(/%u[0-9a-f]{4}/gi,(function(e){return"%26%23"+parseInt(e.slice(2),16)+"%3B"}));let i="";for(let e=0;e<o.length;e+=H){const t=o.length>=H?o.slice(e,e+H):o,s=[];for(let e=0;e<t.length;++e){let n=t.charCodeAt(e);45===n||46===n||95===n||126===n||n>=48&&n<=57||n>=65&&n<=90||n>=97&&n<=122||"RFC1738"===r&&(40===n||41===n)?s[s.length]=t.charAt(e):n<128?s[s.length]=X[n]:n<2048?s[s.length]=X[192|n>>6]+X[128|63&n]:n<55296||n>=57344?s[s.length]=X[224|n>>12]+X[128|n>>6&63]+X[128|63&n]:(e+=1,n=65536+((1023&n)<<10|1023&t.charCodeAt(e)),s[s.length]=X[240|n>>18]+X[128|n>>12&63]+X[128|n>>6&63]+X[128|63&n])}i+=s.join("")}return i},encodeValuesOnly:!1,format:W,formatter:B,indices:!1,serializeDate:e=>(z??(z=Function.prototype.call.bind(Date.prototype.toISOString)))(e),skipNulls:!1,strictNullHandling:!1};const Q={};function Y(e,t,s,n,r,o,i,a,l,c,u,h,d,f,p,m,g,y){let w=e,_=y,b=0,v=!1;for(;void 0!==(_=_.get(Q))&&!v;){const t=_.get(e);if(b+=1,void 0!==t){if(t===b)throw new RangeError("Cyclic object value");v=!0}void 0===_.get(Q)&&(b=0)}if("function"==typeof c?w=c(t,w):w instanceof Date?w=d?.(w):"comma"===s&&I(w)&&(w=K(w,(function(e){return e instanceof Date?d?.(e):e}))),null===w){if(o)return l&&!m?l(t,G.encoder,g,"key",f):t;w=""}if("string"==typeof(x=w)||"number"==typeof x||"boolean"==typeof x||"symbol"==typeof x||"bigint"==typeof x||function(e){return!(!e||"object"!=typeof e||!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e)))}(w)){if(l){const e=m?t:l(t,G.encoder,g,"key",f);return[p?.(e)+"="+p?.(l(w,G.encoder,g,"value",f))]}return[p?.(t)+"="+p?.(String(w))]}var x;const S=[];if(void 0===w)return S;let $;if("comma"===s&&I(w))m&&l&&(w=K(w,l)),$=[{value:w.length>0?w.join(",")||null:void 0}];else if(I(c))$=c;else{const e=Object.keys(w);$=u?e.sort(u):e}const A=a?String(t).replace(/\./g,"%2E"):String(t),O=n&&I(w)&&1===w.length?A+"[]":A;if(r&&I(w)&&0===w.length)return O+"[]";for(let t=0;t<$.length;++t){const _=$[t],v="object"==typeof _&&void 0!==_.value?_.value:w[_];if(i&&null===v)continue;const x=h&&a?_.replace(/\./g,"%2E"):_,A=I(w)?"function"==typeof s?s(O,x):O:O+(h?"."+x:"["+x+"]");y.set(e,b);const k=new WeakMap;k.set(Q,y),V(S,Y(v,A,s,n,r,o,i,a,"comma"===s&&m&&I(w)?null:l,c,u,h,d,f,p,m,g,k))}return S}function Z(e,t={}){let s=e;const n=function(e=G){if(void 0!==e.allowEmptyArrays&&"boolean"!=typeof e.allowEmptyArrays)throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(void 0!==e.encodeDotInKeys&&"boolean"!=typeof e.encodeDotInKeys)throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(null!==e.encoder&&void 0!==e.encoder&&"function"!=typeof e.encoder)throw new TypeError("Encoder has to be a function.");const t=e.charset||G.charset;if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let s=W;if(void 0!==e.format){if(!F(U,e.format))throw new TypeError("Unknown format option provided.");s=e.format}const n=U[s];let r,o=G.filter;if(("function"==typeof e.filter||I(e.filter))&&(o=e.filter),r=e.arrayFormat&&e.arrayFormat in J?e.arrayFormat:"indices"in e?e.indices?"indices":"repeat":G.arrayFormat,"commaRoundTrip"in e&&"boolean"!=typeof e.commaRoundTrip)throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const i=void 0===e.allowDots?1==!!e.encodeDotInKeys||G.allowDots:!!e.allowDots;return{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:G.addQueryPrefix,allowDots:i,allowEmptyArrays:"boolean"==typeof e.allowEmptyArrays?!!e.allowEmptyArrays:G.allowEmptyArrays,arrayFormat:r,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:G.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:void 0===e.delimiter?G.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:G.encode,encodeDotInKeys:"boolean"==typeof e.encodeDotInKeys?e.encodeDotInKeys:G.encodeDotInKeys,encoder:"function"==typeof e.encoder?e.encoder:G.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:G.encodeValuesOnly,filter:o,format:s,formatter:n,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:G.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:G.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:G.strictNullHandling}}(t);let r,o;"function"==typeof n.filter?(o=n.filter,s=o("",s)):I(n.filter)&&(o=n.filter,r=o);const i=[];if("object"!=typeof s||null===s)return"";const a=J[n.arrayFormat],l="comma"===a&&n.commaRoundTrip;r||(r=Object.keys(s)),n.sort&&r.sort(n.sort);const c=new WeakMap;for(let e=0;e<r.length;++e){const t=r[e];n.skipNulls&&null===s[t]||V(i,Y(s[t],t,a,l,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,c))}const u=i.join(n.delimiter);let h=!0===n.addQueryPrefix?"?":"";return n.charsetSentinel&&("iso-8859-1"===n.charset?h+="utf8=%26%2310003%3B&":h+="utf8=%E2%9C%93&"),u.length>0?h+u:""}let ee,te;function se(e){let t;return(ee??(t=new globalThis.TextEncoder,ee=t.encode.bind(t)))(e)}function ne(e){let t;return(te??(t=new globalThis.TextDecoder,te=t.decode.bind(t)))(e)}var re,oe;class ie{constructor(){re.set(this,void 0),oe.set(this,void 0),r(this,re,new Uint8Array),r(this,oe,null)}decode(e){if(null==e)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):"string"==typeof e?se(e):e;r(this,re,function(e){let t=0;for(const s of e)t+=s.length;const s=new Uint8Array(t);let n=0;for(const t of e)s.set(t,n),n+=t.length;return s}([o(this,re,"f"),t]));const s=[];let n;for(;null!=(n=ae(o(this,re,"f"),o(this,oe,"f")));){if(n.carriage&&null==o(this,oe,"f")){r(this,oe,n.index);continue}if(null!=o(this,oe,"f")&&(n.index!==o(this,oe,"f")+1||n.carriage)){s.push(ne(o(this,re,"f").subarray(0,o(this,oe,"f")-1))),r(this,re,o(this,re,"f").subarray(o(this,oe,"f"))),r(this,oe,null);continue}const e=null!==o(this,oe,"f")?n.preceding-1:n.preceding,t=ne(o(this,re,"f").subarray(0,e));s.push(t),r(this,re,o(this,re,"f").subarray(n.index)),r(this,oe,null)}return s}flush(){return o(this,re,"f").length?this.decode("\n"):[]}}function ae(e,t){for(let s=t??0;s<e.length;s++){if(10===e[s])return{preceding:s,index:s+1,carriage:!1};if(13===e[s])return{preceding:s,index:s+1,carriage:!0}}return null}function le(e){for(let t=0;t<e.length-1;t++){if(10===e[t]&&10===e[t+1])return t+2;if(13===e[t]&&13===e[t+1])return t+2;if(13===e[t]&&10===e[t+1]&&t+3<e.length&&13===e[t+2]&&10===e[t+3])return t+4}return-1}re=new WeakMap,oe=new WeakMap,ie.NEWLINE_CHARS=new Set(["\n","\r"]),ie.NEWLINE_REGEXP=/\r\n|[\n\r]/g;const ce={off:0,error:200,warn:300,info:400,debug:500},ue=(e,t,s)=>{var n,r;if(e)return n=ce,r=e,Object.prototype.hasOwnProperty.call(n,r)?e:void me(s).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(ce))}`)};function he(){}function de(e,t,s){return!t||ce[e]>ce[s]?he:t[e].bind(t)}const fe={error:he,warn:he,info:he,debug:he};let pe=new WeakMap;function me(e){const t=e.logger,s=e.logLevel??"off";if(!t)return fe;const n=pe.get(t);if(n&&n[0]===s)return n[1];const r={error:de("error",t,s),warn:de("warn",t,s),info:de("info",t,s),debug:de("debug",t,s)};return pe.set(t,[s,r]),r}const ge=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map((([e,t])=>[e,"authorization"===e.toLowerCase()||"cookie"===e.toLowerCase()||"set-cookie"===e.toLowerCase()?"***":t])))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);var ye,we,_e;class be{constructor(e,t,s){this.iterator=e,ye.set(this,void 0),this.controller=t,r(this,ye,s)}static fromSSEResponse(e,t,s){let n=!1;const r=s?me(s):console;return new be((async function*(){if(n)throw new c("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let s=!1;try{for await(const n of async function*(e,t){if(!e.body){if(t.abort(),void 0!==globalThis.navigator&&"ReactNative"===globalThis.navigator.product)throw new c("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new c("Attempted to iterate over a response with no body")}const s=new ve,n=new ie,r=N(e.body);for await(const e of async function*(e){let t=new Uint8Array;for await(const s of e){if(null==s)continue;const e=s instanceof ArrayBuffer?new Uint8Array(s):"string"==typeof s?se(s):s;let n,r=new Uint8Array(t.length+e.length);for(r.set(t),r.set(e,t.length),t=r;-1!==(n=le(t));)yield t.slice(0,n),t=t.slice(n)}t.length>0&&(yield t)}(r))for(const t of n.decode(e)){const e=s.decode(t);e&&(yield e)}for(const e of n.flush()){const t=s.decode(e);t&&(yield t)}}(e,t))if(!s)if(n.data.startsWith("[DONE]"))s=!0;else if(null!==n.event&&n.event.startsWith("thread.")){let e;try{e=JSON.parse(n.data)}catch(e){throw console.error("Could not parse message into JSON:",n.data),console.error("From chunk:",n.raw),e}if("error"==n.event)throw new u(void 0,e.error,e.message,void 0);yield{event:n.event,data:e}}else{let t;try{t=JSON.parse(n.data)}catch(e){throw r.error("Could not parse message into JSON:",n.data),r.error("From chunk:",n.raw),e}if(t&&t.error)throw new u(void 0,t.error,void 0,e.headers);yield t}s=!0}catch(e){if(a(e))return;throw e}finally{s||t.abort()}}),t,s)}static fromReadableStream(e,t,s){let n=!1;return new be((async function*(){if(n)throw new c("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let s=!1;try{for await(const t of async function*(){const t=new ie,s=N(e);for await(const e of s)for(const s of t.decode(e))yield s;for(const e of t.flush())yield e}())s||t&&(yield JSON.parse(t));s=!0}catch(e){if(a(e))return;throw e}finally{s||t.abort()}}),t,s)}[(ye=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[],t=[],s=this.iterator(),n=n=>({next:()=>{if(0===n.length){const n=s.next();e.push(n),t.push(n)}return n.shift()}});return[new be((()=>n(e)),this.controller,o(this,ye,"f")),new be((()=>n(t)),this.controller,o(this,ye,"f"))]}toReadableStream(){const e=this;let t;return M({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{const{value:s,done:n}=await t.next();if(n)return e.close();const r=se(JSON.stringify(s)+"\n");e.enqueue(r)}catch(t){e.error(t)}},async cancel(){await(t.return?.())}})}}class ve{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;const e={event:this.event,data:this.data.join("\n"),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,s,n]=function(e,t){const s=e.indexOf(t);if(-1!==s)return[e.substring(0,s),t,e.substring(s+t.length)];return[e,"",""]}(e,":");return n.startsWith(" ")&&(n=n.substring(1)),"event"===t?this.event=n:"data"===t&&this.data.push(n),null}}async function xe(e,t){const{response:s,requestLogID:n,retryOfRequestLogID:r,startTime:o}=t,i=await(async()=>{if(t.options.stream)return me(e).debug("response",s.status,s.url,s.headers,s.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(s,t.controller,e):be.fromSSEResponse(s,t.controller,e);if(204===s.status)return null;if(t.options.__binaryResponse)return s;const n=s.headers.get("content-type"),r=n?.split(";")[0]?.trim();if(r?.includes("application/json")||r?.endsWith("+json")){return Se(await s.json(),s)}return await s.text()})();return me(e).debug(`[${n}] response parsed`,ge({retryOfRequestLogID:r,url:s.url,status:s.status,body:i,durationMs:Date.now()-o})),i}function Se(e,t){return!e||"object"!=typeof e||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get("x-request-id"),enumerable:!1})}class $e extends Promise{constructor(e,t,s=xe){super((e=>{e(null)})),this.responsePromise=t,this.parseResponse=s,we.set(this,void 0),r(this,we,e)}_thenUnwrap(e){return new $e(o(this,we,"f"),this.responsePromise,(async(t,s)=>Se(e(await this.parseResponse(t,s),s),s.response)))}asResponse(){return this.responsePromise.then((e=>e.response))}async withResponse(){const[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(o(this,we,"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)}}we=new WeakMap;class Ae{constructor(e,t,s,n){_e.set(this,void 0),r(this,_e,e),this.options=n,this.response=t,this.body=s}hasNextPage(){return!!this.getPaginatedItems().length&&null!=this.nextPageRequestOptions()}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new c("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await o(this,_e,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(_e=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class Ie extends $e{constructor(e,t,s){super(e,t,(async(e,t)=>new s(e,t.response,await xe(e,t),t.options)))}async*[Symbol.asyncIterator](){const e=await(this);for await(const t of e)yield t}}class Oe extends Ae{constructor(e,t,s,n){super(e,t,s,n),this.data=s.data||[],this.object=s.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class ke extends Ae{constructor(e,t,s,n){super(e,t,s,n),this.data=s.data||[],this.has_more=s.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return!1!==this.has_more&&super.hasNextPage()}nextPageRequestOptions(){const e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...k(this.options.query),after:t}}:null}}class Re extends Ae{constructor(e,t,s,n){super(e,t,s,n),this.data=s.data||[],this.has_more=s.has_more||!1,this.last_id=s.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return!1!==this.has_more&&super.hasNextPage()}nextPageRequestOptions(){const e=this.last_id;return e?{...this.options,query:{...k(this.options.query),after:e}}:null}}const Ee=()=>{if("undefined"==typeof File){const{process:e}=globalThis,t="string"==typeof e?.versions?.node&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Pe(e,t,s){return Ee(),new File(e,t??"unknown_file",s)}function Ce(e){return("object"==typeof e&&null!==e&&("name"in e&&e.name&&String(e.name)||"url"in e&&e.url&&String(e.url)||"filename"in e&&e.filename&&String(e.filename)||"path"in e&&e.path&&String(e.path))||"").split(/[\\/]/).pop()||void 0}const Te=e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator],qe=async(e,t)=>({...e,body:await Me(e.body,t)}),je=new WeakMap;const Me=async(e,t)=>{if(!await function(e){const t="function"==typeof e?e:e.fetch,s=je.get(t);if(s)return s;const n=(async()=>{try{const e="Response"in t?t.Response:(await t("data:,")).constructor,s=new FormData;return s.toString()!==await new e(s).text()}catch{return!0}})();return je.set(t,n),n}(t))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const s=new FormData;return await Promise.all(Object.entries(e||{}).map((([e,t])=>Le(s,e,t)))),s},Le=async(e,t,s)=>{if(void 0!==s){if(null==s)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if("string"==typeof s||"number"==typeof s||"boolean"==typeof s)e.append(t,String(s));else if(s instanceof Response)e.append(t,Pe([await s.blob()],Ce(s)));else if(Te(s))e.append(t,Pe([await new Response(L(s)).blob()],Ce(s)));else if((e=>e instanceof Blob&&"name"in e)(s))e.append(t,s,Ce(s));else if(Array.isArray(s))await Promise.all(s.map((s=>Le(e,t+"[]",s))));else{if("object"!=typeof s)throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${s} instead`);await Promise.all(Object.entries(s).map((([s,n])=>Le(e,`${t}[${s}]`,n))))}}},Ne=e=>null!=e&&"object"==typeof e&&"number"==typeof e.size&&"string"==typeof e.type&&"function"==typeof e.text&&"function"==typeof e.slice&&"function"==typeof e.arrayBuffer;async function De(e){let t=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(Ne(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else{if(!Te(e)){const t=e?.constructor?.name;throw new Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:""}${function(e){if("object"!=typeof e||null===e)return"";const t=Object.getOwnPropertyNames(e);return`; props: [${t.map((e=>`"${e}"`)).join(", ")}]`}(e)}`)}for await(const s of e)t.push(...await De(s))}return t}class We{constructor(e){this._client=e}}function Be(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const Ue=Object.freeze(Object.create(null)),Fe=(e=Be)=>function(t,...s){if(1===t.length)return t[0];let n=!1;const r=[],o=t.reduce(((t,o,i)=>{/[?#]/.test(o)&&(n=!0);const a=s[i];let l=(n?encodeURIComponent:e)(""+a);return i!==s.length&&(null==a||"object"==typeof a&&a.toString===Object.getPrototypeOf(Object.getPrototypeOf(a.hasOwnProperty??Ue)??Ue)?.toString)&&(l=a+"",r.push({start:t.length+o.length,length:l.length,error:`Value of type ${Object.prototype.toString.call(a).slice(8,-1)} is not a valid path parameter`})),t+o+(i===s.length?"":l)}),""),i=o.split(/[?#]/,1)[0],a=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;let l;for(;null!==(l=a.exec(i));)r.push({start:l.index,length:l[0].length,error:`Value "${l[0]}" can't be safely passed as a path parameter`});if(r.sort(((e,t)=>e.start-t.start)),r.length>0){let e=0;const t=r.reduce(((t,s)=>{const n=" ".repeat(s.start-e),r="^".repeat(s.length);return e=s.start+s.length,t+n+r}),"");throw new c(`Path parameters result in path with invalid segments:\n${r.map((e=>e.error)).join("\n")}\n${o}\n${t}`)}return o},Xe=Fe(Be);let He=class extends We{list(e,t={},s){return this._client.getAPIList(Xe`/chat/completions/${e}/messages`,ke,{query:t,...s})}};function Ke(e){return void 0!==e&&"function"in e&&void 0!==e.function}function Je(e){return"auto-parseable-response-format"===e?.$brand}function Ve(e){return"auto-parseable-tool"===e?.$brand}function ze(e,t){const s=e.choices.map((e=>{if("length"===e.finish_reason)throw new x;if("content_filter"===e.finish_reason)throw new S;return Ze(e.message.tool_calls),{...e,message:{...e.message,...e.message.tool_calls?{tool_calls:e.message.tool_calls?.map((e=>function(e,t){const s=e.tools?.find((e=>Ke(e)&&e.function?.name===t.function.name));return{...t,function:{...t.function,parsed_arguments:Ve(s)?s.$parseRaw(t.function.arguments):s?.function.strict?JSON.parse(t.function.arguments):null}}}(t,e)))??void 0}:void 0,parsed:e.message.content&&!e.message.refusal?Ge(t,e.message.content):null}}}));return{...e,choices:s}}function Ge(e,t){if("json_schema"!==e.response_format?.type)return null;if("json_schema"===e.response_format?.type){if("$parseRaw"in e.response_format){return e.response_format.$parseRaw(t)}return JSON.parse(t)}return null}function Qe(e,t){if(!e||!("tools"in e)||!e.tools)return!1;const s=e.tools?.find((e=>Ke(e)&&e.function?.name===t.function.name));return Ke(s)&&(Ve(s)||s?.function.strict||!1)}function Ye(e){return!!Je(e.response_format)||(e.tools?.some((e=>Ve(e)||"function"===e.type&&!0===e.function.strict))??!1)}function Ze(e){for(const t of e||[])if("function"!==t.type)throw new c(`Currently only \`function\` tool calls are supported; Received \`${t.type}\``)}const et=e=>"assistant"===e?.role,tt=e=>"tool"===e?.role;var st,nt,rt,ot,it,at,lt,ct,ut,ht,dt,ft,pt,mt,gt,yt,wt,_t,bt,vt,xt;class St{constructor(){st.add(this),this.controller=new AbortController,nt.set(this,void 0),rt.set(this,(()=>{})),ot.set(this,(()=>{})),it.set(this,void 0),at.set(this,(()=>{})),lt.set(this,(()=>{})),ct.set(this,{}),ut.set(this,!1),ht.set(this,!1),dt.set(this,!1),ft.set(this,!1),r(this,nt,new Promise(((e,t)=>{r(this,rt,e),r(this,ot,t)}))),r(this,it,new Promise(((e,t)=>{r(this,at,e),r(this,lt,t)}))),o(this,nt,"f").catch((()=>{})),o(this,it,"f").catch((()=>{}))}_run(e){setTimeout((()=>{e().then((()=>{this._emitFinal(),this._emit("end")}),o(this,st,"m",pt).bind(this))}),0)}_connected(){this.ended||(o(this,rt,"f").call(this),this._emit("connect"))}get ended(){return o(this,ut,"f")}get errored(){return o(this,ht,"f")}get aborted(){return o(this,dt,"f")}abort(){this.controller.abort()}on(e,t){return(o(this,ct,"f")[e]||(o(this,ct,"f")[e]=[])).push({listener:t}),this}off(e,t){const s=o(this,ct,"f")[e];if(!s)return this;const n=s.findIndex((e=>e.listener===t));return n>=0&&s.splice(n,1),this}once(e,t){return(o(this,ct,"f")[e]||(o(this,ct,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise(((t,s)=>{r(this,ft,!0),"error"!==e&&this.once("error",s),this.once(e,t)}))}async done(){r(this,ft,!0),await o(this,it,"f")}_emit(e,...t){if(o(this,ut,"f"))return;"end"===e&&(r(this,ut,!0),o(this,at,"f").call(this));const s=o(this,ct,"f")[e];if(s&&(o(this,ct,"f")[e]=s.filter((e=>!e.once)),s.forEach((({listener:e})=>e(...t)))),"abort"===e){const e=t[0];return o(this,ft,"f")||s?.length||Promise.reject(e),o(this,ot,"f").call(this,e),o(this,lt,"f").call(this,e),void this._emit("end")}if("error"===e){const e=t[0];o(this,ft,"f")||s?.length||Promise.reject(e),o(this,ot,"f").call(this,e),o(this,lt,"f").call(this,e),this._emit("end")}}_emitFinal(){}}function $t(e){return"function"==typeof e.parse}nt=new WeakMap,rt=new WeakMap,ot=new WeakMap,it=new WeakMap,at=new WeakMap,lt=new WeakMap,ct=new WeakMap,ut=new WeakMap,ht=new WeakMap,dt=new WeakMap,ft=new WeakMap,st=new WeakSet,pt=function(e){if(r(this,ht,!0),e instanceof Error&&"AbortError"===e.name&&(e=new h),e instanceof h)return r(this,dt,!0),this._emit("abort",e);if(e instanceof c)return this._emit("error",e);if(e instanceof Error){const t=new c(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new c(String(e)))};const At=10;class It extends St{constructor(){super(...arguments),mt.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);const 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),tt(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(et(e)&&e.tool_calls)for(const t of e.tool_calls)"function"===t.type&&this._emit("functionToolCall",t.function)}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new c("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),o(this,mt,"m",gt).call(this)}async finalMessage(){return await this.done(),o(this,mt,"m",yt).call(this)}async finalFunctionToolCall(){return await this.done(),o(this,mt,"m",wt).call(this)}async finalFunctionToolCallResult(){return await this.done(),o(this,mt,"m",_t).call(this)}async totalUsage(){return await this.done(),o(this,mt,"m",bt).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=o(this,mt,"m",yt).call(this);t&&this._emit("finalMessage",t);const s=o(this,mt,"m",gt).call(this);s&&this._emit("finalContent",s);const n=o(this,mt,"m",wt).call(this);n&&this._emit("finalFunctionToolCall",n);const r=o(this,mt,"m",_t).call(this);null!=r&&this._emit("finalFunctionToolCallResult",r),this._chatCompletions.some((e=>e.usage))&&this._emit("totalUsage",o(this,mt,"m",bt).call(this))}async _createChatCompletion(e,t,s){const n=s?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",(()=>this.controller.abort()))),o(this,mt,"m",vt).call(this,t);const r=await e.chat.completions.create({...t,stream:!1},{...s,signal:this.controller.signal});return this._connected(),this._addChatCompletion(ze(r,t))}async _runChatCompletion(e,t,s){for(const e of t.messages)this._addMessage(e,!1);return await this._createChatCompletion(e,t,s)}async _runTools(e,t,s){const n="tool",{tool_choice:r="auto",stream:i,...a}=t,l="string"!=typeof r&&"function"===r.type&&r?.function?.name,{maxChatCompletions:u=At}=s||{},h=t.tools.map((e=>{if(Ve(e)){if(!e.$callback)throw new c("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:e.$callback,name:e.function.name,description:e.function.description||"",parameters:e.function.parameters,parse:e.$parseRaw,strict:!0}}}return e})),d={};for(const e of h)"function"===e.type&&(d[e.function.name||e.function.function.name]=e.function);const f="tools"in t?h.map((e=>"function"===e.type?{type:"function",function:{name:e.function.name||e.function.function.name,parameters:e.function.parameters,description:e.function.description,strict:e.function.strict}}:e)):void 0;for(const e of t.messages)this._addMessage(e,!1);for(let t=0;t<u;++t){const t=await this._createChatCompletion(e,{...a,tool_choice:r,tools:f,messages:[...this.messages]},s),i=t.choices[0]?.message;if(!i)throw new c("missing message in ChatCompletion response");if(!i.tool_calls?.length)return;for(const e of i.tool_calls){if("function"!==e.type)continue;const t=e.id,{name:s,arguments:r}=e.function,i=d[s];if(!i){const e=`Invalid tool_call: ${JSON.stringify(s)}. Available options are: ${Object.keys(d).map((e=>JSON.stringify(e))).join(", ")}. Please try again`;this._addMessage({role:n,tool_call_id:t,content:e});continue}if(l&&l!==s){const e=`Invalid tool_call: ${JSON.stringify(s)}. ${JSON.stringify(l)} requested. Please try again`;this._addMessage({role:n,tool_call_id:t,content:e});continue}let a;try{a=$t(i)?await i.parse(r):r}catch(e){const s=e instanceof Error?e.message:String(e);this._addMessage({role:n,tool_call_id:t,content:s});continue}const c=await i.function(a,this),u=o(this,mt,"m",xt).call(this,c);if(this._addMessage({role:n,tool_call_id:t,content:u}),l)return}}}}mt=new WeakSet,gt=function(){return o(this,mt,"m",yt).call(this).content??null},yt=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(et(t)){return{...t,content:t.content??null,refusal:t.refusal??null}}}throw new c("stream ended without producing a ChatCompletionMessage with role=assistant")},wt=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(et(t)&&t?.tool_calls?.length)return t.tool_calls.filter((e=>"function"===e.type)).at(-1)?.function}},_t=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(tt(t)&&null!=t.content&&"string"==typeof t.content&&this.messages.some((e=>"assistant"===e.role&&e.tool_calls?.some((e=>"function"===e.type&&e.id===t.tool_call_id)))))return t.content}},bt=function(){const e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{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},vt=function(e){if(null!=e.n&&e.n>1)throw new c("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},xt=function(e){return"string"==typeof e?e:void 0===e?"undefined":JSON.stringify(e)};class Ot extends It{static runTools(e,t,s){const n=new Ot,r={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run((()=>n._runTools(e,t,r))),n}_addMessage(e,t=!0){super._addMessage(e,t),et(e)&&e.content&&this._emit("content",e.content)}}const kt=1,Rt=2,Et=4,Pt=8,Ct=16,Tt=32,qt=64,jt=128,Mt=256,Lt=511;class Nt extends Error{}class Dt extends Error{}const Wt=(e,t)=>{const s=e.length;let n=0;const r=e=>{throw new Nt(`${e} at position ${n}`)},o=e=>{throw new Dt(`${e} at position ${n}`)},i=()=>(h(),n>=s&&r("Unexpected end of input"),'"'===e[n]?a():"{"===e[n]?l():"["===e[n]?c():"null"===e.substring(n,n+4)||Ct&t&&s-n<4&&"null".startsWith(e.substring(n))?(n+=4,null):"true"===e.substring(n,n+4)||Tt&t&&s-n<4&&"true".startsWith(e.substring(n))?(n+=4,!0):"false"===e.substring(n,n+5)||Tt&t&&s-n<5&&"false".startsWith(e.substring(n))?(n+=5,!1):"Infinity"===e.substring(n,n+8)||jt&t&&s-n<8&&"Infinity".startsWith(e.substring(n))?(n+=8,1/0):"-Infinity"===e.substring(n,n+9)||Mt&t&&1<s-n&&s-n<9&&"-Infinity".startsWith(e.substring(n))?(n+=9,-1/0):"NaN"===e.substring(n,n+3)||qt&t&&s-n<3&&"NaN".startsWith(e.substring(n))?(n+=3,NaN):u()),a=()=>{const i=n;let a=!1;for(n++;n<s&&('"'!==e[n]||a&&"\\"===e[n-1]);)a="\\"===e[n]&&!a,n++;if('"'==e.charAt(n))try{return JSON.parse(e.substring(i,++n-Number(a)))}catch(e){o(String(e))}else if(kt&t)try{return JSON.parse(e.substring(i,n-Number(a))+'"')}catch(t){return JSON.parse(e.substring(i,e.lastIndexOf("\\"))+'"')}r("Unterminated string literal")},l=()=>{n++,h();const o={};try{for(;"}"!==e[n];){if(h(),n>=s&&Pt&t)return o;const r=a();h(),n++;try{const e=i();Object.defineProperty(o,r,{value:e,writable:!0,enumerable:!0,configurable:!0})}catch(e){if(Pt&t)return o;throw e}h(),","===e[n]&&n++}}catch(e){if(Pt&t)return o;r("Expected '}' at end of object")}return n++,o},c=()=>{n++;const s=[];try{for(;"]"!==e[n];)s.push(i()),h(),","===e[n]&&n++}catch(e){if(Et&t)return s;r("Expected ']' at end of array")}return n++,s},u=()=>{if(0===n){"-"===e&&Rt&t&&r("Not sure what '-' is");try{return JSON.parse(e)}catch(s){if(Rt&t)try{return"."===e[e.length-1]?JSON.parse(e.substring(0,e.lastIndexOf("."))):JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch(e){}o(String(s))}}const i=n;for("-"===e[n]&&n++;e[n]&&!",]}".includes(e[n]);)n++;n!=s||Rt&t||r("Unterminated number literal");try{return JSON.parse(e.substring(i,n))}catch(s){"-"===e.substring(i,n)&&Rt&t&&r("Not sure what '-' is");try{return JSON.parse(e.substring(i,e.lastIndexOf("e")))}catch(e){o(String(e))}}},h=()=>{for(;n<s&&" \n\r\t".includes(e[n]);)n++};return i()},Bt=e=>function(e,t=Lt){if("string"!=typeof e)throw new TypeError("expecting str, got "+typeof e);if(!e.trim())throw new Error(`${e} is empty`);return Wt(e.trim(),t)}(e,Lt^Rt);var Ut,Ft,Xt,Ht,Kt,Jt,Vt,zt,Gt,Qt,Yt,Zt;class es extends It{constructor(e){super(),Ut.add(this),Ft.set(this,void 0),Xt.set(this,void 0),Ht.set(this,void 0),r(this,Ft,e),r(this,Xt,[])}get currentChatCompletionSnapshot(){return o(this,Ht,"f")}static fromReadableStream(e){const t=new es(null);return t._run((()=>t._fromReadableStream(e))),t}static createChatCompletion(e,t,s){const n=new es(t);return n._run((()=>n._runChatCompletion(e,{...t,stream:!0},{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}}))),n}async _createChatCompletion(e,t,s){super._createChatCompletion;const n=s?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",(()=>this.controller.abort()))),o(this,Ut,"m",Kt).call(this);const r=await e.chat.completions.create({...t,stream:!0},{...s,signal:this.controller.signal});this._connected();for await(const e of r)o(this,Ut,"m",Vt).call(this,e);if(r.controller.signal?.aborted)throw new h;return this._addChatCompletion(o(this,Ut,"m",Qt).call(this))}async _fromReadableStream(e,t){const s=t?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",(()=>this.controller.abort()))),o(this,Ut,"m",Kt).call(this),this._connected();const n=be.fromReadableStream(e,this.controller);let r;for await(const e of n)r&&r!==e.id&&this._addChatCompletion(o(this,Ut,"m",Qt).call(this)),o(this,Ut,"m",Vt).call(this,e),r=e.id;if(n.controller.signal?.aborted)throw new h;return this._addChatCompletion(o(this,Ut,"m",Qt).call(this))}[(Ft=new WeakMap,Xt=new WeakMap,Ht=new WeakMap,Ut=new WeakSet,Kt=function(){this.ended||r(this,Ht,void 0)},Jt=function(e){let t=o(this,Xt,"f")[e.index];return t||(t={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},o(this,Xt,"f")[e.index]=t,t)},Vt=function(e){if(this.ended)return;const t=o(this,Ut,"m",Zt).call(this,e);this._emit("chunk",e,t);for(const s of e.choices){const e=t.choices[s.index];null!=s.delta.content&&"assistant"===e.message?.role&&e.message?.content&&(this._emit("content",s.delta.content,e.message.content),this._emit("content.delta",{delta:s.delta.content,snapshot:e.message.content,parsed:e.message.parsed})),null!=s.delta.refusal&&"assistant"===e.message?.role&&e.message?.refusal&&this._emit("refusal.delta",{delta:s.delta.refusal,snapshot:e.message.refusal}),null!=s.logprobs?.content&&"assistant"===e.message?.role&&this._emit("logprobs.content.delta",{content:s.logprobs?.content,snapshot:e.logprobs?.content??[]}),null!=s.logprobs?.refusal&&"assistant"===e.message?.role&&this._emit("logprobs.refusal.delta",{refusal:s.logprobs?.refusal,snapshot:e.logprobs?.refusal??[]});const n=o(this,Ut,"m",Jt).call(this,e);e.finish_reason&&(o(this,Ut,"m",Gt).call(this,e),null!=n.current_tool_call_index&&o(this,Ut,"m",zt).call(this,e,n.current_tool_call_index));for(const t of s.delta.tool_calls??[])n.current_tool_call_index!==t.index&&(o(this,Ut,"m",Gt).call(this,e),null!=n.current_tool_call_index&&o(this,Ut,"m",zt).call(this,e,n.current_tool_call_index)),n.current_tool_call_index=t.index;for(const t of s.delta.tool_calls??[]){const s=e.message.tool_calls?.[t.index];s?.type&&("function"===s?.type&&this._emit("tool_calls.function.arguments.delta",{name:s.function?.name,index:t.index,arguments:s.function.arguments,parsed_arguments:s.function.parsed_arguments,arguments_delta:t.function?.arguments??""}))}}},zt=function(e,t){if(o(this,Ut,"m",Jt).call(this,e).done_tool_calls.has(t))return;const s=e.message.tool_calls?.[t];if(!s)throw new Error("no tool call snapshot");if(!s.type)throw new Error("tool call snapshot missing `type`");if("function"===s.type){const e=o(this,Ft,"f")?.tools?.find((e=>Ke(e)&&e.function.name===s.function.name));this._emit("tool_calls.function.arguments.done",{name:s.function.name,index:t,arguments:s.function.arguments,parsed_arguments:Ve(e)?e.$parseRaw(s.function.arguments):e?.function.strict?JSON.parse(s.function.arguments):null})}else s.type},Gt=function(e){const t=o(this,Ut,"m",Jt).call(this,e);if(e.message.content&&!t.content_done){t.content_done=!0;const s=o(this,Ut,"m",Yt).call(this);this._emit("content.done",{content:e.message.content,parsed:s?s.$parseRaw(e.message.content):null})}e.message.refusal&&!t.refusal_done&&(t.refusal_done=!0,this._emit("refusal.done",{refusal:e.message.refusal})),e.logprobs?.content&&!t.logprobs_content_done&&(t.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:e.logprobs.content})),e.logprobs?.refusal&&!t.logprobs_refusal_done&&(t.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:e.logprobs.refusal}))},Qt=function(){if(this.ended)throw new c("stream has ended, this shouldn't happen");const e=o(this,Ht,"f");if(!e)throw new c("request ended without sending any chunks");return r(this,Ht,void 0),r(this,Xt,[]),function(e,t){const{id:s,choices:n,created:r,model:o,system_fingerprint:i,...a}=e,l={...a,id:s,choices:n.map((({message:t,finish_reason:s,index:n,logprobs:r,...o})=>{if(!s)throw new c(`missing finish_reason for choice ${n}`);const{content:i=null,function_call:a,tool_calls:l,...u}=t,h=t.role;if(!h)throw new c(`missing role for choice ${n}`);if(a){const{arguments:e,name:l}=a;if(null==e)throw new c(`missing function_call.arguments for choice ${n}`);if(!l)throw new c(`missing function_call.name for choice ${n}`);return{...o,message:{content:i,function_call:{arguments:e,name:l},role:h,refusal:t.refusal??null},finish_reason:s,index:n,logprobs:r}}return l?{...o,index:n,finish_reason:s,logprobs:r,message:{...u,role:h,content:i,refusal:t.refusal??null,tool_calls:l.map(((t,s)=>{const{function:r,type:o,id:i,...a}=t,{arguments:l,name:u,...h}=r||{};if(null==i)throw new c(`missing choices[${n}].tool_calls[${s}].id\n${ts(e)}`);if(null==o)throw new c(`missing choices[${n}].tool_calls[${s}].type\n${ts(e)}`);if(null==u)throw new c(`missing choices[${n}].tool_calls[${s}].function.name\n${ts(e)}`);if(null==l)throw new c(`missing choices[${n}].tool_calls[${s}].function.arguments\n${ts(e)}`);return{...a,id:i,type:o,function:{...h,name:u,arguments:l}}}))}}:{...o,message:{...u,content:i,role:h,refusal:t.refusal??null},finish_reason:s,index:n,logprobs:r}})),created:r,model:o,object:"chat.completion",...i?{system_fingerprint:i}:{}};return function(e,t){return t&&Ye(t)?ze(e,t):{...e,choices:e.choices.map((e=>(Ze(e.message.tool_calls),{...e,message:{...e.message,parsed:null,...e.message.tool_calls?{tool_calls:e.message.tool_calls}:void 0}})))}}(l,t)}(e,o(this,Ft,"f"))},Yt=function(){const e=o(this,Ft,"f")?.response_format;return Je(e)?e:null},Zt=function(e){var t,s,n,i;let a=o(this,Ht,"f");const{choices:l,...c}=e;a?Object.assign(a,c):a=r(this,Ht,{...c,choices:[]});for(const{delta:r,finish_reason:l,index:c,logprobs:u=null,...h}of e.choices){let e=a.choices[c];if(e||(e=a.choices[c]={finish_reason:l,index:c,message:{},logprobs:u,...h}),u)if(e.logprobs){const{content:n,refusal:r,...o}=u;Object.assign(e.logprobs,o),n&&((t=e.logprobs).content??(t.content=[]),e.logprobs.content.push(...n)),r&&((s=e.logprobs).refusal??(s.refusal=[]),e.logprobs.refusal.push(...r))}else e.logprobs=Object.assign({},u);if(l&&(e.finish_reason=l,o(this,Ft,"f")&&Ye(o(this,Ft,"f")))){if("length"===l)throw new x;if("content_filter"===l)throw new S}if(Object.assign(e,h),!r)continue;const{content:d,refusal:f,function_call:p,role:m,tool_calls:g,...y}=r;if(Object.assign(e.message,y),f&&(e.message.refusal=(e.message.refusal||"")+f),m&&(e.message.role=m),p&&(e.message.function_call?(p.name&&(e.message.function_call.name=p.name),p.arguments&&((n=e.message.function_call).arguments??(n.arguments=""),e.message.function_call.arguments+=p.arguments)):e.message.function_call=p),d&&(e.message.content=(e.message.content||"")+d,!e.message.refusal&&o(this,Ut,"m",Yt).call(this)&&(e.message.parsed=Bt(e.message.content))),g){e.message.tool_calls||(e.message.tool_calls=[]);for(const{index:t,id:s,type:n,function:r,...a}of g){const l=(i=e.message.tool_calls)[t]??(i[t]={});Object.assign(l,a),s&&(l.id=s),n&&(l.type=n),r&&(l.function??(l.function={name:r.name??"",arguments:""})),r?.name&&(l.function.name=r.name),r?.arguments&&(l.function.arguments+=r.arguments,Qe(o(this,Ft,"f"),l)&&(l.function.parsed_arguments=Bt(l.function.arguments)))}}}return a},Symbol.asyncIterator)](){const e=[],t=[];let s=!1;return this.on("chunk",(s=>{const n=t.shift();n?n.resolve(s):e.push(s)})),this.on("end",(()=>{s=!0;for(const e of t)e.resolve(void 0);t.length=0})),this.on("abort",(e=>{s=!0;for(const s of t)s.reject(e);t.length=0})),this.on("error",(e=>{s=!0;for(const s of t)s.reject(e);t.length=0})),{next:async()=>{if(!e.length)return s?{value:void 0,done:!0}:new Promise(((e,s)=>t.push({resolve:e,reject:s}))).then((e=>e?{value:e,done:!1}:{value:void 0,done:!0}));return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new be(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function ts(e){return JSON.stringify(e)}class ss extends es{static fromReadableStream(e){const t=new ss(null);return t._run((()=>t._fromReadableStream(e))),t}static runTools(e,t,s){const n=new ss(t),r={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run((()=>n._runTools(e,t,r))),n}}let ns=class extends We{constructor(){super(...arguments),this.messages=new He(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(Xe`/chat/completions/${e}`,t)}update(e,t,s){return this._client.post(Xe`/chat/completions/${e}`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/chat/completions",ke,{query:e,...t})}delete(e,t){return this._client.delete(Xe`/chat/completions/${e}`,t)}parse(e,t){return function(e){for(const t of e??[]){if("function"!==t.type)throw new c(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(!0!==t.function.strict)throw new c(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap((t=>ze(t,e)))}runTools(e,t){return e.stream?ss.runTools(this._client,e,t):Ot.runTools(this._client,e,t)}stream(e,t){return es.createChatCompletion(this._client,e,t)}};ns.Messages=He;class rs extends We{constructor(){super(...arguments),this.completions=new ns(this._client)}}rs.Completions=ns;const os=Symbol("brand.privateNullableHeaders");function*is(e){if(!e)return;if(os in e){const{values:t,nulls:s}=e;yield*t.entries();for(const e of s)yield[e,null];return}let t,s=!1;e instanceof Headers?t=e.entries():O(e)?t=e:(s=!0,t=Object.entries(e??{}));for(let e of t){const t=e[0];if("string"!=typeof t)throw new TypeError("expected header name to be a string");const n=O(e[1])?e[1]:[e[1]];let r=!1;for(const e of n)void 0!==e&&(s&&!r&&(r=!0,yield[t,null]),yield[t,e])}}const as=e=>{const t=new Headers,s=new Set;for(const n of e){const e=new Set;for(const[r,o]of is(n)){const n=r.toLowerCase();e.has(n)||(t.delete(r),e.add(n)),null===o?(t.delete(r),s.add(n)):(t.append(r,o),s.delete(n))}}return{[os]:!0,values:t,nulls:s}};class ls extends We{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:as([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}}class cs extends We{create(e,t){return this._client.post("/audio/transcriptions",qe({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}}class us extends We{create(e,t){return this._client.post("/audio/translations",qe({body:e,...t,__metadata:{model:e.model}},this._client))}}class hs extends We{constructor(){super(...arguments),this.transcriptions=new cs(this._client),this.translations=new us(this._client),this.speech=new ls(this._client)}}hs.Transcriptions=cs,hs.Translations=us,hs.Speech=ls;class ds extends We{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(Xe`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",ke,{query:e,...t})}cancel(e,t){return this._client.post(Xe`/batches/${e}/cancel`,t)}}class fs extends We{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:as([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(Xe`/assistants/${e}`,{...t,headers:as([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,s){return this._client.post(Xe`/assistants/${e}`,{body:t,...s,headers:as([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",ke,{query:e,...t,headers:as([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(Xe`/assistants/${e}`,{...t,headers:as([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class ps extends We{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:as([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class ms extends We{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:as([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}let gs=class extends We{constructor(){super(...arguments),this.sessions=new ps(this._client),this.transcriptionSessions=new ms(this._client)}};gs.Sessions=ps,gs.TranscriptionSessions=ms;class ys extends We{create(e,t,s){return this._client.post(Xe`/threads/${e}/messages`,{body:t,...s,headers:as([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,t,s){const{thread_id:n}=t;return this._client.get(Xe`/threads/${n}/messages/${e}`,{...s,headers:as([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,t,s){const{thread_id:n,...r}=t;return this._client.post(Xe`/threads/${n}/messages/${e}`,{body:r,...s,headers:as([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t={},s){return this._client.getAPIList(Xe`/threads/${e}/messages`,ke,{query:t,...s,headers:as([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,t,s){const{thread_id:n}=t;return this._client.delete(Xe`/threads/${n}/messages/${e}`,{...s,headers:as([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}class ws extends We{retrieve(e,t,s){const{thread_id:n,run_id:r,...o}=t;return this._client.get(Xe`/threads/${n}/runs/${r}/steps/${e}`,{query:o,...s,headers:as([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t,s){const{thread_id:n,...r}=t;return this._client.getAPIList(Xe`/threads/${n}/runs/${e}/steps`,ke,{query:r,...s,headers:as([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}const _s=e=>void 0!==globalThis.process?globalThis.process.env?.[e]?.trim()??void 0:void 0!==globalThis.Deno?globalThis.Deno.env?.get?.(e)?.trim():void 0;var bs,vs,xs,Ss,$s,As,Is,Os,ks,Rs,Es,Ps,Cs,Ts,qs,js,Ms,Ls,Ns,Ds,Ws,Bs,Us;class Fs extends St{constructor(){super(...arguments),bs.add(this),xs.set(this,[]),Ss.set(this,{}),$s.set(this,{}),As.set(this,void 0),Is.set(this,void 0),Os.set(this,void 0),ks.set(this,void 0),Rs.set(this,void 0),Es.set(this,void 0),Ps.set(this,void 0),Cs.set(this,void 0),Ts.set(this,void 0)}[(xs=new WeakMap,Ss=new WeakMap,$s=new WeakMap,As=new WeakMap,Is=new WeakMap,Os=new WeakMap,ks=new WeakMap,Rs=new WeakMap,Es=new WeakMap,Ps=new WeakMap,Cs=new WeakMap,Ts=new WeakMap,bs=new WeakSet,Symbol.asyncIterator)](){const e=[],t=[];let s=!1;return this.on("event",(s=>{const n=t.shift();n?n.resolve(s):e.push(s)})),this.on("end",(()=>{s=!0;for(const e of t)e.resolve(void 0);t.length=0})),this.on("abort",(e=>{s=!0;for(const s of t)s.reject(e);t.length=0})),this.on("error",(e=>{s=!0;for(const s of t)s.reject(e);t.length=0})),{next:async()=>{if(!e.length)return s?{value:void 0,done:!0}:new Promise(((e,s)=>t.push({resolve:e,reject:s}))).then((e=>e?{value:e,done:!1}:{value:void 0,done:!0}));return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){const t=new vs;return t._run((()=>t._fromReadableStream(e))),t}async _fromReadableStream(e,t){const s=t?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",(()=>this.controller.abort()))),this._connected();const n=be.fromReadableStream(e,this.controller);for await(const e of n)o(this,bs,"m",qs).call(this,e);if(n.controller.signal?.aborted)throw new h;return this._addRun(o(this,bs,"m",js).call(this))}toReadableStream(){return new be(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,s,n){const r=new vs;return r._run((()=>r._runToolAssistantStream(e,t,s,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}}))),r}async _createToolAssistantStream(e,t,s,n){const r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",(()=>this.controller.abort())));const i={...s,stream:!0},a=await e.submitToolOutputs(t,i,{...n,signal:this.controller.signal});this._connected();for await(const e of a)o(this,bs,"m",qs).call(this,e);if(a.controller.signal?.aborted)throw new h;return this._addRun(o(this,bs,"m",js).call(this))}static createThreadAssistantStream(e,t,s){const n=new vs;return n._run((()=>n._threadAssistantStream(e,t,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}}))),n}static createAssistantStream(e,t,s,n){const r=new vs;return r._run((()=>r._runAssistantStream(e,t,s,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}}))),r}currentEvent(){return o(this,Ps,"f")}currentRun(){return o(this,Cs,"f")}currentMessageSnapshot(){return o(this,As,"f")}currentRunStepSnapshot(){return o(this,Ts,"f")}async finalRunSteps(){return await this.done(),Object.values(o(this,Ss,"f"))}async finalMessages(){return await this.done(),Object.values(o(this,$s,"f"))}async finalRun(){if(await this.done(),!o(this,Is,"f"))throw Error("Final run was not received.");return o(this,Is,"f")}async _createThreadAssistantStream(e,t,s){const n=s?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",(()=>this.controller.abort())));const r={...t,stream:!0},i=await e.createAndRun(r,{...s,signal:this.controller.signal});this._connected();for await(const e of i)o(this,bs,"m",qs).call(this,e);if(i.controller.signal?.aborted)throw new h;return this._addRun(o(this,bs,"m",js).call(this))}async _createAssistantStream(e,t,s,n){const r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",(()=>this.controller.abort())));const i={...s,stream:!0},a=await e.create(t,i,{...n,signal:this.controller.signal});this._connected();for await(const e of a)o(this,bs,"m",qs).call(this,e);if(a.controller.signal?.aborted)throw new h;return this._addRun(o(this,bs,"m",js).call(this))}static accumulateDelta(e,t){for(const[s,n]of Object.entries(t)){if(!e.hasOwnProperty(s)){e[s]=n;continue}let t=e[s];if(null!=t)if("index"!==s&&"type"!==s){if("string"==typeof t&&"string"==typeof n)t+=n;else if("number"==typeof t&&"number"==typeof n)t+=n;else{if(!R(t)||!R(n)){if(Array.isArray(t)&&Array.isArray(n)){if(t.every((e=>"string"==typeof e||"number"==typeof e))){t.push(...n);continue}for(const e of n){if(!R(e))throw new Error(`Expected array delta entry to be an object but got: ${e}`);const s=e.index;if(null==s)throw console.error(e),new Error("Expected array delta entry to have an `index` property");if("number"!=typeof s)throw new Error(`Expected array delta entry \`index\` property to be a number but got ${s}`);const n=t[s];null==n?t.push(e):t[s]=this.accumulateDelta(n,e)}continue}throw Error(`Unhandled record type: ${s}, deltaValue: ${n}, accValue: ${t}`)}t=this.accumulateDelta(t,n)}e[s]=t}else e[s]=n;else e[s]=n}return e}_addRun(e){return e}async _threadAssistantStream(e,t,s){return await this._createThreadAssistantStream(t,e,s)}async _runAssistantStream(e,t,s,n){return await this._createAssistantStream(t,e,s,n)}async _runToolAssistantStream(e,t,s,n){return await this._createToolAssistantStream(t,e,s,n)}}vs=Fs,qs=function(e){if(!this.ended)switch(r(this,Ps,e),o(this,bs,"m",Ns).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":o(this,bs,"m",Us).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":o(this,bs,"m",Ls).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":o(this,bs,"m",Ms).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},js=function(){if(this.ended)throw new c("stream has ended, this shouldn't happen");if(!o(this,Is,"f"))throw Error("Final run has not been received");return o(this,Is,"f")},Ms=function(e){const[t,s]=o(this,bs,"m",Ws).call(this,e,o(this,As,"f"));r(this,As,t),o(this,$s,"f")[t.id]=t;for(const e of s){const s=t.content[e.index];"text"==s?.type&&this._emit("textCreated",s.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(const s of e.data.delta.content){if("text"==s.type&&s.text){let e=s.text,n=t.content[s.index];if(!n||"text"!=n.type)throw Error("The snapshot associated with this text delta is not text or missing");this._emit("textDelta",e,n.text)}if(s.index!=o(this,Os,"f")){if(o(this,ks,"f"))switch(o(this,ks,"f").type){case"text":this._emit("textDone",o(this,ks,"f").text,o(this,As,"f"));break;case"image_file":this._emit("imageFileDone",o(this,ks,"f").image_file,o(this,As,"f"))}r(this,Os,s.index)}r(this,ks,t.content[s.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(void 0!==o(this,Os,"f")){const t=e.data.content[o(this,Os,"f")];if(t)switch(t.type){case"image_file":this._emit("imageFileDone",t.image_file,o(this,As,"f"));break;case"text":this._emit("textDone",t.text,o(this,As,"f"))}}o(this,As,"f")&&this._emit("messageDone",e.data),r(this,As,void 0)}},Ls=function(e){const t=o(this,bs,"m",Ds).call(this,e);switch(r(this,Ts,t),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":const s=e.data.delta;if(s.step_details&&"tool_calls"==s.step_details.type&&s.step_details.tool_calls&&"tool_calls"==t.step_details.type)for(const e of s.step_details.tool_calls)e.index==o(this,Rs,"f")?this._emit("toolCallDelta",e,t.step_details.tool_calls[e.index]):(o(this,Es,"f")&&this._emit("toolCallDone",o(this,Es,"f")),r(this,Rs,e.index),r(this,Es,t.step_details.tool_calls[e.index]),o(this,Es,"f")&&this._emit("toolCallCreated",o(this,Es,"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":r(this,Ts,void 0);"tool_calls"==e.data.step_details.type&&o(this,Es,"f")&&(this._emit("toolCallDone",o(this,Es,"f")),r(this,Es,void 0)),this._emit("runStepDone",e.data,t)}},Ns=function(e){o(this,xs,"f").push(e),this._emit("event",e)},Ds=function(e){switch(e.event){case"thread.run.step.created":return o(this,Ss,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=o(this,Ss,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let s=e.data;if(s.delta){const n=vs.accumulateDelta(t,s.delta);o(this,Ss,"f")[e.data.id]=n}return o(this,Ss,"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":o(this,Ss,"f")[e.data.id]=e.data}if(o(this,Ss,"f")[e.data.id])return o(this,Ss,"f")[e.data.id];throw new Error("No snapshot available")},Ws=function(e,t){let s=[];switch(e.event){case"thread.message.created":return[e.data,s];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(const e of n.delta.content)if(e.index in t.content){let s=t.content[e.index];t.content[e.index]=o(this,bs,"m",Bs).call(this,e,s)}else t.content[e.index]=e,s.push(e);return[t,s];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,s];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Bs=function(e,t){return vs.accumulateDelta(t,e)},Us=function(e){switch(r(this,Cs,e.data),e.event){case"thread.run.created":case"thread.run.queued":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":r(this,Is,e.data),o(this,Es,"f")&&(this._emit("toolCallDone",o(this,Es,"f")),r(this,Es,void 0))}};let Xs=class extends We{constructor(){super(...arguments),this.steps=new ws(this._client)}create(e,t,s){const{include:n,...r}=t;return this._client.post(Xe`/threads/${e}/runs`,{query:{include:n},body:r,...s,headers:as([{"OpenAI-Beta":"assistants=v2"},s?.headers]),stream:t.stream??!1})}retrieve(e,t,s){const{thread_id:n}=t;return this._client.get(Xe`/threads/${n}/runs/${e}`,{...s,headers:as([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,t,s){const{thread_id:n,...r}=t;return this._client.post(Xe`/threads/${n}/runs/${e}`,{body:r,...s,headers:as([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t={},s){return this._client.getAPIList(Xe`/threads/${e}/runs`,ke,{query:t,...s,headers:as([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}cancel(e,t,s){const{thread_id:n}=t;return this._client.post(Xe`/threads/${n}/runs/${e}/cancel`,{...s,headers:as([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async createAndPoll(e,t,s){const n=await this.create(e,t,s);return await this.poll(n.id,{thread_id:e},s)}createAndStream(e,t,s){return Fs.createAssistantStream(e,this._client.beta.threads.runs,t,s)}async poll(e,t,s){const n=as([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:r,response:o}=await this.retrieve(e,t,{...s,headers:{...s?.headers,...n}}).withResponse();switch(r.status){case"queued":case"in_progress":case"cancelling":let e=5e3;if(s?.pollIntervalMs)e=s.pollIntervalMs;else{const t=o.headers.get("openai-poll-after-ms");if(t){const s=parseInt(t);isNaN(s)||(e=s)}}await E(e);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return r}}}stream(e,t,s){return Fs.createAssistantStream(e,this._client.beta.threads.runs,t,s)}submitToolOutputs(e,t,s){const{thread_id:n,...r}=t;return this._client.post(Xe`/threads/${n}/runs/${e}/submit_tool_outputs`,{body:r,...s,headers:as([{"OpenAI-Beta":"assistants=v2"},s?.headers]),stream:t.stream??!1})}async submitToolOutputsAndPoll(e,t,s){const n=await this.submitToolOutputs(e,t,s);return await this.poll(n.id,t,s)}submitToolOutputsStream(e,t,s){return Fs.createToolAssistantStream(e,this._client.beta.threads.runs,t,s)}};Xs.Steps=ws;class Hs extends We{constructor(){super(...arguments),this.runs=new Xs(this._client),this.messages=new ys(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:as([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(Xe`/threads/${e}`,{...t,headers:as([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,s){return this._client.post(Xe`/threads/${e}`,{body:t,...s,headers:as([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,t){return this._client.delete(Xe`/threads/${e}`,{...t,headers:as([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:as([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1})}async createAndRunPoll(e,t){const s=await this.createAndRun(e,t);return await this.runs.poll(s.id,{thread_id:s.thread_id},t)}createAndRunStream(e,t){return Fs.createThreadAssistantStream(e,this._client.beta.threads,t)}}Hs.Runs=Xs,Hs.Messages=ys;class Ks extends We{constructor(){super(...arguments),this.realtime=new gs(this._client),this.assistants=new fs(this._client),this.threads=new Hs(this._client)}}Ks.Realtime=gs,Ks.Assistants=fs,Ks.Threads=Hs;class Js extends We{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class Vs extends We{retrieve(e,t,s){const{container_id:n}=t;return this._client.get(Xe`/containers/${n}/files/${e}/content`,{...s,headers:as([{Accept:"application/binary"},s?.headers]),__binaryResponse:!0})}}let zs=class extends We{constructor(){super(...arguments),this.content=new Vs(this._client)}create(e,t,s){return this._client.post(Xe`/containers/${e}/files`,qe({body:t,...s},this._client))}retrieve(e,t,s){const{container_id:n}=t;return this._client.get(Xe`/containers/${n}/files/${e}`,s)}list(e,t={},s){return this._client.getAPIList(Xe`/containers/${e}/files`,ke,{query:t,...s})}delete(e,t,s){const{container_id:n}=t;return this._client.delete(Xe`/containers/${n}/files/${e}`,{...s,headers:as([{Accept:"*/*"},s?.headers])})}};zs.Content=Vs;class Gs extends We{constructor(){super(...arguments),this.files=new zs(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(Xe`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",ke,{query:e,...t})}delete(e,t){return this._client.delete(Xe`/containers/${e}`,{...t,headers:as([{Accept:"*/*"},t?.headers])})}}Gs.Files=zs;class Qs extends We{create(e,t,s){const{include:n,...r}=t;return this._client.post(Xe`/conversations/${e}/items`,{query:{include:n},body:r,...s})}retrieve(e,t,s){const{conversation_id:n,...r}=t;return this._client.get(Xe`/conversations/${n}/items/${e}`,{query:r,...s})}list(e,t={},s){return this._client.getAPIList(Xe`/conversations/${e}/items`,Re,{query:t,...s})}delete(e,t,s){const{conversation_id:n}=t;return this._client.delete(Xe`/conversations/${n}/items/${e}`,s)}}class Ys extends We{constructor(){super(...arguments),this.items=new Qs(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t})}retrieve(e,t){return this._client.get(Xe`/conversations/${e}`,t)}update(e,t,s){return this._client.post(Xe`/conversations/${e}`,{body:t,...s})}delete(e,t){return this._client.delete(Xe`/conversations/${e}`,t)}}Ys.Items=Qs;class Zs extends We{create(e,t){const s=!!e.encoding_format;let n=s?e.encoding_format:"base64";s&&me(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);const r=this._client.post("/embeddings",{body:{...e,encoding_format:n},...t});return s?r:(me(this._client).debug("embeddings/decoding base64 embeddings from base64"),r._thenUnwrap((e=>(e&&e.data&&e.data.forEach((e=>{const t=e.embedding;e.embedding=(e=>{if("undefined"!=typeof Buffer){const t=Buffer.from(e,"base64");return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}{const t=atob(e),s=t.length,n=new Uint8Array(s);for(let e=0;e<s;e++)n[e]=t.charCodeAt(e);return Array.from(new Float32Array(n.buffer))}})(t)})),e))))}}class en extends We{retrieve(e,t,s){const{eval_id:n,run_id:r}=t;return this._client.get(Xe`/evals/${n}/runs/${r}/output_items/${e}`,s)}list(e,t,s){const{eval_id:n,...r}=t;return this._client.getAPIList(Xe`/evals/${n}/runs/${e}/output_items`,ke,{query:r,...s})}}class tn extends We{constructor(){super(...arguments),this.outputItems=new en(this._client)}create(e,t,s){return this._client.post(Xe`/evals/${e}/runs`,{body:t,...s})}retrieve(e,t,s){const{eval_id:n}=t;return this._client.get(Xe`/evals/${n}/runs/${e}`,s)}list(e,t={},s){return this._client.getAPIList(Xe`/evals/${e}/runs`,ke,{query:t,...s})}delete(e,t,s){const{eval_id:n}=t;return this._client.delete(Xe`/evals/${n}/runs/${e}`,s)}cancel(e,t,s){const{eval_id:n}=t;return this._client.post(Xe`/evals/${n}/runs/${e}`,s)}}tn.OutputItems=en;class sn extends We{constructor(){super(...arguments),this.runs=new tn(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(Xe`/evals/${e}`,t)}update(e,t,s){return this._client.post(Xe`/evals/${e}`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/evals",ke,{query:e,...t})}delete(e,t){return this._client.delete(Xe`/evals/${e}`,t)}}sn.Runs=tn;let nn=class extends We{create(e,t){return this._client.post("/files",qe({body:e,...t},this._client))}retrieve(e,t){return this._client.get(Xe`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",ke,{query:e,...t})}delete(e,t){return this._client.delete(Xe`/files/${e}`,t)}content(e,t){return this._client.get(Xe`/files/${e}/content`,{...t,headers:as([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:s=18e5}={}){const n=new Set(["processed","error","deleted"]),r=Date.now();let o=await this.retrieve(e);for(;!o.status||!n.has(o.status);)if(await E(t),o=await this.retrieve(e),Date.now()-r>s)throw new f({message:`Giving up on waiting for file ${e} to finish processing after ${s} milliseconds.`});return o}};class rn extends We{}let on=class extends We{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})}};class an extends We{constructor(){super(...arguments),this.graders=new on(this._client)}}an.Graders=on;class ln extends We{create(e,t,s){return this._client.getAPIList(Xe`/fine_tuning/checkpoints/${e}/permissions`,Oe,{body:t,method:"post",...s})}retrieve(e,t={},s){return this._client.get(Xe`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...s})}delete(e,t,s){const{fine_tuned_model_checkpoint:n}=t;return this._client.delete(Xe`/fine_tuning/checkpoints/${n}/permissions/${e}`,s)}}let cn=class extends We{constructor(){super(...arguments),this.permissions=new ln(this._client)}};cn.Permissions=ln;class un extends We{list(e,t={},s){return this._client.getAPIList(Xe`/fine_tuning/jobs/${e}/checkpoints`,ke,{query:t,...s})}}class hn extends We{constructor(){super(...arguments),this.checkpoints=new un(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(Xe`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",ke,{query:e,...t})}cancel(e,t){return this._client.post(Xe`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},s){return this._client.getAPIList(Xe`/fine_tuning/jobs/${e}/events`,ke,{query:t,...s})}pause(e,t){return this._client.post(Xe`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(Xe`/fine_tuning/jobs/${e}/resume`,t)}}hn.Checkpoints=un;class dn extends We{constructor(){super(...arguments),this.methods=new rn(this._client),this.jobs=new hn(this._client),this.checkpoints=new cn(this._client),this.alpha=new an(this._client)}}dn.Methods=rn,dn.Jobs=hn,dn.Checkpoints=cn,dn.Alpha=an;class fn extends We{}class pn extends We{constructor(){super(...arguments),this.graderModels=new fn(this._client)}}pn.GraderModels=fn;class mn extends We{createVariation(e,t){return this._client.post("/images/variations",qe({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",qe({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})}}class gn extends We{retrieve(e,t){return this._client.get(Xe`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",Oe,e)}delete(e,t){return this._client.delete(Xe`/models/${e}`,t)}}class yn extends We{create(e,t){return this._client.post("/moderations",{body:e,...t})}}class wn extends We{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t})}}class _n extends We{constructor(){super(...arguments),this.clientSecrets=new wn(this._client)}}function bn(e,t){return t&&function(e){if(Je(e.text?.format))return!0;return!1}(t)?vn(e,t):{...e,output_parsed:null,output:e.output.map((e=>"function_call"===e.type?{...e,parsed_arguments:null}:"message"===e.type?{...e,content:e.content.map((e=>({...e,parsed:null})))}:e))}}function vn(e,t){const s=e.output.map((e=>{if("function_call"===e.type)return{...e,parsed_arguments:Sn(t,e)};if("message"===e.type){const s=e.content.map((e=>"output_text"===e.type?{...e,parsed:xn(t,e.text)}:e));return{...e,content:s}}return e})),n=Object.assign({},e,{output:s});return Object.getOwnPropertyDescriptor(e,"output_text")||$n(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(const e of n.output)if("message"===e.type)for(const t of e.content)if("output_text"===t.type&&null!==t.parsed)return t.parsed;return null}}),n}function xn(e,t){if("json_schema"!==e.text?.format?.type)return null;if("$parseRaw"in e.text?.format){const s=e.text?.format;return s.$parseRaw(t)}return JSON.parse(t)}function Sn(e,t){const s=(n=e.tools??[],r=t.name,n.find((e=>"function"===e.type&&e.name===r)));var n,r,o;return{...t,...t,parsed_arguments:(o=s,"auto-parseable-tool"===o?.$brand?s.$parseRaw(t.arguments):s?.strict?JSON.parse(t.arguments):null)}}function $n(e){const t=[];for(const s of e.output)if("message"===s.type)for(const e of s.content)"output_text"===e.type&&t.push(e.text);e.output_text=t.join("")}var An,In,On,kn,Rn,En,Pn,Cn;_n.ClientSecrets=wn;class Tn extends St{constructor(e){super(),An.add(this),In.set(this,void 0),On.set(this,void 0),kn.set(this,void 0),r(this,In,e)}static createResponse(e,t,s){const n=new Tn(t);return n._run((()=>n._createOrRetrieveResponse(e,t,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}}))),n}async _createOrRetrieveResponse(e,t,s){const n=s?.signal;let r;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",(()=>this.controller.abort()))),o(this,An,"m",Rn).call(this);let i=null;"response_id"in t?(r=await e.responses.retrieve(t.response_id,{stream:!0},{...s,signal:this.controller.signal,stream:!0}),i=t.starting_after??null):r=await e.responses.create({...t,stream:!0},{...s,signal:this.controller.signal}),this._connected();for await(const e of r)o(this,An,"m",En).call(this,e,i);if(r.controller.signal?.aborted)throw new h;return o(this,An,"m",Pn).call(this)}[(In=new WeakMap,On=new WeakMap,kn=new WeakMap,An=new WeakSet,Rn=function(){this.ended||r(this,On,void 0)},En=function(e,t){if(this.ended)return;const s=(e,s)=>{(null==t||s.sequence_number>t)&&this._emit(e,s)},n=o(this,An,"m",Cn).call(this,e);switch(s("event",e),e.type){case"response.output_text.delta":{const t=n.output[e.output_index];if(!t)throw new c(`missing output at index ${e.output_index}`);if("message"===t.type){const n=t.content[e.content_index];if(!n)throw new c(`missing content at index ${e.content_index}`);if("output_text"!==n.type)throw new c(`expected content to be 'output_text', got ${n.type}`);s("response.output_text.delta",{...e,snapshot:n.text})}break}case"response.function_call_arguments.delta":{const t=n.output[e.output_index];if(!t)throw new c(`missing output at index ${e.output_index}`);"function_call"===t.type&&s("response.function_call_arguments.delta",{...e,snapshot:t.arguments});break}default:s(e.type,e)}},Pn=function(){if(this.ended)throw new c("stream has ended, this shouldn't happen");const e=o(this,On,"f");if(!e)throw new c("request ended without sending any events");r(this,On,void 0);const t=function(e,t){return bn(e,t)}(e,o(this,In,"f"));return r(this,kn,t),t},Cn=function(e){let t=o(this,On,"f");if(!t){if("response.created"!==e.type)throw new c(`When snapshot hasn't been set yet, expected 'response.created' event, got ${e.type}`);return t=r(this,On,e.response),t}switch(e.type){case"response.output_item.added":t.output.push(e.item);break;case"response.content_part.added":{const s=t.output[e.output_index];if(!s)throw new c(`missing output at index ${e.output_index}`);const n=s.type,r=e.part;"message"===n&&"reasoning_text"!==r.type?s.content.push(r):"reasoning"===n&&"reasoning_text"===r.type&&(s.content||(s.content=[]),s.content.push(r));break}case"response.output_text.delta":{const s=t.output[e.output_index];if(!s)throw new c(`missing output at index ${e.output_index}`);if("message"===s.type){const t=s.content[e.content_index];if(!t)throw new c(`missing content at index ${e.content_index}`);if("output_text"!==t.type)throw new c(`expected content to be 'output_text', got ${t.type}`);t.text+=e.delta}break}case"response.function_call_arguments.delta":{const s=t.output[e.output_index];if(!s)throw new c(`missing output at index ${e.output_index}`);"function_call"===s.type&&(s.arguments+=e.delta);break}case"response.reasoning_text.delta":{const s=t.output[e.output_index];if(!s)throw new c(`missing output at index ${e.output_index}`);if("reasoning"===s.type){const t=s.content?.[e.content_index];if(!t)throw new c(`missing content at index ${e.content_index}`);if("reasoning_text"!==t.type)throw new c(`expected content to be 'reasoning_text', got ${t.type}`);t.text+=e.delta}break}case"response.completed":r(this,On,e.response)}return t},Symbol.asyncIterator)](){const e=[],t=[];let s=!1;return this.on("event",(s=>{const n=t.shift();n?n.resolve(s):e.push(s)})),this.on("end",(()=>{s=!0;for(const e of t)e.resolve(void 0);t.length=0})),this.on("abort",(e=>{s=!0;for(const s of t)s.reject(e);t.length=0})),this.on("error",(e=>{s=!0;for(const s of t)s.reject(e);t.length=0})),{next:async()=>{if(!e.length)return s?{value:void 0,done:!0}:new Promise(((e,s)=>t.push({resolve:e,reject:s}))).then((e=>e?{value:e,done:!1}:{value:void 0,done:!0}));return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const e=o(this,kn,"f");if(!e)throw new c("stream ended without producing a ChatCompletion");return e}}class qn extends We{list(e,t={},s){return this._client.getAPIList(Xe`/responses/${e}/input_items`,ke,{query:t,...s})}}class jn extends We{constructor(){super(...arguments),this.inputItems=new qn(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap((e=>("object"in e&&"response"===e.object&&$n(e),e)))}retrieve(e,t={},s){return this._client.get(Xe`/responses/${e}`,{query:t,...s,stream:t?.stream??!1})._thenUnwrap((e=>("object"in e&&"response"===e.object&&$n(e),e)))}delete(e,t){return this._client.delete(Xe`/responses/${e}`,{...t,headers:as([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap((t=>vn(t,e)))}stream(e,t){return Tn.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(Xe`/responses/${e}/cancel`,t)}}jn.InputItems=qn;class Mn extends We{create(e,t,s){return this._client.post(Xe`/uploads/${e}/parts`,qe({body:t,...s},this._client))}}class Ln extends We{constructor(){super(...arguments),this.parts=new Mn(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(Xe`/uploads/${e}/cancel`,t)}complete(e,t,s){return this._client.post(Xe`/uploads/${e}/complete`,{body:t,...s})}}Ln.Parts=Mn;class Nn extends We{create(e,t,s){return this._client.post(Xe`/vector_stores/${e}/file_batches`,{body:t,...s,headers:as([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,t,s){const{vector_store_id:n}=t;return this._client.get(Xe`/vector_stores/${n}/file_batches/${e}`,{...s,headers:as([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}cancel(e,t,s){const{vector_store_id:n}=t;return this._client.post(Xe`/vector_stores/${n}/file_batches/${e}/cancel`,{...s,headers:as([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async createAndPoll(e,t,s){const n=await this.create(e,t);return await this.poll(e,n.id,s)}listFiles(e,t,s){const{vector_store_id:n,...r}=t;return this._client.getAPIList(Xe`/vector_stores/${n}/file_batches/${e}/files`,ke,{query:r,...s,headers:as([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async poll(e,t,s){const n=as([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:r,response:o}=await this.retrieve(t,{vector_store_id:e},{...s,headers:n}).withResponse();switch(r.status){case"in_progress":let e=5e3;if(s?.pollIntervalMs)e=s.pollIntervalMs;else{const t=o.headers.get("openai-poll-after-ms");if(t){const s=parseInt(t);isNaN(s)||(e=s)}}await E(e);break;case"failed":case"cancelled":case"completed":return r}}}async uploadAndPoll(e,{files:t,fileIds:s=[]},n){if(null==t||0==t.length)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const r=n?.maxConcurrency??5,o=Math.min(r,t.length),i=this._client,a=t.values(),l=[...s];const c=Array(o).fill(a).map((async function(e){for(let t of e){const e=await i.files.create({file:t,purpose:"assistants"},n);l.push(e.id)}}));return await(async e=>{const t=await Promise.allSettled(e),s=t.filter((e=>"rejected"===e.status));if(s.length){for(const e of s)console.error(e.reason);throw new Error(`${s.length} promise(s) failed - see the above errors`)}const n=[];for(const e of t)"fulfilled"===e.status&&n.push(e.value);return n})(c),await this.createAndPoll(e,{file_ids:l})}}class Dn extends We{create(e,t,s){return this._client.post(Xe`/vector_stores/${e}/files`,{body:t,...s,headers:as([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,t,s){const{vector_store_id:n}=t;return this._client.get(Xe`/vector_stores/${n}/files/${e}`,{...s,headers:as([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,t,s){const{vector_store_id:n,...r}=t;return this._client.post(Xe`/vector_stores/${n}/files/${e}`,{body:r,...s,headers:as([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t={},s){return this._client.getAPIList(Xe`/vector_stores/${e}/files`,ke,{query:t,...s,headers:as([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,t,s){const{vector_store_id:n}=t;return this._client.delete(Xe`/vector_stores/${n}/files/${e}`,{...s,headers:as([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async createAndPoll(e,t,s){const n=await this.create(e,t,s);return await this.poll(e,n.id,s)}async poll(e,t,s){const n=as([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){const r=await this.retrieve(t,{vector_store_id:e},{...s,headers:n}).withResponse(),o=r.data;switch(o.status){case"in_progress":let e=5e3;if(s?.pollIntervalMs)e=s.pollIntervalMs;else{const t=r.response.headers.get("openai-poll-after-ms");if(t){const s=parseInt(t);isNaN(s)||(e=s)}}await E(e);break;case"failed":case"completed":return o}}}async upload(e,t,s){const n=await this._client.files.create({file:t,purpose:"assistants"},s);return this.create(e,{file_id:n.id},s)}async uploadAndPoll(e,t,s){const n=await this.upload(e,t,s);return await this.poll(e,n.id,s)}content(e,t,s){const{vector_store_id:n}=t;return this._client.getAPIList(Xe`/vector_stores/${n}/files/${e}/content`,Oe,{...s,headers:as([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}class Wn extends We{constructor(){super(...arguments),this.files=new Dn(this._client),this.fileBatches=new Nn(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:as([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(Xe`/vector_stores/${e}`,{...t,headers:as([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,s){return this._client.post(Xe`/vector_stores/${e}`,{body:t,...s,headers:as([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",ke,{query:e,...t,headers:as([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(Xe`/vector_stores/${e}`,{...t,headers:as([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,s){return this._client.getAPIList(Xe`/vector_stores/${e}/search`,Oe,{body:t,method:"post",...s,headers:as([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}var Bn,Un,Fn,Xn,Hn,Kn,Jn;Wn.Files=Dn,Wn.FileBatches=Nn;class Vn extends We{constructor(){super(...arguments),Bn.add(this)}async unwrap(e,t,s=this._client.webhookSecret,n=300){return await this.verifySignature(e,t,s,n),JSON.parse(e)}async verifySignature(e,t,s=this._client.webhookSecret,n=300){if("undefined"==typeof crypto||"function"!=typeof crypto.subtle.importKey||"function"!=typeof crypto.subtle.verify)throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");o(this,Bn,"m",Un).call(this,s);const r=as([t]).values,i=o(this,Bn,"m",Fn).call(this,r,"webhook-signature"),a=o(this,Bn,"m",Fn).call(this,r,"webhook-timestamp"),l=o(this,Bn,"m",Fn).call(this,r,"webhook-id"),c=parseInt(a,10);if(isNaN(c))throw new $("Invalid webhook timestamp format");const u=Math.floor(Date.now()/1e3);if(u-c>n)throw new $("Webhook timestamp is too old");if(c>u+n)throw new $("Webhook timestamp is too new");const h=i.split(" ").map((e=>e.startsWith("v1,")?e.substring(3):e)),d=s.startsWith("whsec_")?Buffer.from(s.replace("whsec_",""),"base64"):Buffer.from(s,"utf-8"),f=l?`${l}.${a}.${e}`:`${a}.${e}`,p=await crypto.subtle.importKey("raw",d,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(const e of h)try{const t=Buffer.from(e,"base64");if(await crypto.subtle.verify("HMAC",p,t,(new TextEncoder).encode(f)))return}catch{continue}throw new $("The given webhook signature does not match the expected signature")}}Bn=new WeakSet,Un=function(e){if("string"!=typeof e||0===e.length)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")},Fn=function(e,t){if(!e)throw new Error("Headers are required");const s=e.get(t);if(null==s)throw new Error(`Missing required header: ${t}`);return s};class zn{constructor({baseURL:e=_s("OPENAI_BASE_URL"),apiKey:t=_s("OPENAI_API_KEY"),organization:s=_s("OPENAI_ORG_ID")??null,project:n=_s("OPENAI_PROJECT_ID")??null,webhookSecret:o=_s("OPENAI_WEBHOOK_SECRET")??null,...i}={}){if(Xn.add(this),Kn.set(this,void 0),this.completions=new Js(this),this.chat=new rs(this),this.embeddings=new Zs(this),this.files=new nn(this),this.images=new mn(this),this.audio=new hs(this),this.moderations=new yn(this),this.models=new gn(this),this.fineTuning=new dn(this),this.graders=new pn(this),this.vectorStores=new Wn(this),this.webhooks=new Vn(this),this.beta=new Ks(this),this.batches=new ds(this),this.uploads=new Ln(this),this.responses=new jn(this),this.realtime=new _n(this),this.conversations=new Ys(this),this.evals=new sn(this),this.containers=new Gs(this),void 0===t)throw new c("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");const a={apiKey:t,organization:s,project:n,webhookSecret:o,...i,baseURL:e||"https://api.openai.com/v1"};if(!a.dangerouslyAllowBrowser&&"undefined"!=typeof window&&void 0!==window.document&&"undefined"!=typeof navigator)throw new c("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n");this.baseURL=a.baseURL,this.timeout=a.timeout??Hn.DEFAULT_TIMEOUT,this.logger=a.logger??console;const l="warn";this.logLevel=l,this.logLevel=ue(a.logLevel,"ClientOptions.logLevel",this)??ue(_s("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??l,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.fetch=a.fetch??function(){if("undefined"!=typeof fetch)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`")}(),r(this,Kn,D),this._options=a,this.apiKey="string"==typeof t?t:"Missing Key",this.organization=s,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 as([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return Z(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${P}`}defaultIdempotencyKey(){return`stainless-node-retry-${i()}`}makeStatusError(e,t,s,n){return u.generate(e,t,s,n)}async _callApiKey(){const e=this._options.apiKey;if("function"!=typeof e)return!1;let t;try{t=await e()}catch(e){if(e instanceof c)throw e;throw new c(`Failed to get token from 'apiKey' function: ${e.message}`,{cause:e})}if("string"!=typeof t||!t)throw new c(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,s){const n=!o(this,Xn,"m",Jn).call(this)&&s||this.baseURL,r=(e=>A.test(e))(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return function(e){if(!e)return!0;for(const t in e)return!1;return!0}(i)||(t={...i,...t}),"object"==typeof t&&t&&!Array.isArray(t)&&(r.search=this.stringifyQuery(t)),r.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:t,options:s}){}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,s){return this.request(Promise.resolve(s).then((s=>({method:e,path:t,...s}))))}request(e,t=null){return new $e(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,s){const n=await e,r=n.maxRetries??this.maxRetries;null==t&&(t=r),await this.prepareOptions(n);const{req:o,url:i,timeout:c}=await this.buildRequest(n,{retryCount:r-t});await this.prepareRequest(o,{url:i,options:n});const u="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),p=void 0===s?"":`, retryOf: ${s}`,m=Date.now();if(me(this).debug(`[${u}] sending request`,ge({retryOfRequestLogID:s,method:n.method,url:i,options:n,headers:o.headers})),n.signal?.aborted)throw new h;const g=new AbortController,y=await this.fetchWithTimeout(i,o,c,g).catch(l),w=Date.now();if(y instanceof globalThis.Error){const e=`retrying, ${t} attempts remaining`;if(n.signal?.aborted)throw new h;const r=a(y)||/timed? ?out/i.test(String(y)+("cause"in y?String(y.cause):""));if(t)return me(this).info(`[${u}] connection ${r?"timed out":"failed"} - ${e}`),me(this).debug(`[${u}] connection ${r?"timed out":"failed"} (${e})`,ge({retryOfRequestLogID:s,url:i,durationMs:w-m,message:y.message})),this.retryRequest(n,t,s??u);if(me(this).info(`[${u}] connection ${r?"timed out":"failed"} - error; no more retries left`),me(this).debug(`[${u}] connection ${r?"timed out":"failed"} (error; no more retries left)`,ge({retryOfRequestLogID:s,url:i,durationMs:w-m,message:y.message})),r)throw new f;throw new d({cause:y})}const _=`[${u}${p}${[...y.headers.entries()].filter((([e])=>"x-request-id"===e)).map((([e,t])=>", "+e+": "+JSON.stringify(t))).join("")}] ${o.method} ${i} ${y.ok?"succeeded":"failed"} with status ${y.status} in ${w-m}ms`;if(!y.ok){const e=await this.shouldRetry(y);if(t&&e){const e=`retrying, ${t} attempts remaining`;return await async function(e){if(null===e||"object"!=typeof e)return;if(e[Symbol.asyncIterator])return void await(e[Symbol.asyncIterator]().return?.());const t=e.getReader(),s=t.cancel();t.releaseLock(),await s}(y.body),me(this).info(`${_} - ${e}`),me(this).debug(`[${u}] response error (${e})`,ge({retryOfRequestLogID:s,url:y.url,status:y.status,headers:y.headers,durationMs:w-m})),this.retryRequest(n,t,s??u,y.headers)}const r=e?"error; no more retries left":"error; not retryable";me(this).info(`${_} - ${r}`);const o=await y.text().catch((e=>l(e).message)),i=(e=>{try{return JSON.parse(e)}catch(e){return}})(o),a=i?void 0:o;me(this).debug(`[${u}] response error (${r})`,ge({retryOfRequestLogID:s,url:y.url,status:y.status,headers:y.headers,message:a,durationMs:Date.now()-m}));throw this.makeStatusError(y.status,i,a,y.headers)}return me(this).info(_),me(this).debug(`[${u}] response start`,ge({retryOfRequestLogID:s,url:y.url,status:y.status,headers:y.headers,durationMs:w-m})),{response:y,options:n,controller:g,requestLogID:u,retryOfRequestLogID:s,startTime:m}}getAPIList(e,t,s){return this.requestAPIList(t,{method:"get",path:e,...s})}requestAPIList(e,t){const s=this.makeRequest(t,null,void 0);return new Ie(this,s,e)}async fetchWithTimeout(e,t,s,n){const{signal:r,method:o,...i}=t||{};r&&r.addEventListener("abort",(()=>n.abort()));const a=setTimeout((()=>n.abort()),s),l=globalThis.ReadableStream&&i.body instanceof globalThis.ReadableStream||"object"==typeof i.body&&null!==i.body&&Symbol.asyncIterator in i.body,c={signal:n.signal,...l?{duplex:"half"}:{},method:"GET",...i};o&&(c.method=o.toUpperCase());try{return await this.fetch.call(void 0,e,c)}finally{clearTimeout(a)}}async shouldRetry(e){const t=e.headers.get("x-should-retry");return"true"===t||"false"!==t&&(408===e.status||(409===e.status||(429===e.status||e.status>=500)))}async retryRequest(e,t,s,n){let r;const o=n?.get("retry-after-ms");if(o){const e=parseFloat(o);Number.isNaN(e)||(r=e)}const i=n?.get("retry-after");if(i&&!r){const e=parseFloat(i);r=Number.isNaN(e)?Date.parse(i)-Date.now():1e3*e}if(!(r&&0<=r&&r<6e4)){const s=e.maxRetries??this.maxRetries;r=this.calculateDefaultRetryTimeoutMillis(t,s)}return await E(r),this.makeRequest(e,t-1,s)}calculateDefaultRetryTimeoutMillis(e,t){const s=t-e;return Math.min(.5*Math.pow(2,s),8)*(1-.25*Math.random())*1e3}async buildRequest(e,{retryCount:t=0}={}){const s={...e},{method:n,path:r,query:o,defaultBaseURL:i}=s,a=this.buildURL(r,o,i);"timeout"in s&&((e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new c(`${e} must be an integer`);if(t<0)throw new c(`${e} must be a positive integer`)})("timeout",s.timeout),s.timeout=s.timeout??this.timeout;const{bodyHeaders:l,body:u}=this.buildBody({options:s});return{req:{method:n,headers:await this.buildHeaders({options:e,method:n,bodyHeaders:l,retryCount:t}),...s.signal&&{signal:s.signal},...globalThis.ReadableStream&&u instanceof globalThis.ReadableStream&&{duplex:"half"},...u&&{body:u},...this.fetchOptions??{},...s.fetchOptions??{}},url:a,timeout:s.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:s,retryCount:n}){let r={};this.idempotencyHeader&&"get"!==t&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),r[this.idempotencyHeader]=e.idempotencyKey);const o=as([r,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(n),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...j??(j=C()),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,s,e.headers]);return this.validateHeaders(o),o.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};const s=as([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||"string"==typeof e&&s.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}:"object"==typeof e&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&"function"==typeof e.next)?{bodyHeaders:void 0,body:L(e)}:o(this,Kn,"f").call(this,{body:e,headers:s})}}function Gn({msg:e,isError:t,isInfinite:s}){const n=document.querySelector("#message");n.style.color=t?"red":"limegreen",n.textContent=e,n.style.display="block",s||setTimeout((()=>n.style.display="none"),5e3)}Hn=zn,Kn=new WeakMap,Xn=new WeakSet,Jn=function(){return"https://api.openai.com/v1"!==this.baseURL},zn.OpenAI=Hn,zn.DEFAULT_TIMEOUT=6e5,zn.OpenAIError=c,zn.APIError=u,zn.APIConnectionError=d,zn.APIConnectionTimeoutError=f,zn.APIUserAbortError=h,zn.NotFoundError=y,zn.ConflictError=w,zn.RateLimitError=b,zn.BadRequestError=p,zn.AuthenticationError=m,zn.InternalServerError=v,zn.PermissionDeniedError=g,zn.UnprocessableEntityError=_,zn.InvalidWebhookSignatureError=$,zn.toFile=async function(e,t,s){if(Ee(),(e=>null!=e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.lastModified&&Ne(e))(e=await e))return e instanceof File?e:Pe([await e.arrayBuffer()],e.name);if((e=>null!=e&&"object"==typeof e&&"string"==typeof e.url&&"function"==typeof e.blob)(e)){const n=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),Pe(await De(n),t,s)}const n=await De(e);if(t||(t=Ce(e)),!s?.type){const e=n.find((e=>"object"==typeof e&&"type"in e&&e.type));"string"==typeof e&&(s={...s,type:e})}return Pe(n,t,s)},zn.Completions=Js,zn.Chat=rs,zn.Embeddings=Zs,zn.Files=nn,zn.Images=mn,zn.Audio=hs,zn.Moderations=yn,zn.Models=gn,zn.FineTuning=dn,zn.Graders=pn,zn.VectorStores=Wn,zn.Webhooks=Vn,zn.Beta=Ks,zn.Batches=ds,zn.Uploads=Ln,zn.Responses=jn,zn.Realtime=_n,zn.Conversations=Ys,zn.Evals=sn,zn.Containers=Gs;const Qn=document.querySelector("#apiKey"),Yn=document.querySelector("#model"),Zn=document.querySelector("#models"),er=document.querySelector("#includeImages-line"),tr=document.querySelector("#baseURL");function sr(){!function(e){const t=e.match(/gpt-(\d+)/);return!!(null==t?void 0:t[1])&&Number(t[1])>=4}(Yn.value)?er.style.display="none":er.style.display="flex"}Yn.addEventListener("input",sr),Yn.addEventListener("focus",(function(){return n(this,void 0,void 0,(function*(){var e,t;const s=null===(e=Qn.value)||void 0===e?void 0:e.trim(),n=null===(t=tr.value)||void 0===t?void 0:t.trim();if(s){Yn.innerHTML="";try{const e=new zn({apiKey:s,baseURL:n,dangerouslyAllowBrowser:!0}),t=(yield e.models.list()).data.filter((e=>e.id.startsWith("gpt")||-1!==e.id.search(/^o\d+/gi)||e.id.startsWith("chatgpt")));t.sort(((e,t)=>t.id.localeCompare(e.id)));for(const e of t){const t=document.createElement("option");t.value=e.id,t.textContent=e.id,Zn.appendChild(t)}sr()}catch(e){console.error(e),Gn({msg:e,isError:!0})}}}))}));document.querySelector("#check-model").addEventListener("click",(function(){return n(this,void 0,void 0,(function*(){var e,t,s;const n=null===(e=Yn.value)||void 0===e?void 0:e.trim(),r=null===(t=Qn.value)||void 0===t?void 0:t.trim(),o=null===(s=tr.value)||void 0===s?void 0:s.trim();try{Gn({msg:"Checking GPT version...",isInfinite:!0,isError:!1});const e=new zn({apiKey:r,baseURL:o,dangerouslyAllowBrowser:!0});yield e.chat.completions.create({model:n,messages:[{role:"user",content:"reply just pong"}]}),Gn({msg:"The model is valid!"})}catch(e){Gn({msg:e,isError:!0})}}))}));const nr=["includeImages"],rr={autocomplete:[],clipboard:["typing","mouseover"],"question-to-answer":["typing","infinite","mouseover"]};function or(){const s=rr[e.actualMode],n=t.filter((e=>!s.includes(e)&&!nr.includes(e)));for(const e of s)document.querySelector("#"+e).parentElement.style.display="none";for(const e of n)document.querySelector("#"+e).parentElement.style.display=""}for(const t of s)t.addEventListener("click",(function(){const n=t.value;e.actualMode=n;for(const e of s)e.value!==n?e.classList.add("not-selected"):e.classList.remove("not-selected");or()}));const ir="1.1.5",ar=document.querySelector("#version");function lr(e,t=!0){if(t)return void(ar.textContent="v"+e);const s=document.createElement("a");s.href="https://github.com/yoannchb-pro/MoodleGPT",s.rel="noopener noreferrer",s.target="_blank",s.textContent="v"+e,ar.appendChild(s),ar.appendChild(document.createTextNode(" is now available !"))}!function(){n(this,void 0,void 0,(function*(){const e=yield function(){return n(this,void 0,void 0,(function*(){const e=yield fetch("https://raw.githubusercontent.com/yoannchb-pro/MoodleGPT/main/package.json");return(yield e.json()).version}))}().catch((e=>(console.error(e),ir))),t=e.split("."),s=ir.split("."),r=Math.min(t.length,s.length);for(let n=0;n<r;++n){if(parseInt(t[n])>parseInt(s[n]))return lr(e,!1);if(parseInt(s[n])>parseInt(t[n]))return lr(ir)}lr(ir)}))}();const cr=document.querySelector("#settings"),ur=document.querySelector("#advanced-settings"),hr=document.querySelector("#switch-settings");hr.addEventListener("click",(function(e){e.preventDefault(),"flex"===ur.style.display?(cr.style.display="flex",ur.style.display="none",hr.textContent="Advanced settings"):(cr.style.display="none",ur.style.display="flex",hr.textContent="Go back to settings")}));const dr=document.querySelector(".save"),fr=["apiKey","code","model","baseURL","maxTokens"];dr.addEventListener("click",(function(){const[s,n,r,o,i]=fr.map((e=>document.querySelector("#"+e).value.trim())),[a,l,c,u,h,d,f,p,m]=t.map((e=>{const t=document.querySelector("#"+e);return t.checked&&"none"!==t.parentElement.style.display}));s&&r?n.length>0&&n.length<2?Gn({msg:"The code should at least contain 2 characters",isError:!0}):(chrome.storage.sync.set({moodleGPT:{apiKey:s,code:n,model:r,baseURL:o,maxTokens:i?parseInt(i):void 0,logs:a,title:l,cursor:c,typing:u,mouseover:h,infinite:d,timeout:f,history:p,includeImages:m,mode:e.actualMode}}),Gn({msg:"Configuration saved"})):Gn({msg:"Please complete all the form",isError:!0})})),chrome.storage.sync.get(["moodleGPT"]).then((function(n){const r=n.moodleGPT;if(r){if(r.mode){e.actualMode=r.mode;for(const e of s)e.value===r.mode?e.classList.remove("not-selected"):e.classList.add("not-selected")}fr.forEach((e=>r[e]?document.querySelector("#"+e).value=r[e]:null)),t.forEach((e=>document.querySelector("#"+e).checked=r[e]||""))}or(),sr()}))}));
|
|
//# sourceMappingURL=popup.js.map
|