3 lines
123 KiB
JavaScript
3 lines
123 KiB
JavaScript
!function(e){"function"==typeof define&&define.amd?define(e):e()}((function(){"use strict";var e,t,n,s,r,o,i,a,l,c,u,d,h,p,f={},_=[],m=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,g=Array.isArray;function y(e,t){for(var n in t)e[n]=t[n];return e}function b(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function w(e,s,r,o,i){var a={type:e,props:s,key:r,ref:o,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:null==i?++n:i,__i:-1,__u:0};return null==i&&null!=t.vnode&&t.vnode(a),a}function v(e){return e.children}function x(e,t){this.props=e,this.context=t}function S(e,t){if(null==t)return e.__?S(e.__,e.__i+1):null;for(var n;t<e.__k.length;t++)if(null!=(n=e.__k[t])&&null!=n.__e)return n.__e;return"function"==typeof e.type?S(e):null}function k(e){if(e.__P&&e.__d){var n=e.__v,s=n.__e,r=[],o=[],i=y({},n);i.__v=n.__v+1,t.vnode&&t.vnode(i),M(e.__P,i,n,e.__n,e.__P.namespaceURI,32&n.__u?[s]:null,r,null==s?S(n):s,!!(32&n.__u),o),i.__v=n.__v,i.__.__k[i.__i]=i,L(r,i,o),n.__e=n.__=null,i.__e!=s&&$(i)}}function $(e){if(null!=(e=e.__)&&null!=e.__c)return e.__e=e.__c.base=null,e.__k.some((function(t){if(null!=t&&null!=t.__e)return e.__e=e.__c.base=t.__e})),$(e)}function A(e){(!e.__d&&(e.__d=!0)&&s.push(e)&&!I.__r++||r!=t.debounceRendering)&&((r=t.debounceRendering)||o)(I)}function I(){try{for(var e,t=1;s.length;)s.length>t&&s.sort(i),e=s.shift(),t=s.length,k(e)}finally{s.length=I.__r=0}}function O(e,t,n,s,r,o,i,a,l,c,u){var d,h,p,m,g,y,b,w=s&&s.__k||_,v=t.length;for(l=R(n,t,w,l,v),d=0;d<v;d++)null!=(p=n.__k[d])&&(h=-1!=p.__i&&w[p.__i]||f,p.__i=d,y=M(e,p,h,r,o,i,a,l,c,u),m=p.__e,p.ref&&h.ref!=p.ref&&(h.ref&&W(h.ref,null,p),u.push(p.ref,p.__c||m,p)),null==g&&null!=m&&(g=m),(b=!!(4&p.__u))||h.__k===p.__k?(l=P(p,l,e,b),b&&h.__e&&(h.__e=null)):"function"==typeof p.type&&void 0!==y?l=y:m&&(l=m.nextSibling),p.__u&=-7);return n.__e=g,l}function R(e,t,n,s,r){var o,i,a,l,c,u=n.length,d=u,h=0;for(e.__k=new Array(r),o=0;o<r;o++)null!=(i=t[o])&&"boolean"!=typeof i&&"function"!=typeof i?("string"==typeof i||"number"==typeof i||"bigint"==typeof i||i.constructor==String?i=e.__k[o]=w(null,i,null,null,null):g(i)?i=e.__k[o]=w(v,{children:i},null,null,null):void 0===i.constructor&&i.__b>0?i=e.__k[o]=w(i.type,i.props,i.key,i.ref?i.ref:null,i.__v):e.__k[o]=i,l=o+h,i.__=e,i.__b=e.__b+1,a=null,-1!=(c=i.__i=C(i,n,l,d))&&(d--,(a=n[c])&&(a.__u|=2)),null==a||null==a.__v?(-1==c&&(r>u?h--:r<u&&h++),"function"!=typeof i.type&&(i.__u|=4)):c!=l&&(c==l-1?h--:c==l+1?h++:(c>l?h--:h++,i.__u|=4))):e.__k[o]=null;if(d)for(o=0;o<u;o++)null!=(a=n[o])&&!(2&a.__u)&&(a.__e==s&&(s=S(a)),B(a,a));return s}function P(e,t,n,s){var r,o;if("function"==typeof e.type){for(r=e.__k,o=0;r&&o<r.length;o++)r[o]&&(r[o].__=e,t=P(r[o],t,n,s));return t}e.__e!=t&&(s&&(t&&e.type&&!t.parentNode&&(t=S(e)),n.insertBefore(e.__e,t||null)),t=e.__e);do{t=t&&t.nextSibling}while(null!=t&&8==t.nodeType);return t}function C(e,t,n,s){var r,o,i,a=e.key,l=e.type,c=t[n],u=null!=c&&!(2&c.__u);if(null===c&&null==a||u&&a==c.key&&l==c.type)return n;if(s>(u?1:0))for(r=n-1,o=n+1;r>=0||o<t.length;)if(null!=(c=t[i=r>=0?r--:o++])&&!(2&c.__u)&&a==c.key&&l==c.type)return i;return-1}function E(e,t,n){"-"==t[0]?e.setProperty(t,null==n?"":n):e[t]=null==n?"":"number"!=typeof n||m.test(t)?n:n+"px"}function T(e,t,n,s,r){var o,i;e:if("style"==t)if("string"==typeof n)e.style.cssText=n;else{if("string"==typeof s&&(e.style.cssText=s=""),s)for(t in s)n&&t in n||E(e.style,t,"");if(n)for(t in n)s&&n[t]==s[t]||E(e.style,t,n[t])}else if("o"==t[0]&&"n"==t[1])o=t!=(t=t.replace(u,"$1")),i=t.toLowerCase(),t=i in e||"onFocusOut"==t||"onFocusIn"==t?i.slice(2):t.slice(2),e.l||(e.l={}),e.l[t+o]=n,n?s?n[c]=s[c]:(n[c]=d,e.addEventListener(t,o?p:h,o)):e.removeEventListener(t,o?p:h,o);else{if("http://www.w3.org/2000/svg"==r)t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if("width"!=t&&"height"!=t&&"href"!=t&&"list"!=t&&"form"!=t&&"tabIndex"!=t&&"download"!=t&&"rowSpan"!=t&&"colSpan"!=t&&"role"!=t&&"popover"!=t&&t in e)try{e[t]=null==n?"":n;break e}catch(e){}"function"==typeof n||(null==n||!1===n&&"-"!=t[4]?e.removeAttribute(t):e.setAttribute(t,"popover"==t&&1==n?"":n))}}function j(e){return function(n){if(this.l){var s=this.l[n.type+e];if(null==n[l])n[l]=d++;else if(n[l]<s[c])return;return s(t.event?t.event(n):n)}}}function M(e,n,s,r,o,i,a,l,c,u){var d,h,p,f,m,w,S,k,$,A,I,R,P,C,E,T=n.type;if(void 0!==n.constructor)return null;128&s.__u&&(c=!!(32&s.__u),i=[l=n.__e=s.__e]),(d=t.__b)&&d(n);e:if("function"==typeof T)try{if(k=n.props,$=T.prototype&&T.prototype.render,A=(d=T.contextType)&&r[d.__c],I=d?A?A.props.value:d.__:r,s.__c?S=(h=n.__c=s.__c).__=h.__E:($?n.__c=h=new T(k,I):(n.__c=h=new x(k,I),h.constructor=T,h.render=U),A&&A.sub(h),h.state||(h.state={}),h.__n=r,p=h.__d=!0,h.__h=[],h._sb=[]),$&&null==h.__s&&(h.__s=h.state),$&&null!=T.getDerivedStateFromProps&&(h.__s==h.state&&(h.__s=y({},h.__s)),y(h.__s,T.getDerivedStateFromProps(k,h.__s))),f=h.props,m=h.state,h.__v=n,p)$&&null==T.getDerivedStateFromProps&&null!=h.componentWillMount&&h.componentWillMount(),$&&null!=h.componentDidMount&&h.__h.push(h.componentDidMount);else{if($&&null==T.getDerivedStateFromProps&&k!==f&&null!=h.componentWillReceiveProps&&h.componentWillReceiveProps(k,I),n.__v==s.__v||!h.__e&&null!=h.shouldComponentUpdate&&!1===h.shouldComponentUpdate(k,h.__s,I)){n.__v!=s.__v&&(h.props=k,h.state=h.__s,h.__d=!1),n.__e=s.__e,n.__k=s.__k,n.__k.some((function(e){e&&(e.__=n)})),_.push.apply(h.__h,h._sb),h._sb=[],h.__h.length&&a.push(h);break e}null!=h.componentWillUpdate&&h.componentWillUpdate(k,h.__s,I),$&&null!=h.componentDidUpdate&&h.__h.push((function(){h.componentDidUpdate(f,m,w)}))}if(h.context=I,h.props=k,h.__P=e,h.__e=!1,R=t.__r,P=0,$)h.state=h.__s,h.__d=!1,R&&R(n),d=h.render(h.props,h.state,h.context),_.push.apply(h.__h,h._sb),h._sb=[];else do{h.__d=!1,R&&R(n),d=h.render(h.props,h.state,h.context),h.state=h.__s}while(h.__d&&++P<25);h.state=h.__s,null!=h.getChildContext&&(r=y(y({},r),h.getChildContext())),$&&!p&&null!=h.getSnapshotBeforeUpdate&&(w=h.getSnapshotBeforeUpdate(f,m)),C=null!=d&&d.type===v&&null==d.key?D(d.props.children):d,l=O(e,g(C)?C:[C],n,s,r,o,i,a,l,c,u),h.base=n.__e,n.__u&=-161,h.__h.length&&a.push(h),S&&(h.__E=h.__=null)}catch(e){if(n.__v=null,c||null!=i)if(e.then){for(n.__u|=c?160:128;l&&8==l.nodeType&&l.nextSibling;)l=l.nextSibling;i[i.indexOf(l)]=null,n.__e=l}else{for(E=i.length;E--;)b(i[E]);N(n)}else n.__e=s.__e,n.__k=s.__k,e.then||N(n);t.__e(e,n,s)}else null==i&&n.__v==s.__v?(n.__k=s.__k,n.__e=s.__e):l=n.__e=q(s.__e,n,s,r,o,i,a,c,u);return(d=t.diffed)&&d(n),128&n.__u?void 0:l}function N(e){e&&(e.__c&&(e.__c.__e=!0),e.__k&&e.__k.some(N))}function L(e,n,s){for(var r=0;r<s.length;r++)W(s[r],s[++r],s[++r]);t.__c&&t.__c(n,e),e.some((function(n){try{e=n.__h,n.__h=[],e.some((function(e){e.call(n)}))}catch(e){t.__e(e,n.__v)}}))}function D(e){return"object"!=typeof e||null==e||e.__b>0?e:g(e)?e.map(D):y({},e)}function q(n,s,r,o,i,a,l,c,u){var d,h,p,_,m,y,w,v=r.props||f,x=s.props,k=s.type;if("svg"==k?i="http://www.w3.org/2000/svg":"math"==k?i="http://www.w3.org/1998/Math/MathML":i||(i="http://www.w3.org/1999/xhtml"),null!=a)for(d=0;d<a.length;d++)if((m=a[d])&&"setAttribute"in m==!!k&&(k?m.localName==k:3==m.nodeType)){n=m,a[d]=null;break}if(null==n){if(null==k)return document.createTextNode(x);n=document.createElementNS(i,k,x.is&&x),c&&(t.__m&&t.__m(s,a),c=!1),a=null}if(null==k)v===x||c&&n.data==x||(n.data=x);else{if(a=a&&e.call(n.childNodes),!c&&null!=a)for(v={},d=0;d<n.attributes.length;d++)v[(m=n.attributes[d]).name]=m.value;for(d in v)m=v[d],"dangerouslySetInnerHTML"==d?p=m:"children"==d||d in x||"value"==d&&"defaultValue"in x||"checked"==d&&"defaultChecked"in x||T(n,d,null,m,i);for(d in x)m=x[d],"children"==d?_=m:"dangerouslySetInnerHTML"==d?h=m:"value"==d?y=m:"checked"==d?w=m:c&&"function"!=typeof m||v[d]===m||T(n,d,m,v[d],i);if(h)c||p&&(h.__html==p.__html||h.__html==n.innerHTML)||(n.innerHTML=h.__html),s.__k=[];else if(p&&(n.innerHTML=""),O("template"==s.type?n.content:n,g(_)?_:[_],s,r,o,"foreignObject"==k?"http://www.w3.org/1999/xhtml":i,a,l,a?a[0]:r.__k&&S(r,0),c,u),null!=a)for(d=a.length;d--;)b(a[d]);c||(d="value","progress"==k&&null==y?n.removeAttribute("value"):null!=y&&(y!==n[d]||"progress"==k&&!y||"option"==k&&y!=v[d])&&T(n,d,y,v[d],i),d="checked",null!=w&&w!=n[d]&&T(n,d,w,v[d],i))}return n}function W(e,n,s){try{if("function"==typeof e){var r="function"==typeof e.__u;r&&e.__u(),r&&null==n||(e.__u=e(n))}else e.current=n}catch(e){t.__e(e,s)}}function B(e,n,s){var r,o;if(t.unmount&&t.unmount(e),(r=e.ref)&&(r.current&&r.current!=e.__e||W(r,null,n)),null!=(r=e.__c)){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(e){t.__e(e,n)}r.base=r.__P=null}if(r=e.__k)for(o=0;o<r.length;o++)r[o]&&B(r[o],n,s||"function"!=typeof e.type);s||b(e.__e),e.__c=e.__=e.__e=void 0}function U(e,t,n){return this.constructor(e,n)}e=_.slice,t={__e:function(e,t,n,s){for(var r,o,i;t=t.__;)if((r=t.__c)&&!r.__)try{if((o=r.constructor)&&null!=o.getDerivedStateFromError&&(r.setState(o.getDerivedStateFromError(e)),i=r.__d),null!=r.componentDidCatch&&(r.componentDidCatch(e,s||{}),i=r.__d),i)return r.__E=r}catch(t){e=t}throw e}},n=0,x.prototype.setState=function(e,t){var n;n=null!=this.__s&&this.__s!=this.state?this.__s:this.__s=y({},this.state),"function"==typeof e&&(e=e(y({},n),this.props)),e&&y(n,e),null!=e&&this.__v&&(t&&this._sb.push(t),A(this))},x.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),A(this))},x.prototype.render=v,s=[],o="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,i=function(e,t){return e.__v.__b-t.__v.__b},I.__r=0,a=Math.random().toString(8),l="__d"+a,c="__a"+a,u=/(PointerCapture)$|Capture$/i,d=0,h=j(!1),p=j(!0);var F=0;function H(e,n,s,r,o,i){n||(n={});var a,l,c=n;if("ref"in c)for(l in c={},n)"ref"==l?a=n[l]:c[l]=n[l];var u={type:e,props:c,key:s,ref:a,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--F,__i:-1,__u:0,__source:o,__self:i};if("function"==typeof e&&(a=e.defaultProps))for(l in a)void 0===c[l]&&(c[l]=a[l]);return t.vnode&&t.vnode(u),u}function X(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{l(s.next(e))}catch(e){o(e)}}function a(e){try{l(s.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}l((s=s.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;var K,J,V,z,G=0,Q=[],Y=t,Z=Y.__b,ee=Y.__r,te=Y.diffed,ne=Y.__c,se=Y.unmount,re=Y.__;function oe(e,t){Y.__h&&Y.__h(J,e,G||t),G=0;var n=J.__H||(J.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function ie(e){return G=1,function(e,t){var n=oe(K++,2);if(n.t=e,!n.__c&&(n.__=[pe(void 0,t),function(e){var t=n.__N?n.__N[0]:n.__[0],s=n.t(t,e);t!==s&&(n.__N=[s,n.__[1]],n.__c.setState({}))}],n.__c=J,!J.__f)){var s=function(e,t,s){if(!n.__c.__H)return!0;var o=n.__c.__H.__.filter((function(e){return e.__c}));if(o.every((function(e){return!e.__N})))return!r||r.call(this,e,t,s);var i=n.__c.props!==e;return o.some((function(e){if(e.__N){var t=e.__[0];e.__=e.__N,e.__N=void 0,t!==e.__[0]&&(i=!0)}})),r&&r.call(this,e,t,s)||i};J.__f=!0;var r=J.shouldComponentUpdate,o=J.componentWillUpdate;J.componentWillUpdate=function(e,t,n){if(this.__e){var i=r;r=void 0,s(e,t,n),r=i}o&&o.call(this,e,t,n)},J.shouldComponentUpdate=s}return n.__N||n.__}(pe,e)}function ae(e,t){var n=oe(K++,3);!Y.__s&&function(e,t){return!e||e.length!==t.length||t.some((function(t,n){return t!==e[n]}))}(n.__H,t)&&(n.__=e,n.u=t,J.__H.__h.push(n))}function le(){for(var e;e=Q.shift();){var t=e.__H;if(e.__P&&t)try{t.__h.some(de),t.__h.some(he),t.__h=[]}catch(n){t.__h=[],Y.__e(n,e.__v)}}}Y.__b=function(e){J=null,Z&&Z(e)},Y.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),re&&re(e,t)},Y.__r=function(e){ee&&ee(e),K=0;var t=(J=e.__c).__H;t&&(V===J?(t.__h=[],J.__h=[],t.__.some((function(e){e.__N&&(e.__=e.__N),e.u=e.__N=void 0}))):(t.__h.some(de),t.__h.some(he),t.__h=[],K=0)),V=J},Y.diffed=function(e){te&&te(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(1!==Q.push(t)&&z===Y.requestAnimationFrame||((z=Y.requestAnimationFrame)||ue)(le)),t.__H.__.some((function(e){e.u&&(e.__H=e.u),e.u=void 0}))),V=J=null},Y.__c=function(e,t){t.some((function(e){try{e.__h.some(de),e.__h=e.__h.filter((function(e){return!e.__||he(e)}))}catch(n){t.some((function(e){e.__h&&(e.__h=[])})),t=[],Y.__e(n,e.__v)}})),ne&&ne(e,t)},Y.unmount=function(e){se&&se(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.some((function(e){try{de(e)}catch(e){t=e}})),n.__H=void 0,t&&Y.__e(t,n.__v))};var ce="function"==typeof requestAnimationFrame;function ue(e){var t,n=function(){clearTimeout(s),ce&&cancelAnimationFrame(t),setTimeout(e)},s=setTimeout(n,35);ce&&(t=requestAnimationFrame(n))}function de(e){var t=J,n=e.__c;"function"==typeof n&&(e.__c=void 0,n()),J=t}function he(e){var t=J;e.__c=e.__(),J=t}function pe(e,t){return"function"==typeof t?t(e):t}function fe(){const[e,t]=ie("2.0.0"),[n,s]=ie(!1);return ae((()=>{(()=>{X(this,void 0,void 0,(function*(){try{const n=yield fetch("https://raw.githubusercontent.com/yoannchb-pro/MoodleGPT/main/package.json"),r=(yield n.json()).version,o=r.split("."),i=e.split("."),a=Math.min(o.length,i.length);for(let e=0;e<a;++e){if(parseInt(o[e])>parseInt(i[e]))return t(r),void s(!0);if(parseInt(i[e])>parseInt(o[e]))return}}catch(e){console.error(e)}}))})()}),[]),H("div",{class:"flex items-center gap-4 mb-2",children:[H("img",{src:"../icon.png",alt:"SparkAssist Logo",class:"w-12 h-12 drop-shadow-md animate-float"}),H("div",{children:[H("h1",{class:"m-0 text-2xl font-bold bg-gradient-to-r from-indigo-300 to-indigo-400 bg-clip-text text-transparent",children:"SparkAssist"}),H("p",{class:"m-0 mt-1 text-xs text-text-secondary",children:n?H(v,{children:[H("a",{href:"https://github.com/yoannchb-pro/MoodleGPT",target:"_blank",rel:"noopener noreferrer",class:"text-sky-400 no-underline font-medium hover:text-sky-300 transition-colors",children:["v",e]})," ","is now available !"]}):`v${e}`})]})]})}function _e(e,t,n,s,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,n),n}function me(e,t,n,s){if("a"===n&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?s:"a"===n?s.call(e):s?s.value:t.get(e)}let ge=function(){const{crypto:e}=globalThis;if(e?.randomUUID)return ge=e.randomUUID.bind(e),e.randomUUID();const t=new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>255*Math.random()&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(e=>(+e^n()&15>>+e/4).toString(16)))};function ye(e){return"object"==typeof e&&null!==e&&("name"in e&&"AbortError"===e.name||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}const be=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 we extends Error{}class ve extends we{constructor(e,t,n,s){super(`${ve.makeMessage(e,t,n)}`),this.status=e,this.headers=s,this.requestID=s?.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,n){const s=t?.message?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,t,n,s){if(!e||!s)return new Se({message:n,cause:be(t)});const r=t?.error;return 400===e?new $e(e,r,n,s):401===e?new Ae(e,r,n,s):403===e?new Ie(e,r,n,s):404===e?new Oe(e,r,n,s):409===e?new Re(e,r,n,s):422===e?new Pe(e,r,n,s):429===e?new Ce(e,r,n,s):e>=500?new Ee(e,r,n,s):new ve(e,r,n,s)}}class xe extends ve{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class Se extends ve{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class ke extends Se{constructor({message:e}={}){super({message:e??"Request timed out."})}}class $e extends ve{}class Ae extends ve{}class Ie extends ve{}class Oe extends ve{}class Re extends ve{}class Pe extends ve{}class Ce extends ve{}class Ee extends ve{}class Te extends we{constructor(){super("Could not parse response content as the length limit was reached")}}class je extends we{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class Me extends Error{constructor(e){super(e)}}const Ne=/^[a-z][a-z0-9+.-]*:/i;let Le=e=>(Le=Array.isArray,Le(e)),De=Le;function qe(e){return"object"!=typeof e?{}:e??{}}function We(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)}const Be=e=>new Promise((t=>setTimeout(t,e))),Ue="5.23.2";const Fe=()=>{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":Ue,"X-Stainless-OS":Xe(Deno.build.os),"X-Stainless-Arch":He(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":Ue,"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":Ue,"X-Stainless-OS":Xe(globalThis.process.platform??"unknown"),"X-Stainless-Arch":He(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:n}of e){const e=n.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":Ue,"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":Ue,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};const He=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",Xe=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 Ke;function Je(...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 Ve(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return Je({start(){},async pull(e){const{done:n,value:s}=await t.next();n?e.close():e.enqueue(s)},async cancel(){await(t.return?.())}})}function ze(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 Ge=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)}),Qe="RFC3986",Ye=e=>String(e),Ze={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:Ye};let et=(e,t)=>(et=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),et(e,t));const tt=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),nt=1024;function st(e,t){if(Le(e)){const n=[];for(let s=0;s<e.length;s+=1)n.push(t(e[s]));return n}return t(e)}const rt={brackets:e=>String(e)+"[]",comma:"comma",indices:(e,t)=>String(e)+"["+t+"]",repeat:e=>String(e)},ot=function(e,t){Array.prototype.push.apply(e,Le(t)?t:[t])};let it;const at={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:(e,t,n,s,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"===n)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+=nt){const t=o.length>=nt?o.slice(e,e+nt):o,n=[];for(let e=0;e<t.length;++e){let s=t.charCodeAt(e);45===s||46===s||95===s||126===s||s>=48&&s<=57||s>=65&&s<=90||s>=97&&s<=122||"RFC1738"===r&&(40===s||41===s)?n[n.length]=t.charAt(e):s<128?n[n.length]=tt[s]:s<2048?n[n.length]=tt[192|s>>6]+tt[128|63&s]:s<55296||s>=57344?n[n.length]=tt[224|s>>12]+tt[128|s>>6&63]+tt[128|63&s]:(e+=1,s=65536+((1023&s)<<10|1023&t.charCodeAt(e)),n[n.length]=tt[240|s>>18]+tt[128|s>>12&63]+tt[128|s>>6&63]+tt[128|63&s])}i+=n.join("")}return i},encodeValuesOnly:!1,format:Qe,formatter:Ye,indices:!1,serializeDate:e=>(it??(it=Function.prototype.call.bind(Date.prototype.toISOString)))(e),skipNulls:!1,strictNullHandling:!1};const lt={};function ct(e,t,n,s,r,o,i,a,l,c,u,d,h,p,f,_,m,g){let y=e,b=g,w=0,v=!1;for(;void 0!==(b=b.get(lt))&&!v;){const t=b.get(e);if(w+=1,void 0!==t){if(t===w)throw new RangeError("Cyclic object value");v=!0}void 0===b.get(lt)&&(w=0)}if("function"==typeof c?y=c(t,y):y instanceof Date?y=h?.(y):"comma"===n&&Le(y)&&(y=st(y,(function(e){return e instanceof Date?h?.(e):e}))),null===y){if(o)return l&&!_?l(t,at.encoder,m,"key",p):t;y=""}if(function(e){return"string"==typeof e||"number"==typeof e||"boolean"==typeof e||"symbol"==typeof e||"bigint"==typeof e}(y)||function(e){return!(!e||"object"!=typeof e||!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e)))}(y)){if(l){const e=_?t:l(t,at.encoder,m,"key",p);return[f?.(e)+"="+f?.(l(y,at.encoder,m,"value",p))]}return[f?.(t)+"="+f?.(String(y))]}const x=[];if(void 0===y)return x;let S;if("comma"===n&&Le(y))_&&l&&(y=st(y,l)),S=[{value:y.length>0?y.join(",")||null:void 0}];else if(Le(c))S=c;else{const e=Object.keys(y);S=u?e.sort(u):e}const k=a?String(t).replace(/\./g,"%2E"):String(t),$=s&&Le(y)&&1===y.length?k+"[]":k;if(r&&Le(y)&&0===y.length)return $+"[]";for(let t=0;t<S.length;++t){const b=S[t],v="object"==typeof b&&void 0!==b.value?b.value:y[b];if(i&&null===v)continue;const k=d&&a?b.replace(/\./g,"%2E"):b,A=Le(y)?"function"==typeof n?n($,k):$:$+(d?"."+k:"["+k+"]");g.set(e,w);const I=new WeakMap;I.set(lt,g),ot(x,ct(v,A,n,s,r,o,i,a,"comma"===n&&_&&Le(y)?null:l,c,u,d,h,p,f,_,m,I))}return x}function ut(e,t={}){let n=e;const s=function(e=at){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||at.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 n=Qe;if(void 0!==e.format){if(!et(Ze,e.format))throw new TypeError("Unknown format option provided.");n=e.format}const s=Ze[n];let r,o=at.filter;if(("function"==typeof e.filter||Le(e.filter))&&(o=e.filter),r=e.arrayFormat&&e.arrayFormat in rt?e.arrayFormat:"indices"in e?e.indices?"indices":"repeat":at.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||at.allowDots:!!e.allowDots;return{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:at.addQueryPrefix,allowDots:i,allowEmptyArrays:"boolean"==typeof e.allowEmptyArrays?!!e.allowEmptyArrays:at.allowEmptyArrays,arrayFormat:r,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:at.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:void 0===e.delimiter?at.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:at.encode,encodeDotInKeys:"boolean"==typeof e.encodeDotInKeys?e.encodeDotInKeys:at.encodeDotInKeys,encoder:"function"==typeof e.encoder?e.encoder:at.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:at.encodeValuesOnly,filter:o,format:n,formatter:s,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:at.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:at.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:at.strictNullHandling}}(t);let r,o;"function"==typeof s.filter?(o=s.filter,n=o("",n)):Le(s.filter)&&(o=s.filter,r=o);const i=[];if("object"!=typeof n||null===n)return"";const a=rt[s.arrayFormat],l="comma"===a&&s.commaRoundTrip;r||(r=Object.keys(n)),s.sort&&r.sort(s.sort);const c=new WeakMap;for(let e=0;e<r.length;++e){const t=r[e];s.skipNulls&&null===n[t]||ot(i,ct(n[t],t,a,l,s.allowEmptyArrays,s.strictNullHandling,s.skipNulls,s.encodeDotInKeys,s.encode?s.encoder:null,s.filter,s.sort,s.allowDots,s.serializeDate,s.format,s.formatter,s.encodeValuesOnly,s.charset,c))}const u=i.join(s.delimiter);let d=!0===s.addQueryPrefix?"?":"";return s.charsetSentinel&&("iso-8859-1"===s.charset?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),u.length>0?d+u:""}let dt,ht;function pt(e){let t;return(dt??(t=new globalThis.TextEncoder,dt=t.encode.bind(t)))(e)}function ft(e){let t;return(ht??(t=new globalThis.TextDecoder,ht=t.decode.bind(t)))(e)}var _t,mt;class gt{constructor(){_t.set(this,void 0),mt.set(this,void 0),_e(this,_t,new Uint8Array),_e(this,mt,null)}decode(e){if(null==e)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):"string"==typeof e?pt(e):e;_e(this,_t,function(e){let t=0;for(const n of e)t+=n.length;const n=new Uint8Array(t);let s=0;for(const t of e)n.set(t,s),s+=t.length;return n}([me(this,_t,"f"),t]));const n=[];let s;for(;null!=(s=yt(me(this,_t,"f"),me(this,mt,"f")));){if(s.carriage&&null==me(this,mt,"f")){_e(this,mt,s.index);continue}if(null!=me(this,mt,"f")&&(s.index!==me(this,mt,"f")+1||s.carriage)){n.push(ft(me(this,_t,"f").subarray(0,me(this,mt,"f")-1))),_e(this,_t,me(this,_t,"f").subarray(me(this,mt,"f"))),_e(this,mt,null);continue}const e=null!==me(this,mt,"f")?s.preceding-1:s.preceding,t=ft(me(this,_t,"f").subarray(0,e));n.push(t),_e(this,_t,me(this,_t,"f").subarray(s.index)),_e(this,mt,null)}return n}flush(){return me(this,_t,"f").length?this.decode("\n"):[]}}function yt(e,t){for(let n=t??0;n<e.length;n++){if(10===e[n])return{preceding:n,index:n+1,carriage:!1};if(13===e[n])return{preceding:n,index:n+1,carriage:!0}}return null}function bt(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}_t=new WeakMap,mt=new WeakMap,gt.NEWLINE_CHARS=new Set(["\n","\r"]),gt.NEWLINE_REGEXP=/\r\n|[\n\r]/g;const wt={off:0,error:200,warn:300,info:400,debug:500},vt=(e,t,n)=>{var s,r;if(e)return s=wt,r=e,Object.prototype.hasOwnProperty.call(s,r)?e:void At(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(wt))}`)};function xt(){}function St(e,t,n){return!t||wt[e]>wt[n]?xt:t[e].bind(t)}const kt={error:xt,warn:xt,info:xt,debug:xt};let $t=new WeakMap;function At(e){const t=e.logger,n=e.logLevel??"off";if(!t)return kt;const s=$t.get(t);if(s&&s[0]===n)return s[1];const r={error:St("error",t,n),warn:St("warn",t,n),info:St("info",t,n),debug:St("debug",t,n)};return $t.set(t,[n,r]),r}const It=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 Ot,Rt,Pt;class Ct{constructor(e,t,n){this.iterator=e,Ot.set(this,void 0),this.controller=t,_e(this,Ot,n)}static fromSSEResponse(e,t,n){let s=!1;const r=n?At(n):console;return new Ct((async function*(){if(s)throw new we("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let n=!1;try{for await(const s of async function*(e,t){if(!e.body){if(t.abort(),void 0!==globalThis.navigator&&"ReactNative"===globalThis.navigator.product)throw new we("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 we("Attempted to iterate over a response with no body")}const n=new Et,s=new gt,r=ze(e.body);for await(const e of async function*(e){let t=new Uint8Array;for await(const n of e){if(null==n)continue;const e=n instanceof ArrayBuffer?new Uint8Array(n):"string"==typeof n?pt(n):n;let s,r=new Uint8Array(t.length+e.length);for(r.set(t),r.set(e,t.length),t=r;-1!==(s=bt(t));)yield t.slice(0,s),t=t.slice(s)}t.length>0&&(yield t)}(r))for(const t of s.decode(e)){const e=n.decode(t);e&&(yield e)}for(const e of s.flush()){const t=n.decode(e);t&&(yield t)}}(e,t))if(!n)if(s.data.startsWith("[DONE]"))n=!0;else if(null!==s.event&&s.event.startsWith("thread.")){let e;try{e=JSON.parse(s.data)}catch(e){throw console.error("Could not parse message into JSON:",s.data),console.error("From chunk:",s.raw),e}if("error"==s.event)throw new ve(void 0,e.error,e.message,void 0);yield{event:s.event,data:e}}else{let t;try{t=JSON.parse(s.data)}catch(e){throw r.error("Could not parse message into JSON:",s.data),r.error("From chunk:",s.raw),e}if(t&&t.error)throw new ve(void 0,t.error,void 0,e.headers);yield t}n=!0}catch(e){if(ye(e))return;throw e}finally{n||t.abort()}}),t,n)}static fromReadableStream(e,t,n){let s=!1;return new Ct((async function*(){if(s)throw new we("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let n=!1;try{for await(const t of async function*(){const t=new gt,n=ze(e);for await(const e of n)for(const n of t.decode(e))yield n;for(const e of t.flush())yield e}())n||t&&(yield JSON.parse(t));n=!0}catch(e){if(ye(e))return;throw e}finally{n||t.abort()}}),t,n)}[(Ot=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[],t=[],n=this.iterator(),s=s=>({next:()=>{if(0===s.length){const s=n.next();e.push(s),t.push(s)}return s.shift()}});return[new Ct((()=>s(e)),this.controller,me(this,Ot,"f")),new Ct((()=>s(t)),this.controller,me(this,Ot,"f"))]}toReadableStream(){const e=this;let t;return Je({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{const{value:n,done:s}=await t.next();if(s)return e.close();const r=pt(JSON.stringify(n)+"\n");e.enqueue(r)}catch(t){e.error(t)}},async cancel(){await(t.return?.())}})}}class Et{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,n,s]=function(e,t){const n=e.indexOf(t);if(-1!==n)return[e.substring(0,n),t,e.substring(n+t.length)];return[e,"",""]}(e,":");return s.startsWith(" ")&&(s=s.substring(1)),"event"===t?this.event=s:"data"===t&&this.data.push(s),null}}async function Tt(e,t){const{response:n,requestLogID:s,retryOfRequestLogID:r,startTime:o}=t,i=await(async()=>{if(t.options.stream)return At(e).debug("response",n.status,n.url,n.headers,n.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(n,t.controller,e):Ct.fromSSEResponse(n,t.controller,e);if(204===n.status)return null;if(t.options.__binaryResponse)return n;const s=n.headers.get("content-type"),r=s?.split(";")[0]?.trim();if(r?.includes("application/json")||r?.endsWith("+json")){return jt(await n.json(),n)}return await n.text()})();return At(e).debug(`[${s}] response parsed`,It({retryOfRequestLogID:r,url:n.url,status:n.status,body:i,durationMs:Date.now()-o})),i}function jt(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 Mt extends Promise{constructor(e,t,n=Tt){super((e=>{e(null)})),this.responsePromise=t,this.parseResponse=n,Rt.set(this,void 0),_e(this,Rt,e)}_thenUnwrap(e){return new Mt(me(this,Rt,"f"),this.responsePromise,(async(t,n)=>jt(e(await this.parseResponse(t,n),n),n.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(me(this,Rt,"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)}}Rt=new WeakMap;class Nt{constructor(e,t,n,s){Pt.set(this,void 0),_e(this,Pt,e),this.options=s,this.response=t,this.body=n}hasNextPage(){return!!this.getPaginatedItems().length&&null!=this.nextPageRequestOptions()}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new we("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await me(this,Pt,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Pt=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class Lt extends Mt{constructor(e,t,n){super(e,t,(async(e,t)=>new n(e,t.response,await Tt(e,t),t.options)))}async*[Symbol.asyncIterator](){const e=await(this);for await(const t of e)yield t}}class Dt extends Nt{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class qt extends Nt{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[],this.has_more=n.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:{...qe(this.options.query),after:t}}:null}}class Wt extends Nt{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[],this.has_more=n.has_more||!1,this.last_id=n.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:{...qe(this.options.query),after:e}}:null}}const Bt=()=>{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 Ut(e,t,n){return Bt(),new File(e,t??"unknown_file",n)}function Ft(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 Ht=e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator],Xt=async(e,t)=>({...e,body:await Jt(e.body,t)}),Kt=new WeakMap;const Jt=async(e,t)=>{if(!await function(e){const t="function"==typeof e?e:e.fetch,n=Kt.get(t);if(n)return n;const s=(async()=>{try{const e="Response"in t?t.Response:(await t("data:,")).constructor,n=new FormData;return n.toString()!==await new e(n).text()}catch{return!0}})();return Kt.set(t,s),s}(t))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const n=new FormData;return await Promise.all(Object.entries(e||{}).map((([e,t])=>Vt(n,e,t)))),n},Vt=async(e,t,n)=>{if(void 0!==n){if(null==n)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if("string"==typeof n||"number"==typeof n||"boolean"==typeof n)e.append(t,String(n));else if(n instanceof Response)e.append(t,Ut([await n.blob()],Ft(n)));else if(Ht(n))e.append(t,Ut([await new Response(Ve(n)).blob()],Ft(n)));else if((e=>e instanceof Blob&&"name"in e)(n))e.append(t,n,Ft(n));else if(Array.isArray(n))await Promise.all(n.map((n=>Vt(e,t+"[]",n))));else{if("object"!=typeof n)throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`);await Promise.all(Object.entries(n).map((([n,s])=>Vt(e,`${t}[${n}]`,s))))}}},zt=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 Gt(e){let t=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(zt(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else{if(!Ht(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 n of e)t.push(...await Gt(n))}return t}class Qt{constructor(e){this._client=e}}function Yt(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const Zt=Object.freeze(Object.create(null)),en=(e=Yt)=>function(t,...n){if(1===t.length)return t[0];let s=!1;const r=[],o=t.reduce(((t,o,i)=>{/[?#]/.test(o)&&(s=!0);const a=n[i];let l=(s?encodeURIComponent:e)(""+a);return i!==n.length&&(null==a||"object"==typeof a&&a.toString===Object.getPrototypeOf(Object.getPrototypeOf(a.hasOwnProperty??Zt)??Zt)?.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===n.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,n)=>{const s=" ".repeat(n.start-e),r="^".repeat(n.length);return e=n.start+n.length,t+s+r}),"");throw new we(`Path parameters result in path with invalid segments:\n${r.map((e=>e.error)).join("\n")}\n${o}\n${t}`)}return o},tn=en(Yt);let nn=class extends Qt{list(e,t={},n){return this._client.getAPIList(tn`/chat/completions/${e}/messages`,qt,{query:t,...n})}};function sn(e){return void 0!==e&&"function"in e&&void 0!==e.function}function rn(e){return"auto-parseable-response-format"===e?.$brand}function on(e){return"auto-parseable-tool"===e?.$brand}function an(e,t){const n=e.choices.map((e=>{if("length"===e.finish_reason)throw new Te;if("content_filter"===e.finish_reason)throw new je;return dn(e.message.tool_calls),{...e,message:{...e.message,...e.message.tool_calls?{tool_calls:e.message.tool_calls?.map((e=>function(e,t){const n=e.tools?.find((e=>sn(e)&&e.function?.name===t.function.name));return{...t,function:{...t.function,parsed_arguments:on(n)?n.$parseRaw(t.function.arguments):n?.function.strict?JSON.parse(t.function.arguments):null}}}(t,e)))??void 0}:void 0,parsed:e.message.content&&!e.message.refusal?ln(t,e.message.content):null}}}));return{...e,choices:n}}function ln(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 cn(e,t){if(!e||!("tools"in e)||!e.tools)return!1;const n=e.tools?.find((e=>sn(e)&&e.function?.name===t.function.name));return sn(n)&&(on(n)||n?.function.strict||!1)}function un(e){return!!rn(e.response_format)||(e.tools?.some((e=>on(e)||"function"===e.type&&!0===e.function.strict))??!1)}function dn(e){for(const t of e||[])if("function"!==t.type)throw new we(`Currently only \`function\` tool calls are supported; Received \`${t.type}\``)}const hn=e=>"assistant"===e?.role,pn=e=>"tool"===e?.role;var fn,_n,mn,gn,yn,bn,wn,vn,xn,Sn,kn,$n,An,In,On,Rn,Pn,Cn,En,Tn,jn;class Mn{constructor(){fn.add(this),this.controller=new AbortController,_n.set(this,void 0),mn.set(this,(()=>{})),gn.set(this,(()=>{})),yn.set(this,void 0),bn.set(this,(()=>{})),wn.set(this,(()=>{})),vn.set(this,{}),xn.set(this,!1),Sn.set(this,!1),kn.set(this,!1),$n.set(this,!1),_e(this,_n,new Promise(((e,t)=>{_e(this,mn,e),_e(this,gn,t)}))),_e(this,yn,new Promise(((e,t)=>{_e(this,bn,e),_e(this,wn,t)}))),me(this,_n,"f").catch((()=>{})),me(this,yn,"f").catch((()=>{}))}_run(e){setTimeout((()=>{e().then((()=>{this._emitFinal(),this._emit("end")}),me(this,fn,"m",An).bind(this))}),0)}_connected(){this.ended||(me(this,mn,"f").call(this),this._emit("connect"))}get ended(){return me(this,xn,"f")}get errored(){return me(this,Sn,"f")}get aborted(){return me(this,kn,"f")}abort(){this.controller.abort()}on(e,t){return(me(this,vn,"f")[e]||(me(this,vn,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=me(this,vn,"f")[e];if(!n)return this;const s=n.findIndex((e=>e.listener===t));return s>=0&&n.splice(s,1),this}once(e,t){return(me(this,vn,"f")[e]||(me(this,vn,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise(((t,n)=>{_e(this,$n,!0),"error"!==e&&this.once("error",n),this.once(e,t)}))}async done(){_e(this,$n,!0),await me(this,yn,"f")}_emit(e,...t){if(me(this,xn,"f"))return;"end"===e&&(_e(this,xn,!0),me(this,bn,"f").call(this));const n=me(this,vn,"f")[e];if(n&&(me(this,vn,"f")[e]=n.filter((e=>!e.once)),n.forEach((({listener:e})=>e(...t)))),"abort"===e){const e=t[0];return me(this,$n,"f")||n?.length||Promise.reject(e),me(this,gn,"f").call(this,e),me(this,wn,"f").call(this,e),void this._emit("end")}if("error"===e){const e=t[0];me(this,$n,"f")||n?.length||Promise.reject(e),me(this,gn,"f").call(this,e),me(this,wn,"f").call(this,e),this._emit("end")}}_emitFinal(){}}function Nn(e){return"function"==typeof e.parse}_n=new WeakMap,mn=new WeakMap,gn=new WeakMap,yn=new WeakMap,bn=new WeakMap,wn=new WeakMap,vn=new WeakMap,xn=new WeakMap,Sn=new WeakMap,kn=new WeakMap,$n=new WeakMap,fn=new WeakSet,An=function(e){if(_e(this,Sn,!0),e instanceof Error&&"AbortError"===e.name&&(e=new xe),e instanceof xe)return _e(this,kn,!0),this._emit("abort",e);if(e instanceof we)return this._emit("error",e);if(e instanceof Error){const t=new we(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new we(String(e)))};const Ln=10;class Dn extends Mn{constructor(){super(...arguments),In.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),pn(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(hn(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 we("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),me(this,In,"m",On).call(this)}async finalMessage(){return await this.done(),me(this,In,"m",Rn).call(this)}async finalFunctionToolCall(){return await this.done(),me(this,In,"m",Pn).call(this)}async finalFunctionToolCallResult(){return await this.done(),me(this,In,"m",Cn).call(this)}async totalUsage(){return await this.done(),me(this,In,"m",En).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=me(this,In,"m",Rn).call(this);t&&this._emit("finalMessage",t);const n=me(this,In,"m",On).call(this);n&&this._emit("finalContent",n);const s=me(this,In,"m",Pn).call(this);s&&this._emit("finalFunctionToolCall",s);const r=me(this,In,"m",Cn).call(this);null!=r&&this._emit("finalFunctionToolCallResult",r),this._chatCompletions.some((e=>e.usage))&&this._emit("totalUsage",me(this,In,"m",En).call(this))}async _createChatCompletion(e,t,n){const s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",(()=>this.controller.abort()))),me(this,In,"m",Tn).call(this,t);const r=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(an(r,t))}async _runChatCompletion(e,t,n){for(const e of t.messages)this._addMessage(e,!1);return await this._createChatCompletion(e,t,n)}async _runTools(e,t,n){const s="tool",{tool_choice:r="auto",stream:o,...i}=t,a="string"!=typeof r&&"function"===r.type&&r?.function?.name,{maxChatCompletions:l=Ln}=n||{},c=t.tools.map((e=>{if(on(e)){if(!e.$callback)throw new we("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})),u={};for(const e of c)"function"===e.type&&(u[e.function.name||e.function.function.name]=e.function);const d="tools"in t?c.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<l;++t){const t=await this._createChatCompletion(e,{...i,tool_choice:r,tools:d,messages:[...this.messages]},n),o=t.choices[0]?.message;if(!o)throw new we("missing message in ChatCompletion response");if(!o.tool_calls?.length)return;for(const e of o.tool_calls){if("function"!==e.type)continue;const t=e.id,{name:n,arguments:r}=e.function,o=u[n];if(!o){const e=`Invalid tool_call: ${JSON.stringify(n)}. Available options are: ${Object.keys(u).map((e=>JSON.stringify(e))).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:t,content:e});continue}if(a&&a!==n){const e=`Invalid tool_call: ${JSON.stringify(n)}. ${JSON.stringify(a)} requested. Please try again`;this._addMessage({role:s,tool_call_id:t,content:e});continue}let i;try{i=Nn(o)?await o.parse(r):r}catch(e){const n=e instanceof Error?e.message:String(e);this._addMessage({role:s,tool_call_id:t,content:n});continue}const l=await o.function(i,this),c=me(this,In,"m",jn).call(this,l);if(this._addMessage({role:s,tool_call_id:t,content:c}),a)return}}}}In=new WeakSet,On=function(){return me(this,In,"m",Rn).call(this).content??null},Rn=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(hn(t)){return{...t,content:t.content??null,refusal:t.refusal??null}}}throw new we("stream ended without producing a ChatCompletionMessage with role=assistant")},Pn=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(hn(t)&&t?.tool_calls?.length)return t.tool_calls.filter((e=>"function"===e.type)).at(-1)?.function}},Cn=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(pn(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}},En=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},Tn=function(e){if(null!=e.n&&e.n>1)throw new we("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},jn=function(e){return"string"==typeof e?e:void 0===e?"undefined":JSON.stringify(e)};class qn extends Dn{static runTools(e,t,n){const s=new qn,r={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run((()=>s._runTools(e,t,r))),s}_addMessage(e,t=!0){super._addMessage(e,t),hn(e)&&e.content&&this._emit("content",e.content)}}const Wn=1,Bn=2,Un=4,Fn=8,Hn=16,Xn=32,Kn=64,Jn=128,Vn=256,zn=511;class Gn extends Error{}class Qn extends Error{}const Yn=(e,t)=>{const n=e.length;let s=0;const r=e=>{throw new Gn(`${e} at position ${s}`)},o=e=>{throw new Qn(`${e} at position ${s}`)},i=()=>(d(),s>=n&&r("Unexpected end of input"),'"'===e[s]?a():"{"===e[s]?l():"["===e[s]?c():"null"===e.substring(s,s+4)||Hn&t&&n-s<4&&"null".startsWith(e.substring(s))?(s+=4,null):"true"===e.substring(s,s+4)||Xn&t&&n-s<4&&"true".startsWith(e.substring(s))?(s+=4,!0):"false"===e.substring(s,s+5)||Xn&t&&n-s<5&&"false".startsWith(e.substring(s))?(s+=5,!1):"Infinity"===e.substring(s,s+8)||Jn&t&&n-s<8&&"Infinity".startsWith(e.substring(s))?(s+=8,1/0):"-Infinity"===e.substring(s,s+9)||Vn&t&&1<n-s&&n-s<9&&"-Infinity".startsWith(e.substring(s))?(s+=9,-1/0):"NaN"===e.substring(s,s+3)||Kn&t&&n-s<3&&"NaN".startsWith(e.substring(s))?(s+=3,NaN):u()),a=()=>{const i=s;let a=!1;for(s++;s<n&&('"'!==e[s]||a&&"\\"===e[s-1]);)a="\\"===e[s]&&!a,s++;if('"'==e.charAt(s))try{return JSON.parse(e.substring(i,++s-Number(a)))}catch(e){o(String(e))}else if(Wn&t)try{return JSON.parse(e.substring(i,s-Number(a))+'"')}catch(t){return JSON.parse(e.substring(i,e.lastIndexOf("\\"))+'"')}r("Unterminated string literal")},l=()=>{s++,d();const o={};try{for(;"}"!==e[s];){if(d(),s>=n&&Fn&t)return o;const r=a();d(),s++;try{const e=i();Object.defineProperty(o,r,{value:e,writable:!0,enumerable:!0,configurable:!0})}catch(e){if(Fn&t)return o;throw e}d(),","===e[s]&&s++}}catch(e){if(Fn&t)return o;r("Expected '}' at end of object")}return s++,o},c=()=>{s++;const n=[];try{for(;"]"!==e[s];)n.push(i()),d(),","===e[s]&&s++}catch(e){if(Un&t)return n;r("Expected ']' at end of array")}return s++,n},u=()=>{if(0===s){"-"===e&&Bn&t&&r("Not sure what '-' is");try{return JSON.parse(e)}catch(n){if(Bn&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(n))}}const i=s;for("-"===e[s]&&s++;e[s]&&!",]}".includes(e[s]);)s++;s!=n||Bn&t||r("Unterminated number literal");try{return JSON.parse(e.substring(i,s))}catch(n){"-"===e.substring(i,s)&&Bn&t&&r("Not sure what '-' is");try{return JSON.parse(e.substring(i,e.lastIndexOf("e")))}catch(e){o(String(e))}}},d=()=>{for(;s<n&&" \n\r\t".includes(e[s]);)s++};return i()},Zn=e=>function(e,t=zn){if("string"!=typeof e)throw new TypeError("expecting str, got "+typeof e);if(!e.trim())throw new Error(`${e} is empty`);return Yn(e.trim(),t)}(e,zn^Bn);var es,ts,ns,ss,rs,os,is,as,ls,cs,us,ds;class hs extends Dn{constructor(e){super(),es.add(this),ts.set(this,void 0),ns.set(this,void 0),ss.set(this,void 0),_e(this,ts,e),_e(this,ns,[])}get currentChatCompletionSnapshot(){return me(this,ss,"f")}static fromReadableStream(e){const t=new hs(null);return t._run((()=>t._fromReadableStream(e))),t}static createChatCompletion(e,t,n){const s=new hs(t);return s._run((()=>s._runChatCompletion(e,{...t,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}}))),s}async _createChatCompletion(e,t,n){super._createChatCompletion;const s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",(()=>this.controller.abort()))),me(this,es,"m",rs).call(this);const r=await e.chat.completions.create({...t,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(const e of r)me(this,es,"m",is).call(this,e);if(r.controller.signal?.aborted)throw new xe;return this._addChatCompletion(me(this,es,"m",cs).call(this))}async _fromReadableStream(e,t){const n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",(()=>this.controller.abort()))),me(this,es,"m",rs).call(this),this._connected();const s=Ct.fromReadableStream(e,this.controller);let r;for await(const e of s)r&&r!==e.id&&this._addChatCompletion(me(this,es,"m",cs).call(this)),me(this,es,"m",is).call(this,e),r=e.id;if(s.controller.signal?.aborted)throw new xe;return this._addChatCompletion(me(this,es,"m",cs).call(this))}[(ts=new WeakMap,ns=new WeakMap,ss=new WeakMap,es=new WeakSet,rs=function(){this.ended||_e(this,ss,void 0)},os=function(e){let t=me(this,ns,"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},me(this,ns,"f")[e.index]=t,t)},is=function(e){if(this.ended)return;const t=me(this,es,"m",ds).call(this,e);this._emit("chunk",e,t);for(const n of e.choices){const e=t.choices[n.index];null!=n.delta.content&&"assistant"===e.message?.role&&e.message?.content&&(this._emit("content",n.delta.content,e.message.content),this._emit("content.delta",{delta:n.delta.content,snapshot:e.message.content,parsed:e.message.parsed})),null!=n.delta.refusal&&"assistant"===e.message?.role&&e.message?.refusal&&this._emit("refusal.delta",{delta:n.delta.refusal,snapshot:e.message.refusal}),null!=n.logprobs?.content&&"assistant"===e.message?.role&&this._emit("logprobs.content.delta",{content:n.logprobs?.content,snapshot:e.logprobs?.content??[]}),null!=n.logprobs?.refusal&&"assistant"===e.message?.role&&this._emit("logprobs.refusal.delta",{refusal:n.logprobs?.refusal,snapshot:e.logprobs?.refusal??[]});const s=me(this,es,"m",os).call(this,e);e.finish_reason&&(me(this,es,"m",ls).call(this,e),null!=s.current_tool_call_index&&me(this,es,"m",as).call(this,e,s.current_tool_call_index));for(const t of n.delta.tool_calls??[])s.current_tool_call_index!==t.index&&(me(this,es,"m",ls).call(this,e),null!=s.current_tool_call_index&&me(this,es,"m",as).call(this,e,s.current_tool_call_index)),s.current_tool_call_index=t.index;for(const t of n.delta.tool_calls??[]){const n=e.message.tool_calls?.[t.index];n?.type&&("function"===n?.type&&this._emit("tool_calls.function.arguments.delta",{name:n.function?.name,index:t.index,arguments:n.function.arguments,parsed_arguments:n.function.parsed_arguments,arguments_delta:t.function?.arguments??""}))}}},as=function(e,t){if(me(this,es,"m",os).call(this,e).done_tool_calls.has(t))return;const n=e.message.tool_calls?.[t];if(!n)throw new Error("no tool call snapshot");if(!n.type)throw new Error("tool call snapshot missing `type`");if("function"===n.type){const e=me(this,ts,"f")?.tools?.find((e=>sn(e)&&e.function.name===n.function.name));this._emit("tool_calls.function.arguments.done",{name:n.function.name,index:t,arguments:n.function.arguments,parsed_arguments:on(e)?e.$parseRaw(n.function.arguments):e?.function.strict?JSON.parse(n.function.arguments):null})}else n.type},ls=function(e){const t=me(this,es,"m",os).call(this,e);if(e.message.content&&!t.content_done){t.content_done=!0;const n=me(this,es,"m",us).call(this);this._emit("content.done",{content:e.message.content,parsed:n?n.$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}))},cs=function(){if(this.ended)throw new we("stream has ended, this shouldn't happen");const e=me(this,ss,"f");if(!e)throw new we("request ended without sending any chunks");return _e(this,ss,void 0),_e(this,ns,[]),function(e,t){const{id:n,choices:s,created:r,model:o,system_fingerprint:i,...a}=e,l={...a,id:n,choices:s.map((({message:t,finish_reason:n,index:s,logprobs:r,...o})=>{if(!n)throw new we(`missing finish_reason for choice ${s}`);const{content:i=null,function_call:a,tool_calls:l,...c}=t,u=t.role;if(!u)throw new we(`missing role for choice ${s}`);if(a){const{arguments:e,name:l}=a;if(null==e)throw new we(`missing function_call.arguments for choice ${s}`);if(!l)throw new we(`missing function_call.name for choice ${s}`);return{...o,message:{content:i,function_call:{arguments:e,name:l},role:u,refusal:t.refusal??null},finish_reason:n,index:s,logprobs:r}}return l?{...o,index:s,finish_reason:n,logprobs:r,message:{...c,role:u,content:i,refusal:t.refusal??null,tool_calls:l.map(((t,n)=>{const{function:r,type:o,id:i,...a}=t,{arguments:l,name:c,...u}=r||{};if(null==i)throw new we(`missing choices[${s}].tool_calls[${n}].id\n${ps(e)}`);if(null==o)throw new we(`missing choices[${s}].tool_calls[${n}].type\n${ps(e)}`);if(null==c)throw new we(`missing choices[${s}].tool_calls[${n}].function.name\n${ps(e)}`);if(null==l)throw new we(`missing choices[${s}].tool_calls[${n}].function.arguments\n${ps(e)}`);return{...a,id:i,type:o,function:{...u,name:c,arguments:l}}}))}}:{...o,message:{...c,content:i,role:u,refusal:t.refusal??null},finish_reason:n,index:s,logprobs:r}})),created:r,model:o,object:"chat.completion",...i?{system_fingerprint:i}:{}};return function(e,t){return t&&un(t)?an(e,t):{...e,choices:e.choices.map((e=>(dn(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,me(this,ts,"f"))},us=function(){const e=me(this,ts,"f")?.response_format;return rn(e)?e:null},ds=function(e){var t,n,s,r;let o=me(this,ss,"f");const{choices:i,...a}=e;o?Object.assign(o,a):o=_e(this,ss,{...a,choices:[]});for(const{delta:i,finish_reason:a,index:l,logprobs:c=null,...u}of e.choices){let e=o.choices[l];if(e||(e=o.choices[l]={finish_reason:a,index:l,message:{},logprobs:c,...u}),c)if(e.logprobs){const{content:s,refusal:r,...o}=c;Object.assign(e.logprobs,o),s&&((t=e.logprobs).content??(t.content=[]),e.logprobs.content.push(...s)),r&&((n=e.logprobs).refusal??(n.refusal=[]),e.logprobs.refusal.push(...r))}else e.logprobs=Object.assign({},c);if(a&&(e.finish_reason=a,me(this,ts,"f")&&un(me(this,ts,"f")))){if("length"===a)throw new Te;if("content_filter"===a)throw new je}if(Object.assign(e,u),!i)continue;const{content:d,refusal:h,function_call:p,role:f,tool_calls:_,...m}=i;if(Object.assign(e.message,m),h&&(e.message.refusal=(e.message.refusal||"")+h),f&&(e.message.role=f),p&&(e.message.function_call?(p.name&&(e.message.function_call.name=p.name),p.arguments&&((s=e.message.function_call).arguments??(s.arguments=""),e.message.function_call.arguments+=p.arguments)):e.message.function_call=p),d&&(e.message.content=(e.message.content||"")+d,!e.message.refusal&&me(this,es,"m",us).call(this)&&(e.message.parsed=Zn(e.message.content))),_){e.message.tool_calls||(e.message.tool_calls=[]);for(const{index:t,id:n,type:s,function:o,...i}of _){const a=(r=e.message.tool_calls)[t]??(r[t]={});Object.assign(a,i),n&&(a.id=n),s&&(a.type=s),o&&(a.function??(a.function={name:o.name??"",arguments:""})),o?.name&&(a.function.name=o.name),o?.arguments&&(a.function.arguments+=o.arguments,cn(me(this,ts,"f"),a)&&(a.function.parsed_arguments=Zn(a.function.arguments)))}}}return o},Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("chunk",(n=>{const s=t.shift();s?s.resolve(n):e.push(n)})),this.on("end",(()=>{n=!0;for(const e of t)e.resolve(void 0);t.length=0})),this.on("abort",(e=>{n=!0;for(const n of t)n.reject(e);t.length=0})),this.on("error",(e=>{n=!0;for(const n of t)n.reject(e);t.length=0})),{next:async()=>{if(!e.length)return n?{value:void 0,done:!0}:new Promise(((e,n)=>t.push({resolve:e,reject:n}))).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 Ct(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function ps(e){return JSON.stringify(e)}class fs extends hs{static fromReadableStream(e){const t=new fs(null);return t._run((()=>t._fromReadableStream(e))),t}static runTools(e,t,n){const s=new fs(t),r={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run((()=>s._runTools(e,t,r))),s}}let _s=class extends Qt{constructor(){super(...arguments),this.messages=new nn(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(tn`/chat/completions/${e}`,t)}update(e,t,n){return this._client.post(tn`/chat/completions/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/chat/completions",qt,{query:e,...t})}delete(e,t){return this._client.delete(tn`/chat/completions/${e}`,t)}parse(e,t){return function(e){for(const t of e??[]){if("function"!==t.type)throw new we(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(!0!==t.function.strict)throw new we(`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=>an(t,e)))}runTools(e,t){return e.stream?fs.runTools(this._client,e,t):qn.runTools(this._client,e,t)}stream(e,t){return hs.createChatCompletion(this._client,e,t)}};_s.Messages=nn;class ms extends Qt{constructor(){super(...arguments),this.completions=new _s(this._client)}}ms.Completions=_s;const gs=Symbol("brand.privateNullableHeaders");function*ys(e){if(!e)return;if(gs in e){const{values:t,nulls:n}=e;yield*t.entries();for(const e of n)yield[e,null];return}let t,n=!1;e instanceof Headers?t=e.entries():De(e)?t=e:(n=!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 s=De(e[1])?e[1]:[e[1]];let r=!1;for(const e of s)void 0!==e&&(n&&!r&&(r=!0,yield[t,null]),yield[t,e])}}const bs=e=>{const t=new Headers,n=new Set;for(const s of e){const e=new Set;for(const[r,o]of ys(s)){const s=r.toLowerCase();e.has(s)||(t.delete(r),e.add(s)),null===o?(t.delete(r),n.add(s)):(t.append(r,o),n.delete(s))}}return{[gs]:!0,values:t,nulls:n}};class ws extends Qt{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:bs([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}}class vs extends Qt{create(e,t){return this._client.post("/audio/transcriptions",Xt({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}}class xs extends Qt{create(e,t){return this._client.post("/audio/translations",Xt({body:e,...t,__metadata:{model:e.model}},this._client))}}class Ss extends Qt{constructor(){super(...arguments),this.transcriptions=new vs(this._client),this.translations=new xs(this._client),this.speech=new ws(this._client)}}Ss.Transcriptions=vs,Ss.Translations=xs,Ss.Speech=ws;class ks extends Qt{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(tn`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",qt,{query:e,...t})}cancel(e,t){return this._client.post(tn`/batches/${e}/cancel`,t)}}class $s extends Qt{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:bs([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(tn`/assistants/${e}`,{...t,headers:bs([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,n){return this._client.post(tn`/assistants/${e}`,{body:t,...n,headers:bs([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",qt,{query:e,...t,headers:bs([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(tn`/assistants/${e}`,{...t,headers:bs([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class As extends Qt{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:bs([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class Is extends Qt{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:bs([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}let Os=class extends Qt{constructor(){super(...arguments),this.sessions=new As(this._client),this.transcriptionSessions=new Is(this._client)}};Os.Sessions=As,Os.TranscriptionSessions=Is;class Rs extends Qt{create(e,t,n){return this._client.post(tn`/threads/${e}/messages`,{body:t,...n,headers:bs([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,t,n){const{thread_id:s}=t;return this._client.get(tn`/threads/${s}/messages/${e}`,{...n,headers:bs([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,t,n){const{thread_id:s,...r}=t;return this._client.post(tn`/threads/${s}/messages/${e}`,{body:r,...n,headers:bs([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,t={},n){return this._client.getAPIList(tn`/threads/${e}/messages`,qt,{query:t,...n,headers:bs([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,t,n){const{thread_id:s}=t;return this._client.delete(tn`/threads/${s}/messages/${e}`,{...n,headers:bs([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}}class Ps extends Qt{retrieve(e,t,n){const{thread_id:s,run_id:r,...o}=t;return this._client.get(tn`/threads/${s}/runs/${r}/steps/${e}`,{query:o,...n,headers:bs([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,t,n){const{thread_id:s,...r}=t;return this._client.getAPIList(tn`/threads/${s}/runs/${e}/steps`,qt,{query:r,...n,headers:bs([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}}const Cs=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 Es,Ts,js,Ms,Ns,Ls,Ds,qs,Ws,Bs,Us,Fs,Hs,Xs,Ks,Js,Vs,zs,Gs,Qs,Ys,Zs,er;class tr extends Mn{constructor(){super(...arguments),Es.add(this),js.set(this,[]),Ms.set(this,{}),Ns.set(this,{}),Ls.set(this,void 0),Ds.set(this,void 0),qs.set(this,void 0),Ws.set(this,void 0),Bs.set(this,void 0),Us.set(this,void 0),Fs.set(this,void 0),Hs.set(this,void 0),Xs.set(this,void 0)}[(js=new WeakMap,Ms=new WeakMap,Ns=new WeakMap,Ls=new WeakMap,Ds=new WeakMap,qs=new WeakMap,Ws=new WeakMap,Bs=new WeakMap,Us=new WeakMap,Fs=new WeakMap,Hs=new WeakMap,Xs=new WeakMap,Es=new WeakSet,Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("event",(n=>{const s=t.shift();s?s.resolve(n):e.push(n)})),this.on("end",(()=>{n=!0;for(const e of t)e.resolve(void 0);t.length=0})),this.on("abort",(e=>{n=!0;for(const n of t)n.reject(e);t.length=0})),this.on("error",(e=>{n=!0;for(const n of t)n.reject(e);t.length=0})),{next:async()=>{if(!e.length)return n?{value:void 0,done:!0}:new Promise(((e,n)=>t.push({resolve:e,reject:n}))).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 Ts;return t._run((()=>t._fromReadableStream(e))),t}async _fromReadableStream(e,t){const n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",(()=>this.controller.abort()))),this._connected();const s=Ct.fromReadableStream(e,this.controller);for await(const e of s)me(this,Es,"m",Ks).call(this,e);if(s.controller.signal?.aborted)throw new xe;return this._addRun(me(this,Es,"m",Js).call(this))}toReadableStream(){return new Ct(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,s){const r=new Ts;return r._run((()=>r._runToolAssistantStream(e,t,n,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}}))),r}async _createToolAssistantStream(e,t,n,s){const r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",(()=>this.controller.abort())));const o={...n,stream:!0},i=await e.submitToolOutputs(t,o,{...s,signal:this.controller.signal});this._connected();for await(const e of i)me(this,Es,"m",Ks).call(this,e);if(i.controller.signal?.aborted)throw new xe;return this._addRun(me(this,Es,"m",Js).call(this))}static createThreadAssistantStream(e,t,n){const s=new Ts;return s._run((()=>s._threadAssistantStream(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}}))),s}static createAssistantStream(e,t,n,s){const r=new Ts;return r._run((()=>r._runAssistantStream(e,t,n,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}}))),r}currentEvent(){return me(this,Fs,"f")}currentRun(){return me(this,Hs,"f")}currentMessageSnapshot(){return me(this,Ls,"f")}currentRunStepSnapshot(){return me(this,Xs,"f")}async finalRunSteps(){return await this.done(),Object.values(me(this,Ms,"f"))}async finalMessages(){return await this.done(),Object.values(me(this,Ns,"f"))}async finalRun(){if(await this.done(),!me(this,Ds,"f"))throw Error("Final run was not received.");return me(this,Ds,"f")}async _createThreadAssistantStream(e,t,n){const s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",(()=>this.controller.abort())));const r={...t,stream:!0},o=await e.createAndRun(r,{...n,signal:this.controller.signal});this._connected();for await(const e of o)me(this,Es,"m",Ks).call(this,e);if(o.controller.signal?.aborted)throw new xe;return this._addRun(me(this,Es,"m",Js).call(this))}async _createAssistantStream(e,t,n,s){const r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",(()=>this.controller.abort())));const o={...n,stream:!0},i=await e.create(t,o,{...s,signal:this.controller.signal});this._connected();for await(const e of i)me(this,Es,"m",Ks).call(this,e);if(i.controller.signal?.aborted)throw new xe;return this._addRun(me(this,Es,"m",Js).call(this))}static accumulateDelta(e,t){for(const[n,s]of Object.entries(t)){if(!e.hasOwnProperty(n)){e[n]=s;continue}let t=e[n];if(null!=t)if("index"!==n&&"type"!==n){if("string"==typeof t&&"string"==typeof s)t+=s;else if("number"==typeof t&&"number"==typeof s)t+=s;else{if(!We(t)||!We(s)){if(Array.isArray(t)&&Array.isArray(s)){if(t.every((e=>"string"==typeof e||"number"==typeof e))){t.push(...s);continue}for(const e of s){if(!We(e))throw new Error(`Expected array delta entry to be an object but got: ${e}`);const n=e.index;if(null==n)throw console.error(e),new Error("Expected array delta entry to have an `index` property");if("number"!=typeof n)throw new Error(`Expected array delta entry \`index\` property to be a number but got ${n}`);const s=t[n];null==s?t.push(e):t[n]=this.accumulateDelta(s,e)}continue}throw Error(`Unhandled record type: ${n}, deltaValue: ${s}, accValue: ${t}`)}t=this.accumulateDelta(t,s)}e[n]=t}else e[n]=s;else e[n]=s}return e}_addRun(e){return e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,s){return await this._createAssistantStream(t,e,n,s)}async _runToolAssistantStream(e,t,n,s){return await this._createToolAssistantStream(t,e,n,s)}}Ts=tr,Ks=function(e){if(!this.ended)switch(_e(this,Fs,e),me(this,Es,"m",Gs).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":me(this,Es,"m",er).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":me(this,Es,"m",zs).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":me(this,Es,"m",Vs).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 we("stream has ended, this shouldn't happen");if(!me(this,Ds,"f"))throw Error("Final run has not been received");return me(this,Ds,"f")},Vs=function(e){const[t,n]=me(this,Es,"m",Ys).call(this,e,me(this,Ls,"f"));_e(this,Ls,t),me(this,Ns,"f")[t.id]=t;for(const e of n){const n=t.content[e.index];"text"==n?.type&&this._emit("textCreated",n.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 n of e.data.delta.content){if("text"==n.type&&n.text){let e=n.text,s=t.content[n.index];if(!s||"text"!=s.type)throw Error("The snapshot associated with this text delta is not text or missing");this._emit("textDelta",e,s.text)}if(n.index!=me(this,qs,"f")){if(me(this,Ws,"f"))switch(me(this,Ws,"f").type){case"text":this._emit("textDone",me(this,Ws,"f").text,me(this,Ls,"f"));break;case"image_file":this._emit("imageFileDone",me(this,Ws,"f").image_file,me(this,Ls,"f"))}_e(this,qs,n.index)}_e(this,Ws,t.content[n.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(void 0!==me(this,qs,"f")){const t=e.data.content[me(this,qs,"f")];if(t)switch(t.type){case"image_file":this._emit("imageFileDone",t.image_file,me(this,Ls,"f"));break;case"text":this._emit("textDone",t.text,me(this,Ls,"f"))}}me(this,Ls,"f")&&this._emit("messageDone",e.data),_e(this,Ls,void 0)}},zs=function(e){const t=me(this,Es,"m",Qs).call(this,e);switch(_e(this,Xs,t),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":const n=e.data.delta;if(n.step_details&&"tool_calls"==n.step_details.type&&n.step_details.tool_calls&&"tool_calls"==t.step_details.type)for(const e of n.step_details.tool_calls)e.index==me(this,Bs,"f")?this._emit("toolCallDelta",e,t.step_details.tool_calls[e.index]):(me(this,Us,"f")&&this._emit("toolCallDone",me(this,Us,"f")),_e(this,Bs,e.index),_e(this,Us,t.step_details.tool_calls[e.index]),me(this,Us,"f")&&this._emit("toolCallCreated",me(this,Us,"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":_e(this,Xs,void 0);"tool_calls"==e.data.step_details.type&&me(this,Us,"f")&&(this._emit("toolCallDone",me(this,Us,"f")),_e(this,Us,void 0)),this._emit("runStepDone",e.data,t)}},Gs=function(e){me(this,js,"f").push(e),this._emit("event",e)},Qs=function(e){switch(e.event){case"thread.run.step.created":return me(this,Ms,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=me(this,Ms,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let n=e.data;if(n.delta){const s=Ts.accumulateDelta(t,n.delta);me(this,Ms,"f")[e.data.id]=s}return me(this,Ms,"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":me(this,Ms,"f")[e.data.id]=e.data}if(me(this,Ms,"f")[e.data.id])return me(this,Ms,"f")[e.data.id];throw new Error("No snapshot available")},Ys=function(e,t){let n=[];switch(e.event){case"thread.message.created":return[e.data,n];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let s=e.data;if(s.delta.content)for(const e of s.delta.content)if(e.index in t.content){let n=t.content[e.index];t.content[e.index]=me(this,Es,"m",Zs).call(this,e,n)}else t.content[e.index]=e,n.push(e);return[t,n];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,n];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Zs=function(e,t){return Ts.accumulateDelta(t,e)},er=function(e){switch(_e(this,Hs,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":_e(this,Ds,e.data),me(this,Us,"f")&&(this._emit("toolCallDone",me(this,Us,"f")),_e(this,Us,void 0))}};let nr=class extends Qt{constructor(){super(...arguments),this.steps=new Ps(this._client)}create(e,t,n){const{include:s,...r}=t;return this._client.post(tn`/threads/${e}/runs`,{query:{include:s},body:r,...n,headers:bs([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:t.stream??!1})}retrieve(e,t,n){const{thread_id:s}=t;return this._client.get(tn`/threads/${s}/runs/${e}`,{...n,headers:bs([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,t,n){const{thread_id:s,...r}=t;return this._client.post(tn`/threads/${s}/runs/${e}`,{body:r,...n,headers:bs([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,t={},n){return this._client.getAPIList(tn`/threads/${e}/runs`,qt,{query:t,...n,headers:bs([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}cancel(e,t,n){const{thread_id:s}=t;return this._client.post(tn`/threads/${s}/runs/${e}/cancel`,{...n,headers:bs([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async createAndPoll(e,t,n){const s=await this.create(e,t,n);return await this.poll(s.id,{thread_id:e},n)}createAndStream(e,t,n){return tr.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){const s=bs([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:r,response:o}=await this.retrieve(e,t,{...n,headers:{...n?.headers,...s}}).withResponse();switch(r.status){case"queued":case"in_progress":case"cancelling":let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{const t=o.headers.get("openai-poll-after-ms");if(t){const n=parseInt(t);isNaN(n)||(e=n)}}await Be(e);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return r}}}stream(e,t,n){return tr.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n){const{thread_id:s,...r}=t;return this._client.post(tn`/threads/${s}/runs/${e}/submit_tool_outputs`,{body:r,...n,headers:bs([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:t.stream??!1})}async submitToolOutputsAndPoll(e,t,n){const s=await this.submitToolOutputs(e,t,n);return await this.poll(s.id,t,n)}submitToolOutputsStream(e,t,n){return tr.createToolAssistantStream(e,this._client.beta.threads.runs,t,n)}};nr.Steps=Ps;class sr extends Qt{constructor(){super(...arguments),this.runs=new nr(this._client),this.messages=new Rs(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:bs([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(tn`/threads/${e}`,{...t,headers:bs([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,n){return this._client.post(tn`/threads/${e}`,{body:t,...n,headers:bs([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,t){return this._client.delete(tn`/threads/${e}`,{...t,headers:bs([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:bs([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1})}async createAndRunPoll(e,t){const n=await this.createAndRun(e,t);return await this.runs.poll(n.id,{thread_id:n.thread_id},t)}createAndRunStream(e,t){return tr.createThreadAssistantStream(e,this._client.beta.threads,t)}}sr.Runs=nr,sr.Messages=Rs;class rr extends Qt{constructor(){super(...arguments),this.realtime=new Os(this._client),this.assistants=new $s(this._client),this.threads=new sr(this._client)}}rr.Realtime=Os,rr.Assistants=$s,rr.Threads=sr;class or extends Qt{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class ir extends Qt{retrieve(e,t,n){const{container_id:s}=t;return this._client.get(tn`/containers/${s}/files/${e}/content`,{...n,headers:bs([{Accept:"application/binary"},n?.headers]),__binaryResponse:!0})}}let ar=class extends Qt{constructor(){super(...arguments),this.content=new ir(this._client)}create(e,t,n){return this._client.post(tn`/containers/${e}/files`,Xt({body:t,...n},this._client))}retrieve(e,t,n){const{container_id:s}=t;return this._client.get(tn`/containers/${s}/files/${e}`,n)}list(e,t={},n){return this._client.getAPIList(tn`/containers/${e}/files`,qt,{query:t,...n})}delete(e,t,n){const{container_id:s}=t;return this._client.delete(tn`/containers/${s}/files/${e}`,{...n,headers:bs([{Accept:"*/*"},n?.headers])})}};ar.Content=ir;class lr extends Qt{constructor(){super(...arguments),this.files=new ar(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(tn`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",qt,{query:e,...t})}delete(e,t){return this._client.delete(tn`/containers/${e}`,{...t,headers:bs([{Accept:"*/*"},t?.headers])})}}lr.Files=ar;class cr extends Qt{create(e,t,n){const{include:s,...r}=t;return this._client.post(tn`/conversations/${e}/items`,{query:{include:s},body:r,...n})}retrieve(e,t,n){const{conversation_id:s,...r}=t;return this._client.get(tn`/conversations/${s}/items/${e}`,{query:r,...n})}list(e,t={},n){return this._client.getAPIList(tn`/conversations/${e}/items`,Wt,{query:t,...n})}delete(e,t,n){const{conversation_id:s}=t;return this._client.delete(tn`/conversations/${s}/items/${e}`,n)}}class ur extends Qt{constructor(){super(...arguments),this.items=new cr(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t})}retrieve(e,t){return this._client.get(tn`/conversations/${e}`,t)}update(e,t,n){return this._client.post(tn`/conversations/${e}`,{body:t,...n})}delete(e,t){return this._client.delete(tn`/conversations/${e}`,t)}}ur.Items=cr;class dr extends Qt{create(e,t){const n=!!e.encoding_format;let s=n?e.encoding_format:"base64";n&&At(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);const r=this._client.post("/embeddings",{body:{...e,encoding_format:s},...t});return n?r:(At(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),n=t.length,s=new Uint8Array(n);for(let e=0;e<n;e++)s[e]=t.charCodeAt(e);return Array.from(new Float32Array(s.buffer))}})(t)})),e))))}}class hr extends Qt{retrieve(e,t,n){const{eval_id:s,run_id:r}=t;return this._client.get(tn`/evals/${s}/runs/${r}/output_items/${e}`,n)}list(e,t,n){const{eval_id:s,...r}=t;return this._client.getAPIList(tn`/evals/${s}/runs/${e}/output_items`,qt,{query:r,...n})}}class pr extends Qt{constructor(){super(...arguments),this.outputItems=new hr(this._client)}create(e,t,n){return this._client.post(tn`/evals/${e}/runs`,{body:t,...n})}retrieve(e,t,n){const{eval_id:s}=t;return this._client.get(tn`/evals/${s}/runs/${e}`,n)}list(e,t={},n){return this._client.getAPIList(tn`/evals/${e}/runs`,qt,{query:t,...n})}delete(e,t,n){const{eval_id:s}=t;return this._client.delete(tn`/evals/${s}/runs/${e}`,n)}cancel(e,t,n){const{eval_id:s}=t;return this._client.post(tn`/evals/${s}/runs/${e}`,n)}}pr.OutputItems=hr;class fr extends Qt{constructor(){super(...arguments),this.runs=new pr(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(tn`/evals/${e}`,t)}update(e,t,n){return this._client.post(tn`/evals/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/evals",qt,{query:e,...t})}delete(e,t){return this._client.delete(tn`/evals/${e}`,t)}}fr.Runs=pr;let _r=class extends Qt{create(e,t){return this._client.post("/files",Xt({body:e,...t},this._client))}retrieve(e,t){return this._client.get(tn`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",qt,{query:e,...t})}delete(e,t){return this._client.delete(tn`/files/${e}`,t)}content(e,t){return this._client.get(tn`/files/${e}/content`,{...t,headers:bs([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:n=18e5}={}){const s=new Set(["processed","error","deleted"]),r=Date.now();let o=await this.retrieve(e);for(;!o.status||!s.has(o.status);)if(await Be(t),o=await this.retrieve(e),Date.now()-r>n)throw new ke({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return o}};class mr extends Qt{}let gr=class extends Qt{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 yr extends Qt{constructor(){super(...arguments),this.graders=new gr(this._client)}}yr.Graders=gr;class br extends Qt{create(e,t,n){return this._client.getAPIList(tn`/fine_tuning/checkpoints/${e}/permissions`,Dt,{body:t,method:"post",...n})}retrieve(e,t={},n){return this._client.get(tn`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...n})}delete(e,t,n){const{fine_tuned_model_checkpoint:s}=t;return this._client.delete(tn`/fine_tuning/checkpoints/${s}/permissions/${e}`,n)}}let wr=class extends Qt{constructor(){super(...arguments),this.permissions=new br(this._client)}};wr.Permissions=br;class vr extends Qt{list(e,t={},n){return this._client.getAPIList(tn`/fine_tuning/jobs/${e}/checkpoints`,qt,{query:t,...n})}}class xr extends Qt{constructor(){super(...arguments),this.checkpoints=new vr(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(tn`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",qt,{query:e,...t})}cancel(e,t){return this._client.post(tn`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},n){return this._client.getAPIList(tn`/fine_tuning/jobs/${e}/events`,qt,{query:t,...n})}pause(e,t){return this._client.post(tn`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(tn`/fine_tuning/jobs/${e}/resume`,t)}}xr.Checkpoints=vr;class Sr extends Qt{constructor(){super(...arguments),this.methods=new mr(this._client),this.jobs=new xr(this._client),this.checkpoints=new wr(this._client),this.alpha=new yr(this._client)}}Sr.Methods=mr,Sr.Jobs=xr,Sr.Checkpoints=wr,Sr.Alpha=yr;class kr extends Qt{}class $r extends Qt{constructor(){super(...arguments),this.graderModels=new kr(this._client)}}$r.GraderModels=kr;class Ar extends Qt{createVariation(e,t){return this._client.post("/images/variations",Xt({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",Xt({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 Ir extends Qt{retrieve(e,t){return this._client.get(tn`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",Dt,e)}delete(e,t){return this._client.delete(tn`/models/${e}`,t)}}class Or extends Qt{create(e,t){return this._client.post("/moderations",{body:e,...t})}}class Rr extends Qt{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t})}}class Pr extends Qt{constructor(){super(...arguments),this.clientSecrets=new Rr(this._client)}}function Cr(e,t){return t&&function(e){if(rn(e.text?.format))return!0;return!1}(t)?Er(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 Er(e,t){const n=e.output.map((e=>{if("function_call"===e.type)return{...e,parsed_arguments:jr(t,e)};if("message"===e.type){const n=e.content.map((e=>"output_text"===e.type?{...e,parsed:Tr(t,e.text)}:e));return{...e,content:n}}return e})),s=Object.assign({},e,{output:n});return Object.getOwnPropertyDescriptor(e,"output_text")||Mr(s),Object.defineProperty(s,"output_parsed",{enumerable:!0,get(){for(const e of s.output)if("message"===e.type)for(const t of e.content)if("output_text"===t.type&&null!==t.parsed)return t.parsed;return null}}),s}function Tr(e,t){if("json_schema"!==e.text?.format?.type)return null;if("$parseRaw"in e.text?.format){const n=e.text?.format;return n.$parseRaw(t)}return JSON.parse(t)}function jr(e,t){const n=(s=e.tools??[],r=t.name,s.find((e=>"function"===e.type&&e.name===r)));var s,r,o;return{...t,...t,parsed_arguments:(o=n,"auto-parseable-tool"===o?.$brand?n.$parseRaw(t.arguments):n?.strict?JSON.parse(t.arguments):null)}}function Mr(e){const t=[];for(const n of e.output)if("message"===n.type)for(const e of n.content)"output_text"===e.type&&t.push(e.text);e.output_text=t.join("")}var Nr,Lr,Dr,qr,Wr,Br,Ur,Fr;Pr.ClientSecrets=Rr;class Hr extends Mn{constructor(e){super(),Nr.add(this),Lr.set(this,void 0),Dr.set(this,void 0),qr.set(this,void 0),_e(this,Lr,e)}static createResponse(e,t,n){const s=new Hr(t);return s._run((()=>s._createOrRetrieveResponse(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}}))),s}async _createOrRetrieveResponse(e,t,n){const s=n?.signal;let r;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",(()=>this.controller.abort()))),me(this,Nr,"m",Wr).call(this);let o=null;"response_id"in t?(r=await e.responses.retrieve(t.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),o=t.starting_after??null):r=await e.responses.create({...t,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(const e of r)me(this,Nr,"m",Br).call(this,e,o);if(r.controller.signal?.aborted)throw new xe;return me(this,Nr,"m",Ur).call(this)}[(Lr=new WeakMap,Dr=new WeakMap,qr=new WeakMap,Nr=new WeakSet,Wr=function(){this.ended||_e(this,Dr,void 0)},Br=function(e,t){if(this.ended)return;const n=(e,n)=>{(null==t||n.sequence_number>t)&&this._emit(e,n)},s=me(this,Nr,"m",Fr).call(this,e);switch(n("event",e),e.type){case"response.output_text.delta":{const t=s.output[e.output_index];if(!t)throw new we(`missing output at index ${e.output_index}`);if("message"===t.type){const s=t.content[e.content_index];if(!s)throw new we(`missing content at index ${e.content_index}`);if("output_text"!==s.type)throw new we(`expected content to be 'output_text', got ${s.type}`);n("response.output_text.delta",{...e,snapshot:s.text})}break}case"response.function_call_arguments.delta":{const t=s.output[e.output_index];if(!t)throw new we(`missing output at index ${e.output_index}`);"function_call"===t.type&&n("response.function_call_arguments.delta",{...e,snapshot:t.arguments});break}default:n(e.type,e)}},Ur=function(){if(this.ended)throw new we("stream has ended, this shouldn't happen");const e=me(this,Dr,"f");if(!e)throw new we("request ended without sending any events");_e(this,Dr,void 0);const t=function(e,t){return Cr(e,t)}(e,me(this,Lr,"f"));return _e(this,qr,t),t},Fr=function(e){let t=me(this,Dr,"f");if(!t){if("response.created"!==e.type)throw new we(`When snapshot hasn't been set yet, expected 'response.created' event, got ${e.type}`);return t=_e(this,Dr,e.response),t}switch(e.type){case"response.output_item.added":t.output.push(e.item);break;case"response.content_part.added":{const n=t.output[e.output_index];if(!n)throw new we(`missing output at index ${e.output_index}`);const s=n.type,r=e.part;"message"===s&&"reasoning_text"!==r.type?n.content.push(r):"reasoning"===s&&"reasoning_text"===r.type&&(n.content||(n.content=[]),n.content.push(r));break}case"response.output_text.delta":{const n=t.output[e.output_index];if(!n)throw new we(`missing output at index ${e.output_index}`);if("message"===n.type){const t=n.content[e.content_index];if(!t)throw new we(`missing content at index ${e.content_index}`);if("output_text"!==t.type)throw new we(`expected content to be 'output_text', got ${t.type}`);t.text+=e.delta}break}case"response.function_call_arguments.delta":{const n=t.output[e.output_index];if(!n)throw new we(`missing output at index ${e.output_index}`);"function_call"===n.type&&(n.arguments+=e.delta);break}case"response.reasoning_text.delta":{const n=t.output[e.output_index];if(!n)throw new we(`missing output at index ${e.output_index}`);if("reasoning"===n.type){const t=n.content?.[e.content_index];if(!t)throw new we(`missing content at index ${e.content_index}`);if("reasoning_text"!==t.type)throw new we(`expected content to be 'reasoning_text', got ${t.type}`);t.text+=e.delta}break}case"response.completed":_e(this,Dr,e.response)}return t},Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("event",(n=>{const s=t.shift();s?s.resolve(n):e.push(n)})),this.on("end",(()=>{n=!0;for(const e of t)e.resolve(void 0);t.length=0})),this.on("abort",(e=>{n=!0;for(const n of t)n.reject(e);t.length=0})),this.on("error",(e=>{n=!0;for(const n of t)n.reject(e);t.length=0})),{next:async()=>{if(!e.length)return n?{value:void 0,done:!0}:new Promise(((e,n)=>t.push({resolve:e,reject:n}))).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=me(this,qr,"f");if(!e)throw new we("stream ended without producing a ChatCompletion");return e}}class Xr extends Qt{list(e,t={},n){return this._client.getAPIList(tn`/responses/${e}/input_items`,qt,{query:t,...n})}}class Kr extends Qt{constructor(){super(...arguments),this.inputItems=new Xr(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&&Mr(e),e)))}retrieve(e,t={},n){return this._client.get(tn`/responses/${e}`,{query:t,...n,stream:t?.stream??!1})._thenUnwrap((e=>("object"in e&&"response"===e.object&&Mr(e),e)))}delete(e,t){return this._client.delete(tn`/responses/${e}`,{...t,headers:bs([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap((t=>Er(t,e)))}stream(e,t){return Hr.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(tn`/responses/${e}/cancel`,t)}}Kr.InputItems=Xr;class Jr extends Qt{create(e,t,n){return this._client.post(tn`/uploads/${e}/parts`,Xt({body:t,...n},this._client))}}class Vr extends Qt{constructor(){super(...arguments),this.parts=new Jr(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(tn`/uploads/${e}/cancel`,t)}complete(e,t,n){return this._client.post(tn`/uploads/${e}/complete`,{body:t,...n})}}Vr.Parts=Jr;class zr extends Qt{create(e,t,n){return this._client.post(tn`/vector_stores/${e}/file_batches`,{body:t,...n,headers:bs([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,t,n){const{vector_store_id:s}=t;return this._client.get(tn`/vector_stores/${s}/file_batches/${e}`,{...n,headers:bs([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}cancel(e,t,n){const{vector_store_id:s}=t;return this._client.post(tn`/vector_stores/${s}/file_batches/${e}/cancel`,{...n,headers:bs([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async createAndPoll(e,t,n){const s=await this.create(e,t);return await this.poll(e,s.id,n)}listFiles(e,t,n){const{vector_store_id:s,...r}=t;return this._client.getAPIList(tn`/vector_stores/${s}/file_batches/${e}/files`,qt,{query:r,...n,headers:bs([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async poll(e,t,n){const s=bs([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:r,response:o}=await this.retrieve(t,{vector_store_id:e},{...n,headers:s}).withResponse();switch(r.status){case"in_progress":let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{const t=o.headers.get("openai-poll-after-ms");if(t){const n=parseInt(t);isNaN(n)||(e=n)}}await Be(e);break;case"failed":case"cancelled":case"completed":return r}}}async uploadAndPoll(e,{files:t,fileIds:n=[]},s){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=s?.maxConcurrency??5,o=Math.min(r,t.length),i=this._client,a=t.values(),l=[...n];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"},s);l.push(e.id)}}));return await(async e=>{const t=await Promise.allSettled(e),n=t.filter((e=>"rejected"===e.status));if(n.length){for(const e of n)console.error(e.reason);throw new Error(`${n.length} promise(s) failed - see the above errors`)}const s=[];for(const e of t)"fulfilled"===e.status&&s.push(e.value);return s})(c),await this.createAndPoll(e,{file_ids:l})}}class Gr extends Qt{create(e,t,n){return this._client.post(tn`/vector_stores/${e}/files`,{body:t,...n,headers:bs([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,t,n){const{vector_store_id:s}=t;return this._client.get(tn`/vector_stores/${s}/files/${e}`,{...n,headers:bs([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,t,n){const{vector_store_id:s,...r}=t;return this._client.post(tn`/vector_stores/${s}/files/${e}`,{body:r,...n,headers:bs([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e,t={},n){return this._client.getAPIList(tn`/vector_stores/${e}/files`,qt,{query:t,...n,headers:bs([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,t,n){const{vector_store_id:s}=t;return this._client.delete(tn`/vector_stores/${s}/files/${e}`,{...n,headers:bs([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}async createAndPoll(e,t,n){const s=await this.create(e,t,n);return await this.poll(e,s.id,n)}async poll(e,t,n){const s=bs([n?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){const r=await this.retrieve(t,{vector_store_id:e},{...n,headers:s}).withResponse(),o=r.data;switch(o.status){case"in_progress":let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{const t=r.response.headers.get("openai-poll-after-ms");if(t){const n=parseInt(t);isNaN(n)||(e=n)}}await Be(e);break;case"failed":case"completed":return o}}}async upload(e,t,n){const s=await this._client.files.create({file:t,purpose:"assistants"},n);return this.create(e,{file_id:s.id},n)}async uploadAndPoll(e,t,n){const s=await this.upload(e,t,n);return await this.poll(e,s.id,n)}content(e,t,n){const{vector_store_id:s}=t;return this._client.getAPIList(tn`/vector_stores/${s}/files/${e}/content`,Dt,{...n,headers:bs([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}}class Qr extends Qt{constructor(){super(...arguments),this.files=new Gr(this._client),this.fileBatches=new zr(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:bs([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(tn`/vector_stores/${e}`,{...t,headers:bs([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,n){return this._client.post(tn`/vector_stores/${e}`,{body:t,...n,headers:bs([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",qt,{query:e,...t,headers:bs([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(tn`/vector_stores/${e}`,{...t,headers:bs([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,n){return this._client.getAPIList(tn`/vector_stores/${e}/search`,Dt,{body:t,method:"post",...n,headers:bs([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}}var Yr,Zr,eo,to,no,so,ro;Qr.Files=Gr,Qr.FileBatches=zr;class oo extends Qt{constructor(){super(...arguments),Yr.add(this)}async unwrap(e,t,n=this._client.webhookSecret,s=300){return await this.verifySignature(e,t,n,s),JSON.parse(e)}async verifySignature(e,t,n=this._client.webhookSecret,s=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");me(this,Yr,"m",Zr).call(this,n);const r=bs([t]).values,o=me(this,Yr,"m",eo).call(this,r,"webhook-signature"),i=me(this,Yr,"m",eo).call(this,r,"webhook-timestamp"),a=me(this,Yr,"m",eo).call(this,r,"webhook-id"),l=parseInt(i,10);if(isNaN(l))throw new Me("Invalid webhook timestamp format");const c=Math.floor(Date.now()/1e3);if(c-l>s)throw new Me("Webhook timestamp is too old");if(l>c+s)throw new Me("Webhook timestamp is too new");const u=o.split(" ").map((e=>e.startsWith("v1,")?e.substring(3):e)),d=n.startsWith("whsec_")?Buffer.from(n.replace("whsec_",""),"base64"):Buffer.from(n,"utf-8"),h=a?`${a}.${i}.${e}`:`${i}.${e}`,p=await crypto.subtle.importKey("raw",d,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(const e of u)try{const t=Buffer.from(e,"base64");if(await crypto.subtle.verify("HMAC",p,t,(new TextEncoder).encode(h)))return}catch{continue}throw new Me("The given webhook signature does not match the expected signature")}}Yr=new WeakSet,Zr=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")},eo=function(e,t){if(!e)throw new Error("Headers are required");const n=e.get(t);if(null==n)throw new Error(`Missing required header: ${t}`);return n};class io{constructor({baseURL:e=Cs("OPENAI_BASE_URL"),apiKey:t=Cs("OPENAI_API_KEY"),organization:n=Cs("OPENAI_ORG_ID")??null,project:s=Cs("OPENAI_PROJECT_ID")??null,webhookSecret:r=Cs("OPENAI_WEBHOOK_SECRET")??null,...o}={}){if(to.add(this),so.set(this,void 0),this.completions=new or(this),this.chat=new ms(this),this.embeddings=new dr(this),this.files=new _r(this),this.images=new Ar(this),this.audio=new Ss(this),this.moderations=new Or(this),this.models=new Ir(this),this.fineTuning=new Sr(this),this.graders=new $r(this),this.vectorStores=new Qr(this),this.webhooks=new oo(this),this.beta=new rr(this),this.batches=new ks(this),this.uploads=new Vr(this),this.responses=new Kr(this),this.realtime=new Pr(this),this.conversations=new ur(this),this.evals=new fr(this),this.containers=new lr(this),void 0===t)throw new we("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");const i={apiKey:t,organization:n,project:s,webhookSecret:r,...o,baseURL:e||"https://api.openai.com/v1"};if(!i.dangerouslyAllowBrowser&&"undefined"!=typeof window&&void 0!==window.document&&"undefined"!=typeof navigator)throw new we("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=i.baseURL,this.timeout=i.timeout??no.DEFAULT_TIMEOUT,this.logger=i.logger??console;const a="warn";this.logLevel=a,this.logLevel=vt(i.logLevel,"ClientOptions.logLevel",this)??vt(Cs("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??a,this.fetchOptions=i.fetchOptions,this.maxRetries=i.maxRetries??2,this.fetch=i.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`")}(),_e(this,so,Ge),this._options=i,this.apiKey="string"==typeof t?t:"Missing Key",this.organization=n,this.project=s,this.webhookSecret=r}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 bs([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return ut(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${Ue}`}defaultIdempotencyKey(){return`stainless-node-retry-${ge()}`}makeStatusError(e,t,n,s){return ve.generate(e,t,n,s)}async _callApiKey(){const e=this._options.apiKey;if("function"!=typeof e)return!1;let t;try{t=await e()}catch(e){if(e instanceof we)throw e;throw new we(`Failed to get token from 'apiKey' function: ${e.message}`,{cause:e})}if("string"!=typeof t||!t)throw new we(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,n){const s=!me(this,to,"m",ro).call(this)&&n||this.baseURL,r=(e=>Ne.test(e))(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),o=this.defaultQuery();return function(e){if(!e)return!0;for(const t in e)return!1;return!0}(o)||(t={...o,...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:n}){}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,n){return this.request(Promise.resolve(n).then((n=>({method:e,path:t,...n}))))}request(e,t=null){return new Mt(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){const s=await e,r=s.maxRetries??this.maxRetries;null==t&&(t=r),await this.prepareOptions(s);const{req:o,url:i,timeout:a}=await this.buildRequest(s,{retryCount:r-t});await this.prepareRequest(o,{url:i,options:s});const l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),c=void 0===n?"":`, retryOf: ${n}`,u=Date.now();if(At(this).debug(`[${l}] sending request`,It({retryOfRequestLogID:n,method:s.method,url:i,options:s,headers:o.headers})),s.signal?.aborted)throw new xe;const d=new AbortController,h=await this.fetchWithTimeout(i,o,a,d).catch(be),p=Date.now();if(h instanceof globalThis.Error){const e=`retrying, ${t} attempts remaining`;if(s.signal?.aborted)throw new xe;const r=ye(h)||/timed? ?out/i.test(String(h)+("cause"in h?String(h.cause):""));if(t)return At(this).info(`[${l}] connection ${r?"timed out":"failed"} - ${e}`),At(this).debug(`[${l}] connection ${r?"timed out":"failed"} (${e})`,It({retryOfRequestLogID:n,url:i,durationMs:p-u,message:h.message})),this.retryRequest(s,t,n??l);if(At(this).info(`[${l}] connection ${r?"timed out":"failed"} - error; no more retries left`),At(this).debug(`[${l}] connection ${r?"timed out":"failed"} (error; no more retries left)`,It({retryOfRequestLogID:n,url:i,durationMs:p-u,message:h.message})),r)throw new ke;throw new Se({cause:h})}const f=`[${l}${c}${[...h.headers.entries()].filter((([e])=>"x-request-id"===e)).map((([e,t])=>", "+e+": "+JSON.stringify(t))).join("")}] ${o.method} ${i} ${h.ok?"succeeded":"failed"} with status ${h.status} in ${p-u}ms`;if(!h.ok){const e=await this.shouldRetry(h);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(),n=t.cancel();t.releaseLock(),await n}(h.body),At(this).info(`${f} - ${e}`),At(this).debug(`[${l}] response error (${e})`,It({retryOfRequestLogID:n,url:h.url,status:h.status,headers:h.headers,durationMs:p-u})),this.retryRequest(s,t,n??l,h.headers)}const r=e?"error; no more retries left":"error; not retryable";At(this).info(`${f} - ${r}`);const o=await h.text().catch((e=>be(e).message)),i=(e=>{try{return JSON.parse(e)}catch(e){return}})(o),a=i?void 0:o;At(this).debug(`[${l}] response error (${r})`,It({retryOfRequestLogID:n,url:h.url,status:h.status,headers:h.headers,message:a,durationMs:Date.now()-u}));throw this.makeStatusError(h.status,i,a,h.headers)}return At(this).info(f),At(this).debug(`[${l}] response start`,It({retryOfRequestLogID:n,url:h.url,status:h.status,headers:h.headers,durationMs:p-u})),{response:h,options:s,controller:d,requestLogID:l,retryOfRequestLogID:n,startTime:u}}getAPIList(e,t,n){return this.requestAPIList(t,{method:"get",path:e,...n})}requestAPIList(e,t){const n=this.makeRequest(t,null,void 0);return new Lt(this,n,e)}async fetchWithTimeout(e,t,n,s){const{signal:r,method:o,...i}=t||{};r&&r.addEventListener("abort",(()=>s.abort()));const a=setTimeout((()=>s.abort()),n),l=globalThis.ReadableStream&&i.body instanceof globalThis.ReadableStream||"object"==typeof i.body&&null!==i.body&&Symbol.asyncIterator in i.body,c={signal:s.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,n,s){let r;const o=s?.get("retry-after-ms");if(o){const e=parseFloat(o);Number.isNaN(e)||(r=e)}const i=s?.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 n=e.maxRetries??this.maxRetries;r=this.calculateDefaultRetryTimeoutMillis(t,n)}return await Be(r),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){const n=t-e;return Math.min(.5*Math.pow(2,n),8)*(1-.25*Math.random())*1e3}async buildRequest(e,{retryCount:t=0}={}){const n={...e},{method:s,path:r,query:o,defaultBaseURL:i}=n,a=this.buildURL(r,o,i);"timeout"in n&&((e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new we(`${e} must be an integer`);if(t<0)throw new we(`${e} must be a positive integer`)})("timeout",n.timeout),n.timeout=n.timeout??this.timeout;const{bodyHeaders:l,body:c}=this.buildBody({options:n});return{req:{method:s,headers:await this.buildHeaders({options:e,method:s,bodyHeaders:l,retryCount:t}),...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&c instanceof globalThis.ReadableStream&&{duplex:"half"},...c&&{body:c},...this.fetchOptions??{},...n.fetchOptions??{}},url:a,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:s}){let r={};this.idempotencyHeader&&"get"!==t&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),r[this.idempotencyHeader]=e.idempotencyKey);const o=bs([r,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Ke??(Ke=Fe()),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(o),o.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};const n=bs([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||"string"==typeof e&&n.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:Ve(e)}:me(this,so,"f").call(this,{body:e,headers:n})}}function ao(e,t,n){const[s,r]=ie([]),[o,i]=ie(null);return{models:s,fetchModels:()=>X(this,void 0,void 0,(function*(){if(e)try{const s=new io({apiKey:e,baseURL:t||void 0,project:n||void 0,dangerouslyAllowBrowser:!0}),o=(yield s.models.list()).data.filter((e=>e.id.startsWith("gpt")||-1!==e.id.search(/^o\d+/gi)||e.id.startsWith("chatgpt")));o.sort(((e,t)=>t.id.localeCompare(e.id))),r(o.map((e=>e.id))),i(null)}catch(e){console.error(e),i(e.message||String(e))}})),validateModel:(s,r)=>X(this,void 0,void 0,(function*(){var o,i;if(!e||!s)return{success:!1,error:"API Key and Model are required"};try{const a=new io({apiKey:e,baseURL:t||void 0,project:n||void 0,dangerouslyAllowBrowser:!0}),l=null===(i=null===(o=(yield a.chat.completions.create({model:s,messages:[{role:"user",content:"reply just pong, set success to true, and provide a random number between 1 and 100."}],max_completion_tokens:r||2e3,response_format:{type:"json_schema",json_schema:{name:"model_test",strict:!0,schema:{type:"object",properties:{reply:{type:"string",description:"The text reply"},success:{type:"boolean",description:"Always true"},data:{type:"object",properties:{number:{type:"integer"}},required:["number"],additionalProperties:!1}},required:["reply","success","data"],additionalProperties:!1}}}})).choices[0])||void 0===o?void 0:o.message)||void 0===i?void 0:i.content;if(!l)throw new Error("No content returned from the model.");const c=JSON.parse(l);if("string"!=typeof c.reply||"boolean"!=typeof c.success||"object"!=typeof c.data||"number"!=typeof c.data.number)throw new Error("Model did not follow the JSON schema correctly.");return{success:!0,message:"The model is valid and supports structured outputs!"}}catch(e){return{success:!1,error:e.message||String(e)}}})),error:o,isCurrentVersionSupportingImages:e=>{if(!e)return!1;const t=e.match(/gpt-(\d+)/);return!!(null==t?void 0:t[1])&&Number(t[1])>=4}}}function lo({config:e,onChange:t,showMessage:n,visible:s}){if(!s)return null;const{models:r,fetchModels:o,validateModel:i}=ao(e.apiKey,e.baseURL,e.projectId),[a,l]=ie(!1);return H("div",{class:"bg-panel-bg backdrop-blur-md border border-panel-border rounded-2xl p-4 shadow-[0_8px_32px_0_rgba(0,0,0,0.3)]",id:"settings",children:[H("div",{class:"flex flex-col gap-2 mb-4",children:[H("label",{htmlFor:"apiKey",class:"text-sm font-medium text-text-secondary",children:["Api Key",H("span",{class:"text-error ml-1",children:"*"})]}),H("input",{id:"apiKey",type:"text",placeholder:"sk-...",class:"w-full px-3 py-2.5 bg-input-bg border border-input-border rounded-lg text-text-primary text-sm transition-all focus:outline-none focus:border-input-focus focus:ring-2 focus:ring-primary/20 box-border",value:e.apiKey||"",onInput:e=>t("apiKey",e.target.value)})]}),H("div",{class:"flex flex-col gap-2",children:[H("label",{htmlFor:"model",class:"text-sm font-medium text-text-secondary",children:["GPT Model",H("span",{class:"text-error ml-1",children:"*"})]}),H("div",{class:"relative flex items-center",children:[H("input",{type:"text",id:"model",list:"models",placeholder:"gpt-4o",class:"w-full pl-3 pr-9 py-2.5 bg-input-bg border border-input-border rounded-lg text-text-primary text-sm transition-all focus:outline-none focus:border-input-focus focus:ring-2 focus:ring-primary/20 box-border",value:e.model||"",onInput:e=>t("model",e.target.value),onFocus:o}),H("datalist",{id:"models",children:r.map((e=>H("option",{value:e,children:e},e)))}),H("i",{class:`fa-solid ${a?"fa-spinner fa-spin":"fa-play"} absolute right-3 text-primary text-sm transition-all hover:scale-110 hover:text-primary-hover cursor-pointer`,onClick:()=>X(this,void 0,void 0,(function*(){if(!e.model)return void n("Please select a model first",!0);l(!0),n("Checking GPT version...",!1);const t=yield i(e.model,e.maxTokens);l(!1),t.success?n(t.message||"Valid model"):n(t.error||"Invalid model",!0)})),title:"Test"})]})]})]})}function co({config:e,onChange:t,visible:n}){return n?H("div",{class:"bg-panel-bg backdrop-blur-md border border-panel-border rounded-2xl p-4 shadow-[0_8px_32px_0_rgba(0,0,0,0.3)] flex flex-col gap-4",id:"advanced-settings",children:[H("div",{class:"flex flex-col gap-2",children:[H("label",{htmlFor:"code",class:"text-sm font-medium text-text-secondary",children:"Activation Code"}),H("input",{id:"code",type:"text",placeholder:"Secret key...",class:"w-full px-3 py-2.5 bg-input-bg border border-input-border rounded-lg text-text-primary text-sm transition-all focus:outline-none focus:border-input-focus focus:ring-2 focus:ring-primary/20 box-border",value:e.code||"",onInput:e=>t("code",e.target.value)})]}),H("div",{class:"flex flex-col gap-2",children:[H("label",{htmlFor:"baseURL",class:"text-sm font-medium text-text-secondary",children:"Base URL"}),H("input",{id:"baseURL",type:"text",placeholder:"https://api.openai.com/v1",class:"w-full px-3 py-2.5 bg-input-bg border border-input-border rounded-lg text-text-primary text-sm transition-all focus:outline-none focus:border-input-focus focus:ring-2 focus:ring-primary/20 box-border",value:e.baseURL||"",onInput:e=>t("baseURL",e.target.value)})]}),H("div",{class:"flex flex-col gap-2",children:[H("label",{htmlFor:"projectId",class:"text-sm font-medium text-text-secondary",children:"Project ID"}),H("input",{id:"projectId",type:"text",placeholder:"proj_...",class:"w-full px-3 py-2.5 bg-input-bg border border-input-border rounded-lg text-text-primary text-sm transition-all focus:outline-none focus:border-input-focus focus:ring-2 focus:ring-primary/20 box-border",value:e.projectId||"",onInput:e=>t("projectId",e.target.value)})]}),H("div",{class:"flex flex-col gap-2",children:[H("label",{htmlFor:"maxTokens",class:"text-sm font-medium text-text-secondary",children:"Max Tokens"}),H("input",{id:"maxTokens",type:"number",class:"w-full px-3 py-2.5 bg-input-bg border border-input-border rounded-lg text-text-primary text-sm transition-all focus:outline-none focus:border-input-focus focus:ring-2 focus:ring-primary/20 box-border",value:e.maxTokens||"",onInput:e=>{const n=e.target.value;t("maxTokens",n?parseInt(n):void 0)}})]}),H("div",{class:"flex flex-col gap-2",children:[H("label",{htmlFor:"timeoutValue",class:"text-sm font-medium text-text-secondary",children:"Timeout (s)"}),H("input",{id:"timeoutValue",type:"number",placeholder:"20",class:"w-full px-3 py-2.5 bg-input-bg border border-input-border rounded-lg text-text-primary text-sm transition-all focus:outline-none focus:border-input-focus focus:ring-2 focus:ring-primary/20 box-border",value:e.timeoutValue||"",onInput:e=>{const n=e.target.value;t("timeoutValue",n?parseInt(n):void 0)}})]})]}):null}function uo({config:e,onChange:t}){const{isCurrentVersionSupportingImages:n}=ao(),s=(n,s,r=!0)=>r?H("div",{class:"flex justify-between items-center",children:[H("label",{htmlFor:n,class:"text-sm text-text-primary",children:s}),H("label",{class:"toggle-switch",children:[H("input",{id:n,type:"checkbox",checked:!!e[n],onChange:e=>t(n,e.target.checked)}),H("span",{class:"slider"})]})]}):null,r="clipboard"===e.mode;return H("div",{class:"bg-panel-bg backdrop-blur-md border border-panel-border rounded-2xl p-4 shadow-[0_8px_32px_0_rgba(0,0,0,0.3)] grid grid-cols-2 gap-4",children:[s("logs","Console logs"),s("title","Title hint"),s("cursor","Cursor hint"),s("timeout","Timeout"),s("typing","Typing effect",!r),s("mouseover","Hover effect",!r),s("infinite","Infinite try"),s("history","History"),s("includeImages","Images (GPT-4)",n(e.model))]})}function ho({mode:e,onChange:t}){return H(v,{children:[H("div",{class:"flex items-center gap-2 text-sm font-semibold text-text-primary my-2",children:[H("i",{class:"fa-solid fa-bolt text-primary"}),H("span",{children:"Operating Mode"})]}),H("ul",{id:"mode",class:"list-none p-0 m-0 flex bg-input-bg rounded-xl border border-input-border overflow-hidden",children:[H("li",{class:"flex-1",children:H("button",{value:"autocomplete",class:"w-full p-2.5 border-none font-sans text-sm font-semibold cursor-pointer transition-colors duration-300 "+("autocomplete"===e?"bg-primary text-text-primary shadow-[0_2px_8px_rgba(99,102,241,0.4)]":"bg-transparent text-text-secondary hover:bg-white/5 hover:text-text-primary"),onClick:()=>t("autocomplete"),children:"autocomplete"})}),H("li",{class:"flex-1",children:H("button",{value:"clipboard",class:"w-full p-2.5 border-none font-sans text-sm font-semibold cursor-pointer transition-colors duration-300 "+("clipboard"===e?"bg-primary text-text-primary shadow-[0_2px_8px_rgba(99,102,241,0.4)]":"bg-transparent text-text-secondary hover:bg-white/5 hover:text-text-primary"),onClick:()=>t("clipboard"),children:"clipboard"})})]})]})}no=io,so=new WeakMap,to=new WeakSet,ro=function(){return"https://api.openai.com/v1"!==this.baseURL},io.OpenAI=no,io.DEFAULT_TIMEOUT=6e5,io.OpenAIError=we,io.APIError=ve,io.APIConnectionError=Se,io.APIConnectionTimeoutError=ke,io.APIUserAbortError=xe,io.NotFoundError=Oe,io.ConflictError=Re,io.RateLimitError=Ce,io.BadRequestError=$e,io.AuthenticationError=Ae,io.InternalServerError=Ee,io.PermissionDeniedError=Ie,io.UnprocessableEntityError=Pe,io.InvalidWebhookSignatureError=Me,io.toFile=async function(e,t,n){if(Bt(),(e=>null!=e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.lastModified&&zt(e))(e=await e))return e instanceof File?e:Ut([await e.arrayBuffer()],e.name);if((e=>null!=e&&"object"==typeof e&&"string"==typeof e.url&&"function"==typeof e.blob)(e)){const s=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),Ut(await Gt(s),t,n)}const s=await Gt(e);if(t||(t=Ft(e)),!n?.type){const e=s.find((e=>"object"==typeof e&&"type"in e&&e.type));"string"==typeof e&&(n={...n,type:e})}return Ut(s,t,n)},io.Completions=or,io.Chat=ms,io.Embeddings=dr,io.Files=_r,io.Images=Ar,io.Audio=Ss,io.Moderations=Or,io.Models=Ir,io.FineTuning=Sr,io.Graders=$r,io.VectorStores=Qr,io.Webhooks=oo,io.Beta=rr,io.Batches=ks,io.Uploads=Vr,io.Responses=Kr,io.Realtime=Pr,io.Conversations=ur,io.Evals=fr,io.Containers=lr;const po=document.getElementById("root");po&&function(n,s){var r,o,i;s==document&&(s=document.documentElement),t.__&&t.__(n,s),r=s.__k,o=[],i=[],M(s,n=s.__k=function(t,n,s){var r,o,i,a={};for(i in n)"key"==i?r=n[i]:"ref"==i?o=n[i]:a[i]=n[i];if(arguments.length>2&&(a.children=arguments.length>3?e.call(arguments,2):s),"function"==typeof t&&null!=t.defaultProps)for(i in t.defaultProps)void 0===a[i]&&(a[i]=t.defaultProps[i]);return w(t,a,r,o,null)}(v,null,[n]),r||f,f,s.namespaceURI,r?null:s.firstChild?e.call(s.childNodes):null,o,r?r.__e:s.firstChild,!1,i),L(o,n,i)}(H((function(){const{config:e,loading:t,saveConfig:n,setConfig:s}=function(){const[e,t]=ie({mode:"autocomplete",title:!0,cursor:!0,timeout:!0}),[n,s]=ie(!0);return ae((()=>{chrome.storage.sync.get(["moodleGPT"]).then((e=>{e.moodleGPT&&t((t=>Object.assign(Object.assign({},t),e.moodleGPT))),s(!1)}))}),[]),{config:e,loading:n,saveConfig:n=>X(this,void 0,void 0,(function*(){const s=Object.assign(Object.assign({},e),n);t(s),yield chrome.storage.sync.set({moodleGPT:s})})),setConfig:t}}(),[r,o]=ie(!1),[i,a]=ie(null);if(t)return null;const l=(e,t)=>{s((n=>Object.assign(Object.assign({},n),{[e]:t})))},c=(e,t=!1)=>{a({text:e,isError:t}),setTimeout((()=>a(null)),5e3)};return H("main",{class:"p-6 flex flex-col gap-5 bg-gradient-to-br from-gradient-start to-gradient-end text-text-primary min-h-screen font-sans antialiased overflow-x-hidden",children:[H(fe,{}),H(lo,{config:e,onChange:l,showMessage:c,visible:!r}),H(co,{config:e,onChange:l,visible:r}),H("a",{href:"#",class:"block text-center text-sm text-text-secondary no-underline transition-colors hover:text-text-primary",onClick:e=>{e.preventDefault(),o(!r)},children:r?"Go back to settings":"Show Advanced Settings"}),H(ho,{mode:e.mode||"autocomplete",onChange:e=>l("mode",e)}),H("div",{class:"flex items-center gap-2 text-sm font-semibold text-text-primary my-2",children:[H("i",{class:"fa-solid fa-sliders text-primary"}),H("span",{children:"Options"})]}),H(uo,{config:e,onChange:l}),i&&H("p",{class:"text-center text-sm font-medium m-0 min-h-[18px] "+(i.isError?"text-error":"text-success"),children:i.text}),H("button",{class:"w-full p-3 bg-gradient-to-br from-primary to-primary-hover text-white border-none rounded-xl text-base font-semibold cursor-pointer transition-all hover:-translate-y-0.5 hover:shadow-[0_4px_12px_rgba(99,102,241,0.4)] active:translate-y-0 mt-2",onClick:()=>X(this,void 0,void 0,(function*(){e.apiKey&&e.model?e.code&&e.code.length>0&&e.code.length<2?c("The code should at least contain 2 characters",!0):(yield n(e),c("Configuration saved")):c("Please complete all the form",!0)})),children:"Save Preferences"}),H("div",{class:"flex justify-center gap-6 mt-2",children:[H("a",{class:"text-sm font-medium no-underline transition-colors text-amber-400 hover:text-amber-300",href:"https://www.buymeacoffee.com/yoannchbpro",target:"_blank",rel:"noopener noreferrer",children:"Support"}),H("a",{class:"text-sm font-medium no-underline transition-colors text-text-secondary hover:text-text-primary",href:"https://github.com/yoannchb-pro/MoodleGPT",target:"_blank",rel:"noopener noreferrer",children:"Docs"})]})]})}),{}),po)}));
|
|
//# sourceMappingURL=popup.js.map
|