@mulmocast/slide 0.6.1 → 0.6.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,115 +0,0 @@
1
- (function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))r(s);new MutationObserver(s=>{for(const o of s)if(o.type==="childList")for(const i of o.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&r(i)}).observe(document,{childList:!0,subtree:!0});function n(s){const o={};return s.integrity&&(o.integrity=s.integrity),s.referrerPolicy&&(o.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?o.credentials="include":s.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function r(s){if(s.ep)return;s.ep=!0;const o=n(s);fetch(s.href,o)}})();function Ed(e){const t=Object.create(null);for(const n of e.split(","))t[n]=1;return n=>n in t}const Ne={},Mr=[],$t=()=>{},ov=()=>!1,Ma=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&(e.charCodeAt(2)>122||e.charCodeAt(2)<97),Td=e=>e.startsWith("onUpdate:"),Ye=Object.assign,Pd=(e,t)=>{const n=e.indexOf(t);n>-1&&e.splice(n,1)},eS=Object.prototype.hasOwnProperty,Ie=(e,t)=>eS.call(e,t),he=Array.isArray,Nr=e=>Mi(e)==="[object Map]",Na=e=>Mi(e)==="[object Set]",lf=e=>Mi(e)==="[object Date]",ye=e=>typeof e=="function",qe=e=>typeof e=="string",Ot=e=>typeof e=="symbol",Me=e=>e!==null&&typeof e=="object",iv=e=>(Me(e)||ye(e))&&ye(e.then)&&ye(e.catch),av=Object.prototype.toString,Mi=e=>av.call(e),tS=e=>Mi(e).slice(8,-1),lv=e=>Mi(e)==="[object Object]",Id=e=>qe(e)&&e!=="NaN"&&e[0]!=="-"&&""+parseInt(e,10)===e,fi=Ed(",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted"),Fa=e=>{const t=Object.create(null);return(n=>t[n]||(t[n]=e(n)))},nS=/-\w/g,Fn=Fa(e=>e.replace(nS,t=>t.slice(1).toUpperCase())),rS=/\B([A-Z])/g,cr=Fa(e=>e.replace(rS,"-$1").toLowerCase()),uv=Fa(e=>e.charAt(0).toUpperCase()+e.slice(1)),sl=Fa(e=>e?`on${uv(e)}`:""),Nn=(e,t)=>!Object.is(e,t),ta=(e,...t)=>{for(let n=0;n<e.length;n++)e[n](...t)},cv=(e,t,n,r=!1)=>{Object.defineProperty(e,t,{configurable:!0,enumerable:!1,writable:r,value:n})},ka=e=>{const t=parseFloat(e);return isNaN(t)?e:t};let uf;const Oa=()=>uf||(uf=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{});function xa(e){if(he(e)){const t={};for(let n=0;n<e.length;n++){const r=e[n],s=qe(r)?aS(r):xa(r);if(s)for(const o in s)t[o]=s[o]}return t}else if(qe(e)||Me(e))return e}const sS=/;(?![^(]*\))/g,oS=/:([^]+)/,iS=/\/\*[^]*?\*\//g;function aS(e){const t={};return e.replace(iS,"").split(sS).forEach(n=>{if(n){const r=n.split(oS);r.length>1&&(t[r[0].trim()]=r[1].trim())}}),t}function Rt(e){let t="";if(qe(e))t=e;else if(he(e))for(let n=0;n<e.length;n++){const r=Rt(e[n]);r&&(t+=r+" ")}else if(Me(e))for(const n in e)e[n]&&(t+=n+" ");return t.trim()}function cf(e){if(!e)return null;let{class:t,style:n}=e;return t&&!qe(t)&&(e.class=Rt(t)),n&&(e.style=xa(n)),e}const lS="itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly",uS=Ed(lS);function dv(e){return!!e||e===""}function cS(e,t){if(e.length!==t.length)return!1;let n=!0;for(let r=0;n&&r<e.length;r++)n=Ni(e[r],t[r]);return n}function Ni(e,t){if(e===t)return!0;let n=lf(e),r=lf(t);if(n||r)return n&&r?e.getTime()===t.getTime():!1;if(n=Ot(e),r=Ot(t),n||r)return e===t;if(n=he(e),r=he(t),n||r)return n&&r?cS(e,t):!1;if(n=Me(e),r=Me(t),n||r){if(!n||!r)return!1;const s=Object.keys(e).length,o=Object.keys(t).length;if(s!==o)return!1;for(const i in e){const a=e.hasOwnProperty(i),l=t.hasOwnProperty(i);if(a&&!l||!a&&l||!Ni(e[i],t[i]))return!1}}return String(e)===String(t)}function dS(e,t){return e.findIndex(n=>Ni(n,t))}const fv=e=>!!(e&&e.__v_isRef===!0),Ue=e=>qe(e)?e:e==null?"":he(e)||Me(e)&&(e.toString===av||!ye(e.toString))?fv(e)?Ue(e.value):JSON.stringify(e,pv,2):String(e),pv=(e,t)=>fv(t)?pv(e,t.value):Nr(t)?{[`Map(${t.size})`]:[...t.entries()].reduce((n,[r,s],o)=>(n[ol(r,o)+" =>"]=s,n),{})}:Na(t)?{[`Set(${t.size})`]:[...t.values()].map(n=>ol(n))}:Ot(t)?ol(t):Me(t)&&!he(t)&&!lv(t)?String(t):t,ol=(e,t="")=>{var n;return Ot(e)?`Symbol(${(n=e.description)!=null?n:t})`:e};let ut;class fS{constructor(t=!1){this.detached=t,this._active=!0,this._on=0,this.effects=[],this.cleanups=[],this._isPaused=!1,this.__v_skip=!0,this.parent=ut,!t&&ut&&(this.index=(ut.scopes||(ut.scopes=[])).push(this)-1)}get active(){return this._active}pause(){if(this._active){this._isPaused=!0;let t,n;if(this.scopes)for(t=0,n=this.scopes.length;t<n;t++)this.scopes[t].pause();for(t=0,n=this.effects.length;t<n;t++)this.effects[t].pause()}}resume(){if(this._active&&this._isPaused){this._isPaused=!1;let t,n;if(this.scopes)for(t=0,n=this.scopes.length;t<n;t++)this.scopes[t].resume();for(t=0,n=this.effects.length;t<n;t++)this.effects[t].resume()}}run(t){if(this._active){const n=ut;try{return ut=this,t()}finally{ut=n}}}on(){++this._on===1&&(this.prevScope=ut,ut=this)}off(){this._on>0&&--this._on===0&&(ut=this.prevScope,this.prevScope=void 0)}stop(t){if(this._active){this._active=!1;let n,r;for(n=0,r=this.effects.length;n<r;n++)this.effects[n].stop();for(this.effects.length=0,n=0,r=this.cleanups.length;n<r;n++)this.cleanups[n]();if(this.cleanups.length=0,this.scopes){for(n=0,r=this.scopes.length;n<r;n++)this.scopes[n].stop(!0);this.scopes.length=0}if(!this.detached&&this.parent&&!t){const s=this.parent.scopes.pop();s&&s!==this&&(this.parent.scopes[this.index]=s,s.index=this.index)}this.parent=void 0}}}function pS(){return ut}let Fe;const il=new WeakSet;class hv{constructor(t){this.fn=t,this.deps=void 0,this.depsTail=void 0,this.flags=5,this.next=void 0,this.cleanup=void 0,this.scheduler=void 0,ut&&ut.active&&ut.effects.push(this)}pause(){this.flags|=64}resume(){this.flags&64&&(this.flags&=-65,il.has(this)&&(il.delete(this),this.trigger()))}notify(){this.flags&2&&!(this.flags&32)||this.flags&8||mv(this)}run(){if(!(this.flags&1))return this.fn();this.flags|=2,df(this),_v(this);const t=Fe,n=Mt;Fe=this,Mt=!0;try{return this.fn()}finally{yv(this),Fe=t,Mt=n,this.flags&=-3}}stop(){if(this.flags&1){for(let t=this.deps;t;t=t.nextDep)Md(t);this.deps=this.depsTail=void 0,df(this),this.onStop&&this.onStop(),this.flags&=-2}}trigger(){this.flags&64?il.add(this):this.scheduler?this.scheduler():this.runIfDirty()}runIfDirty(){qu(this)&&this.run()}get dirty(){return qu(this)}}let gv=0,pi,hi;function mv(e,t=!1){if(e.flags|=8,t){e.next=hi,hi=e;return}e.next=pi,pi=e}function Cd(){gv++}function Rd(){if(--gv>0)return;if(hi){let t=hi;for(hi=void 0;t;){const n=t.next;t.next=void 0,t.flags&=-9,t=n}}let e;for(;pi;){let t=pi;for(pi=void 0;t;){const n=t.next;if(t.next=void 0,t.flags&=-9,t.flags&1)try{t.trigger()}catch(r){e||(e=r)}t=n}}if(e)throw e}function _v(e){for(let t=e.deps;t;t=t.nextDep)t.version=-1,t.prevActiveLink=t.dep.activeLink,t.dep.activeLink=t}function yv(e){let t,n=e.depsTail,r=n;for(;r;){const s=r.prevDep;r.version===-1?(r===n&&(n=s),Md(r),hS(r)):t=r,r.dep.activeLink=r.prevActiveLink,r.prevActiveLink=void 0,r=s}e.deps=t,e.depsTail=n}function qu(e){for(let t=e.deps;t;t=t.nextDep)if(t.dep.version!==t.version||t.dep.computed&&(vv(t.dep.computed)||t.dep.version!==t.version))return!0;return!!e._dirty}function vv(e){if(e.flags&4&&!(e.flags&16)||(e.flags&=-17,e.globalVersion===vi)||(e.globalVersion=vi,!e.isSSR&&e.flags&128&&(!e.deps&&!e._dirty||!qu(e))))return;e.flags|=2;const t=e.dep,n=Fe,r=Mt;Fe=e,Mt=!0;try{_v(e);const s=e.fn(e._value);(t.version===0||Nn(s,e._value))&&(e.flags|=128,e._value=s,t.version++)}catch(s){throw t.version++,s}finally{Fe=n,Mt=r,yv(e),e.flags&=-3}}function Md(e,t=!1){const{dep:n,prevSub:r,nextSub:s}=e;if(r&&(r.nextSub=s,e.prevSub=void 0),s&&(s.prevSub=r,e.nextSub=void 0),n.subs===e&&(n.subs=r,!r&&n.computed)){n.computed.flags&=-5;for(let o=n.computed.deps;o;o=o.nextDep)Md(o,!0)}!t&&!--n.sc&&n.map&&n.map.delete(n.key)}function hS(e){const{prevDep:t,nextDep:n}=e;t&&(t.nextDep=n,e.prevDep=void 0),n&&(n.prevDep=t,e.nextDep=void 0)}let Mt=!0;const bv=[];function hn(){bv.push(Mt),Mt=!1}function gn(){const e=bv.pop();Mt=e===void 0?!0:e}function df(e){const{cleanup:t}=e;if(e.cleanup=void 0,t){const n=Fe;Fe=void 0;try{t()}finally{Fe=n}}}let vi=0;class gS{constructor(t,n){this.sub=t,this.dep=n,this.version=n.version,this.nextDep=this.prevDep=this.nextSub=this.prevSub=this.prevActiveLink=void 0}}class Nd{constructor(t){this.computed=t,this.version=0,this.activeLink=void 0,this.subs=void 0,this.map=void 0,this.key=void 0,this.sc=0,this.__v_skip=!0}track(t){if(!Fe||!Mt||Fe===this.computed)return;let n=this.activeLink;if(n===void 0||n.sub!==Fe)n=this.activeLink=new gS(Fe,this),Fe.deps?(n.prevDep=Fe.depsTail,Fe.depsTail.nextDep=n,Fe.depsTail=n):Fe.deps=Fe.depsTail=n,Av(n);else if(n.version===-1&&(n.version=this.version,n.nextDep)){const r=n.nextDep;r.prevDep=n.prevDep,n.prevDep&&(n.prevDep.nextDep=r),n.prevDep=Fe.depsTail,n.nextDep=void 0,Fe.depsTail.nextDep=n,Fe.depsTail=n,Fe.deps===n&&(Fe.deps=r)}return n}trigger(t){this.version++,vi++,this.notify(t)}notify(t){Cd();try{for(let n=this.subs;n;n=n.prevSub)n.sub.notify()&&n.sub.dep.notify()}finally{Rd()}}}function Av(e){if(e.dep.sc++,e.sub.flags&4){const t=e.dep.computed;if(t&&!e.dep.subs){t.flags|=20;for(let r=t.deps;r;r=r.nextDep)Av(r)}const n=e.dep.subs;n!==e&&(e.prevSub=n,n&&(n.nextSub=e)),e.dep.subs=e}}const Lu=new WeakMap,lr=Symbol(""),Uu=Symbol(""),bi=Symbol("");function ze(e,t,n){if(Mt&&Fe){let r=Lu.get(e);r||Lu.set(e,r=new Map);let s=r.get(n);s||(r.set(n,s=new Nd),s.map=r,s.key=n),s.track()}}function dn(e,t,n,r,s,o){const i=Lu.get(e);if(!i){vi++;return}const a=l=>{l&&l.trigger()};if(Cd(),t==="clear")i.forEach(a);else{const l=he(e),u=l&&Id(n);if(l&&n==="length"){const c=Number(r);i.forEach((d,p)=>{(p==="length"||p===bi||!Ot(p)&&p>=c)&&a(d)})}else switch((n!==void 0||i.has(void 0))&&a(i.get(n)),u&&a(i.get(bi)),t){case"add":l?u&&a(i.get("length")):(a(i.get(lr)),Nr(e)&&a(i.get(Uu)));break;case"delete":l||(a(i.get(lr)),Nr(e)&&a(i.get(Uu)));break;case"set":Nr(e)&&a(i.get(lr));break}}Rd()}function fr(e){const t=Pe(e);return t===e?t:(ze(t,"iterate",bi),gt(e)?t:t.map(xt))}function Da(e){return ze(e=Pe(e),"iterate",bi),e}function Rn(e,t){return mn(e)?Lr(ur(e)?xt(t):t):xt(t)}const mS={__proto__:null,[Symbol.iterator](){return al(this,Symbol.iterator,e=>Rn(this,e))},concat(...e){return fr(this).concat(...e.map(t=>he(t)?fr(t):t))},entries(){return al(this,"entries",e=>(e[1]=Rn(this,e[1]),e))},every(e,t){return Qt(this,"every",e,t,void 0,arguments)},filter(e,t){return Qt(this,"filter",e,t,n=>n.map(r=>Rn(this,r)),arguments)},find(e,t){return Qt(this,"find",e,t,n=>Rn(this,n),arguments)},findIndex(e,t){return Qt(this,"findIndex",e,t,void 0,arguments)},findLast(e,t){return Qt(this,"findLast",e,t,n=>Rn(this,n),arguments)},findLastIndex(e,t){return Qt(this,"findLastIndex",e,t,void 0,arguments)},forEach(e,t){return Qt(this,"forEach",e,t,void 0,arguments)},includes(...e){return ll(this,"includes",e)},indexOf(...e){return ll(this,"indexOf",e)},join(e){return fr(this).join(e)},lastIndexOf(...e){return ll(this,"lastIndexOf",e)},map(e,t){return Qt(this,"map",e,t,void 0,arguments)},pop(){return Kr(this,"pop")},push(...e){return Kr(this,"push",e)},reduce(e,...t){return ff(this,"reduce",e,t)},reduceRight(e,...t){return ff(this,"reduceRight",e,t)},shift(){return Kr(this,"shift")},some(e,t){return Qt(this,"some",e,t,void 0,arguments)},splice(...e){return Kr(this,"splice",e)},toReversed(){return fr(this).toReversed()},toSorted(e){return fr(this).toSorted(e)},toSpliced(...e){return fr(this).toSpliced(...e)},unshift(...e){return Kr(this,"unshift",e)},values(){return al(this,"values",e=>Rn(this,e))}};function al(e,t,n){const r=Da(e),s=r[t]();return r!==e&&!gt(e)&&(s._next=s.next,s.next=()=>{const o=s._next();return o.done||(o.value=n(o.value)),o}),s}const _S=Array.prototype;function Qt(e,t,n,r,s,o){const i=Da(e),a=i!==e&&!gt(e),l=i[t];if(l!==_S[t]){const d=l.apply(e,o);return a?xt(d):d}let u=n;i!==e&&(a?u=function(d,p){return n.call(this,Rn(e,d),p,e)}:n.length>2&&(u=function(d,p){return n.call(this,d,p,e)}));const c=l.call(i,u,r);return a&&s?s(c):c}function ff(e,t,n,r){const s=Da(e);let o=n;return s!==e&&(gt(e)?n.length>3&&(o=function(i,a,l){return n.call(this,i,a,l,e)}):o=function(i,a,l){return n.call(this,i,Rn(e,a),l,e)}),s[t](o,...r)}function ll(e,t,n){const r=Pe(e);ze(r,"iterate",bi);const s=r[t](...n);return(s===-1||s===!1)&&xd(n[0])?(n[0]=Pe(n[0]),r[t](...n)):s}function Kr(e,t,n=[]){hn(),Cd();const r=Pe(e)[t].apply(e,n);return Rd(),gn(),r}const yS=Ed("__proto__,__v_isRef,__isVue"),Sv=new Set(Object.getOwnPropertyNames(Symbol).filter(e=>e!=="arguments"&&e!=="caller").map(e=>Symbol[e]).filter(Ot));function vS(e){Ot(e)||(e=String(e));const t=Pe(this);return ze(t,"has",e),t.hasOwnProperty(e)}class wv{constructor(t=!1,n=!1){this._isReadonly=t,this._isShallow=n}get(t,n,r){if(n==="__v_skip")return t.__v_skip;const s=this._isReadonly,o=this._isShallow;if(n==="__v_isReactive")return!s;if(n==="__v_isReadonly")return s;if(n==="__v_isShallow")return o;if(n==="__v_raw")return r===(s?o?RS:Iv:o?Pv:Tv).get(t)||Object.getPrototypeOf(t)===Object.getPrototypeOf(r)?t:void 0;const i=he(t);if(!s){let l;if(i&&(l=mS[n]))return l;if(n==="hasOwnProperty")return vS}const a=Reflect.get(t,n,Ze(t)?t:r);if((Ot(n)?Sv.has(n):yS(n))||(s||ze(t,"get",n),o))return a;if(Ze(a)){const l=i&&Id(n)?a:a.value;return s&&Me(l)?Vu(l):l}return Me(a)?s?Vu(a):kd(a):a}}class Ev extends wv{constructor(t=!1){super(!1,t)}set(t,n,r,s){let o=t[n];const i=he(t)&&Id(n);if(!this._isShallow){const u=mn(o);if(!gt(r)&&!mn(r)&&(o=Pe(o),r=Pe(r)),!i&&Ze(o)&&!Ze(r))return u||(o.value=r),!0}const a=i?Number(n)<t.length:Ie(t,n),l=Reflect.set(t,n,r,Ze(t)?t:s);return t===Pe(s)&&(a?Nn(r,o)&&dn(t,"set",n,r):dn(t,"add",n,r)),l}deleteProperty(t,n){const r=Ie(t,n);t[n];const s=Reflect.deleteProperty(t,n);return s&&r&&dn(t,"delete",n,void 0),s}has(t,n){const r=Reflect.has(t,n);return(!Ot(n)||!Sv.has(n))&&ze(t,"has",n),r}ownKeys(t){return ze(t,"iterate",he(t)?"length":lr),Reflect.ownKeys(t)}}class bS extends wv{constructor(t=!1){super(!0,t)}set(t,n){return!0}deleteProperty(t,n){return!0}}const AS=new Ev,SS=new bS,wS=new Ev(!0);const Gu=e=>e,Ui=e=>Reflect.getPrototypeOf(e);function ES(e,t,n){return function(...r){const s=this.__v_raw,o=Pe(s),i=Nr(o),a=e==="entries"||e===Symbol.iterator&&i,l=e==="keys"&&i,u=s[e](...r),c=n?Gu:t?Lr:xt;return!t&&ze(o,"iterate",l?Uu:lr),Ye(Object.create(u),{next(){const{value:d,done:p}=u.next();return p?{value:d,done:p}:{value:a?[c(d[0]),c(d[1])]:c(d),done:p}}})}}function Gi(e){return function(...t){return e==="delete"?!1:e==="clear"?void 0:this}}function TS(e,t){const n={get(s){const o=this.__v_raw,i=Pe(o),a=Pe(s);e||(Nn(s,a)&&ze(i,"get",s),ze(i,"get",a));const{has:l}=Ui(i),u=t?Gu:e?Lr:xt;if(l.call(i,s))return u(o.get(s));if(l.call(i,a))return u(o.get(a));o!==i&&o.get(s)},get size(){const s=this.__v_raw;return!e&&ze(Pe(s),"iterate",lr),s.size},has(s){const o=this.__v_raw,i=Pe(o),a=Pe(s);return e||(Nn(s,a)&&ze(i,"has",s),ze(i,"has",a)),s===a?o.has(s):o.has(s)||o.has(a)},forEach(s,o){const i=this,a=i.__v_raw,l=Pe(a),u=t?Gu:e?Lr:xt;return!e&&ze(l,"iterate",lr),a.forEach((c,d)=>s.call(o,u(c),u(d),i))}};return Ye(n,e?{add:Gi("add"),set:Gi("set"),delete:Gi("delete"),clear:Gi("clear")}:{add(s){!t&&!gt(s)&&!mn(s)&&(s=Pe(s));const o=Pe(this);return Ui(o).has.call(o,s)||(o.add(s),dn(o,"add",s,s)),this},set(s,o){!t&&!gt(o)&&!mn(o)&&(o=Pe(o));const i=Pe(this),{has:a,get:l}=Ui(i);let u=a.call(i,s);u||(s=Pe(s),u=a.call(i,s));const c=l.call(i,s);return i.set(s,o),u?Nn(o,c)&&dn(i,"set",s,o):dn(i,"add",s,o),this},delete(s){const o=Pe(this),{has:i,get:a}=Ui(o);let l=i.call(o,s);l||(s=Pe(s),l=i.call(o,s)),a&&a.call(o,s);const u=o.delete(s);return l&&dn(o,"delete",s,void 0),u},clear(){const s=Pe(this),o=s.size!==0,i=s.clear();return o&&dn(s,"clear",void 0,void 0),i}}),["keys","values","entries",Symbol.iterator].forEach(s=>{n[s]=ES(s,e,t)}),n}function Fd(e,t){const n=TS(e,t);return(r,s,o)=>s==="__v_isReactive"?!e:s==="__v_isReadonly"?e:s==="__v_raw"?r:Reflect.get(Ie(n,s)&&s in r?n:r,s,o)}const PS={get:Fd(!1,!1)},IS={get:Fd(!1,!0)},CS={get:Fd(!0,!1)};const Tv=new WeakMap,Pv=new WeakMap,Iv=new WeakMap,RS=new WeakMap;function MS(e){switch(e){case"Object":case"Array":return 1;case"Map":case"Set":case"WeakMap":case"WeakSet":return 2;default:return 0}}function NS(e){return e.__v_skip||!Object.isExtensible(e)?0:MS(tS(e))}function kd(e){return mn(e)?e:Od(e,!1,AS,PS,Tv)}function FS(e){return Od(e,!1,wS,IS,Pv)}function Vu(e){return Od(e,!0,SS,CS,Iv)}function Od(e,t,n,r,s){if(!Me(e)||e.__v_raw&&!(t&&e.__v_isReactive))return e;const o=NS(e);if(o===0)return e;const i=s.get(e);if(i)return i;const a=new Proxy(e,o===2?r:n);return s.set(e,a),a}function ur(e){return mn(e)?ur(e.__v_raw):!!(e&&e.__v_isReactive)}function mn(e){return!!(e&&e.__v_isReadonly)}function gt(e){return!!(e&&e.__v_isShallow)}function xd(e){return e?!!e.__v_raw:!1}function Pe(e){const t=e&&e.__v_raw;return t?Pe(t):e}function kS(e){return!Ie(e,"__v_skip")&&Object.isExtensible(e)&&cv(e,"__v_skip",!0),e}const xt=e=>Me(e)?kd(e):e,Lr=e=>Me(e)?Vu(e):e;function Ze(e){return e?e.__v_isRef===!0:!1}function be(e){return OS(e,!1)}function OS(e,t){return Ze(e)?e:new xS(e,t)}class xS{constructor(t,n){this.dep=new Nd,this.__v_isRef=!0,this.__v_isShallow=!1,this._rawValue=n?t:Pe(t),this._value=n?t:xt(t),this.__v_isShallow=n}get value(){return this.dep.track(),this._value}set value(t){const n=this._rawValue,r=this.__v_isShallow||gt(t)||mn(t);t=r?t:Pe(t),Nn(t,n)&&(this._rawValue=t,this._value=r?t:xt(t),this.dep.trigger())}}function Dd(e){return Ze(e)?e.value:e}const DS={get:(e,t,n)=>t==="__v_raw"?e:Dd(Reflect.get(e,t,n)),set:(e,t,n,r)=>{const s=e[t];return Ze(s)&&!Ze(n)?(s.value=n,!0):Reflect.set(e,t,n,r)}};function Cv(e){return ur(e)?e:new Proxy(e,DS)}class qS{constructor(t,n,r){this.fn=t,this.setter=n,this._value=void 0,this.dep=new Nd(this),this.__v_isRef=!0,this.deps=void 0,this.depsTail=void 0,this.flags=16,this.globalVersion=vi-1,this.next=void 0,this.effect=this,this.__v_isReadonly=!n,this.isSSR=r}notify(){if(this.flags|=16,!(this.flags&8)&&Fe!==this)return mv(this,!0),!0}get value(){const t=this.dep.track();return vv(this),t&&(t.version=this.dep.version),this._value}set value(t){this.setter&&this.setter(t)}}function LS(e,t,n=!1){let r,s;return ye(e)?r=e:(r=e.get,s=e.set),new qS(r,s,n)}const Vi={},la=new WeakMap;let sr;function US(e,t=!1,n=sr){if(n){let r=la.get(n);r||la.set(n,r=[]),r.push(e)}}function GS(e,t,n=Ne){const{immediate:r,deep:s,once:o,scheduler:i,augmentJob:a,call:l}=n,u=S=>s?S:gt(S)||s===!1||s===0?fn(S,1):fn(S);let c,d,p,g,y=!1,_=!1;if(Ze(e)?(d=()=>e.value,y=gt(e)):ur(e)?(d=()=>u(e),y=!0):he(e)?(_=!0,y=e.some(S=>ur(S)||gt(S)),d=()=>e.map(S=>{if(Ze(S))return S.value;if(ur(S))return u(S);if(ye(S))return l?l(S,2):S()})):ye(e)?t?d=l?()=>l(e,2):e:d=()=>{if(p){hn();try{p()}finally{gn()}}const S=sr;sr=c;try{return l?l(e,3,[g]):e(g)}finally{sr=S}}:d=$t,t&&s){const S=d,P=s===!0?1/0:s;d=()=>fn(S(),P)}const b=pS(),m=()=>{c.stop(),b&&b.active&&Pd(b.effects,c)};if(o&&t){const S=t;t=(...P)=>{S(...P),m()}}let v=_?new Array(e.length).fill(Vi):Vi;const A=S=>{if(!(!(c.flags&1)||!c.dirty&&!S))if(t){const P=c.run();if(s||y||(_?P.some((E,w)=>Nn(E,v[w])):Nn(P,v))){p&&p();const E=sr;sr=c;try{const w=[P,v===Vi?void 0:_&&v[0]===Vi?[]:v,g];v=P,l?l(t,3,w):t(...w)}finally{sr=E}}}else c.run()};return a&&a(A),c=new hv(d),c.scheduler=i?()=>i(A,!1):A,g=S=>US(S,!1,c),p=c.onStop=()=>{const S=la.get(c);if(S){if(l)l(S,4);else for(const P of S)P();la.delete(c)}},t?r?A(!0):v=c.run():i?i(A.bind(null,!0),!0):c.run(),m.pause=c.pause.bind(c),m.resume=c.resume.bind(c),m.stop=m,m}function fn(e,t=1/0,n){if(t<=0||!Me(e)||e.__v_skip||(n=n||new Map,(n.get(e)||0)>=t))return e;if(n.set(e,t),t--,Ze(e))fn(e.value,t,n);else if(he(e))for(let r=0;r<e.length;r++)fn(e[r],t,n);else if(Na(e)||Nr(e))e.forEach(r=>{fn(r,t,n)});else if(lv(e)){for(const r in e)fn(e[r],t,n);for(const r of Object.getOwnPropertySymbols(e))Object.prototype.propertyIsEnumerable.call(e,r)&&fn(e[r],t,n)}return e}function Fi(e,t,n,r){try{return r?e(...r):e()}catch(s){qa(s,t,n)}}function Yt(e,t,n,r){if(ye(e)){const s=Fi(e,t,n,r);return s&&iv(s)&&s.catch(o=>{qa(o,t,n)}),s}if(he(e)){const s=[];for(let o=0;o<e.length;o++)s.push(Yt(e[o],t,n,r));return s}}function qa(e,t,n,r=!0){const s=t?t.vnode:null,{errorHandler:o,throwUnhandledErrorInProduction:i}=t&&t.appContext.config||Ne;if(t){let a=t.parent;const l=t.proxy,u=`https://vuejs.org/error-reference/#runtime-${n}`;for(;a;){const c=a.ec;if(c){for(let d=0;d<c.length;d++)if(c[d](e,l,u)===!1)return}a=a.parent}if(o){hn(),Fi(o,null,10,[e,l,u]),gn();return}}VS(e,n,s,r,i)}function VS(e,t,n,r=!0,s=!1){if(s)throw e;console.error(e)}const rt=[];let jt=-1;const Fr=[];let Mn=null,Tr=0;const Rv=Promise.resolve();let ua=null;function ca(e){const t=ua||Rv;return e?t.then(this?e.bind(this):e):t}function BS(e){let t=jt+1,n=rt.length;for(;t<n;){const r=t+n>>>1,s=rt[r],o=Ai(s);o<e||o===e&&s.flags&2?t=r+1:n=r}return t}function qd(e){if(!(e.flags&1)){const t=Ai(e),n=rt[rt.length-1];!n||!(e.flags&2)&&t>=Ai(n)?rt.push(e):rt.splice(BS(t),0,e),e.flags|=1,Mv()}}function Mv(){ua||(ua=Rv.then(Fv))}function HS(e){he(e)?Fr.push(...e):Mn&&e.id===-1?Mn.splice(Tr+1,0,e):e.flags&1||(Fr.push(e),e.flags|=1),Mv()}function pf(e,t,n=jt+1){for(;n<rt.length;n++){const r=rt[n];if(r&&r.flags&2){if(e&&r.id!==e.uid)continue;rt.splice(n,1),n--,r.flags&4&&(r.flags&=-2),r(),r.flags&4||(r.flags&=-2)}}}function Nv(e){if(Fr.length){const t=[...new Set(Fr)].sort((n,r)=>Ai(n)-Ai(r));if(Fr.length=0,Mn){Mn.push(...t);return}for(Mn=t,Tr=0;Tr<Mn.length;Tr++){const n=Mn[Tr];n.flags&4&&(n.flags&=-2),n.flags&8||n(),n.flags&=-2}Mn=null,Tr=0}}const Ai=e=>e.id==null?e.flags&2?-1:1/0:e.id;function Fv(e){try{for(jt=0;jt<rt.length;jt++){const t=rt[jt];t&&!(t.flags&8)&&(t.flags&4&&(t.flags&=-2),Fi(t,t.i,t.i?15:14),t.flags&4||(t.flags&=-2))}}finally{for(;jt<rt.length;jt++){const t=rt[jt];t&&(t.flags&=-2)}jt=-1,rt.length=0,Nv(),ua=null,(rt.length||Fr.length)&&Fv()}}let Xe=null,kv=null;function da(e){const t=Xe;return Xe=e,kv=e&&e.type.__scopeId||null,t}function JS(e,t=Xe,n){if(!t||e._n)return e;const r=(...s)=>{r._d&&Ef(-1);const o=da(t);let i;try{i=e(...s)}finally{da(o),r._d&&Ef(1)}return i};return r._n=!0,r._c=!0,r._d=!0,r}function Cr(e,t){if(Xe===null)return e;const n=Ba(Xe),r=e.dirs||(e.dirs=[]);for(let s=0;s<t.length;s++){let[o,i,a,l=Ne]=t[s];o&&(ye(o)&&(o={mounted:o,updated:o}),o.deep&&fn(i),r.push({dir:o,instance:n,value:i,oldValue:void 0,arg:a,modifiers:l}))}return e}function qn(e,t,n,r){const s=e.dirs,o=t&&t.dirs;for(let i=0;i<s.length;i++){const a=s[i];o&&(a.oldValue=o[i].value);let l=a.dir[r];l&&(hn(),Yt(l,n,8,[e.el,a,e,t]),gn())}}function jS(e,t){if(st){let n=st.provides;const r=st.parent&&st.parent.provides;r===n&&(n=st.provides=Object.create(r)),n[e]=t}}function na(e,t,n=!1){const r=Bw();if(r||Or){let s=Or?Or._context.provides:r?r.parent==null||r.ce?r.vnode.appContext&&r.vnode.appContext.provides:r.parent.provides:void 0;if(s&&e in s)return s[e];if(arguments.length>1)return n&&ye(t)?t.call(r&&r.proxy):t}}const WS=Symbol.for("v-scx"),KS=()=>na(WS);function pt(e,t,n){return Ov(e,t,n)}function Ov(e,t,n=Ne){const{immediate:r,deep:s,flush:o,once:i}=n,a=Ye({},n),l=t&&r||!t&&o!=="post";let u;if(wi){if(o==="sync"){const g=KS();u=g.__watcherHandles||(g.__watcherHandles=[])}else if(!l){const g=()=>{};return g.stop=$t,g.resume=$t,g.pause=$t,g}}const c=st;a.call=(g,y,_)=>Yt(g,c,y,_);let d=!1;o==="post"?a.scheduler=g=>{lt(g,c&&c.suspense)}:o!=="sync"&&(d=!0,a.scheduler=(g,y)=>{y?g():qd(g)}),a.augmentJob=g=>{t&&(g.flags|=4),d&&(g.flags|=2,c&&(g.id=c.uid,g.i=c))};const p=GS(e,t,a);return wi&&(u?u.push(p):l&&p()),p}function $S(e,t,n){const r=this.proxy,s=qe(e)?e.includes(".")?xv(r,e):()=>r[e]:e.bind(r,r);let o;ye(t)?o=t:(o=t.handler,n=t);const i=Oi(this),a=Ov(s,o.bind(r),n);return i(),a}function xv(e,t){const n=t.split(".");return()=>{let r=e;for(let s=0;s<n.length&&r;s++)r=r[n[s]];return r}}const YS=Symbol("_vte"),zS=e=>e.__isTeleport,XS=Symbol("_leaveCb");function Ld(e,t){e.shapeFlag&6&&e.component?(e.transition=t,Ld(e.component.subTree,t)):e.shapeFlag&128?(e.ssContent.transition=t.clone(e.ssContent),e.ssFallback.transition=t.clone(e.ssFallback)):e.transition=t}function ki(e,t){return ye(e)?Ye({name:e.name},t,{setup:e}):e}function Dv(e){e.ids=[e.ids[0]+e.ids[2]+++"-",0,0]}function hf(e,t){let n;return!!((n=Object.getOwnPropertyDescriptor(e,t))&&!n.configurable)}const fa=new WeakMap;function gi(e,t,n,r,s=!1){if(he(e)){e.forEach((_,b)=>gi(_,t&&(he(t)?t[b]:t),n,r,s));return}if(kr(r)&&!s){r.shapeFlag&512&&r.type.__asyncResolved&&r.component.subTree.component&&gi(e,t,n,r.component.subTree);return}const o=r.shapeFlag&4?Ba(r.component):r.el,i=s?null:o,{i:a,r:l}=e,u=t&&t.r,c=a.refs===Ne?a.refs={}:a.refs,d=a.setupState,p=Pe(d),g=d===Ne?ov:_=>hf(c,_)?!1:Ie(p,_),y=(_,b)=>!(b&&hf(c,b));if(u!=null&&u!==l){if(gf(t),qe(u))c[u]=null,g(u)&&(d[u]=null);else if(Ze(u)){const _=t;y(u,_.k)&&(u.value=null),_.k&&(c[_.k]=null)}}if(ye(l))Fi(l,a,12,[i,c]);else{const _=qe(l),b=Ze(l);if(_||b){const m=()=>{if(e.f){const v=_?g(l)?d[l]:c[l]:y()||!e.k?l.value:c[e.k];if(s)he(v)&&Pd(v,o);else if(he(v))v.includes(o)||v.push(o);else if(_)c[l]=[o],g(l)&&(d[l]=c[l]);else{const A=[o];y(l,e.k)&&(l.value=A),e.k&&(c[e.k]=A)}}else _?(c[l]=i,g(l)&&(d[l]=i)):b&&(y(l,e.k)&&(l.value=i),e.k&&(c[e.k]=i))};if(i){const v=()=>{m(),fa.delete(e)};v.id=-1,fa.set(e,v),lt(v,n)}else gf(e),m()}}}function gf(e){const t=fa.get(e);t&&(t.flags|=8,fa.delete(e))}Oa().requestIdleCallback;Oa().cancelIdleCallback;const kr=e=>!!e.type.__asyncLoader,qv=e=>e.type.__isKeepAlive;function QS(e,t){Lv(e,"a",t)}function ZS(e,t){Lv(e,"da",t)}function Lv(e,t,n=st){const r=e.__wdc||(e.__wdc=()=>{let s=n;for(;s;){if(s.isDeactivated)return;s=s.parent}return e()});if(La(t,r,n),n){let s=n.parent;for(;s&&s.parent;)qv(s.parent.vnode)&&ew(r,t,n,s),s=s.parent}}function ew(e,t,n,r){const s=La(t,e,r,!0);Ua(()=>{Pd(r[t],s)},n)}function La(e,t,n=st,r=!1){if(n){const s=n[e]||(n[e]=[]),o=t.__weh||(t.__weh=(...i)=>{hn();const a=Oi(n),l=Yt(t,n,e,i);return a(),gn(),l});return r?s.unshift(o):s.push(o),o}}const bn=e=>(t,n=st)=>{(!wi||e==="sp")&&La(e,(...r)=>t(...r),n)},tw=bn("bm"),pa=bn("m"),nw=bn("bu"),rw=bn("u"),sw=bn("bum"),Ua=bn("um"),ow=bn("sp"),iw=bn("rtg"),aw=bn("rtc");function lw(e,t=st){La("ec",e,t)}const uw=Symbol.for("v-ndc");function mi(e,t,n,r){let s;const o=n,i=he(e);if(i||qe(e)){const a=i&&ur(e);let l=!1,u=!1;a&&(l=!gt(e),u=mn(e),e=Da(e)),s=new Array(e.length);for(let c=0,d=e.length;c<d;c++)s[c]=t(l?u?Lr(xt(e[c])):xt(e[c]):e[c],c,void 0,o)}else if(typeof e=="number"){s=new Array(e);for(let a=0;a<e;a++)s[a]=t(a+1,a,void 0,o)}else if(Me(e))if(e[Symbol.iterator])s=Array.from(e,(a,l)=>t(a,l,void 0,o));else{const a=Object.keys(e);s=new Array(a.length);for(let l=0,u=a.length;l<u;l++){const c=a[l];s[l]=t(e[c],c,l,o)}}else s=[];return s}function cw(e,t,n={},r,s){if(Xe.ce||Xe.parent&&kr(Xe.parent)&&Xe.parent.ce){const u=Object.keys(n).length>0;return ue(),Ur(He,null,[Nt("slot",n,r&&r())],u?-2:64)}let o=e[t];o&&o._c&&(o._d=!1),ue();const i=o&&Uv(o(n)),a=n.key||i&&i.key,l=Ur(He,{key:(a&&!Ot(a)?a:`_${t}`)+(!i&&r?"_fb":"")},i||(r?r():[]),i&&e._===1?64:-2);return o&&o._c&&(o._d=!0),l}function Uv(e){return e.some(t=>Vd(t)?!(t.type===_n||t.type===He&&!Uv(t.children)):!0)?e:null}const Bu=e=>e?ib(e)?Ba(e):Bu(e.parent):null,_i=Ye(Object.create(null),{$:e=>e,$el:e=>e.vnode.el,$data:e=>e.data,$props:e=>e.props,$attrs:e=>e.attrs,$slots:e=>e.slots,$refs:e=>e.refs,$parent:e=>Bu(e.parent),$root:e=>Bu(e.root),$host:e=>e.ce,$emit:e=>e.emit,$options:e=>Vv(e),$forceUpdate:e=>e.f||(e.f=()=>{qd(e.update)}),$nextTick:e=>e.n||(e.n=ca.bind(e.proxy)),$watch:e=>$S.bind(e)}),ul=(e,t)=>e!==Ne&&!e.__isScriptSetup&&Ie(e,t),dw={get({_:e},t){if(t==="__v_skip")return!0;const{ctx:n,setupState:r,data:s,props:o,accessCache:i,type:a,appContext:l}=e;if(t[0]!=="$"){const p=i[t];if(p!==void 0)switch(p){case 1:return r[t];case 2:return s[t];case 4:return n[t];case 3:return o[t]}else{if(ul(r,t))return i[t]=1,r[t];if(s!==Ne&&Ie(s,t))return i[t]=2,s[t];if(Ie(o,t))return i[t]=3,o[t];if(n!==Ne&&Ie(n,t))return i[t]=4,n[t];Hu&&(i[t]=0)}}const u=_i[t];let c,d;if(u)return t==="$attrs"&&ze(e.attrs,"get",""),u(e);if((c=a.__cssModules)&&(c=c[t]))return c;if(n!==Ne&&Ie(n,t))return i[t]=4,n[t];if(d=l.config.globalProperties,Ie(d,t))return d[t]},set({_:e},t,n){const{data:r,setupState:s,ctx:o}=e;return ul(s,t)?(s[t]=n,!0):r!==Ne&&Ie(r,t)?(r[t]=n,!0):Ie(e.props,t)||t[0]==="$"&&t.slice(1)in e?!1:(o[t]=n,!0)},has({_:{data:e,setupState:t,accessCache:n,ctx:r,appContext:s,props:o,type:i}},a){let l;return!!(n[a]||e!==Ne&&a[0]!=="$"&&Ie(e,a)||ul(t,a)||Ie(o,a)||Ie(r,a)||Ie(_i,a)||Ie(s.config.globalProperties,a)||(l=i.__cssModules)&&l[a])},defineProperty(e,t,n){return n.get!=null?e._.accessCache[t]=0:Ie(n,"value")&&this.set(e,t,n.value,null),Reflect.defineProperty(e,t,n)}};function mf(e){return he(e)?e.reduce((t,n)=>(t[n]=null,t),{}):e}let Hu=!0;function fw(e){const t=Vv(e),n=e.proxy,r=e.ctx;Hu=!1,t.beforeCreate&&_f(t.beforeCreate,e,"bc");const{data:s,computed:o,methods:i,watch:a,provide:l,inject:u,created:c,beforeMount:d,mounted:p,beforeUpdate:g,updated:y,activated:_,deactivated:b,beforeDestroy:m,beforeUnmount:v,destroyed:A,unmounted:S,render:P,renderTracked:E,renderTriggered:w,errorCaptured:I,serverPrefetch:L,expose:H,inheritAttrs:B,components:F,directives:j,filters:U}=t;if(u&&pw(u,r,null),i)for(const T in i){const M=i[T];ye(M)&&(r[T]=M.bind(n))}if(s){const T=s.call(n,n);Me(T)&&(e.data=kd(T))}if(Hu=!0,o)for(const T in o){const M=o[T],k=ye(M)?M.bind(n,n):ye(M.get)?M.get.bind(n,n):$t,G=!ye(M)&&ye(M.set)?M.set.bind(n):$t,V=xe({get:k,set:G});Object.defineProperty(r,T,{enumerable:!0,configurable:!0,get:()=>V.value,set:W=>V.value=W})}if(a)for(const T in a)Gv(a[T],r,n,T);if(l){const T=ye(l)?l.call(n):l;Reflect.ownKeys(T).forEach(M=>{jS(M,T[M])})}c&&_f(c,e,"c");function R(T,M){he(M)?M.forEach(k=>T(k.bind(n))):M&&T(M.bind(n))}if(R(tw,d),R(pa,p),R(nw,g),R(rw,y),R(QS,_),R(ZS,b),R(lw,I),R(aw,E),R(iw,w),R(sw,v),R(Ua,S),R(ow,L),he(H))if(H.length){const T=e.exposed||(e.exposed={});H.forEach(M=>{Object.defineProperty(T,M,{get:()=>n[M],set:k=>n[M]=k,enumerable:!0})})}else e.exposed||(e.exposed={});P&&e.render===$t&&(e.render=P),B!=null&&(e.inheritAttrs=B),F&&(e.components=F),j&&(e.directives=j),L&&Dv(e)}function pw(e,t,n=$t){he(e)&&(e=Ju(e));for(const r in e){const s=e[r];let o;Me(s)?"default"in s?o=na(s.from||r,s.default,!0):o=na(s.from||r):o=na(s),Ze(o)?Object.defineProperty(t,r,{enumerable:!0,configurable:!0,get:()=>o.value,set:i=>o.value=i}):t[r]=o}}function _f(e,t,n){Yt(he(e)?e.map(r=>r.bind(t.proxy)):e.bind(t.proxy),t,n)}function Gv(e,t,n,r){let s=r.includes(".")?xv(n,r):()=>n[r];if(qe(e)){const o=t[e];ye(o)&&pt(s,o)}else if(ye(e))pt(s,e.bind(n));else if(Me(e))if(he(e))e.forEach(o=>Gv(o,t,n,r));else{const o=ye(e.handler)?e.handler.bind(n):t[e.handler];ye(o)&&pt(s,o,e)}}function Vv(e){const t=e.type,{mixins:n,extends:r}=t,{mixins:s,optionsCache:o,config:{optionMergeStrategies:i}}=e.appContext,a=o.get(t);let l;return a?l=a:!s.length&&!n&&!r?l=t:(l={},s.length&&s.forEach(u=>ha(l,u,i,!0)),ha(l,t,i)),Me(t)&&o.set(t,l),l}function ha(e,t,n,r=!1){const{mixins:s,extends:o}=t;o&&ha(e,o,n,!0),s&&s.forEach(i=>ha(e,i,n,!0));for(const i in t)if(!(r&&i==="expose")){const a=hw[i]||n&&n[i];e[i]=a?a(e[i],t[i]):t[i]}return e}const hw={data:yf,props:vf,emits:vf,methods:ui,computed:ui,beforeCreate:tt,created:tt,beforeMount:tt,mounted:tt,beforeUpdate:tt,updated:tt,beforeDestroy:tt,beforeUnmount:tt,destroyed:tt,unmounted:tt,activated:tt,deactivated:tt,errorCaptured:tt,serverPrefetch:tt,components:ui,directives:ui,watch:mw,provide:yf,inject:gw};function yf(e,t){return t?e?function(){return Ye(ye(e)?e.call(this,this):e,ye(t)?t.call(this,this):t)}:t:e}function gw(e,t){return ui(Ju(e),Ju(t))}function Ju(e){if(he(e)){const t={};for(let n=0;n<e.length;n++)t[e[n]]=e[n];return t}return e}function tt(e,t){return e?[...new Set([].concat(e,t))]:t}function ui(e,t){return e?Ye(Object.create(null),e,t):t}function vf(e,t){return e?he(e)&&he(t)?[...new Set([...e,...t])]:Ye(Object.create(null),mf(e),mf(t??{})):t}function mw(e,t){if(!e)return t;if(!t)return e;const n=Ye(Object.create(null),e);for(const r in t)n[r]=tt(e[r],t[r]);return n}function Bv(){return{app:null,config:{isNativeTag:ov,performance:!1,globalProperties:{},optionMergeStrategies:{},errorHandler:void 0,warnHandler:void 0,compilerOptions:{}},mixins:[],components:{},directives:{},provides:Object.create(null),optionsCache:new WeakMap,propsCache:new WeakMap,emitsCache:new WeakMap}}let _w=0;function yw(e,t){return function(r,s=null){ye(r)||(r=Ye({},r)),s!=null&&!Me(s)&&(s=null);const o=Bv(),i=new WeakSet,a=[];let l=!1;const u=o.app={_uid:_w++,_component:r,_props:s,_container:null,_context:o,_instance:null,version:$w,get config(){return o.config},set config(c){},use(c,...d){return i.has(c)||(c&&ye(c.install)?(i.add(c),c.install(u,...d)):ye(c)&&(i.add(c),c(u,...d))),u},mixin(c){return o.mixins.includes(c)||o.mixins.push(c),u},component(c,d){return d?(o.components[c]=d,u):o.components[c]},directive(c,d){return d?(o.directives[c]=d,u):o.directives[c]},mount(c,d,p){if(!l){const g=u._ceVNode||Nt(r,s);return g.appContext=o,p===!0?p="svg":p===!1&&(p=void 0),e(g,c,p),l=!0,u._container=c,c.__vue_app__=u,Ba(g.component)}},onUnmount(c){a.push(c)},unmount(){l&&(Yt(a,u._instance,16),e(null,u._container),delete u._container.__vue_app__)},provide(c,d){return o.provides[c]=d,u},runWithContext(c){const d=Or;Or=u;try{return c()}finally{Or=d}}};return u}}let Or=null;const vw=(e,t)=>t==="modelValue"||t==="model-value"?e.modelModifiers:e[`${t}Modifiers`]||e[`${Fn(t)}Modifiers`]||e[`${cr(t)}Modifiers`];function bw(e,t,...n){if(e.isUnmounted)return;const r=e.vnode.props||Ne;let s=n;const o=t.startsWith("update:"),i=o&&vw(r,t.slice(7));i&&(i.trim&&(s=n.map(c=>qe(c)?c.trim():c)),i.number&&(s=n.map(ka)));let a,l=r[a=sl(t)]||r[a=sl(Fn(t))];!l&&o&&(l=r[a=sl(cr(t))]),l&&Yt(l,e,6,s);const u=r[a+"Once"];if(u){if(!e.emitted)e.emitted={};else if(e.emitted[a])return;e.emitted[a]=!0,Yt(u,e,6,s)}}const Aw=new WeakMap;function Hv(e,t,n=!1){const r=n?Aw:t.emitsCache,s=r.get(e);if(s!==void 0)return s;const o=e.emits;let i={},a=!1;if(!ye(e)){const l=u=>{const c=Hv(u,t,!0);c&&(a=!0,Ye(i,c))};!n&&t.mixins.length&&t.mixins.forEach(l),e.extends&&l(e.extends),e.mixins&&e.mixins.forEach(l)}return!o&&!a?(Me(e)&&r.set(e,null),null):(he(o)?o.forEach(l=>i[l]=null):Ye(i,o),Me(e)&&r.set(e,i),i)}function Ga(e,t){return!e||!Ma(t)?!1:(t=t.slice(2).replace(/Once$/,""),Ie(e,t[0].toLowerCase()+t.slice(1))||Ie(e,cr(t))||Ie(e,t))}function bf(e){const{type:t,vnode:n,proxy:r,withProxy:s,propsOptions:[o],slots:i,attrs:a,emit:l,render:u,renderCache:c,props:d,data:p,setupState:g,ctx:y,inheritAttrs:_}=e,b=da(e);let m,v;try{if(n.shapeFlag&4){const S=s||r,P=S;m=Kt(u.call(P,S,c,d,g,p,y)),v=a}else{const S=t;m=Kt(S.length>1?S(d,{attrs:a,slots:i,emit:l}):S(d,null)),v=t.props?a:Sw(a)}}catch(S){yi.length=0,qa(S,e,1),m=Nt(_n)}let A=m;if(v&&_!==!1){const S=Object.keys(v),{shapeFlag:P}=A;S.length&&P&7&&(o&&S.some(Td)&&(v=ww(v,o)),A=Gr(A,v,!1,!0))}return n.dirs&&(A=Gr(A,null,!1,!0),A.dirs=A.dirs?A.dirs.concat(n.dirs):n.dirs),n.transition&&Ld(A,n.transition),m=A,da(b),m}const Sw=e=>{let t;for(const n in e)(n==="class"||n==="style"||Ma(n))&&((t||(t={}))[n]=e[n]);return t},ww=(e,t)=>{const n={};for(const r in e)(!Td(r)||!(r.slice(9)in t))&&(n[r]=e[r]);return n};function Ew(e,t,n){const{props:r,children:s,component:o}=e,{props:i,children:a,patchFlag:l}=t,u=o.emitsOptions;if(t.dirs||t.transition)return!0;if(n&&l>=0){if(l&1024)return!0;if(l&16)return r?Af(r,i,u):!!i;if(l&8){const c=t.dynamicProps;for(let d=0;d<c.length;d++){const p=c[d];if(Jv(i,r,p)&&!Ga(u,p))return!0}}}else return(s||a)&&(!a||!a.$stable)?!0:r===i?!1:r?i?Af(r,i,u):!0:!!i;return!1}function Af(e,t,n){const r=Object.keys(t);if(r.length!==Object.keys(e).length)return!0;for(let s=0;s<r.length;s++){const o=r[s];if(Jv(t,e,o)&&!Ga(n,o))return!0}return!1}function Jv(e,t,n){const r=e[n],s=t[n];return n==="style"&&Me(r)&&Me(s)?!Ni(r,s):r!==s}function Tw({vnode:e,parent:t},n){for(;t;){const r=t.subTree;if(r.suspense&&r.suspense.activeBranch===e&&(r.el=e.el),r===e)(e=t.vnode).el=n,t=t.parent;else break}}const jv={},Wv=()=>Object.create(jv),Kv=e=>Object.getPrototypeOf(e)===jv;function Pw(e,t,n,r=!1){const s={},o=Wv();e.propsDefaults=Object.create(null),$v(e,t,s,o);for(const i in e.propsOptions[0])i in s||(s[i]=void 0);n?e.props=r?s:FS(s):e.type.props?e.props=s:e.props=o,e.attrs=o}function Iw(e,t,n,r){const{props:s,attrs:o,vnode:{patchFlag:i}}=e,a=Pe(s),[l]=e.propsOptions;let u=!1;if((r||i>0)&&!(i&16)){if(i&8){const c=e.vnode.dynamicProps;for(let d=0;d<c.length;d++){let p=c[d];if(Ga(e.emitsOptions,p))continue;const g=t[p];if(l)if(Ie(o,p))g!==o[p]&&(o[p]=g,u=!0);else{const y=Fn(p);s[y]=ju(l,a,y,g,e,!1)}else g!==o[p]&&(o[p]=g,u=!0)}}}else{$v(e,t,s,o)&&(u=!0);let c;for(const d in a)(!t||!Ie(t,d)&&((c=cr(d))===d||!Ie(t,c)))&&(l?n&&(n[d]!==void 0||n[c]!==void 0)&&(s[d]=ju(l,a,d,void 0,e,!0)):delete s[d]);if(o!==a)for(const d in o)(!t||!Ie(t,d))&&(delete o[d],u=!0)}u&&dn(e.attrs,"set","")}function $v(e,t,n,r){const[s,o]=e.propsOptions;let i=!1,a;if(t)for(let l in t){if(fi(l))continue;const u=t[l];let c;s&&Ie(s,c=Fn(l))?!o||!o.includes(c)?n[c]=u:(a||(a={}))[c]=u:Ga(e.emitsOptions,l)||(!(l in r)||u!==r[l])&&(r[l]=u,i=!0)}if(o){const l=Pe(n),u=a||Ne;for(let c=0;c<o.length;c++){const d=o[c];n[d]=ju(s,l,d,u[d],e,!Ie(u,d))}}return i}function ju(e,t,n,r,s,o){const i=e[n];if(i!=null){const a=Ie(i,"default");if(a&&r===void 0){const l=i.default;if(i.type!==Function&&!i.skipFactory&&ye(l)){const{propsDefaults:u}=s;if(n in u)r=u[n];else{const c=Oi(s);r=u[n]=l.call(null,t),c()}}else r=l;s.ce&&s.ce._setProp(n,r)}i[0]&&(o&&!a?r=!1:i[1]&&(r===""||r===cr(n))&&(r=!0))}return r}const Cw=new WeakMap;function Yv(e,t,n=!1){const r=n?Cw:t.propsCache,s=r.get(e);if(s)return s;const o=e.props,i={},a=[];let l=!1;if(!ye(e)){const c=d=>{l=!0;const[p,g]=Yv(d,t,!0);Ye(i,p),g&&a.push(...g)};!n&&t.mixins.length&&t.mixins.forEach(c),e.extends&&c(e.extends),e.mixins&&e.mixins.forEach(c)}if(!o&&!l)return Me(e)&&r.set(e,Mr),Mr;if(he(o))for(let c=0;c<o.length;c++){const d=Fn(o[c]);Sf(d)&&(i[d]=Ne)}else if(o)for(const c in o){const d=Fn(c);if(Sf(d)){const p=o[c],g=i[d]=he(p)||ye(p)?{type:p}:Ye({},p),y=g.type;let _=!1,b=!0;if(he(y))for(let m=0;m<y.length;++m){const v=y[m],A=ye(v)&&v.name;if(A==="Boolean"){_=!0;break}else A==="String"&&(b=!1)}else _=ye(y)&&y.name==="Boolean";g[0]=_,g[1]=b,(_||Ie(g,"default"))&&a.push(d)}}const u=[i,a];return Me(e)&&r.set(e,u),u}function Sf(e){return e[0]!=="$"&&!fi(e)}const Ud=e=>e==="_"||e==="_ctx"||e==="$stable",Gd=e=>he(e)?e.map(Kt):[Kt(e)],Rw=(e,t,n)=>{if(t._n)return t;const r=JS((...s)=>Gd(t(...s)),n);return r._c=!1,r},zv=(e,t,n)=>{const r=e._ctx;for(const s in e){if(Ud(s))continue;const o=e[s];if(ye(o))t[s]=Rw(s,o,r);else if(o!=null){const i=Gd(o);t[s]=()=>i}}},Xv=(e,t)=>{const n=Gd(t);e.slots.default=()=>n},Qv=(e,t,n)=>{for(const r in t)(n||!Ud(r))&&(e[r]=t[r])},Mw=(e,t,n)=>{const r=e.slots=Wv();if(e.vnode.shapeFlag&32){const s=t._;s?(Qv(r,t,n),n&&cv(r,"_",s,!0)):zv(t,r)}else t&&Xv(e,t)},Nw=(e,t,n)=>{const{vnode:r,slots:s}=e;let o=!0,i=Ne;if(r.shapeFlag&32){const a=t._;a?n&&a===1?o=!1:Qv(s,t,n):(o=!t.$stable,zv(t,s)),i=t}else t&&(Xv(e,t),i={default:1});if(o)for(const a in s)!Ud(a)&&i[a]==null&&delete s[a]},lt=Dw;function Fw(e){return kw(e)}function kw(e,t){const n=Oa();n.__VUE__=!0;const{insert:r,remove:s,patchProp:o,createElement:i,createText:a,createComment:l,setText:u,setElementText:c,parentNode:d,nextSibling:p,setScopeId:g=$t,insertStaticContent:y}=e,_=(C,D,$,x=null,N=null,q=null,J=void 0,K=null,Q=!!D.dynamicChildren)=>{if(C===D)return;C&&!$r(C,D)&&(x=re(C),W(C,N,q,!0),C=null),D.patchFlag===-2&&(Q=!1,D.dynamicChildren=null);const{type:z,ref:ae,shapeFlag:te}=D;switch(z){case Va:b(C,D,$,x);break;case _n:m(C,D,$,x);break;case dl:C==null&&v(D,$,x,J);break;case He:F(C,D,$,x,N,q,J,K,Q);break;default:te&1?P(C,D,$,x,N,q,J,K,Q):te&6?j(C,D,$,x,N,q,J,K,Q):(te&64||te&128)&&z.process(C,D,$,x,N,q,J,K,Q,we)}ae!=null&&N?gi(ae,C&&C.ref,q,D||C,!D):ae==null&&C&&C.ref!=null&&gi(C.ref,null,q,C,!0)},b=(C,D,$,x)=>{if(C==null)r(D.el=a(D.children),$,x);else{const N=D.el=C.el;D.children!==C.children&&u(N,D.children)}},m=(C,D,$,x)=>{C==null?r(D.el=l(D.children||""),$,x):D.el=C.el},v=(C,D,$,x)=>{[C.el,C.anchor]=y(C.children,D,$,x,C.el,C.anchor)},A=({el:C,anchor:D},$,x)=>{let N;for(;C&&C!==D;)N=p(C),r(C,$,x),C=N;r(D,$,x)},S=({el:C,anchor:D})=>{let $;for(;C&&C!==D;)$=p(C),s(C),C=$;s(D)},P=(C,D,$,x,N,q,J,K,Q)=>{if(D.type==="svg"?J="svg":D.type==="math"&&(J="mathml"),C==null)E(D,$,x,N,q,J,K,Q);else{const z=C.el&&C.el._isVueCE?C.el:null;try{z&&z._beginPatch(),L(C,D,N,q,J,K,Q)}finally{z&&z._endPatch()}}},E=(C,D,$,x,N,q,J,K)=>{let Q,z;const{props:ae,shapeFlag:te,transition:se,dirs:de}=C;if(Q=C.el=i(C.type,q,ae&&ae.is,ae),te&8?c(Q,C.children):te&16&&I(C.children,Q,null,x,N,cl(C,q),J,K),de&&qn(C,null,x,"created"),w(Q,C,C.scopeId,J,x),ae){for(const ge in ae)ge!=="value"&&!fi(ge)&&o(Q,ge,null,ae[ge],q,x);"value"in ae&&o(Q,"value",null,ae.value,q),(z=ae.onVnodeBeforeMount)&&Ht(z,x,C)}de&&qn(C,null,x,"beforeMount");const _e=Ow(N,se);_e&&se.beforeEnter(Q),r(Q,D,$),((z=ae&&ae.onVnodeMounted)||_e||de)&&lt(()=>{z&&Ht(z,x,C),_e&&se.enter(Q),de&&qn(C,null,x,"mounted")},N)},w=(C,D,$,x,N)=>{if($&&g(C,$),x)for(let q=0;q<x.length;q++)g(C,x[q]);if(N){let q=N.subTree;if(D===q||nb(q.type)&&(q.ssContent===D||q.ssFallback===D)){const J=N.vnode;w(C,J,J.scopeId,J.slotScopeIds,N.parent)}}},I=(C,D,$,x,N,q,J,K,Q=0)=>{for(let z=Q;z<C.length;z++){const ae=C[z]=K?cn(C[z]):Kt(C[z]);_(null,ae,D,$,x,N,q,J,K)}},L=(C,D,$,x,N,q,J)=>{const K=D.el=C.el;let{patchFlag:Q,dynamicChildren:z,dirs:ae}=D;Q|=C.patchFlag&16;const te=C.props||Ne,se=D.props||Ne;let de;if($&&Ln($,!1),(de=se.onVnodeBeforeUpdate)&&Ht(de,$,D,C),ae&&qn(D,C,$,"beforeUpdate"),$&&Ln($,!0),(te.innerHTML&&se.innerHTML==null||te.textContent&&se.textContent==null)&&c(K,""),z?H(C.dynamicChildren,z,K,$,x,cl(D,N),q):J||M(C,D,K,null,$,x,cl(D,N),q,!1),Q>0){if(Q&16)B(K,te,se,$,N);else if(Q&2&&te.class!==se.class&&o(K,"class",null,se.class,N),Q&4&&o(K,"style",te.style,se.style,N),Q&8){const _e=D.dynamicProps;for(let ge=0;ge<_e.length;ge++){const pe=_e[ge],Le=te[pe],Ge=se[pe];(Ge!==Le||pe==="value")&&o(K,pe,Le,Ge,N,$)}}Q&1&&C.children!==D.children&&c(K,D.children)}else!J&&z==null&&B(K,te,se,$,N);((de=se.onVnodeUpdated)||ae)&&lt(()=>{de&&Ht(de,$,D,C),ae&&qn(D,C,$,"updated")},x)},H=(C,D,$,x,N,q,J)=>{for(let K=0;K<D.length;K++){const Q=C[K],z=D[K],ae=Q.el&&(Q.type===He||!$r(Q,z)||Q.shapeFlag&198)?d(Q.el):$;_(Q,z,ae,null,x,N,q,J,!0)}},B=(C,D,$,x,N)=>{if(D!==$){if(D!==Ne)for(const q in D)!fi(q)&&!(q in $)&&o(C,q,D[q],null,N,x);for(const q in $){if(fi(q))continue;const J=$[q],K=D[q];J!==K&&q!=="value"&&o(C,q,K,J,N,x)}"value"in $&&o(C,"value",D.value,$.value,N)}},F=(C,D,$,x,N,q,J,K,Q)=>{const z=D.el=C?C.el:a(""),ae=D.anchor=C?C.anchor:a("");let{patchFlag:te,dynamicChildren:se,slotScopeIds:de}=D;de&&(K=K?K.concat(de):de),C==null?(r(z,$,x),r(ae,$,x),I(D.children||[],$,ae,N,q,J,K,Q)):te>0&&te&64&&se&&C.dynamicChildren&&C.dynamicChildren.length===se.length?(H(C.dynamicChildren,se,$,N,q,J,K),(D.key!=null||N&&D===N.subTree)&&Zv(C,D,!0)):M(C,D,$,ae,N,q,J,K,Q)},j=(C,D,$,x,N,q,J,K,Q)=>{D.slotScopeIds=K,C==null?D.shapeFlag&512?N.ctx.activate(D,$,x,J,Q):U(D,$,x,N,q,J,Q):O(C,D,Q)},U=(C,D,$,x,N,q,J)=>{const K=C.component=Vw(C,x,N);if(qv(C)&&(K.ctx.renderer=we),Hw(K,!1,J),K.asyncDep){if(N&&N.registerDep(K,R,J),!C.el){const Q=K.subTree=Nt(_n);m(null,Q,D,$),C.placeholder=Q.el}}else R(K,C,D,$,N,q,J)},O=(C,D,$)=>{const x=D.component=C.component;if(Ew(C,D,$))if(x.asyncDep&&!x.asyncResolved){T(x,D,$);return}else x.next=D,x.update();else D.el=C.el,x.vnode=D},R=(C,D,$,x,N,q,J)=>{const K=()=>{if(C.isMounted){let{next:te,bu:se,u:de,parent:_e,vnode:ge}=C;{const vt=eb(C);if(vt){te&&(te.el=ge.el,T(C,te,J)),vt.asyncDep.then(()=>{lt(()=>{C.isUnmounted||z()},N)});return}}let pe=te,Le;Ln(C,!1),te?(te.el=ge.el,T(C,te,J)):te=ge,se&&ta(se),(Le=te.props&&te.props.onVnodeBeforeUpdate)&&Ht(Le,_e,te,ge),Ln(C,!0);const Ge=bf(C),je=C.subTree;C.subTree=Ge,_(je,Ge,d(je.el),re(je),C,N,q),te.el=Ge.el,pe===null&&Tw(C,Ge.el),de&&lt(de,N),(Le=te.props&&te.props.onVnodeUpdated)&&lt(()=>Ht(Le,_e,te,ge),N)}else{let te;const{el:se,props:de}=D,{bm:_e,m:ge,parent:pe,root:Le,type:Ge}=C,je=kr(D);Ln(C,!1),_e&&ta(_e),!je&&(te=de&&de.onVnodeBeforeMount)&&Ht(te,pe,D),Ln(C,!0);{Le.ce&&Le.ce._hasShadowRoot()&&Le.ce._injectChildStyle(Ge);const vt=C.subTree=bf(C);_(null,vt,$,x,C,N,q),D.el=vt.el}if(ge&&lt(ge,N),!je&&(te=de&&de.onVnodeMounted)){const vt=D;lt(()=>Ht(te,pe,vt),N)}(D.shapeFlag&256||pe&&kr(pe.vnode)&&pe.vnode.shapeFlag&256)&&C.a&&lt(C.a,N),C.isMounted=!0,D=$=x=null}};C.scope.on();const Q=C.effect=new hv(K);C.scope.off();const z=C.update=Q.run.bind(Q),ae=C.job=Q.runIfDirty.bind(Q);ae.i=C,ae.id=C.uid,Q.scheduler=()=>qd(ae),Ln(C,!0),z()},T=(C,D,$)=>{D.component=C;const x=C.vnode.props;C.vnode=D,C.next=null,Iw(C,D.props,x,$),Nw(C,D.children,$),hn(),pf(C),gn()},M=(C,D,$,x,N,q,J,K,Q=!1)=>{const z=C&&C.children,ae=C?C.shapeFlag:0,te=D.children,{patchFlag:se,shapeFlag:de}=D;if(se>0){if(se&128){G(z,te,$,x,N,q,J,K,Q);return}else if(se&256){k(z,te,$,x,N,q,J,K,Q);return}}de&8?(ae&16&&ne(z,N,q),te!==z&&c($,te)):ae&16?de&16?G(z,te,$,x,N,q,J,K,Q):ne(z,N,q,!0):(ae&8&&c($,""),de&16&&I(te,$,x,N,q,J,K,Q))},k=(C,D,$,x,N,q,J,K,Q)=>{C=C||Mr,D=D||Mr;const z=C.length,ae=D.length,te=Math.min(z,ae);let se;for(se=0;se<te;se++){const de=D[se]=Q?cn(D[se]):Kt(D[se]);_(C[se],de,$,null,N,q,J,K,Q)}z>ae?ne(C,N,q,!0,!1,te):I(D,$,x,N,q,J,K,Q,te)},G=(C,D,$,x,N,q,J,K,Q)=>{let z=0;const ae=D.length;let te=C.length-1,se=ae-1;for(;z<=te&&z<=se;){const de=C[z],_e=D[z]=Q?cn(D[z]):Kt(D[z]);if($r(de,_e))_(de,_e,$,null,N,q,J,K,Q);else break;z++}for(;z<=te&&z<=se;){const de=C[te],_e=D[se]=Q?cn(D[se]):Kt(D[se]);if($r(de,_e))_(de,_e,$,null,N,q,J,K,Q);else break;te--,se--}if(z>te){if(z<=se){const de=se+1,_e=de<ae?D[de].el:x;for(;z<=se;)_(null,D[z]=Q?cn(D[z]):Kt(D[z]),$,_e,N,q,J,K,Q),z++}}else if(z>se)for(;z<=te;)W(C[z],N,q,!0),z++;else{const de=z,_e=z,ge=new Map;for(z=_e;z<=se;z++){const ct=D[z]=Q?cn(D[z]):Kt(D[z]);ct.key!=null&&ge.set(ct.key,z)}let pe,Le=0;const Ge=se-_e+1;let je=!1,vt=0;const Vt=new Array(Ge);for(z=0;z<Ge;z++)Vt[z]=0;for(z=de;z<=te;z++){const ct=C[z];if(Le>=Ge){W(ct,N,q,!0);continue}let Bt;if(ct.key!=null)Bt=ge.get(ct.key);else for(pe=_e;pe<=se;pe++)if(Vt[pe-_e]===0&&$r(ct,D[pe])){Bt=pe;break}Bt===void 0?W(ct,N,q,!0):(Vt[Bt-_e]=z+1,Bt>=vt?vt=Bt:je=!0,_(ct,D[Bt],$,null,N,q,J,K,Q),Le++)}const sf=je?xw(Vt):Mr;for(pe=sf.length-1,z=Ge-1;z>=0;z--){const ct=_e+z,Bt=D[ct],of=D[ct+1],af=ct+1<ae?of.el||tb(of):x;Vt[z]===0?_(null,Bt,$,af,N,q,J,K,Q):je&&(pe<0||z!==sf[pe]?V(Bt,$,af,2):pe--)}}},V=(C,D,$,x,N=null)=>{const{el:q,type:J,transition:K,children:Q,shapeFlag:z}=C;if(z&6){V(C.component.subTree,D,$,x);return}if(z&128){C.suspense.move(D,$,x);return}if(z&64){J.move(C,D,$,we);return}if(J===He){r(q,D,$);for(let te=0;te<Q.length;te++)V(Q[te],D,$,x);r(C.anchor,D,$);return}if(J===dl){A(C,D,$);return}if(x!==2&&z&1&&K)if(x===0)K.beforeEnter(q),r(q,D,$),lt(()=>K.enter(q),N);else{const{leave:te,delayLeave:se,afterLeave:de}=K,_e=()=>{C.ctx.isUnmounted?s(q):r(q,D,$)},ge=()=>{q._isLeaving&&q[XS](!0),te(q,()=>{_e(),de&&de()})};se?se(q,_e,ge):ge()}else r(q,D,$)},W=(C,D,$,x=!1,N=!1)=>{const{type:q,props:J,ref:K,children:Q,dynamicChildren:z,shapeFlag:ae,patchFlag:te,dirs:se,cacheIndex:de}=C;if(te===-2&&(N=!1),K!=null&&(hn(),gi(K,null,$,C,!0),gn()),de!=null&&(D.renderCache[de]=void 0),ae&256){D.ctx.deactivate(C);return}const _e=ae&1&&se,ge=!kr(C);let pe;if(ge&&(pe=J&&J.onVnodeBeforeUnmount)&&Ht(pe,D,C),ae&6)Z(C.component,$,x);else{if(ae&128){C.suspense.unmount($,x);return}_e&&qn(C,null,D,"beforeUnmount"),ae&64?C.type.remove(C,D,$,we,x):z&&!z.hasOnce&&(q!==He||te>0&&te&64)?ne(z,D,$,!1,!0):(q===He&&te&384||!N&&ae&16)&&ne(Q,D,$),x&&X(C)}(ge&&(pe=J&&J.onVnodeUnmounted)||_e)&&lt(()=>{pe&&Ht(pe,D,C),_e&&qn(C,null,D,"unmounted")},$)},X=C=>{const{type:D,el:$,anchor:x,transition:N}=C;if(D===He){Y($,x);return}if(D===dl){S(C);return}const q=()=>{s($),N&&!N.persisted&&N.afterLeave&&N.afterLeave()};if(C.shapeFlag&1&&N&&!N.persisted){const{leave:J,delayLeave:K}=N,Q=()=>J($,q);K?K(C.el,q,Q):Q()}else q()},Y=(C,D)=>{let $;for(;C!==D;)$=p(C),s(C),C=$;s(D)},Z=(C,D,$)=>{const{bum:x,scope:N,job:q,subTree:J,um:K,m:Q,a:z}=C;wf(Q),wf(z),x&&ta(x),N.stop(),q&&(q.flags|=8,W(J,C,D,$)),K&&lt(K,D),lt(()=>{C.isUnmounted=!0},D)},ne=(C,D,$,x=!1,N=!1,q=0)=>{for(let J=q;J<C.length;J++)W(C[J],D,$,x,N)},re=C=>{if(C.shapeFlag&6)return re(C.component.subTree);if(C.shapeFlag&128)return C.suspense.next();const D=p(C.anchor||C.el),$=D&&D[YS];return $?p($):D};let Ae=!1;const le=(C,D,$)=>{let x;C==null?D._vnode&&(W(D._vnode,null,null,!0),x=D._vnode.component):_(D._vnode||null,C,D,null,null,null,$),D._vnode=C,Ae||(Ae=!0,pf(x),Nv(),Ae=!1)},we={p:_,um:W,m:V,r:X,mt:U,mc:I,pc:M,pbc:H,n:re,o:e};return{render:le,hydrate:void 0,createApp:yw(le)}}function cl({type:e,props:t},n){return n==="svg"&&e==="foreignObject"||n==="mathml"&&e==="annotation-xml"&&t&&t.encoding&&t.encoding.includes("html")?void 0:n}function Ln({effect:e,job:t},n){n?(e.flags|=32,t.flags|=4):(e.flags&=-33,t.flags&=-5)}function Ow(e,t){return(!e||e&&!e.pendingBranch)&&t&&!t.persisted}function Zv(e,t,n=!1){const r=e.children,s=t.children;if(he(r)&&he(s))for(let o=0;o<r.length;o++){const i=r[o];let a=s[o];a.shapeFlag&1&&!a.dynamicChildren&&((a.patchFlag<=0||a.patchFlag===32)&&(a=s[o]=cn(s[o]),a.el=i.el),!n&&a.patchFlag!==-2&&Zv(i,a)),a.type===Va&&(a.patchFlag===-1&&(a=s[o]=cn(a)),a.el=i.el),a.type===_n&&!a.el&&(a.el=i.el)}}function xw(e){const t=e.slice(),n=[0];let r,s,o,i,a;const l=e.length;for(r=0;r<l;r++){const u=e[r];if(u!==0){if(s=n[n.length-1],e[s]<u){t[r]=s,n.push(r);continue}for(o=0,i=n.length-1;o<i;)a=o+i>>1,e[n[a]]<u?o=a+1:i=a;u<e[n[o]]&&(o>0&&(t[r]=n[o-1]),n[o]=r)}}for(o=n.length,i=n[o-1];o-- >0;)n[o]=i,i=t[i];return n}function eb(e){const t=e.subTree.component;if(t)return t.asyncDep&&!t.asyncResolved?t:eb(t)}function wf(e){if(e)for(let t=0;t<e.length;t++)e[t].flags|=8}function tb(e){if(e.placeholder)return e.placeholder;const t=e.component;return t?tb(t.subTree):null}const nb=e=>e.__isSuspense;function Dw(e,t){t&&t.pendingBranch?he(e)?t.effects.push(...e):t.effects.push(e):HS(e)}const He=Symbol.for("v-fgt"),Va=Symbol.for("v-txt"),_n=Symbol.for("v-cmt"),dl=Symbol.for("v-stc"),yi=[];let ht=null;function ue(e=!1){yi.push(ht=e?null:[])}function qw(){yi.pop(),ht=yi[yi.length-1]||null}let Si=1;function Ef(e,t=!1){Si+=e,e<0&&ht&&t&&(ht.hasOnce=!0)}function rb(e){return e.dynamicChildren=Si>0?ht||Mr:null,qw(),Si>0&&ht&&ht.push(e),e}function fe(e,t,n,r,s,o){return rb(oe(e,t,n,r,s,o,!0))}function Ur(e,t,n,r,s){return rb(Nt(e,t,n,r,s,!0))}function Vd(e){return e?e.__v_isVNode===!0:!1}function $r(e,t){return e.type===t.type&&e.key===t.key}const sb=({key:e})=>e??null,ra=({ref:e,ref_key:t,ref_for:n})=>(typeof e=="number"&&(e=""+e),e!=null?qe(e)||Ze(e)||ye(e)?{i:Xe,r:e,k:t,f:!!n}:e:null);function oe(e,t=null,n=null,r=0,s=null,o=e===He?0:1,i=!1,a=!1){const l={__v_isVNode:!0,__v_skip:!0,type:e,props:t,key:t&&sb(t),ref:t&&ra(t),scopeId:kv,slotScopeIds:null,children:n,component:null,suspense:null,ssContent:null,ssFallback:null,dirs:null,transition:null,el:null,anchor:null,target:null,targetStart:null,targetAnchor:null,staticCount:0,shapeFlag:o,patchFlag:r,dynamicProps:s,dynamicChildren:null,appContext:null,ctx:Xe};return a?(Bd(l,n),o&128&&e.normalize(l)):n&&(l.shapeFlag|=qe(n)?8:16),Si>0&&!i&&ht&&(l.patchFlag>0||o&6)&&l.patchFlag!==32&&ht.push(l),l}const Nt=Lw;function Lw(e,t=null,n=null,r=0,s=null,o=!1){if((!e||e===uw)&&(e=_n),Vd(e)){const a=Gr(e,t,!0);return n&&Bd(a,n),Si>0&&!o&&ht&&(a.shapeFlag&6?ht[ht.indexOf(e)]=a:ht.push(a)),a.patchFlag=-2,a}if(Kw(e)&&(e=e.__vccOpts),t){t=ob(t);let{class:a,style:l}=t;a&&!qe(a)&&(t.class=Rt(a)),Me(l)&&(xd(l)&&!he(l)&&(l=Ye({},l)),t.style=xa(l))}const i=qe(e)?1:nb(e)?128:zS(e)?64:Me(e)?4:ye(e)?2:0;return oe(e,t,n,r,s,i,o,!0)}function ob(e){return e?xd(e)||Kv(e)?Ye({},e):e:null}function Gr(e,t,n=!1,r=!1){const{props:s,ref:o,patchFlag:i,children:a,transition:l}=e,u=t?Wu(s||{},t):s,c={__v_isVNode:!0,__v_skip:!0,type:e.type,props:u,key:u&&sb(u),ref:t&&t.ref?n&&o?he(o)?o.concat(ra(t)):[o,ra(t)]:ra(t):o,scopeId:e.scopeId,slotScopeIds:e.slotScopeIds,children:a,target:e.target,targetStart:e.targetStart,targetAnchor:e.targetAnchor,staticCount:e.staticCount,shapeFlag:e.shapeFlag,patchFlag:t&&e.type!==He?i===-1?16:i|16:i,dynamicProps:e.dynamicProps,dynamicChildren:e.dynamicChildren,appContext:e.appContext,dirs:e.dirs,transition:l,component:e.component,suspense:e.suspense,ssContent:e.ssContent&&Gr(e.ssContent),ssFallback:e.ssFallback&&Gr(e.ssFallback),placeholder:e.placeholder,el:e.el,anchor:e.anchor,ctx:e.ctx,ce:e.ce};return l&&r&&Ld(c,l.clone(c)),c}function Wt(e=" ",t=0){return Nt(Va,null,e,t)}function Be(e="",t=!1){return t?(ue(),Ur(_n,null,e)):Nt(_n,null,e)}function Kt(e){return e==null||typeof e=="boolean"?Nt(_n):he(e)?Nt(He,null,e.slice()):Vd(e)?cn(e):Nt(Va,null,String(e))}function cn(e){return e.el===null&&e.patchFlag!==-1||e.memo?e:Gr(e)}function Bd(e,t){let n=0;const{shapeFlag:r}=e;if(t==null)t=null;else if(he(t))n=16;else if(typeof t=="object")if(r&65){const s=t.default;s&&(s._c&&(s._d=!1),Bd(e,s()),s._c&&(s._d=!0));return}else{n=32;const s=t._;!s&&!Kv(t)?t._ctx=Xe:s===3&&Xe&&(Xe.slots._===1?t._=1:(t._=2,e.patchFlag|=1024))}else ye(t)?(t={default:t,_ctx:Xe},n=32):(t=String(t),r&64?(n=16,t=[Wt(t)]):n=8);e.children=t,e.shapeFlag|=n}function Wu(...e){const t={};for(let n=0;n<e.length;n++){const r=e[n];for(const s in r)if(s==="class")t.class!==r.class&&(t.class=Rt([t.class,r.class]));else if(s==="style")t.style=xa([t.style,r.style]);else if(Ma(s)){const o=t[s],i=r[s];i&&o!==i&&!(he(o)&&o.includes(i))&&(t[s]=o?[].concat(o,i):i)}else s!==""&&(t[s]=r[s])}return t}function Ht(e,t,n,r=null){Yt(e,t,7,[n,r])}const Uw=Bv();let Gw=0;function Vw(e,t,n){const r=e.type,s=(t?t.appContext:e.appContext)||Uw,o={uid:Gw++,vnode:e,type:r,parent:t,appContext:s,root:null,next:null,subTree:null,effect:null,update:null,job:null,scope:new fS(!0),render:null,proxy:null,exposed:null,exposeProxy:null,withProxy:null,provides:t?t.provides:Object.create(s.provides),ids:t?t.ids:["",0,0],accessCache:null,renderCache:[],components:null,directives:null,propsOptions:Yv(r,s),emitsOptions:Hv(r,s),emit:null,emitted:null,propsDefaults:Ne,inheritAttrs:r.inheritAttrs,ctx:Ne,data:Ne,props:Ne,attrs:Ne,slots:Ne,refs:Ne,setupState:Ne,setupContext:null,suspense:n,suspenseId:n?n.pendingId:0,asyncDep:null,asyncResolved:!1,isMounted:!1,isUnmounted:!1,isDeactivated:!1,bc:null,c:null,bm:null,m:null,bu:null,u:null,um:null,bum:null,da:null,a:null,rtg:null,rtc:null,ec:null,sp:null};return o.ctx={_:o},o.root=t?t.root:o,o.emit=bw.bind(null,o),e.ce&&e.ce(o),o}let st=null;const Bw=()=>st||Xe;let ga,Ku;{const e=Oa(),t=(n,r)=>{let s;return(s=e[n])||(s=e[n]=[]),s.push(r),o=>{s.length>1?s.forEach(i=>i(o)):s[0](o)}};ga=t("__VUE_INSTANCE_SETTERS__",n=>st=n),Ku=t("__VUE_SSR_SETTERS__",n=>wi=n)}const Oi=e=>{const t=st;return ga(e),e.scope.on(),()=>{e.scope.off(),ga(t)}},Tf=()=>{st&&st.scope.off(),ga(null)};function ib(e){return e.vnode.shapeFlag&4}let wi=!1;function Hw(e,t=!1,n=!1){t&&Ku(t);const{props:r,children:s}=e.vnode,o=ib(e);Pw(e,r,o,t),Mw(e,s,n||t);const i=o?Jw(e,t):void 0;return t&&Ku(!1),i}function Jw(e,t){const n=e.type;e.accessCache=Object.create(null),e.proxy=new Proxy(e.ctx,dw);const{setup:r}=n;if(r){hn();const s=e.setupContext=r.length>1?Ww(e):null,o=Oi(e),i=Fi(r,e,0,[e.props,s]),a=iv(i);if(gn(),o(),(a||e.sp)&&!kr(e)&&Dv(e),a){if(i.then(Tf,Tf),t)return i.then(l=>{Pf(e,l)}).catch(l=>{qa(l,e,0)});e.asyncDep=i}else Pf(e,i)}else ab(e)}function Pf(e,t,n){ye(t)?e.type.__ssrInlineRender?e.ssrRender=t:e.render=t:Me(t)&&(e.setupState=Cv(t)),ab(e)}function ab(e,t,n){const r=e.type;e.render||(e.render=r.render||$t);{const s=Oi(e);hn();try{fw(e)}finally{gn(),s()}}}const jw={get(e,t){return ze(e,"get",""),e[t]}};function Ww(e){const t=n=>{e.exposed=n||{}};return{attrs:new Proxy(e.attrs,jw),slots:e.slots,emit:e.emit,expose:t}}function Ba(e){return e.exposed?e.exposeProxy||(e.exposeProxy=new Proxy(Cv(kS(e.exposed)),{get(t,n){if(n in t)return t[n];if(n in _i)return _i[n](e)},has(t,n){return n in t||n in _i}})):e.proxy}function Kw(e){return ye(e)&&"__vccOpts"in e}const xe=(e,t)=>LS(e,t,wi),$w="3.5.28";let $u;const If=typeof window<"u"&&window.trustedTypes;if(If)try{$u=If.createPolicy("vue",{createHTML:e=>e})}catch{}const lb=$u?e=>$u.createHTML(e):e=>e,Yw="http://www.w3.org/2000/svg",zw="http://www.w3.org/1998/Math/MathML",un=typeof document<"u"?document:null,Cf=un&&un.createElement("template"),Xw={insert:(e,t,n)=>{t.insertBefore(e,n||null)},remove:e=>{const t=e.parentNode;t&&t.removeChild(e)},createElement:(e,t,n,r)=>{const s=t==="svg"?un.createElementNS(Yw,e):t==="mathml"?un.createElementNS(zw,e):n?un.createElement(e,{is:n}):un.createElement(e);return e==="select"&&r&&r.multiple!=null&&s.setAttribute("multiple",r.multiple),s},createText:e=>un.createTextNode(e),createComment:e=>un.createComment(e),setText:(e,t)=>{e.nodeValue=t},setElementText:(e,t)=>{e.textContent=t},parentNode:e=>e.parentNode,nextSibling:e=>e.nextSibling,querySelector:e=>un.querySelector(e),setScopeId(e,t){e.setAttribute(t,"")},insertStaticContent(e,t,n,r,s,o){const i=n?n.previousSibling:t.lastChild;if(s&&(s===o||s.nextSibling))for(;t.insertBefore(s.cloneNode(!0),n),!(s===o||!(s=s.nextSibling)););else{Cf.innerHTML=lb(r==="svg"?`<svg>${e}</svg>`:r==="mathml"?`<math>${e}</math>`:e);const a=Cf.content;if(r==="svg"||r==="mathml"){const l=a.firstChild;for(;l.firstChild;)a.appendChild(l.firstChild);a.removeChild(l)}t.insertBefore(a,n)}return[i?i.nextSibling:t.firstChild,n?n.previousSibling:t.lastChild]}},Qw=Symbol("_vtc");function Zw(e,t,n){const r=e[Qw];r&&(t=(t?[t,...r]:[...r]).join(" ")),t==null?e.removeAttribute("class"):n?e.setAttribute("class",t):e.className=t}const ma=Symbol("_vod"),ub=Symbol("_vsh"),cb={name:"show",beforeMount(e,{value:t},{transition:n}){e[ma]=e.style.display==="none"?"":e.style.display,n&&t?n.beforeEnter(e):Yr(e,t)},mounted(e,{value:t},{transition:n}){n&&t&&n.enter(e)},updated(e,{value:t,oldValue:n},{transition:r}){!t!=!n&&(r?t?(r.beforeEnter(e),Yr(e,!0),r.enter(e)):r.leave(e,()=>{Yr(e,!1)}):Yr(e,t))},beforeUnmount(e,{value:t}){Yr(e,t)}};function Yr(e,t){e.style.display=t?e[ma]:"none",e[ub]=!t}const eE=Symbol(""),tE=/(?:^|;)\s*display\s*:/;function nE(e,t,n){const r=e.style,s=qe(n);let o=!1;if(n&&!s){if(t)if(qe(t))for(const i of t.split(";")){const a=i.slice(0,i.indexOf(":")).trim();n[a]==null&&sa(r,a,"")}else for(const i in t)n[i]==null&&sa(r,i,"");for(const i in n)i==="display"&&(o=!0),sa(r,i,n[i])}else if(s){if(t!==n){const i=r[eE];i&&(n+=";"+i),r.cssText=n,o=tE.test(n)}}else t&&e.removeAttribute("style");ma in e&&(e[ma]=o?r.display:"",e[ub]&&(r.display="none"))}const Rf=/\s*!important$/;function sa(e,t,n){if(he(n))n.forEach(r=>sa(e,t,r));else if(n==null&&(n=""),t.startsWith("--"))e.setProperty(t,n);else{const r=rE(e,t);Rf.test(n)?e.setProperty(cr(r),n.replace(Rf,""),"important"):e[r]=n}}const Mf=["Webkit","Moz","ms"],fl={};function rE(e,t){const n=fl[t];if(n)return n;let r=Fn(t);if(r!=="filter"&&r in e)return fl[t]=r;r=uv(r);for(let s=0;s<Mf.length;s++){const o=Mf[s]+r;if(o in e)return fl[t]=o}return t}const Nf="http://www.w3.org/1999/xlink";function Ff(e,t,n,r,s,o=uS(t)){r&&t.startsWith("xlink:")?n==null?e.removeAttributeNS(Nf,t.slice(6,t.length)):e.setAttributeNS(Nf,t,n):n==null||o&&!dv(n)?e.removeAttribute(t):e.setAttribute(t,o?"":Ot(n)?String(n):n)}function kf(e,t,n,r,s){if(t==="innerHTML"||t==="textContent"){n!=null&&(e[t]=t==="innerHTML"?lb(n):n);return}const o=e.tagName;if(t==="value"&&o!=="PROGRESS"&&!o.includes("-")){const a=o==="OPTION"?e.getAttribute("value")||"":e.value,l=n==null?e.type==="checkbox"?"on":"":String(n);(a!==l||!("_value"in e))&&(e.value=l),n==null&&e.removeAttribute(t),e._value=n;return}let i=!1;if(n===""||n==null){const a=typeof e[t];a==="boolean"?n=dv(n):n==null&&a==="string"?(n="",i=!0):a==="number"&&(n=0,i=!0)}try{e[t]=n}catch{}i&&e.removeAttribute(s||t)}function ir(e,t,n,r){e.addEventListener(t,n,r)}function sE(e,t,n,r){e.removeEventListener(t,n,r)}const Of=Symbol("_vei");function oE(e,t,n,r,s=null){const o=e[Of]||(e[Of]={}),i=o[t];if(r&&i)i.value=r;else{const[a,l]=iE(t);if(r){const u=o[t]=uE(r,s);ir(e,a,u,l)}else i&&(sE(e,a,i,l),o[t]=void 0)}}const xf=/(?:Once|Passive|Capture)$/;function iE(e){let t;if(xf.test(e)){t={};let r;for(;r=e.match(xf);)e=e.slice(0,e.length-r[0].length),t[r[0].toLowerCase()]=!0}return[e[2]===":"?e.slice(3):cr(e.slice(2)),t]}let pl=0;const aE=Promise.resolve(),lE=()=>pl||(aE.then(()=>pl=0),pl=Date.now());function uE(e,t){const n=r=>{if(!r._vts)r._vts=Date.now();else if(r._vts<=n.attached)return;Yt(cE(r,n.value),t,5,[r])};return n.value=e,n.attached=lE(),n}function cE(e,t){if(he(t)){const n=e.stopImmediatePropagation;return e.stopImmediatePropagation=()=>{n.call(e),e._stopped=!0},t.map(r=>s=>!s._stopped&&r&&r(s))}else return t}const Df=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&e.charCodeAt(2)>96&&e.charCodeAt(2)<123,dE=(e,t,n,r,s,o)=>{const i=s==="svg";t==="class"?Zw(e,r,i):t==="style"?nE(e,n,r):Ma(t)?Td(t)||oE(e,t,n,r,o):(t[0]==="."?(t=t.slice(1),!0):t[0]==="^"?(t=t.slice(1),!1):fE(e,t,r,i))?(kf(e,t,r),!e.tagName.includes("-")&&(t==="value"||t==="checked"||t==="selected")&&Ff(e,t,r,i,o,t!=="value")):e._isVueCE&&(/[A-Z]/.test(t)||!qe(r))?kf(e,Fn(t),r,o,t):(t==="true-value"?e._trueValue=r:t==="false-value"&&(e._falseValue=r),Ff(e,t,r,i))};function fE(e,t,n,r){if(r)return!!(t==="innerHTML"||t==="textContent"||t in e&&Df(t)&&ye(n));if(t==="spellcheck"||t==="draggable"||t==="translate"||t==="autocorrect"||t==="sandbox"&&e.tagName==="IFRAME"||t==="form"||t==="list"&&e.tagName==="INPUT"||t==="type"&&e.tagName==="TEXTAREA")return!1;if(t==="width"||t==="height"){const s=e.tagName;if(s==="IMG"||s==="VIDEO"||s==="CANVAS"||s==="SOURCE")return!1}return Df(t)&&qe(n)?!1:t in e}const _a=e=>{const t=e.props["onUpdate:modelValue"]||!1;return he(t)?n=>ta(t,n):t};function pE(e){e.target.composing=!0}function qf(e){const t=e.target;t.composing&&(t.composing=!1,t.dispatchEvent(new Event("input")))}const xr=Symbol("_assign");function Lf(e,t,n){return t&&(e=e.trim()),n&&(e=ka(e)),e}const db={created(e,{modifiers:{lazy:t,trim:n,number:r}},s){e[xr]=_a(s);const o=r||s.props&&s.props.type==="number";ir(e,t?"change":"input",i=>{i.target.composing||e[xr](Lf(e.value,n,o))}),(n||o)&&ir(e,"change",()=>{e.value=Lf(e.value,n,o)}),t||(ir(e,"compositionstart",pE),ir(e,"compositionend",qf),ir(e,"change",qf))},mounted(e,{value:t}){e.value=t??""},beforeUpdate(e,{value:t,oldValue:n,modifiers:{lazy:r,trim:s,number:o}},i){if(e[xr]=_a(i),e.composing)return;const a=(o||e.type==="number")&&!/^0\d/.test(e.value)?ka(e.value):e.value,l=t??"";a!==l&&(document.activeElement===e&&e.type!=="range"&&(r&&t===n||s&&e.value.trim()===l)||(e.value=l))}},Uf={deep:!0,created(e,{value:t,modifiers:{number:n}},r){const s=Na(t);ir(e,"change",()=>{const o=Array.prototype.filter.call(e.options,i=>i.selected).map(i=>n?ka(ya(i)):ya(i));e[xr](e.multiple?s?new Set(o):o:o[0]),e._assigning=!0,ca(()=>{e._assigning=!1})}),e[xr]=_a(r)},mounted(e,{value:t}){Gf(e,t)},beforeUpdate(e,t,n){e[xr]=_a(n)},updated(e,{value:t}){e._assigning||Gf(e,t)}};function Gf(e,t){const n=e.multiple,r=he(t);if(!(n&&!r&&!Na(t))){for(let s=0,o=e.options.length;s<o;s++){const i=e.options[s],a=ya(i);if(n)if(r){const l=typeof a;l==="string"||l==="number"?i.selected=t.some(u=>String(u)===String(a)):i.selected=dS(t,a)>-1}else i.selected=t.has(a);else if(Ni(ya(i),t)){e.selectedIndex!==s&&(e.selectedIndex=s);return}}!n&&e.selectedIndex!==-1&&(e.selectedIndex=-1)}}function ya(e){return"_value"in e?e._value:e.value}const hE=Ye({patchProp:dE},Xw);let Vf;function gE(){return Vf||(Vf=Fw(hE))}const mE=((...e)=>{const t=gE().createApp(...e),{mount:n}=t;return t.mount=r=>{const s=yE(r);if(!s)return;const o=t._component;!ye(o)&&!o.render&&!o.template&&(o.template=s.innerHTML),s.nodeType===1&&(s.textContent="");const i=n(s,!1,_E(s));return s instanceof Element&&(s.removeAttribute("v-cloak"),s.setAttribute("data-v-app","")),i},t});function _E(e){if(e instanceof SVGElement)return"svg";if(typeof MathMLElement=="function"&&e instanceof MathMLElement)return"mathml"}function yE(e){return qe(e)?document.querySelector(e):e}const hl=async e=>await new Promise(t=>setTimeout(t,e)),vE=(e,t)=>{const n=r=>r instanceof Error?r:new Error("Aborted");return new Promise((r,s)=>{if(t.aborted){s(n(t.reason));return}const o=()=>{clearTimeout(i),s(n(t.reason))},i=setTimeout(()=>{t.removeEventListener("abort",o),r()},e);t.addEventListener("abort",o,{once:!0})})},bE={class:"items-center justify-center w-full"},AE={key:0,class:"group relative"},SE=["src"],wE={class:"play-overlay absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity duration-200 pointer-events-none"},EE={key:0,class:"w-8 h-8 text-white ml-1",fill:"currentColor",viewBox:"0 0 24 24"},TE={key:1,class:"w-8 h-8 text-white",fill:"currentColor",viewBox:"0 0 24 24"},PE={key:1,class:"group relative inline-block"},IE=["src","controls"],CE=["src"],RE={class:"play-overlay absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity duration-200 pointer-events-none"},ME={key:0,class:"w-8 h-8 text-white ml-1",fill:"currentColor",viewBox:"0 0 24 24"},NE={key:1,class:"w-8 h-8 text-white",fill:"currentColor",viewBox:"0 0 24 24"},FE={key:2,class:"group relative inline-block"},kE=["src"],OE=["src"],xE={class:"play-overlay absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity duration-200 pointer-events-none"},DE={key:0,class:"w-8 h-8 text-white ml-1",fill:"currentColor",viewBox:"0 0 24 24"},qE={key:1,class:"w-8 h-8 text-white",fill:"currentColor",viewBox:"0 0 24 24"},LE={key:3,class:"group relative inline-block"},UE=["src"],GE={class:"play-overlay absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity duration-200 pointer-events-none"},VE={key:0,class:"w-8 h-8 text-white ml-1",fill:"currentColor",viewBox:"0 0 24 24"},BE={key:1,class:"w-8 h-8 text-white",fill:"currentColor",viewBox:"0 0 24 24"},HE={key:4},JE={key:5,class:"mt-4 px-6 py-4 text-left"},jE={class:"text-lg leading-relaxed font-sans text-gray-800"},WE={key:0,class:"text-base leading-relaxed font-sans text-gray-400 mt-3 italic"},KE="https://github.com/receptron/mulmocast-cli/blob/main/assets/images/mulmocast_credit.png?raw=true",$E=ki({__name:"mulmo_player",props:{index:{},videoWithAudioSource:{default:void 0},soundEffectSource:{default:void 0},videoSource:{default:void 0},imageSource:{default:void 0},audioSource:{default:void 0},text:{default:void 0},originalText:{default:void 0},duration:{default:void 0},defaultLang:{default:void 0},currentLang:{default:void 0},playbackSpeed:{default:1}},emits:["play","pause","ended"],setup(e,{expose:t,emit:n}){const r=e,s=n,o=be(),i=be(),a=be(),l=be(),u=be(!1),c=()=>{i.value&&a.value&&!isNaN(i.value.duration)&&!isNaN(a.value.duration)&&(u.value=a.value.duration>i.value.duration+1)},d=()=>{if(i.value){if(r.soundEffectSource){i.value.volume=1;return}r.videoSource&&(r.audioSource&&r.currentLang&&r.defaultLang&&r.currentLang!==r.defaultLang?i.value.volume=.2:i.value.volume=0)}},p=()=>{const X=r.playbackSpeed??1;o.value&&(o.value.playbackRate=X),i.value&&(i.value.playbackRate=X),a.value&&(a.value.playbackRate=X),l.value&&(l.value.playbackRate=X)};pt([()=>r.currentLang,()=>r.defaultLang,()=>r.videoSource,()=>r.audioSource],()=>{d()}),pt(()=>r.playbackSpeed,()=>{p()}),pt(i,X=>{X&&(d(),p())}),pt([o,a,l],()=>{p()}),pa(()=>{d(),p()});const g=be(!1),y=be(!1),_=xe(()=>j.value||y.value);let b=null;const m=()=>{b&&(b.abort(),b=null)},v=()=>{j.value=!0,a.value&&i.value&&!a.value.ended&&(a.value.currentTime=i.value.currentTime,a.value.play().catch(()=>{})),s("play")},A=X=>{y.value||i.value?.ended&&a.value&&!a.value.ended||(document.hidden||(j.value=!1),!i.value?.ended&&a?.value&&a.value?.pause(),H(X))},S=()=>{g.value||(!a.value||a.value.ended)&&B()},P=()=>{g.value||(!i.value||i.value.ended)&&B()},E=()=>{if(!i.value||!a.value)return;const X=Math.min(a.value.currentTime,i.value.duration);Math.abs(i.value.currentTime-X)>.5&&(i.value.currentTime=X)},w=()=>{j.value=!0,i.value&&!i.value.ended&&i.value.play().catch(()=>{}),s("play")},I=()=>{y.value||a.value?.ended||(document.hidden||(j.value=!1),i.value&&!i.value.ended&&i.value.pause(),s("pause"))},L=()=>{j.value=!0,s("play")},H=X=>{if(y.value)return;document.hidden||(j.value=!1);const Y=X.target;Y.duration!==Y.currentTime&&s("pause")},B=()=>{g.value||(g.value=!0,j.value=!1,s("ended"))},F=()=>{o.value?.pause(),i.value?.pause(),a.value?.pause(),l.value?.pause()},j=be(!1);let U=null;const O=async()=>{if(y.value=!1,g.value=!1,j.value=!0,o.value&&(p(),o.value.play().catch(()=>{})),i.value&&(d(),p(),i.value.play().catch(()=>{}),a.value&&(a.value.currentTime=i.value.currentTime,a.value.play().catch(()=>{}))),l.value&&(p(),l.value.play().catch(()=>{})),!o.value&&!i.value&&!l.value)try{m(),b=new AbortController,await vE((r.duration??0)*1e3,b.signal),b=null,g.value||(j.value=!1,g.value=!0,s("ended"))}catch{}},R=()=>{y.value=!0,j.value=!1,g.value=!0,m(),o.value?.pause(),i.value?.pause(),a.value?.pause(),l.value?.pause()},T=()=>{!a.value||!i.value||a.value.ended||Math.abs(a.value.currentTime-i.value.currentTime)>.5&&(a.value.currentTime=i.value.currentTime)},M=X=>{X?.paused&&!X.ended&&X.play().catch(()=>{})},k=(X,Y)=>{Y.paused&&!Y.ended&&(X.ended||(Y.currentTime=X.currentTime),Y.play().catch(()=>{}))},G=()=>{j.value&&(M(o.value),i.value&&a.value?(M(i.value),k(i.value,a.value)):M(i.value),M(l.value))},V=()=>{document.hidden&&j.value?U||(U=setInterval(G,500)):document.hidden||U&&(clearInterval(U),U=null)},W=()=>{document.hidden&&j.value&&setTimeout(G,50)};return pa(()=>{document.addEventListener("visibilitychange",V),o.value?.addEventListener("pause",W),i.value?.addEventListener("pause",W),l.value?.addEventListener("pause",W),a.value?.addEventListener("pause",W)}),Ua(()=>{document.removeEventListener("visibilitychange",V),o.value?.removeEventListener("pause",W),i.value?.removeEventListener("pause",W),l.value?.removeEventListener("pause",W),a.value?.removeEventListener("pause",W),U&&(clearInterval(U),U=null),m()}),t({play:O,stop:R}),(X,Y)=>(ue(),fe("div",bE,[e.videoWithAudioSource?(ue(),fe("div",AE,[oe("video",{ref_key:"videoWithAudioRef",ref:o,src:e.videoWithAudioSource,class:"mulmocast-video mx-auto h-auto max-h-[80vh] w-auto object-contain",controls:!0,playsinline:"true",onPlay:L,onPause:H,onEnded:B},null,40,SE),oe("div",wE,[oe("button",{class:"pointer-events-auto w-16 h-16 bg-black/50 hover:bg-black/70 rounded-full flex items-center justify-center transition-colors cursor-pointer",onClick:Y[0]||(Y[0]=Z=>_.value?F():O())},[_.value?(ue(),fe("svg",TE,[...Y[5]||(Y[5]=[oe("path",{d:"M6 19h4V5H6v14zm8-14v14h4V5h-4z"},null,-1)])])):(ue(),fe("svg",EE,[...Y[4]||(Y[4]=[oe("path",{d:"M8 5v14l11-7z"},null,-1)])]))])])])):e.soundEffectSource||e.videoSource?(ue(),fe("div",PE,[oe("video",{ref_key:"videoRef",ref:i,class:"mulmocast-video mx-auto h-auto max-h-[80vh] w-auto object-contain",src:e.soundEffectSource||e.videoSource,controls:!u.value,playsinline:"true",onPlay:v,onPause:A,onEnded:S,onSeeked:T,onLoadedmetadata:c},null,40,IE),e.audioSource?(ue(),fe("audio",{key:0,ref_key:"audioSyncRef",ref:a,src:e.audioSource,controls:!0,class:Rt(u.value?"mulmocast-audio absolute bottom-0 left-0 w-full":"hidden"),onEnded:P,onSeeked:E,onPlay:w,onPause:I,onLoadedmetadata:c},null,42,CE)):Be("",!0),oe("div",RE,[oe("button",{class:"pointer-events-auto w-16 h-16 bg-black/50 hover:bg-black/70 rounded-full flex items-center justify-center transition-colors cursor-pointer",onClick:Y[1]||(Y[1]=Z=>_.value?F():O())},[_.value?(ue(),fe("svg",NE,[...Y[7]||(Y[7]=[oe("path",{d:"M6 19h4V5H6v14zm8-14v14h4V5h-4z"},null,-1)])])):(ue(),fe("svg",ME,[...Y[6]||(Y[6]=[oe("path",{d:"M8 5v14l11-7z"},null,-1)])]))])])])):e.audioSource?(ue(),fe("div",FE,[e.imageSource?(ue(),fe("img",{key:0,src:e.imageSource,class:"mx-auto h-auto max-h-[80vh] w-auto object-contain",alt:"Background"},null,8,kE)):(ue(),fe("img",{key:1,src:KE,class:"mx-auto h-auto max-h-[80vh] w-auto object-contain",alt:"Background"})),oe("audio",{ref_key:"audioRef",ref:l,class:"mulmocast-audio absolute inset-0 w-full h-full",src:e.audioSource,controls:!0,onPlay:L,onPause:H,onEnded:B},null,40,OE),oe("div",xE,[oe("button",{class:"pointer-events-auto w-16 h-16 bg-black/50 hover:bg-black/70 rounded-full flex items-center justify-center transition-colors cursor-pointer",onClick:Y[2]||(Y[2]=Z=>_.value?F():O())},[_.value?(ue(),fe("svg",qE,[...Y[9]||(Y[9]=[oe("path",{d:"M6 19h4V5H6v14zm8-14v14h4V5h-4z"},null,-1)])])):(ue(),fe("svg",DE,[...Y[8]||(Y[8]=[oe("path",{d:"M8 5v14l11-7z"},null,-1)])]))])])])):e.imageSource?(ue(),fe("div",LE,[oe("img",{src:e.imageSource,class:"max-w-full max-h-full object-contain"},null,8,UE),oe("div",GE,[oe("button",{class:"pointer-events-auto w-16 h-16 bg-black/50 hover:bg-black/70 rounded-full flex items-center justify-center transition-colors cursor-pointer",onClick:Y[3]||(Y[3]=Z=>_.value?F():O())},[_.value?(ue(),fe("svg",BE,[...Y[11]||(Y[11]=[oe("path",{d:"M6 19h4V5H6v14zm8-14v14h4V5h-4z"},null,-1)])])):(ue(),fe("svg",VE,[...Y[10]||(Y[10]=[oe("path",{d:"M8 5v14l11-7z"},null,-1)])]))])])])):(ue(),fe("div",HE,"No media available")),e.text?(ue(),fe("div",JE,[oe("p",jE,Ue(e.text),1),e.originalText&&e.originalText!==e.text?(ue(),fe("p",WE,Ue(e.originalText),1)):Be("",!0)])):Be("",!0)]))}}),fb=(e,t)=>{const n=e.__vccOpts||e;for(const[r,s]of t)n[r]=s;return n},gl=fb($E,[["__scopeId","data-v-843621f0"]]),YE=["value"],zE=["value"],XE=ki({__name:"select_language",props:{modelValue:{}},emits:["update:modelValue"],setup(e,{emit:t}){const n=["en","ja"],r={en:"English",ja:"日本語"},s=t,o=i=>{const a=i.target;s("update:modelValue",a.value)};return(i,a)=>(ue(),fe("select",{value:e.modelValue,class:"px-4 py-2 bg-white border-2 border-gray-300 rounded-lg shadow-sm hover:border-indigo-400 focus:border-indigo-500 focus:ring-2 focus:ring-indigo-200 focus:outline-none transition-colors cursor-pointer text-base font-medium text-gray-700",onChange:o},[(ue(),fe(He,null,mi(n,l=>oe("option",{key:l,value:l},Ue(r[l]||l),9,zE)),64))],40,YE))}}),QE={class:"w-full overflow-hidden"},ZE={class:"max-w-7xl mx-auto px-4"},eT={class:"grid grid-cols-[auto,1fr,auto] gap-x-4 gap-y-4 max-sm:grid-cols-2"},tT=["disabled"],nT={class:"col-start-2 row-start-1 min-w-0 max-sm:col-span-2 max-sm:col-start-1"},rT=["disabled"],sT={key:0,class:"mulmo-text-box col-start-2 row-start-2 min-w-0 mt-1 rounded-lg px-6 py-4 text-left max-sm:col-span-2 max-sm:col-start-1 max-sm:row-start-3"},oT={class:"mulmo-text-primary text-lg leading-relaxed font-sans"},iT={key:0,class:"mulmo-text-secondary text-base leading-relaxed font-sans mt-3 italic"},aT=["src"],lT=ki({__name:"mulmo_viewer",props:{dataSet:{default:void 0},basePath:{},initPage:{default:void 0},audioLang:{default:"en"},textLang:{default:"en"},playbackSpeed:{default:1}},emits:["updatedPage","update:audioLang","update:textLang","allCompleted"],setup(e,{expose:t,emit:n}){const r=e,s=n,o=r.dataSet?.beats?.length??0,i=be(r.initPage??0),a=be(!0),l=be(),u=be(),c=xe({get:()=>r.audioLang,set:F=>s("update:audioLang",F||"en")}),d=xe({get:()=>r.textLang,set:F=>s("update:textLang",F||"en")});let p=0;pt(()=>r.audioLang,async(F,j)=>{if(F!==j&&b.value){p++;const U=p;if(l.value?.stop(),await hl(500),U!==p)return;l.value&&(b.value=!0,await l.value.play())}}),pt(()=>r.textLang,async(F,j)=>{F!==j&&b.value&&(await hl(100),l.value&&await l.value.play())}),pt(u,F=>{F&&(F.volume=.3)});const g=xe(()=>r.dataSet?.beats[i.value]),y=F=>F?r.basePath+"/"+F:"",_=xe(()=>y(r.dataSet?.bgmSource)),b=be(!1),m=()=>{b.value=!0,u.value&&(u.value.volume=.3,u.value.play())},v=()=>{b.value=!1,u.value&&u.value.pause()},A=async()=>{p++;const F=p;l.value?.stop(),await hl(500),F===p&&l.value&&l.value.play()},S=F=>{i.value!==F&&(i.value=F,b.value&&a.value&&A())},P=F=>{const j=i.value+F;return j>-1&&j<o?(S(j),s("updatedPage",j),!0):!1},E=()=>{a.value&&P(1)||(b.value=!1,u.value&&u.value.pause(),s("allCompleted"))},w={onPlay:m,onPause:v,onEnded:E},I=xe(()=>{const F=g.value,j=F?.audioSources?.[c.value],U=F?.multiLinguals?.[d.value]??F?.text??"",O=r.dataSet?.lang?F?.multiLinguals?.[r.dataSet.lang]??F?.text??"":"";return{videoWithAudioSource:y(F?.videoWithAudioSource),videoSource:y(F?.videoSource),soundEffectSource:y(F?.soundEffectSource),audioSource:y(j),imageSource:y(F?.imageSource),index:i.value,text:U,originalText:O,duration:F?.duration,defaultLang:r.dataSet?.lang,currentLang:c.value,playbackSpeed:r.playbackSpeed,...w}}),L=xe(()=>r.dataSet?.beats[i.value+1]),H=xe(()=>{if(i.value+1>=o)return null;const F=L.value;return{videoWithAudioSource:y(F?.videoWithAudioSource),videoSource:y(F?.videoSource),soundEffectSource:y(F?.soundEffectSource),audioSource:y(F?.audioSources?.[c.value]),imageSource:y(F?.imageSource),index:i.value+1,text:F?.multiLinguals?.[d.value]??F?.text??"",duration:F?.duration}}),B=xe(()=>({MulmoPlayer:gl,pageProps:I.value,currentPage:i.value,pageCount:o,pageMove:P,isPlaying:b.value,audioLang:c,textLang:d,SelectLanguage:XE,mediaPlayerRef:l,handlePlay:m,handlePause:v,handleEnded:E}));return t({updatePage:S}),(F,j)=>(ue(),fe(He,null,[cw(F.$slots,"default",cf(ob(B.value)),()=>[oe("div",QE,[oe("div",ZE,[oe("div",eT,[oe("button",{class:"col-start-1 row-start-1 justify-self-start w-auto px-4 py-2 bg-gray-500 text-white rounded hover:bg-gray-600 disabled:opacity-50 self-center max-sm:row-start-2",disabled:i.value===0,onClick:j[0]||(j[0]=U=>P(-1))}," Prev ",8,tT),oe("div",nT,[Nt(gl,Wu({ref_key:"mediaPlayer",ref:l},{...I.value,text:"",originalText:""}),null,16)]),oe("button",{class:"col-start-3 row-start-1 justify-self-end w-auto px-4 py-2 bg-gray-500 text-white rounded hover:bg-gray-600 disabled:opacity-50 self-center max-sm:col-start-2 max-sm:row-start-2",disabled:i.value>=Dd(o)-1,onClick:j[1]||(j[1]=U=>P(1))}," Next ",8,rT),I.value.text?(ue(),fe("div",sT,[oe("p",oT,Ue(I.value.text),1),I.value.originalText&&I.value.originalText!==I.value.text?(ue(),fe("p",iT,Ue(I.value.originalText),1)):Be("",!0)])):Be("",!0)])])])]),H.value?Cr((ue(),Ur(gl,cf(Wu({key:0},H.value)),null,16)),[[cb,!1]]):Be("",!0),_.value?(ue(),fe("audio",{key:1,ref_key:"bgmRef",ref:u,src:_.value},null,8,aT)):Be("",!0)],64))}}),uT=fb(lT,[["__scopeId","data-v-46289647"]]);function cT(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Hd(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if(typeof t=="function"){var n=function r(){var s=!1;try{s=this instanceof r}catch{}return s?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(r){var s=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(n,r,s.get?s:{enumerable:!0,get:function(){return e[r]}})}),n}var Jt={exports:{}};const dT={},fT=Object.freeze(Object.defineProperty({__proto__:null,default:dT},Symbol.toStringTag,{value:"Module"})),Bi=Hd(fT),pT="17.3.1",hT={version:pT};var Bf;function gT(){if(Bf)return Jt.exports;Bf=1;var e={};const t=Bi,n=Bi,r=Bi,s=Bi,i=hT.version,a=["🔐 encrypt with Dotenvx: https://dotenvx.com","🔐 prevent committing .env to code: https://dotenvx.com/precommit","🔐 prevent building .env in docker: https://dotenvx.com/prebuild","🤖 agentic secret storage: https://dotenvx.com/as2","⚡️ secrets for agents: https://dotenvx.com/as2","🛡️ auth for agents: https://vestauth.com","🛠️ run anywhere with `dotenvx run -- yourcommand`","⚙️ specify custom .env file path with { path: '/custom/path/.env' }","⚙️ enable debug logging with { debug: true }","⚙️ override existing env vars with { override: true }","⚙️ suppress all logs with { quiet: true }","⚙️ write to custom object with { processEnv: myObject }","⚙️ load multiple .env files with { path: ['.env.local', '.env'] }"];function l(){return a[Math.floor(Math.random()*a.length)]}function u(F){return typeof F=="string"?!["false","0","no","off",""].includes(F.toLowerCase()):!!F}function c(){return process.stdout.isTTY}function d(F){return c()?`\x1B[2m${F}\x1B[0m`:F}const p=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function g(F){const j={};let U=F.toString();U=U.replace(/\r\n?/mg,`
2
- `);let O;for(;(O=p.exec(U))!=null;){const R=O[1];let T=O[2]||"";T=T.trim();const M=T[0];T=T.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),M==='"'&&(T=T.replace(/\\n/g,`
3
- `),T=T.replace(/\\r/g,"\r")),j[R]=T}return j}function y(F){F=F||{};const j=S(F);F.path=j;const U=B.configDotenv(F);if(!U.parsed){const M=new Error(`MISSING_DATA: Cannot parse ${j} for an unknown reason`);throw M.code="MISSING_DATA",M}const O=v(F).split(","),R=O.length;let T;for(let M=0;M<R;M++)try{const k=O[M].trim(),G=A(U,k);T=B.decrypt(G.ciphertext,G.key);break}catch(k){if(M+1>=R)throw k}return B.parse(T)}function _(F){console.error(`[dotenv@${i}][WARN] ${F}`)}function b(F){console.log(`[dotenv@${i}][DEBUG] ${F}`)}function m(F){console.log(`[dotenv@${i}] ${F}`)}function v(F){return F&&F.DOTENV_KEY&&F.DOTENV_KEY.length>0?F.DOTENV_KEY:e.DOTENV_KEY&&e.DOTENV_KEY.length>0?e.DOTENV_KEY:""}function A(F,j){let U;try{U=new URL(j)}catch(k){if(k.code==="ERR_INVALID_URL"){const G=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw G.code="INVALID_DOTENV_KEY",G}throw k}const O=U.password;if(!O){const k=new Error("INVALID_DOTENV_KEY: Missing key part");throw k.code="INVALID_DOTENV_KEY",k}const R=U.searchParams.get("environment");if(!R){const k=new Error("INVALID_DOTENV_KEY: Missing environment part");throw k.code="INVALID_DOTENV_KEY",k}const T=`DOTENV_VAULT_${R.toUpperCase()}`,M=F.parsed[T];if(!M){const k=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${T} in your .env.vault file.`);throw k.code="NOT_FOUND_DOTENV_ENVIRONMENT",k}return{ciphertext:M,key:O}}function S(F){let j=null;if(F&&F.path&&F.path.length>0)if(Array.isArray(F.path))for(const U of F.path)t.existsSync(U)&&(j=U.endsWith(".vault")?U:`${U}.vault`);else j=F.path.endsWith(".vault")?F.path:`${F.path}.vault`;else j=n.resolve(process.cwd(),".env.vault");return t.existsSync(j)?j:null}function P(F){return F[0]==="~"?n.join(r.homedir(),F.slice(1)):F}function E(F){const j=u(e.DOTENV_CONFIG_DEBUG||F&&F.debug),U=u(e.DOTENV_CONFIG_QUIET||F&&F.quiet);(j||!U)&&m("Loading env from encrypted .env.vault");const O=B._parseVault(F);let R=e;return F&&F.processEnv!=null&&(R=F.processEnv),B.populate(R,O,F),{parsed:O}}function w(F){const j=n.resolve(process.cwd(),".env");let U="utf8",O=e;F&&F.processEnv!=null&&(O=F.processEnv);let R=u(O.DOTENV_CONFIG_DEBUG||F&&F.debug),T=u(O.DOTENV_CONFIG_QUIET||F&&F.quiet);F&&F.encoding?U=F.encoding:R&&b("No encoding is specified. UTF-8 is used by default");let M=[j];if(F&&F.path)if(!Array.isArray(F.path))M=[P(F.path)];else{M=[];for(const W of F.path)M.push(P(W))}let k;const G={};for(const W of M)try{const X=B.parse(t.readFileSync(W,{encoding:U}));B.populate(G,X,F)}catch(X){R&&b(`Failed to load ${W} ${X.message}`),k=X}const V=B.populate(O,G,F);if(R=u(O.DOTENV_CONFIG_DEBUG||R),T=u(O.DOTENV_CONFIG_QUIET||T),R||!T){const W=Object.keys(V).length,X=[];for(const Y of M)try{const Z=n.relative(process.cwd(),Y);X.push(Z)}catch(Z){R&&b(`Failed to load ${Y} ${Z.message}`),k=Z}m(`injecting env (${W}) from ${X.join(",")} ${d(`-- tip: ${l()}`)}`)}return k?{parsed:G,error:k}:{parsed:G}}function I(F){if(v(F).length===0)return B.configDotenv(F);const j=S(F);return j?B._configVault(F):(_(`You set DOTENV_KEY but you are missing a .env.vault file at ${j}. Did you forget to build it?`),B.configDotenv(F))}function L(F,j){const U=Buffer.from(j.slice(-64),"hex");let O=Buffer.from(F,"base64");const R=O.subarray(0,12),T=O.subarray(-16);O=O.subarray(12,-16);try{const M=s.createDecipheriv("aes-256-gcm",U,R);return M.setAuthTag(T),`${M.update(O)}${M.final()}`}catch(M){const k=M instanceof RangeError,G=M.message==="Invalid key length",V=M.message==="Unsupported state or unable to authenticate data";if(k||G){const W=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw W.code="INVALID_DOTENV_KEY",W}else if(V){const W=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw W.code="DECRYPTION_FAILED",W}else throw M}}function H(F,j,U={}){const O=!!(U&&U.debug),R=!!(U&&U.override),T={};if(typeof j!="object"){const M=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw M.code="OBJECT_REQUIRED",M}for(const M of Object.keys(j))Object.prototype.hasOwnProperty.call(F,M)?(R===!0&&(F[M]=j[M],T[M]=j[M]),O&&b(R===!0?`"${M}" is already defined and WAS overwritten`:`"${M}" is already defined and was NOT overwritten`)):(F[M]=j[M],T[M]=j[M]);return T}const B={configDotenv:w,_configVault:E,_parseVault:y,config:I,decrypt:L,parse:g,populate:H};return Jt.exports.configDotenv=B.configDotenv,Jt.exports._configVault=B._configVault,Jt.exports._parseVault=B._parseVault,Jt.exports.config=B.config,Jt.exports.decrypt=B.decrypt,Jt.exports.parse=B.parse,Jt.exports.populate=B.populate,Jt.exports=B,Jt.exports}var mT=gT();const _T=cT(mT);var ml={},_l={},Zt={},yl={},zr={},Hf;function Ha(){if(Hf)return zr;Hf=1,Object.defineProperty(zr,"__esModule",{value:!0}),zr.NodeState=void 0;var e;return(function(t){t.Waiting="waiting",t.Queued="queued",t.Executing="executing",t.ExecutingServer="executing-server",t.Failed="failed",t.TimedOut="timed-out",t.Abort="abort",t.Completed="completed",t.Injected="injected",t.Skipped="skipped"})(e||(zr.NodeState=e={})),zr}var Xr={},Jf;function Hr(){if(Jf)return Xr;Jf=1,Object.defineProperty(Xr,"__esModule",{value:!0}),Xr.GraphAILogger=void 0;const e={debug:!0,info:!0,log:!0,warn:!0,error:!0};let t=null;function n(c,d){e[c]=d}function r(c){t=c}function s(c,...d){e[c]&&(t?t(c,...d):(console[c]||console.log)(...d))}function o(...c){s("debug",...c)}function i(...c){s("info",...c)}function a(...c){s("log",...c)}function l(...c){s("warn",...c)}function u(...c){s("error",...c)}return Xr.GraphAILogger={setLevelEnabled:n,setLogger:r,debug:o,info:i,log:a,warn:l,error:u},Xr}var en={},jf;function Ja(){if(jf)return en;jf=1,Object.defineProperty(en,"__esModule",{value:!0}),en.utilsFunctions=en.propFunctions=en.propFunctionRegex=void 0;const e=_t(),t=Hr();en.propFunctionRegex=/^[a-zA-Z]+\([^)]*\)$/;const n=(u,c)=>{if(Array.isArray(u)){if(c==="length()")return u.length;if(c==="flat()")return u.flat();if(c==="toJSON()")return JSON.stringify(u,null,2);if(c==="isEmpty()")return u.length===0;if(c==="average()"||c==="mean()")return u.length?u.reduce((p,g)=>p+g,0)/u.length:0;if(c==="sum()")return u.reduce((p,g)=>p+g,0);if(c==="max()")return u.length?Math.max(...u):0;if(c==="min()")return u.length?Math.min(...u):0;const d=c.match(/^join\(([,-\s]?)\)$/);if(d&&Array.isArray(d))return u.join(d[1]??"")}},r=(u,c)=>{if((0,e.isObject)(u)){if(c==="keys()")return Object.keys(u);if(c==="values()")return Object.values(u);if(c==="toJSON()")return JSON.stringify(u,null,2)}},s=(u,c)=>{if(typeof u=="string"){if(c==="codeBlock()"){const y=(`
4
- `+u).match(/\n```[a-zA-Z]*([\s\S]*?)\n```/);if(y)return y[1]}if(c==="codeBlockOrRaw()"){const y=(`
5
- `+u).match(/\n```[a-zA-Z]*([\s\S]*?)\n```/);return y?y[1]:u}if(c==="jsonParse()")return JSON.parse(u);if(c==="toNumber()"){const y=Number(u);if(!isNaN(y))return y}if(c==="trim()")return u.trim();if(c==="toLowerCase()")return u.toLowerCase();if(c==="toUpperCase()")return u.toUpperCase();const d=c.match(/^equal\(([A-Za-z0-9!#$%&()*+,\-./:;<=>?@]+)\)/);if(d)return u===d[1];const p=c.match(/^slice\((-?\d+)(?:,\s*(-?\d+))?\)/);if(p){if(p[2]!==void 0)return u.slice(Number(p[1]),Number(p[2]));if(p[1]!==void 0)return u.slice(Number(p[1]));t.GraphAILogger.warn("slice is not valid format: "+p)}const g=c.match(/^split\(([-_:;.,\s\n]+)\)$/);if(g)return u.split(g[1])}},o=(u,c)=>{if(u!==void 0&&Number.isFinite(u)){if(c==="toString()")return String(u);const d=/^add\((-?\d+)\)$/,p=c.match(d);if(p)return Number(u)+Number(p[1]);const g=c.match(/^equal\(([A-Za-z0-9!#$%&()*+,\-/:;<=>?@]+)\)/);if(g)return u===Number(g[1])}},i=(u,c)=>{if(typeof u=="boolean"&&c==="not()")return!u},a=(u,c)=>{if(u===void 0){const d=c.match(/^default\(([A-Za-z0-9!#$%&()*+,\-/:;<=>?@]+)\)/);if(d)return d[1].match(/^[0-9-]+$/)?Number(d[1]):d[1]}};en.propFunctions=[n,r,s,o,i,a];const l=(u,c)=>u==="@now"||u==="@now_ms"?Date.now():u==="@now_s"?Math.floor(Date.now()/1e3):u==="@loop"?c[e.loopCounterKey].result:(t.GraphAILogger.warn("not match template utility function: ${"+u+"}"),"");return en.utilsFunctions=l,en}var Wf;function _t(){return Wf||(Wf=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.loopCounterKey=e.isStaticNodeData=e.isComputedNodeData=e.isNamedInputs=e.defaultTestContext=e.isLogicallyTrue=e.debugResultKey=e.agentInfoWrapper=e.defaultAgentInfo=e.strIntentionalError=e.isNull=e.isObject=e.parseNodeName=e.sleep=void 0,e.assert=i;const t=Ha(),n=Hr(),r=Ja(),s=async m=>await new Promise(v=>setTimeout(v,m));e.sleep=s;const o=(m,v=!1,A)=>{if(v)return typeof m=="string"&&m[0]==="."?{nodeId:"self",propIds:m.split(".").slice(1)}:{value:m};if(typeof m=="string"){const S=/^:(.*)$/,P=m.match(S);if(P){const I=P[1].split(new RegExp("(?<!\\()\\.(?!\\))"));return I.length==1?{nodeId:I[0]}:{nodeId:I[0],propIds:I.slice(1)}}const E=/^@(.*)$/,w=m.match(E);if(A&&w)return{value:(0,r.utilsFunctions)(m,A)}}return{value:m}};e.parseNodeName=o;function i(m,v,A=!1,S){if(!m){if(!A)throw S?new Error(v,{cause:S}):new Error(v);n.GraphAILogger.warn("warn: "+v)}}const a=m=>m!==null&&typeof m=="object";e.isObject=a;const l=m=>m==null;e.isNull=l,e.strIntentionalError="Intentional Error for Debugging",e.defaultAgentInfo={name:"defaultAgentInfo",samples:[{inputs:[],params:{},result:{}}],description:"",category:[],author:"",repository:"",license:""};const u=m=>({agent:m,mock:m,...e.defaultAgentInfo});e.agentInfoWrapper=u;const c=m=>{const v=[];return Object.keys(m).forEach(A=>{v.push([A]),Object.keys(m[A]).length>0&&c(m[A]).forEach(S=>{v.push([A,...S])})}),v},d=(m,v)=>c({[m]:p(v)}).map(A=>":"+A.join("."));e.debugResultKey=d;const p=m=>m==null?{}:typeof m=="string"?{}:Array.isArray(m)?Array.from(m.keys()).reduce((v,A)=>(v["$"+String(A)]=p(m[A]),v),{}):Object.keys(m).reduce((v,A)=>(v[A]=p(m[A]),v),{}),g=m=>!(Array.isArray(m)?m.length===0:!m);e.isLogicallyTrue=g,e.defaultTestContext={debugInfo:{nodeId:"test",retry:0,verbose:!0,state:t.NodeState.Executing,subGraphs:new Map},params:{},filterParams:{},agents:{},log:[]};const y=m=>(0,e.isObject)(m)&&!Array.isArray(m)&&Object.keys(m||{}).length>0;e.isNamedInputs=y;const _=m=>"agent"in m;e.isComputedNodeData=_;const b=m=>!("agent"in m);e.isStaticNodeData=b,e.loopCounterKey="__loopIndex"})(yl)),yl}var vl={},Kf;function ja(){return Kf||(Kf=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.dataSourceNodeIds=e.inputs2dataSources=void 0;const t=_t(),n=s=>{if(Array.isArray(s))return s.map(o=>(0,e.inputs2dataSources)(o)).flat();if((0,t.isObject)(s))return Object.values(s).map(o=>(0,e.inputs2dataSources)(o)).flat();if(typeof s=="string"){const o=[...s.matchAll(/\${(:[^}]+)}/g)].map(i=>i[1]);if(o.length>0)return(0,e.inputs2dataSources)(o)}return(0,t.parseNodeName)(s)};e.inputs2dataSources=n;const r=s=>{if(!Array.isArray(s))throw new Error("sources must be array!! maybe inputs is invalid");return s.filter(o=>o.nodeId).map(o=>o.nodeId)};e.dataSourceNodeIds=r})(vl)),vl}var Qr={},$f;function yT(){if($f)return Qr;$f=1,Object.defineProperty(Qr,"__esModule",{value:!0}),Qr.TransactionLog=void 0;const e=Ha(),t=_t(),n=ja();class r{nodeId;state;startTime;endTime;retryCount;agentId;params;inputs;inputsData;namedInputs;injectFrom;errorMessage;result;resultKeys;mapIndex;isLoop;repeatCount;log;constructor(o,i){this.nodeId=o,this.state=e.NodeState.Waiting,this.mapIndex=i}initForComputedNode(o,i){this.agentId=o.getAgentId(),this.params=o.params,i.appendLog(this)}onInjected(o,i,a){const l="endTime"in this;this.result=o.result,this.state=o.state,this.endTime=Date.now(),this.injectFrom=a,i.setLoopLog(this),l?i.updateLog(this):i.appendLog(this)}onComplete(o,i,a){this.result=o.result,this.resultKeys=(0,t.debugResultKey)(this.agentId||"",o.result),this.state=o.state,this.endTime=Date.now(),i.setLoopLog(this),a.length>0&&(this.log=a),i.updateLog(this)}beforeExecute(o,i,a,l,u){this.agentId=u,this.state=o.state,this.retryCount=o.retryCount>0?o.retryCount:void 0,this.startTime=a,this.inputs=(0,n.dataSourceNodeIds)(o.dataSources);const c=Object.values(l);this.inputsData=c.length>0?c:void 0,this.namedInputs=l,i.setLoopLog(this),i.appendLog(this)}beforeAddTask(o,i){this.state=o.state,i.setLoopLog(this),i.appendLog(this)}onError(o,i,a){this.state=o.state,this.errorMessage=a,this.endTime=Date.now(),i.setLoopLog(this),i.updateLog(this)}onSkipped(o,i){this.state=o.state,i.setLoopLog(this),i.updateLog(this)}}return Qr.TransactionLog=r,Qr}var bl={},Zr={},Yf;function pb(){if(Yf)return Zr;Yf=1,Object.defineProperty(Zr,"__esModule",{value:!0}),Zr.getDataFromSource=void 0;const e=_t(),t=Ja(),n=Hr(),r=(i,a,l)=>{if(a.match(t.propFunctionRegex))for(const c of l){const d=c(i,a);if(!(0,e.isNull)(d))return d}if(Array.isArray(i)){const c=/^\$(\d+)$/,d=a.match(c);if(d){const p=parseInt(d[1],10);return i[p]}if(a==="$last")return i[i.length-1]}else if((0,e.isObject)(i)&&a in i)return i[a]},s=(i,a,l)=>{if(a&&a.length>0){const u=a[0],c=r(i,u,l);return c===void 0&&n.GraphAILogger.debug(`prop: ${a.join(".")} is not hit`),a.length>1?s(c,a.slice(1),l):c}return i},o=(i,a,l=[])=>a.nodeId?s(i,a.propIds,l):a.value;return Zr.getDataFromSource=o,Zr}var zf;function hb(){return zf||(zf=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.cleanResult=e.cleanResultInner=e.resultOf=e.resultsOf=void 0;const t=_t(),n=pb(),r=Ja(),s=(c,d,p,g,y)=>{const _=o(d.filter(m=>m.startsWith(":")),p,g,y),b=d.filter(m=>m.startsWith("@")).reduce((m,v)=>(m[v]=(0,r.utilsFunctions)(v,p),m),{});return Array.from(d.keys()).reduce((m,v)=>d[v].startsWith(":")?m.replaceAll("${"+d[v]+"}",_[v]):m.replaceAll("${"+d[v]+"}",b[d[v]]),c)},o=(c,d,p,g=!1)=>{if(Array.isArray(c))return c.map(y=>o(y,d,p,g));if((0,t.isNamedInputs)(c))return(0,e.resultsOf)(c,d,p,g);if(typeof c=="string"){const y=[...c.matchAll(/\${([:@][^}]+)}/g)].map(_=>_[1]);if(y.length>0)return s(c,y,d,p,g)}return(0,e.resultOf)((0,t.parseNodeName)(c,g,d),d,p)},i=(c,d,p,g=!1)=>Object.keys(c).reduce((y,_)=>{const b=c[_];return y[_]=(0,t.isNamedInputs)(b)?(0,e.resultsOf)(b,d,p,g):o(b,d,p,g),y},{});e.resultsOf=i;const a=(c,d,p)=>{const{result:g}=c.nodeId?d[c.nodeId]:{result:void 0};return(0,n.getDataFromSource)(g,c,p)};e.resultOf=a;const l=c=>Array.isArray(c)?c.map(d=>(0,e.cleanResultInner)(d)).filter(d=>!(0,t.isNull)(d)):(0,t.isObject)(c)?Object.keys(c).reduce((d,p)=>{const g=(0,e.cleanResultInner)(c[p]);return(0,t.isNull)(g)||(d[p]=g),d},{}):c;e.cleanResultInner=l;const u=c=>Object.keys(c).reduce((d,p)=>{const g=(0,e.cleanResultInner)(c[p]);return(0,t.isNull)(g)||(d[p]=g),d},{});e.cleanResult=u})(bl)),bl}var Xf;function vT(){if(Xf)return Zt;Xf=1,Object.defineProperty(Zt,"__esModule",{value:!0}),Zt.StaticNode=Zt.ComputedNode=Zt.Node=void 0;const e=_t(),t=ja(),n=Ha(),r=_t(),s=yT(),o=hb(),i=Hr();class a{nodeId;waitlist=new Set;state=n.NodeState.Waiting;result=void 0;graph;log;console;constructor(d,p){this.nodeId=d,this.graph=p,this.log=new s.TransactionLog(d,this.graph.mapIndex),this.console={}}asString(){return`${this.nodeId}: ${this.state} ${[...this.waitlist]}`}onSetResult(){this.waitlist.forEach(d=>{const p=this.graph.nodes[d];p.isComputedNode&&(p.removePending(this.nodeId),this.graph.pushQueueIfReadyAndRunning(p))})}afterConsoleLog(d){this.console!==!1&&(this.console===!0||this.console.after===!0?i.GraphAILogger.log(typeof d=="string"?d:JSON.stringify(d,null,2)):this.console.after&&((0,r.isObject)(this.console.after)?i.GraphAILogger.log(JSON.stringify((0,o.resultsOf)(this.console.after,{self:{result:d}},this.graph.propFunctions,!0),null,2)):i.GraphAILogger.log(this.console.after)))}}Zt.Node=a;class l extends a{graphId;isResult;params;filterParams;nestedGraph;retryLimit;retryCount=0;repeatUntil;agentId;agentFunction;timeout;priority;error;transactionId;passThrough;anyInput;dataSources=[];inputs;output;pendings;ifSource;unlessSource;defaultValue;isSkip=!1;debugInfo;isStaticNode=!1;isComputedNode=!0;constructor(d,p,g,y){if(super(p,y),this.graphId=d,this.params=g.params??{},this.console=g.console??{},this.filterParams=g.filterParams??{},this.passThrough=g.passThrough,this.retryLimit=g.retry??y.retryLimit??0,this.repeatUntil=g.repeatUntil,this.timeout=g.timeout,this.isResult=g.isResult??!1,this.priority=g.priority??0,(0,r.assert)(["function","string"].includes(typeof g.agent),"agent must be either string or function"),typeof g.agent=="string")this.agentId=g.agent;else{const _=g.agent;this.agentFunction=async({namedInputs:b,params:m})=>_(b,m)}if(this.anyInput=g.anyInput??!1,this.inputs=g.inputs,this.output=g.output,this.dataSources=[...g.inputs?(0,t.inputs2dataSources)(g.inputs).flat(10):[],...this.agentId?[(0,r.parseNodeName)(this.agentId)]:[],...g.passThrough?(0,t.inputs2dataSources)(g.passThrough).flat(10):[]],g.inputs&&Array.isArray(g.inputs))throw new Error(`array inputs have been deprecated. nodeId: ${p}: see https://github.com/receptron/graphai/blob/main/docs/NamedInputs.md`);this.pendings=new Set((0,t.dataSourceNodeIds)(this.dataSources)),g.graph&&(this.nestedGraph=typeof g.graph=="string"?this.addPendingNode(g.graph):g.graph),g.graphLoader&&y.graphLoader&&(this.nestedGraph=y.graphLoader(g.graphLoader)),g.if&&(this.ifSource=this.addPendingNode(g.if)),g.unless&&(this.unlessSource=this.addPendingNode(g.unless)),g.defaultValue&&(this.defaultValue=g.defaultValue),this.isSkip=!1,this.log.initForComputedNode(this,y)}getAgentId(){return this.agentId??"__custom__function"}getConfig(d,p){if(p){if(d)return this.graph.config;const g=this.graph.config??{};return{...g.global??{},...g[p]??{}}}return{}}addPendingNode(d){const p=(0,r.parseNodeName)(d);return(0,r.assert)(!!p.nodeId,`Invalid data source ${d}`),this.pendings.add(p.nodeId),p}updateState(d){this.state=d,this.debugInfo&&(this.debugInfo.state=d)}resetPending(){this.pendings.clear(),this.state===n.NodeState.Executing&&this.updateState(n.NodeState.Abort),this.debugInfo&&this.debugInfo.subGraphs&&this.debugInfo.subGraphs.forEach(d=>d.abort(!0))}isReadyNode(){return this.state!==n.NodeState.Waiting||this.pendings.size!==0?!1:(this.isSkip=!!(this.ifSource&&!(0,r.isLogicallyTrue)(this.graph.resultOf(this.ifSource))||this.unlessSource&&(0,r.isLogicallyTrue)(this.graph.resultOf(this.unlessSource))),this.isSkip&&this.defaultValue===void 0?(this.updateState(n.NodeState.Skipped),this.log.onSkipped(this,this.graph),!1):!0)}retry(d,p){this.updateState(d),this.log.onError(this,this.graph,p.message),this.retryCount<this.retryLimit?(this.retryCount++,this.execute()):(this.result=void 0,this.error=p,this.transactionId=void 0,this.graph.onExecutionComplete(this))}checkDataAvailability(){const{params:d,...p}=this.inputs??{};return Object.values(this.graph.resultsOf(p)).flat().some(g=>g!==void 0)}beforeAddTask(){this.updateState(n.NodeState.Queued),this.log.beforeAddTask(this,this.graph)}removePending(d){this.anyInput?this.checkDataAvailability()&&this.pendings.clear():this.pendings.delete(d)}isCurrentTransaction(d){return this.transactionId===d}executeTimeout(d){this.state===n.NodeState.Executing&&this.isCurrentTransaction(d)&&(i.GraphAILogger.warn(`-- timeout ${this.timeout} with ${this.nodeId}`),this.retry(n.NodeState.TimedOut,Error("Timeout")))}shouldApplyAgentFilter(d,p){return d.agentIds&&Array.isArray(d.agentIds)&&d.agentIds.length>0&&p&&d.agentIds.includes(p)||d.nodeIds&&Array.isArray(d.nodeIds)&&d.nodeIds.length>0&&d.nodeIds.includes(this.nodeId)?!0:!d.agentIds&&!d.nodeIds}agentFilterHandler(d,p,g){let y=0;const _=b=>{const m=this.graph.agentFilters[y++];return m?this.shouldApplyAgentFilter(m,g)?(m.filterParams&&(b.filterParams={...m.filterParams,...b.filterParams}),m.agent(b,_)):_(b):p(b)};return _(d)}async execute(){if(this.isSkip){this.afterExecute(this.defaultValue,[]);return}const d=this.graph.resultsOf(this.inputs,this.anyInput),p=this.agentId?this.graph.resultOf((0,r.parseNodeName)(this.agentId)):this.agentId;typeof p=="function"&&(this.agentFunction=p);const g=!!this.nestedGraph||!!(typeof p=="string"&&this.graph.getAgentFunctionInfo(p,this.nodeId).hasGraphData),y=this.getConfig(g,p),_=Date.now();this.prepareExecute(_,d,p),this.timeout&&this.timeout>0&&setTimeout(()=>{this.executeTimeout(_)},this.timeout);try{const b=this.agentFunction??this.graph.getAgentFunctionInfo(p,this.nodeId).agent,m=[],v=this.getContext(d,m,p,y);g&&(this.graph.taskManager.prepareForNesting(),v.forNestedGraph={graphData:this.nestedGraph?"nodes"in this.nestedGraph?this.nestedGraph:this.graph.resultOf(this.nestedGraph):{version:0,nodes:{}},agents:this.graph.agentFunctionInfoDictionary,graphOptions:{agentFilters:this.graph.agentFilters,taskManager:this.graph.taskManager,bypassAgentIds:this.graph.bypassAgentIds,config:y,graphLoader:this.graph.graphLoader},onLogCallback:this.graph.onLogCallback,callbacks:this.graph.callbacks}),this.beforeConsoleLog(v);const A=await this.agentFilterHandler(v,b,p);if(this.afterConsoleLog(A),g&&this.graph.taskManager.restoreAfterNesting(),!this.isCurrentTransaction(_)){i.GraphAILogger.log(`-- transactionId mismatch with ${this.nodeId} (probably timeout)`);return}if(this.repeatUntil?.exists){const S={self:{result:this.getResult(A)}},P=(0,o.resultsOf)({data:this.repeatUntil?.exists},S,[],!0);if((0,e.isNull)(P?.data)){this.retry(n.NodeState.Failed,Error("Repeat Until"));return}}this.afterExecute(A,m)}catch(b){this.errorProcess(b,_,d)}}afterExecute(d,p){this.state!=n.NodeState.Abort&&(this.updateState(n.NodeState.Completed),this.result=this.getResult(d),this.output&&(this.result=(0,o.resultsOf)(this.output,{self:this},this.graph.propFunctions,!0),this.passThrough&&(this.result={...this.result,...this.graph.resultsOf(this.passThrough)})),this.log.onComplete(this,this.graph,p),this.onSetResult(),this.graph.onExecutionComplete(this))}prepareExecute(d,p,g){this.updateState(n.NodeState.Executing),this.log.beforeExecute(this,this.graph,d,p,g),this.transactionId=d}errorProcess(d,p,g){if(d instanceof Error&&d.message!==e.strIntentionalError&&(i.GraphAILogger.error(`<-- NodeId: ${this.nodeId}, Agent: ${this.agentId}`),i.GraphAILogger.error({namedInputs:g}),i.GraphAILogger.error(d),i.GraphAILogger.error("-->")),!this.isCurrentTransaction(p)){i.GraphAILogger.warn(`-- transactionId mismatch with ${this.nodeId} (not timeout)`);return}d instanceof Error?this.retry(n.NodeState.Failed,d):(i.GraphAILogger.error(`-- NodeId: ${this.nodeId}: Unknown error was caught`),this.retry(n.NodeState.Failed,Error("Unknown")))}getContext(d,p,g,y){return this.debugInfo=this.getDebugInfo(g),{params:{...this.params??{},...(0,e.isNamedInputs)(d?.params)?d?.params:{}},namedInputs:d,inputSchema:this.agentFunction?void 0:this.graph.getAgentFunctionInfo(g,this.nodeId)?.inputs,debugInfo:this.debugInfo,cacheType:this.agentFunction?void 0:this.graph.getAgentFunctionInfo(g,this.nodeId)?.cacheType,filterParams:this.filterParams,config:y,log:p}}getResult(d){if(d&&this.passThrough){if((0,r.isObject)(d)&&!Array.isArray(d))return{...d,...this.graph.resultsOf(this.passThrough)};if(Array.isArray(d))return d.map(p=>(0,r.isObject)(p)&&!Array.isArray(p)?{...p,...this.graph.resultsOf(this.passThrough)}:p)}return d}getDebugInfo(d){return{nodeId:this.nodeId,agentId:d,retry:this.retryCount,state:this.state,subGraphs:new Map,verbose:this.graph.verbose,version:this.graph.version,isResult:this.isResult}}beforeConsoleLog(d){this.console!==!1&&(this.console===!0||this.console.before===!0?i.GraphAILogger.log(JSON.stringify(d.namedInputs,null,2)):this.console.before&&i.GraphAILogger.log(this.console.before))}}Zt.ComputedNode=l;class u extends a{value;update;isResult;isStaticNode=!0;isComputedNode=!1;constructor(d,p,g){super(d,g),this.value=p.value,this.update=p.update?(0,r.parseNodeName)(p.update):void 0,this.isResult=p.isResult??!1,this.console=p.console??{}}updateValue(d,p){this.value=d,this.log.onInjected(this,this.graph,p)}setResultValue(d){this.state=n.NodeState.Injected,this.result=this.value,this.log.onInjected(this,this.graph,d),this.onSetResult()}consoleLog(){this.afterConsoleLog(this.result)}}return Zt.StaticNode=u,Zt}var Un={},Gn={},bt={},Qf;function On(){if(Qf)return bt;Qf=1,Object.defineProperty(bt,"__esModule",{value:!0}),bt.ValidationError=bt.staticNodeAttributeKeys=bt.computedNodeAttributeKeys=bt.graphDataAttributeKeys=void 0,bt.graphDataAttributeKeys=["nodes","concurrency","agentId","loop","verbose","version","metadata"],bt.computedNodeAttributeKeys=["inputs","output","anyInput","params","retry","repeatUntil","timeout","agent","graph","graphLoader","isResult","priority","if","unless","defaultValue","filterParams","console","passThrough"],bt.staticNodeAttributeKeys=["value","update","isResult","console"];class e extends Error{constructor(n){super(`\x1B[41m${n}\x1B[0m`),Object.setPrototypeOf(this,e.prototype)}}return bt.ValidationError=e,bt}var Zf;function bT(){if(Zf)return Gn;Zf=1,Object.defineProperty(Gn,"__esModule",{value:!0}),Gn.graphDataValidator=Gn.graphNodesValidator=void 0;const e=On(),t=r=>{if(r.nodes===void 0)throw new e.ValidationError("Invalid Graph Data: no nodes");if(typeof r.nodes!="object")throw new e.ValidationError("Invalid Graph Data: invalid nodes");if(Array.isArray(r.nodes))throw new e.ValidationError("Invalid Graph Data: nodes must be object");if(Object.keys(r.nodes).length===0)throw new e.ValidationError("Invalid Graph Data: nodes is empty");Object.keys(r).forEach(s=>{if(!e.graphDataAttributeKeys.includes(s))throw new e.ValidationError("Graph Data does not allow "+s)})};Gn.graphNodesValidator=t;const n=r=>{if(r.loop){if(r.loop.count===void 0&&r.loop.while===void 0)throw new e.ValidationError("Loop: Either count or while is required in loop");if(r.loop.count!==void 0&&r.loop.while!==void 0)throw new e.ValidationError("Loop: Both count and while cannot be set")}if(r.concurrency!==void 0){if(!Number.isInteger(r.concurrency))throw new e.ValidationError("Concurrency must be an integer");if(r.concurrency<1)throw new e.ValidationError("Concurrency must be a positive integer")}};return Gn.graphDataValidator=n,Gn}var es={},ep;function AT(){if(ep)return es;ep=1,Object.defineProperty(es,"__esModule",{value:!0}),es.nodeValidator=void 0;const e=On(),t=n=>{if(n.agent&&n.value)throw new e.ValidationError("Cannot set both agent and value");return!0};return es.nodeValidator=t,es}var ts={},tp;function ST(){if(tp)return ts;tp=1,Object.defineProperty(ts,"__esModule",{value:!0}),ts.staticNodeValidator=void 0;const e=On(),t=n=>(Object.keys(n).forEach(r=>{if(!e.staticNodeAttributeKeys.includes(r))throw new e.ValidationError("Static node does not allow "+r)}),!0);return ts.staticNodeValidator=t,ts}var ns={},np;function wT(){if(np)return ns;np=1,Object.defineProperty(ns,"__esModule",{value:!0}),ns.computedNodeValidator=void 0;const e=On(),t=n=>(Object.keys(n).forEach(r=>{if(!e.computedNodeAttributeKeys.includes(r))throw new e.ValidationError("Computed node does not allow "+r)}),!0);return ns.computedNodeValidator=t,ns}var rs={},rp;function ET(){if(rp)return rs;rp=1,Object.defineProperty(rs,"__esModule",{value:!0}),rs.relationValidator=void 0;const e=_t(),t=ja(),n=On(),r=(s,o,i)=>{const a=new Set(Object.keys(s.nodes)),l={},u={};i.forEach(p=>{const g=s.nodes[p];l[p]=new Set;const y=(_,b)=>{b.forEach(m=>{if(m){if(!a.has(m))throw new n.ValidationError(`${_} not match: NodeId ${p}, Inputs: ${m}`);u[m]===void 0&&(u[m]=new Set),l[p].add(m),u[m].add(p)}})};if(g&&(0,e.isComputedNodeData)(g)){if(g.inputs){const _=(0,t.dataSourceNodeIds)((0,t.inputs2dataSources)(g.inputs));y("Inputs",_)}if(g.if){const _=(0,t.dataSourceNodeIds)((0,t.inputs2dataSources)({if:g.if}));y("If",_)}if(g.unless){const _=(0,t.dataSourceNodeIds)((0,t.inputs2dataSources)({unless:g.unless}));y("Unless",_)}if(g.graph&&typeof g?.graph=="string"){const _=(0,t.dataSourceNodeIds)((0,t.inputs2dataSources)({graph:g.graph}));y("Graph",_)}if(typeof g.agent=="string"&&g.agent[0]===":"){const _=(0,t.dataSourceNodeIds)((0,t.inputs2dataSources)({agent:g.agent}));y("Agent",_)}}}),o.forEach(p=>{const g=s.nodes[p];if((0,e.isStaticNodeData)(g)&&g.update){const y=g.update,_=(0,e.parseNodeName)(y).nodeId;if(!_)throw new n.ValidationError("Update it a literal");if(!a.has(_))throw new n.ValidationError(`Update not match: NodeId ${p}, update: ${y}`)}});const c=p=>{p.forEach(y=>{(u[y]||[]).forEach(_=>{l[_].delete(y)})});const g=[];return Object.keys(l).forEach(y=>{l[y].size===0&&(g.push(y),delete l[y])}),g};let d=c(o);if(d.length===0)throw new n.ValidationError("No Initial Runnning Node");do d=c(d);while(d.length>0);if(Object.keys(l).length>0)throw new n.ValidationError("Some nodes are not executed: "+Object.keys(l).join(", "))};return rs.relationValidator=r,rs}var ss={},sp;function TT(){if(sp)return ss;sp=1,Object.defineProperty(ss,"__esModule",{value:!0}),ss.agentValidator=void 0;const e=On(),t=(n,r)=>(n.forEach(s=>{if(!r.has(s)&&s[0]!==":")throw new e.ValidationError("Invalid Agent : "+s+" is not in AgentFunctionInfoDictionary.")}),!0);return ss.agentValidator=t,ss}var op;function PT(){if(op)return Un;op=1,Object.defineProperty(Un,"__esModule",{value:!0}),Un.validateAgent=Un.validateGraphData=void 0;const e=_t(),t=bT(),n=AT(),r=ST(),s=wT(),o=ET(),i=TT(),a=On(),l=(c,d)=>{(0,t.graphNodesValidator)(c),(0,t.graphDataValidator)(c);const p=[],g=[],y=new Set;return Object.keys(c.nodes).forEach(_=>{const b=c.nodes[_],m=(0,e.isStaticNodeData)(b);(0,n.nodeValidator)(b);const v=m?"":b.agent;m&&(0,r.staticNodeValidator)(b)&&g.push(_),!m&&(0,s.computedNodeValidator)(b)&&p.push(_)&&typeof v=="string"&&y.add(v)}),(0,i.agentValidator)(y,new Set(d)),(0,o.relationValidator)(c,g,p),!0};Un.validateGraphData=l;const u=c=>{Object.keys(c).forEach(d=>{if(d!=="default"){const p=c[d];if(!p||!p.agent)throw new a.ValidationError("No Agent: "+d+" is not in AgentFunctionInfoDictionary.")}})};return Un.validateAgent=u,Un}var os={},ip;function gb(){if(ip)return os;ip=1,Object.defineProperty(os,"__esModule",{value:!0}),os.TaskManager=void 0;const e=_t();class t{concurrency;taskQueue=[];runningNodes=new Set;constructor(r){this.concurrency=r}dequeueTaskIfPossible(){if(this.runningNodes.size<this.concurrency){const r=this.taskQueue.shift();r&&(this.runningNodes.add(r.node),r.callback(r.node))}}addTask(r,s,o){const i=this.taskQueue.filter(a=>a.node.priority>=r.priority).length;(0,e.assert)(i<=this.taskQueue.length,"TaskManager.addTask: Something is really wrong."),this.taskQueue.splice(i,0,{node:r,graphId:s,callback:o}),this.dequeueTaskIfPossible()}isRunning(r){return[...this.runningNodes].filter(o=>o.graphId==r).length>0||Array.from(this.taskQueue).filter(o=>o.graphId===r).length>0}onComplete(r){(0,e.assert)(this.runningNodes.has(r),`TaskManager.onComplete node(${r.nodeId}) is not in list`),this.runningNodes.delete(r),this.dequeueTaskIfPossible()}prepareForNesting(){this.concurrency++}restoreAfterNesting(){this.concurrency--}getStatus(r=!1){const s=Array.from(this.runningNodes).map(a=>a.nodeId),o=this.taskQueue.map(a=>a.node.nodeId),i=r?{runningNodes:s,queuedNodes:o}:{};return{concurrency:this.concurrency,queue:this.taskQueue.length,running:this.runningNodes.size,...i}}reset(){this.taskQueue.length=0,this.runningNodes.clear()}}return os.TaskManager=t,os}var ap;function IT(){return ap||(ap=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.GraphAI=e.graphDataLatestVersion=e.defaultConcurrency=void 0;const t=vT(),n=hb(),r=Ja(),s=_t(),o=pb(),i=PT(),a=gb(),l=Hr();e.defaultConcurrency=8,e.graphDataLatestVersion=.5;class u{version;graphId;graphData;staticNodeInitData={};loop;forceLoop;logs=[];mapIndex;bypassAgentIds;config={};agentFunctionInfoDictionary;taskManager;agentFilters;retryLimit;propFunctions;graphLoader;nodes;onLogCallback=(d,p)=>{};callbacks=[];verbose;onComplete;repeatCount=0;createNodes(d){const p=Object.keys(d.nodes).reduce((g,y)=>{const _=d.nodes[y];if((0,s.isComputedNodeData)(_))g[y]=new t.ComputedNode(this.graphId,y,_,this);else{const b=this.staticNodeInitData[y];g[y]=new t.StaticNode(y,b!==void 0?{..._,value:b}:_,this)}return g},{});return Object.keys(p).forEach(g=>{const y=p[g];y.isComputedNode&&y.pendings.forEach(_=>{if(p[_])p[_].waitlist.add(g);else throw new Error(`createNode: invalid input ${_} for node, ${g}`)})}),p}getValueFromResults(d,p){return(0,o.getDataFromSource)(d.nodeId?p[d.nodeId]:void 0,d,this.propFunctions)}setStaticNodeResults(d=!1){Object.keys(this.graphData.nodes).forEach(p=>{const g=this.nodes[p];g?.isStaticNode&&(g?.value!==void 0&&g.setResultValue(p),d&&g.consoleLog())})}updateStaticNodes(d,p=!1){Object.keys(this.graphData.nodes).forEach(g=>{const y=this.nodes[g];if(y?.isStaticNode){const _=y?.update;if(_&&d){const b=this.getValueFromResults(_,d);this.updateStaticNodeValue(g,b,_.nodeId)}p&&y.consoleLog()}})}constructor(d,p,g={taskManager:void 0,agentFilters:[],bypassAgentIds:[],config:{},graphLoader:void 0,forceLoop:!1,mapIndex:void 0}){!d.version&&!g.taskManager&&l.GraphAILogger.warn("------------ missing version number"),this.version=d.version??e.graphDataLatestVersion,this.version<e.graphDataLatestVersion&&l.GraphAILogger.warn(`------------ upgrade to ${e.graphDataLatestVersion}!`),this.retryLimit=d.retry,this.graphId=`${Date.now().toString(36)}-${Math.random().toString(36).substr(2,9)}`,this.agentFunctionInfoDictionary=p,this.propFunctions=r.propFunctions,this.taskManager=g.taskManager??new a.TaskManager(d.concurrency??e.defaultConcurrency),this.agentFilters=g.agentFilters??[],this.bypassAgentIds=g.bypassAgentIds??[],this.config=g.config,this.graphLoader=g.graphLoader,this.forceLoop=g.forceLoop??!1,this.mapIndex=g.mapIndex,this.loop=d.loop,this.verbose=d.verbose===!0,this.onComplete=y=>{throw new Error("SOMETHING IS WRONG: onComplete is called without run()")},(0,i.validateGraphData)(d,[...Object.keys(p),...this.bypassAgentIds]),(0,i.validateAgent)(p),this.graphData={...d,nodes:{...d.nodes,[s.loopCounterKey]:{value:0,update:`:${s.loopCounterKey}.add(1)`}}},this.nodes=this.createNodes(this.graphData)}getAgentFunctionInfo(d,p){if(d&&this.agentFunctionInfoDictionary[d])return this.agentFunctionInfoDictionary[d];if(d&&this.bypassAgentIds.includes(d))return{agent:async()=>null,hasGraphData:!1,inputs:null,cacheType:void 0};throw p?new Error(`No agent: ${d} in ${p} node`):new Error("No agent: "+d)}asString(){return Object.values(this.nodes).map(d=>d.asString()).join(`
6
- `)}results(d,p=!1){return Object.keys(this.nodes).filter(g=>d&&(p||g!==s.loopCounterKey)||this.nodes[g].isResult).reduce((g,y)=>{const _=this.nodes[y];return _.result!==void 0&&(g[y]=_.result),g},{})}errors(){return Object.keys(this.nodes).reduce((d,p)=>{const g=this.nodes[p];return g.isComputedNode&&g.error!==void 0&&(d[p]=g.error),d},{})}pushReadyNodesIntoQueue(){Object.keys(this.nodes).forEach(d=>{const p=this.nodes[d];p.isComputedNode&&this.pushQueueIfReady(p)})}pushQueueIfReady(d){d.isReadyNode()&&this.pushQueue(d)}pushQueueIfReadyAndRunning(d){this.isRunning()&&this.pushQueueIfReady(d)}pushQueue(d){d.beforeAddTask(),this.taskManager.addTask(d,this.graphId,p=>{(0,s.assert)(d.nodeId===p.nodeId,"GraphAI.pushQueue node mismatch"),d.execute()})}async run(d=!1){this.setStaticNodeResults();const p=Object.values(this.nodes).filter(g=>g.isStaticNode).filter(g=>g.result===void 0&&g.update===void 0);if(p.length>0){const g=p.map(y=>y.nodeId).join(", ");throw new Error(`Static node(s) must have value. Set value, injectValue, or set update. Affected nodeIds: ${g}`)}if(this.isRunning())throw new Error("This GraphAI instance is already running");return this.pushReadyNodesIntoQueue(),this.isRunning()?new Promise((g,y)=>{this.onComplete=(_=!1)=>{const b=this.errors(),m=Object.keys(b);m.length>0||_?y(b[m[0]]):g(this.results(d))}}):(l.GraphAILogger.warn("-- nothing to execute"),{})}abort(d=!1){this.isRunning()&&this.resetPending(),Object.values(this.nodes).forEach(p=>p.isComputedNode&&(p.transactionId=void 0)),d||this.taskManager.reset(),this.onComplete(this.isRunning())}resetPending(){Object.values(this.nodes).map(d=>{d.isComputedNode&&d.resetPending()})}isRunning(){return this.taskManager.isRunning(this.graphId)}onExecutionComplete(d){if(this.taskManager.onComplete(d),!(this.isRunning()||this.processLoopIfNecessary())){if(this.verbose){const p=Object.values(this.nodes).filter(g=>g.isComputedNode&&g.state!=="completed");p.length>0&&console.log("Those nodes are not running. "+p.map(g=>`${g.nodeId}: ${g.state}`).join(", "))}this.onComplete(!1)}}processLoopIfNecessary(){if(!this.forceLoop&&Object.keys(this.errors()).length>0)return!1;this.repeatCount++;const d=this.loop;if(!d)return!1;const p=this.results(!0,!0);if(this.updateStaticNodes(p),this.setStaticNodeResults(),d.count===void 0||this.repeatCount<d.count){if(d.while){const g=(0,s.parseNodeName)(d.while),y=this.getValueFromResults(g,this.results(!0,!0));if(!(0,s.isLogicallyTrue)(y))return!1}return this.nodes=this.createNodes(this.graphData),this.updateStaticNodes(p,!0),this.setStaticNodeResults(),this.pushReadyNodesIntoQueue(),!0}return!1}initializeGraphAI(){if(this.isRunning())throw new Error("This GraphAI instance is running");this.nodes=this.createNodes(this.graphData),this.setStaticNodeResults()}setPreviousResults(d){this.updateStaticNodes(d)}setLoopLog(d){d.isLoop=!!this.loop,d.repeatCount=this.repeatCount}appendLog(d){this.logs.push(d),this.onLogCallback(d,!1),this.callbacks.forEach(p=>p(d,!1))}updateLog(d){this.onLogCallback(d,!0),this.callbacks.forEach(p=>p(d,!1))}registerCallback(d){this.callbacks.push(d)}clearCallbacks(){this.callbacks=[]}transactionLogs(){return this.logs}injectValue(d,p,g){this.staticNodeInitData[d]=p,this.updateStaticNodeValue(d,p,g)}setLoopCount(d){this.loop={count:d}}updateStaticNodeValue(d,p,g){const y=this.nodes[d];if(y&&y.isStaticNode)y.updateValue(p,g);else throw new Error(`injectValue with Invalid nodeId, ${d}`)}resultsOf(d,p=!1){const g=(0,n.resultsOf)(d??{},this.nodes,this.propFunctions);return p?(0,n.cleanResult)(g):g}resultOf(d){return(0,n.resultOf)(d,this.nodes,this.propFunctions)}}e.GraphAI=u})(_l)),_l}var lp;function Oe(){return lp||(lp=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.TaskManager=e.GraphAILogger=e.ValidationError=e.inputs2dataSources=e.isNull=e.isStaticNodeData=e.isComputedNodeData=e.debugResultKey=e.parseNodeName=e.isObject=e.sleep=e.assert=e.strIntentionalError=e.defaultTestContext=e.agentInfoWrapper=e.defaultAgentInfo=e.NodeState=e.graphDataLatestVersion=e.defaultConcurrency=e.GraphAI=void 0;var t=IT();Object.defineProperty(e,"GraphAI",{enumerable:!0,get:function(){return t.GraphAI}}),Object.defineProperty(e,"defaultConcurrency",{enumerable:!0,get:function(){return t.defaultConcurrency}}),Object.defineProperty(e,"graphDataLatestVersion",{enumerable:!0,get:function(){return t.graphDataLatestVersion}});var n=Ha();Object.defineProperty(e,"NodeState",{enumerable:!0,get:function(){return n.NodeState}});var r=_t();Object.defineProperty(e,"defaultAgentInfo",{enumerable:!0,get:function(){return r.defaultAgentInfo}}),Object.defineProperty(e,"agentInfoWrapper",{enumerable:!0,get:function(){return r.agentInfoWrapper}}),Object.defineProperty(e,"defaultTestContext",{enumerable:!0,get:function(){return r.defaultTestContext}}),Object.defineProperty(e,"strIntentionalError",{enumerable:!0,get:function(){return r.strIntentionalError}}),Object.defineProperty(e,"assert",{enumerable:!0,get:function(){return r.assert}}),Object.defineProperty(e,"sleep",{enumerable:!0,get:function(){return r.sleep}}),Object.defineProperty(e,"isObject",{enumerable:!0,get:function(){return r.isObject}}),Object.defineProperty(e,"parseNodeName",{enumerable:!0,get:function(){return r.parseNodeName}}),Object.defineProperty(e,"debugResultKey",{enumerable:!0,get:function(){return r.debugResultKey}}),Object.defineProperty(e,"isComputedNodeData",{enumerable:!0,get:function(){return r.isComputedNodeData}}),Object.defineProperty(e,"isStaticNodeData",{enumerable:!0,get:function(){return r.isStaticNodeData}}),Object.defineProperty(e,"isNull",{enumerable:!0,get:function(){return r.isNull}});var s=ja();Object.defineProperty(e,"inputs2dataSources",{enumerable:!0,get:function(){return s.inputs2dataSources}});var o=On();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return o.ValidationError}});var i=Hr();Object.defineProperty(e,"GraphAILogger",{enumerable:!0,get:function(){return i.GraphAILogger}});var a=gb();Object.defineProperty(e,"TaskManager",{enumerable:!0,get:function(){return a.TaskManager}})})(ml)),ml}Oe();var tn={},We={},Al={},up;function CT(){return up||(up=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.stringSplitterAgent=void 0;const t=Oe(),n=2048,r=async({params:l,namedInputs:u})=>{(0,t.assert)(!!u,"stringSplitterAgent: namedInputs is UNDEFINED!");const c=u.text,d=l.chunkSize??n,p=l.overlap??Math.floor(d/8),g=Math.floor(c.length/(d-p))+1;return{contents:new Array(g).fill(void 0).map((_,b)=>{const m=b*(d-p);return c.substring(m,m+d)}),count:g,chunkSize:d,overlap:p}};e.stringSplitterAgent=r;const s={text:"Here's to the crazy ones, the misfits, the rebels, the troublemakers, the round pegs in the square holes ... the ones who see things differently -- they're not fond of rules, and they have no respect for the status quo. ... You can quote them, disagree with them, glorify or vilify them, but the only thing you can't do is ignore them because they change things. ... They push the human race forward, and while some may see them as the crazy ones, we see genius, because the people who are crazy enough to think that they can change the world, are the ones who do."},o={chunkSize:64},i={contents:["Here's to the crazy ones, the misfits, the rebels, the troublema","roublemakers, the round pegs in the square holes ... the ones wh"," ones who see things differently -- they're not fond of rules, a","rules, and they have no respect for the status quo. ... You can ","You can quote them, disagree with them, glorify or vilify them, ","y them, but the only thing you can't do is ignore them because t","ecause they change things. ... They push the human race forward,","forward, and while some may see them as the crazy ones, we see g","we see genius, because the people who are crazy enough to think ","o think that they can change the world, are the ones who do."," do."],count:11,chunkSize:64,overlap:8},a={name:"stringSplitterAgent",agent:e.stringSplitterAgent,mock:e.stringSplitterAgent,inputs:{type:"object",properties:{text:{type:"string",description:"text to be chuncked"}},required:["text"]},output:{type:"object",properties:{contents:{type:"array",description:"the array of text chunks"},count:{type:"number",description:"the number of chunks"},chunkSize:{type:"number",description:"the chunk size"},overlap:{type:"number",description:"the overlap size"}}},samples:[{inputs:s,params:o,result:i}],description:"This agent strip one long string into chunks using following parameters",category:["string"],author:"Satoshi Nakajima",repository:"https://github.com/receptron/graphai",source:"https://github.com/receptron/graphai/blob/main/agents/vanilla_agents/src/string_agents/string_splitter_agent.ts",package:"@graphai/vanilla",license:"MIT"};e.default=a})(Al)),Al}var Sl={},cp;function RT(){return cp||(cp=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.stringTemplateAgent=void 0;const t=Oe(),n=(i,a,l)=>typeof i=="string"?i===a?l:i.replace(a,l):Array.isArray(i)?i.map(u=>n(u,a,l)):(0,t.isObject)(i)?Object.keys(i).reduce((u,c)=>(u[c]=n(i[c],a,l),u),{}):i,r=async({params:i,namedInputs:a})=>{if(i.template===void 0){if(a.text)return a.text;console.warn("warning: stringTemplateAgent no template")}return Object.keys(a).reduce((l,u)=>n(l,"${"+u+"}",a[u]),i.template)};e.stringTemplateAgent=r;const s={message1:"hello",message2:"test"},o={name:"stringTemplateAgent",agent:e.stringTemplateAgent,mock:e.stringTemplateAgent,inputs:{type:"object",description:"Key-value pairs where each key corresponds to a variable used in the template (e.g., ${key}).",additionalProperties:{type:["string","number","boolean","object","array","null"],description:"Any value to be substituted into the template. Objects and arrays are injected directly if the entire field is a placeholder."}},params:{type:"object",description:"The template to apply substitutions to. Supports strings, arrays, and deeply nested object structures with placeholder strings.",properties:{template:{description:"The template structure where placeholders like ${key} will be replaced with values from 'inputs'.",anyOf:[{type:"string"},{type:"array",items:{anyOf:[{type:"string"},{type:"object",additionalProperties:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}}]}},{type:"object",additionalProperties:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}},{type:"object",additionalProperties:!0}]}}]}},required:["template"],additionalProperties:!1},output:{description:"The result after placeholder substitution, matching the structure and type of the original template.",anyOf:[{type:"string"},{type:"array",items:{anyOf:[{type:"string"},{type:"object",additionalProperties:!0}]}},{type:"object",additionalProperties:!0}]},samples:[{inputs:s,params:{template:"${message1}: ${message2}"},result:"hello: test"},{inputs:s,params:{template:["${message1}: ${message2}","${message2}: ${message1}"]},result:["hello: test","test: hello"]},{inputs:s,params:{template:{apple:"${message1}",lemon:"${message2}"}},result:{apple:"hello",lemon:"test"}},{inputs:s,params:{template:[{apple:"${message1}",lemon:"${message2}"}]},result:[{apple:"hello",lemon:"test"}]},{inputs:s,params:{template:{apple:"${message1}",lemon:["${message2}"]}},result:{apple:"hello",lemon:["test"]}},{inputs:{agent:"openAiAgent",row:"hello world",params:{text:"message"}},params:{template:{version:.5,nodes:{ai:{agent:"${agent}",isResult:!0,params:"${params}",inputs:{prompt:"${row}"}}}}},result:{nodes:{ai:{agent:"openAiAgent",inputs:{prompt:"hello world"},isResult:!0,params:{text:"message"}}},version:.5}}],description:"Template agent",category:["string"],author:"Satoshi Nakajima",repository:"https://github.com/receptron/graphai",source:"https://github.com/receptron/graphai/blob/main/agents/vanilla_agents/src/string_agents/string_template_agent.ts",package:"@graphai/vanilla",cacheType:"pureAgent",license:"MIT"};e.default=o})(Sl)),Sl}var wl={},dp;function MT(){return dp||(dp=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.jsonParserAgent=void 0;const t=async({namedInputs:l})=>{const{text:u,data:c}=l;if(c)return{text:JSON.stringify(c,null,2)};const d=(`
7
- `+u).match(/\n```[a-zA-Z]*([\s\S]*?)\n```/);return d?{data:JSON.parse(d[1])}:{data:JSON.parse(u??"")}};e.jsonParserAgent=t;const n={apple:"red",lemon:"yellow"},r=JSON.stringify(n),s=["```",r,"```"].join(`
8
- `),o=["```json",r,"```"].join(`
9
- `),i=["```JSON",r,"```"].join(`
10
- `),a={name:"jsonParserAgent",agent:e.jsonParserAgent,mock:e.jsonParserAgent,inputs:{type:"object",description:"The input object containing either a JSON string in 'text' or a raw JavaScript object in 'data'. One of them is required.",properties:{text:{type:"string",description:"A JSON string, possibly embedded in a Markdown code block. If provided, it will be parsed into a data object."},data:{anyOf:[{type:"object"},{type:"array"},{type:"string"},{type:"number"}],description:"Raw data to be converted into a formatted JSON string in the 'text' output."}},required:[],additionalProperties:!1},params:{type:"object",description:"No parameters are required for this agent.",properties:{},additionalProperties:!1},output:{type:"object",description:"Returns either a parsed data object (from 'text') or a formatted JSON string (from 'data').",properties:{text:{type:"string",description:"A pretty-printed JSON string generated from the 'data' input, if provided."},data:{anyOf:[{type:"object"},{type:"array"},{type:"string"},{type:"number"}],description:"Parsed data object from the 'text' input, or the original 'data' if no parsing was required."}},required:[],additionalProperties:!1},samples:[{inputs:{data:n},params:{},result:{text:JSON.stringify(n,null,2)}},{inputs:{text:JSON.stringify(n,null,2)},params:{},result:{data:n}},{inputs:{text:s},params:{},result:{data:n}},{inputs:{text:o},params:{},result:{data:n}},{inputs:{text:i},params:{},result:{data:n}}],description:"Template agent",category:["string"],author:"Satoshi Nakajima",repository:"https://github.com/receptron/graphai",source:"https://github.com/receptron/graphai/blob/main/agents/vanilla_agents/src/string_agents/json_parser_agent.ts",package:"@graphai/vanilla",license:"MIT"};e.default=a})(wl)),wl}var El={},fp;function NT(){return fp||(fp=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.stringCaseVariantsAgent=void 0;const t=async({namedInputs:r,params:s})=>{const{suffix:o}=s,i=r.text.trim().replace(/[\s-_]+/g," ").toLowerCase().split(" ");o&&i[i.length-1]!==o&&i.push(o);const a=i.join(" "),l=i.map((d,p)=>p===0?d:d.charAt(0).toUpperCase()+d.slice(1)).join(""),u=a.replace(/\s+/g,"_"),c=a.replace(/\s+/g,"-");return{lowerCamelCase:l,snakeCase:u,kebabCase:c,normalized:a}};e.stringCaseVariantsAgent=t;const n={name:"stringCaseVariantsAgent",agent:e.stringCaseVariantsAgent,mock:e.stringCaseVariantsAgent,inputs:{type:"object",properties:{text:{type:"string",description:"The input string to be transformed into various casing styles."}},required:["text"],additionalProperties:!1},params:{type:"object",properties:{suffix:{type:"string",description:"An optional suffix to append to the input string before transforming cases."}},additionalProperties:!1},output:{type:"object",properties:{kebabCase:{type:"string",description:"The input string converted to kebab-case (e.g., 'this-is-a-pen')."},snakeCase:{type:"string",description:"The input string converted to snake_case (e.g., 'this_is_a_pen')."},lowerCamelCase:{type:"string",description:"The input string converted to lowerCamelCase (e.g., 'thisIsAPen')."},normalized:{type:"string",description:"The original string, optionally appended with the suffix, in lowercase with normalized spacing."}},required:["kebabCase","snakeCase","lowerCamelCase","normalized"],additionalProperties:!1},samples:[{inputs:{text:"this is a pen"},params:{},result:{kebabCase:"this-is-a-pen",lowerCamelCase:"thisIsAPen",normalized:"this is a pen",snakeCase:"this_is_a_pen"}},{inputs:{text:"string case variants"},params:{suffix:"agent"},result:{kebabCase:"string-case-variants-agent",lowerCamelCase:"stringCaseVariantsAgent",normalized:"string case variants agent",snakeCase:"string_case_variants_agent"}}],description:"Format String Cases agent",category:["string"],author:"Receptron team",repository:"https://github.com/receptron/graphai",source:"https://github.com/receptron/graphai/blob/main/agents/vanilla_agents/src/string_agents/string_case_variants_agent.ts",package:"@graphai/vanilla",license:"MIT"};e.default=n})(El)),El}var Hi={},Tl={},Pl={},pp;function mb(){return pp||(pp=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.nestedAgent=e.nestedAgentGenerator=void 0;const t=Oe(),n=(o,i)=>async a=>{const{namedInputs:l,log:u,debugInfo:c,params:d,forNestedGraph:p}=a;(0,t.assert)(!!p,"Please update graphai to 0.5.19 or higher");const{agents:g,graphOptions:y,onLogCallback:_,callbacks:b}=p,{taskManager:m}=y,v=d.supressError??!1;if(m){const w=m.getStatus(!1);(0,t.assert)(w.concurrency>w.running,`nestedAgent: Concurrency is too low: ${w.concurrency}`)}(0,t.assert)(!!o,"nestedAgent: graph is required");const{nodes:A}=o,S=Object.keys(A).reduce((w,I)=>{const L=A[I];if("agent"in L)w[I]=L;else{const{value:H,update:B,isResult:F,console:j}=L;w[I]={value:H,update:B,isResult:F,console:j}}return w},{}),P={...o,nodes:S,version:t.graphDataLatestVersion},E=Object.keys(l);E.length>0&&E.forEach(w=>{P.nodes[w]===void 0?P.nodes[w]={value:l[w]}:l[w]!==void 0&&(P.nodes[w].value=l[w])});try{P.version===void 0&&c.version&&(P.version=c.version);const w=new t.GraphAI(P,g||{},y);l.loopCount&&w.setLoopCount(l.loopCount),_&&(w.onLogCallback=_),b&&(w.callbacks=b),c.subGraphs.set(w.graphId,w);const I=await w.run(!1);return c.subGraphs.delete(w.graphId),u?.push(...w.transactionLogs()),i&&i.resultNodeId?I[i.resultNodeId]:I}catch(w){if(w instanceof Error&&v)return{onError:{message:w.message,error:w}};throw w}};e.nestedAgentGenerator=n;const r=async o=>{const{forNestedGraph:i,params:a}=o,{graphData:l}=i??{graphData:{nodes:{}}};return(0,t.assert)(!!l,"No GraphData"),await(0,e.nestedAgentGenerator)(l,a)(o)};e.nestedAgent=r;const s={name:"nestedAgent",agent:e.nestedAgent,mock:e.nestedAgent,samples:[{inputs:{message:"hello"},params:{},result:{test:["hello"]},graph:{nodes:{test:{agent:"copyAgent",params:{namedKey:"messages"},inputs:{messages:[":message"]},isResult:!0}}}},{inputs:{message:"hello"},params:{resultNodeId:"test"},result:["hello"],graph:{nodes:{test:{agent:"copyAgent",params:{namedKey:"messages"},inputs:{messages:[":message"]},isResult:!0}}}},{inputs:{loopCount:5},params:{resultNodeId:"test"},result:4,graph:{nodes:{test:{agent:"copyAgent",params:{namedKey:"count"},inputs:{count:"@loop"},isResult:!0}}}}],description:"nested Agent",category:["graph"],author:"Receptron team",repository:"https://github.com/receptron/graphai",source:"https://github.com/receptron/graphai/blob/main/agents/vanilla_agents/src/graph_agents/nested_agent.ts",package:"@graphai/vanilla",license:"MIT"};e.default=s})(Pl)),Pl}var hp;function FT(){return hp||(hp=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.nestedAgentGenerator=void 0;var t=mb();Object.defineProperty(e,"nestedAgentGenerator",{enumerable:!0,get:function(){return t.nestedAgentGenerator}})})(Tl)),Tl}var gp;function kT(){if(gp)return Hi;gp=1,Object.defineProperty(Hi,"__esModule",{value:!0});const e=FT(),n={version:Oe().graphDataLatestVersion,nodes:{newText:{value:""},oldText:{value:""},isNewText:{if:":newText",agent:"copyAgent",inputs:{text:":newText"}},isOldText:{unless:":newText",agent:"copyAgent",inputs:{text:":oldText"}},updatedText:{agent:"copyAgent",anyInput:!0,inputs:{text:[":isNewText.text",":isOldText.text"]}},resultText:{isResult:!0,agent:"copyAgent",anyInput:!0,inputs:{text:":updatedText.text.$0"}}}},r=(0,e.nestedAgentGenerator)(n,{resultNodeId:"resultText"}),s={name:"stringUpdateTextAgent",agent:r,mock:r,inputs:{type:"object",properties:{newText:{type:"string",description:"The new text to use if provided and not empty."},oldText:{type:"string",description:"The fallback text used if 'newText' is empty or not provided."}},additionalProperties:!1},params:{type:"object",description:"No parameters are used in this agent.",properties:{},additionalProperties:!1},output:{type:"object",properties:{text:{type:"string",description:"The resulting text. It is either the value of 'newText' if non-empty, otherwise 'oldText', or an empty string if both are missing."}},required:["text"],additionalProperties:!1},samples:[{inputs:{newText:"new",oldText:"old"},params:{},result:{text:"new"}},{inputs:{newText:"",oldText:"old"},params:{},result:{text:"old"}},{inputs:{},params:{},result:{text:""}},{inputs:{oldText:"old"},params:{},result:{text:"old"}}],description:"",category:[],author:"",repository:"",source:"https://github.com/receptron/graphai/blob/main/agents/vanilla_agents/src/string_agents/string_update_text_agent.ts",package:"@graphai/vanilla",tools:[],license:"",hasGraphData:!0};return Hi.default=s,Hi}var Il={},mp;function OT(){return mp||(mp=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.consoleAgent=void 0;const t=async({namedInputs:r})=>{const{text:s}=r;return console.info(s),{text:s}};e.consoleAgent=t;const n={name:"consoleAgent",agent:e.consoleAgent,mock:e.consoleAgent,inputs:{type:"object",properties:{text:{type:"string",description:"text"}}},output:{type:"object",properties:{text:{type:"string",description:"text"}}},samples:[{inputs:{text:"hello"},params:{},result:{text:"hello"}}],description:"Just text to console.info",category:["string"],author:"Receptron team",repository:"https://github.com/receptron/graphai",source:"https://github.com/receptron/graphai/blob/main/agents/vanilla_agents/src/string_agents/console_agent.ts",package:"@graphai/vanilla",license:"MIT"};e.default=n})(Il)),Il}var _p;function xT(){if(_p)return We;_p=1;var e=We&&We.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(We,"__esModule",{value:!0}),We.consoleAgent=We.stringUpdateTextAgent=We.stringCaseVariantsAgent=We.jsonParserAgent=We.stringTemplateAgent=We.stringSplitterAgent=void 0;const t=e(CT());We.stringSplitterAgent=t.default;const n=e(RT());We.stringTemplateAgent=n.default;const r=e(MT());We.jsonParserAgent=r.default;const s=e(NT());We.stringCaseVariantsAgent=s.default;const o=e(kT());We.stringUpdateTextAgent=o.default;const i=e(OT());return We.consoleAgent=i.default,We}var Ve={},Cl={},Vn={},Rl={},yp;function DT(){return yp||(yp=1,Object.defineProperty(Rl,"__esModule",{value:!0})),Rl}var vp;function it(){return vp||(vp=1,(function(e){var t=Vn&&Vn.__createBinding||(Object.create?(function(l,u,c,d){d===void 0&&(d=c);var p=Object.getOwnPropertyDescriptor(u,c);(!p||("get"in p?!u.__esModule:p.writable||p.configurable))&&(p={enumerable:!0,get:function(){return u[c]}}),Object.defineProperty(l,d,p)}):(function(l,u,c,d){d===void 0&&(d=c),l[d]=u[c]})),n=Vn&&Vn.__exportStar||function(l,u){for(var c in l)c!=="default"&&!Object.prototype.hasOwnProperty.call(u,c)&&t(u,l,c)};Object.defineProperty(e,"__esModule",{value:!0}),e.isNull=e.arrayValidate=e.isNamedInputs=e.sample2GraphData=void 0;const r=Oe();n(DT(),e);const s=(l,u)=>{const c={},d=Array.isArray(l.inputs)?(Array.from(l.inputs.keys()).forEach(g=>{c["sampleInput"+g]={value:l.inputs[g]}}),Object.keys(c).map(g=>":"+g)):(c.sampleInput={value:l.inputs},Object.keys(l.inputs).reduce((g,y)=>(g[y]=":sampleInput."+y,g),{}));return c.node={isResult:!0,agent:u,params:l.params,inputs:d,graph:l.graph},{version:.5,nodes:c}};e.sample2GraphData=s;const o=l=>Object.keys(l||{}).length>0;e.isNamedInputs=o;const i=(l,u,c="")=>{(0,r.assert)((0,e.isNamedInputs)(u),`${l}: namedInputs is UNDEFINED!`+c),(0,r.assert)(!!u.array,`${l}: namedInputs.array is UNDEFINED!`+c),(0,r.assert)(Array.isArray(u.array),`${l}: namedInputs.array is not Array.`+c)};e.arrayValidate=i;const a=l=>l==null;e.isNull=a})(Vn)),Vn}var bp;function qT(){return bp||(bp=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.pushAgent=void 0;const t=Oe(),n=it(),r=async({namedInputs:o,params:i})=>{const a=" Set inputs: { array: :arrayNodeId, item: :itemNodeId }";(0,n.arrayValidate)("pushAgent",o,a);const{item:l,items:u,array:c,...d}=o;(0,t.assert)(l!==void 0||u!==void 0,"pushAgent: namedInputs.item and namedInputs.items are UNDEFINED!"+a),(0,t.assert)(u===void 0||Array.isArray(u),"pushAgent: namedInputs.items is not array!");const p=c.map(g=>g);return l!==void 0&&p.push(l),u&&u.forEach(g=>{p.push(g)}),i.arrayKey?{...d,[i.arrayKey]:p}:{...d,array:p}};e.pushAgent=r;const s={name:"pushAgent",agent:e.pushAgent,mock:e.pushAgent,inputs:{type:"object",properties:{array:{type:"array",description:"the array to push an item to"},item:{anyOf:[{type:"string"},{type:"integer"},{type:"object"},{type:"array"},{type:"boolean"}],description:"the item push into the array"},items:{type:"array",description:"items push into the array"}},required:["array"]},output:{type:"object",properties:{array:{type:"array"}}},samples:[{inputs:{array:[1,2],item:3},params:{},result:{array:[1,2,3]}},{inputs:{array:[!0,!1],item:!1},params:{},result:{array:[!0,!1,!1]}},{inputs:{array:[1,2],item:3,data:{example:"hello"}},params:{},result:{array:[1,2,3],data:{example:"hello"}}},{inputs:{array:[{apple:1}],item:{lemon:2}},params:{},result:{array:[{apple:1},{lemon:2}]}},{inputs:{array:[{apple:1}],items:[{lemon:2},{banana:3}]},params:{},result:{array:[{apple:1},{lemon:2},{banana:3}]}},{inputs:{array:[1,2],item:3},params:{arrayKey:"test"},result:{test:[1,2,3]}}],description:"push Agent",category:["array"],cacheType:"pureAgent",author:"Receptron team",repository:"https://github.com/receptron/graphai",source:"https://github.com/receptron/graphai/blob/main/agents/vanilla_agents/src/array_agents/push_agent.ts",package:"@graphai/vanilla",license:"MIT"};e.default=s})(Cl)),Cl}var Ml={},Ap;function LT(){return Ap||(Ap=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.popAgent=void 0;const t=it(),n=async({namedInputs:s})=>{(0,t.arrayValidate)("popAgent",s);const o=[...s.array],i=o.pop();return{array:o,item:i}};e.popAgent=n;const r={name:"popAgent",agent:e.popAgent,mock:e.popAgent,inputs:{type:"object",properties:{array:{type:"array",description:"the array to pop an item from"}},required:["array"]},output:{type:"object",properties:{item:{anyOf:[{type:"string"},{type:"integer"},{type:"object"},{type:"array"}],description:"the item popped from the array"},array:{type:"array",description:"the remaining array"}}},samples:[{inputs:{array:[1,2,3]},params:{},result:{array:[1,2],item:3}},{inputs:{array:["a","b","c"]},params:{},result:{array:["a","b"],item:"c"}},{inputs:{array:[1,2,3],array2:["a","b","c"]},params:{},result:{array:[1,2],item:3}}],description:"Pop Agent",category:["array"],cacheType:"pureAgent",author:"Receptron team",repository:"https://github.com/receptron/graphai",source:"https://github.com/receptron/graphai/blob/main/agents/vanilla_agents/src/array_agents/pop_agent.ts",package:"@graphai/vanilla",license:"MIT"};e.default=r})(Ml)),Ml}var Nl={},Sp;function UT(){return Sp||(Sp=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.shiftAgent=void 0;const t=it(),n=async({namedInputs:s})=>{(0,t.arrayValidate)("shiftAgent",s);const o=s.array.map(a=>a),i=o.shift();return{array:o,item:i}};e.shiftAgent=n;const r={name:"shiftAgent",agent:e.shiftAgent,mock:e.shiftAgent,inputs:{type:"object",properties:{array:{type:"array",description:"the array to shift an item from"}},required:["array"]},output:{type:"object",properties:{item:{anyOf:[{type:"string"},{type:"integer"},{type:"object"},{type:"array"}],description:"the item shifted from the array"},array:{type:"array",description:"the remaining array"}}},samples:[{inputs:{array:[1,2,3]},params:{},result:{array:[2,3],item:1}},{inputs:{array:["a","b","c"]},params:{},result:{array:["b","c"],item:"a"}}],description:"shift Agent",category:["array"],cacheType:"pureAgent",author:"Receptron team",repository:"https://github.com/receptron/graphai",source:"https://github.com/receptron/graphai/blob/main/agents/vanilla_agents/src/array_agents/shift_agent.ts",package:"@graphai/vanilla",license:"MIT"};e.default=r})(Nl)),Nl}var Fl={},wp;function GT(){return wp||(wp=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.arrayFlatAgent=void 0;const t=it(),n=async({namedInputs:s,params:o})=>{(0,t.arrayValidate)("arrayFlatAgent",s);const i=o.depth??1;return{array:s.array.map(l=>l).flat(i)}};e.arrayFlatAgent=n;const r={name:"arrayFlatAgent",agent:e.arrayFlatAgent,mock:e.arrayFlatAgent,inputs:{type:"object",properties:{array:{type:"array",description:"The array to be flattened"}},required:["array"]},output:{type:"object",properties:{array:{type:"array",description:"flattened array"}}},params:{type:"object",properties:{depth:{type:"number",description:"flattening depth"}}},samples:[{inputs:{array:[[1],[2],[3]]},params:{},result:{array:[1,2,3]}},{inputs:{array:[[1],[2],[[3]]]},params:{},result:{array:[1,2,[3]]}},{inputs:{array:[[1],[2],[[3]]]},params:{depth:2},result:{array:[1,2,3]}},{inputs:{array:[["a"],["b"],["c"]]},params:{},result:{array:["a","b","c"]}}],description:"Array Flat Agent",category:["array"],author:"Receptron team",repository:"https://github.com/receptron/graphai",source:"https://github.com/receptron/graphai/blob/main/agents/vanilla_agents/src/array_agents/array_flat_agent.ts",package:"@graphai/vanilla",cacheType:"pureAgent",license:"MIT"};e.default=r})(Fl)),Fl}var kl={},Ep;function VT(){return Ep||(Ep=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.arrayJoinAgent=void 0;const t=it(),n=async({namedInputs:s,params:o})=>{(0,t.arrayValidate)("arrayJoinAgent",s);const i=o.separator??"",{flat:a}=o;return{text:a?s.array.flat(a).join(i):s.array.join(i)}};e.arrayJoinAgent=n;const r={name:"arrayJoinAgent",agent:e.arrayJoinAgent,mock:e.arrayJoinAgent,inputs:{type:"object",properties:{array:{type:"array",description:"array join"}},required:["array"]},params:{type:"object",properties:{separator:{type:"string",description:"array join separator"},flat:{type:"number",description:"array flat depth"}}},output:{type:"object",properties:{text:{type:"string",description:"joined text"}}},samples:[{inputs:{array:[[1],[2],[3]]},params:{},result:{text:"123"}},{inputs:{array:[[1],[2],[[3]]]},params:{},result:{text:"123"}},{inputs:{array:[["a"],["b"],["c"]]},params:{},result:{text:"abc"}},{inputs:{array:[[1],[2],[3]]},params:{separator:"|"},result:{text:"1|2|3"}},{inputs:{array:[[[1]],[[2],[3]]]},params:{separator:"|"},result:{text:"1|2,3"}},{inputs:{array:[[[1]],[[2],[3]]]},params:{separator:"|",flat:1},result:{text:"1|2|3"}},{inputs:{array:[[[[1]],[[2],[3]]]]},params:{separator:"|",flat:1},result:{text:"1|2,3"}},{inputs:{array:[[[[1]],[[2],[3]]]]},params:{separator:"|",flat:2},result:{text:"1|2|3"}}],description:"Array Join Agent",category:["array"],cacheType:"pureAgent",author:"Receptron team",repository:"https://github.com/receptron/graphai",source:"https://github.com/receptron/graphai/blob/main/agents/vanilla_agents/src/array_agents/array_join_agent.ts",package:"@graphai/vanilla",license:"MIT"};e.default=r})(kl)),kl}var Ol={},Tp;function BT(){return Tp||(Tp=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.arrayToObjectAgent=void 0;const t=Oe(),n=it(),r=async({params:o,namedInputs:i})=>{(0,t.assert)((0,n.isNamedInputs)(i),"arrayToObjectAgent: namedInputs is UNDEFINED!");const{items:a}=i,{key:l}=o;return(0,t.assert)(a!==void 0&&Array.isArray(a),"arrayToObjectAgent: namedInputs.items is not array!"),(0,t.assert)(l!=null,"arrayToObjectAgent: params.key is UNDEFINED!"),i.items.reduce((u,c)=>(u[c[l]]=c,u),{})};e.arrayToObjectAgent=r;const s={name:"arrayToObjectAgent",agent:e.arrayToObjectAgent,mock:e.arrayToObjectAgent,inputs:{type:"object",properties:{items:{type:"array",description:"the array to pop an item from"}},required:["items"]},output:{type:"object",properties:{anyOf:[{type:"string"},{type:"integer"},{type:"object"},{type:"array"}],description:"the item popped from the array"}},samples:[{inputs:{items:[{id:1,data:"a"},{id:2,data:"b"}]},params:{key:"id"},result:{1:{id:1,data:"a"},2:{id:2,data:"b"}}}],description:"Array To Object Agent",category:["array"],cacheType:"pureAgent",author:"Receptron team",repository:"https://github.com/receptron/graphai",source:"https://github.com/receptron/graphai/blob/main/agents/vanilla_agents/src/array_agents/array_to_object.ts",package:"@graphai/vanilla",license:"MIT"};e.default=s})(Ol)),Ol}var xl={},Pp;function HT(){return Pp||(Pp=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.arrayFindFirstExistsAgent=void 0;const t=Oe(),n=it(),r=async({namedInputs:o})=>((0,n.arrayValidate)("arrayFindFirstExistsAgent",o),o.array.find(i=>!(0,t.isNull)(i)));e.arrayFindFirstExistsAgent=r;const s={name:"arrayFindFirstExistsAgent",agent:e.arrayFindFirstExistsAgent,mock:e.arrayFindFirstExistsAgent,inputs:{type:"object",properties:{array:{type:"array",description:"The array to be find"}},required:["array"]},output:{type:"object"},params:{},samples:[{inputs:{array:[null,2]},params:{},result:2},{inputs:{array:[void 0,null,3]},params:{},result:3},{inputs:{array:[void 0,null,0]},result:0,params:{}}],description:"Array Flat Agent",category:["array"],author:"Receptron team",repository:"https://github.com/receptron/graphai",source:"https://github.com/receptron/graphai/blob/main/agents/vanilla_agents/src/array_agents/array_flat_agent.ts",package:"@graphai/vanilla",cacheType:"pureAgent",license:"MIT"};e.default=s})(xl)),xl}var Ip;function JT(){if(Ip)return Ve;Ip=1;var e=Ve&&Ve.__importDefault||function(l){return l&&l.__esModule?l:{default:l}};Object.defineProperty(Ve,"__esModule",{value:!0}),Ve.arrayFindFirstExistsAgent=Ve.arrayToObjectAgent=Ve.arrayJoinAgent=Ve.arrayFlatAgent=Ve.shiftAgent=Ve.popAgent=Ve.pushAgent=void 0;const t=e(qT());Ve.pushAgent=t.default;const n=e(LT());Ve.popAgent=n.default;const r=e(UT());Ve.shiftAgent=r.default;const s=e(GT());Ve.arrayFlatAgent=s.default;const o=e(VT());Ve.arrayJoinAgent=o.default;const i=e(BT());Ve.arrayToObjectAgent=i.default;const a=e(HT());return Ve.arrayFindFirstExistsAgent=a.default,Ve}var nn={},Dl={},Cp;function jT(){return Cp||(Cp=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.dotProductAgent=void 0;const t=Oe(),n=async({namedInputs:s})=>{(0,t.assert)(!!s,"dotProductAgent: namedInputs is UNDEFINED!");const o=s.matrix,i=s.vector;if(o[0].length!=i.length)throw new Error(`dotProduct: Length of vectors do not match. ${o[0].length}, ${i.length}`);return o.map(l=>l.reduce((u,c,d)=>u+c*i[d],0))};e.dotProductAgent=n;const r={name:"dotProductAgent",agent:e.dotProductAgent,mock:e.dotProductAgent,inputs:{type:"object",properties:{matrix:{type:"array",description:"A two-dimensional array of numbers. Each inner array represents a vector to be compared.",items:{type:"array",items:{type:"number",description:"A numeric value within a vector."},description:"A vector of numbers (row in the matrix)."}},vector:{type:"array",description:"A single vector of numbers to compute dot products with each vector in the matrix.",items:{type:"number",description:"A numeric component of the target vector."}}},required:["matrix","vector"],additionalProperties:!1},params:{type:"object",description:"No parameters are used in this agent.",properties:{},additionalProperties:!1},output:{type:"array",description:"An array of numbers representing the dot products between each vector in 'matrix' and the input 'vector'.",items:{type:"number",description:"The result of a dot product between a matrix row and the input vector."}},samples:[{inputs:{matrix:[[1,2],[3,4],[5,6]],vector:[3,2]},params:{},result:[7,17,27]},{inputs:{matrix:[[1,2],[2,3]],vector:[1,2]},params:{},result:[5,8]}],description:"dotProduct Agent",category:["matrix"],author:"Receptron team",repository:"https://github.com/receptron/graphai",source:"https://github.com/receptron/graphai/blob/main/agents/vanilla_agents/src/matrix_agents/dot_product_agent.ts",package:"@graphai/vanilla",license:"MIT"};e.default=r})(Dl)),Dl}var ql={},Rp;function WT(){return Rp||(Rp=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.sortByValuesAgent=void 0;const t=Oe(),n=async({params:s,namedInputs:o})=>{(0,t.assert)(!!o,"sortByValue: namedInputs is UNDEFINED!"),(0,t.assert)(!!o.array,"sortByValue: namedInputs.array is UNDEFINED!"),(0,t.assert)(!!o.values,"sortByValue: namedInputs.values is UNDEFINED!");const i=s?.assendant??!1?-1:1,a=o.array,l=o.values;return a.map((d,p)=>({item:d,value:l[p]})).sort((d,p)=>(p.value-d.value)*i).map(d=>d.item)};e.sortByValuesAgent=n;const r={name:"sortByValuesAgent",agent:e.sortByValuesAgent,mock:e.sortByValuesAgent,inputs:{type:"object",properties:{array:{type:"array",description:"The array of items to be sorted. Each item will be paired with a corresponding numeric value from the 'values' array."},values:{type:"array",description:"An array of numeric values used to determine the sort order of the 'array' items. Must be the same length as 'array'.",items:{type:"number"}}},required:["array","values"],additionalProperties:!1},params:{type:"object",properties:{assendant:{type:"boolean",description:"If true, sorts in ascending order; otherwise, in descending order (default)."}},additionalProperties:!1},output:{type:"array",description:"A new array where items from 'array' are sorted based on their corresponding values in 'values'.",items:{type:"any"}},samples:[{inputs:{array:["banana","orange","lemon","apple"],values:[2,5,6,4]},params:{},result:["lemon","orange","apple","banana"]},{inputs:{array:["banana","orange","lemon","apple"],values:[2,5,6,4]},params:{assendant:!0},result:["banana","apple","orange","lemon"]}],description:"sortByValues Agent",category:["matrix"],author:"Receptron team",repository:"https://github.com/receptron/graphai",source:"https://github.com/receptron/graphai/blob/main/agents/vanilla_agents/src/matrix_agents/sort_by_values_agent.ts",package:"@graphai/vanilla",license:"MIT"};e.default=r})(ql)),ql}var Mp;function KT(){if(Mp)return nn;Mp=1;var e=nn&&nn.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(nn,"__esModule",{value:!0}),nn.sortByValuesAgent=nn.dotProductAgent=void 0;const t=e(jT());nn.dotProductAgent=t.default;const n=e(WT());return nn.sortByValuesAgent=n.default,nn}var Ke={},Ll={},Np;function $T(){return Np||(Np=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.echoAgent=void 0;const t=async({params:r,filterParams:s})=>r.filterParams?s:r;e.echoAgent=t;const n={name:"echoAgent",agent:e.echoAgent,mock:e.echoAgent,inputs:{type:"object",description:"This agent does not use inputs. Leave empty.",properties:{},additionalProperties:!1},params:{type:"object",description:"Any parameters you want to echo back. If 'filterParams' is true, only filtered parameters will be returned.",properties:{filterParams:{type:"boolean",description:"If true, returns 'filterParams' instead of the full 'params'."}},additionalProperties:!0},output:{type:"object",description:"Returns the full 'params' object or the 'filterParams' object if 'filterParams' is set to true.",additionalProperties:!0},samples:[{inputs:{},params:{text:"this is test"},result:{text:"this is test"}},{inputs:{},params:{text:"If you add filterParams option, it will respond to filterParams",filterParams:!0},result:{}}],description:"Echo agent",category:["test"],cacheType:"pureAgent",author:"Satoshi Nakajima",repository:"https://github.com/receptron/graphai",source:"https://github.com/receptron/graphai/blob/main/agents/vanilla_agents/src/test_agents/echo_agent.ts",package:"@graphai/vanilla",license:"MIT"};e.default=n})(Ll)),Ll}var Ul={},Fp;function YT(){return Fp||(Fp=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.countingAgent=void 0;const t=async({params:r})=>({list:new Array(r.count).fill(void 0).map((s,o)=>o)});e.countingAgent=t;const n={name:"countingAgent",agent:e.countingAgent,mock:e.countingAgent,inputs:{type:"object",description:"This agent does not require any inputs. Leave empty.",properties:{},additionalProperties:!1},params:{type:"object",description:"Parameter that defines how many numbers to generate, starting from 0.",properties:{count:{type:"integer",minimum:0,description:"The number of integers to generate, starting from 0 up to count - 1."}},required:["count"],additionalProperties:!1},output:{type:"object",description:"An object containing a list of sequential integers.",properties:{list:{type:"array",description:"An array of integers from 0 to count - 1.",items:{type:"integer"}}},required:["list"],additionalProperties:!1},samples:[{inputs:{},params:{count:4},result:{list:[0,1,2,3]}}],description:"Counting agent",category:["test"],cacheType:"pureAgent",author:"Receptron team",repository:"https://github.com/receptron/graphai",source:"https://github.com/receptron/graphai/blob/main/agents/vanilla_agents/src/test_agents/counting_agent.ts",package:"@graphai/vanilla",license:"MIT"};e.default=n})(Ul)),Ul}var Gl={},kp;function zT(){return kp||(kp=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.copyMessageAgent=void 0;const t=async({params:r})=>({messages:new Array(r.count).fill(void 0).map(()=>r.message)});e.copyMessageAgent=t;const n={name:"copyMessageAgent",agent:e.copyMessageAgent,mock:e.copyMessageAgent,inputs:{type:"object",description:"This agent does not use any inputs. Leave empty.",properties:{},additionalProperties:!1},params:{type:"object",description:"Parameters to define the message and how many times to repeat it.",properties:{count:{type:"integer",minimum:1,description:"The number of times the message should be duplicated in the array."},message:{type:"string",description:"The message string to be repeated."}},required:["count","message"],additionalProperties:!1},output:{type:"object",description:"An object containing the repeated messages.",properties:{messages:{type:"array",description:"An array of repeated message strings.",items:{type:"string"}}},required:["messages"],additionalProperties:!1},samples:[{inputs:{},params:{count:4,message:"hello"},result:{messages:["hello","hello","hello","hello"]}}],description:"CopyMessage agent",category:["test"],cacheType:"pureAgent",author:"Receptron team",repository:"https://github.com/receptron/graphai",source:"https://github.com/receptron/graphai/blob/main/agents/vanilla_agents/src/test_agents/copy_message_agent.ts",package:"@graphai/vanilla",license:"MIT"};e.default=n})(Gl)),Gl}var Vl={},Op;function XT(){return Op||(Op=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.copy2ArrayAgent=void 0;const t=Oe(),n=it(),r=async({namedInputs:o,params:i})=>{(0,t.assert)((0,n.isNamedInputs)(o),"copy2ArrayAgent: namedInputs is UNDEFINED!");const a=o.item?o.item:o;return new Array(i.count).fill(void 0).map(()=>a)};e.copy2ArrayAgent=r;const s={name:"copy2ArrayAgent",agent:e.copy2ArrayAgent,mock:e.copy2ArrayAgent,inputs:{type:"object",description:"The input item to be duplicated. Can be provided as 'item' or as a free-form object.",properties:{item:{description:"The item to be copied into each element of the resulting array.",anyOf:[{type:"object"},{type:"string"},{type:"number"},{type:"array"},{type:"boolean"}]}},additionalProperties:!0},params:{type:"object",description:"Parameters controlling the number of copies to return.",properties:{count:{type:"integer",description:"The number of times to copy the input item into the output array.",minimum:1}},required:["count"],additionalProperties:!1},output:{type:"array",description:"An array of 'count' copies of the input item.",items:{description:"A duplicated copy of the input item.",anyOf:[{type:"object"},{type:"string"},{type:"number"},{type:"array"},{type:"boolean"}]}},samples:[{inputs:{item:{message:"hello"}},params:{count:10},result:[{message:"hello"},{message:"hello"},{message:"hello"},{message:"hello"},{message:"hello"},{message:"hello"},{message:"hello"},{message:"hello"},{message:"hello"},{message:"hello"}]},{inputs:{message:"hello"},params:{count:10},result:[{message:"hello"},{message:"hello"},{message:"hello"},{message:"hello"},{message:"hello"},{message:"hello"},{message:"hello"},{message:"hello"},{message:"hello"},{message:"hello"}]},{inputs:{item:"hello"},params:{count:10},result:["hello","hello","hello","hello","hello","hello","hello","hello","hello","hello"]}],description:"Copy2Array agent",category:["test"],cacheType:"pureAgent",author:"Receptron team",repository:"https://github.com/receptron/graphai",source:"https://github.com/receptron/graphai/blob/main/agents/vanilla_agents/src/test_agents/copy2array_agent.ts",package:"@graphai/vanilla",license:"MIT"};e.default=s})(Vl)),Vl}var Bl={},xp;function QT(){return xp||(xp=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.mergeNodeIdAgent=void 0;const t=it(),n=async({debugInfo:{nodeId:s},namedInputs:o})=>((0,t.arrayValidate)("mergeNodeIdAgent",o),o.array.reduce((a,l)=>({...a,...l}),{[s]:"hello"}));e.mergeNodeIdAgent=n;const r={name:"mergeNodeIdAgent",agent:e.mergeNodeIdAgent,mock:e.mergeNodeIdAgent,inputs:{type:"object",properties:{array:{type:"array",description:"An array of objects to be merged together into a single object. Each object represents a partial result or state.",items:{type:"object",description:"A single object containing key-value pairs to merge."}}},required:["array"],additionalProperties:!1},params:{type:"object",description:"This agent does not take any parameters. The object must be empty.",properties:{},additionalProperties:!1},samples:[{inputs:{array:[{message:"hello"}]},params:{},result:{message:"hello",test:"hello"}}],description:"merge node id agent",category:["test"],author:"Receptron team",repository:"https://github.com/receptron/graphai",source:"https://github.com/receptron/graphai/blob/main/agents/vanilla_agents/src/test_agents/merge_node_id_agent.ts",package:"@graphai/vanilla",license:"MIT"};e.default=r})(Bl)),Bl}var Hl={},Dp;function ZT(){return Dp||(Dp=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.streamMockAgent=void 0;const t=Oe(),n=async({params:s,filterParams:o,namedInputs:i})=>{const a=s.message??i.message??"";for await(const l of a.split(""))o.streamTokenCallback&&o.streamTokenCallback(l),await(0,t.sleep)(s.sleep||100);return{message:a}};e.streamMockAgent=n;const r={name:"streamMockAgent",agent:e.streamMockAgent,mock:e.streamMockAgent,inputs:{anyOf:[{type:"object",properties:{message:{type:"string",description:"streaming message"}}},{type:"array"}]},samples:[{inputs:{},params:{message:"this is params test"},result:{message:"this is params test"}},{inputs:{message:"this is named inputs test"},params:{},result:{message:"this is named inputs test"}}],description:"Stream mock agent",category:["test"],author:"Isamu Arimoto",repository:"https://github.com/receptron/graphai",source:"https://github.com/receptron/graphai/blob/main/agents/vanilla_agents/src/test_agents/stream_mock_agent.ts",package:"@graphai/vanilla",license:"MIT",stream:!0};e.default=r})(Hl)),Hl}var qp;function eP(){if(qp)return Ke;qp=1;var e=Ke&&Ke.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(Ke,"__esModule",{value:!0}),Ke.streamMockAgent=Ke.mergeNodeIdAgent=Ke.copy2ArrayAgent=Ke.copyMessageAgent=Ke.countingAgent=Ke.echoAgent=void 0;const t=e($T());Ke.echoAgent=t.default;const n=e(YT());Ke.countingAgent=n.default;const r=e(zT());Ke.copyMessageAgent=r.default;const s=e(XT());Ke.copy2ArrayAgent=s.default;const o=e(QT());Ke.mergeNodeIdAgent=o.default;const i=e(ZT());return Ke.streamMockAgent=i.default,Ke}var rn={},Jl={},Lp;function tP(){return Lp||(Lp=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.mapAgent=void 0;const t=Oe(),n=async({params:s,namedInputs:o,log:i,debugInfo:a,forNestedGraph:l})=>{(0,t.assert)(!!l,"Please update graphai to 0.5.19 or higher");const{limit:u,resultAll:c,compositeResult:d,compositeResultKey:p,supressError:g,rowKey:y,expandKeys:_}=s,{agents:b,graphData:m,graphOptions:v,onLogCallback:A,callbacks:S}=l,{taskManager:P}=v;if(P){const B=P.getStatus();(0,t.assert)(B.concurrency>B.running,`mapAgent: Concurrency is too low: ${B.concurrency}`)}(0,t.assert)(!!o.rows,"mapAgent: rows property is required in namedInput"),(0,t.assert)(!!m,"mapAgent: graph is required");const E=o.rows.map(B=>B);u&&u<E.length&&(E.length=u);const w=y??"row",{nodes:I}=m,L={...m,nodes:{...I},version:t.graphDataLatestVersion},H=Object.keys(o);L.nodes.__mapIndex={},H.forEach(B=>{const F=B==="rows"?w:B;L.nodes[F]===void 0?L.nodes[F]={value:o[B]}:"agent"in L.nodes[F]||(L.nodes[F].value=o[B])});try{L.version===void 0&&a.version&&(L.version=a.version);const B=E.map((O,R)=>{const T=new t.GraphAI(L,b||{},{...v??{},mapIndex:R});return a.subGraphs.set(T.graphId,T),T.injectValue(w,O,"__mapAgent_inputs__"),T.injectValue("__mapIndex",R,"__mapAgent_inputs__"),_&&_.length>0&&_.map(M=>{T.injectValue(M,o[M]?.[R])}),A&&(T.onLogCallback=A),S&&(T.callbacks=S),T}),F=B.map(O=>O.run(c)),j=await Promise.all(F),U=Object.keys(j[0]);if(B.map(O=>{a.subGraphs.delete(O.graphId)}),i){const O=B.map((R,T)=>R.transactionLogs().map(M=>(M.mapIndex=T,M)));i.push(...O.flat())}if(d||p){const O=U.reduce((R,T)=>(R[T]=j.map(M=>M[T]),R),{});return p?O[p]:O}return j}catch(B){if(B instanceof Error&&g)return{onError:{message:B.message,error:B}};throw B}};e.mapAgent=n;const r={name:"mapAgent",agent:e.mapAgent,mock:e.mapAgent,samples:[{inputs:{rows:["apple","orange","banana","lemon"],color:["red","orange","yellow","yellow"]},params:{compositeResult:!0,expandKeys:["color"]},graph:{version:.5,nodes:{node2:{agent:"copyAgent",inputs:{a:":row",b:":color"},isResult:!0}}},result:{node2:[{a:"apple",b:"red"},{a:"orange",b:"orange"},{a:"banana",b:"yellow"},{a:"lemon",b:"yellow"}]}},{inputs:{rows:[1,2]},params:{},result:[{test:[1]},{test:[2]}],graph:{nodes:{test:{agent:"copyAgent",params:{namedKey:"rows"},inputs:{rows:[":row"]},isResult:!0}}}},{inputs:{rows:[1,2]},params:{rowKey:"myKey"},result:[{test:[1]},{test:[2]}],graph:{nodes:{test:{agent:"copyAgent",params:{namedKey:"rows"},inputs:{rows:[":myKey"]},isResult:!0}}}},{inputs:{rows:["apple","orange","banana","lemon","melon","pineapple","tomato"]},params:{},graph:{nodes:{node2:{agent:"stringTemplateAgent",params:{template:"I love ${word}."},inputs:{word:":row"},isResult:!0}}},result:[{node2:"I love apple."},{node2:"I love orange."},{node2:"I love banana."},{node2:"I love lemon."},{node2:"I love melon."},{node2:"I love pineapple."},{node2:"I love tomato."}]},{inputs:{rows:[{fruit:"apple"},{fruit:"orange"}]},params:{},graph:{nodes:{node2:{agent:"stringTemplateAgent",params:{template:"I love ${item}."},inputs:{item:":row.fruit"},isResult:!0}}},result:[{node2:"I love apple."},{node2:"I love orange."}]},{inputs:{rows:[{fruit:"apple"},{fruit:"orange"}],name:"You",verb:"like"},params:{},graph:{nodes:{node2:{agent:"stringTemplateAgent",params:{template:"${name} ${verb} ${fruit}."},inputs:{fruit:":row.fruit",name:":name",verb:":verb"},isResult:!0}}},result:[{node2:"You like apple."},{node2:"You like orange."}]},{inputs:{rows:[1,2]},params:{resultAll:!0},result:[{__mapIndex:0,test:[1],row:1},{__mapIndex:1,test:[2],row:2}],graph:{nodes:{test:{agent:"copyAgent",params:{namedKey:"rows"},inputs:{rows:[":row"]}}}}},{inputs:{rows:[1,2]},params:{resultAll:!0},result:[{__mapIndex:0,map:[{test:1},{test:1}],row:1,test:1},{__mapIndex:1,map:[{test:2},{test:2}],test:2,row:2}],graph:{nodes:{test:{agent:"copyAgent",params:{namedKey:"row"},inputs:{row:":row"}},map:{agent:"mapAgent",inputs:{rows:[":test",":test"]},graph:{nodes:{test:{isResult:!0,agent:"copyAgent",params:{namedKey:"row"},inputs:{row:":row"}}}}}}}},{inputs:{rows:[1,2]},params:{compositeResult:!0},result:{test:[[1],[2]]},graph:{nodes:{test:{agent:"copyAgent",params:{namedKey:"rows"},inputs:{rows:[":row"]},isResult:!0}}}},{inputs:{rows:["apple","orange","banana","lemon","melon","pineapple","tomato"]},params:{compositeResult:!0},graph:{nodes:{node2:{agent:"stringTemplateAgent",params:{template:"I love ${row}."},inputs:{row:":row"},isResult:!0}}},result:{node2:["I love apple.","I love orange.","I love banana.","I love lemon.","I love melon.","I love pineapple.","I love tomato."]}},{inputs:{rows:["apple","orange","banana","lemon","melon","pineapple","tomato"]},params:{compositeResult:!0,compositeResultKey:"node2"},graph:{nodes:{node2:{agent:"stringTemplateAgent",params:{template:"I love ${row}."},inputs:{row:":row"},isResult:!0}}},result:["I love apple.","I love orange.","I love banana.","I love lemon.","I love melon.","I love pineapple.","I love tomato."]},{inputs:{rows:[1,2]},params:{resultAll:!0,compositeResult:!0},result:{test:[[1],[2]],__mapIndex:[0,1],row:[1,2]},graph:{nodes:{test:{agent:"copyAgent",params:{namedKey:"rows"},inputs:{rows:[":row"]}}}}},{inputs:{rows:[1,2]},params:{resultAll:!0,compositeResult:!0},result:{__mapIndex:[0,1],test:[[1],[2]],map:[{test:[[[1]],[[1]]]},{test:[[[2]],[[2]]]}],row:[1,2]},graph:{nodes:{test:{agent:"copyAgent",params:{namedKey:"rows"},inputs:{rows:[":row"]}},map:{agent:"mapAgent",inputs:{rows:[":test",":test"]},params:{compositeResult:!0},graph:{nodes:{test:{isResult:!0,agent:"copyAgent",params:{namedKey:"rows"},inputs:{rows:[":row"]}}}}}}}}],description:"Map Agent",category:["graph"],author:"Receptron team",repository:"https://github.com/receptron/graphai",source:"https://github.com/receptron/graphai/blob/main/agents/vanilla_agents/src/graph_agents/map_agent.ts",package:"@graphai/vanilla",license:"MIT"};e.default=r})(Jl)),Jl}var Up;function nP(){if(Up)return rn;Up=1;var e=rn&&rn.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(rn,"__esModule",{value:!0}),rn.mapAgent=rn.nestedAgent=void 0;const t=e(mb());rn.nestedAgent=t.default;const n=e(tP());return rn.mapAgent=n.default,rn}var $e={},jl={},Gp;function rP(){return Gp||(Gp=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.totalAgent=void 0;const t=Oe(),n=it(),r=async({namedInputs:o,params:i})=>{const{flatResponse:a}=i;(0,t.assert)((0,n.isNamedInputs)(o),"totalAgent: namedInputs is UNDEFINED! Set inputs: { array: :arrayNodeId }"),(0,t.assert)(!!o?.array,"totalAgent: namedInputs.array is UNDEFINED! Set inputs: { array: :arrayNodeId }");const l=o.array.reduce((u,c)=>((Array.isArray(c)?c:[c]).forEach(p=>{Object.keys(p).forEach(g=>{const y=p[g];u[g]?u[g]+=y:u[g]=y})}),u),{});return a?l:{data:l}};e.totalAgent=r;const s={name:"totalAgent",agent:e.totalAgent,mock:e.totalAgent,inputs:{type:"object",properties:{array:{type:"array",description:"An array of objects or arrays of objects. Each inner object must have numeric values which will be aggregated by key.",items:{anyOf:[{type:"object",description:"A flat object containing numeric values to be summed."},{type:"array",items:{type:"object",description:"Nested array of objects, each containing numeric values to be summed."}}]}}},required:["array"],additionalProperties:!1},params:{type:"object",properties:{flatResponse:{type:"boolean",description:"If true, the result will be returned as a plain object (e.g., { a: 6 }); otherwise, wrapped in { data: {...} }."}},additionalProperties:!1},output:{type:"object"},samples:[{inputs:{array:[{a:1},{a:2},{a:3}]},params:{},result:{data:{a:6}}},{inputs:{array:[[{a:1,b:-1},{c:10}],[{a:2,b:-1}],[{a:3,b:-2},{d:-10}]]},params:{},result:{data:{a:6,b:-4,c:10,d:-10}}},{inputs:{array:[{a:1}]},params:{},result:{data:{a:1}}},{inputs:{array:[{a:1},{a:2}]},params:{},result:{data:{a:3}}},{inputs:{array:[{a:1},{a:2},{a:3}]},params:{},result:{data:{a:6}}},{inputs:{array:[{a:1,b:1},{a:2,b:2},{a:3,b:0}]},params:{},result:{data:{a:6,b:3}}},{inputs:{array:[{a:1},{a:2,b:2},{a:3,b:0}]},params:{},result:{data:{a:6,b:2}}},{inputs:{array:[{a:1},{a:2},{a:3}]},params:{flatResponse:!0},result:{a:6}},{inputs:{array:[[{a:1,b:-1},{c:10}],[{a:2,b:-1}],[{a:3,b:-2},{d:-10}]]},params:{flatResponse:!0},result:{a:6,b:-4,c:10,d:-10}},{inputs:{array:[{a:1}]},params:{flatResponse:!0},result:{a:1}},{inputs:{array:[{a:1},{a:2}]},params:{flatResponse:!0},result:{a:3}},{inputs:{array:[{a:1},{a:2},{a:3}]},params:{flatResponse:!0},result:{a:6}},{inputs:{array:[{a:1,b:1},{a:2,b:2},{a:3,b:0}]},params:{flatResponse:!0},result:{a:6,b:3}},{inputs:{array:[{a:1},{a:2,b:2},{a:3,b:0}]},params:{flatResponse:!0},result:{a:6,b:2}}],description:"Returns the sum of input values",category:["data"],author:"Satoshi Nakajima",repository:"https://github.com/snakajima/graphai",source:"https://github.com/receptron/graphai/blob/main/agents/vanilla_agents/src/data_agents/total_agent.ts",package:"@graphai/vanilla",license:"MIT"};e.default=s})(jl)),jl}var Wl={},Vp;function sP(){return Vp||(Vp=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.dataSumTemplateAgent=void 0;const t=Oe(),n=it(),r=async({namedInputs:o,params:i})=>{const{flatResponse:a}=i;(0,t.assert)((0,n.isNamedInputs)(o),"dataSumTemplateAgent: namedInputs is UNDEFINED! Set inputs: { array: :arrayNodeId }"),(0,t.assert)(!!o?.array,"dataSumTemplateAgent: namedInputs.array is UNDEFINED! Set inputs: { array: :arrayNodeId }");const l=o.array.reduce((u,c)=>u+c,0);return a?l:{result:l}};e.dataSumTemplateAgent=r;const s={name:"dataSumTemplateAgent",agent:e.dataSumTemplateAgent,mock:e.dataSumTemplateAgent,inputs:{type:"object",properties:{array:{type:"array",description:"the array of numbers to calculate the sum of",items:{type:"integer"}}},required:["array"]},output:{type:"number"},samples:[{inputs:{array:[1]},params:{},result:{result:1}},{inputs:{array:[1,2]},params:{},result:{result:3}},{inputs:{array:[1,2,3]},params:{},result:{result:6}},{inputs:{array:[1]},params:{flatResponse:!0},result:1},{inputs:{array:[1,2]},params:{flatResponse:!0},result:3},{inputs:{array:[1,2,3]},params:{flatResponse:!0},result:6}],description:"Returns the sum of input values",category:["data"],author:"Satoshi Nakajima",repository:"https://github.com/receptron/graphai",source:"https://github.com/receptron/graphai/blob/main/agents/vanilla_agents/src/data_agents/data_sum_template_agent.ts",package:"@graphai/vanilla",license:"MIT"};e.default=s})(Wl)),Wl}var Kl={},Bp;function oP(){return Bp||(Bp=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.propertyFilterAgent=void 0;const t=(o,i,a,l,u,c,d,p,g)=>{const y=l||Object.keys(o),_=new Set(u??[]),b=y.reduce((m,v)=>{if(!_.has(v)){const A=c&&c[v];A&&A[o[v]]?m[v]=A[o[v]]:m[v]=o[v]}return m},{});return d&&d.forEach(m=>{(m.index===void 0||m.index===i)&&(b[m.propId]=a[m.from])}),g&&g.forEach(m=>{const v=a[m.from??1];m.equal?b[m.propId]=m.equal===v:m.notEqual&&(b[m.propId]=m.notEqual!==v)}),p&&Object.keys(p).forEach(m=>{const v=b[m];b[m]=b[p[m]],b[p[m]]=v}),b},n=async({namedInputs:o,params:i})=>{const{include:a,exclude:l,alter:u,inject:c,swap:d,inspect:p}=i,{array:g,item:y}=o;if(g){const[_]=g;return Array.isArray(_)?_.map((b,m)=>t(b,m,g,a,l,u,c,d,p)):t(_,0,g,a,l,u,c,d,p)}else if(y)return t(y,0,[],a,l,u,c,d,p);return!1};e.propertyFilterAgent=n;const r={array:[[{color:"red",model:"Model 3",type:"EV",maker:"Tesla",range:300},{color:"blue",model:"Model Y",type:"EV",maker:"Tesla",range:400}],"Tesla Motors"]},s={name:"propertyFilterAgent",agent:e.propertyFilterAgent,mock:e.propertyFilterAgent,inputs:{type:"object"},output:{type:"any",properties:{array:{type:"array",description:"the array to apply filter"},item:{type:"object",description:"the object to apply filter"}}},samples:[{inputs:{array:[r.array[0][0]]},params:{include:["color","model"]},result:{color:"red",model:"Model 3"}},{inputs:{item:r.array[0][0]},params:{include:["color","model"]},result:{color:"red",model:"Model 3"}},{inputs:r,params:{include:["color","model"]},result:[{color:"red",model:"Model 3"},{color:"blue",model:"Model Y"}]},{inputs:r,params:{exclude:["color","model"]},result:[{type:"EV",maker:"Tesla",range:300},{type:"EV",maker:"Tesla",range:400}]},{inputs:{item:r.array[0][0]},params:{exclude:["color","model"]},result:{type:"EV",maker:"Tesla",range:300}},{inputs:r,params:{alter:{color:{red:"blue",blue:"red"}}},result:[{color:"blue",model:"Model 3",type:"EV",maker:"Tesla",range:300},{color:"red",model:"Model Y",type:"EV",maker:"Tesla",range:400}]},{inputs:{item:r.array[0][0]},params:{alter:{color:{red:"blue",blue:"red"}}},result:{color:"blue",model:"Model 3",type:"EV",maker:"Tesla",range:300}},{inputs:r,params:{swap:{maker:"model"}},result:[{color:"red",model:"Tesla",type:"EV",maker:"Model 3",range:300},{color:"blue",model:"Tesla",type:"EV",maker:"Model Y",range:400}]},{inputs:{item:r.array[0][0]},params:{swap:{maker:"model"}},result:{color:"red",model:"Tesla",type:"EV",maker:"Model 3",range:300}},{inputs:r,params:{inject:[{propId:"maker",from:1}]},result:[{color:"red",model:"Model 3",type:"EV",maker:"Tesla Motors",range:300},{color:"blue",model:"Model Y",type:"EV",maker:"Tesla Motors",range:400}]},{inputs:r,params:{inject:[{propId:"maker",from:1,index:0}]},result:[{color:"red",model:"Model 3",type:"EV",maker:"Tesla Motors",range:300},{color:"blue",model:"Model Y",type:"EV",maker:"Tesla",range:400}]},{inputs:r,params:{inspect:[{propId:"isTesla",equal:"Tesla Motors"},{propId:"isGM",notEqual:"Tesla Motors",from:1}]},result:[{color:"red",model:"Model 3",type:"EV",maker:"Tesla",range:300,isTesla:!0,isGM:!1},{color:"blue",model:"Model Y",type:"EV",maker:"Tesla",range:400,isTesla:!0,isGM:!1}]}],description:"Filter properties based on property name either with 'include', 'exclude', 'alter', 'swap', 'inject', 'inspect'",category:["data"],author:"Receptron team",repository:"https://github.com/receptron/graphai",source:"https://github.com/receptron/graphai/blob/main/agents/vanilla_agents/src/data_agents/property_filter_agent.ts",package:"@graphai/vanilla",license:"MIT"};e.default=s})(Kl)),Kl}var $l={},Hp;function iP(){return Hp||(Hp=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.copyAgent=void 0;const t=Oe(),n=it(),r=async({namedInputs:o,params:i})=>{const{namedKey:a}=i;return(0,t.assert)((0,n.isNamedInputs)(o),"copyAgent: namedInputs is UNDEFINED!"),a?o[a]:o};e.copyAgent=r;const s={name:"copyAgent",agent:e.copyAgent,mock:e.copyAgent,inputs:{type:"object",description:"A dynamic object containing any number of named input fields. The agent either returns the whole object or a single value by key.",additionalProperties:{type:["string","number","boolean","object","array","null"],description:"A value associated with a named input key. Can be any JSON-compatible type."}},params:{type:"object",properties:{namedKey:{type:"string",description:"If specified, the agent will return only the value associated with this key from namedInputs."}},additionalProperties:!1},output:{anyOf:[{type:"string"},{type:"integer"},{type:"object"},{type:"array"}]},samples:[{inputs:{color:"red",model:"Model 3"},params:{},result:{color:"red",model:"Model 3"}},{inputs:{array:["Hello World","Discarded"]},params:{},result:{array:["Hello World","Discarded"]}},{inputs:{color:"red",model:"Model 3"},params:{namedKey:"color"},result:"red"}],description:"Returns namedInputs",category:["data"],author:"Receptron team",repository:"https://github.com/receptron/graphai",source:"https://github.com/receptron/graphai/blob/main/agents/vanilla_agents/src/data_agents/copy_agent.ts",package:"@graphai/vanilla",license:"MIT"};e.default=s})($l)),$l}var Yl={},Jp;function aP(){return Jp||(Jp=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.lookupDictionaryAgent=void 0;const t=Oe(),n=it(),r=async({namedInputs:i,params:a})=>{const{namedKey:l}=i;(0,t.assert)((0,n.isNamedInputs)(i),"lookupDictionaryAgent: namedInputs is UNDEFINED!");const u=a[l];if(!a.supressError&&u===void 0)throw new Error(`lookupDictionaryAgent error: ${l} is missing`);return u};e.lookupDictionaryAgent=r;const s={openai:{model:"gpt4-o",temperature:.7},groq:{model:"llama3-8b-8192",temperature:.6},gemini:{model:"gemini-2.0-pro-exp-02-05",temperature:.7}},o={name:"lookupDictionaryAgent",agent:e.lookupDictionaryAgent,mock:e.lookupDictionaryAgent,inputs:{type:"object",properties:{namedKey:{type:"string",description:"The key to look up in the dictionary provided by 'params'."},supressError:{type:"boolean",description:"If true, prevents the agent from throwing an error when the key is missing in 'params'. Optional."}},required:["namedKey"],additionalProperties:!1},params:{type:"object",description:"A dictionary of values from which one is selected using the 'namedKey'.",additionalProperties:{type:["string","number","boolean","object","array","null"],description:"Any JSON-compatible value associated with a key in the dictionary."}},output:{anyOf:[{type:"string"},{type:"integer"},{type:"object"},{type:"array"}]},samples:[{inputs:{namedKey:"openai"},params:s,result:{model:"gpt4-o",temperature:.7}},{inputs:{namedKey:"gemini"},params:s,result:{model:"gemini-2.0-pro-exp-02-05",temperature:.7}}],description:"Select elements with params",category:["data"],author:"Receptron team",repository:"https://github.com/receptron/graphai",source:"https://github.com/receptron/graphai/blob/main/agents/vanilla_agents/src/data_agents/lookup_dictionary_agent.ts",package:"@graphai/vanilla",license:"MIT"};e.default=o})(Yl)),Yl}var zl={},jp;function lP(){return jp||(jp=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.mergeObjectAgent=void 0;const t=Oe(),n=it(),r=async({namedInputs:o})=>{(0,t.assert)((0,n.isNamedInputs)(o),"mergeObjectAgent: namedInputs is UNDEFINED!");const{items:i}=o;return(0,t.assert)(i!==void 0&&Array.isArray(i),"mergeObjectAgent: namedInputs.items is not array!"),Object.assign({},...i)};e.mergeObjectAgent=r;const s={name:"mergeObjectAgent",agent:e.mergeObjectAgent,mock:e.mergeObjectAgent,inputs:{type:"object",properties:{items:{type:"array",description:"An array of objects whose key-value pairs will be merged into a single object. Later objects override earlier ones on key conflict.",items:{type:"object",description:"An individual object contributing to the merged result."}}},required:["items"],additionalProperties:!1},params:{type:"object",description:"This agent does not take any parameters. The object must be empty.",properties:{},additionalProperties:!1},output:{anyOf:{type:"object"}},samples:[{inputs:{items:[{color:"red"},{model:"Model 3"}]},params:{},result:{color:"red",model:"Model 3"}}],description:"Returns namedInputs",category:["data"],author:"Receptron team",repository:"https://github.com/receptron/graphai",source:"https://github.com/receptron/graphai/blob/main/agents/vanilla_agents/src/data_agents/merge_objects_agent.ts",package:"@graphai/vanilla",license:"MIT"};e.default=s})(zl)),zl}var Wp;function uP(){if(Wp)return $e;Wp=1;var e=$e&&$e.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty($e,"__esModule",{value:!0}),$e.mergeObjectAgent=$e.lookupDictionaryAgent=$e.copyAgent=$e.propertyFilterAgent=$e.dataSumTemplateAgent=$e.totalAgent=void 0;const t=e(rP());$e.totalAgent=t.default;const n=e(sP());$e.dataSumTemplateAgent=n.default;const r=e(oP());$e.propertyFilterAgent=r.default;const s=e(iP());$e.copyAgent=s.default;const o=e(aP());$e.lookupDictionaryAgent=o.default;const i=e(lP());return $e.mergeObjectAgent=i.default,$e}var Bn={},Xl={},Kp;function cP(){return Kp||(Kp=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.vanillaFetchAgent=void 0;const t=Oe(),n=["GET","HEAD","POST","OPTIONS","PUT","DELETE","PATCH"],r=["POST","PUT","PATCH"],s=async({namedInputs:i,params:a,config:l})=>{const{url:u,method:c,queryParams:d,body:p}={...a,...i};(0,t.assert)(!!u,"fetchAgent: no url");const g=a.supressError??!1,y=new URL(u),_={...a.headers?a.headers:{},...i.headers?i.headers:{}};if(l&&l.authorization&&(_.Authorization=l.authorization),d){const A=new URLSearchParams(d);y.search=A.toString()}p&&(_["Content-Type"]="application/json");const b={method:c?c.toUpperCase():p?"POST":"GET",headers:new Headers(_),body:p?JSON.stringify(p):void 0};if((0,t.assert)(n.includes(b.method??""),"fetchAgent: invalid method: "+b.method),(0,t.assert)(!r.includes(b.method??"")||!!p,"fetchAgent: The request body is required for this method: "+b.method),a?.debug)return{url:y.toString(),method:b.method,headers:_,body:b.body};const m=await fetch(y.toString(),b);if(!m.ok){const A=m.status,P=(a?.type??"json")==="json"?await m.json():await m.text();if(g)return{onError:{message:`HTTP error: ${A}`,status:A,error:P}};throw new Error(`HTTP error: ${A}`)}const v=await(async()=>{const A=a?.type??"json";if(A==="json")return await m.json();if(A==="text")return m.text();throw new Error(`Unknown Type! ${A}`)})();return a.flatResponse===!1?{data:v}:v};e.vanillaFetchAgent=s;const o={name:"vanillaFetchAgent",agent:e.vanillaFetchAgent,mock:e.vanillaFetchAgent,inputs:{type:"object",properties:{url:{type:"string",description:"The request URL. Can be provided in either 'inputs' or 'params'."},method:{type:"string",description:"The HTTP method to use (GET, POST, PUT, etc.). Defaults to GET if not specified and no body is provided; otherwise POST."},headers:{type:"object",description:"Optional HTTP headers to include in the request. Values from both inputs and params are merged."},queryParams:{type:"object",description:"Optional query parameters to append to the URL."},body:{description:"Optional request body to send with POST, PUT, or PATCH methods.",anyOf:[{type:"string"},{type:"object"}]}},required:[],additionalProperties:!1},params:{type:"object",properties:{url:{type:"string",description:"The request URL (overridden if also specified in inputs)."},method:{type:"string",description:"The HTTP method (overridden if also specified in inputs)."},headers:{type:"object",description:"Additional headers. Merged with inputs.headers."},queryParams:{type:"object",description:"Query parameters to append to the URL."},body:{description:"Request body to be sent, used with POST/PUT/PATCH.",anyOf:[{type:"string"},{type:"object"}]},debug:{type:"boolean",description:"If true, returns the prepared request details instead of performing the actual fetch."},supressError:{type:"boolean",description:"If true, suppresses thrown errors and returns the error response instead."},flatResponse:{type:"boolean",description:"If true, returns the raw response. If false, wraps the response in an object with a 'data' key. Default is false."},type:{type:"string",enum:["json","text"],description:"Response type to parse. Either 'json' or 'text'. Defaults to 'json'."}},required:[],additionalProperties:!1},output:{description:"Returns either the HTTP response body or a debug object. If an error occurs and 'supressError' is true, returns an object with an 'onError' key.",anyOf:[{type:"object",properties:{onError:{type:"object",properties:{message:{type:"string"},status:{type:"integer"},error:{}},required:["message","status","error"]}},required:["onError"],additionalProperties:!0},{type:"object",description:"Debug information returned when 'debug' is true.",properties:{method:{type:"string"},url:{type:"string"},headers:{type:"object"},body:{}},required:["method","url","headers"]},{},{type:"object",description:"When 'flatResponse' is false, the response is wrapped as { data: ... }.",properties:{data:{}},required:["data"],additionalProperties:!0}]},samples:[{inputs:{url:"https://example.com",queryParams:{foo:"bar"},headers:{"x-myHeader":"secret"}},params:{debug:!0},result:{method:"GET",url:"https://example.com/?foo=bar",headers:{"x-myHeader":"secret"},body:void 0}},{inputs:{url:"https://example.com",body:{foo:"bar"}},params:{debug:!0},result:{method:"POST",url:"https://example.com/",headers:{"Content-Type":"application/json"},body:JSON.stringify({foo:"bar"})}},{inputs:{url:"https://example.com",body:{foo:"bar"},method:"PUT"},params:{debug:!0},result:{method:"PUT",url:"https://example.com/",headers:{"Content-Type":"application/json"},body:JSON.stringify({foo:"bar"})}},{inputs:{url:"https://example.com",method:"options"},params:{debug:!0},result:{method:"OPTIONS",url:"https://example.com/",headers:{},body:void 0}},{inputs:{},params:{url:"https://example.com",body:{foo:"bar"},method:"PUT",debug:!0},result:{method:"PUT",url:"https://example.com/",headers:{"Content-Type":"application/json"},body:JSON.stringify({foo:"bar"})}},{inputs:{method:"DELETE",headers:{authentication:"bearer XXX"}},params:{url:"https://example.com",body:{foo:"bar"},method:"PUT",headers:{"Content-Type":"application/json"},debug:!0},result:{method:"DELETE",url:"https://example.com/",headers:{"Content-Type":"application/json",authentication:"bearer XXX"},body:JSON.stringify({foo:"bar"})}}],description:"Retrieves JSON data from the specified URL",category:["service"],author:"Receptron",repository:"https://github.com/receptron/graphai",source:"https://github.com/receptron/graphai/blob/main/agents/vanilla_agents/src/service_agents/vanilla_fetch_agent.ts",package:"@graphai/vanilla",license:"MIT"};e.default=o})(Xl)),Xl}var $p;function dP(){if($p)return Bn;$p=1;var e=Bn&&Bn.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(Bn,"__esModule",{value:!0}),Bn.vanillaFetchAgent=void 0;const t=e(cP());return Bn.vanillaFetchAgent=t.default,Bn}var Hn={},Ql={},Yp;function fP(){return Yp||(Yp=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.sleeperAgent=void 0;const t=Oe(),n=async({params:s,namedInputs:o})=>(await(0,t.sleep)(s?.duration??10),o);e.sleeperAgent=n;const r={name:"sleeperAgent",agent:e.sleeperAgent,mock:e.sleeperAgent,inputs:{type:"object",description:"Arbitrary input data. This agent does not modify it and returns it unchanged after a delay.",additionalProperties:!0},params:{type:"object",properties:{duration:{type:"number",description:"Optional duration in milliseconds to pause execution before returning the input. Defaults to 10ms."}},additionalProperties:!1},output:{type:"object",description:"Returns the same object passed as 'inputs', unchanged.",additionalProperties:!0},samples:[{inputs:{},params:{duration:1},result:{}},{inputs:{array:[{a:1},{b:2}]},params:{duration:1},result:{array:[{a:1},{b:2}]}}],description:"sleeper Agent for test and debug",category:["sleeper"],author:"Receptron team",repository:"https://github.com/receptron/graphai",source:"https://github.com/receptron/graphai/blob/main/agents/vanilla_agents/src/sleeper_agents/sleeper_agent.ts",package:"@graphai/vanilla",license:"MIT"};e.default=r})(Ql)),Ql}var zp;function pP(){if(zp)return Hn;zp=1;var e=Hn&&Hn.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(Hn,"__esModule",{value:!0}),Hn.sleeperAgent=void 0;const t=e(fP());return Hn.sleeperAgent=t.default,Hn}var Jn={},Zl={},Xp;function hP(){return Xp||(Xp=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.compareAgent=void 0;const t=o=>{const i=o.map(c=>Array.isArray(c)?t(c):c),[a,l,u]=i;if(l==="==")return a===u;if(l==="!=")return a!==u;if(l===">")return Number(a)>Number(u);if(l===">=")return Number(a)>=Number(u);if(l==="<")return Number(a)<Number(u);if(l==="<=")return Number(a)<=Number(u);if(l==="||")return!!a||!!u;if(l==="&&")return!!a&&!!u;if(l==="XOR")return!!a==!u;throw new Error("unknown compare operator")},n=o=>o==null,r=async({namedInputs:o,params:i})=>{const{array:a,leftValue:l,rightValue:u}=o,c=a??[],d=(()=>{if(c.length===2&&i.operator)return[c[0],i.operator,c[1]];if(c.length===3)return c;if(c.length===0&&!n(l)&&!n(u)&&i.operator)return[l,i.operator,u];throw new Error("compare inputs is wrong.")})(),p=t(d);return i?.value?{result:i?.value[p?"true":"false"]??p}:{result:p}};e.compareAgent=r;const s={name:"compareAgent",agent:e.compareAgent,mock:e.compareAgent,inputs:{type:"object",properties:{array:{type:"array",description:"A 3-element array in the form [leftOperand, operator, rightOperand]. Used for direct comparison logic.",items:{type:["string","number","boolean","array"]}},leftValue:{type:["string","number","boolean"],description:"Left-hand operand used when 'array' is not provided. Used with 'rightValue' and 'params.operator'."},rightValue:{type:["string","number","boolean"],description:"Right-hand operand used when 'array' is not provided. Used with 'leftValue' and 'params.operator'."}},additionalProperties:!1},params:{type:"object",properties:{operator:{type:"string",description:"The comparison operator to apply, such as '==', '!=', '>', '>=', '<', '<=', '||', '&&', or 'XOR'. Required if 'array' does not include the operator."},value:{type:"object",description:"An optional mapping for the comparison result. If provided, it must contain keys 'true' and/or 'false' to return custom values instead of booleans.",properties:{true:{type:["string","number","boolean"],description:"Custom result to return when the comparison evaluates to true."},false:{type:["string","number","boolean"],description:"Custom result to return when the comparison evaluates to false."}},additionalProperties:!1}},additionalProperties:!1},output:{},samples:[{inputs:{array:["abc","==","abc"]},params:{value:{true:"a",false:"b"}},result:{result:"a"}},{inputs:{array:["abc","==","abca"]},params:{value:{true:"a",false:"b"}},result:{result:"b"}},{inputs:{array:["abc","==","abc"]},params:{},result:{result:!0}},{inputs:{array:["abc","==","abcd"]},params:{},result:{result:!1}},{inputs:{array:["abc","!=","abc"]},params:{},result:{result:!1}},{inputs:{array:["abc","!=","abcd"]},params:{},result:{result:!0}},{inputs:{array:["10",">","5"]},params:{},result:{result:!0}},{inputs:{array:["10",">","15"]},params:{},result:{result:!1}},{inputs:{array:[10,">",5]},params:{},result:{result:!0}},{inputs:{array:[10,">",15]},params:{},result:{result:!1}},{inputs:{array:["10",">=","5"]},params:{},result:{result:!0}},{inputs:{array:["10",">=","10"]},params:{},result:{result:!0}},{inputs:{array:["10",">=","19"]},params:{},result:{result:!1}},{inputs:{array:[10,">=",5]},params:{},result:{result:!0}},{inputs:{array:[10,">=",10]},params:{},result:{result:!0}},{inputs:{array:[10,">=",19]},params:{},result:{result:!1}},{inputs:{array:["10","<","5"]},params:{},result:{result:!1}},{inputs:{array:["10","<","15"]},params:{},result:{result:!0}},{inputs:{array:[10,"<",5]},params:{},result:{result:!1}},{inputs:{array:[10,"<",15]},params:{},result:{result:!0}},{inputs:{array:["10","<=","5"]},params:{},result:{result:!1}},{inputs:{array:["10","<=","10"]},params:{},result:{result:!0}},{inputs:{array:["10","<=","19"]},params:{},result:{result:!0}},{inputs:{array:[10,"<=",5]},params:{},result:{result:!1}},{inputs:{array:[10,"<=",10]},params:{},result:{result:!0}},{inputs:{array:[10,"<=",19]},params:{},result:{result:!0}},{inputs:{array:[!0,"||",!1]},params:{},result:{result:!0}},{inputs:{array:[!1,"||",!1]},params:{},result:{result:!1}},{inputs:{array:[!0,"&&",!1]},params:{},result:{result:!1}},{inputs:{array:[!0,"&&",!0]},params:{},result:{result:!0}},{inputs:{array:[!0,"XOR",!1]},params:{},result:{result:!0}},{inputs:{array:[!1,"XOR",!0]},params:{},result:{result:!0}},{inputs:{array:[!1,"XOR",!1]},params:{},result:{result:!1}},{inputs:{array:[!0,"XOR",!0]},params:{},result:{result:!1}},{inputs:{array:[["aaa","==","aaa"],"||",["aaa","==","bbb"]]},params:{},result:{result:!0}},{inputs:{array:[["aaa","==","aaa"],"&&",["aaa","==","bbb"]]},params:{},result:{result:!1}},{inputs:{array:[[["aaa","==","aaa"],"&&",["bbb","==","bbb"]],"||",["aaa","&&","bbb"]]},params:{},result:{result:!0}},{inputs:{array:["abc","abc"]},params:{value:{true:"a",false:"b"},operator:"=="},result:{result:"a"}},{inputs:{array:["abc","abca"]},params:{value:{true:"a",false:"b"},operator:"=="},result:{result:"b"}},{inputs:{array:["abc","abc"]},params:{operator:"=="},result:{result:!0}},{inputs:{array:["abc","abcd"]},params:{operator:"=="},result:{result:!1}},{inputs:{array:["abc","abc"]},params:{operator:"!="},result:{result:!1}},{inputs:{array:["abc","abcd"]},params:{operator:"!="},result:{result:!0}},{inputs:{array:["10","5"]},params:{operator:">"},result:{result:!0}},{inputs:{array:["10","15"]},params:{operator:">"},result:{result:!1}},{inputs:{array:[10,5]},params:{operator:">"},result:{result:!0}},{inputs:{array:[10,15]},params:{operator:">"},result:{result:!1}},{inputs:{array:["10","5"]},params:{operator:">="},result:{result:!0}},{inputs:{array:["10","10"]},params:{operator:">="},result:{result:!0}},{inputs:{array:["10","19"]},params:{operator:">="},result:{result:!1}},{inputs:{array:[10,5]},params:{operator:">="},result:{result:!0}},{inputs:{array:[10,10]},params:{operator:">="},result:{result:!0}},{inputs:{array:[10,19]},params:{operator:">="},result:{result:!1}},{inputs:{array:["10","5"]},params:{operator:"<"},result:{result:!1}},{inputs:{array:["10","15"]},params:{operator:"<"},result:{result:!0}},{inputs:{array:[10,5]},params:{operator:"<"},result:{result:!1}},{inputs:{array:[10,15]},params:{operator:"<"},result:{result:!0}},{inputs:{array:[!0,!1]},params:{operator:"||"},result:{result:!0}},{inputs:{array:[!1,!1]},params:{operator:"||"},result:{result:!1}},{inputs:{array:[!0,!1]},params:{operator:"&&"},result:{result:!1}},{inputs:{array:[!0,!0]},params:{operator:"&&"},result:{result:!0}},{inputs:{array:[!0,!1]},params:{operator:"XOR"},result:{result:!0}},{inputs:{array:[!1,!0]},params:{operator:"XOR"},result:{result:!0}},{inputs:{array:[!1,!1]},params:{operator:"XOR"},result:{result:!1}},{inputs:{array:[!0,!0]},params:{operator:"XOR"},result:{result:!1}},{inputs:{leftValue:"abc",rightValue:"abc"},params:{value:{true:"a",false:"b"},operator:"=="},result:{result:"a"}},{inputs:{leftValue:"abc",rightValue:"abca"},params:{value:{true:"a",false:"b"},operator:"=="},result:{result:"b"}}],description:"compare",category:["compare"],author:"Receptron",repository:"https://github.com/receptron/graphai",source:"https://github.com/receptron/graphai/blob/main/agents/vanilla_agents/src/compare_agents/compare_agent.ts",package:"@graphai/vanilla",license:"MIT"};e.default=s})(Zl)),Zl}var Qp;function gP(){if(Qp)return Jn;Qp=1;var e=Jn&&Jn.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(Jn,"__esModule",{value:!0}),Jn.compareAgent=void 0;const t=e(hP());return Jn.compareAgent=t.default,Jn}var jn={},eu={},Zp;function mP(){return Zp||(Zp=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.images2messageAgent=void 0;const t=Oe(),n=it(),r=(i,a,l)=>a==="http"?{url:i}:{url:`data:image/${a};base64,${i}`,detail:l??"auto"},s=async({namedInputs:i,params:a})=>{const{imageType:l,detail:u}=a,{array:c,prompt:d}=i;(0,n.arrayValidate)("images2messageAgent",i),(0,t.assert)(!!l,"images2messageAgent: params.imageType is UNDEFINED! Set Type: png, jpg...");const p=c.map(g=>({type:"image_url",image_url:r(g,l,u)}));return d&&p.unshift({type:"text",text:d}),{message:{role:"user",content:p}}};e.images2messageAgent=s;const o={name:"images2messageAgent",agent:e.images2messageAgent,mock:e.images2messageAgent,inputs:{type:"object",properties:{array:{type:"array",description:"An array of base64-encoded image data strings or image URLs. These will be converted into OpenAI Vision-compatible image message format.",items:{type:"string",description:"Base64 image string or HTTP URL depending on 'imageType'."}},prompt:{type:"string",description:"Optional prompt text to include as the first message content before images."}},required:["array"],additionalProperties:!1},params:{type:"object",properties:{imageType:{type:"string",description:"The type of image input: 'png', 'jpg', etc. for base64, or 'http' for image URLs."},detail:{type:"string",description:"The level of image detail requested by the model (e.g., 'auto', 'low', 'high'). Optional."}},required:["imageType"],additionalProperties:!1},output:{type:"object",properties:{message:{type:"object",description:"OpenAI-compatible chat message including images and optional prompt text.",properties:{role:{type:"string",enum:["user"],description:"Message role, always 'user' for this agent."},content:{type:"array",description:"The array of message content elements, including optional text and one or more images.",items:{type:"object",oneOf:[{properties:{type:{type:"string",const:"text"},text:{type:"string",description:"Prompt message text."}},required:["type","text"],additionalProperties:!1},{properties:{type:{type:"string",const:"image_url"},image_url:{type:"object",properties:{url:{type:"string",description:"URL or data URL of the image."},detail:{type:"string",description:"Image detail level (e.g., 'high', 'low', 'auto'). Optional for base64."}},required:["url"],additionalProperties:!1}},required:["type","image_url"],additionalProperties:!1}]}}},required:["role","content"],additionalProperties:!1}},required:["message"],additionalProperties:!1},samples:[{inputs:{array:["abcabc","122123"]},params:{imageType:"png"},result:{message:{content:[{image_url:{detail:"auto",url:"data:image/png;base64,abcabc"},type:"image_url"},{image_url:{detail:"auto",url:"data:image/png;base64,122123"},type:"image_url"}],role:"user"}}},{inputs:{array:["abcabc","122123"],prompt:"hello"},params:{imageType:"jpg",detail:"high"},result:{message:{content:[{type:"text",text:"hello"},{image_url:{detail:"high",url:"data:image/jpg;base64,abcabc"},type:"image_url"},{image_url:{detail:"high",url:"data:image/jpg;base64,122123"},type:"image_url"}],role:"user"}}},{inputs:{array:["http://example.com/1.jpg","http://example.com/2.jpg"]},params:{imageType:"http"},result:{message:{content:[{image_url:{url:"http://example.com/1.jpg"},type:"image_url"},{image_url:{url:"http://example.com/2.jpg"},type:"image_url"}],role:"user"}}}],description:"Returns the message data for llm include image",category:["image"],author:"Receptron team",repository:"https://github.com/snakajima/graphai",source:"https://github.com/receptron/graphai/blob/main/agents/vanilla_agents/src/images_agents/image_to_message_agent.ts",package:"@graphai/vanilla",license:"MIT"};e.default=o})(eu)),eu}var eh;function _P(){if(eh)return jn;eh=1;var e=jn&&jn.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(jn,"__esModule",{value:!0}),jn.images2messageAgent=void 0;const t=e(mP());return jn.images2messageAgent=t.default,jn}var tu={},th;function yP(){return th||(th=1,(function(e){var t={};Object.defineProperty(e,"__esModule",{value:!0}),e.stringEmbeddingsAgent=void 0;const n="text-embedding-3-small",r="https://api.openai.com/v1/embeddings",s=async({params:i,namedInputs:a,config:l})=>{const{array:u,item:c}=a,{apiKey:d,model:p,baseURL:g}={...l||{},...i},y=g??r,_=p??n,b=d??t.OPENAI_API_KEY,m={"Content-Type":"application/json",Authorization:b?`Bearer ${b}`:""},A=await fetch(y,{method:"POST",headers:m,body:JSON.stringify({input:u??[c],model:_})}),S=await A.json();if(!A.ok)throw new Error(`HTTP error! status: ${A.status}`);if("data"in S)return S.data.map(P=>P.embedding);if("embeddings"in S)return S.embeddings};e.stringEmbeddingsAgent=s;const o={name:"stringEmbeddingsAgent",agent:e.stringEmbeddingsAgent,mock:e.stringEmbeddingsAgent,samples:[],description:"Embeddings Agent",category:["embedding"],author:"Receptron team",repository:"https://github.com/receptron/graphai",source:"https://github.com/receptron/graphai/blob/main/agents/vanilla_agents/src/embedding_agent.ts",package:"@graphai/vanilla",cacheType:"pureAgent",license:"MIT"};e.default=o})(tu)),tu}var nh;function vP(){return nh||(nh=1,(function(e){var t=tn&&tn.__createBinding||(Object.create?(function(o,i,a,l){l===void 0&&(l=a);var u=Object.getOwnPropertyDescriptor(i,a);(!u||("get"in u?!i.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return i[a]}}),Object.defineProperty(o,l,u)}):(function(o,i,a,l){l===void 0&&(l=a),o[l]=i[a]})),n=tn&&tn.__exportStar||function(o,i){for(var a in o)a!=="default"&&!Object.prototype.hasOwnProperty.call(i,a)&&t(i,o,a)},r=tn&&tn.__importDefault||function(o){return o&&o.__esModule?o:{default:o}};Object.defineProperty(e,"__esModule",{value:!0}),e.stringEmbeddingsAgent=void 0,n(xT(),e),n(JT(),e),n(KT(),e),n(eP(),e),n(nP(),e),n(uP(),e),n(dP(),e),n(pP(),e),n(gP(),e),n(_P(),e);const s=r(yP());e.stringEmbeddingsAgent=s.default})(tn)),tn}vP();var sn={},on={},Ji={exports:{}},is={},At={},rh;function ve(){if(rh)return At;rh=1,Object.defineProperty(At,"__esModule",{value:!0}),At.__setModuleDefault=At.__createBinding=void 0,At.__classPrivateFieldSet=e,At.__classPrivateFieldGet=t,At.__exportStar=r,At.__importStar=i;function e(a,l,u,c,d){if(c==="m")throw new TypeError("Private method is not writable");if(c==="a"&&!d)throw new TypeError("Private accessor was defined without a setter");if(typeof l=="function"?a!==l||!d:!l.has(a))throw new TypeError("Cannot write private member to an object whose class did not declare it");return c==="a"?d.call(a,u):d?d.value=u:l.set(a,u),u}function t(a,l,u,c){if(u==="a"&&!c)throw new TypeError("Private accessor was defined without a getter");if(typeof l=="function"?a!==l||!c:!l.has(a))throw new TypeError("Cannot read private member from an object whose class did not declare it");return u==="m"?c:u==="a"?c.call(a):c?c.value:l.get(a)}var n=Object.create?function(a,l,u,c){c===void 0&&(c=u);var d=Object.getOwnPropertyDescriptor(l,u);(!d||("get"in d?!l.__esModule:d.writable||d.configurable))&&(d={enumerable:!0,get:function(){return l[u]}}),Object.defineProperty(a,c,d)}:function(a,l,u,c){c===void 0&&(c=u),a[c]=l[u]};At.__createBinding=n;function r(a,l){for(var u in a)u!=="default"&&!Object.prototype.hasOwnProperty.call(l,u)&&n(l,a,u)}var s=Object.create?function(a,l){Object.defineProperty(a,"default",{enumerable:!0,value:l})}:function(a,l){a.default=l};At.__setModuleDefault=s;var o=function(a){return o=Object.getOwnPropertyNames||function(l){var u=[];for(var c in l)Object.prototype.hasOwnProperty.call(l,c)&&(u[u.length]=c);return u},o(a)};function i(a){if(a&&a.__esModule)return a;var l={};if(a!=null)for(var u=o(a),c=0;c<u.length;c++)u[c]!=="default"&&n(l,a,u[c]);return s(l,a),l}return At}var pr={},sh;function _b(){if(sh)return pr;sh=1,Object.defineProperty(pr,"__esModule",{value:!0}),pr.uuid4=void 0;let e=function(){const{crypto:t}=globalThis;if(t?.randomUUID)return pr.uuid4=t.randomUUID.bind(t),t.randomUUID();const n=new Uint8Array(1),r=t?()=>t.getRandomValues(n)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,s=>(+s^r()&15>>+s/4).toString(16))};return pr.uuid4=e,pr}var nu={},Se={},hr={},oh;function Jd(){if(oh)return hr;oh=1,Object.defineProperty(hr,"__esModule",{value:!0}),hr.castToError=void 0,hr.isAbortError=e;function e(n){return typeof n=="object"&&n!==null&&("name"in n&&n.name==="AbortError"||"message"in n&&String(n.message).includes("FetchRequestCanceledException"))}const t=n=>{if(n instanceof Error)return n;if(typeof n=="object"&&n!==null){try{if(Object.prototype.toString.call(n)==="[object Error]"){const r=new Error(n.message,n.cause?{cause:n.cause}:{});return n.stack&&(r.stack=n.stack),n.cause&&!r.cause&&(r.cause=n.cause),n.name&&(r.name=n.name),r}}catch{}try{return new Error(JSON.stringify(n))}catch{}}return new Error(n)};return hr.castToError=t,hr}var ih;function yn(){if(ih)return Se;ih=1,Object.defineProperty(Se,"__esModule",{value:!0}),Se.InvalidWebhookSignatureError=Se.ContentFilterFinishReasonError=Se.LengthFinishReasonError=Se.InternalServerError=Se.RateLimitError=Se.UnprocessableEntityError=Se.ConflictError=Se.NotFoundError=Se.PermissionDeniedError=Se.AuthenticationError=Se.BadRequestError=Se.APIConnectionTimeoutError=Se.APIConnectionError=Se.APIUserAbortError=Se.APIError=Se.OpenAIError=void 0;const e=Jd();class t extends Error{}Se.OpenAIError=t;class n extends t{constructor(v,A,S,P){super(`${n.makeMessage(v,A,S)}`),this.status=v,this.headers=P,this.requestID=P?.get("x-request-id"),this.error=A;const E=A;this.code=E?.code,this.param=E?.param,this.type=E?.type}static makeMessage(v,A,S){const P=A?.message?typeof A.message=="string"?A.message:JSON.stringify(A.message):A?JSON.stringify(A):S;return v&&P?`${v} ${P}`:v?`${v} status code (no body)`:P||"(no status code or body)"}static generate(v,A,S,P){if(!v||!P)return new s({message:S,cause:(0,e.castToError)(A)});const E=A?.error;return v===400?new i(v,E,S,P):v===401?new a(v,E,S,P):v===403?new l(v,E,S,P):v===404?new u(v,E,S,P):v===409?new c(v,E,S,P):v===422?new d(v,E,S,P):v===429?new p(v,E,S,P):v>=500?new g(v,E,S,P):new n(v,E,S,P)}}Se.APIError=n;class r extends n{constructor({message:v}={}){super(void 0,void 0,v||"Request was aborted.",void 0)}}Se.APIUserAbortError=r;class s extends n{constructor({message:v,cause:A}){super(void 0,void 0,v||"Connection error.",void 0),A&&(this.cause=A)}}Se.APIConnectionError=s;class o extends s{constructor({message:v}={}){super({message:v??"Request timed out."})}}Se.APIConnectionTimeoutError=o;class i extends n{}Se.BadRequestError=i;class a extends n{}Se.AuthenticationError=a;class l extends n{}Se.PermissionDeniedError=l;class u extends n{}Se.NotFoundError=u;class c extends n{}Se.ConflictError=c;class d extends n{}Se.UnprocessableEntityError=d;class p extends n{}Se.RateLimitError=p;class g extends n{}Se.InternalServerError=g;class y extends t{constructor(){super("Could not parse response content as the length limit was reached")}}Se.LengthFinishReasonError=y;class _ extends t{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}Se.ContentFilterFinishReasonError=_;class b extends Error{constructor(v){super(v)}}return Se.InvalidWebhookSignatureError=b,Se}var ah;function kn(){return ah||(ah=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.safeJSON=e.maybeCoerceBoolean=e.maybeCoerceFloat=e.maybeCoerceInteger=e.coerceBoolean=e.coerceFloat=e.coerceInteger=e.validatePositiveInteger=e.ensurePresent=e.isReadonlyArray=e.isArray=e.isAbsoluteURL=void 0,e.maybeObj=o,e.isEmptyObj=i,e.hasOwn=a,e.isObj=l;const t=yn(),n=/^[a-z][a-z0-9+.-]*:/i,r=v=>n.test(v);e.isAbsoluteURL=r;let s=v=>(e.isArray=Array.isArray,(0,e.isArray)(v));e.isArray=s,e.isReadonlyArray=e.isArray;function o(v){return typeof v!="object"?{}:v??{}}function i(v){if(!v)return!0;for(const A in v)return!1;return!0}function a(v,A){return Object.prototype.hasOwnProperty.call(v,A)}function l(v){return v!=null&&typeof v=="object"&&!Array.isArray(v)}const u=v=>{if(v==null)throw new t.OpenAIError(`Expected a value to be given but received ${v} instead.`);return v};e.ensurePresent=u;const c=(v,A)=>{if(typeof A!="number"||!Number.isInteger(A))throw new t.OpenAIError(`${v} must be an integer`);if(A<0)throw new t.OpenAIError(`${v} must be a positive integer`);return A};e.validatePositiveInteger=c;const d=v=>{if(typeof v=="number")return Math.round(v);if(typeof v=="string")return parseInt(v,10);throw new t.OpenAIError(`Could not coerce ${v} (type: ${typeof v}) into a number`)};e.coerceInteger=d;const p=v=>{if(typeof v=="number")return v;if(typeof v=="string")return parseFloat(v);throw new t.OpenAIError(`Could not coerce ${v} (type: ${typeof v}) into a number`)};e.coerceFloat=p;const g=v=>typeof v=="boolean"?v:typeof v=="string"?v==="true":!!v;e.coerceBoolean=g;const y=v=>{if(v!=null)return(0,e.coerceInteger)(v)};e.maybeCoerceInteger=y;const _=v=>{if(v!=null)return(0,e.coerceFloat)(v)};e.maybeCoerceFloat=_;const b=v=>{if(v!=null)return(0,e.coerceBoolean)(v)};e.maybeCoerceBoolean=b;const m=v=>{try{return JSON.parse(v)}catch{return}};e.safeJSON=m})(nu)),nu}var as={},lh;function xi(){if(lh)return as;lh=1,Object.defineProperty(as,"__esModule",{value:!0}),as.sleep=void 0;const e=t=>new Promise(n=>setTimeout(n,t));return as.sleep=e,as}var Wn={},ls={},uh;function yb(){return uh||(uh=1,Object.defineProperty(ls,"__esModule",{value:!0}),ls.VERSION=void 0,ls.VERSION="6.18.0"),ls}var ch;function dh(){if(ch)return Wn;ch=1,Object.defineProperty(Wn,"__esModule",{value:!0}),Wn.getPlatformHeaders=Wn.isRunningInBrowser=void 0;const e=yb(),t=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";Wn.isRunningInBrowser=t;function n(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}const r=()=>{const u=n();if(u==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":e.VERSION,"X-Stainless-OS":i(Deno.build.os),"X-Stainless-Arch":o(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":e.VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(u==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":e.VERSION,"X-Stainless-OS":i(globalThis.process.platform??"unknown"),"X-Stainless-Arch":o(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const c=s();return c?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":e.VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${c.browser}`,"X-Stainless-Runtime-Version":c.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":e.VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function s(){if(typeof navigator>"u"||!navigator)return null;const u=[{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:c,pattern:d}of u){const p=d.exec(navigator.userAgent);if(p){const g=p[1]||0,y=p[2]||0,_=p[3]||0;return{browser:c,version:`${g}.${y}.${_}`}}}return null}const o=u=>u==="x32"?"x32":u==="x86_64"||u==="x64"?"x64":u==="arm"?"arm":u==="aarch64"||u==="arm64"?"arm64":u?`other:${u}`:"unknown",i=u=>(u=u.toLowerCase(),u.includes("ios")?"iOS":u==="android"?"Android":u==="darwin"?"MacOS":u==="win32"?"Windows":u==="freebsd"?"FreeBSD":u==="openbsd"?"OpenBSD":u==="linux"?"Linux":u?`Other:${u}`:"Unknown");let a;const l=()=>a??(a=r());return Wn.getPlatformHeaders=l,Wn}var En={},fh;function va(){if(fh)return En;fh=1,Object.defineProperty(En,"__esModule",{value:!0}),En.getDefaultFetch=e,En.makeReadableStream=t,En.ReadableStreamFrom=n,En.ReadableStreamToAsyncIterable=r,En.CancelReadableStream=s;function e(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function t(...o){const i=globalThis.ReadableStream;if(typeof i>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new i(...o)}function n(o){let i=Symbol.asyncIterator in o?o[Symbol.asyncIterator]():o[Symbol.iterator]();return t({start(){},async pull(a){const{done:l,value:u}=await i.next();l?a.close():a.enqueue(u)},async cancel(){await i.return?.()}})}function r(o){if(o[Symbol.asyncIterator])return o;const i=o.getReader();return{async next(){try{const a=await i.read();return a?.done&&i.releaseLock(),a}catch(a){throw i.releaseLock(),a}},async return(){const a=i.cancel();return i.releaseLock(),await a,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function s(o){if(o===null||typeof o!="object")return;if(o[Symbol.asyncIterator]){await o[Symbol.asyncIterator]().return?.();return}const i=o.getReader(),a=i.cancel();i.releaseLock(),await a}return En}var us={},ph;function bP(){if(ph)return us;ph=1,Object.defineProperty(us,"__esModule",{value:!0}),us.FallbackEncoder=void 0;const e=({headers:t,body:n})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(n)});return us.FallbackEncoder=e,us}var ru={},su={},hh;function jd(){return hh||(hh=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.RFC3986=e.RFC1738=e.formatters=e.default_formatter=e.default_format=void 0,e.default_format="RFC3986";const t=n=>String(n);e.default_formatter=t,e.formatters={RFC1738:n=>String(n).replace(/%20/g,"+"),RFC3986:e.default_formatter},e.RFC1738="RFC1738",e.RFC3986="RFC3986"})(su)),su}var ji={},ou={},gh;function AP(){return gh||(gh=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.encode=e.has=void 0,e.merge=a,e.assign_single_source=l,e.decode=u,e.compact=p,e.is_regexp=g,e.is_buffer=y,e.combine=_,e.maybe_map=b;const t=jd(),n=kn();let r=(m,v)=>(e.has=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),(0,e.has)(m,v));e.has=r;const s=(()=>{const m=[];for(let v=0;v<256;++v)m.push("%"+((v<16?"0":"")+v.toString(16)).toUpperCase());return m})();function o(m){for(;m.length>1;){const v=m.pop();if(!v)continue;const A=v.obj[v.prop];if((0,n.isArray)(A)){const S=[];for(let P=0;P<A.length;++P)typeof A[P]<"u"&&S.push(A[P]);v.obj[v.prop]=S}}}function i(m,v){const A=v&&v.plainObjects?Object.create(null):{};for(let S=0;S<m.length;++S)typeof m[S]<"u"&&(A[S]=m[S]);return A}function a(m,v,A={}){if(!v)return m;if(typeof v!="object"){if((0,n.isArray)(m))m.push(v);else if(m&&typeof m=="object")(A&&(A.plainObjects||A.allowPrototypes)||!(0,e.has)(Object.prototype,v))&&(m[v]=!0);else return[m,v];return m}if(!m||typeof m!="object")return[m].concat(v);let S=m;return(0,n.isArray)(m)&&!(0,n.isArray)(v)&&(S=i(m,A)),(0,n.isArray)(m)&&(0,n.isArray)(v)?(v.forEach(function(P,E){if((0,e.has)(m,E)){const w=m[E];w&&typeof w=="object"&&P&&typeof P=="object"?m[E]=a(w,P,A):m.push(P)}else m[E]=P}),m):Object.keys(v).reduce(function(P,E){const w=v[E];return(0,e.has)(P,E)?P[E]=a(P[E],w,A):P[E]=w,P},S)}function l(m,v){return Object.keys(v).reduce(function(A,S){return A[S]=v[S],A},m)}function u(m,v,A){const S=m.replace(/\+/g," ");if(A==="iso-8859-1")return S.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(S)}catch{return S}}const c=1024,d=(m,v,A,S,P)=>{if(m.length===0)return m;let E=m;if(typeof m=="symbol"?E=Symbol.prototype.toString.call(m):typeof m!="string"&&(E=String(m)),A==="iso-8859-1")return escape(E).replace(/%u[0-9a-f]{4}/gi,function(I){return"%26%23"+parseInt(I.slice(2),16)+"%3B"});let w="";for(let I=0;I<E.length;I+=c){const L=E.length>=c?E.slice(I,I+c):E,H=[];for(let B=0;B<L.length;++B){let F=L.charCodeAt(B);if(F===45||F===46||F===95||F===126||F>=48&&F<=57||F>=65&&F<=90||F>=97&&F<=122||P===t.RFC1738&&(F===40||F===41)){H[H.length]=L.charAt(B);continue}if(F<128){H[H.length]=s[F];continue}if(F<2048){H[H.length]=s[192|F>>6]+s[128|F&63];continue}if(F<55296||F>=57344){H[H.length]=s[224|F>>12]+s[128|F>>6&63]+s[128|F&63];continue}B+=1,F=65536+((F&1023)<<10|L.charCodeAt(B)&1023),H[H.length]=s[240|F>>18]+s[128|F>>12&63]+s[128|F>>6&63]+s[128|F&63]}w+=H.join("")}return w};e.encode=d;function p(m){const v=[{obj:{o:m},prop:"o"}],A=[];for(let S=0;S<v.length;++S){const P=v[S],E=P.obj[P.prop],w=Object.keys(E);for(let I=0;I<w.length;++I){const L=w[I],H=E[L];typeof H=="object"&&H!==null&&A.indexOf(H)===-1&&(v.push({obj:E,prop:L}),A.push(H))}}return o(v),m}function g(m){return Object.prototype.toString.call(m)==="[object RegExp]"}function y(m){return!m||typeof m!="object"?!1:!!(m.constructor&&m.constructor.isBuffer&&m.constructor.isBuffer(m))}function _(m,v){return[].concat(m,v)}function b(m,v){if((0,n.isArray)(m)){const A=[];for(let S=0;S<m.length;S+=1)A.push(v(m[S]));return A}return v(m)}})(ou)),ou}var mh;function SP(){if(mh)return ji;mh=1,Object.defineProperty(ji,"__esModule",{value:!0}),ji.stringify=d;const e=AP(),t=jd(),n=kn(),r={brackets(p){return String(p)+"[]"},comma:"comma",indices(p,g){return String(p)+"["+g+"]"},repeat(p){return String(p)}},s=function(p,g){Array.prototype.push.apply(p,(0,n.isArray)(g)?g:[g])};let o;const i={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:e.encode,encodeValuesOnly:!1,format:t.default_format,formatter:t.default_formatter,indices:!1,serializeDate(p){return(o??(o=Function.prototype.call.bind(Date.prototype.toISOString)))(p)},skipNulls:!1,strictNullHandling:!1};function a(p){return typeof p=="string"||typeof p=="number"||typeof p=="boolean"||typeof p=="symbol"||typeof p=="bigint"}const l={};function u(p,g,y,_,b,m,v,A,S,P,E,w,I,L,H,B,F,j){let U=p,O=j,R=0,T=!1;for(;(O=O.get(l))!==void 0&&!T;){const W=O.get(p);if(R+=1,typeof W<"u"){if(W===R)throw new RangeError("Cyclic object value");T=!0}typeof O.get(l)>"u"&&(R=0)}if(typeof P=="function"?U=P(g,U):U instanceof Date?U=I?.(U):y==="comma"&&(0,n.isArray)(U)&&(U=(0,e.maybe_map)(U,function(W){return W instanceof Date?I?.(W):W})),U===null){if(m)return S&&!B?S(g,i.encoder,F,"key",L):g;U=""}if(a(U)||(0,e.is_buffer)(U)){if(S){const W=B?g:S(g,i.encoder,F,"key",L);return[H?.(W)+"="+H?.(S(U,i.encoder,F,"value",L))]}return[H?.(g)+"="+H?.(String(U))]}const M=[];if(typeof U>"u")return M;let k;if(y==="comma"&&(0,n.isArray)(U))B&&S&&(U=(0,e.maybe_map)(U,S)),k=[{value:U.length>0?U.join(",")||null:void 0}];else if((0,n.isArray)(P))k=P;else{const W=Object.keys(U);k=E?W.sort(E):W}const G=A?String(g).replace(/\./g,"%2E"):String(g),V=_&&(0,n.isArray)(U)&&U.length===1?G+"[]":G;if(b&&(0,n.isArray)(U)&&U.length===0)return V+"[]";for(let W=0;W<k.length;++W){const X=k[W],Y=typeof X=="object"&&typeof X.value<"u"?X.value:U[X];if(v&&Y===null)continue;const Z=w&&A?X.replace(/\./g,"%2E"):X,ne=(0,n.isArray)(U)?typeof y=="function"?y(V,Z):V:V+(w?"."+Z:"["+Z+"]");j.set(p,R);const re=new WeakMap;re.set(l,j),s(M,u(Y,ne,y,_,b,m,v,A,y==="comma"&&B&&(0,n.isArray)(U)?null:S,P,E,w,I,L,H,B,F,re))}return M}function c(p=i){if(typeof p.allowEmptyArrays<"u"&&typeof p.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof p.encodeDotInKeys<"u"&&typeof p.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(p.encoder!==null&&typeof p.encoder<"u"&&typeof p.encoder!="function")throw new TypeError("Encoder has to be a function.");const g=p.charset||i.charset;if(typeof p.charset<"u"&&p.charset!=="utf-8"&&p.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let y=t.default_format;if(typeof p.format<"u"){if(!(0,e.has)(t.formatters,p.format))throw new TypeError("Unknown format option provided.");y=p.format}const _=t.formatters[y];let b=i.filter;(typeof p.filter=="function"||(0,n.isArray)(p.filter))&&(b=p.filter);let m;if(p.arrayFormat&&p.arrayFormat in r?m=p.arrayFormat:"indices"in p?m=p.indices?"indices":"repeat":m=i.arrayFormat,"commaRoundTrip"in p&&typeof p.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const v=typeof p.allowDots>"u"?p.encodeDotInKeys?!0:i.allowDots:!!p.allowDots;return{addQueryPrefix:typeof p.addQueryPrefix=="boolean"?p.addQueryPrefix:i.addQueryPrefix,allowDots:v,allowEmptyArrays:typeof p.allowEmptyArrays=="boolean"?!!p.allowEmptyArrays:i.allowEmptyArrays,arrayFormat:m,charset:g,charsetSentinel:typeof p.charsetSentinel=="boolean"?p.charsetSentinel:i.charsetSentinel,commaRoundTrip:!!p.commaRoundTrip,delimiter:typeof p.delimiter>"u"?i.delimiter:p.delimiter,encode:typeof p.encode=="boolean"?p.encode:i.encode,encodeDotInKeys:typeof p.encodeDotInKeys=="boolean"?p.encodeDotInKeys:i.encodeDotInKeys,encoder:typeof p.encoder=="function"?p.encoder:i.encoder,encodeValuesOnly:typeof p.encodeValuesOnly=="boolean"?p.encodeValuesOnly:i.encodeValuesOnly,filter:b,format:y,formatter:_,serializeDate:typeof p.serializeDate=="function"?p.serializeDate:i.serializeDate,skipNulls:typeof p.skipNulls=="boolean"?p.skipNulls:i.skipNulls,sort:typeof p.sort=="function"?p.sort:null,strictNullHandling:typeof p.strictNullHandling=="boolean"?p.strictNullHandling:i.strictNullHandling}}function d(p,g={}){let y=p;const _=c(g);let b,m;typeof _.filter=="function"?(m=_.filter,y=m("",y)):(0,n.isArray)(_.filter)&&(m=_.filter,b=m);const v=[];if(typeof y!="object"||y===null)return"";const A=r[_.arrayFormat],S=A==="comma"&&_.commaRoundTrip;b||(b=Object.keys(y)),_.sort&&b.sort(_.sort);const P=new WeakMap;for(let I=0;I<b.length;++I){const L=b[I];_.skipNulls&&y[L]===null||s(v,u(y[L],L,A,S,_.allowEmptyArrays,_.strictNullHandling,_.skipNulls,_.encodeDotInKeys,_.encode?_.encoder:null,_.filter,_.sort,_.allowDots,_.serializeDate,_.format,_.formatter,_.encodeValuesOnly,_.charset,P))}const E=v.join(_.delimiter);let w=_.addQueryPrefix===!0?"?":"";return _.charsetSentinel&&(_.charset==="iso-8859-1"?w+="utf8=%26%2310003%3B&":w+="utf8=%E2%9C%93&"),E.length>0?w+E:""}return ji}var _h;function wP(){return _h||(_h=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.formats=e.stringify=void 0;const t=jd(),n={formatters:t.formatters,RFC1738:t.RFC1738,RFC3986:t.RFC3986,default:t.default_format};e.formats=n;var r=SP();Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}})})(ru)),ru}var dt={},cs={},gr={},mr={},_r={},yh;function Wd(){if(yh)return _r;yh=1,Object.defineProperty(_r,"__esModule",{value:!0}),_r.concatBytes=e,_r.encodeUTF8=n,_r.decodeUTF8=s;function e(o){let i=0;for(const u of o)i+=u.length;const a=new Uint8Array(i);let l=0;for(const u of o)a.set(u,l),l+=u.length;return a}let t;function n(o){let i;return(t??(i=new globalThis.TextEncoder,t=i.encode.bind(i)))(o)}let r;function s(o){let i;return(r??(i=new globalThis.TextDecoder,r=i.decode.bind(i)))(o)}return _r}var vh;function EP(){if(vh)return mr;vh=1;var e,t;Object.defineProperty(mr,"__esModule",{value:!0}),mr.LineDecoder=void 0,mr.findDoubleNewlineIndex=i;const n=ve(),r=Wd();class s{constructor(){e.set(this,void 0),t.set(this,void 0),n.__classPrivateFieldSet(this,e,new Uint8Array,"f"),n.__classPrivateFieldSet(this,t,null,"f")}decode(l){if(l==null)return[];const u=l instanceof ArrayBuffer?new Uint8Array(l):typeof l=="string"?(0,r.encodeUTF8)(l):l;n.__classPrivateFieldSet(this,e,(0,r.concatBytes)([n.__classPrivateFieldGet(this,e,"f"),u]),"f");const c=[];let d;for(;(d=o(n.__classPrivateFieldGet(this,e,"f"),n.__classPrivateFieldGet(this,t,"f")))!=null;){if(d.carriage&&n.__classPrivateFieldGet(this,t,"f")==null){n.__classPrivateFieldSet(this,t,d.index,"f");continue}if(n.__classPrivateFieldGet(this,t,"f")!=null&&(d.index!==n.__classPrivateFieldGet(this,t,"f")+1||d.carriage)){c.push((0,r.decodeUTF8)(n.__classPrivateFieldGet(this,e,"f").subarray(0,n.__classPrivateFieldGet(this,t,"f")-1))),n.__classPrivateFieldSet(this,e,n.__classPrivateFieldGet(this,e,"f").subarray(n.__classPrivateFieldGet(this,t,"f")),"f"),n.__classPrivateFieldSet(this,t,null,"f");continue}const p=n.__classPrivateFieldGet(this,t,"f")!==null?d.preceding-1:d.preceding,g=(0,r.decodeUTF8)(n.__classPrivateFieldGet(this,e,"f").subarray(0,p));c.push(g),n.__classPrivateFieldSet(this,e,n.__classPrivateFieldGet(this,e,"f").subarray(d.index),"f"),n.__classPrivateFieldSet(this,t,null,"f")}return c}flush(){return n.__classPrivateFieldGet(this,e,"f").length?this.decode(`
11
- `):[]}}mr.LineDecoder=s,e=new WeakMap,t=new WeakMap,s.NEWLINE_CHARS=new Set([`
12
- `,"\r"]),s.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function o(a,l){for(let d=l??0;d<a.length;d++){if(a[d]===10)return{preceding:d,index:d+1,carriage:!1};if(a[d]===13)return{preceding:d,index:d+1,carriage:!0}}return null}function i(a){for(let c=0;c<a.length-1;c++){if(a[c]===10&&a[c+1]===10||a[c]===13&&a[c+1]===13)return c+2;if(a[c]===13&&a[c+1]===10&&c+3<a.length&&a[c+2]===13&&a[c+3]===10)return c+4}return-1}return mr}var Tn={},bh;function Wa(){if(bh)return Tn;bh=1,Object.defineProperty(Tn,"__esModule",{value:!0}),Tn.formatRequestDetails=Tn.parseLogLevel=void 0,Tn.loggerFor=a;const e=kn(),t={off:0,error:200,warn:300,info:400,debug:500},n=(u,c,d)=>{if(u){if((0,e.hasOwn)(t,u))return u;a(d).warn(`${c} was set to ${JSON.stringify(u)}, expected one of ${JSON.stringify(Object.keys(t))}`)}};Tn.parseLogLevel=n;function r(){}function s(u,c,d){return!c||t[u]>t[d]?r:c[u].bind(c)}const o={error:r,warn:r,info:r,debug:r};let i=new WeakMap;function a(u){const c=u.logger,d=u.logLevel??"off";if(!c)return o;const p=i.get(c);if(p&&p[0]===d)return p[1];const g={error:s("error",c,d),warn:s("warn",c,d),info:s("info",c,d),debug:s("debug",c,d)};return i.set(c,[d,g]),g}const l=u=>(u.options&&(u.options={...u.options},delete u.options.headers),u.headers&&(u.headers=Object.fromEntries((u.headers instanceof Headers?[...u.headers]:Object.entries(u.headers)).map(([c,d])=>[c,c.toLowerCase()==="authorization"||c.toLowerCase()==="cookie"||c.toLowerCase()==="set-cookie"?"***":d]))),"retryOfRequestLogID"in u&&(u.retryOfRequestLogID&&(u.retryOf=u.retryOfRequestLogID),delete u.retryOfRequestLogID),u);return Tn.formatRequestDetails=l,Tn}var Ah;function vb(){if(Ah)return gr;Ah=1;var e;Object.defineProperty(gr,"__esModule",{value:!0}),gr.Stream=void 0,gr._iterSSEMessages=d;const t=ve(),n=yn(),r=va(),s=EP(),o=va(),i=Jd(),a=Wd(),l=Wa(),u=yn();class c{constructor(b,m,v){this.iterator=b,e.set(this,void 0),this.controller=m,t.__classPrivateFieldSet(this,e,v,"f")}static fromSSEResponse(b,m,v){let A=!1;const S=v?(0,l.loggerFor)(v):console;async function*P(){if(A)throw new n.OpenAIError("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");A=!0;let E=!1;try{for await(const w of d(b,m))if(!E){if(w.data.startsWith("[DONE]")){E=!0;continue}if(w.event===null||!w.event.startsWith("thread.")){let I;try{I=JSON.parse(w.data)}catch(L){throw S.error("Could not parse message into JSON:",w.data),S.error("From chunk:",w.raw),L}if(I&&I.error)throw new u.APIError(void 0,I.error,void 0,b.headers);yield I}else{let I;try{I=JSON.parse(w.data)}catch(L){throw console.error("Could not parse message into JSON:",w.data),console.error("From chunk:",w.raw),L}if(w.event=="error")throw new u.APIError(void 0,I.error,I.message,void 0);yield{event:w.event,data:I}}}E=!0}catch(w){if((0,i.isAbortError)(w))return;throw w}finally{E||m.abort()}}return new c(P,m,v)}static fromReadableStream(b,m,v){let A=!1;async function*S(){const E=new s.LineDecoder,w=(0,o.ReadableStreamToAsyncIterable)(b);for await(const I of w)for(const L of E.decode(I))yield L;for(const I of E.flush())yield I}async function*P(){if(A)throw new n.OpenAIError("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");A=!0;let E=!1;try{for await(const w of S())E||w&&(yield JSON.parse(w));E=!0}catch(w){if((0,i.isAbortError)(w))return;throw w}finally{E||m.abort()}}return new c(P,m,v)}[(e=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const b=[],m=[],v=this.iterator(),A=S=>({next:()=>{if(S.length===0){const P=v.next();b.push(P),m.push(P)}return S.shift()}});return[new c(()=>A(b),this.controller,t.__classPrivateFieldGet(this,e,"f")),new c(()=>A(m),this.controller,t.__classPrivateFieldGet(this,e,"f"))]}toReadableStream(){const b=this;let m;return(0,r.makeReadableStream)({async start(){m=b[Symbol.asyncIterator]()},async pull(v){try{const{value:A,done:S}=await m.next();if(S)return v.close();const P=(0,a.encodeUTF8)(JSON.stringify(A)+`
13
- `);v.enqueue(P)}catch(A){v.error(A)}},async cancel(){await m.return?.()}})}}gr.Stream=c;async function*d(_,b){if(!_.body)throw b.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new n.OpenAIError("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new n.OpenAIError("Attempted to iterate over a response with no body");const m=new g,v=new s.LineDecoder,A=(0,o.ReadableStreamToAsyncIterable)(_.body);for await(const S of p(A))for(const P of v.decode(S)){const E=m.decode(P);E&&(yield E)}for(const S of v.flush()){const P=m.decode(S);P&&(yield P)}}async function*p(_){let b=new Uint8Array;for await(const m of _){if(m==null)continue;const v=m instanceof ArrayBuffer?new Uint8Array(m):typeof m=="string"?(0,a.encodeUTF8)(m):m;let A=new Uint8Array(b.length+v.length);A.set(b),A.set(v,b.length),b=A;let S;for(;(S=(0,s.findDoubleNewlineIndex)(b))!==-1;)yield b.slice(0,S),b=b.slice(S)}b.length>0&&(yield b)}class g{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(b){if(b.endsWith("\r")&&(b=b.substring(0,b.length-1)),!b){if(!this.event&&!this.data.length)return null;const S={event:this.event,data:this.data.join(`
14
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],S}if(this.chunks.push(b),b.startsWith(":"))return null;let[m,v,A]=y(b,":");return A.startsWith(" ")&&(A=A.substring(1)),m==="event"?this.event=A:m==="data"&&this.data.push(A),null}}function y(_,b){const m=_.indexOf(b);return m!==-1?[_.substring(0,m),b,_.substring(m+b.length)]:[_,"",""]}return gr}var Sh;function bb(){if(Sh)return cs;Sh=1,Object.defineProperty(cs,"__esModule",{value:!0}),cs.defaultParseResponse=n,cs.addRequestID=r;const e=vb(),t=Wa();async function n(s,o){const{response:i,requestLogID:a,retryOfRequestLogID:l,startTime:u}=o,c=await(async()=>{if(o.options.stream)return(0,t.loggerFor)(s).debug("response",i.status,i.url,i.headers,i.body),o.options.__streamClass?o.options.__streamClass.fromSSEResponse(i,o.controller,s):e.Stream.fromSSEResponse(i,o.controller,s);if(i.status===204)return null;if(o.options.__binaryResponse)return i;const p=i.headers.get("content-type")?.split(";")[0]?.trim();if(p?.includes("application/json")||p?.endsWith("+json")){if(i.headers.get("content-length")==="0")return;const b=await i.json();return r(b,i)}return await i.text()})();return(0,t.loggerFor)(s).debug(`[${a}] response parsed`,(0,t.formatRequestDetails)({retryOfRequestLogID:l,url:i.url,status:i.status,body:c,durationMs:Date.now()-u})),c}function r(s,o){return!s||typeof s!="object"||Array.isArray(s)?s:Object.defineProperty(s,"_request_id",{value:o.headers.get("x-request-id"),enumerable:!1})}return cs}var ds={},wh;function Kd(){if(wh)return ds;wh=1;var e;Object.defineProperty(ds,"__esModule",{value:!0}),ds.APIPromise=void 0;const t=ve(),n=bb();class r extends Promise{constructor(o,i,a=n.defaultParseResponse){super(l=>{l(null)}),this.responsePromise=i,this.parseResponse=a,e.set(this,void 0),t.__classPrivateFieldSet(this,e,o,"f")}_thenUnwrap(o){return new r(t.__classPrivateFieldGet(this,e,"f"),this.responsePromise,async(i,a)=>(0,n.addRequestID)(o(await this.parseResponse(i,a),a),a.response))}asResponse(){return this.responsePromise.then(o=>o.response)}async withResponse(){const[o,i]=await Promise.all([this.parse(),this.asResponse()]);return{data:o,response:i,request_id:i.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(o=>this.parseResponse(t.__classPrivateFieldGet(this,e,"f"),o))),this.parsedPromise}then(o,i){return this.parse().then(o,i)}catch(o){return this.parse().catch(o)}finally(o){return this.parse().finally(o)}}return ds.APIPromise=r,e=new WeakMap,ds}var Eh;function ke(){if(Eh)return dt;Eh=1;var e;Object.defineProperty(dt,"__esModule",{value:!0}),dt.ConversationCursorPage=dt.CursorPage=dt.Page=dt.PagePromise=dt.AbstractPage=void 0;const t=ve(),n=yn(),r=bb(),s=Kd(),o=kn();class i{constructor(p,g,y,_){e.set(this,void 0),t.__classPrivateFieldSet(this,e,p,"f"),this.options=_,this.response=g,this.body=y}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const p=this.nextPageRequestOptions();if(!p)throw new n.OpenAIError("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await t.__classPrivateFieldGet(this,e,"f").requestAPIList(this.constructor,p)}async*iterPages(){let p=this;for(yield p;p.hasNextPage();)p=await p.getNextPage(),yield p}async*[(e=new WeakMap,Symbol.asyncIterator)](){for await(const p of this.iterPages())for(const g of p.getPaginatedItems())yield g}}dt.AbstractPage=i;class a extends s.APIPromise{constructor(p,g,y){super(p,g,async(_,b)=>new y(_,b.response,await(0,r.defaultParseResponse)(_,b),b.options))}async*[Symbol.asyncIterator](){const p=await this;for await(const g of p)yield g}}dt.PagePromise=a;class l extends i{constructor(p,g,y,_){super(p,g,y,_),this.data=y.data||[],this.object=y.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}dt.Page=l;class u extends i{constructor(p,g,y,_){super(p,g,y,_),this.data=y.data||[],this.has_more=y.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){const p=this.getPaginatedItems(),g=p[p.length-1]?.id;return g?{...this.options,query:{...(0,o.maybeObj)(this.options.query),after:g}}:null}}dt.CursorPage=u;class c extends i{constructor(p,g,y,_){super(p,g,y,_),this.data=y.data||[],this.has_more=y.has_more||!1,this.last_id=y.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){const p=this.last_id;return p?{...this.options,query:{...(0,o.maybeObj)(this.options.query),after:p}}:null}}return dt.ConversationCursorPage=c,dt}var iu={},Wi={},au={},Th;function vn(){return Th||(Th=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.createForm=e.multipartFormRequestOptions=e.maybeMultipartFormRequestOptions=e.isAsyncIterable=e.checkFileSupport=void 0,e.makeFile=r,e.getName=s;const t=va(),n=()=>{if(typeof File>"u"){const{process:_}=globalThis,b=typeof _?.versions?.node=="string"&&parseInt(_.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(b?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};e.checkFileSupport=n;function r(_,b,m){return(0,e.checkFileSupport)(),new File(_,b??"unknown_file",m)}function s(_){return(typeof _=="object"&&_!==null&&("name"in _&&_.name&&String(_.name)||"url"in _&&_.url&&String(_.url)||"filename"in _&&_.filename&&String(_.filename)||"path"in _&&_.path&&String(_.path))||"").split(/[\\/]/).pop()||void 0}const o=_=>_!=null&&typeof _=="object"&&typeof _[Symbol.asyncIterator]=="function";e.isAsyncIterable=o;const i=async(_,b)=>g(_.body)?{..._,body:await(0,e.createForm)(_.body,b)}:_;e.maybeMultipartFormRequestOptions=i;const a=async(_,b)=>({..._,body:await(0,e.createForm)(_.body,b)});e.multipartFormRequestOptions=a;const l=new WeakMap;function u(_){const b=typeof _=="function"?_:_.fetch,m=l.get(b);if(m)return m;const v=(async()=>{try{const A="Response"in b?b.Response:(await b("data:,")).constructor,S=new FormData;return S.toString()!==await new A(S).text()}catch{return!0}})();return l.set(b,v),v}const c=async(_,b)=>{if(!await u(b))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const m=new FormData;return await Promise.all(Object.entries(_||{}).map(([v,A])=>y(m,v,A))),m};e.createForm=c;const d=_=>_ instanceof Blob&&"name"in _,p=_=>typeof _=="object"&&_!==null&&(_ instanceof Response||(0,e.isAsyncIterable)(_)||d(_)),g=_=>{if(p(_))return!0;if(Array.isArray(_))return _.some(g);if(_&&typeof _=="object"){for(const b in _)if(g(_[b]))return!0}return!1},y=async(_,b,m)=>{if(m!==void 0){if(m==null)throw new TypeError(`Received null for "${b}"; to pass null in FormData, you must use the string 'null'`);if(typeof m=="string"||typeof m=="number"||typeof m=="boolean")_.append(b,String(m));else if(m instanceof Response)_.append(b,r([await m.blob()],s(m)));else if((0,e.isAsyncIterable)(m))_.append(b,r([await new Response((0,t.ReadableStreamFrom)(m)).blob()],s(m)));else if(d(m))_.append(b,m,s(m));else if(Array.isArray(m))await Promise.all(m.map(v=>y(_,b+"[]",v)));else if(typeof m=="object")await Promise.all(Object.entries(m).map(([v,A])=>y(_,`${b}[${v}]`,A)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${m} instead`)}}})(au)),au}var Ph;function TP(){if(Ph)return Wi;Ph=1,Object.defineProperty(Wi,"__esModule",{value:!0}),Wi.toFile=o;const e=vn(),t=vn(),n=l=>l!=null&&typeof l=="object"&&typeof l.size=="number"&&typeof l.type=="string"&&typeof l.text=="function"&&typeof l.slice=="function"&&typeof l.arrayBuffer=="function",r=l=>l!=null&&typeof l=="object"&&typeof l.name=="string"&&typeof l.lastModified=="number"&&n(l),s=l=>l!=null&&typeof l=="object"&&typeof l.url=="string"&&typeof l.blob=="function";async function o(l,u,c){if((0,t.checkFileSupport)(),l=await l,r(l))return l instanceof File?l:(0,e.makeFile)([await l.arrayBuffer()],l.name);if(s(l)){const p=await l.blob();return u||(u=new URL(l.url).pathname.split(/[\\/]/).pop()),(0,e.makeFile)(await i(p),u,c)}const d=await i(l);if(u||(u=(0,e.getName)(l)),!c?.type){const p=d.find(g=>typeof g=="object"&&"type"in g&&g.type);typeof p=="string"&&(c={...c,type:p})}return(0,e.makeFile)(d,u,c)}async function i(l){let u=[];if(typeof l=="string"||ArrayBuffer.isView(l)||l instanceof ArrayBuffer)u.push(l);else if(n(l))u.push(l instanceof Blob?l:await l.arrayBuffer());else if((0,e.isAsyncIterable)(l))for await(const c of l)u.push(...await i(c));else{const c=l?.constructor?.name;throw new Error(`Unexpected data type: ${typeof l}${c?`; constructor: ${c}`:""}${a(l)}`)}return u}function a(l){return typeof l!="object"||l===null?"":`; props: [${Object.getOwnPropertyNames(l).map(c=>`"${c}"`).join(", ")}]`}return Wi}var Ih;function Ab(){return Ih||(Ih=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.toFile=void 0;var t=TP();Object.defineProperty(e,"toFile",{enumerable:!0,get:function(){return t.toFile}})})(iu)),iu}var lu={},uu={},fs={},ps={},Ch;function ce(){if(Ch)return ps;Ch=1,Object.defineProperty(ps,"__esModule",{value:!0}),ps.APIResource=void 0;class e{constructor(n){this._client=n}}return ps.APIResource=e,ps}var cu={},hs={},du={},Rh;function Te(){return Rh||(Rh=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.path=e.createPathTagFunction=void 0,e.encodeURIPath=n;const t=yn();function n(o){return o.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const r=Object.freeze(Object.create(null)),s=(o=n)=>function(a,...l){if(a.length===1)return a[0];let u=!1;const c=[],d=a.reduce((_,b,m)=>{/[?#]/.test(b)&&(u=!0);const v=l[m];let A=(u?encodeURIComponent:o)(""+v);return m!==l.length&&(v==null||typeof v=="object"&&v.toString===Object.getPrototypeOf(Object.getPrototypeOf(v.hasOwnProperty??r)??r)?.toString)&&(A=v+"",c.push({start:_.length+b.length,length:A.length,error:`Value of type ${Object.prototype.toString.call(v).slice(8,-1)} is not a valid path parameter`})),_+b+(m===l.length?"":A)},""),p=d.split(/[?#]/,1)[0],g=new RegExp("(?<=^|\\/)(?:\\.|%2e){1,2}(?=\\/|$)","gi");let y;for(;(y=g.exec(p))!==null;)c.push({start:y.index,length:y[0].length,error:`Value "${y[0]}" can't be safely passed as a path parameter`});if(c.sort((_,b)=>_.start-b.start),c.length>0){let _=0;const b=c.reduce((m,v)=>{const A=" ".repeat(v.start-_),S="^".repeat(v.length);return _=v.start+v.length,m+A+S},"");throw new t.OpenAIError(`Path parameters result in path with invalid segments:
15
- ${c.map(m=>m.error).join(`
16
- `)}
17
- ${d}
18
- ${b}`)}return d};e.createPathTagFunction=s,e.path=(0,e.createPathTagFunction)(n)})(du)),du}var Mh;function Yu(){if(Mh)return hs;Mh=1,Object.defineProperty(hs,"__esModule",{value:!0}),hs.Messages=void 0;const e=ce(),t=ke(),n=Te();class r extends e.APIResource{list(o,i={},a){return this._client.getAPIList((0,n.path)`/chat/completions/${o}/messages`,t.CursorPage,{query:i,...a})}}return hs.Messages=r,hs}var gs={},ms={},fu={},Nh;function Xt(){return Nh||(Nh=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),ve().__exportStar(yn(),e)})(fu)),fu}var et={},Fh;function Ka(){if(Fh)return et;Fh=1,Object.defineProperty(et,"__esModule",{value:!0}),et.isChatCompletionFunctionTool=t,et.makeParseableResponseFormat=n,et.makeParseableTextFormat=r,et.isAutoParsableResponseFormat=s,et.makeParseableTool=o,et.isAutoParsableTool=i,et.maybeParseChatCompletion=a,et.parseChatCompletion=l,et.shouldParseToolCall=d,et.hasAutoParseableInput=p,et.assertToolCallsAreChatCompletionFunctionToolCalls=g,et.validateInputTools=y;const e=Xt();function t(_){return _!==void 0&&"function"in _&&_.function!==void 0}function n(_,b){const m={..._};return Object.defineProperties(m,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:b,enumerable:!1}}),m}function r(_,b){const m={..._};return Object.defineProperties(m,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:b,enumerable:!1}}),m}function s(_){return _?.$brand==="auto-parseable-response-format"}function o(_,{parser:b,callback:m}){const v={..._};return Object.defineProperties(v,{$brand:{value:"auto-parseable-tool",enumerable:!1},$parseRaw:{value:b,enumerable:!1},$callback:{value:m,enumerable:!1}}),v}function i(_){return _?.$brand==="auto-parseable-tool"}function a(_,b){return!b||!p(b)?{..._,choices:_.choices.map(m=>(g(m.message.tool_calls),{...m,message:{...m.message,parsed:null,...m.message.tool_calls?{tool_calls:m.message.tool_calls}:void 0}}))}:l(_,b)}function l(_,b){const m=_.choices.map(v=>{if(v.finish_reason==="length")throw new e.LengthFinishReasonError;if(v.finish_reason==="content_filter")throw new e.ContentFilterFinishReasonError;return g(v.message.tool_calls),{...v,message:{...v.message,...v.message.tool_calls?{tool_calls:v.message.tool_calls?.map(A=>c(b,A))??void 0}:void 0,parsed:v.message.content&&!v.message.refusal?u(b,v.message.content):null}}});return{..._,choices:m}}function u(_,b){return _.response_format?.type!=="json_schema"?null:_.response_format?.type==="json_schema"?"$parseRaw"in _.response_format?_.response_format.$parseRaw(b):JSON.parse(b):null}function c(_,b){const m=_.tools?.find(v=>t(v)&&v.function?.name===b.function.name);return{...b,function:{...b.function,parsed_arguments:i(m)?m.$parseRaw(b.function.arguments):m?.function.strict?JSON.parse(b.function.arguments):null}}}function d(_,b){if(!_||!("tools"in _)||!_.tools)return!1;const m=_.tools?.find(v=>t(v)&&v.function?.name===b.function.name);return t(m)&&(i(m)||m?.function.strict||!1)}function p(_){return s(_.response_format)?!0:_.tools?.some(b=>i(b)||b.type==="function"&&b.function.strict===!0)??!1}function g(_){for(const b of _||[])if(b.type!=="function")throw new e.OpenAIError(`Currently only \`function\` tool calls are supported; Received \`${b.type}\``)}function y(_){for(const b of _??[]){if(b.type!=="function")throw new e.OpenAIError(`Currently only \`function\` tool types support auto-parsing; Received \`${b.type}\``);if(b.function.strict!==!0)throw new e.OpenAIError(`The \`${b.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}return et}var Pn={},kh;function Sb(){if(kh)return Pn;kh=1,Object.defineProperty(Pn,"__esModule",{value:!0}),Pn.isToolMessage=Pn.isAssistantMessage=void 0,Pn.isPresent=n;const e=r=>r?.role==="assistant";Pn.isAssistantMessage=e;const t=r=>r?.role==="tool";Pn.isToolMessage=t;function n(r){return r!=null}return Pn}var _s={},Oh;function $d(){if(Oh)return _s;Oh=1;var e,t,n,r,s,o,i,a,l,u,c,d,p;Object.defineProperty(_s,"__esModule",{value:!0}),_s.EventStream=void 0;const g=ve(),y=Xt();let _=class{constructor(){e.add(this),this.controller=new AbortController,t.set(this,void 0),n.set(this,()=>{}),r.set(this,()=>{}),s.set(this,void 0),o.set(this,()=>{}),i.set(this,()=>{}),a.set(this,{}),l.set(this,!1),u.set(this,!1),c.set(this,!1),d.set(this,!1),g.__classPrivateFieldSet(this,t,new Promise((m,v)=>{g.__classPrivateFieldSet(this,n,m,"f"),g.__classPrivateFieldSet(this,r,v,"f")}),"f"),g.__classPrivateFieldSet(this,s,new Promise((m,v)=>{g.__classPrivateFieldSet(this,o,m,"f"),g.__classPrivateFieldSet(this,i,v,"f")}),"f"),g.__classPrivateFieldGet(this,t,"f").catch(()=>{}),g.__classPrivateFieldGet(this,s,"f").catch(()=>{})}_run(m){setTimeout(()=>{m().then(()=>{this._emitFinal(),this._emit("end")},g.__classPrivateFieldGet(this,e,"m",p).bind(this))},0)}_connected(){this.ended||(g.__classPrivateFieldGet(this,n,"f").call(this),this._emit("connect"))}get ended(){return g.__classPrivateFieldGet(this,l,"f")}get errored(){return g.__classPrivateFieldGet(this,u,"f")}get aborted(){return g.__classPrivateFieldGet(this,c,"f")}abort(){this.controller.abort()}on(m,v){return(g.__classPrivateFieldGet(this,a,"f")[m]||(g.__classPrivateFieldGet(this,a,"f")[m]=[])).push({listener:v}),this}off(m,v){const A=g.__classPrivateFieldGet(this,a,"f")[m];if(!A)return this;const S=A.findIndex(P=>P.listener===v);return S>=0&&A.splice(S,1),this}once(m,v){return(g.__classPrivateFieldGet(this,a,"f")[m]||(g.__classPrivateFieldGet(this,a,"f")[m]=[])).push({listener:v,once:!0}),this}emitted(m){return new Promise((v,A)=>{g.__classPrivateFieldSet(this,d,!0,"f"),m!=="error"&&this.once("error",A),this.once(m,v)})}async done(){g.__classPrivateFieldSet(this,d,!0,"f"),await g.__classPrivateFieldGet(this,s,"f")}_emit(m,...v){if(g.__classPrivateFieldGet(this,l,"f"))return;m==="end"&&(g.__classPrivateFieldSet(this,l,!0,"f"),g.__classPrivateFieldGet(this,o,"f").call(this));const A=g.__classPrivateFieldGet(this,a,"f")[m];if(A&&(g.__classPrivateFieldGet(this,a,"f")[m]=A.filter(S=>!S.once),A.forEach(({listener:S})=>S(...v))),m==="abort"){const S=v[0];!g.__classPrivateFieldGet(this,d,"f")&&!A?.length&&Promise.reject(S),g.__classPrivateFieldGet(this,r,"f").call(this,S),g.__classPrivateFieldGet(this,i,"f").call(this,S),this._emit("end");return}if(m==="error"){const S=v[0];!g.__classPrivateFieldGet(this,d,"f")&&!A?.length&&Promise.reject(S),g.__classPrivateFieldGet(this,r,"f").call(this,S),g.__classPrivateFieldGet(this,i,"f").call(this,S),this._emit("end")}}_emitFinal(){}};return _s.EventStream=_,t=new WeakMap,n=new WeakMap,r=new WeakMap,s=new WeakMap,o=new WeakMap,i=new WeakMap,a=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,e=new WeakSet,p=function(m){if(g.__classPrivateFieldSet(this,u,!0,"f"),m instanceof Error&&m.name==="AbortError"&&(m=new y.APIUserAbortError),m instanceof y.APIUserAbortError)return g.__classPrivateFieldSet(this,c,!0,"f"),this._emit("abort",m);if(m instanceof y.OpenAIError)return this._emit("error",m);if(m instanceof Error){const v=new y.OpenAIError(m.message);return v.cause=m,this._emit("error",v)}return this._emit("error",new y.OpenAIError(String(m)))},_s}var yr={},xh;function wb(){if(xh)return yr;xh=1,Object.defineProperty(yr,"__esModule",{value:!0}),yr.ParsingToolFunction=void 0,yr.isRunnableFunctionWithParse=e;function e(n){return typeof n.parse=="function"}class t{constructor(r){this.type="function",this.function=r}}return yr.ParsingToolFunction=t,yr}var Dh;function Eb(){if(Dh)return ms;Dh=1;var e,t,n,r,s,o,i,a;Object.defineProperty(ms,"__esModule",{value:!0}),ms.AbstractChatCompletionRunner=void 0;const l=ve(),u=Xt(),c=Ka(),d=Sb(),p=$d(),g=wb(),y=10;let _=class extends p.EventStream{constructor(){super(...arguments),e.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(m){this._chatCompletions.push(m),this._emit("chatCompletion",m);const v=m.choices[0]?.message;return v&&this._addMessage(v),m}_addMessage(m,v=!0){if("content"in m||(m.content=null),this.messages.push(m),v){if(this._emit("message",m),(0,d.isToolMessage)(m)&&m.content)this._emit("functionToolCallResult",m.content);else if((0,d.isAssistantMessage)(m)&&m.tool_calls)for(const A of m.tool_calls)A.type==="function"&&this._emit("functionToolCall",A.function)}}async finalChatCompletion(){await this.done();const m=this._chatCompletions[this._chatCompletions.length-1];if(!m)throw new u.OpenAIError("stream ended without producing a ChatCompletion");return m}async finalContent(){return await this.done(),l.__classPrivateFieldGet(this,e,"m",t).call(this)}async finalMessage(){return await this.done(),l.__classPrivateFieldGet(this,e,"m",n).call(this)}async finalFunctionToolCall(){return await this.done(),l.__classPrivateFieldGet(this,e,"m",r).call(this)}async finalFunctionToolCallResult(){return await this.done(),l.__classPrivateFieldGet(this,e,"m",s).call(this)}async totalUsage(){return await this.done(),l.__classPrivateFieldGet(this,e,"m",o).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const m=this._chatCompletions[this._chatCompletions.length-1];m&&this._emit("finalChatCompletion",m);const v=l.__classPrivateFieldGet(this,e,"m",n).call(this);v&&this._emit("finalMessage",v);const A=l.__classPrivateFieldGet(this,e,"m",t).call(this);A&&this._emit("finalContent",A);const S=l.__classPrivateFieldGet(this,e,"m",r).call(this);S&&this._emit("finalFunctionToolCall",S);const P=l.__classPrivateFieldGet(this,e,"m",s).call(this);P!=null&&this._emit("finalFunctionToolCallResult",P),this._chatCompletions.some(E=>E.usage)&&this._emit("totalUsage",l.__classPrivateFieldGet(this,e,"m",o).call(this))}async _createChatCompletion(m,v,A){const S=A?.signal;S&&(S.aborted&&this.controller.abort(),S.addEventListener("abort",()=>this.controller.abort())),l.__classPrivateFieldGet(this,e,"m",i).call(this,v);const P=await m.chat.completions.create({...v,stream:!1},{...A,signal:this.controller.signal});return this._connected(),this._addChatCompletion((0,c.parseChatCompletion)(P,v))}async _runChatCompletion(m,v,A){for(const S of v.messages)this._addMessage(S,!1);return await this._createChatCompletion(m,v,A)}async _runTools(m,v,A){const S="tool",{tool_choice:P="auto",stream:E,...w}=v,I=typeof P!="string"&&P.type==="function"&&P?.function?.name,{maxChatCompletions:L=y}=A||{},H=v.tools.map(j=>{if((0,c.isAutoParsableTool)(j)){if(!j.$callback)throw new u.OpenAIError("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:j.$callback,name:j.function.name,description:j.function.description||"",parameters:j.function.parameters,parse:j.$parseRaw,strict:!0}}}return j}),B={};for(const j of H)j.type==="function"&&(B[j.function.name||j.function.function.name]=j.function);const F="tools"in v?H.map(j=>j.type==="function"?{type:"function",function:{name:j.function.name||j.function.function.name,parameters:j.function.parameters,description:j.function.description,strict:j.function.strict}}:j):void 0;for(const j of v.messages)this._addMessage(j,!1);for(let j=0;j<L;++j){const O=(await this._createChatCompletion(m,{...w,tool_choice:P,tools:F,messages:[...this.messages]},A)).choices[0]?.message;if(!O)throw new u.OpenAIError("missing message in ChatCompletion response");if(!O.tool_calls?.length)return;for(const R of O.tool_calls){if(R.type!=="function")continue;const T=R.id,{name:M,arguments:k}=R.function,G=B[M];if(G){if(I&&I!==M){const Y=`Invalid tool_call: ${JSON.stringify(M)}. ${JSON.stringify(I)} requested. Please try again`;this._addMessage({role:S,tool_call_id:T,content:Y});continue}}else{const Y=`Invalid tool_call: ${JSON.stringify(M)}. Available options are: ${Object.keys(B).map(Z=>JSON.stringify(Z)).join(", ")}. Please try again`;this._addMessage({role:S,tool_call_id:T,content:Y});continue}let V;try{V=(0,g.isRunnableFunctionWithParse)(G)?await G.parse(k):k}catch(Y){const Z=Y instanceof Error?Y.message:String(Y);this._addMessage({role:S,tool_call_id:T,content:Z});continue}const W=await G.function(V,this),X=l.__classPrivateFieldGet(this,e,"m",a).call(this,W);if(this._addMessage({role:S,tool_call_id:T,content:X}),I)return}}}};return ms.AbstractChatCompletionRunner=_,e=new WeakSet,t=function(){return l.__classPrivateFieldGet(this,e,"m",n).call(this).content??null},n=function(){let m=this.messages.length;for(;m-- >0;){const v=this.messages[m];if((0,d.isAssistantMessage)(v))return{...v,content:v.content??null,refusal:v.refusal??null}}throw new u.OpenAIError("stream ended without producing a ChatCompletionMessage with role=assistant")},r=function(){for(let m=this.messages.length-1;m>=0;m--){const v=this.messages[m];if((0,d.isAssistantMessage)(v)&&v?.tool_calls?.length)return v.tool_calls.filter(A=>A.type==="function").at(-1)?.function}},s=function(){for(let m=this.messages.length-1;m>=0;m--){const v=this.messages[m];if((0,d.isToolMessage)(v)&&v.content!=null&&typeof v.content=="string"&&this.messages.some(A=>A.role==="assistant"&&A.tool_calls?.some(S=>S.type==="function"&&S.id===v.tool_call_id)))return v.content}},o=function(){const m={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:v}of this._chatCompletions)v&&(m.completion_tokens+=v.completion_tokens,m.prompt_tokens+=v.prompt_tokens,m.total_tokens+=v.total_tokens);return m},i=function(m){if(m.n!=null&&m.n>1)throw new u.OpenAIError("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},a=function(m){return typeof m=="string"?m:m===void 0?"undefined":JSON.stringify(m)},ms}var qh;function Lh(){if(qh)return gs;qh=1,Object.defineProperty(gs,"__esModule",{value:!0}),gs.ChatCompletionRunner=void 0;const e=Eb(),t=Sb();let n=class Tb extends e.AbstractChatCompletionRunner{static runTools(s,o,i){const a=new Tb,l={...i,headers:{...i?.headers,"X-Stainless-Helper-Method":"runTools"}};return a._run(()=>a._runTools(s,o,l)),a}_addMessage(s,o=!0){super._addMessage(s,o),(0,t.isAssistantMessage)(s)&&s.content&&this._emit("content",s.content)}};return gs.ChatCompletionRunner=n,gs}var ys={},vs={},an={},Uh;function PP(){if(Uh)return an;Uh=1,Object.defineProperty(an,"__esModule",{value:!0}),an.MalformedJSON=an.PartialJSON=an.partialParse=void 0;const e=1,t=2,n=4,r=8,s=16,o=32,i=64,a=128,l=256,u=a|l,c=s|o|u|i,d=e|t|c,p=n|r,g=d|p,y={STR:e,NUM:t,ARR:n,OBJ:r,NULL:s,BOOL:o,NAN:i,INFINITY:a,MINUS_INFINITY:l,INF:u,SPECIAL:c,ATOM:d,COLLECTION:p,ALL:g};class _ extends Error{}an.PartialJSON=_;class b extends Error{}an.MalformedJSON=b;function m(S,P=y.ALL){if(typeof S!="string")throw new TypeError(`expecting str, got ${typeof S}`);if(!S.trim())throw new Error(`${S} is empty`);return v(S.trim(),P)}const v=(S,P)=>{const E=S.length;let w=0;const I=R=>{throw new _(`${R} at position ${w}`)},L=R=>{throw new b(`${R} at position ${w}`)},H=()=>(O(),w>=E&&I("Unexpected end of input"),S[w]==='"'?B():S[w]==="{"?F():S[w]==="["?j():S.substring(w,w+4)==="null"||y.NULL&P&&E-w<4&&"null".startsWith(S.substring(w))?(w+=4,null):S.substring(w,w+4)==="true"||y.BOOL&P&&E-w<4&&"true".startsWith(S.substring(w))?(w+=4,!0):S.substring(w,w+5)==="false"||y.BOOL&P&&E-w<5&&"false".startsWith(S.substring(w))?(w+=5,!1):S.substring(w,w+8)==="Infinity"||y.INFINITY&P&&E-w<8&&"Infinity".startsWith(S.substring(w))?(w+=8,1/0):S.substring(w,w+9)==="-Infinity"||y.MINUS_INFINITY&P&&1<E-w&&E-w<9&&"-Infinity".startsWith(S.substring(w))?(w+=9,-1/0):S.substring(w,w+3)==="NaN"||y.NAN&P&&E-w<3&&"NaN".startsWith(S.substring(w))?(w+=3,NaN):U()),B=()=>{const R=w;let T=!1;for(w++;w<E&&(S[w]!=='"'||T&&S[w-1]==="\\");)T=S[w]==="\\"?!T:!1,w++;if(S.charAt(w)=='"')try{return JSON.parse(S.substring(R,++w-Number(T)))}catch(M){L(String(M))}else if(y.STR&P)try{return JSON.parse(S.substring(R,w-Number(T))+'"')}catch{return JSON.parse(S.substring(R,S.lastIndexOf("\\"))+'"')}I("Unterminated string literal")},F=()=>{w++,O();const R={};try{for(;S[w]!=="}";){if(O(),w>=E&&y.OBJ&P)return R;const T=B();O(),w++;try{const M=H();Object.defineProperty(R,T,{value:M,writable:!0,enumerable:!0,configurable:!0})}catch(M){if(y.OBJ&P)return R;throw M}O(),S[w]===","&&w++}}catch{if(y.OBJ&P)return R;I("Expected '}' at end of object")}return w++,R},j=()=>{w++;const R=[];try{for(;S[w]!=="]";)R.push(H()),O(),S[w]===","&&w++}catch{if(y.ARR&P)return R;I("Expected ']' at end of array")}return w++,R},U=()=>{if(w===0){S==="-"&&y.NUM&P&&I("Not sure what '-' is");try{return JSON.parse(S)}catch(T){if(y.NUM&P)try{return S[S.length-1]==="."?JSON.parse(S.substring(0,S.lastIndexOf("."))):JSON.parse(S.substring(0,S.lastIndexOf("e")))}catch{}L(String(T))}}const R=w;for(S[w]==="-"&&w++;S[w]&&!",]}".includes(S[w]);)w++;w==E&&!(y.NUM&P)&&I("Unterminated number literal");try{return JSON.parse(S.substring(R,w))}catch{S.substring(R,w)==="-"&&y.NUM&P&&I("Not sure what '-' is");try{return JSON.parse(S.substring(R,S.lastIndexOf("e")))}catch(M){L(String(M))}}},O=()=>{for(;w<E&&`
19
- \r `.includes(S[w]);)w++};return H()},A=S=>m(S,y.ALL^y.NUM);return an.partialParse=A,an}var pu={},Gh;function Pb(){return Gh||(Gh=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),ve().__exportStar(vb(),e)})(pu)),pu}var Vh;function Xu(){if(Vh)return vs;Vh=1;var e,t,n,r,s,o,i,a,l,u,c,d;Object.defineProperty(vs,"__esModule",{value:!0}),vs.ChatCompletionStream=void 0;const p=ve(),g=PP(),y=Xt(),_=Ka(),b=Pb(),m=Eb();let v=class zu extends m.AbstractChatCompletionRunner{constructor(w){super(),e.add(this),t.set(this,void 0),n.set(this,void 0),r.set(this,void 0),p.__classPrivateFieldSet(this,t,w,"f"),p.__classPrivateFieldSet(this,n,[],"f")}get currentChatCompletionSnapshot(){return p.__classPrivateFieldGet(this,r,"f")}static fromReadableStream(w){const I=new zu(null);return I._run(()=>I._fromReadableStream(w)),I}static createChatCompletion(w,I,L){const H=new zu(I);return H._run(()=>H._runChatCompletion(w,{...I,stream:!0},{...L,headers:{...L?.headers,"X-Stainless-Helper-Method":"stream"}})),H}async _createChatCompletion(w,I,L){super._createChatCompletion;const H=L?.signal;H&&(H.aborted&&this.controller.abort(),H.addEventListener("abort",()=>this.controller.abort())),p.__classPrivateFieldGet(this,e,"m",s).call(this);const B=await w.chat.completions.create({...I,stream:!0},{...L,signal:this.controller.signal});this._connected();for await(const F of B)p.__classPrivateFieldGet(this,e,"m",i).call(this,F);if(B.controller.signal?.aborted)throw new y.APIUserAbortError;return this._addChatCompletion(p.__classPrivateFieldGet(this,e,"m",u).call(this))}async _fromReadableStream(w,I){const L=I?.signal;L&&(L.aborted&&this.controller.abort(),L.addEventListener("abort",()=>this.controller.abort())),p.__classPrivateFieldGet(this,e,"m",s).call(this),this._connected();const H=b.Stream.fromReadableStream(w,this.controller);let B;for await(const F of H)B&&B!==F.id&&this._addChatCompletion(p.__classPrivateFieldGet(this,e,"m",u).call(this)),p.__classPrivateFieldGet(this,e,"m",i).call(this,F),B=F.id;if(H.controller.signal?.aborted)throw new y.APIUserAbortError;return this._addChatCompletion(p.__classPrivateFieldGet(this,e,"m",u).call(this))}[(t=new WeakMap,n=new WeakMap,r=new WeakMap,e=new WeakSet,s=function(){this.ended||p.__classPrivateFieldSet(this,r,void 0,"f")},o=function(I){let L=p.__classPrivateFieldGet(this,n,"f")[I.index];return L||(L={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},p.__classPrivateFieldGet(this,n,"f")[I.index]=L,L)},i=function(I){if(this.ended)return;const L=p.__classPrivateFieldGet(this,e,"m",d).call(this,I);this._emit("chunk",I,L);for(const H of I.choices){const B=L.choices[H.index];H.delta.content!=null&&B.message?.role==="assistant"&&B.message?.content&&(this._emit("content",H.delta.content,B.message.content),this._emit("content.delta",{delta:H.delta.content,snapshot:B.message.content,parsed:B.message.parsed})),H.delta.refusal!=null&&B.message?.role==="assistant"&&B.message?.refusal&&this._emit("refusal.delta",{delta:H.delta.refusal,snapshot:B.message.refusal}),H.logprobs?.content!=null&&B.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:H.logprobs?.content,snapshot:B.logprobs?.content??[]}),H.logprobs?.refusal!=null&&B.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:H.logprobs?.refusal,snapshot:B.logprobs?.refusal??[]});const F=p.__classPrivateFieldGet(this,e,"m",o).call(this,B);B.finish_reason&&(p.__classPrivateFieldGet(this,e,"m",l).call(this,B),F.current_tool_call_index!=null&&p.__classPrivateFieldGet(this,e,"m",a).call(this,B,F.current_tool_call_index));for(const j of H.delta.tool_calls??[])F.current_tool_call_index!==j.index&&(p.__classPrivateFieldGet(this,e,"m",l).call(this,B),F.current_tool_call_index!=null&&p.__classPrivateFieldGet(this,e,"m",a).call(this,B,F.current_tool_call_index)),F.current_tool_call_index=j.index;for(const j of H.delta.tool_calls??[]){const U=B.message.tool_calls?.[j.index];U?.type&&(U?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:U.function?.name,index:j.index,arguments:U.function.arguments,parsed_arguments:U.function.parsed_arguments,arguments_delta:j.function?.arguments??""}):(U?.type,void 0))}}},a=function(I,L){if(p.__classPrivateFieldGet(this,e,"m",o).call(this,I).done_tool_calls.has(L))return;const B=I.message.tool_calls?.[L];if(!B)throw new Error("no tool call snapshot");if(!B.type)throw new Error("tool call snapshot missing `type`");if(B.type==="function"){const F=p.__classPrivateFieldGet(this,t,"f")?.tools?.find(j=>(0,_.isChatCompletionFunctionTool)(j)&&j.function.name===B.function.name);this._emit("tool_calls.function.arguments.done",{name:B.function.name,index:L,arguments:B.function.arguments,parsed_arguments:(0,_.isAutoParsableTool)(F)?F.$parseRaw(B.function.arguments):F?.function.strict?JSON.parse(B.function.arguments):null})}else B.type},l=function(I){const L=p.__classPrivateFieldGet(this,e,"m",o).call(this,I);if(I.message.content&&!L.content_done){L.content_done=!0;const H=p.__classPrivateFieldGet(this,e,"m",c).call(this);this._emit("content.done",{content:I.message.content,parsed:H?H.$parseRaw(I.message.content):null})}I.message.refusal&&!L.refusal_done&&(L.refusal_done=!0,this._emit("refusal.done",{refusal:I.message.refusal})),I.logprobs?.content&&!L.logprobs_content_done&&(L.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:I.logprobs.content})),I.logprobs?.refusal&&!L.logprobs_refusal_done&&(L.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:I.logprobs.refusal}))},u=function(){if(this.ended)throw new y.OpenAIError("stream has ended, this shouldn't happen");const I=p.__classPrivateFieldGet(this,r,"f");if(!I)throw new y.OpenAIError("request ended without sending any chunks");return p.__classPrivateFieldSet(this,r,void 0,"f"),p.__classPrivateFieldSet(this,n,[],"f"),A(I,p.__classPrivateFieldGet(this,t,"f"))},c=function(){const I=p.__classPrivateFieldGet(this,t,"f")?.response_format;return(0,_.isAutoParsableResponseFormat)(I)?I:null},d=function(I){var L,H,B,F;let j=p.__classPrivateFieldGet(this,r,"f");const{choices:U,...O}=I;j?Object.assign(j,O):j=p.__classPrivateFieldSet(this,r,{...O,choices:[]},"f");for(const{delta:R,finish_reason:T,index:M,logprobs:k=null,...G}of I.choices){let V=j.choices[M];if(V||(V=j.choices[M]={finish_reason:T,index:M,message:{},logprobs:k,...G}),k)if(!V.logprobs)V.logprobs=Object.assign({},k);else{const{content:Ae,refusal:le,...we}=k;Object.assign(V.logprobs,we),Ae&&((L=V.logprobs).content??(L.content=[]),V.logprobs.content.push(...Ae)),le&&((H=V.logprobs).refusal??(H.refusal=[]),V.logprobs.refusal.push(...le))}if(T&&(V.finish_reason=T,p.__classPrivateFieldGet(this,t,"f")&&(0,_.hasAutoParseableInput)(p.__classPrivateFieldGet(this,t,"f")))){if(T==="length")throw new y.LengthFinishReasonError;if(T==="content_filter")throw new y.ContentFilterFinishReasonError}if(Object.assign(V,G),!R)continue;const{content:W,refusal:X,function_call:Y,role:Z,tool_calls:ne,...re}=R;if(Object.assign(V.message,re),X&&(V.message.refusal=(V.message.refusal||"")+X),Z&&(V.message.role=Z),Y&&(V.message.function_call?(Y.name&&(V.message.function_call.name=Y.name),Y.arguments&&((B=V.message.function_call).arguments??(B.arguments=""),V.message.function_call.arguments+=Y.arguments)):V.message.function_call=Y),W&&(V.message.content=(V.message.content||"")+W,!V.message.refusal&&p.__classPrivateFieldGet(this,e,"m",c).call(this)&&(V.message.parsed=(0,g.partialParse)(V.message.content))),ne){V.message.tool_calls||(V.message.tool_calls=[]);for(const{index:Ae,id:le,type:we,function:ee,...C}of ne){const D=(F=V.message.tool_calls)[Ae]??(F[Ae]={});Object.assign(D,C),le&&(D.id=le),we&&(D.type=we),ee&&(D.function??(D.function={name:ee.name??"",arguments:""})),ee?.name&&(D.function.name=ee.name),ee?.arguments&&(D.function.arguments+=ee.arguments,(0,_.shouldParseToolCall)(p.__classPrivateFieldGet(this,t,"f"),D)&&(D.function.parsed_arguments=(0,g.partialParse)(D.function.arguments)))}}}return j},Symbol.asyncIterator)](){const w=[],I=[];let L=!1;return this.on("chunk",H=>{const B=I.shift();B?B.resolve(H):w.push(H)}),this.on("end",()=>{L=!0;for(const H of I)H.resolve(void 0);I.length=0}),this.on("abort",H=>{L=!0;for(const B of I)B.reject(H);I.length=0}),this.on("error",H=>{L=!0;for(const B of I)B.reject(H);I.length=0}),{next:async()=>w.length?{value:w.shift(),done:!1}:L?{value:void 0,done:!0}:new Promise((B,F)=>I.push({resolve:B,reject:F})).then(B=>B?{value:B,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new b.Stream(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};vs.ChatCompletionStream=v;function A(E,w){const{id:I,choices:L,created:H,model:B,system_fingerprint:F,...j}=E,U={...j,id:I,choices:L.map(({message:O,finish_reason:R,index:T,logprobs:M,...k})=>{if(!R)throw new y.OpenAIError(`missing finish_reason for choice ${T}`);const{content:G=null,function_call:V,tool_calls:W,...X}=O,Y=O.role;if(!Y)throw new y.OpenAIError(`missing role for choice ${T}`);if(V){const{arguments:Z,name:ne}=V;if(Z==null)throw new y.OpenAIError(`missing function_call.arguments for choice ${T}`);if(!ne)throw new y.OpenAIError(`missing function_call.name for choice ${T}`);return{...k,message:{content:G,function_call:{arguments:Z,name:ne},role:Y,refusal:O.refusal??null},finish_reason:R,index:T,logprobs:M}}return W?{...k,index:T,finish_reason:R,logprobs:M,message:{...X,role:Y,content:G,refusal:O.refusal??null,tool_calls:W.map((Z,ne)=>{const{function:re,type:Ae,id:le,...we}=Z,{arguments:ee,name:C,...D}=re||{};if(le==null)throw new y.OpenAIError(`missing choices[${T}].tool_calls[${ne}].id
20
- ${S(E)}`);if(Ae==null)throw new y.OpenAIError(`missing choices[${T}].tool_calls[${ne}].type
21
- ${S(E)}`);if(C==null)throw new y.OpenAIError(`missing choices[${T}].tool_calls[${ne}].function.name
22
- ${S(E)}`);if(ee==null)throw new y.OpenAIError(`missing choices[${T}].tool_calls[${ne}].function.arguments
23
- ${S(E)}`);return{...we,id:le,type:Ae,function:{...D,name:C,arguments:ee}}})}}:{...k,message:{...X,content:G,role:Y,refusal:O.refusal??null},finish_reason:R,index:T,logprobs:M}}),created:H,model:B,object:"chat.completion",...F?{system_fingerprint:F}:{}};return(0,_.maybeParseChatCompletion)(U,w)}function S(E){return JSON.stringify(E)}function P(E){}return vs}var Bh;function Hh(){if(Bh)return ys;Bh=1,Object.defineProperty(ys,"__esModule",{value:!0}),ys.ChatCompletionStreamingRunner=void 0;const e=Xu();let t=class Qu extends e.ChatCompletionStream{static fromReadableStream(r){const s=new Qu(null);return s._run(()=>s._fromReadableStream(r)),s}static runTools(r,s,o){const i=new Qu(s),a={...o,headers:{...o?.headers,"X-Stainless-Helper-Method":"runTools"}};return i._run(()=>i._runTools(r,s,a)),i}};return ys.ChatCompletionStreamingRunner=t,ys}var Jh;function ba(){return Jh||(Jh=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ChatCompletionRunner=e.ChatCompletionStream=e.ParsingToolFunction=e.ChatCompletionStreamingRunner=e.Completions=void 0;const t=ve(),n=ce(),r=t.__importStar(Yu()),s=Yu(),o=ke(),i=Te(),a=Lh(),l=Hh(),u=Xu(),c=Ka();class d extends n.APIResource{constructor(){super(...arguments),this.messages=new r.Messages(this._client)}create(m,v){return this._client.post("/chat/completions",{body:m,...v,stream:m.stream??!1})}retrieve(m,v){return this._client.get((0,i.path)`/chat/completions/${m}`,v)}update(m,v,A){return this._client.post((0,i.path)`/chat/completions/${m}`,{body:v,...A})}list(m={},v){return this._client.getAPIList("/chat/completions",o.CursorPage,{query:m,...v})}delete(m,v){return this._client.delete((0,i.path)`/chat/completions/${m}`,v)}parse(m,v){return(0,c.validateInputTools)(m.tools),this._client.chat.completions.create(m,{...v,headers:{...v?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(A=>(0,c.parseChatCompletion)(A,m))}runTools(m,v){return m.stream?l.ChatCompletionStreamingRunner.runTools(this._client,m,v):a.ChatCompletionRunner.runTools(this._client,m,v)}stream(m,v){return u.ChatCompletionStream.createChatCompletion(this._client,m,v)}}e.Completions=d;var p=Hh();Object.defineProperty(e,"ChatCompletionStreamingRunner",{enumerable:!0,get:function(){return p.ChatCompletionStreamingRunner}});var g=wb();Object.defineProperty(e,"ParsingToolFunction",{enumerable:!0,get:function(){return g.ParsingToolFunction}});var y=Xu();Object.defineProperty(e,"ChatCompletionStream",{enumerable:!0,get:function(){return y.ChatCompletionStream}});var _=Lh();Object.defineProperty(e,"ChatCompletionRunner",{enumerable:!0,get:function(){return _.ChatCompletionRunner}}),d.Messages=s.Messages})(cu)),cu}var jh;function Ib(){if(jh)return fs;jh=1,Object.defineProperty(fs,"__esModule",{value:!0}),fs.Chat=void 0;const e=ve(),t=ce(),n=e.__importStar(ba()),r=ba();class s extends t.APIResource{constructor(){super(...arguments),this.completions=new n.Completions(this._client)}}return fs.Chat=s,s.Completions=r.Completions,fs}var hu={},Wh;function IP(){return Wh||(Wh=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Messages=e.Completions=void 0;const t=ve();var n=ba();Object.defineProperty(e,"Completions",{enumerable:!0,get:function(){return n.Completions}}),t.__exportStar(ba(),e);var r=Yu();Object.defineProperty(e,"Messages",{enumerable:!0,get:function(){return r.Messages}})})(hu)),hu}var Kh;function CP(){return Kh||(Kh=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Completions=e.Chat=void 0;var t=Ib();Object.defineProperty(e,"Chat",{enumerable:!0,get:function(){return t.Chat}});var n=IP();Object.defineProperty(e,"Completions",{enumerable:!0,get:function(){return n.Completions}})})(uu)),uu}var gu={},$h;function RP(){return $h||($h=1,Object.defineProperty(gu,"__esModule",{value:!0})),gu}var bs={},As={},Kn={},Yh;function De(){if(Yh)return Kn;Yh=1,Object.defineProperty(Kn,"__esModule",{value:!0}),Kn.isEmptyHeaders=Kn.buildHeaders=void 0;const e=kn(),t=Symbol("brand.privateNullableHeaders");function*n(o){if(!o)return;if(t in o){const{values:l,nulls:u}=o;yield*l.entries();for(const c of u)yield[c,null];return}let i=!1,a;o instanceof Headers?a=o.entries():(0,e.isReadonlyArray)(o)?a=o:(i=!0,a=Object.entries(o??{}));for(let l of a){const u=l[0];if(typeof u!="string")throw new TypeError("expected header name to be a string");const c=(0,e.isReadonlyArray)(l[1])?l[1]:[l[1]];let d=!1;for(const p of c)p!==void 0&&(i&&!d&&(d=!0,yield[u,null]),yield[u,p])}}const r=o=>{const i=new Headers,a=new Set;for(const l of o){const u=new Set;for(const[c,d]of n(l)){const p=c.toLowerCase();u.has(p)||(i.delete(c),u.add(p)),d===null?(i.delete(c),a.add(p)):(i.append(c,d),a.delete(p))}}return{[t]:!0,values:i,nulls:a}};Kn.buildHeaders=r;const s=o=>{for(const i of n(o))return!1;return!0};return Kn.isEmptyHeaders=s,Kn}var zh;function Xh(){if(zh)return As;zh=1,Object.defineProperty(As,"__esModule",{value:!0}),As.Speech=void 0;const e=ce(),t=De();class n extends e.APIResource{create(s,o){return this._client.post("/audio/speech",{body:s,...o,headers:(0,t.buildHeaders)([{Accept:"application/octet-stream"},o?.headers]),__binaryResponse:!0})}}return As.Speech=n,As}var Ss={},Qh;function Zh(){if(Qh)return Ss;Qh=1,Object.defineProperty(Ss,"__esModule",{value:!0}),Ss.Transcriptions=void 0;const e=ce(),t=vn();class n extends e.APIResource{create(s,o){return this._client.post("/audio/transcriptions",(0,t.multipartFormRequestOptions)({body:s,...o,stream:s.stream??!1,__metadata:{model:s.model}},this._client))}}return Ss.Transcriptions=n,Ss}var ws={},eg;function tg(){if(eg)return ws;eg=1,Object.defineProperty(ws,"__esModule",{value:!0}),ws.Translations=void 0;const e=ce(),t=vn();class n extends e.APIResource{create(s,o){return this._client.post("/audio/translations",(0,t.multipartFormRequestOptions)({body:s,...o,__metadata:{model:s.model}},this._client))}}return ws.Translations=n,ws}var ng;function Cb(){if(ng)return bs;ng=1,Object.defineProperty(bs,"__esModule",{value:!0}),bs.Audio=void 0;const e=ve(),t=ce(),n=e.__importStar(Xh()),r=Xh(),s=e.__importStar(Zh()),o=Zh(),i=e.__importStar(tg()),a=tg();class l extends t.APIResource{constructor(){super(...arguments),this.transcriptions=new s.Transcriptions(this._client),this.translations=new i.Translations(this._client),this.speech=new n.Speech(this._client)}}return bs.Audio=l,l.Transcriptions=o.Transcriptions,l.Translations=a.Translations,l.Speech=r.Speech,bs}var Es={},rg;function Rb(){if(rg)return Es;rg=1,Object.defineProperty(Es,"__esModule",{value:!0}),Es.Batches=void 0;const e=ce(),t=ke(),n=Te();class r extends e.APIResource{create(o,i){return this._client.post("/batches",{body:o,...i})}retrieve(o,i){return this._client.get((0,n.path)`/batches/${o}`,i)}list(o={},i){return this._client.getAPIList("/batches",t.CursorPage,{query:o,...i})}cancel(o,i){return this._client.post((0,n.path)`/batches/${o}/cancel`,i)}}return Es.Batches=r,Es}var Ts={},Ps={},sg;function og(){if(sg)return Ps;sg=1,Object.defineProperty(Ps,"__esModule",{value:!0}),Ps.Assistants=void 0;const e=ce(),t=ke(),n=De(),r=Te();class s extends e.APIResource{create(i,a){return this._client.post("/assistants",{body:i,...a,headers:(0,n.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},a?.headers])})}retrieve(i,a){return this._client.get((0,r.path)`/assistants/${i}`,{...a,headers:(0,n.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},a?.headers])})}update(i,a,l){return this._client.post((0,r.path)`/assistants/${i}`,{body:a,...l,headers:(0,n.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},l?.headers])})}list(i={},a){return this._client.getAPIList("/assistants",t.CursorPage,{query:i,...a,headers:(0,n.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},a?.headers])})}delete(i,a){return this._client.delete((0,r.path)`/assistants/${i}`,{...a,headers:(0,n.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},a?.headers])})}}return Ps.Assistants=s,Ps}var Is={},Cs={},ig;function ag(){if(ig)return Cs;ig=1,Object.defineProperty(Cs,"__esModule",{value:!0}),Cs.Sessions=void 0;const e=ce(),t=De();class n extends e.APIResource{create(s,o){return this._client.post("/realtime/sessions",{body:s,...o,headers:(0,t.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},o?.headers])})}}return Cs.Sessions=n,Cs}var Rs={},lg;function ug(){if(lg)return Rs;lg=1,Object.defineProperty(Rs,"__esModule",{value:!0}),Rs.TranscriptionSessions=void 0;const e=ce(),t=De();class n extends e.APIResource{create(s,o){return this._client.post("/realtime/transcription_sessions",{body:s,...o,headers:(0,t.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},o?.headers])})}}return Rs.TranscriptionSessions=n,Rs}var cg;function dg(){if(cg)return Is;cg=1,Object.defineProperty(Is,"__esModule",{value:!0}),Is.Realtime=void 0;const e=ve(),t=ce(),n=e.__importStar(ag()),r=ag(),s=e.__importStar(ug()),o=ug();class i extends t.APIResource{constructor(){super(...arguments),this.sessions=new n.Sessions(this._client),this.transcriptionSessions=new s.TranscriptionSessions(this._client)}}return Is.Realtime=i,i.Sessions=r.Sessions,i.TranscriptionSessions=o.TranscriptionSessions,Is}var Ms={},Ns={},fg;function pg(){if(fg)return Ns;fg=1,Object.defineProperty(Ns,"__esModule",{value:!0}),Ns.Sessions=void 0;const e=ce(),t=De(),n=Te();class r extends e.APIResource{create(o,i){return this._client.post("/chatkit/sessions",{body:o,...i,headers:(0,t.buildHeaders)([{"OpenAI-Beta":"chatkit_beta=v1"},i?.headers])})}cancel(o,i){return this._client.post((0,n.path)`/chatkit/sessions/${o}/cancel`,{...i,headers:(0,t.buildHeaders)([{"OpenAI-Beta":"chatkit_beta=v1"},i?.headers])})}}return Ns.Sessions=r,Ns}var Fs={},hg;function gg(){if(hg)return Fs;hg=1,Object.defineProperty(Fs,"__esModule",{value:!0}),Fs.Threads=void 0;const e=ce(),t=ke(),n=De(),r=Te();class s extends e.APIResource{retrieve(i,a){return this._client.get((0,r.path)`/chatkit/threads/${i}`,{...a,headers:(0,n.buildHeaders)([{"OpenAI-Beta":"chatkit_beta=v1"},a?.headers])})}list(i={},a){return this._client.getAPIList("/chatkit/threads",t.ConversationCursorPage,{query:i,...a,headers:(0,n.buildHeaders)([{"OpenAI-Beta":"chatkit_beta=v1"},a?.headers])})}delete(i,a){return this._client.delete((0,r.path)`/chatkit/threads/${i}`,{...a,headers:(0,n.buildHeaders)([{"OpenAI-Beta":"chatkit_beta=v1"},a?.headers])})}listItems(i,a={},l){return this._client.getAPIList((0,r.path)`/chatkit/threads/${i}/items`,t.ConversationCursorPage,{query:a,...l,headers:(0,n.buildHeaders)([{"OpenAI-Beta":"chatkit_beta=v1"},l?.headers])})}}return Fs.Threads=s,Fs}var mg;function _g(){if(mg)return Ms;mg=1,Object.defineProperty(Ms,"__esModule",{value:!0}),Ms.ChatKit=void 0;const e=ve(),t=ce(),n=e.__importStar(pg()),r=pg(),s=e.__importStar(gg()),o=gg();class i extends t.APIResource{constructor(){super(...arguments),this.sessions=new n.Sessions(this._client),this.threads=new s.Threads(this._client)}}return Ms.ChatKit=i,i.Sessions=r.Sessions,i.Threads=o.Threads,Ms}var ks={},Os={},yg;function vg(){if(yg)return Os;yg=1,Object.defineProperty(Os,"__esModule",{value:!0}),Os.Messages=void 0;const e=ce(),t=ke(),n=De(),r=Te();class s extends e.APIResource{create(i,a,l){return this._client.post((0,r.path)`/threads/${i}/messages`,{body:a,...l,headers:(0,n.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},l?.headers])})}retrieve(i,a,l){const{thread_id:u}=a;return this._client.get((0,r.path)`/threads/${u}/messages/${i}`,{...l,headers:(0,n.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},l?.headers])})}update(i,a,l){const{thread_id:u,...c}=a;return this._client.post((0,r.path)`/threads/${u}/messages/${i}`,{body:c,...l,headers:(0,n.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},l?.headers])})}list(i,a={},l){return this._client.getAPIList((0,r.path)`/threads/${i}/messages`,t.CursorPage,{query:a,...l,headers:(0,n.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},l?.headers])})}delete(i,a,l){const{thread_id:u}=a;return this._client.delete((0,r.path)`/threads/${u}/messages/${i}`,{...l,headers:(0,n.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},l?.headers])})}}return Os.Messages=s,Os}var xs={},Ds={},bg;function Ag(){if(bg)return Ds;bg=1,Object.defineProperty(Ds,"__esModule",{value:!0}),Ds.Steps=void 0;const e=ce(),t=ke(),n=De(),r=Te();class s extends e.APIResource{retrieve(i,a,l){const{thread_id:u,run_id:c,...d}=a;return this._client.get((0,r.path)`/threads/${u}/runs/${c}/steps/${i}`,{query:d,...l,headers:(0,n.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},l?.headers])})}list(i,a,l){const{thread_id:u,...c}=a;return this._client.getAPIList((0,r.path)`/threads/${u}/runs/${i}/steps`,t.CursorPage,{query:c,...l,headers:(0,n.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},l?.headers])})}}return Ds.Steps=s,Ds}var qs={},mu={},ln={},Sg;function MP(){if(Sg)return ln;Sg=1,Object.defineProperty(ln,"__esModule",{value:!0}),ln.toFloat32Array=ln.fromBase64=ln.toBase64=void 0;const e=yn(),t=Wd(),n=o=>{if(!o)return"";if(typeof globalThis.Buffer<"u")return globalThis.Buffer.from(o).toString("base64");if(typeof o=="string"&&(o=(0,t.encodeUTF8)(o)),typeof btoa<"u")return btoa(String.fromCharCode.apply(null,o));throw new e.OpenAIError("Cannot generate base64 string; Expected `Buffer` or `btoa` to be defined")};ln.toBase64=n;const r=o=>{if(typeof globalThis.Buffer<"u"){const i=globalThis.Buffer.from(o,"base64");return new Uint8Array(i.buffer,i.byteOffset,i.byteLength)}if(typeof atob<"u"){const i=atob(o),a=new Uint8Array(i.length);for(let l=0;l<i.length;l++)a[l]=i.charCodeAt(l);return a}throw new e.OpenAIError("Cannot decode base64 string; Expected `Buffer` or `atob` to be defined")};ln.fromBase64=r;const s=o=>{if(typeof Buffer<"u"){const i=Buffer.from(o,"base64");return Array.from(new Float32Array(i.buffer,i.byteOffset,i.length/Float32Array.BYTES_PER_ELEMENT))}else{const i=atob(o),a=i.length,l=new Uint8Array(a);for(let u=0;u<a;u++)l[u]=i.charCodeAt(u);return Array.from(new Float32Array(l.buffer))}};return ln.toFloat32Array=s,ln}var Ls={},wg;function Mb(){if(wg)return Ls;wg=1;var e={};Object.defineProperty(Ls,"__esModule",{value:!0}),Ls.readEnv=void 0;const t=n=>{if(typeof globalThis.process<"u")return e?.[n]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(n)?.trim()};return Ls.readEnv=t,Ls}var Eg;function $a(){return Eg||(Eg=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0});const t=ve();t.__exportStar(kn(),e),t.__exportStar(MP(),e),t.__exportStar(Mb(),e),t.__exportStar(Wa(),e),t.__exportStar(_b(),e),t.__exportStar(xi(),e)})(mu)),mu}var Tg;function Nb(){if(Tg)return qs;Tg=1;var e,t,n,r,s,o,i,a,l,u,c,d,p,g,y,_,b,m,v,A,S,P,E;Object.defineProperty(qs,"__esModule",{value:!0}),qs.AssistantStream=void 0;const w=ve(),I=Pb(),L=Xt(),H=$d(),B=$a();let F=class extends H.EventStream{constructor(){super(...arguments),e.add(this),n.set(this,[]),r.set(this,{}),s.set(this,{}),o.set(this,void 0),i.set(this,void 0),a.set(this,void 0),l.set(this,void 0),u.set(this,void 0),c.set(this,void 0),d.set(this,void 0),p.set(this,void 0),g.set(this,void 0)}[(n=new WeakMap,r=new WeakMap,s=new WeakMap,o=new WeakMap,i=new WeakMap,a=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,p=new WeakMap,g=new WeakMap,e=new WeakSet,Symbol.asyncIterator)](){const U=[],O=[];let R=!1;return this.on("event",T=>{const M=O.shift();M?M.resolve(T):U.push(T)}),this.on("end",()=>{R=!0;for(const T of O)T.resolve(void 0);O.length=0}),this.on("abort",T=>{R=!0;for(const M of O)M.reject(T);O.length=0}),this.on("error",T=>{R=!0;for(const M of O)M.reject(T);O.length=0}),{next:async()=>U.length?{value:U.shift(),done:!1}:R?{value:void 0,done:!0}:new Promise((M,k)=>O.push({resolve:M,reject:k})).then(M=>M?{value:M,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(U){const O=new t;return O._run(()=>O._fromReadableStream(U)),O}async _fromReadableStream(U,O){const R=O?.signal;R&&(R.aborted&&this.controller.abort(),R.addEventListener("abort",()=>this.controller.abort())),this._connected();const T=I.Stream.fromReadableStream(U,this.controller);for await(const M of T)w.__classPrivateFieldGet(this,e,"m",y).call(this,M);if(T.controller.signal?.aborted)throw new L.APIUserAbortError;return this._addRun(w.__classPrivateFieldGet(this,e,"m",_).call(this))}toReadableStream(){return new I.Stream(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(U,O,R,T){const M=new t;return M._run(()=>M._runToolAssistantStream(U,O,R,{...T,headers:{...T?.headers,"X-Stainless-Helper-Method":"stream"}})),M}async _createToolAssistantStream(U,O,R,T){const M=T?.signal;M&&(M.aborted&&this.controller.abort(),M.addEventListener("abort",()=>this.controller.abort()));const k={...R,stream:!0},G=await U.submitToolOutputs(O,k,{...T,signal:this.controller.signal});this._connected();for await(const V of G)w.__classPrivateFieldGet(this,e,"m",y).call(this,V);if(G.controller.signal?.aborted)throw new L.APIUserAbortError;return this._addRun(w.__classPrivateFieldGet(this,e,"m",_).call(this))}static createThreadAssistantStream(U,O,R){const T=new t;return T._run(()=>T._threadAssistantStream(U,O,{...R,headers:{...R?.headers,"X-Stainless-Helper-Method":"stream"}})),T}static createAssistantStream(U,O,R,T){const M=new t;return M._run(()=>M._runAssistantStream(U,O,R,{...T,headers:{...T?.headers,"X-Stainless-Helper-Method":"stream"}})),M}currentEvent(){return w.__classPrivateFieldGet(this,d,"f")}currentRun(){return w.__classPrivateFieldGet(this,p,"f")}currentMessageSnapshot(){return w.__classPrivateFieldGet(this,o,"f")}currentRunStepSnapshot(){return w.__classPrivateFieldGet(this,g,"f")}async finalRunSteps(){return await this.done(),Object.values(w.__classPrivateFieldGet(this,r,"f"))}async finalMessages(){return await this.done(),Object.values(w.__classPrivateFieldGet(this,s,"f"))}async finalRun(){if(await this.done(),!w.__classPrivateFieldGet(this,i,"f"))throw Error("Final run was not received.");return w.__classPrivateFieldGet(this,i,"f")}async _createThreadAssistantStream(U,O,R){const T=R?.signal;T&&(T.aborted&&this.controller.abort(),T.addEventListener("abort",()=>this.controller.abort()));const M={...O,stream:!0},k=await U.createAndRun(M,{...R,signal:this.controller.signal});this._connected();for await(const G of k)w.__classPrivateFieldGet(this,e,"m",y).call(this,G);if(k.controller.signal?.aborted)throw new L.APIUserAbortError;return this._addRun(w.__classPrivateFieldGet(this,e,"m",_).call(this))}async _createAssistantStream(U,O,R,T){const M=T?.signal;M&&(M.aborted&&this.controller.abort(),M.addEventListener("abort",()=>this.controller.abort()));const k={...R,stream:!0},G=await U.create(O,k,{...T,signal:this.controller.signal});this._connected();for await(const V of G)w.__classPrivateFieldGet(this,e,"m",y).call(this,V);if(G.controller.signal?.aborted)throw new L.APIUserAbortError;return this._addRun(w.__classPrivateFieldGet(this,e,"m",_).call(this))}static accumulateDelta(U,O){for(const[R,T]of Object.entries(O)){if(!U.hasOwnProperty(R)){U[R]=T;continue}let M=U[R];if(M==null){U[R]=T;continue}if(R==="index"||R==="type"){U[R]=T;continue}if(typeof M=="string"&&typeof T=="string")M+=T;else if(typeof M=="number"&&typeof T=="number")M+=T;else if((0,B.isObj)(M)&&(0,B.isObj)(T))M=this.accumulateDelta(M,T);else if(Array.isArray(M)&&Array.isArray(T)){if(M.every(k=>typeof k=="string"||typeof k=="number")){M.push(...T);continue}for(const k of T){if(!(0,B.isObj)(k))throw new Error(`Expected array delta entry to be an object but got: ${k}`);const G=k.index;if(G==null)throw console.error(k),new Error("Expected array delta entry to have an `index` property");if(typeof G!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${G}`);const V=M[G];V==null?M.push(k):M[G]=this.accumulateDelta(V,k)}continue}else throw Error(`Unhandled record type: ${R}, deltaValue: ${T}, accValue: ${M}`);U[R]=M}return U}_addRun(U){return U}async _threadAssistantStream(U,O,R){return await this._createThreadAssistantStream(O,U,R)}async _runAssistantStream(U,O,R,T){return await this._createAssistantStream(O,U,R,T)}async _runToolAssistantStream(U,O,R,T){return await this._createToolAssistantStream(O,U,R,T)}};return qs.AssistantStream=F,t=F,y=function(U){if(!this.ended)switch(w.__classPrivateFieldSet(this,d,U,"f"),w.__classPrivateFieldGet(this,e,"m",v).call(this,U),U.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":w.__classPrivateFieldGet(this,e,"m",E).call(this,U);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":w.__classPrivateFieldGet(this,e,"m",m).call(this,U);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":w.__classPrivateFieldGet(this,e,"m",b).call(this,U);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},_=function(){if(this.ended)throw new L.OpenAIError("stream has ended, this shouldn't happen");if(!w.__classPrivateFieldGet(this,i,"f"))throw Error("Final run has not been received");return w.__classPrivateFieldGet(this,i,"f")},b=function(U){const[O,R]=w.__classPrivateFieldGet(this,e,"m",S).call(this,U,w.__classPrivateFieldGet(this,o,"f"));w.__classPrivateFieldSet(this,o,O,"f"),w.__classPrivateFieldGet(this,s,"f")[O.id]=O;for(const T of R){const M=O.content[T.index];M?.type=="text"&&this._emit("textCreated",M.text)}switch(U.event){case"thread.message.created":this._emit("messageCreated",U.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",U.data.delta,O),U.data.delta.content)for(const T of U.data.delta.content){if(T.type=="text"&&T.text){let M=T.text,k=O.content[T.index];if(k&&k.type=="text")this._emit("textDelta",M,k.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(T.index!=w.__classPrivateFieldGet(this,a,"f")){if(w.__classPrivateFieldGet(this,l,"f"))switch(w.__classPrivateFieldGet(this,l,"f").type){case"text":this._emit("textDone",w.__classPrivateFieldGet(this,l,"f").text,w.__classPrivateFieldGet(this,o,"f"));break;case"image_file":this._emit("imageFileDone",w.__classPrivateFieldGet(this,l,"f").image_file,w.__classPrivateFieldGet(this,o,"f"));break}w.__classPrivateFieldSet(this,a,T.index,"f")}w.__classPrivateFieldSet(this,l,O.content[T.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(w.__classPrivateFieldGet(this,a,"f")!==void 0){const T=U.data.content[w.__classPrivateFieldGet(this,a,"f")];if(T)switch(T.type){case"image_file":this._emit("imageFileDone",T.image_file,w.__classPrivateFieldGet(this,o,"f"));break;case"text":this._emit("textDone",T.text,w.__classPrivateFieldGet(this,o,"f"));break}}w.__classPrivateFieldGet(this,o,"f")&&this._emit("messageDone",U.data),w.__classPrivateFieldSet(this,o,void 0,"f")}},m=function(U){const O=w.__classPrivateFieldGet(this,e,"m",A).call(this,U);switch(w.__classPrivateFieldSet(this,g,O,"f"),U.event){case"thread.run.step.created":this._emit("runStepCreated",U.data);break;case"thread.run.step.delta":const R=U.data.delta;if(R.step_details&&R.step_details.type=="tool_calls"&&R.step_details.tool_calls&&O.step_details.type=="tool_calls")for(const M of R.step_details.tool_calls)M.index==w.__classPrivateFieldGet(this,u,"f")?this._emit("toolCallDelta",M,O.step_details.tool_calls[M.index]):(w.__classPrivateFieldGet(this,c,"f")&&this._emit("toolCallDone",w.__classPrivateFieldGet(this,c,"f")),w.__classPrivateFieldSet(this,u,M.index,"f"),w.__classPrivateFieldSet(this,c,O.step_details.tool_calls[M.index],"f"),w.__classPrivateFieldGet(this,c,"f")&&this._emit("toolCallCreated",w.__classPrivateFieldGet(this,c,"f")));this._emit("runStepDelta",U.data.delta,O);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":w.__classPrivateFieldSet(this,g,void 0,"f"),U.data.step_details.type=="tool_calls"&&w.__classPrivateFieldGet(this,c,"f")&&(this._emit("toolCallDone",w.__classPrivateFieldGet(this,c,"f")),w.__classPrivateFieldSet(this,c,void 0,"f")),this._emit("runStepDone",U.data,O);break}},v=function(U){w.__classPrivateFieldGet(this,n,"f").push(U),this._emit("event",U)},A=function(U){switch(U.event){case"thread.run.step.created":return w.__classPrivateFieldGet(this,r,"f")[U.data.id]=U.data,U.data;case"thread.run.step.delta":let O=w.__classPrivateFieldGet(this,r,"f")[U.data.id];if(!O)throw Error("Received a RunStepDelta before creation of a snapshot");let R=U.data;if(R.delta){const T=t.accumulateDelta(O,R.delta);w.__classPrivateFieldGet(this,r,"f")[U.data.id]=T}return w.__classPrivateFieldGet(this,r,"f")[U.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":w.__classPrivateFieldGet(this,r,"f")[U.data.id]=U.data;break}if(w.__classPrivateFieldGet(this,r,"f")[U.data.id])return w.__classPrivateFieldGet(this,r,"f")[U.data.id];throw new Error("No snapshot available")},S=function(U,O){let R=[];switch(U.event){case"thread.message.created":return[U.data,R];case"thread.message.delta":if(!O)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let T=U.data;if(T.delta.content)for(const M of T.delta.content)if(M.index in O.content){let k=O.content[M.index];O.content[M.index]=w.__classPrivateFieldGet(this,e,"m",P).call(this,M,k)}else O.content[M.index]=M,R.push(M);return[O,R];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(O)return[O,R];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},P=function(U,O){return t.accumulateDelta(O,U)},E=function(U){switch(w.__classPrivateFieldSet(this,p,U.data,"f"),U.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":w.__classPrivateFieldSet(this,i,U.data,"f"),w.__classPrivateFieldGet(this,c,"f")&&(this._emit("toolCallDone",w.__classPrivateFieldGet(this,c,"f")),w.__classPrivateFieldSet(this,c,void 0,"f"));break}},qs}var Pg;function Ig(){if(Pg)return xs;Pg=1,Object.defineProperty(xs,"__esModule",{value:!0}),xs.Runs=void 0;const e=ve(),t=ce(),n=e.__importStar(Ag()),r=Ag(),s=ke(),o=De(),i=Nb(),a=xi(),l=Te();class u extends t.APIResource{constructor(){super(...arguments),this.steps=new n.Steps(this._client)}create(d,p,g){const{include:y,..._}=p;return this._client.post((0,l.path)`/threads/${d}/runs`,{query:{include:y},body:_,...g,headers:(0,o.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},g?.headers]),stream:p.stream??!1})}retrieve(d,p,g){const{thread_id:y}=p;return this._client.get((0,l.path)`/threads/${y}/runs/${d}`,{...g,headers:(0,o.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},g?.headers])})}update(d,p,g){const{thread_id:y,..._}=p;return this._client.post((0,l.path)`/threads/${y}/runs/${d}`,{body:_,...g,headers:(0,o.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},g?.headers])})}list(d,p={},g){return this._client.getAPIList((0,l.path)`/threads/${d}/runs`,s.CursorPage,{query:p,...g,headers:(0,o.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},g?.headers])})}cancel(d,p,g){const{thread_id:y}=p;return this._client.post((0,l.path)`/threads/${y}/runs/${d}/cancel`,{...g,headers:(0,o.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},g?.headers])})}async createAndPoll(d,p,g){const y=await this.create(d,p,g);return await this.poll(y.id,{thread_id:d},g)}createAndStream(d,p,g){return i.AssistantStream.createAssistantStream(d,this._client.beta.threads.runs,p,g)}async poll(d,p,g){const y=(0,o.buildHeaders)([g?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":g?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:_,response:b}=await this.retrieve(d,p,{...g,headers:{...g?.headers,...y}}).withResponse();switch(_.status){case"queued":case"in_progress":case"cancelling":let m=5e3;if(g?.pollIntervalMs)m=g.pollIntervalMs;else{const v=b.headers.get("openai-poll-after-ms");if(v){const A=parseInt(v);isNaN(A)||(m=A)}}await(0,a.sleep)(m);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return _}}}stream(d,p,g){return i.AssistantStream.createAssistantStream(d,this._client.beta.threads.runs,p,g)}submitToolOutputs(d,p,g){const{thread_id:y,..._}=p;return this._client.post((0,l.path)`/threads/${y}/runs/${d}/submit_tool_outputs`,{body:_,...g,headers:(0,o.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},g?.headers]),stream:p.stream??!1})}async submitToolOutputsAndPoll(d,p,g){const y=await this.submitToolOutputs(d,p,g);return await this.poll(y.id,p,g)}submitToolOutputsStream(d,p,g){return i.AssistantStream.createToolAssistantStream(d,this._client.beta.threads.runs,p,g)}}return xs.Runs=u,u.Steps=r.Steps,xs}var Cg;function Rg(){if(Cg)return ks;Cg=1,Object.defineProperty(ks,"__esModule",{value:!0}),ks.Threads=void 0;const e=ve(),t=ce(),n=e.__importStar(vg()),r=vg(),s=e.__importStar(Ig()),o=Ig(),i=De(),a=Nb(),l=Te();class u extends t.APIResource{constructor(){super(...arguments),this.runs=new s.Runs(this._client),this.messages=new n.Messages(this._client)}create(d={},p){return this._client.post("/threads",{body:d,...p,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},p?.headers])})}retrieve(d,p){return this._client.get((0,l.path)`/threads/${d}`,{...p,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},p?.headers])})}update(d,p,g){return this._client.post((0,l.path)`/threads/${d}`,{body:p,...g,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},g?.headers])})}delete(d,p){return this._client.delete((0,l.path)`/threads/${d}`,{...p,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},p?.headers])})}createAndRun(d,p){return this._client.post("/threads/runs",{body:d,...p,headers:(0,i.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},p?.headers]),stream:d.stream??!1})}async createAndRunPoll(d,p){const g=await this.createAndRun(d,p);return await this.runs.poll(g.id,{thread_id:g.thread_id},p)}createAndRunStream(d,p){return a.AssistantStream.createThreadAssistantStream(d,this._client.beta.threads,p)}}return ks.Threads=u,u.Runs=o.Runs,u.Messages=r.Messages,ks}var Mg;function Fb(){if(Mg)return Ts;Mg=1,Object.defineProperty(Ts,"__esModule",{value:!0}),Ts.Beta=void 0;const e=ve(),t=ce(),n=e.__importStar(og()),r=og(),s=e.__importStar(dg()),o=dg(),i=e.__importStar(_g()),a=_g(),l=e.__importStar(Rg()),u=Rg();class c extends t.APIResource{constructor(){super(...arguments),this.realtime=new s.Realtime(this._client),this.chatkit=new i.ChatKit(this._client),this.assistants=new n.Assistants(this._client),this.threads=new l.Threads(this._client)}}return Ts.Beta=c,c.Realtime=o.Realtime,c.ChatKit=a.ChatKit,c.Assistants=r.Assistants,c.Threads=u.Threads,Ts}var Us={},Ng;function kb(){if(Ng)return Us;Ng=1,Object.defineProperty(Us,"__esModule",{value:!0}),Us.Completions=void 0;const e=ce();class t extends e.APIResource{create(r,s){return this._client.post("/completions",{body:r,...s,stream:r.stream??!1})}}return Us.Completions=t,Us}var Gs={},Vs={},Bs={},Fg;function kg(){if(Fg)return Bs;Fg=1,Object.defineProperty(Bs,"__esModule",{value:!0}),Bs.Content=void 0;const e=ce(),t=De(),n=Te();class r extends e.APIResource{retrieve(o,i,a){const{container_id:l}=i;return this._client.get((0,n.path)`/containers/${l}/files/${o}/content`,{...a,headers:(0,t.buildHeaders)([{Accept:"application/binary"},a?.headers]),__binaryResponse:!0})}}return Bs.Content=r,Bs}var Og;function xg(){if(Og)return Vs;Og=1,Object.defineProperty(Vs,"__esModule",{value:!0}),Vs.Files=void 0;const e=ve(),t=ce(),n=e.__importStar(kg()),r=kg(),s=ke(),o=De(),i=vn(),a=Te();class l extends t.APIResource{constructor(){super(...arguments),this.content=new n.Content(this._client)}create(c,d,p){return this._client.post((0,a.path)`/containers/${c}/files`,(0,i.multipartFormRequestOptions)({body:d,...p},this._client))}retrieve(c,d,p){const{container_id:g}=d;return this._client.get((0,a.path)`/containers/${g}/files/${c}`,p)}list(c,d={},p){return this._client.getAPIList((0,a.path)`/containers/${c}/files`,s.CursorPage,{query:d,...p})}delete(c,d,p){const{container_id:g}=d;return this._client.delete((0,a.path)`/containers/${g}/files/${c}`,{...p,headers:(0,o.buildHeaders)([{Accept:"*/*"},p?.headers])})}}return Vs.Files=l,l.Content=r.Content,Vs}var Dg;function Ob(){if(Dg)return Gs;Dg=1,Object.defineProperty(Gs,"__esModule",{value:!0}),Gs.Containers=void 0;const e=ve(),t=ce(),n=e.__importStar(xg()),r=xg(),s=ke(),o=De(),i=Te();class a extends t.APIResource{constructor(){super(...arguments),this.files=new n.Files(this._client)}create(u,c){return this._client.post("/containers",{body:u,...c})}retrieve(u,c){return this._client.get((0,i.path)`/containers/${u}`,c)}list(u={},c){return this._client.getAPIList("/containers",s.CursorPage,{query:u,...c})}delete(u,c){return this._client.delete((0,i.path)`/containers/${u}`,{...c,headers:(0,o.buildHeaders)([{Accept:"*/*"},c?.headers])})}}return Gs.Containers=a,a.Files=r.Files,Gs}var Hs={},Js={},qg;function Lg(){if(qg)return Js;qg=1,Object.defineProperty(Js,"__esModule",{value:!0}),Js.Items=void 0;const e=ce(),t=ke(),n=Te();class r extends e.APIResource{create(o,i,a){const{include:l,...u}=i;return this._client.post((0,n.path)`/conversations/${o}/items`,{query:{include:l},body:u,...a})}retrieve(o,i,a){const{conversation_id:l,...u}=i;return this._client.get((0,n.path)`/conversations/${l}/items/${o}`,{query:u,...a})}list(o,i={},a){return this._client.getAPIList((0,n.path)`/conversations/${o}/items`,t.ConversationCursorPage,{query:i,...a})}delete(o,i,a){const{conversation_id:l}=i;return this._client.delete((0,n.path)`/conversations/${l}/items/${o}`,a)}}return Js.Items=r,Js}var Ug;function xb(){if(Ug)return Hs;Ug=1,Object.defineProperty(Hs,"__esModule",{value:!0}),Hs.Conversations=void 0;const e=ve(),t=ce(),n=e.__importStar(Lg()),r=Lg(),s=Te();class o extends t.APIResource{constructor(){super(...arguments),this.items=new n.Items(this._client)}create(a={},l){return this._client.post("/conversations",{body:a,...l})}retrieve(a,l){return this._client.get((0,s.path)`/conversations/${a}`,l)}update(a,l,u){return this._client.post((0,s.path)`/conversations/${a}`,{body:l,...u})}delete(a,l){return this._client.delete((0,s.path)`/conversations/${a}`,l)}}return Hs.Conversations=o,o.Items=r.Items,Hs}var js={},Gg;function Db(){if(Gg)return js;Gg=1,Object.defineProperty(js,"__esModule",{value:!0}),js.Embeddings=void 0;const e=ce(),t=$a();class n extends e.APIResource{create(s,o){const i=!!s.encoding_format;let a=i?s.encoding_format:"base64";i&&(0,t.loggerFor)(this._client).debug("embeddings/user defined encoding_format:",s.encoding_format);const l=this._client.post("/embeddings",{body:{...s,encoding_format:a},...o});return i?l:((0,t.loggerFor)(this._client).debug("embeddings/decoding base64 embeddings from base64"),l._thenUnwrap(u=>(u&&u.data&&u.data.forEach(c=>{const d=c.embedding;c.embedding=(0,t.toFloat32Array)(d)}),u)))}}return js.Embeddings=n,js}var Ws={},Ks={},$s={},Vg;function Bg(){if(Vg)return $s;Vg=1,Object.defineProperty($s,"__esModule",{value:!0}),$s.OutputItems=void 0;const e=ce(),t=ke(),n=Te();class r extends e.APIResource{retrieve(o,i,a){const{eval_id:l,run_id:u}=i;return this._client.get((0,n.path)`/evals/${l}/runs/${u}/output_items/${o}`,a)}list(o,i,a){const{eval_id:l,...u}=i;return this._client.getAPIList((0,n.path)`/evals/${l}/runs/${o}/output_items`,t.CursorPage,{query:u,...a})}}return $s.OutputItems=r,$s}var Hg;function Jg(){if(Hg)return Ks;Hg=1,Object.defineProperty(Ks,"__esModule",{value:!0}),Ks.Runs=void 0;const e=ve(),t=ce(),n=e.__importStar(Bg()),r=Bg(),s=ke(),o=Te();class i extends t.APIResource{constructor(){super(...arguments),this.outputItems=new n.OutputItems(this._client)}create(l,u,c){return this._client.post((0,o.path)`/evals/${l}/runs`,{body:u,...c})}retrieve(l,u,c){const{eval_id:d}=u;return this._client.get((0,o.path)`/evals/${d}/runs/${l}`,c)}list(l,u={},c){return this._client.getAPIList((0,o.path)`/evals/${l}/runs`,s.CursorPage,{query:u,...c})}delete(l,u,c){const{eval_id:d}=u;return this._client.delete((0,o.path)`/evals/${d}/runs/${l}`,c)}cancel(l,u,c){const{eval_id:d}=u;return this._client.post((0,o.path)`/evals/${d}/runs/${l}`,c)}}return Ks.Runs=i,i.OutputItems=r.OutputItems,Ks}var jg;function qb(){if(jg)return Ws;jg=1,Object.defineProperty(Ws,"__esModule",{value:!0}),Ws.Evals=void 0;const e=ve(),t=ce(),n=e.__importStar(Jg()),r=Jg(),s=ke(),o=Te();class i extends t.APIResource{constructor(){super(...arguments),this.runs=new n.Runs(this._client)}create(l,u){return this._client.post("/evals",{body:l,...u})}retrieve(l,u){return this._client.get((0,o.path)`/evals/${l}`,u)}update(l,u,c){return this._client.post((0,o.path)`/evals/${l}`,{body:u,...c})}list(l={},u){return this._client.getAPIList("/evals",s.CursorPage,{query:l,...u})}delete(l,u){return this._client.delete((0,o.path)`/evals/${l}`,u)}}return Ws.Evals=i,i.Runs=r.Runs,Ws}var Ys={},Wg;function Lb(){if(Wg)return Ys;Wg=1,Object.defineProperty(Ys,"__esModule",{value:!0}),Ys.Files=void 0;const e=ce(),t=ke(),n=De(),r=xi(),s=Xt(),o=vn(),i=Te();class a extends e.APIResource{create(u,c){return this._client.post("/files",(0,o.multipartFormRequestOptions)({body:u,...c},this._client))}retrieve(u,c){return this._client.get((0,i.path)`/files/${u}`,c)}list(u={},c){return this._client.getAPIList("/files",t.CursorPage,{query:u,...c})}delete(u,c){return this._client.delete((0,i.path)`/files/${u}`,c)}content(u,c){return this._client.get((0,i.path)`/files/${u}/content`,{...c,headers:(0,n.buildHeaders)([{Accept:"application/binary"},c?.headers]),__binaryResponse:!0})}async waitForProcessing(u,{pollInterval:c=5e3,maxWait:d=1800*1e3}={}){const p=new Set(["processed","error","deleted"]),g=Date.now();let y=await this.retrieve(u);for(;!y.status||!p.has(y.status);)if(await(0,r.sleep)(c),y=await this.retrieve(u),Date.now()-g>d)throw new s.APIConnectionTimeoutError({message:`Giving up on waiting for file ${u} to finish processing after ${d} milliseconds.`});return y}}return Ys.Files=a,Ys}var zs={},Xs={},Kg;function $g(){if(Kg)return Xs;Kg=1,Object.defineProperty(Xs,"__esModule",{value:!0}),Xs.Methods=void 0;const e=ce();class t extends e.APIResource{}return Xs.Methods=t,Xs}var Qs={},Zs={},Yg;function zg(){if(Yg)return Zs;Yg=1,Object.defineProperty(Zs,"__esModule",{value:!0}),Zs.Graders=void 0;const e=ce();class t extends e.APIResource{run(r,s){return this._client.post("/fine_tuning/alpha/graders/run",{body:r,...s})}validate(r,s){return this._client.post("/fine_tuning/alpha/graders/validate",{body:r,...s})}}return Zs.Graders=t,Zs}var Xg;function Qg(){if(Xg)return Qs;Xg=1,Object.defineProperty(Qs,"__esModule",{value:!0}),Qs.Alpha=void 0;const e=ve(),t=ce(),n=e.__importStar(zg()),r=zg();class s extends t.APIResource{constructor(){super(...arguments),this.graders=new n.Graders(this._client)}}return Qs.Alpha=s,s.Graders=r.Graders,Qs}var eo={},to={},Zg;function em(){if(Zg)return to;Zg=1,Object.defineProperty(to,"__esModule",{value:!0}),to.Permissions=void 0;const e=ce(),t=ke(),n=Te();class r extends e.APIResource{create(o,i,a){return this._client.getAPIList((0,n.path)`/fine_tuning/checkpoints/${o}/permissions`,t.Page,{body:i,method:"post",...a})}retrieve(o,i={},a){return this._client.get((0,n.path)`/fine_tuning/checkpoints/${o}/permissions`,{query:i,...a})}delete(o,i,a){const{fine_tuned_model_checkpoint:l}=i;return this._client.delete((0,n.path)`/fine_tuning/checkpoints/${l}/permissions/${o}`,a)}}return to.Permissions=r,to}var tm;function nm(){if(tm)return eo;tm=1,Object.defineProperty(eo,"__esModule",{value:!0}),eo.Checkpoints=void 0;const e=ve(),t=ce(),n=e.__importStar(em()),r=em();class s extends t.APIResource{constructor(){super(...arguments),this.permissions=new n.Permissions(this._client)}}return eo.Checkpoints=s,s.Permissions=r.Permissions,eo}var no={},ro={},rm;function sm(){if(rm)return ro;rm=1,Object.defineProperty(ro,"__esModule",{value:!0}),ro.Checkpoints=void 0;const e=ce(),t=ke(),n=Te();class r extends e.APIResource{list(o,i={},a){return this._client.getAPIList((0,n.path)`/fine_tuning/jobs/${o}/checkpoints`,t.CursorPage,{query:i,...a})}}return ro.Checkpoints=r,ro}var om;function im(){if(om)return no;om=1,Object.defineProperty(no,"__esModule",{value:!0}),no.Jobs=void 0;const e=ve(),t=ce(),n=e.__importStar(sm()),r=sm(),s=ke(),o=Te();class i extends t.APIResource{constructor(){super(...arguments),this.checkpoints=new n.Checkpoints(this._client)}create(l,u){return this._client.post("/fine_tuning/jobs",{body:l,...u})}retrieve(l,u){return this._client.get((0,o.path)`/fine_tuning/jobs/${l}`,u)}list(l={},u){return this._client.getAPIList("/fine_tuning/jobs",s.CursorPage,{query:l,...u})}cancel(l,u){return this._client.post((0,o.path)`/fine_tuning/jobs/${l}/cancel`,u)}listEvents(l,u={},c){return this._client.getAPIList((0,o.path)`/fine_tuning/jobs/${l}/events`,s.CursorPage,{query:u,...c})}pause(l,u){return this._client.post((0,o.path)`/fine_tuning/jobs/${l}/pause`,u)}resume(l,u){return this._client.post((0,o.path)`/fine_tuning/jobs/${l}/resume`,u)}}return no.Jobs=i,i.Checkpoints=r.Checkpoints,no}var am;function Ub(){if(am)return zs;am=1,Object.defineProperty(zs,"__esModule",{value:!0}),zs.FineTuning=void 0;const e=ve(),t=ce(),n=e.__importStar($g()),r=$g(),s=e.__importStar(Qg()),o=Qg(),i=e.__importStar(nm()),a=nm(),l=e.__importStar(im()),u=im();class c extends t.APIResource{constructor(){super(...arguments),this.methods=new n.Methods(this._client),this.jobs=new l.Jobs(this._client),this.checkpoints=new i.Checkpoints(this._client),this.alpha=new s.Alpha(this._client)}}return zs.FineTuning=c,c.Methods=r.Methods,c.Jobs=u.Jobs,c.Checkpoints=a.Checkpoints,c.Alpha=o.Alpha,zs}var so={},oo={},lm;function um(){if(lm)return oo;lm=1,Object.defineProperty(oo,"__esModule",{value:!0}),oo.GraderModels=void 0;const e=ce();class t extends e.APIResource{}return oo.GraderModels=t,oo}var cm;function Gb(){if(cm)return so;cm=1,Object.defineProperty(so,"__esModule",{value:!0}),so.Graders=void 0;const e=ve(),t=ce(),n=e.__importStar(um()),r=um();class s extends t.APIResource{constructor(){super(...arguments),this.graderModels=new n.GraderModels(this._client)}}return so.Graders=s,s.GraderModels=r.GraderModels,so}var io={},dm;function Vb(){if(dm)return io;dm=1,Object.defineProperty(io,"__esModule",{value:!0}),io.Images=void 0;const e=ce(),t=vn();class n extends e.APIResource{createVariation(s,o){return this._client.post("/images/variations",(0,t.multipartFormRequestOptions)({body:s,...o},this._client))}edit(s,o){return this._client.post("/images/edits",(0,t.multipartFormRequestOptions)({body:s,...o,stream:s.stream??!1},this._client))}generate(s,o){return this._client.post("/images/generations",{body:s,...o,stream:s.stream??!1})}}return io.Images=n,io}var ao={},fm;function Bb(){if(fm)return ao;fm=1,Object.defineProperty(ao,"__esModule",{value:!0}),ao.Models=void 0;const e=ce(),t=ke(),n=Te();class r extends e.APIResource{retrieve(o,i){return this._client.get((0,n.path)`/models/${o}`,i)}list(o){return this._client.getAPIList("/models",t.Page,o)}delete(o,i){return this._client.delete((0,n.path)`/models/${o}`,i)}}return ao.Models=r,ao}var lo={},pm;function Hb(){if(pm)return lo;pm=1,Object.defineProperty(lo,"__esModule",{value:!0}),lo.Moderations=void 0;const e=ce();class t extends e.APIResource{create(r,s){return this._client.post("/moderations",{body:r,...s})}}return lo.Moderations=t,lo}var uo={},co={},hm;function gm(){if(hm)return co;hm=1,Object.defineProperty(co,"__esModule",{value:!0}),co.Calls=void 0;const e=ce(),t=De(),n=Te();class r extends e.APIResource{accept(o,i,a){return this._client.post((0,n.path)`/realtime/calls/${o}/accept`,{body:i,...a,headers:(0,t.buildHeaders)([{Accept:"*/*"},a?.headers])})}hangup(o,i){return this._client.post((0,n.path)`/realtime/calls/${o}/hangup`,{...i,headers:(0,t.buildHeaders)([{Accept:"*/*"},i?.headers])})}refer(o,i,a){return this._client.post((0,n.path)`/realtime/calls/${o}/refer`,{body:i,...a,headers:(0,t.buildHeaders)([{Accept:"*/*"},a?.headers])})}reject(o,i={},a){return this._client.post((0,n.path)`/realtime/calls/${o}/reject`,{body:i,...a,headers:(0,t.buildHeaders)([{Accept:"*/*"},a?.headers])})}}return co.Calls=r,co}var fo={},mm;function _m(){if(mm)return fo;mm=1,Object.defineProperty(fo,"__esModule",{value:!0}),fo.ClientSecrets=void 0;const e=ce();class t extends e.APIResource{create(r,s){return this._client.post("/realtime/client_secrets",{body:r,...s})}}return fo.ClientSecrets=t,fo}var ym;function Jb(){if(ym)return uo;ym=1,Object.defineProperty(uo,"__esModule",{value:!0}),uo.Realtime=void 0;const e=ve(),t=ce(),n=e.__importStar(gm()),r=gm(),s=e.__importStar(_m()),o=_m();class i extends t.APIResource{constructor(){super(...arguments),this.clientSecrets=new s.ClientSecrets(this._client),this.calls=new n.Calls(this._client)}}return uo.Realtime=i,i.ClientSecrets=o.ClientSecrets,i.Calls=r.Calls,uo}var po={},St={},vm;function jb(){if(vm)return St;vm=1,Object.defineProperty(St,"__esModule",{value:!0}),St.maybeParseResponse=n,St.parseResponse=r,St.hasAutoParseableInput=o,St.makeParseableResponseTool=i,St.isAutoParsableTool=a,St.shouldParseToolCall=c,St.validateInputTools=d,St.addOutputText=p;const e=Xt(),t=Ka();function n(g,y){return!y||!o(y)?{...g,output_parsed:null,output:g.output.map(_=>_.type==="function_call"?{..._,parsed_arguments:null}:_.type==="message"?{..._,content:_.content.map(b=>({...b,parsed:null}))}:_)}:r(g,y)}function r(g,y){const _=g.output.map(m=>{if(m.type==="function_call")return{...m,parsed_arguments:u(y,m)};if(m.type==="message"){const v=m.content.map(A=>A.type==="output_text"?{...A,parsed:s(y,A.text)}:A);return{...m,content:v}}return m}),b=Object.assign({},g,{output:_});return Object.getOwnPropertyDescriptor(g,"output_text")||p(b),Object.defineProperty(b,"output_parsed",{enumerable:!0,get(){for(const m of b.output)if(m.type==="message"){for(const v of m.content)if(v.type==="output_text"&&v.parsed!==null)return v.parsed}return null}}),b}function s(g,y){return g.text?.format?.type!=="json_schema"?null:"$parseRaw"in g.text?.format?(g.text?.format).$parseRaw(y):JSON.parse(y)}function o(g){return!!(0,t.isAutoParsableResponseFormat)(g.text?.format)}function i(g,{parser:y,callback:_}){const b={...g};return Object.defineProperties(b,{$brand:{value:"auto-parseable-tool",enumerable:!1},$parseRaw:{value:y,enumerable:!1},$callback:{value:_,enumerable:!1}}),b}function a(g){return g?.$brand==="auto-parseable-tool"}function l(g,y){return g.find(_=>_.type==="function"&&_.name===y)}function u(g,y){const _=l(g.tools??[],y.name);return{...y,...y,parsed_arguments:a(_)?_.$parseRaw(y.arguments):_?.strict?JSON.parse(y.arguments):null}}function c(g,y){if(!g)return!1;const _=l(g.tools??[],y.name);return a(_)||_?.strict||!1}function d(g){for(const y of g??[]){if(y.type!=="function")throw new e.OpenAIError(`Currently only \`function\` tool types support auto-parsing; Received \`${y.type}\``);if(y.function.strict!==!0)throw new e.OpenAIError(`The \`${y.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}function p(g){const y=[];for(const _ of g.output)if(_.type==="message")for(const b of _.content)b.type==="output_text"&&y.push(b.text);g.output_text=y.join("")}return St}var ho={},bm;function NP(){if(bm)return ho;bm=1;var e,t,n,r,s,o,i,a;Object.defineProperty(ho,"__esModule",{value:!0}),ho.ResponseStream=void 0;const l=ve(),u=Xt(),c=$d(),d=jb();let p=class Wb extends c.EventStream{constructor(_){super(),e.add(this),t.set(this,void 0),n.set(this,void 0),r.set(this,void 0),l.__classPrivateFieldSet(this,t,_,"f")}static createResponse(_,b,m){const v=new Wb(b);return v._run(()=>v._createOrRetrieveResponse(_,b,{...m,headers:{...m?.headers,"X-Stainless-Helper-Method":"stream"}})),v}async _createOrRetrieveResponse(_,b,m){const v=m?.signal;v&&(v.aborted&&this.controller.abort(),v.addEventListener("abort",()=>this.controller.abort())),l.__classPrivateFieldGet(this,e,"m",s).call(this);let A,S=null;"response_id"in b?(A=await _.responses.retrieve(b.response_id,{stream:!0},{...m,signal:this.controller.signal,stream:!0}),S=b.starting_after??null):A=await _.responses.create({...b,stream:!0},{...m,signal:this.controller.signal}),this._connected();for await(const P of A)l.__classPrivateFieldGet(this,e,"m",o).call(this,P,S);if(A.controller.signal?.aborted)throw new u.APIUserAbortError;return l.__classPrivateFieldGet(this,e,"m",i).call(this)}[(t=new WeakMap,n=new WeakMap,r=new WeakMap,e=new WeakSet,s=function(){this.ended||l.__classPrivateFieldSet(this,n,void 0,"f")},o=function(b,m){if(this.ended)return;const v=(S,P)=>{(m==null||P.sequence_number>m)&&this._emit(S,P)},A=l.__classPrivateFieldGet(this,e,"m",a).call(this,b);switch(v("event",b),b.type){case"response.output_text.delta":{const S=A.output[b.output_index];if(!S)throw new u.OpenAIError(`missing output at index ${b.output_index}`);if(S.type==="message"){const P=S.content[b.content_index];if(!P)throw new u.OpenAIError(`missing content at index ${b.content_index}`);if(P.type!=="output_text")throw new u.OpenAIError(`expected content to be 'output_text', got ${P.type}`);v("response.output_text.delta",{...b,snapshot:P.text})}break}case"response.function_call_arguments.delta":{const S=A.output[b.output_index];if(!S)throw new u.OpenAIError(`missing output at index ${b.output_index}`);S.type==="function_call"&&v("response.function_call_arguments.delta",{...b,snapshot:S.arguments});break}default:v(b.type,b);break}},i=function(){if(this.ended)throw new u.OpenAIError("stream has ended, this shouldn't happen");const b=l.__classPrivateFieldGet(this,n,"f");if(!b)throw new u.OpenAIError("request ended without sending any events");l.__classPrivateFieldSet(this,n,void 0,"f");const m=g(b,l.__classPrivateFieldGet(this,t,"f"));return l.__classPrivateFieldSet(this,r,m,"f"),m},a=function(b){let m=l.__classPrivateFieldGet(this,n,"f");if(!m){if(b.type!=="response.created")throw new u.OpenAIError(`When snapshot hasn't been set yet, expected 'response.created' event, got ${b.type}`);return m=l.__classPrivateFieldSet(this,n,b.response,"f"),m}switch(b.type){case"response.output_item.added":{m.output.push(b.item);break}case"response.content_part.added":{const v=m.output[b.output_index];if(!v)throw new u.OpenAIError(`missing output at index ${b.output_index}`);const A=v.type,S=b.part;A==="message"&&S.type!=="reasoning_text"?v.content.push(S):A==="reasoning"&&S.type==="reasoning_text"&&(v.content||(v.content=[]),v.content.push(S));break}case"response.output_text.delta":{const v=m.output[b.output_index];if(!v)throw new u.OpenAIError(`missing output at index ${b.output_index}`);if(v.type==="message"){const A=v.content[b.content_index];if(!A)throw new u.OpenAIError(`missing content at index ${b.content_index}`);if(A.type!=="output_text")throw new u.OpenAIError(`expected content to be 'output_text', got ${A.type}`);A.text+=b.delta}break}case"response.function_call_arguments.delta":{const v=m.output[b.output_index];if(!v)throw new u.OpenAIError(`missing output at index ${b.output_index}`);v.type==="function_call"&&(v.arguments+=b.delta);break}case"response.reasoning_text.delta":{const v=m.output[b.output_index];if(!v)throw new u.OpenAIError(`missing output at index ${b.output_index}`);if(v.type==="reasoning"){const A=v.content?.[b.content_index];if(!A)throw new u.OpenAIError(`missing content at index ${b.content_index}`);if(A.type!=="reasoning_text")throw new u.OpenAIError(`expected content to be 'reasoning_text', got ${A.type}`);A.text+=b.delta}break}case"response.completed":{l.__classPrivateFieldSet(this,n,b.response,"f");break}}return m},Symbol.asyncIterator)](){const _=[],b=[];let m=!1;return this.on("event",v=>{const A=b.shift();A?A.resolve(v):_.push(v)}),this.on("end",()=>{m=!0;for(const v of b)v.resolve(void 0);b.length=0}),this.on("abort",v=>{m=!0;for(const A of b)A.reject(v);b.length=0}),this.on("error",v=>{m=!0;for(const A of b)A.reject(v);b.length=0}),{next:async()=>_.length?{value:_.shift(),done:!1}:m?{value:void 0,done:!0}:new Promise((A,S)=>b.push({resolve:A,reject:S})).then(A=>A?{value:A,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const _=l.__classPrivateFieldGet(this,r,"f");if(!_)throw new u.OpenAIError("stream ended without producing a ChatCompletion");return _}};ho.ResponseStream=p;function g(y,_){return(0,d.maybeParseResponse)(y,_)}return ho}var go={},Am;function Sm(){if(Am)return go;Am=1,Object.defineProperty(go,"__esModule",{value:!0}),go.InputItems=void 0;const e=ce(),t=ke(),n=Te();class r extends e.APIResource{list(o,i={},a){return this._client.getAPIList((0,n.path)`/responses/${o}/input_items`,t.CursorPage,{query:i,...a})}}return go.InputItems=r,go}var mo={},wm;function Em(){if(wm)return mo;wm=1,Object.defineProperty(mo,"__esModule",{value:!0}),mo.InputTokens=void 0;const e=ce();class t extends e.APIResource{count(r={},s){return this._client.post("/responses/input_tokens",{body:r,...s})}}return mo.InputTokens=t,mo}var Tm;function Kb(){if(Tm)return po;Tm=1,Object.defineProperty(po,"__esModule",{value:!0}),po.Responses=void 0;const e=ve(),t=jb(),n=NP(),r=ce(),s=e.__importStar(Sm()),o=Sm(),i=e.__importStar(Em()),a=Em(),l=De(),u=Te();class c extends r.APIResource{constructor(){super(...arguments),this.inputItems=new s.InputItems(this._client),this.inputTokens=new i.InputTokens(this._client)}create(p,g){return this._client.post("/responses",{body:p,...g,stream:p.stream??!1})._thenUnwrap(y=>("object"in y&&y.object==="response"&&(0,t.addOutputText)(y),y))}retrieve(p,g={},y){return this._client.get((0,u.path)`/responses/${p}`,{query:g,...y,stream:g?.stream??!1})._thenUnwrap(_=>("object"in _&&_.object==="response"&&(0,t.addOutputText)(_),_))}delete(p,g){return this._client.delete((0,u.path)`/responses/${p}`,{...g,headers:(0,l.buildHeaders)([{Accept:"*/*"},g?.headers])})}parse(p,g){return this._client.responses.create(p,g)._thenUnwrap(y=>(0,t.parseResponse)(y,p))}stream(p,g){return n.ResponseStream.createResponse(this._client,p,g)}cancel(p,g){return this._client.post((0,u.path)`/responses/${p}/cancel`,g)}compact(p,g){return this._client.post("/responses/compact",{body:p,...g})}}return po.Responses=c,c.InputItems=o.InputItems,c.InputTokens=a.InputTokens,po}var _o={},yo={},Pm;function Im(){if(Pm)return yo;Pm=1,Object.defineProperty(yo,"__esModule",{value:!0}),yo.Parts=void 0;const e=ce(),t=vn(),n=Te();class r extends e.APIResource{create(o,i,a){return this._client.post((0,n.path)`/uploads/${o}/parts`,(0,t.multipartFormRequestOptions)({body:i,...a},this._client))}}return yo.Parts=r,yo}var Cm;function $b(){if(Cm)return _o;Cm=1,Object.defineProperty(_o,"__esModule",{value:!0}),_o.Uploads=void 0;const e=ve(),t=ce(),n=e.__importStar(Im()),r=Im(),s=Te();class o extends t.APIResource{constructor(){super(...arguments),this.parts=new n.Parts(this._client)}create(a,l){return this._client.post("/uploads",{body:a,...l})}cancel(a,l){return this._client.post((0,s.path)`/uploads/${a}/cancel`,l)}complete(a,l,u){return this._client.post((0,s.path)`/uploads/${a}/complete`,{body:l,...u})}}return _o.Uploads=o,o.Parts=r.Parts,_o}var vo={},bo={},Ao={},Rm;function FP(){if(Rm)return Ao;Rm=1,Object.defineProperty(Ao,"__esModule",{value:!0}),Ao.allSettledWithThrow=void 0;const e=async t=>{const n=await Promise.allSettled(t),r=n.filter(o=>o.status==="rejected");if(r.length){for(const o of r)console.error(o.reason);throw new Error(`${r.length} promise(s) failed - see the above errors`)}const s=[];for(const o of n)o.status==="fulfilled"&&s.push(o.value);return s};return Ao.allSettledWithThrow=e,Ao}var Mm;function Nm(){if(Mm)return bo;Mm=1,Object.defineProperty(bo,"__esModule",{value:!0}),bo.FileBatches=void 0;const e=ce(),t=ke(),n=De(),r=xi(),s=FP(),o=Te();class i extends e.APIResource{create(l,u,c){return this._client.post((0,o.path)`/vector_stores/${l}/file_batches`,{body:u,...c,headers:(0,n.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},c?.headers])})}retrieve(l,u,c){const{vector_store_id:d}=u;return this._client.get((0,o.path)`/vector_stores/${d}/file_batches/${l}`,{...c,headers:(0,n.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},c?.headers])})}cancel(l,u,c){const{vector_store_id:d}=u;return this._client.post((0,o.path)`/vector_stores/${d}/file_batches/${l}/cancel`,{...c,headers:(0,n.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},c?.headers])})}async createAndPoll(l,u,c){const d=await this.create(l,u);return await this.poll(l,d.id,c)}listFiles(l,u,c){const{vector_store_id:d,...p}=u;return this._client.getAPIList((0,o.path)`/vector_stores/${d}/file_batches/${l}/files`,t.CursorPage,{query:p,...c,headers:(0,n.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},c?.headers])})}async poll(l,u,c){const d=(0,n.buildHeaders)([c?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":c?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:p,response:g}=await this.retrieve(u,{vector_store_id:l},{...c,headers:d}).withResponse();switch(p.status){case"in_progress":let y=5e3;if(c?.pollIntervalMs)y=c.pollIntervalMs;else{const _=g.headers.get("openai-poll-after-ms");if(_){const b=parseInt(_);isNaN(b)||(y=b)}}await(0,r.sleep)(y);break;case"failed":case"cancelled":case"completed":return p}}}async uploadAndPoll(l,{files:u,fileIds:c=[]},d){if(u==null||u.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const p=d?.maxConcurrency??5,g=Math.min(p,u.length),y=this._client,_=u.values(),b=[...c];async function m(A){for(let S of A){const P=await y.files.create({file:S,purpose:"assistants"},d);b.push(P.id)}}const v=Array(g).fill(_).map(m);return await(0,s.allSettledWithThrow)(v),await this.createAndPoll(l,{file_ids:b})}}return bo.FileBatches=i,bo}var So={},Fm;function km(){if(Fm)return So;Fm=1,Object.defineProperty(So,"__esModule",{value:!0}),So.Files=void 0;const e=ce(),t=ke(),n=De(),r=$a(),s=Te();class o extends e.APIResource{create(a,l,u){return this._client.post((0,s.path)`/vector_stores/${a}/files`,{body:l,...u,headers:(0,n.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},u?.headers])})}retrieve(a,l,u){const{vector_store_id:c}=l;return this._client.get((0,s.path)`/vector_stores/${c}/files/${a}`,{...u,headers:(0,n.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},u?.headers])})}update(a,l,u){const{vector_store_id:c,...d}=l;return this._client.post((0,s.path)`/vector_stores/${c}/files/${a}`,{body:d,...u,headers:(0,n.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},u?.headers])})}list(a,l={},u){return this._client.getAPIList((0,s.path)`/vector_stores/${a}/files`,t.CursorPage,{query:l,...u,headers:(0,n.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},u?.headers])})}delete(a,l,u){const{vector_store_id:c}=l;return this._client.delete((0,s.path)`/vector_stores/${c}/files/${a}`,{...u,headers:(0,n.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},u?.headers])})}async createAndPoll(a,l,u){const c=await this.create(a,l,u);return await this.poll(a,c.id,u)}async poll(a,l,u){const c=(0,n.buildHeaders)([u?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":u?.pollIntervalMs?.toString()??void 0}]);for(;;){const d=await this.retrieve(l,{vector_store_id:a},{...u,headers:c}).withResponse(),p=d.data;switch(p.status){case"in_progress":let g=5e3;if(u?.pollIntervalMs)g=u.pollIntervalMs;else{const y=d.response.headers.get("openai-poll-after-ms");if(y){const _=parseInt(y);isNaN(_)||(g=_)}}await(0,r.sleep)(g);break;case"failed":case"completed":return p}}}async upload(a,l,u){const c=await this._client.files.create({file:l,purpose:"assistants"},u);return this.create(a,{file_id:c.id},u)}async uploadAndPoll(a,l,u){const c=await this.upload(a,l,u);return await this.poll(a,c.id,u)}content(a,l,u){const{vector_store_id:c}=l;return this._client.getAPIList((0,s.path)`/vector_stores/${c}/files/${a}/content`,t.Page,{...u,headers:(0,n.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},u?.headers])})}}return So.Files=o,So}var Om;function Yb(){if(Om)return vo;Om=1,Object.defineProperty(vo,"__esModule",{value:!0}),vo.VectorStores=void 0;const e=ve(),t=ce(),n=e.__importStar(Nm()),r=Nm(),s=e.__importStar(km()),o=km(),i=ke(),a=De(),l=Te();class u extends t.APIResource{constructor(){super(...arguments),this.files=new s.Files(this._client),this.fileBatches=new n.FileBatches(this._client)}create(d,p){return this._client.post("/vector_stores",{body:d,...p,headers:(0,a.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},p?.headers])})}retrieve(d,p){return this._client.get((0,l.path)`/vector_stores/${d}`,{...p,headers:(0,a.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},p?.headers])})}update(d,p,g){return this._client.post((0,l.path)`/vector_stores/${d}`,{body:p,...g,headers:(0,a.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},g?.headers])})}list(d={},p){return this._client.getAPIList("/vector_stores",i.CursorPage,{query:d,...p,headers:(0,a.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},p?.headers])})}delete(d,p){return this._client.delete((0,l.path)`/vector_stores/${d}`,{...p,headers:(0,a.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},p?.headers])})}search(d,p,g){return this._client.getAPIList((0,l.path)`/vector_stores/${d}/search`,i.Page,{body:p,method:"post",...g,headers:(0,a.buildHeaders)([{"OpenAI-Beta":"assistants=v2"},g?.headers])})}}return vo.VectorStores=u,u.Files=o.Files,u.FileBatches=r.FileBatches,vo}var wo={},xm;function zb(){if(xm)return wo;xm=1,Object.defineProperty(wo,"__esModule",{value:!0}),wo.Videos=void 0;const e=ce(),t=ke(),n=De(),r=vn(),s=Te();class o extends e.APIResource{create(a,l){return this._client.post("/videos",(0,r.maybeMultipartFormRequestOptions)({body:a,...l},this._client))}retrieve(a,l){return this._client.get((0,s.path)`/videos/${a}`,l)}list(a={},l){return this._client.getAPIList("/videos",t.ConversationCursorPage,{query:a,...l})}delete(a,l){return this._client.delete((0,s.path)`/videos/${a}`,l)}downloadContent(a,l={},u){return this._client.get((0,s.path)`/videos/${a}/content`,{query:l,...u,headers:(0,n.buildHeaders)([{Accept:"application/binary"},u?.headers]),__binaryResponse:!0})}remix(a,l,u){return this._client.post((0,s.path)`/videos/${a}/remix`,(0,r.maybeMultipartFormRequestOptions)({body:l,...u},this._client))}}return wo.Videos=o,wo}var Eo={},Dm;function Xb(){if(Dm)return Eo;Dm=1;var e,t,n;Object.defineProperty(Eo,"__esModule",{value:!0}),Eo.Webhooks=void 0;const r=ve(),s=Xt(),o=ce(),i=De();class a extends o.APIResource{constructor(){super(...arguments),e.add(this)}async unwrap(u,c,d=this._client.webhookSecret,p=300){return await this.verifySignature(u,c,d,p),JSON.parse(u)}async verifySignature(u,c,d=this._client.webhookSecret,p=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");r.__classPrivateFieldGet(this,e,"m",t).call(this,d);const g=(0,i.buildHeaders)([c]).values,y=r.__classPrivateFieldGet(this,e,"m",n).call(this,g,"webhook-signature"),_=r.__classPrivateFieldGet(this,e,"m",n).call(this,g,"webhook-timestamp"),b=r.__classPrivateFieldGet(this,e,"m",n).call(this,g,"webhook-id"),m=parseInt(_,10);if(isNaN(m))throw new s.InvalidWebhookSignatureError("Invalid webhook timestamp format");const v=Math.floor(Date.now()/1e3);if(v-m>p)throw new s.InvalidWebhookSignatureError("Webhook timestamp is too old");if(m>v+p)throw new s.InvalidWebhookSignatureError("Webhook timestamp is too new");const A=y.split(" ").map(w=>w.startsWith("v1,")?w.substring(3):w),S=d.startsWith("whsec_")?Buffer.from(d.replace("whsec_",""),"base64"):Buffer.from(d,"utf-8"),P=b?`${b}.${_}.${u}`:`${_}.${u}`,E=await crypto.subtle.importKey("raw",S,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(const w of A)try{const I=Buffer.from(w,"base64");if(await crypto.subtle.verify("HMAC",E,I,new TextEncoder().encode(P)))return}catch{continue}throw new s.InvalidWebhookSignatureError("The given webhook signature does not match the expected signature")}}return Eo.Webhooks=a,e=new WeakSet,t=function(u){if(typeof u!="string"||u.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},n=function(u,c){if(!u)throw new Error("Headers are required");const d=u.get(c);if(d==null)throw new Error(`Missing required header: ${c}`);return d},Eo}var qm;function kP(){return qm||(qm=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Webhooks=e.Videos=e.VectorStores=e.Uploads=e.Responses=e.Realtime=e.Moderations=e.Models=e.Images=e.Graders=e.FineTuning=e.Files=e.Evals=e.Embeddings=e.Conversations=e.Containers=e.Completions=e.Beta=e.Batches=e.Audio=void 0;const t=ve();t.__exportStar(CP(),e),t.__exportStar(RP(),e);var n=Cb();Object.defineProperty(e,"Audio",{enumerable:!0,get:function(){return n.Audio}});var r=Rb();Object.defineProperty(e,"Batches",{enumerable:!0,get:function(){return r.Batches}});var s=Fb();Object.defineProperty(e,"Beta",{enumerable:!0,get:function(){return s.Beta}});var o=kb();Object.defineProperty(e,"Completions",{enumerable:!0,get:function(){return o.Completions}});var i=Ob();Object.defineProperty(e,"Containers",{enumerable:!0,get:function(){return i.Containers}});var a=xb();Object.defineProperty(e,"Conversations",{enumerable:!0,get:function(){return a.Conversations}});var l=Db();Object.defineProperty(e,"Embeddings",{enumerable:!0,get:function(){return l.Embeddings}});var u=qb();Object.defineProperty(e,"Evals",{enumerable:!0,get:function(){return u.Evals}});var c=Lb();Object.defineProperty(e,"Files",{enumerable:!0,get:function(){return c.Files}});var d=Ub();Object.defineProperty(e,"FineTuning",{enumerable:!0,get:function(){return d.FineTuning}});var p=Gb();Object.defineProperty(e,"Graders",{enumerable:!0,get:function(){return p.Graders}});var g=Vb();Object.defineProperty(e,"Images",{enumerable:!0,get:function(){return g.Images}});var y=Bb();Object.defineProperty(e,"Models",{enumerable:!0,get:function(){return y.Models}});var _=Hb();Object.defineProperty(e,"Moderations",{enumerable:!0,get:function(){return _.Moderations}});var b=Jb();Object.defineProperty(e,"Realtime",{enumerable:!0,get:function(){return b.Realtime}});var m=Kb();Object.defineProperty(e,"Responses",{enumerable:!0,get:function(){return m.Responses}});var v=$b();Object.defineProperty(e,"Uploads",{enumerable:!0,get:function(){return v.Uploads}});var A=Yb();Object.defineProperty(e,"VectorStores",{enumerable:!0,get:function(){return A.VectorStores}});var S=zb();Object.defineProperty(e,"Videos",{enumerable:!0,get:function(){return S.Videos}});var P=Xb();Object.defineProperty(e,"Webhooks",{enumerable:!0,get:function(){return P.Webhooks}})})(lu)),lu}var Lm;function Zu(){if(Lm)return is;Lm=1;var e,t,n,r;Object.defineProperty(is,"__esModule",{value:!0}),is.OpenAI=void 0;const s=ve(),o=_b(),i=kn(),a=xi(),l=Jd(),u=dh(),c=s.__importStar(va()),d=s.__importStar(bP()),p=s.__importStar(wP()),g=yb(),y=s.__importStar(yn()),_=s.__importStar(ke()),b=s.__importStar(Ab()),m=s.__importStar(kP()),v=Kd(),A=Rb(),S=kb(),P=Db(),E=Lb(),w=Vb(),I=Bb(),L=Hb(),H=zb(),B=Xb(),F=Cb(),j=Fb(),U=Ib(),O=Ob(),R=xb(),T=qb(),M=Ub(),k=Gb(),G=Jb(),V=Kb(),W=$b(),X=Yb(),Y=dh(),Z=De(),ne=Mb(),re=Wa(),Ae=kn();class le{constructor({baseURL:ee=(0,ne.readEnv)("OPENAI_BASE_URL"),apiKey:C=(0,ne.readEnv)("OPENAI_API_KEY"),organization:D=(0,ne.readEnv)("OPENAI_ORG_ID")??null,project:$=(0,ne.readEnv)("OPENAI_PROJECT_ID")??null,webhookSecret:x=(0,ne.readEnv)("OPENAI_WEBHOOK_SECRET")??null,...N}={}){if(e.add(this),n.set(this,void 0),this.completions=new m.Completions(this),this.chat=new m.Chat(this),this.embeddings=new m.Embeddings(this),this.files=new m.Files(this),this.images=new m.Images(this),this.audio=new m.Audio(this),this.moderations=new m.Moderations(this),this.models=new m.Models(this),this.fineTuning=new m.FineTuning(this),this.graders=new m.Graders(this),this.vectorStores=new m.VectorStores(this),this.webhooks=new m.Webhooks(this),this.beta=new m.Beta(this),this.batches=new m.Batches(this),this.uploads=new m.Uploads(this),this.responses=new m.Responses(this),this.realtime=new m.Realtime(this),this.conversations=new m.Conversations(this),this.evals=new m.Evals(this),this.containers=new m.Containers(this),this.videos=new m.Videos(this),C===void 0)throw new y.OpenAIError("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");const q={apiKey:C,organization:D,project:$,webhookSecret:x,...N,baseURL:ee||"https://api.openai.com/v1"};if(!q.dangerouslyAllowBrowser&&(0,Y.isRunningInBrowser)())throw new y.OpenAIError(`It looks like you're running in a browser-like environment.
24
-
25
- This is disabled by default, as it risks exposing your secret API credentials to attackers.
26
- If you understand the risks and have appropriate mitigations in place,
27
- you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
28
-
29
- new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
30
-
31
- https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
32
- `);this.baseURL=q.baseURL,this.timeout=q.timeout??t.DEFAULT_TIMEOUT,this.logger=q.logger??console;const J="warn";this.logLevel=J,this.logLevel=(0,re.parseLogLevel)(q.logLevel,"ClientOptions.logLevel",this)??(0,re.parseLogLevel)((0,ne.readEnv)("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??J,this.fetchOptions=q.fetchOptions,this.maxRetries=q.maxRetries??2,this.fetch=q.fetch??c.getDefaultFetch(),s.__classPrivateFieldSet(this,n,d.FallbackEncoder,"f"),this._options=q,this.apiKey=typeof C=="string"?C:"Missing Key",this.organization=D,this.project=$,this.webhookSecret=x}withOptions(ee){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,...ee})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:ee,nulls:C}){}async authHeaders(ee){return(0,Z.buildHeaders)([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(ee){return p.stringify(ee,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${g.VERSION}`}defaultIdempotencyKey(){return`stainless-node-retry-${(0,o.uuid4)()}`}makeStatusError(ee,C,D,$){return y.APIError.generate(ee,C,D,$)}async _callApiKey(){const ee=this._options.apiKey;if(typeof ee!="function")return!1;let C;try{C=await ee()}catch(D){throw D instanceof y.OpenAIError?D:new y.OpenAIError(`Failed to get token from 'apiKey' function: ${D.message}`,{cause:D})}if(typeof C!="string"||!C)throw new y.OpenAIError(`Expected 'apiKey' function argument to return a string but it returned ${C}`);return this.apiKey=C,!0}buildURL(ee,C,D){const $=!s.__classPrivateFieldGet(this,e,"m",r).call(this)&&D||this.baseURL,x=(0,i.isAbsoluteURL)(ee)?new URL(ee):new URL($+($.endsWith("/")&&ee.startsWith("/")?ee.slice(1):ee)),N=this.defaultQuery();return(0,Ae.isEmptyObj)(N)||(C={...N,...C}),typeof C=="object"&&C&&!Array.isArray(C)&&(x.search=this.stringifyQuery(C)),x.toString()}async prepareOptions(ee){await this._callApiKey()}async prepareRequest(ee,{url:C,options:D}){}get(ee,C){return this.methodRequest("get",ee,C)}post(ee,C){return this.methodRequest("post",ee,C)}patch(ee,C){return this.methodRequest("patch",ee,C)}put(ee,C){return this.methodRequest("put",ee,C)}delete(ee,C){return this.methodRequest("delete",ee,C)}methodRequest(ee,C,D){return this.request(Promise.resolve(D).then($=>({method:ee,path:C,...$})))}request(ee,C=null){return new v.APIPromise(this,this.makeRequest(ee,C,void 0))}async makeRequest(ee,C,D){const $=await ee,x=$.maxRetries??this.maxRetries;C==null&&(C=x),await this.prepareOptions($);const{req:N,url:q,timeout:J}=await this.buildRequest($,{retryCount:x-C});await this.prepareRequest(N,{url:q,options:$});const K="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),Q=D===void 0?"":`, retryOf: ${D}`,z=Date.now();if((0,re.loggerFor)(this).debug(`[${K}] sending request`,(0,re.formatRequestDetails)({retryOfRequestLogID:D,method:$.method,url:q,options:$,headers:N.headers})),$.signal?.aborted)throw new y.APIUserAbortError;const ae=new AbortController,te=await this.fetchWithTimeout(q,N,J,ae).catch(l.castToError),se=Date.now();if(te instanceof globalThis.Error){const ge=`retrying, ${C} attempts remaining`;if($.signal?.aborted)throw new y.APIUserAbortError;const pe=(0,l.isAbortError)(te)||/timed? ?out/i.test(String(te)+("cause"in te?String(te.cause):""));if(C)return(0,re.loggerFor)(this).info(`[${K}] connection ${pe?"timed out":"failed"} - ${ge}`),(0,re.loggerFor)(this).debug(`[${K}] connection ${pe?"timed out":"failed"} (${ge})`,(0,re.formatRequestDetails)({retryOfRequestLogID:D,url:q,durationMs:se-z,message:te.message})),this.retryRequest($,C,D??K);throw(0,re.loggerFor)(this).info(`[${K}] connection ${pe?"timed out":"failed"} - error; no more retries left`),(0,re.loggerFor)(this).debug(`[${K}] connection ${pe?"timed out":"failed"} (error; no more retries left)`,(0,re.formatRequestDetails)({retryOfRequestLogID:D,url:q,durationMs:se-z,message:te.message})),pe?new y.APIConnectionTimeoutError:new y.APIConnectionError({cause:te})}const de=[...te.headers.entries()].filter(([ge])=>ge==="x-request-id").map(([ge,pe])=>", "+ge+": "+JSON.stringify(pe)).join(""),_e=`[${K}${Q}${de}] ${N.method} ${q} ${te.ok?"succeeded":"failed"} with status ${te.status} in ${se-z}ms`;if(!te.ok){const ge=await this.shouldRetry(te);if(C&&ge){const Vt=`retrying, ${C} attempts remaining`;return await c.CancelReadableStream(te.body),(0,re.loggerFor)(this).info(`${_e} - ${Vt}`),(0,re.loggerFor)(this).debug(`[${K}] response error (${Vt})`,(0,re.formatRequestDetails)({retryOfRequestLogID:D,url:te.url,status:te.status,headers:te.headers,durationMs:se-z})),this.retryRequest($,C,D??K,te.headers)}const pe=ge?"error; no more retries left":"error; not retryable";(0,re.loggerFor)(this).info(`${_e} - ${pe}`);const Le=await te.text().catch(Vt=>(0,l.castToError)(Vt).message),Ge=(0,i.safeJSON)(Le),je=Ge?void 0:Le;throw(0,re.loggerFor)(this).debug(`[${K}] response error (${pe})`,(0,re.formatRequestDetails)({retryOfRequestLogID:D,url:te.url,status:te.status,headers:te.headers,message:je,durationMs:Date.now()-z})),this.makeStatusError(te.status,Ge,je,te.headers)}return(0,re.loggerFor)(this).info(_e),(0,re.loggerFor)(this).debug(`[${K}] response start`,(0,re.formatRequestDetails)({retryOfRequestLogID:D,url:te.url,status:te.status,headers:te.headers,durationMs:se-z})),{response:te,options:$,controller:ae,requestLogID:K,retryOfRequestLogID:D,startTime:z}}getAPIList(ee,C,D){return this.requestAPIList(C,D&&"then"in D?D.then($=>({method:"get",path:ee,...$})):{method:"get",path:ee,...D})}requestAPIList(ee,C){const D=this.makeRequest(C,null,void 0);return new _.PagePromise(this,D,ee)}async fetchWithTimeout(ee,C,D,$){const{signal:x,method:N,...q}=C||{},J=this._makeAbort($);x&&x.addEventListener("abort",J,{once:!0});const K=setTimeout(J,D),Q=globalThis.ReadableStream&&q.body instanceof globalThis.ReadableStream||typeof q.body=="object"&&q.body!==null&&Symbol.asyncIterator in q.body,z={signal:$.signal,...Q?{duplex:"half"}:{},method:"GET",...q};N&&(z.method=N.toUpperCase());try{return await this.fetch.call(void 0,ee,z)}finally{clearTimeout(K)}}async shouldRetry(ee){const C=ee.headers.get("x-should-retry");return C==="true"?!0:C==="false"?!1:ee.status===408||ee.status===409||ee.status===429||ee.status>=500}async retryRequest(ee,C,D,$){let x;const N=$?.get("retry-after-ms");if(N){const J=parseFloat(N);Number.isNaN(J)||(x=J)}const q=$?.get("retry-after");if(q&&!x){const J=parseFloat(q);Number.isNaN(J)?x=Date.parse(q)-Date.now():x=J*1e3}if(!(x&&0<=x&&x<60*1e3)){const J=ee.maxRetries??this.maxRetries;x=this.calculateDefaultRetryTimeoutMillis(C,J)}return await(0,a.sleep)(x),this.makeRequest(ee,C-1,D)}calculateDefaultRetryTimeoutMillis(ee,C){const x=C-ee,N=Math.min(.5*Math.pow(2,x),8),q=1-Math.random()*.25;return N*q*1e3}async buildRequest(ee,{retryCount:C=0}={}){const D={...ee},{method:$,path:x,query:N,defaultBaseURL:q}=D,J=this.buildURL(x,N,q);"timeout"in D&&(0,i.validatePositiveInteger)("timeout",D.timeout),D.timeout=D.timeout??this.timeout;const{bodyHeaders:K,body:Q}=this.buildBody({options:D}),z=await this.buildHeaders({options:ee,method:$,bodyHeaders:K,retryCount:C});return{req:{method:$,headers:z,...D.signal&&{signal:D.signal},...globalThis.ReadableStream&&Q instanceof globalThis.ReadableStream&&{duplex:"half"},...Q&&{body:Q},...this.fetchOptions??{},...D.fetchOptions??{}},url:J,timeout:D.timeout}}async buildHeaders({options:ee,method:C,bodyHeaders:D,retryCount:$}){let x={};this.idempotencyHeader&&C!=="get"&&(ee.idempotencyKey||(ee.idempotencyKey=this.defaultIdempotencyKey()),x[this.idempotencyHeader]=ee.idempotencyKey);const N=(0,Z.buildHeaders)([x,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String($),...ee.timeout?{"X-Stainless-Timeout":String(Math.trunc(ee.timeout/1e3))}:{},...(0,u.getPlatformHeaders)(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(ee),this._options.defaultHeaders,D,ee.headers]);return this.validateHeaders(N),N.values}_makeAbort(ee){return()=>ee.abort()}buildBody({options:{body:ee,headers:C}}){if(!ee)return{bodyHeaders:void 0,body:void 0};const D=(0,Z.buildHeaders)([C]);return ArrayBuffer.isView(ee)||ee instanceof ArrayBuffer||ee instanceof DataView||typeof ee=="string"&&D.values.has("content-type")||globalThis.Blob&&ee instanceof globalThis.Blob||ee instanceof FormData||ee instanceof URLSearchParams||globalThis.ReadableStream&&ee instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:ee}:typeof ee=="object"&&(Symbol.asyncIterator in ee||Symbol.iterator in ee&&"next"in ee&&typeof ee.next=="function")?{bodyHeaders:void 0,body:c.ReadableStreamFrom(ee)}:s.__classPrivateFieldGet(this,n,"f").call(this,{body:ee,headers:D})}}return is.OpenAI=le,t=le,n=new WeakMap,e=new WeakSet,r=function(){return this.baseURL!=="https://api.openai.com/v1"},le.OpenAI=t,le.DEFAULT_TIMEOUT=6e5,le.OpenAIError=y.OpenAIError,le.APIError=y.APIError,le.APIConnectionError=y.APIConnectionError,le.APIConnectionTimeoutError=y.APIConnectionTimeoutError,le.APIUserAbortError=y.APIUserAbortError,le.NotFoundError=y.NotFoundError,le.ConflictError=y.ConflictError,le.RateLimitError=y.RateLimitError,le.BadRequestError=y.BadRequestError,le.AuthenticationError=y.AuthenticationError,le.InternalServerError=y.InternalServerError,le.PermissionDeniedError=y.PermissionDeniedError,le.UnprocessableEntityError=y.UnprocessableEntityError,le.InvalidWebhookSignatureError=y.InvalidWebhookSignatureError,le.toFile=b.toFile,le.Completions=S.Completions,le.Chat=U.Chat,le.Embeddings=P.Embeddings,le.Files=E.Files,le.Images=w.Images,le.Audio=F.Audio,le.Moderations=L.Moderations,le.Models=I.Models,le.FineTuning=M.FineTuning,le.Graders=k.Graders,le.VectorStores=X.VectorStores,le.Webhooks=B.Webhooks,le.Beta=j.Beta,le.Batches=A.Batches,le.Uploads=W.Uploads,le.Responses=V.Responses,le.Realtime=G.Realtime,le.Conversations=R.Conversations,le.Evals=T.Evals,le.Containers=O.Containers,le.Videos=H.Videos,is}var To={},Um;function OP(){if(Um)return To;Um=1;var e={};Object.defineProperty(To,"__esModule",{value:!0}),To.AzureOpenAI=void 0;const t=ve(),n=De(),r=t.__importStar(Xt()),s=$a(),o=Zu();class i extends o.OpenAI{constructor({baseURL:u=(0,s.readEnv)("OPENAI_BASE_URL"),apiKey:c=(0,s.readEnv)("AZURE_OPENAI_API_KEY"),apiVersion:d=(0,s.readEnv)("OPENAI_API_VERSION"),endpoint:p,deployment:g,azureADTokenProvider:y,dangerouslyAllowBrowser:_,...b}={}){if(!d)throw new r.OpenAIError("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).");if(typeof y=="function"&&(_=!0),!y&&!c)throw new r.OpenAIError("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(y&&c)throw new r.OpenAIError("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(b.defaultQuery={...b.defaultQuery,"api-version":d},u){if(p)throw new r.OpenAIError("baseURL and endpoint are mutually exclusive")}else{if(p||(p=e.AZURE_OPENAI_ENDPOINT),!p)throw new r.OpenAIError("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");u=`${p}/openai`}super({apiKey:y??c,baseURL:u,...b,..._!==void 0?{dangerouslyAllowBrowser:_}:{}}),this.apiVersion="",this.apiVersion=d,this.deploymentName=g}async buildRequest(u,c={}){if(a.has(u.path)&&u.method==="post"&&u.body!==void 0){if(!(0,s.isObj)(u.body))throw new Error("Expected request body to be an object");const d=this.deploymentName||u.body.model||u.__metadata?.model;d!==void 0&&!this.baseURL.includes("/deployments")&&(u.path=`/deployments/${d}${u.path}`)}return super.buildRequest(u,c)}async authHeaders(u){return typeof this._options.apiKey=="string"?(0,n.buildHeaders)([{"api-key":this.apiKey}]):super.authHeaders(u)}}To.AzureOpenAI=i;const a=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"]);return To}var Gm;function Qb(){return Gm||(Gm=1,(function(e,t){t=e.exports=function(...u){return new t.default(...u)},Object.defineProperty(t,"__esModule",{value:!0}),t.AzureOpenAI=t.InvalidWebhookSignatureError=t.UnprocessableEntityError=t.PermissionDeniedError=t.InternalServerError=t.AuthenticationError=t.BadRequestError=t.RateLimitError=t.ConflictError=t.NotFoundError=t.APIUserAbortError=t.APIConnectionTimeoutError=t.APIConnectionError=t.APIError=t.OpenAIError=t.PagePromise=t.OpenAI=t.APIPromise=t.toFile=t.default=void 0;var n=Zu();Object.defineProperty(t,"default",{enumerable:!0,get:function(){return n.OpenAI}});var r=Ab();Object.defineProperty(t,"toFile",{enumerable:!0,get:function(){return r.toFile}});var s=Kd();Object.defineProperty(t,"APIPromise",{enumerable:!0,get:function(){return s.APIPromise}});var o=Zu();Object.defineProperty(t,"OpenAI",{enumerable:!0,get:function(){return o.OpenAI}});var i=ke();Object.defineProperty(t,"PagePromise",{enumerable:!0,get:function(){return i.PagePromise}});var a=yn();Object.defineProperty(t,"OpenAIError",{enumerable:!0,get:function(){return a.OpenAIError}}),Object.defineProperty(t,"APIError",{enumerable:!0,get:function(){return a.APIError}}),Object.defineProperty(t,"APIConnectionError",{enumerable:!0,get:function(){return a.APIConnectionError}}),Object.defineProperty(t,"APIConnectionTimeoutError",{enumerable:!0,get:function(){return a.APIConnectionTimeoutError}}),Object.defineProperty(t,"APIUserAbortError",{enumerable:!0,get:function(){return a.APIUserAbortError}}),Object.defineProperty(t,"NotFoundError",{enumerable:!0,get:function(){return a.NotFoundError}}),Object.defineProperty(t,"ConflictError",{enumerable:!0,get:function(){return a.ConflictError}}),Object.defineProperty(t,"RateLimitError",{enumerable:!0,get:function(){return a.RateLimitError}}),Object.defineProperty(t,"BadRequestError",{enumerable:!0,get:function(){return a.BadRequestError}}),Object.defineProperty(t,"AuthenticationError",{enumerable:!0,get:function(){return a.AuthenticationError}}),Object.defineProperty(t,"InternalServerError",{enumerable:!0,get:function(){return a.InternalServerError}}),Object.defineProperty(t,"PermissionDeniedError",{enumerable:!0,get:function(){return a.PermissionDeniedError}}),Object.defineProperty(t,"UnprocessableEntityError",{enumerable:!0,get:function(){return a.UnprocessableEntityError}}),Object.defineProperty(t,"InvalidWebhookSignatureError",{enumerable:!0,get:function(){return a.InvalidWebhookSignatureError}});var l=OP();Object.defineProperty(t,"AzureOpenAI",{enumerable:!0,get:function(){return l.AzureOpenAI}})})(Ji,Ji.exports)),Ji.exports}var _u={},Vm;function Di(){return Vm||(Vm=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.llmMetaDataFirstTokenTime=e.llmMetaDataEndTime=e.initLLMMetaData=e.convertMeta=e.getMessages=e.getMergeValue=e.flatString=void 0;const t=l=>Array.isArray(l)?l.filter(u=>u).join(`
33
- `):l??"";e.flatString=t;const n=(l,u,c,d)=>{const p=l[c],g=u[c];return p||g?[(0,e.flatString)(p),(0,e.flatString)(g)].filter(y=>y).join(`
34
- `):(0,e.flatString)(d)};e.getMergeValue=n;const r=(l,u)=>[...l?[{role:"system",content:l}]:[],...u??[]];e.getMessages=r;const s=l=>{const{start:u,firstToken:c,end:d}=l.timing,p=c?c-u:void 0,g=c?d-c:void 0,y=d-u;return{timing:{start:new Date(u).toISOString(),firstToken:c?new Date(c).toISOString():void 0,end:new Date(d).toISOString(),latencyToFirstToken:p,duration:g,totalElapsed:y}}};e.convertMeta=s;const o=()=>({timing:{start:Date.now(),end:0,totalElapsed:0}});e.initLLMMetaData=o;const i=l=>{l.timing.end=Date.now()};e.llmMetaDataEndTime=i;const a=l=>{l.timing.firstToken===void 0&&(l.timing.firstToken=Date.now())};e.llmMetaDataFirstTokenTime=a})(_u)),_u}var Bm;function xP(){return Bm||(Bm=1,(function(e){var t=on&&on.__createBinding||(Object.create?(function(y,_,b,m){m===void 0&&(m=b);var v=Object.getOwnPropertyDescriptor(_,b);(!v||("get"in v?!_.__esModule:v.writable||v.configurable))&&(v={enumerable:!0,get:function(){return _[b]}}),Object.defineProperty(y,m,v)}):(function(y,_,b,m){m===void 0&&(m=b),y[m]=_[b]})),n=on&&on.__setModuleDefault||(Object.create?(function(y,_){Object.defineProperty(y,"default",{enumerable:!0,value:_})}):function(y,_){y.default=_}),r=on&&on.__importStar||(function(){var y=function(_){return y=Object.getOwnPropertyNames||function(b){var m=[];for(var v in b)Object.prototype.hasOwnProperty.call(b,v)&&(m[m.length]=v);return m},y(_)};return function(_){if(_&&_.__esModule)return _;var b={};if(_!=null)for(var m=y(_),v=0;v<m.length;v++)m[v]!=="default"&&t(b,_,m[v]);return n(b,_),b}})();Object.defineProperty(e,"__esModule",{value:!0}),e.openAIMockAgent=e.openAIAgent=void 0;const s=r(Qb()),o=Oe(),i=Di(),a=y=>({id:y.id,name:y.type==="function"?y.function.name:"",arguments:(()=>{try{return JSON.parse(y.type==="function"?y.function.arguments:"{}")}catch(_){console.log(_);return}})()}),l=(y,_,b,m)=>{(0,i.llmMetaDataEndTime)(b);const v=y?.choices[0]&&y?.choices[0].message?y?.choices[0].message:null,A=v&&v.content?v.content:null,P=(v?.tool_calls&&Array.isArray(v?.tool_calls)?v?.tool_calls:[]).map(a),E=P&&P.length>0?P[0]:void 0,w=(()=>{if(v){const{content:L,role:H,tool_calls:B}=v;return B&&B.length>0?{content:L,role:H,tool_calls:B}:{content:L,role:H}}return null})();w&&_.push(w);const I=(()=>{if(m&&A){const L=JSON.parse(A);if(typeof L=="object"&&L!==null)return L}return null})();return{...y,text:A,tool:E,tool_calls:P,message:w,messages:_,usage:y.usage,metadata:(0,i.convertMeta)(b),responseFormat:I}},u=async({filterParams:y,params:_,namedInputs:b,config:m})=>{const{verbose:v,system:A,images:S,temperature:P,tools:E,tool_choice:w,max_tokens:I,max_completion_tokens:L,prompt:H,messages:B,message:F,response_format:j}={..._,...b},{apiKey:U,stream:O,dataStream:R,forWeb:T,model:M,baseURL:k,apiVersion:G}={...m||{},..._},V=(0,i.initLLMMetaData)(),W=(0,i.getMergeValue)(b,_,"mergeablePrompts",H),X=(0,i.getMergeValue)(b,_,"mergeableSystem",A),Y=(0,i.getMessages)(X,B);if(F?Y.push(F):W&&Y.push({role:"user",content:W}),S){const we={url:S[0],detail:"high"};Y.push({role:"user",content:[{type:"image_url",image_url:we}]})}v&&console.log(Y);const Z=(()=>{if(k)try{if(new URL(k).hostname.endsWith(".openai.azure.com"))return new s.AzureOpenAI({apiKey:U,endpoint:k,apiVersion:G??"2025-04-01-preview"})}catch{}return new s.default({apiKey:U,baseURL:k,dangerouslyAllowBrowser:!!T})})(),ne=M||"gpt-4o",re={model:ne,messages:Y,tools:E,tool_choice:w,max_completion_tokens:L??I,response_format:j};if(ne.startsWith("gpt-4")&&(re.temperature=P??.7),!O&&!R){const we=await Z.chat.completions.create(re);return l(we,Y,V,!!j)}const Ae=Z.chat.completions.stream({...re,stream:!0,stream_options:{include_usage:!0}});if(R||O){R&&y&&y.streamTokenCallback&&y.streamTokenCallback({type:"response.created",response:{}});for await(const we of Ae)if(we.choices[0]){(0,i.llmMetaDataFirstTokenTime)(V);const{content:ee,tool_calls:C}=we.choices[0].delta;if(y&&y.streamTokenCallback)if(R&&(!(0,o.isNull)(ee)||!(0,o.isNull)(C))){const D=(0,o.isNull)(ee)?[{type:"tool_calls",data:C}]:[{type:"text",text:ee}];y.streamTokenCallback({type:"response.in_progress",response:{output:D}})}else(0,o.isNull)(ee)||y.streamTokenCallback(ee)}R&&y&&y.streamTokenCallback&&y.streamTokenCallback({type:"response.completed",response:{}})}const le=await Ae.finalChatCompletion();return l(le,Y,V,!!j)};e.openAIAgent=u;const c="this is response result",d={object:"chat.completion",id:"chatcmpl-9N7HxXYbwjmdbdiQE94MHoVluQhyt",choices:[{message:{role:"assistant",content:c},finish_reason:"stop",index:0,logprobs:null}],created:1715296589,model:"gpt-4o"},p=async({filterParams:y})=>{for await(const b of c.split(""))y&&y.streamTokenCallback&&b&&(await(0,o.sleep)(100),y.streamTokenCallback(b));const _={role:"user",content:c};return{text:c,message:_,messages:[_]}};e.openAIMockAgent=p;const g={name:"openAIAgent",agent:e.openAIAgent,mock:e.openAIMockAgent,inputs:{type:"object",properties:{model:{type:"string"},system:{type:"string"},tools:{type:"object"},tool_choice:{anyOf:[{type:"array"},{type:"object"}]},max_completion_tokens:{type:"number"},verbose:{type:"boolean"},temperature:{type:"number"},baseURL:{type:"string"},apiVersion:{type:"string",description:"Azure API version"},apiKey:{anyOf:[{type:"string"},{type:"object"}]},stream:{type:"boolean"},prompt:{type:"string",description:"query string"},messages:{anyOf:[{type:"string"},{type:"object"},{type:"array"}],description:"chat messages"}}},output:{type:"object",properties:{id:{type:"string"},object:{type:"string"},created:{type:"integer"},model:{type:"string"},choices:{type:"array",items:[{type:"object",properties:{index:{type:"integer"},message:{type:"array",items:[{type:"object",properties:{content:{type:"string"},role:{type:"string"}},required:["content","role"]}]}},required:["index","message","logprobs","finish_reason"]}]},usage:{type:"object",properties:{prompt_tokens:{type:"integer"},completion_tokens:{type:"integer"},total_tokens:{type:"integer"}},required:["prompt_tokens","completion_tokens","total_tokens"]},text:{type:"string"},tool:{arguments:{type:"object"},name:{type:"string"}},message:{type:"object",properties:{content:{type:"string"},role:{type:"string"}},required:["content","role"]}},required:["id","object","created","model","choices","usage"]},params:{type:"object",properties:{model:{type:"string"},system:{type:"string"},tools:{type:"object"},tool_choice:{anyOf:[{type:"array"},{type:"object"}]},max_completion_tokens:{type:"number"},verbose:{type:"boolean"},temperature:{type:"number"},baseURL:{type:"string"},apiVersion:{type:"string",description:"Azure API version"},apiKey:{anyOf:[{type:"string"},{type:"object"}]},stream:{type:"boolean"},prompt:{type:"string",description:"query string"},messages:{anyOf:[{type:"string"},{type:"object"},{type:"array"}],description:"chat messages"}}},outputFormat:{llmResponse:{key:"choices.$0.message.content",type:"string"}},samples:[{inputs:{prompt:c},params:{},result:d}],description:"OpenAI Agent",category:["llm"],author:"Receptron team",repository:"https://github.com/receptron/graphai",source:"https://github.com/receptron/graphai/blob/main/llm_agents/openai_agent/src/openai_agent.ts",package:"@graphai/openai_agent",license:"MIT",stream:!0,npms:["openai"],environmentVariables:["OPENAI_API_KEY"]};e.default=g})(on)),on}var Po={},Hm;function DP(){return Hm||(Hm=1,(function(e){var t=Po&&Po.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(e,"__esModule",{value:!0}),e.openAIImageAgent=void 0;const n=t(Qb()),r=Di(),s=async({params:i,namedInputs:a,config:l})=>{const{system:u,prompt:c}={...i,...a},{apiKey:d,baseURL:p,forWeb:g}={...i,...l||{}},y=(0,r.getMergeValue)(a,i,"mergeablePrompts",c),_=(0,r.getMergeValue)(a,i,"mergeableSystem",u),b=new n.default({apiKey:d,baseURL:p,dangerouslyAllowBrowser:!!g}),m={model:i.model||"dall-e-3",prompt:[_,y].filter(A=>A).join(`
35
- `),n:1,response_format:"url"};return await b.images.generate(m)};e.openAIImageAgent=s;const o={name:"openAIImageAgent",agent:e.openAIImageAgent,mock:e.openAIImageAgent,inputs:{},output:{},params:{},outputFormat:{},samples:[],description:"OpenAI Image Agent",category:["llm"],author:"Receptron team",repository:"https://github.com/receptron/graphai",source:"https://github.com/receptron/graphai/blob/main/llm_agents/openai_agent/src/openai_image_agent.ts",package:"@graphai/openai_agent",license:"MIT",stream:!1,npms:["openai"],environmentVariables:["OPENAI_API_KEY"]};e.default=o})(Po)),Po}var Jm;function qP(){if(Jm)return sn;Jm=1;var e=sn&&sn.__importDefault||function(r){return r&&r.__esModule?r:{default:r}};Object.defineProperty(sn,"__esModule",{value:!0}),sn.openAIImageAgent=sn.openAIAgent=void 0;const t=e(xP());sn.openAIAgent=t.default;const n=e(DP());return sn.openAIImageAgent=n.default,sn}qP();var $n={},Io={},Ki={exports:{}},yu={},wt={},jm;function at(){if(jm)return wt;jm=1,Object.defineProperty(wt,"__esModule",{value:!0}),wt.__setModuleDefault=wt.__createBinding=void 0,wt.__classPrivateFieldSet=e,wt.__classPrivateFieldGet=t,wt.__exportStar=r,wt.__importStar=i;function e(a,l,u,c,d){if(c==="m")throw new TypeError("Private method is not writable");if(c==="a"&&!d)throw new TypeError("Private accessor was defined without a setter");if(typeof l=="function"?a!==l||!d:!l.has(a))throw new TypeError("Cannot write private member to an object whose class did not declare it");return c==="a"?d.call(a,u):d?d.value=u:l.set(a,u),u}function t(a,l,u,c){if(u==="a"&&!c)throw new TypeError("Private accessor was defined without a getter");if(typeof l=="function"?a!==l||!c:!l.has(a))throw new TypeError("Cannot read private member from an object whose class did not declare it");return u==="m"?c:u==="a"?c.call(a):c?c.value:l.get(a)}var n=Object.create?function(a,l,u,c){c===void 0&&(c=u);var d=Object.getOwnPropertyDescriptor(l,u);(!d||("get"in d?!l.__esModule:d.writable||d.configurable))&&(d={enumerable:!0,get:function(){return l[u]}}),Object.defineProperty(a,c,d)}:function(a,l,u,c){c===void 0&&(c=u),a[c]=l[u]};wt.__createBinding=n;function r(a,l){for(var u in a)u!=="default"&&!Object.prototype.hasOwnProperty.call(l,u)&&n(l,a,u)}var s=Object.create?function(a,l){Object.defineProperty(a,"default",{enumerable:!0,value:l})}:function(a,l){a.default=l};wt.__setModuleDefault=s;var o=function(a){return o=Object.getOwnPropertyNames||function(l){var u=[];for(var c in l)Object.prototype.hasOwnProperty.call(l,c)&&(u[u.length]=c);return u},o(a)};function i(a){if(a&&a.__esModule)return a;var l={};if(a!=null)for(var u=o(a),c=0;c<u.length;c++)u[c]!=="default"&&n(l,a,u[c]);return s(l,a),l}return wt}var vr={},Wm;function LP(){if(Wm)return vr;Wm=1,Object.defineProperty(vr,"__esModule",{value:!0}),vr.uuid4=void 0;let e=function(){const{crypto:t}=globalThis;if(t?.randomUUID)return vr.uuid4=t.randomUUID.bind(t),t.randomUUID();const n=new Uint8Array(1),r=t?()=>t.getRandomValues(n)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,s=>(+s^r()&15>>+s/4).toString(16))};return vr.uuid4=e,vr}var vu={},Ce={},br={},Km;function qi(){if(Km)return br;Km=1,Object.defineProperty(br,"__esModule",{value:!0}),br.castToError=void 0,br.isAbortError=e;function e(n){return typeof n=="object"&&n!==null&&("name"in n&&n.name==="AbortError"||"message"in n&&String(n.message).includes("FetchRequestCanceledException"))}const t=n=>{if(n instanceof Error)return n;if(typeof n=="object"&&n!==null){try{if(Object.prototype.toString.call(n)==="[object Error]"){const r=new Error(n.message,n.cause?{cause:n.cause}:{});return n.stack&&(r.stack=n.stack),n.cause&&!r.cause&&(r.cause=n.cause),n.name&&(r.name=n.name),r}}catch{}try{return new Error(JSON.stringify(n))}catch{}}return new Error(n)};return br.castToError=t,br}var $m;function Dt(){if($m)return Ce;$m=1,Object.defineProperty(Ce,"__esModule",{value:!0}),Ce.InternalServerError=Ce.RateLimitError=Ce.UnprocessableEntityError=Ce.ConflictError=Ce.NotFoundError=Ce.PermissionDeniedError=Ce.AuthenticationError=Ce.BadRequestError=Ce.APIConnectionTimeoutError=Ce.APIConnectionError=Ce.APIUserAbortError=Ce.APIError=Ce.AnthropicError=void 0;const e=qi();class t extends Error{}Ce.AnthropicError=t;class n extends t{constructor(_,b,m,v){super(`${n.makeMessage(_,b,m)}`),this.status=_,this.headers=v,this.requestID=v?.get("request-id"),this.error=b}static makeMessage(_,b,m){const v=b?.message?typeof b.message=="string"?b.message:JSON.stringify(b.message):b?JSON.stringify(b):m;return _&&v?`${_} ${v}`:_?`${_} status code (no body)`:v||"(no status code or body)"}static generate(_,b,m,v){if(!_||!v)return new s({message:m,cause:(0,e.castToError)(b)});const A=b;return _===400?new i(_,A,m,v):_===401?new a(_,A,m,v):_===403?new l(_,A,m,v):_===404?new u(_,A,m,v):_===409?new c(_,A,m,v):_===422?new d(_,A,m,v):_===429?new p(_,A,m,v):_>=500?new g(_,A,m,v):new n(_,A,m,v)}}Ce.APIError=n;class r extends n{constructor({message:_}={}){super(void 0,void 0,_||"Request was aborted.",void 0)}}Ce.APIUserAbortError=r;class s extends n{constructor({message:_,cause:b}){super(void 0,void 0,_||"Connection error.",void 0),b&&(this.cause=b)}}Ce.APIConnectionError=s;class o extends s{constructor({message:_}={}){super({message:_??"Request timed out."})}}Ce.APIConnectionTimeoutError=o;class i extends n{}Ce.BadRequestError=i;class a extends n{}Ce.AuthenticationError=a;class l extends n{}Ce.PermissionDeniedError=l;class u extends n{}Ce.NotFoundError=u;class c extends n{}Ce.ConflictError=c;class d extends n{}Ce.UnprocessableEntityError=d;class p extends n{}Ce.RateLimitError=p;class g extends n{}return Ce.InternalServerError=g,Ce}var Ym;function Vr(){return Ym||(Ym=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.pop=e.safeJSON=e.maybeCoerceBoolean=e.maybeCoerceFloat=e.maybeCoerceInteger=e.coerceBoolean=e.coerceFloat=e.coerceInteger=e.validatePositiveInteger=e.ensurePresent=e.isReadonlyArray=e.isArray=e.isAbsoluteURL=void 0,e.maybeObj=o,e.isEmptyObj=i,e.hasOwn=a,e.isObj=l;const t=Dt(),n=/^[a-z][a-z0-9+.-]*:/i,r=A=>n.test(A);e.isAbsoluteURL=r;let s=A=>(e.isArray=Array.isArray,(0,e.isArray)(A));e.isArray=s,e.isReadonlyArray=e.isArray;function o(A){return typeof A!="object"?{}:A??{}}function i(A){if(!A)return!0;for(const S in A)return!1;return!0}function a(A,S){return Object.prototype.hasOwnProperty.call(A,S)}function l(A){return A!=null&&typeof A=="object"&&!Array.isArray(A)}const u=A=>{if(A==null)throw new t.AnthropicError(`Expected a value to be given but received ${A} instead.`);return A};e.ensurePresent=u;const c=(A,S)=>{if(typeof S!="number"||!Number.isInteger(S))throw new t.AnthropicError(`${A} must be an integer`);if(S<0)throw new t.AnthropicError(`${A} must be a positive integer`);return S};e.validatePositiveInteger=c;const d=A=>{if(typeof A=="number")return Math.round(A);if(typeof A=="string")return parseInt(A,10);throw new t.AnthropicError(`Could not coerce ${A} (type: ${typeof A}) into a number`)};e.coerceInteger=d;const p=A=>{if(typeof A=="number")return A;if(typeof A=="string")return parseFloat(A);throw new t.AnthropicError(`Could not coerce ${A} (type: ${typeof A}) into a number`)};e.coerceFloat=p;const g=A=>typeof A=="boolean"?A:typeof A=="string"?A==="true":!!A;e.coerceBoolean=g;const y=A=>{if(A!=null)return(0,e.coerceInteger)(A)};e.maybeCoerceInteger=y;const _=A=>{if(A!=null)return(0,e.coerceFloat)(A)};e.maybeCoerceFloat=_;const b=A=>{if(A!=null)return(0,e.coerceBoolean)(A)};e.maybeCoerceBoolean=b;const m=A=>{try{return JSON.parse(A)}catch{return}};e.safeJSON=m;const v=(A,S)=>{const P=A[S];return delete A[S],P};e.pop=v})(vu)),vu}var Co={},zm;function UP(){if(zm)return Co;zm=1,Object.defineProperty(Co,"__esModule",{value:!0}),Co.sleep=void 0;const e=t=>new Promise(n=>setTimeout(n,t));return Co.sleep=e,Co}var Yn={},Ro={},Xm;function Zb(){return Xm||(Xm=1,Object.defineProperty(Ro,"__esModule",{value:!0}),Ro.VERSION=void 0,Ro.VERSION="0.71.2"),Ro}var Qm;function Zm(){if(Qm)return Yn;Qm=1,Object.defineProperty(Yn,"__esModule",{value:!0}),Yn.getPlatformHeaders=Yn.isRunningInBrowser=void 0;const e=Zb(),t=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";Yn.isRunningInBrowser=t;function n(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}const r=()=>{const u=n();if(u==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":e.VERSION,"X-Stainless-OS":i(Deno.build.os),"X-Stainless-Arch":o(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":e.VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(u==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":e.VERSION,"X-Stainless-OS":i(globalThis.process.platform??"unknown"),"X-Stainless-Arch":o(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const c=s();return c?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":e.VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${c.browser}`,"X-Stainless-Runtime-Version":c.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":e.VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function s(){if(typeof navigator>"u"||!navigator)return null;const u=[{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:c,pattern:d}of u){const p=d.exec(navigator.userAgent);if(p){const g=p[1]||0,y=p[2]||0,_=p[3]||0;return{browser:c,version:`${g}.${y}.${_}`}}}return null}const o=u=>u==="x32"?"x32":u==="x86_64"||u==="x64"?"x64":u==="arm"?"arm":u==="aarch64"||u==="arm64"?"arm64":u?`other:${u}`:"unknown",i=u=>(u=u.toLowerCase(),u.includes("ios")?"iOS":u==="android"?"Android":u==="darwin"?"MacOS":u==="win32"?"Windows":u==="freebsd"?"FreeBSD":u==="openbsd"?"OpenBSD":u==="linux"?"Linux":u?`Other:${u}`:"Unknown");let a;const l=()=>a??(a=r());return Yn.getPlatformHeaders=l,Yn}var In={},e_;function Ei(){if(e_)return In;e_=1,Object.defineProperty(In,"__esModule",{value:!0}),In.getDefaultFetch=e,In.makeReadableStream=t,In.ReadableStreamFrom=n,In.ReadableStreamToAsyncIterable=r,In.CancelReadableStream=s;function e(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function t(...o){const i=globalThis.ReadableStream;if(typeof i>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new i(...o)}function n(o){let i=Symbol.asyncIterator in o?o[Symbol.asyncIterator]():o[Symbol.iterator]();return t({start(){},async pull(a){const{done:l,value:u}=await i.next();l?a.close():a.enqueue(u)},async cancel(){await i.return?.()}})}function r(o){if(o[Symbol.asyncIterator])return o;const i=o.getReader();return{async next(){try{const a=await i.read();return a?.done&&i.releaseLock(),a}catch(a){throw i.releaseLock(),a}},async return(){const a=i.cancel();return i.releaseLock(),await a,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function s(o){if(o===null||typeof o!="object")return;if(o[Symbol.asyncIterator]){await o[Symbol.asyncIterator]().return?.();return}const i=o.getReader(),a=i.cancel();i.releaseLock(),await a}return In}var Mo={},t_;function GP(){if(t_)return Mo;t_=1,Object.defineProperty(Mo,"__esModule",{value:!0}),Mo.FallbackEncoder=void 0;const e=({headers:t,body:n})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(n)});return Mo.FallbackEncoder=e,Mo}var ft={},No={},Ar={},Sr={},wr={},n_;function e0(){if(n_)return wr;n_=1,Object.defineProperty(wr,"__esModule",{value:!0}),wr.concatBytes=e,wr.encodeUTF8=n,wr.decodeUTF8=s;function e(o){let i=0;for(const u of o)i+=u.length;const a=new Uint8Array(i);let l=0;for(const u of o)a.set(u,l),l+=u.length;return a}let t;function n(o){let i;return(t??(i=new globalThis.TextEncoder,t=i.encode.bind(i)))(o)}let r;function s(o){let i;return(r??(i=new globalThis.TextDecoder,r=i.decode.bind(i)))(o)}return wr}var r_;function t0(){if(r_)return Sr;r_=1;var e,t;Object.defineProperty(Sr,"__esModule",{value:!0}),Sr.LineDecoder=void 0,Sr.findDoubleNewlineIndex=i;const n=at(),r=e0();class s{constructor(){e.set(this,void 0),t.set(this,void 0),n.__classPrivateFieldSet(this,e,new Uint8Array,"f"),n.__classPrivateFieldSet(this,t,null,"f")}decode(l){if(l==null)return[];const u=l instanceof ArrayBuffer?new Uint8Array(l):typeof l=="string"?(0,r.encodeUTF8)(l):l;n.__classPrivateFieldSet(this,e,(0,r.concatBytes)([n.__classPrivateFieldGet(this,e,"f"),u]),"f");const c=[];let d;for(;(d=o(n.__classPrivateFieldGet(this,e,"f"),n.__classPrivateFieldGet(this,t,"f")))!=null;){if(d.carriage&&n.__classPrivateFieldGet(this,t,"f")==null){n.__classPrivateFieldSet(this,t,d.index,"f");continue}if(n.__classPrivateFieldGet(this,t,"f")!=null&&(d.index!==n.__classPrivateFieldGet(this,t,"f")+1||d.carriage)){c.push((0,r.decodeUTF8)(n.__classPrivateFieldGet(this,e,"f").subarray(0,n.__classPrivateFieldGet(this,t,"f")-1))),n.__classPrivateFieldSet(this,e,n.__classPrivateFieldGet(this,e,"f").subarray(n.__classPrivateFieldGet(this,t,"f")),"f"),n.__classPrivateFieldSet(this,t,null,"f");continue}const p=n.__classPrivateFieldGet(this,t,"f")!==null?d.preceding-1:d.preceding,g=(0,r.decodeUTF8)(n.__classPrivateFieldGet(this,e,"f").subarray(0,p));c.push(g),n.__classPrivateFieldSet(this,e,n.__classPrivateFieldGet(this,e,"f").subarray(d.index),"f"),n.__classPrivateFieldSet(this,t,null,"f")}return c}flush(){return n.__classPrivateFieldGet(this,e,"f").length?this.decode(`
36
- `):[]}}Sr.LineDecoder=s,e=new WeakMap,t=new WeakMap,s.NEWLINE_CHARS=new Set([`
37
- `,"\r"]),s.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function o(a,l){for(let d=l??0;d<a.length;d++){if(a[d]===10)return{preceding:d,index:d+1,carriage:!1};if(a[d]===13)return{preceding:d,index:d+1,carriage:!0}}return null}function i(a){for(let c=0;c<a.length-1;c++){if(a[c]===10&&a[c+1]===10||a[c]===13&&a[c+1]===13)return c+2;if(a[c]===13&&a[c+1]===10&&c+3<a.length&&a[c+2]===13&&a[c+3]===10)return c+4}return-1}return Sr}var Cn={},s_;function Yd(){if(s_)return Cn;s_=1,Object.defineProperty(Cn,"__esModule",{value:!0}),Cn.formatRequestDetails=Cn.parseLogLevel=void 0,Cn.loggerFor=a;const e=Vr(),t={off:0,error:200,warn:300,info:400,debug:500},n=(u,c,d)=>{if(u){if((0,e.hasOwn)(t,u))return u;a(d).warn(`${c} was set to ${JSON.stringify(u)}, expected one of ${JSON.stringify(Object.keys(t))}`)}};Cn.parseLogLevel=n;function r(){}function s(u,c,d){return!c||t[u]>t[d]?r:c[u].bind(c)}const o={error:r,warn:r,info:r,debug:r};let i=new WeakMap;function a(u){const c=u.logger,d=u.logLevel??"off";if(!c)return o;const p=i.get(c);if(p&&p[0]===d)return p[1];const g={error:s("error",c,d),warn:s("warn",c,d),info:s("info",c,d),debug:s("debug",c,d)};return i.set(c,[d,g]),g}const l=u=>(u.options&&(u.options={...u.options},delete u.options.headers),u.headers&&(u.headers=Object.fromEntries((u.headers instanceof Headers?[...u.headers]:Object.entries(u.headers)).map(([c,d])=>[c,c.toLowerCase()==="x-api-key"||c.toLowerCase()==="authorization"||c.toLowerCase()==="cookie"||c.toLowerCase()==="set-cookie"?"***":d]))),"retryOfRequestLogID"in u&&(u.retryOfRequestLogID&&(u.retryOf=u.retryOfRequestLogID),delete u.retryOfRequestLogID),u);return Cn.formatRequestDetails=l,Cn}var o_;function n0(){if(o_)return Ar;o_=1;var e;Object.defineProperty(Ar,"__esModule",{value:!0}),Ar.Stream=void 0,Ar._iterSSEMessages=p;const t=at(),n=Dt(),r=Ei(),s=t0(),o=Ei(),i=qi(),a=Vr(),l=e0(),u=Yd(),c=Dt();class d{constructor(m,v,A){this.iterator=m,e.set(this,void 0),this.controller=v,t.__classPrivateFieldSet(this,e,A,"f")}static fromSSEResponse(m,v,A){let S=!1;const P=A?(0,u.loggerFor)(A):console;async function*E(){if(S)throw new n.AnthropicError("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");S=!0;let w=!1;try{for await(const I of p(m,v)){if(I.event==="completion")try{yield JSON.parse(I.data)}catch(L){throw P.error("Could not parse message into JSON:",I.data),P.error("From chunk:",I.raw),L}if(I.event==="message_start"||I.event==="message_delta"||I.event==="message_stop"||I.event==="content_block_start"||I.event==="content_block_delta"||I.event==="content_block_stop")try{yield JSON.parse(I.data)}catch(L){throw P.error("Could not parse message into JSON:",I.data),P.error("From chunk:",I.raw),L}if(I.event!=="ping"&&I.event==="error")throw new c.APIError(void 0,(0,a.safeJSON)(I.data)??I.data,void 0,m.headers)}w=!0}catch(I){if((0,i.isAbortError)(I))return;throw I}finally{w||v.abort()}}return new d(E,v,A)}static fromReadableStream(m,v,A){let S=!1;async function*P(){const w=new s.LineDecoder,I=(0,o.ReadableStreamToAsyncIterable)(m);for await(const L of I)for(const H of w.decode(L))yield H;for(const L of w.flush())yield L}async function*E(){if(S)throw new n.AnthropicError("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");S=!0;let w=!1;try{for await(const I of P())w||I&&(yield JSON.parse(I));w=!0}catch(I){if((0,i.isAbortError)(I))return;throw I}finally{w||v.abort()}}return new d(E,v,A)}[(e=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const m=[],v=[],A=this.iterator(),S=P=>({next:()=>{if(P.length===0){const E=A.next();m.push(E),v.push(E)}return P.shift()}});return[new d(()=>S(m),this.controller,t.__classPrivateFieldGet(this,e,"f")),new d(()=>S(v),this.controller,t.__classPrivateFieldGet(this,e,"f"))]}toReadableStream(){const m=this;let v;return(0,r.makeReadableStream)({async start(){v=m[Symbol.asyncIterator]()},async pull(A){try{const{value:S,done:P}=await v.next();if(P)return A.close();const E=(0,l.encodeUTF8)(JSON.stringify(S)+`
38
- `);A.enqueue(E)}catch(S){A.error(S)}},async cancel(){await v.return?.()}})}}Ar.Stream=d;async function*p(b,m){if(!b.body)throw m.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new n.AnthropicError("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new n.AnthropicError("Attempted to iterate over a response with no body");const v=new y,A=new s.LineDecoder,S=(0,o.ReadableStreamToAsyncIterable)(b.body);for await(const P of g(S))for(const E of A.decode(P)){const w=v.decode(E);w&&(yield w)}for(const P of A.flush()){const E=v.decode(P);E&&(yield E)}}async function*g(b){let m=new Uint8Array;for await(const v of b){if(v==null)continue;const A=v instanceof ArrayBuffer?new Uint8Array(v):typeof v=="string"?(0,l.encodeUTF8)(v):v;let S=new Uint8Array(m.length+A.length);S.set(m),S.set(A,m.length),m=S;let P;for(;(P=(0,s.findDoubleNewlineIndex)(m))!==-1;)yield m.slice(0,P),m=m.slice(P)}m.length>0&&(yield m)}class y{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(m){if(m.endsWith("\r")&&(m=m.substring(0,m.length-1)),!m){if(!this.event&&!this.data.length)return null;const P={event:this.event,data:this.data.join(`
39
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],P}if(this.chunks.push(m),m.startsWith(":"))return null;let[v,A,S]=_(m,":");return S.startsWith(" ")&&(S=S.substring(1)),v==="event"?this.event=S:v==="data"&&this.data.push(S),null}}function _(b,m){const v=b.indexOf(m);return v!==-1?[b.substring(0,v),m,b.substring(v+m.length)]:[b,"",""]}return Ar}var i_;function r0(){if(i_)return No;i_=1,Object.defineProperty(No,"__esModule",{value:!0}),No.defaultParseResponse=n,No.addRequestID=r;const e=n0(),t=Yd();async function n(s,o){const{response:i,requestLogID:a,retryOfRequestLogID:l,startTime:u}=o,c=await(async()=>{if(o.options.stream)return(0,t.loggerFor)(s).debug("response",i.status,i.url,i.headers,i.body),o.options.__streamClass?o.options.__streamClass.fromSSEResponse(i,o.controller):e.Stream.fromSSEResponse(i,o.controller);if(i.status===204)return null;if(o.options.__binaryResponse)return i;const p=i.headers.get("content-type")?.split(";")[0]?.trim();if(p?.includes("application/json")||p?.endsWith("+json")){const _=await i.json();return r(_,i)}return await i.text()})();return(0,t.loggerFor)(s).debug(`[${a}] response parsed`,(0,t.formatRequestDetails)({retryOfRequestLogID:l,url:i.url,status:i.status,body:c,durationMs:Date.now()-u})),c}function r(s,o){return!s||typeof s!="object"||Array.isArray(s)?s:Object.defineProperty(s,"_request_id",{value:o.headers.get("request-id"),enumerable:!1})}return No}var Fo={},a_;function zd(){if(a_)return Fo;a_=1;var e;Object.defineProperty(Fo,"__esModule",{value:!0}),Fo.APIPromise=void 0;const t=at(),n=r0();class r extends Promise{constructor(o,i,a=n.defaultParseResponse){super(l=>{l(null)}),this.responsePromise=i,this.parseResponse=a,e.set(this,void 0),t.__classPrivateFieldSet(this,e,o,"f")}_thenUnwrap(o){return new r(t.__classPrivateFieldGet(this,e,"f"),this.responsePromise,async(i,a)=>(0,n.addRequestID)(o(await this.parseResponse(i,a),a),a.response))}asResponse(){return this.responsePromise.then(o=>o.response)}async withResponse(){const[o,i]=await Promise.all([this.parse(),this.asResponse()]);return{data:o,response:i,request_id:i.headers.get("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(o=>this.parseResponse(t.__classPrivateFieldGet(this,e,"f"),o))),this.parsedPromise}then(o,i){return this.parse().then(o,i)}catch(o){return this.parse().catch(o)}finally(o){return this.parse().finally(o)}}return Fo.APIPromise=r,e=new WeakMap,Fo}var l_;function An(){if(l_)return ft;l_=1;var e;Object.defineProperty(ft,"__esModule",{value:!0}),ft.PageCursor=ft.TokenPage=ft.Page=ft.PagePromise=ft.AbstractPage=void 0;const t=at(),n=Dt(),r=r0(),s=zd(),o=Vr();class i{constructor(p,g,y,_){e.set(this,void 0),t.__classPrivateFieldSet(this,e,p,"f"),this.options=_,this.response=g,this.body=y}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const p=this.nextPageRequestOptions();if(!p)throw new n.AnthropicError("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await t.__classPrivateFieldGet(this,e,"f").requestAPIList(this.constructor,p)}async*iterPages(){let p=this;for(yield p;p.hasNextPage();)p=await p.getNextPage(),yield p}async*[(e=new WeakMap,Symbol.asyncIterator)](){for await(const p of this.iterPages())for(const g of p.getPaginatedItems())yield g}}ft.AbstractPage=i;class a extends s.APIPromise{constructor(p,g,y){super(p,g,async(_,b)=>new y(_,b.response,await(0,r.defaultParseResponse)(_,b),b.options))}async*[Symbol.asyncIterator](){const p=await this;for await(const g of p)yield g}}ft.PagePromise=a;class l extends i{constructor(p,g,y,_){super(p,g,y,_),this.data=y.data||[],this.has_more=y.has_more||!1,this.first_id=y.first_id||null,this.last_id=y.last_id||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){if(this.options.query?.before_id){const g=this.first_id;return g?{...this.options,query:{...(0,o.maybeObj)(this.options.query),before_id:g}}:null}const p=this.last_id;return p?{...this.options,query:{...(0,o.maybeObj)(this.options.query),after_id:p}}:null}}ft.Page=l;class u extends i{constructor(p,g,y,_){super(p,g,y,_),this.data=y.data||[],this.has_more=y.has_more||!1,this.next_page=y.next_page||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){const p=this.next_page;return p?{...this.options,query:{...(0,o.maybeObj)(this.options.query),page_token:p}}:null}}ft.TokenPage=u;class c extends i{constructor(p,g,y,_){super(p,g,y,_),this.data=y.data||[],this.has_more=y.has_more||!1,this.next_page=y.next_page||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){const p=this.next_page;return p?{...this.options,query:{...(0,o.maybeObj)(this.options.query),page:p}}:null}}return ft.PageCursor=c,ft}var bu={},$i={},Au={},u_;function Ti(){return u_||(u_=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.createForm=e.multipartFormRequestOptions=e.maybeMultipartFormRequestOptions=e.isAsyncIterable=e.checkFileSupport=void 0,e.makeFile=r,e.getName=s;const t=Ei(),n=()=>{if(typeof File>"u"){const{process:_}=globalThis,b=typeof _?.versions?.node=="string"&&parseInt(_.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(b?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};e.checkFileSupport=n;function r(_,b,m){return(0,e.checkFileSupport)(),new File(_,b??"unknown_file",m)}function s(_){return(typeof _=="object"&&_!==null&&("name"in _&&_.name&&String(_.name)||"url"in _&&_.url&&String(_.url)||"filename"in _&&_.filename&&String(_.filename)||"path"in _&&_.path&&String(_.path))||"").split(/[\\/]/).pop()||void 0}const o=_=>_!=null&&typeof _=="object"&&typeof _[Symbol.asyncIterator]=="function";e.isAsyncIterable=o;const i=async(_,b)=>g(_.body)?{..._,body:await(0,e.createForm)(_.body,b)}:_;e.maybeMultipartFormRequestOptions=i;const a=async(_,b)=>({..._,body:await(0,e.createForm)(_.body,b)});e.multipartFormRequestOptions=a;const l=new WeakMap;function u(_){const b=typeof _=="function"?_:_.fetch,m=l.get(b);if(m)return m;const v=(async()=>{try{const A="Response"in b?b.Response:(await b("data:,")).constructor,S=new FormData;return S.toString()!==await new A(S).text()}catch{return!0}})();return l.set(b,v),v}const c=async(_,b)=>{if(!await u(b))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const m=new FormData;return await Promise.all(Object.entries(_||{}).map(([v,A])=>y(m,v,A))),m};e.createForm=c;const d=_=>_ instanceof Blob&&"name"in _,p=_=>typeof _=="object"&&_!==null&&(_ instanceof Response||(0,e.isAsyncIterable)(_)||d(_)),g=_=>{if(p(_))return!0;if(Array.isArray(_))return _.some(g);if(_&&typeof _=="object"){for(const b in _)if(g(_[b]))return!0}return!1},y=async(_,b,m)=>{if(m!==void 0){if(m==null)throw new TypeError(`Received null for "${b}"; to pass null in FormData, you must use the string 'null'`);if(typeof m=="string"||typeof m=="number"||typeof m=="boolean")_.append(b,String(m));else if(m instanceof Response){let v={};const A=m.headers.get("Content-Type");A&&(v={type:A}),_.append(b,r([await m.blob()],s(m),v))}else if((0,e.isAsyncIterable)(m))_.append(b,r([await new Response((0,t.ReadableStreamFrom)(m)).blob()],s(m)));else if(d(m))_.append(b,r([m],s(m),{type:m.type}));else if(Array.isArray(m))await Promise.all(m.map(v=>y(_,b+"[]",v)));else if(typeof m=="object")await Promise.all(Object.entries(m).map(([v,A])=>y(_,`${b}[${v}]`,A)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${m} instead`)}}})(Au)),Au}var c_;function VP(){if(c_)return $i;c_=1,Object.defineProperty($i,"__esModule",{value:!0}),$i.toFile=o;const e=Ti(),t=Ti(),n=l=>l!=null&&typeof l=="object"&&typeof l.size=="number"&&typeof l.type=="string"&&typeof l.text=="function"&&typeof l.slice=="function"&&typeof l.arrayBuffer=="function",r=l=>l!=null&&typeof l=="object"&&typeof l.name=="string"&&typeof l.lastModified=="number"&&n(l),s=l=>l!=null&&typeof l=="object"&&typeof l.url=="string"&&typeof l.blob=="function";async function o(l,u,c){if((0,t.checkFileSupport)(),l=await l,u||(u=(0,e.getName)(l)),r(l))return l instanceof File&&u==null&&c==null?l:(0,e.makeFile)([await l.arrayBuffer()],u??l.name,{type:l.type,lastModified:l.lastModified,...c});if(s(l)){const p=await l.blob();return u||(u=new URL(l.url).pathname.split(/[\\/]/).pop()),(0,e.makeFile)(await i(p),u,c)}const d=await i(l);if(!c?.type){const p=d.find(g=>typeof g=="object"&&"type"in g&&g.type);typeof p=="string"&&(c={...c,type:p})}return(0,e.makeFile)(d,u,c)}async function i(l){let u=[];if(typeof l=="string"||ArrayBuffer.isView(l)||l instanceof ArrayBuffer)u.push(l);else if(n(l))u.push(l instanceof Blob?l:await l.arrayBuffer());else if((0,e.isAsyncIterable)(l))for await(const c of l)u.push(...await i(c));else{const c=l?.constructor?.name;throw new Error(`Unexpected data type: ${typeof l}${c?`; constructor: ${c}`:""}${a(l)}`)}return u}function a(l){return typeof l!="object"||l===null?"":`; props: [${Object.getOwnPropertyNames(l).map(c=>`"${c}"`).join(", ")}]`}return $i}var d_;function s0(){return d_||(d_=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.toFile=void 0;var t=VP();Object.defineProperty(e,"toFile",{enumerable:!0,get:function(){return t.toFile}})})(bu)),bu}var Su={},wu={},f_;function BP(){return f_||(f_=1,Object.defineProperty(wu,"__esModule",{value:!0})),wu}var ko={},Oo={},p_;function qt(){if(p_)return Oo;p_=1,Object.defineProperty(Oo,"__esModule",{value:!0}),Oo.APIResource=void 0;class e{constructor(n){this._client=n}}return Oo.APIResource=e,Oo}var xo={},zn={},h_;function Lt(){if(h_)return zn;h_=1,Object.defineProperty(zn,"__esModule",{value:!0}),zn.isEmptyHeaders=zn.buildHeaders=void 0;const e=Vr(),t=Symbol.for("brand.privateNullableHeaders");function*n(o){if(!o)return;if(t in o){const{values:l,nulls:u}=o;yield*l.entries();for(const c of u)yield[c,null];return}let i=!1,a;o instanceof Headers?a=o.entries():(0,e.isReadonlyArray)(o)?a=o:(i=!0,a=Object.entries(o??{}));for(let l of a){const u=l[0];if(typeof u!="string")throw new TypeError("expected header name to be a string");const c=(0,e.isReadonlyArray)(l[1])?l[1]:[l[1]];let d=!1;for(const p of c)p!==void 0&&(i&&!d&&(d=!0,yield[u,null]),yield[u,p])}}const r=o=>{const i=new Headers,a=new Set;for(const l of o){const u=new Set;for(const[c,d]of n(l)){const p=c.toLowerCase();u.has(p)||(i.delete(c),u.add(p)),d===null?(i.delete(c),a.add(p)):(i.append(c,d),a.delete(p))}}return{[t]:!0,values:i,nulls:a}};zn.buildHeaders=r;const s=o=>{for(const i of n(o))return!1;return!0};return zn.isEmptyHeaders=s,zn}var Eu={},g_;function dr(){return g_||(g_=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.path=e.createPathTagFunction=void 0,e.encodeURIPath=n;const t=Dt();function n(o){return o.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const r=Object.freeze(Object.create(null)),s=(o=n)=>function(a,...l){if(a.length===1)return a[0];let u=!1;const c=[],d=a.reduce((_,b,m)=>{/[?#]/.test(b)&&(u=!0);const v=l[m];let A=(u?encodeURIComponent:o)(""+v);return m!==l.length&&(v==null||typeof v=="object"&&v.toString===Object.getPrototypeOf(Object.getPrototypeOf(v.hasOwnProperty??r)??r)?.toString)&&(A=v+"",c.push({start:_.length+b.length,length:A.length,error:`Value of type ${Object.prototype.toString.call(v).slice(8,-1)} is not a valid path parameter`})),_+b+(m===l.length?"":A)},""),p=d.split(/[?#]/,1)[0],g=new RegExp("(?<=^|\\/)(?:\\.|%2e){1,2}(?=\\/|$)","gi");let y;for(;(y=g.exec(p))!==null;)c.push({start:y.index,length:y[0].length,error:`Value "${y[0]}" can't be safely passed as a path parameter`});if(c.sort((_,b)=>_.start-b.start),c.length>0){let _=0;const b=c.reduce((m,v)=>{const A=" ".repeat(v.start-_),S="^".repeat(v.length);return _=v.start+v.length,m+A+S},"");throw new t.AnthropicError(`Path parameters result in path with invalid segments:
40
- ${c.map(m=>m.error).join(`
41
- `)}
42
- ${d}
43
- ${b}`)}return d};e.createPathTagFunction=s,e.path=(0,e.createPathTagFunction)(n)})(Eu)),Eu}var m_;function __(){if(m_)return xo;m_=1,Object.defineProperty(xo,"__esModule",{value:!0}),xo.Files=void 0;const e=qt(),t=An(),n=Lt(),r=Ti(),s=dr();class o extends e.APIResource{list(a={},l){const{betas:u,...c}=a??{};return this._client.getAPIList("/v1/files",t.Page,{query:c,...l,headers:(0,n.buildHeaders)([{"anthropic-beta":[...u??[],"files-api-2025-04-14"].toString()},l?.headers])})}delete(a,l={},u){const{betas:c}=l??{};return this._client.delete((0,s.path)`/v1/files/${a}`,{...u,headers:(0,n.buildHeaders)([{"anthropic-beta":[...c??[],"files-api-2025-04-14"].toString()},u?.headers])})}download(a,l={},u){const{betas:c}=l??{};return this._client.get((0,s.path)`/v1/files/${a}/content`,{...u,headers:(0,n.buildHeaders)([{"anthropic-beta":[...c??[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},u?.headers]),__binaryResponse:!0})}retrieveMetadata(a,l={},u){const{betas:c}=l??{};return this._client.get((0,s.path)`/v1/files/${a}`,{...u,headers:(0,n.buildHeaders)([{"anthropic-beta":[...c??[],"files-api-2025-04-14"].toString()},u?.headers])})}upload(a,l){const{betas:u,...c}=a;return this._client.post("/v1/files",(0,r.multipartFormRequestOptions)({body:c,...l,headers:(0,n.buildHeaders)([{"anthropic-beta":[...u??[],"files-api-2025-04-14"].toString()},l?.headers])},this._client))}}return xo.Files=o,xo}var Do={},y_;function v_(){if(y_)return Do;y_=1,Object.defineProperty(Do,"__esModule",{value:!0}),Do.Models=void 0;const e=qt(),t=An(),n=Lt(),r=dr();class s extends e.APIResource{retrieve(i,a={},l){const{betas:u}=a??{};return this._client.get((0,r.path)`/v1/models/${i}?beta=true`,{...l,headers:(0,n.buildHeaders)([{...u?.toString()!=null?{"anthropic-beta":u?.toString()}:void 0},l?.headers])})}list(i={},a){const{betas:l,...u}=i??{};return this._client.getAPIList("/v1/models?beta=true",t.Page,{query:u,...a,headers:(0,n.buildHeaders)([{...l?.toString()!=null?{"anthropic-beta":l?.toString()}:void 0},a?.headers])})}}return Do.Models=s,Do}var Tu={},qo={},b_;function o0(){return b_||(b_=1,Object.defineProperty(qo,"__esModule",{value:!0}),qo.MODEL_NONSTREAMING_TOKENS=void 0,qo.MODEL_NONSTREAMING_TOKENS={"claude-opus-4-20250514":8192,"claude-opus-4-0":8192,"claude-4-opus-20250514":8192,"anthropic.claude-opus-4-20250514-v1:0":8192,"claude-opus-4@20250514":8192,"claude-opus-4-1-20250805":8192,"anthropic.claude-opus-4-1-20250805-v1:0":8192,"claude-opus-4-1@20250805":8192}),qo}var Lo={},A_;function i0(){if(A_)return Lo;A_=1,Object.defineProperty(Lo,"__esModule",{value:!0}),Lo.maybeParseBetaMessage=t,Lo.parseBetaMessage=n;const e=Dt();function t(s,o,i){return!o||!("parse"in(o.output_format??{}))?{...s,content:s.content.map(a=>{if(a.type==="text"){const l=Object.defineProperty({...a},"parsed_output",{value:null,enumerable:!1});return Object.defineProperty(l,"parsed",{get(){return i.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),null},enumerable:!1})}return a}),parsed_output:null}:n(s,o,i)}function n(s,o,i){let a=null;const l=s.content.map(u=>{if(u.type==="text"){const c=r(o,u.text);a===null&&(a=c);const d=Object.defineProperty({...u},"parsed_output",{value:c,enumerable:!1});return Object.defineProperty(d,"parsed",{get(){return i.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."),c},enumerable:!1})}return u});return{...s,content:l,parsed_output:a}}function r(s,o){if(s.output_format?.type!=="json_schema")return null;try{return"parse"in s.output_format?s.output_format.parse(o):JSON.parse(o)}catch(i){throw new e.AnthropicError(`Failed to parse structured output: ${i}`)}}return Lo}var Uo={},Go={},S_;function a0(){if(S_)return Go;S_=1,Object.defineProperty(Go,"__esModule",{value:!0}),Go.partialParse=void 0;const e=o=>{let i=0,a=[];for(;i<o.length;){let l=o[i];if(l==="\\"){i++;continue}if(l==="{"){a.push({type:"brace",value:"{"}),i++;continue}if(l==="}"){a.push({type:"brace",value:"}"}),i++;continue}if(l==="["){a.push({type:"paren",value:"["}),i++;continue}if(l==="]"){a.push({type:"paren",value:"]"}),i++;continue}if(l===":"){a.push({type:"separator",value:":"}),i++;continue}if(l===","){a.push({type:"delimiter",value:","}),i++;continue}if(l==='"'){let p="",g=!1;for(l=o[++i];l!=='"';){if(i===o.length){g=!0;break}if(l==="\\"){if(i++,i===o.length){g=!0;break}p+=l+o[i],l=o[++i]}else p+=l,l=o[++i]}l=o[++i],g||a.push({type:"string",value:p});continue}if(l&&/\s/.test(l)){i++;continue}let c=/[0-9]/;if(l&&c.test(l)||l==="-"||l==="."){let p="";for(l==="-"&&(p+=l,l=o[++i]);l&&c.test(l)||l===".";)p+=l,l=o[++i];a.push({type:"number",value:p});continue}let d=/[a-z]/i;if(l&&d.test(l)){let p="";for(;l&&d.test(l)&&i!==o.length;)p+=l,l=o[++i];if(p=="true"||p=="false"||p==="null")a.push({type:"name",value:p});else{i++;continue}continue}i++}return a},t=o=>{if(o.length===0)return o;let i=o[o.length-1];switch(i.type){case"separator":return o=o.slice(0,o.length-1),t(o);case"number":let a=i.value[i.value.length-1];if(a==="."||a==="-")return o=o.slice(0,o.length-1),t(o);case"string":let l=o[o.length-2];if(l?.type==="delimiter")return o=o.slice(0,o.length-1),t(o);if(l?.type==="brace"&&l.value==="{")return o=o.slice(0,o.length-1),t(o);break;case"delimiter":return o=o.slice(0,o.length-1),t(o)}return o},n=o=>{let i=[];return o.map(a=>{a.type==="brace"&&(a.value==="{"?i.push("}"):i.splice(i.lastIndexOf("}"),1)),a.type==="paren"&&(a.value==="["?i.push("]"):i.splice(i.lastIndexOf("]"),1))}),i.length>0&&i.reverse().map(a=>{a==="}"?o.push({type:"brace",value:"}"}):a==="]"&&o.push({type:"paren",value:"]"})}),o},r=o=>{let i="";return o.map(a=>{a.type==="string"?i+='"'+a.value+'"':i+=a.value}),i},s=o=>JSON.parse(r(n(t(e(o)))));return Go.partialParse=s,Go}var Pu={},w_;function Ya(){return w_||(w_=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),at().__exportStar(Dt(),e)})(Pu)),Pu}var Iu={},E_;function l0(){return E_||(E_=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),at().__exportStar(n0(),e)})(Iu)),Iu}var T_;function HP(){if(T_)return Uo;T_=1;var e,t,n,r,s,o,i,a,l,u,c,d,p,g,y,_,b,m,v,A,S,P,E,w;Object.defineProperty(Uo,"__esModule",{value:!0}),Uo.BetaMessageStream=void 0;const I=at(),L=a0(),H=Ya(),B=qi(),F=l0(),j=i0(),U="__json_buf";function O(M){return M.type==="tool_use"||M.type==="server_tool_use"||M.type==="mcp_tool_use"}let R=class ec{constructor(k,G){e.add(this),this.messages=[],this.receivedMessages=[],t.set(this,void 0),n.set(this,null),this.controller=new AbortController,r.set(this,void 0),s.set(this,()=>{}),o.set(this,()=>{}),i.set(this,void 0),a.set(this,()=>{}),l.set(this,()=>{}),u.set(this,{}),c.set(this,!1),d.set(this,!1),p.set(this,!1),g.set(this,!1),y.set(this,void 0),_.set(this,void 0),b.set(this,void 0),A.set(this,V=>{if(I.__classPrivateFieldSet(this,d,!0,"f"),(0,B.isAbortError)(V)&&(V=new H.APIUserAbortError),V instanceof H.APIUserAbortError)return I.__classPrivateFieldSet(this,p,!0,"f"),this._emit("abort",V);if(V instanceof H.AnthropicError)return this._emit("error",V);if(V instanceof Error){const W=new H.AnthropicError(V.message);return W.cause=V,this._emit("error",W)}return this._emit("error",new H.AnthropicError(String(V)))}),I.__classPrivateFieldSet(this,r,new Promise((V,W)=>{I.__classPrivateFieldSet(this,s,V,"f"),I.__classPrivateFieldSet(this,o,W,"f")}),"f"),I.__classPrivateFieldSet(this,i,new Promise((V,W)=>{I.__classPrivateFieldSet(this,a,V,"f"),I.__classPrivateFieldSet(this,l,W,"f")}),"f"),I.__classPrivateFieldGet(this,r,"f").catch(()=>{}),I.__classPrivateFieldGet(this,i,"f").catch(()=>{}),I.__classPrivateFieldSet(this,n,k,"f"),I.__classPrivateFieldSet(this,b,G?.logger??console,"f")}get response(){return I.__classPrivateFieldGet(this,y,"f")}get request_id(){return I.__classPrivateFieldGet(this,_,"f")}async withResponse(){I.__classPrivateFieldSet(this,g,!0,"f");const k=await I.__classPrivateFieldGet(this,r,"f");if(!k)throw new Error("Could not resolve a `Response` object");return{data:this,response:k,request_id:k.headers.get("request-id")}}static fromReadableStream(k){const G=new ec(null);return G._run(()=>G._fromReadableStream(k)),G}static createMessage(k,G,V,{logger:W}={}){const X=new ec(G,{logger:W});for(const Y of G.messages)X._addMessageParam(Y);return I.__classPrivateFieldSet(X,n,{...G,stream:!0},"f"),X._run(()=>X._createMessage(k,{...G,stream:!0},{...V,headers:{...V?.headers,"X-Stainless-Helper-Method":"stream"}})),X}_run(k){k().then(()=>{this._emitFinal(),this._emit("end")},I.__classPrivateFieldGet(this,A,"f"))}_addMessageParam(k){this.messages.push(k)}_addMessage(k,G=!0){this.receivedMessages.push(k),G&&this._emit("message",k)}async _createMessage(k,G,V){const W=V?.signal;let X;W&&(W.aborted&&this.controller.abort(),X=this.controller.abort.bind(this.controller),W.addEventListener("abort",X));try{I.__classPrivateFieldGet(this,e,"m",S).call(this);const{response:Y,data:Z}=await k.create({...G,stream:!0},{...V,signal:this.controller.signal}).withResponse();this._connected(Y);for await(const ne of Z)I.__classPrivateFieldGet(this,e,"m",P).call(this,ne);if(Z.controller.signal?.aborted)throw new H.APIUserAbortError;I.__classPrivateFieldGet(this,e,"m",E).call(this)}finally{W&&X&&W.removeEventListener("abort",X)}}_connected(k){this.ended||(I.__classPrivateFieldSet(this,y,k,"f"),I.__classPrivateFieldSet(this,_,k?.headers.get("request-id"),"f"),I.__classPrivateFieldGet(this,s,"f").call(this,k),this._emit("connect"))}get ended(){return I.__classPrivateFieldGet(this,c,"f")}get errored(){return I.__classPrivateFieldGet(this,d,"f")}get aborted(){return I.__classPrivateFieldGet(this,p,"f")}abort(){this.controller.abort()}on(k,G){return(I.__classPrivateFieldGet(this,u,"f")[k]||(I.__classPrivateFieldGet(this,u,"f")[k]=[])).push({listener:G}),this}off(k,G){const V=I.__classPrivateFieldGet(this,u,"f")[k];if(!V)return this;const W=V.findIndex(X=>X.listener===G);return W>=0&&V.splice(W,1),this}once(k,G){return(I.__classPrivateFieldGet(this,u,"f")[k]||(I.__classPrivateFieldGet(this,u,"f")[k]=[])).push({listener:G,once:!0}),this}emitted(k){return new Promise((G,V)=>{I.__classPrivateFieldSet(this,g,!0,"f"),k!=="error"&&this.once("error",V),this.once(k,G)})}async done(){I.__classPrivateFieldSet(this,g,!0,"f"),await I.__classPrivateFieldGet(this,i,"f")}get currentMessage(){return I.__classPrivateFieldGet(this,t,"f")}async finalMessage(){return await this.done(),I.__classPrivateFieldGet(this,e,"m",m).call(this)}async finalText(){return await this.done(),I.__classPrivateFieldGet(this,e,"m",v).call(this)}_emit(k,...G){if(I.__classPrivateFieldGet(this,c,"f"))return;k==="end"&&(I.__classPrivateFieldSet(this,c,!0,"f"),I.__classPrivateFieldGet(this,a,"f").call(this));const V=I.__classPrivateFieldGet(this,u,"f")[k];if(V&&(I.__classPrivateFieldGet(this,u,"f")[k]=V.filter(W=>!W.once),V.forEach(({listener:W})=>W(...G))),k==="abort"){const W=G[0];!I.__classPrivateFieldGet(this,g,"f")&&!V?.length&&Promise.reject(W),I.__classPrivateFieldGet(this,o,"f").call(this,W),I.__classPrivateFieldGet(this,l,"f").call(this,W),this._emit("end");return}if(k==="error"){const W=G[0];!I.__classPrivateFieldGet(this,g,"f")&&!V?.length&&Promise.reject(W),I.__classPrivateFieldGet(this,o,"f").call(this,W),I.__classPrivateFieldGet(this,l,"f").call(this,W),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",I.__classPrivateFieldGet(this,e,"m",m).call(this))}async _fromReadableStream(k,G){const V=G?.signal;let W;V&&(V.aborted&&this.controller.abort(),W=this.controller.abort.bind(this.controller),V.addEventListener("abort",W));try{I.__classPrivateFieldGet(this,e,"m",S).call(this),this._connected(null);const X=F.Stream.fromReadableStream(k,this.controller);for await(const Y of X)I.__classPrivateFieldGet(this,e,"m",P).call(this,Y);if(X.controller.signal?.aborted)throw new H.APIUserAbortError;I.__classPrivateFieldGet(this,e,"m",E).call(this)}finally{V&&W&&V.removeEventListener("abort",W)}}[(t=new WeakMap,n=new WeakMap,r=new WeakMap,s=new WeakMap,o=new WeakMap,i=new WeakMap,a=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,p=new WeakMap,g=new WeakMap,y=new WeakMap,_=new WeakMap,b=new WeakMap,A=new WeakMap,e=new WeakSet,m=function(){if(this.receivedMessages.length===0)throw new H.AnthropicError("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},v=function(){if(this.receivedMessages.length===0)throw new H.AnthropicError("stream ended without producing a Message with role=assistant");const G=this.receivedMessages.at(-1).content.filter(V=>V.type==="text").map(V=>V.text);if(G.length===0)throw new H.AnthropicError("stream ended without producing a content block with type=text");return G.join(" ")},S=function(){this.ended||I.__classPrivateFieldSet(this,t,void 0,"f")},P=function(G){if(this.ended)return;const V=I.__classPrivateFieldGet(this,e,"m",w).call(this,G);switch(this._emit("streamEvent",G,V),G.type){case"content_block_delta":{const W=V.content.at(-1);switch(G.delta.type){case"text_delta":{W.type==="text"&&this._emit("text",G.delta.text,W.text||"");break}case"citations_delta":{W.type==="text"&&this._emit("citation",G.delta.citation,W.citations??[]);break}case"input_json_delta":{O(W)&&W.input&&this._emit("inputJson",G.delta.partial_json,W.input);break}case"thinking_delta":{W.type==="thinking"&&this._emit("thinking",G.delta.thinking,W.thinking);break}case"signature_delta":{W.type==="thinking"&&this._emit("signature",W.signature);break}default:G.delta}break}case"message_stop":{this._addMessageParam(V),this._addMessage((0,j.maybeParseBetaMessage)(V,I.__classPrivateFieldGet(this,n,"f"),{logger:I.__classPrivateFieldGet(this,b,"f")}),!0);break}case"content_block_stop":{this._emit("contentBlock",V.content.at(-1));break}case"message_start":{I.__classPrivateFieldSet(this,t,V,"f");break}}},E=function(){if(this.ended)throw new H.AnthropicError("stream has ended, this shouldn't happen");const G=I.__classPrivateFieldGet(this,t,"f");if(!G)throw new H.AnthropicError("request ended without sending any chunks");return I.__classPrivateFieldSet(this,t,void 0,"f"),(0,j.maybeParseBetaMessage)(G,I.__classPrivateFieldGet(this,n,"f"),{logger:I.__classPrivateFieldGet(this,b,"f")})},w=function(G){let V=I.__classPrivateFieldGet(this,t,"f");if(G.type==="message_start"){if(V)throw new H.AnthropicError(`Unexpected event order, got ${G.type} before receiving "message_stop"`);return G.message}if(!V)throw new H.AnthropicError(`Unexpected event order, got ${G.type} before "message_start"`);switch(G.type){case"message_stop":return V;case"message_delta":return V.container=G.delta.container,V.stop_reason=G.delta.stop_reason,V.stop_sequence=G.delta.stop_sequence,V.usage.output_tokens=G.usage.output_tokens,V.context_management=G.context_management,G.usage.input_tokens!=null&&(V.usage.input_tokens=G.usage.input_tokens),G.usage.cache_creation_input_tokens!=null&&(V.usage.cache_creation_input_tokens=G.usage.cache_creation_input_tokens),G.usage.cache_read_input_tokens!=null&&(V.usage.cache_read_input_tokens=G.usage.cache_read_input_tokens),G.usage.server_tool_use!=null&&(V.usage.server_tool_use=G.usage.server_tool_use),V;case"content_block_start":return V.content.push(G.content_block),V;case"content_block_delta":{const W=V.content.at(G.index);switch(G.delta.type){case"text_delta":{W?.type==="text"&&(V.content[G.index]={...W,text:(W.text||"")+G.delta.text});break}case"citations_delta":{W?.type==="text"&&(V.content[G.index]={...W,citations:[...W.citations??[],G.delta.citation]});break}case"input_json_delta":{if(W&&O(W)){let X=W[U]||"";X+=G.delta.partial_json;const Y={...W};if(Object.defineProperty(Y,U,{value:X,enumerable:!1,writable:!0}),X)try{Y.input=(0,L.partialParse)(X)}catch(Z){const ne=new H.AnthropicError(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${Z}. JSON: ${X}`);I.__classPrivateFieldGet(this,A,"f").call(this,ne)}V.content[G.index]=Y}break}case"thinking_delta":{W?.type==="thinking"&&(V.content[G.index]={...W,thinking:W.thinking+G.delta.thinking});break}case"signature_delta":{W?.type==="thinking"&&(V.content[G.index]={...W,signature:G.delta.signature});break}default:G.delta}return V}case"content_block_stop":return V}},Symbol.asyncIterator)](){const k=[],G=[];let V=!1;return this.on("streamEvent",W=>{const X=G.shift();X?X.resolve(W):k.push(W)}),this.on("end",()=>{V=!0;for(const W of G)W.resolve(void 0);G.length=0}),this.on("abort",W=>{V=!0;for(const X of G)X.reject(W);G.length=0}),this.on("error",W=>{V=!0;for(const X of G)X.reject(W);G.length=0}),{next:async()=>k.length?{value:k.shift(),done:!1}:V?{value:void 0,done:!0}:new Promise((X,Y)=>G.push({resolve:X,reject:Y})).then(X=>X?{value:X,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new F.Stream(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};Uo.BetaMessageStream=R;function T(M){}return Uo}var Vo={},Xn={},P_;function JP(){return P_||(P_=1,Object.defineProperty(Xn,"__esModule",{value:!0}),Xn.DEFAULT_SUMMARY_PROMPT=Xn.DEFAULT_TOKEN_THRESHOLD=void 0,Xn.DEFAULT_TOKEN_THRESHOLD=1e5,Xn.DEFAULT_SUMMARY_PROMPT=`You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:
44
- 1. Task Overview
45
- The user's core request and success criteria
46
- Any clarifications or constraints they specified
47
- 2. Current State
48
- What has been completed so far
49
- Files created, modified, or analyzed (with paths if relevant)
50
- Key outputs or artifacts produced
51
- 3. Important Discoveries
52
- Technical constraints or requirements uncovered
53
- Decisions made and their rationale
54
- Errors encountered and how they were resolved
55
- What approaches were tried that didn't work (and why)
56
- 4. Next Steps
57
- Specific actions needed to complete the task
58
- Any blockers or open questions to resolve
59
- Priority order if multiple steps remain
60
- 5. Context to Preserve
61
- User preferences or style requirements
62
- Domain-specific details that aren't obvious
63
- Any promises made to the user
64
- Be concise but complete—err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task.
65
- Wrap your summary in <summary></summary> tags.`),Xn}var I_;function C_(){if(I_)return Vo;I_=1;var e,t,n,r,s,o,i,a,l,u,c;Object.defineProperty(Vo,"__esModule",{value:!0}),Vo.BetaToolRunner=void 0;const d=at(),p=Dt(),g=Lt(),y=JP();function _(){let v,A;return{promise:new Promise((P,E)=>{v=P,A=E}),resolve:v,reject:A}}let b=class{constructor(A,S,P){e.add(this),this.client=A,t.set(this,!1),n.set(this,!1),r.set(this,void 0),s.set(this,void 0),o.set(this,void 0),i.set(this,void 0),a.set(this,void 0),l.set(this,0),d.__classPrivateFieldSet(this,r,{params:{...S,messages:structuredClone(S.messages)}},"f"),d.__classPrivateFieldSet(this,s,{...P,headers:(0,g.buildHeaders)([{"x-stainless-helper":"BetaToolRunner"},P?.headers])},"f"),d.__classPrivateFieldSet(this,a,_(),"f")}async*[(t=new WeakMap,n=new WeakMap,r=new WeakMap,s=new WeakMap,o=new WeakMap,i=new WeakMap,a=new WeakMap,l=new WeakMap,e=new WeakSet,u=async function(){const S=d.__classPrivateFieldGet(this,r,"f").params.compactionControl;if(!S||!S.enabled)return!1;let P=0;if(d.__classPrivateFieldGet(this,o,"f")!==void 0)try{const B=await d.__classPrivateFieldGet(this,o,"f");P=B.usage.input_tokens+(B.usage.cache_creation_input_tokens??0)+(B.usage.cache_read_input_tokens??0)+B.usage.output_tokens}catch{return!1}const E=S.contextTokenThreshold??y.DEFAULT_TOKEN_THRESHOLD;if(P<E)return!1;const w=S.model??d.__classPrivateFieldGet(this,r,"f").params.model,I=S.summaryPrompt??y.DEFAULT_SUMMARY_PROMPT,L=d.__classPrivateFieldGet(this,r,"f").params.messages;if(L[L.length-1].role==="assistant"){const B=L[L.length-1];if(Array.isArray(B.content)){const F=B.content.filter(j=>j.type!=="tool_use");F.length===0?L.pop():B.content=F}}const H=await this.client.beta.messages.create({model:w,messages:[...L,{role:"user",content:[{type:"text",text:I}]}],max_tokens:d.__classPrivateFieldGet(this,r,"f").params.max_tokens},{headers:{"x-stainless-helper":"compaction"}});if(H.content[0]?.type!=="text")throw new p.AnthropicError("Expected text response for compaction");return d.__classPrivateFieldGet(this,r,"f").params.messages=[{role:"user",content:H.content}],!0},Symbol.asyncIterator)](){var A;if(d.__classPrivateFieldGet(this,t,"f"))throw new p.AnthropicError("Cannot iterate over a consumed stream");d.__classPrivateFieldSet(this,t,!0,"f"),d.__classPrivateFieldSet(this,n,!0,"f"),d.__classPrivateFieldSet(this,i,void 0,"f");try{for(;;){let S;try{if(d.__classPrivateFieldGet(this,r,"f").params.max_iterations&&d.__classPrivateFieldGet(this,l,"f")>=d.__classPrivateFieldGet(this,r,"f").params.max_iterations)break;d.__classPrivateFieldSet(this,n,!1,"f"),d.__classPrivateFieldSet(this,i,void 0,"f"),d.__classPrivateFieldSet(this,l,(A=d.__classPrivateFieldGet(this,l,"f"),A++,A),"f"),d.__classPrivateFieldSet(this,o,void 0,"f");const{max_iterations:P,compactionControl:E,...w}=d.__classPrivateFieldGet(this,r,"f").params;if(w.stream?(S=this.client.beta.messages.stream({...w},d.__classPrivateFieldGet(this,s,"f")),d.__classPrivateFieldSet(this,o,S.finalMessage(),"f"),d.__classPrivateFieldGet(this,o,"f").catch(()=>{}),yield S):(d.__classPrivateFieldSet(this,o,this.client.beta.messages.create({...w,stream:!1},d.__classPrivateFieldGet(this,s,"f")),"f"),yield d.__classPrivateFieldGet(this,o,"f")),!await d.__classPrivateFieldGet(this,e,"m",u).call(this)){if(!d.__classPrivateFieldGet(this,n,"f")){const{role:H,content:B}=await d.__classPrivateFieldGet(this,o,"f");d.__classPrivateFieldGet(this,r,"f").params.messages.push({role:H,content:B})}const L=await d.__classPrivateFieldGet(this,e,"m",c).call(this,d.__classPrivateFieldGet(this,r,"f").params.messages.at(-1));if(L)d.__classPrivateFieldGet(this,r,"f").params.messages.push(L);else if(!d.__classPrivateFieldGet(this,n,"f"))break}}finally{S&&S.abort()}}if(!d.__classPrivateFieldGet(this,o,"f"))throw new p.AnthropicError("ToolRunner concluded without a message from the server");d.__classPrivateFieldGet(this,a,"f").resolve(await d.__classPrivateFieldGet(this,o,"f"))}catch(S){throw d.__classPrivateFieldSet(this,t,!1,"f"),d.__classPrivateFieldGet(this,a,"f").promise.catch(()=>{}),d.__classPrivateFieldGet(this,a,"f").reject(S),d.__classPrivateFieldSet(this,a,_(),"f"),S}}setMessagesParams(A){typeof A=="function"?d.__classPrivateFieldGet(this,r,"f").params=A(d.__classPrivateFieldGet(this,r,"f").params):d.__classPrivateFieldGet(this,r,"f").params=A,d.__classPrivateFieldSet(this,n,!0,"f"),d.__classPrivateFieldSet(this,i,void 0,"f")}async generateToolResponse(){const A=await d.__classPrivateFieldGet(this,o,"f")??this.params.messages.at(-1);return A?d.__classPrivateFieldGet(this,e,"m",c).call(this,A):null}done(){return d.__classPrivateFieldGet(this,a,"f").promise}async runUntilDone(){if(!d.__classPrivateFieldGet(this,t,"f"))for await(const A of this);return this.done()}get params(){return d.__classPrivateFieldGet(this,r,"f").params}pushMessages(...A){this.setMessagesParams(S=>({...S,messages:[...S.messages,...A]}))}then(A,S){return this.runUntilDone().then(A,S)}};Vo.BetaToolRunner=b,c=async function(A){return d.__classPrivateFieldGet(this,i,"f")!==void 0?d.__classPrivateFieldGet(this,i,"f"):(d.__classPrivateFieldSet(this,i,m(d.__classPrivateFieldGet(this,r,"f").params,A),"f"),d.__classPrivateFieldGet(this,i,"f"))};async function m(v,A=v.messages.at(-1)){if(!A||A.role!=="assistant"||!A.content||typeof A.content=="string")return null;const S=A.content.filter(E=>E.type==="tool_use");return S.length===0?null:{role:"user",content:await Promise.all(S.map(async E=>{const w=v.tools.find(I=>("name"in I?I.name:I.mcp_server_name)===E.name);if(!w||!("run"in w))return{type:"tool_result",tool_use_id:E.id,content:`Error: Tool '${E.name}' not found`,is_error:!0};try{let I=E.input;"parse"in w&&w.parse&&(I=w.parse(I));const L=await w.run(I);return{type:"tool_result",tool_use_id:E.id,content:L}}catch(I){return{type:"tool_result",tool_use_id:E.id,content:`Error: ${I instanceof Error?I.message:String(I)}`,is_error:!0}}}))}}return Vo}var Bo={},Ho={},R_;function u0(){if(R_)return Ho;R_=1,Object.defineProperty(Ho,"__esModule",{value:!0}),Ho.JSONLDecoder=void 0;const e=Dt(),t=Ei(),n=t0();class r{constructor(o,i){this.iterator=o,this.controller=i}async*decoder(){const o=new n.LineDecoder;for await(const i of this.iterator)for(const a of o.decode(i))yield JSON.parse(a);for(const i of o.flush())yield JSON.parse(i)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(o,i){if(!o.body)throw i.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new e.AnthropicError("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new e.AnthropicError("Attempted to iterate over a response with no body");return new r((0,t.ReadableStreamToAsyncIterable)(o.body),i)}}return Ho.JSONLDecoder=r,Ho}var M_;function N_(){if(M_)return Bo;M_=1,Object.defineProperty(Bo,"__esModule",{value:!0}),Bo.Batches=void 0;const e=qt(),t=An(),n=Lt(),r=u0(),s=Ya(),o=dr();class i extends e.APIResource{create(l,u){const{betas:c,...d}=l;return this._client.post("/v1/messages/batches?beta=true",{body:d,...u,headers:(0,n.buildHeaders)([{"anthropic-beta":[...c??[],"message-batches-2024-09-24"].toString()},u?.headers])})}retrieve(l,u={},c){const{betas:d}=u??{};return this._client.get((0,o.path)`/v1/messages/batches/${l}?beta=true`,{...c,headers:(0,n.buildHeaders)([{"anthropic-beta":[...d??[],"message-batches-2024-09-24"].toString()},c?.headers])})}list(l={},u){const{betas:c,...d}=l??{};return this._client.getAPIList("/v1/messages/batches?beta=true",t.Page,{query:d,...u,headers:(0,n.buildHeaders)([{"anthropic-beta":[...c??[],"message-batches-2024-09-24"].toString()},u?.headers])})}delete(l,u={},c){const{betas:d}=u??{};return this._client.delete((0,o.path)`/v1/messages/batches/${l}?beta=true`,{...c,headers:(0,n.buildHeaders)([{"anthropic-beta":[...d??[],"message-batches-2024-09-24"].toString()},c?.headers])})}cancel(l,u={},c){const{betas:d}=u??{};return this._client.post((0,o.path)`/v1/messages/batches/${l}/cancel?beta=true`,{...c,headers:(0,n.buildHeaders)([{"anthropic-beta":[...d??[],"message-batches-2024-09-24"].toString()},c?.headers])})}async results(l,u={},c){const d=await this.retrieve(l);if(!d.results_url)throw new s.AnthropicError(`No batch \`results_url\`; Has it finished processing? ${d.processing_status} - ${d.id}`);const{betas:p}=u??{};return this._client.get(d.results_url,{...c,headers:(0,n.buildHeaders)([{"anthropic-beta":[...p??[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},c?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((g,y)=>r.JSONLDecoder.fromResponse(y.response,y.controller))}}return Bo.Batches=i,Bo}var F_;function k_(){return F_||(F_=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.BetaToolRunner=e.Messages=void 0;const t=at(),n=qt(),r=o0(),s=Lt(),o=i0(),i=HP(),a=C_(),l=t.__importStar(N_()),u=N_(),c={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-7-sonnet-latest":"February 19th, 2026","claude-3-7-sonnet-20250219":"February 19th, 2026"};class d extends n.APIResource{constructor(){super(...arguments),this.batches=new l.Batches(this._client)}create(y,_){const{betas:b,...m}=y;m.model in c&&console.warn(`The model '${m.model}' is deprecated and will reach end-of-life on ${c[m.model]}
66
- Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let v=this._client._options.timeout;if(!m.stream&&v==null){const A=r.MODEL_NONSTREAMING_TOKENS[m.model]??void 0;v=this._client.calculateNonstreamingTimeout(m.max_tokens,A)}return this._client.post("/v1/messages?beta=true",{body:m,timeout:v??6e5,..._,headers:(0,s.buildHeaders)([{...b?.toString()!=null?{"anthropic-beta":b?.toString()}:void 0},_?.headers]),stream:y.stream??!1})}parse(y,_){return _={..._,headers:(0,s.buildHeaders)([{"anthropic-beta":[...y.betas??[],"structured-outputs-2025-11-13"].toString()},_?.headers])},this.create(y,_).then(b=>(0,o.parseBetaMessage)(b,y,{logger:this._client.logger??console}))}stream(y,_){return i.BetaMessageStream.createMessage(this,y,_)}countTokens(y,_){const{betas:b,...m}=y;return this._client.post("/v1/messages/count_tokens?beta=true",{body:m,..._,headers:(0,s.buildHeaders)([{"anthropic-beta":[...b??[],"token-counting-2024-11-01"].toString()},_?.headers])})}toolRunner(y,_){return new a.BetaToolRunner(this._client,y,_)}}e.Messages=d;var p=C_();Object.defineProperty(e,"BetaToolRunner",{enumerable:!0,get:function(){return p.BetaToolRunner}}),d.Batches=u.Batches,d.BetaToolRunner=a.BetaToolRunner})(Tu)),Tu}var Jo={},jo={},O_;function x_(){if(O_)return jo;O_=1,Object.defineProperty(jo,"__esModule",{value:!0}),jo.Versions=void 0;const e=qt(),t=An(),n=Lt(),r=Ti(),s=dr();class o extends e.APIResource{create(a,l={},u){const{betas:c,...d}=l??{};return this._client.post((0,s.path)`/v1/skills/${a}/versions?beta=true`,(0,r.multipartFormRequestOptions)({body:d,...u,headers:(0,n.buildHeaders)([{"anthropic-beta":[...c??[],"skills-2025-10-02"].toString()},u?.headers])},this._client))}retrieve(a,l,u){const{skill_id:c,betas:d}=l;return this._client.get((0,s.path)`/v1/skills/${c}/versions/${a}?beta=true`,{...u,headers:(0,n.buildHeaders)([{"anthropic-beta":[...d??[],"skills-2025-10-02"].toString()},u?.headers])})}list(a,l={},u){const{betas:c,...d}=l??{};return this._client.getAPIList((0,s.path)`/v1/skills/${a}/versions?beta=true`,t.PageCursor,{query:d,...u,headers:(0,n.buildHeaders)([{"anthropic-beta":[...c??[],"skills-2025-10-02"].toString()},u?.headers])})}delete(a,l,u){const{skill_id:c,betas:d}=l;return this._client.delete((0,s.path)`/v1/skills/${c}/versions/${a}?beta=true`,{...u,headers:(0,n.buildHeaders)([{"anthropic-beta":[...d??[],"skills-2025-10-02"].toString()},u?.headers])})}}return jo.Versions=o,jo}var D_;function q_(){if(D_)return Jo;D_=1,Object.defineProperty(Jo,"__esModule",{value:!0}),Jo.Skills=void 0;const e=at(),t=qt(),n=e.__importStar(x_()),r=x_(),s=An(),o=Lt(),i=Ti(),a=dr();class l extends t.APIResource{constructor(){super(...arguments),this.versions=new n.Versions(this._client)}create(c={},d){const{betas:p,...g}=c??{};return this._client.post("/v1/skills?beta=true",(0,i.multipartFormRequestOptions)({body:g,...d,headers:(0,o.buildHeaders)([{"anthropic-beta":[...p??[],"skills-2025-10-02"].toString()},d?.headers])},this._client))}retrieve(c,d={},p){const{betas:g}=d??{};return this._client.get((0,a.path)`/v1/skills/${c}?beta=true`,{...p,headers:(0,o.buildHeaders)([{"anthropic-beta":[...g??[],"skills-2025-10-02"].toString()},p?.headers])})}list(c={},d){const{betas:p,...g}=c??{};return this._client.getAPIList("/v1/skills?beta=true",s.PageCursor,{query:g,...d,headers:(0,o.buildHeaders)([{"anthropic-beta":[...p??[],"skills-2025-10-02"].toString()},d?.headers])})}delete(c,d={},p){const{betas:g}=d??{};return this._client.delete((0,a.path)`/v1/skills/${c}?beta=true`,{...p,headers:(0,o.buildHeaders)([{"anthropic-beta":[...g??[],"skills-2025-10-02"].toString()},p?.headers])})}}return Jo.Skills=l,l.Versions=r.Versions,Jo}var L_;function c0(){if(L_)return ko;L_=1,Object.defineProperty(ko,"__esModule",{value:!0}),ko.Beta=void 0;const e=at(),t=qt(),n=e.__importStar(__()),r=__(),s=e.__importStar(v_()),o=v_(),i=e.__importStar(k_()),a=k_(),l=e.__importStar(q_()),u=q_();class c extends t.APIResource{constructor(){super(...arguments),this.models=new s.Models(this._client),this.messages=new i.Messages(this._client),this.files=new n.Files(this._client),this.skills=new l.Skills(this._client)}}return ko.Beta=c,c.Models=o.Models,c.Messages=a.Messages,c.Files=r.Files,c.Skills=u.Skills,ko}var Wo={},U_;function d0(){if(U_)return Wo;U_=1,Object.defineProperty(Wo,"__esModule",{value:!0}),Wo.Completions=void 0;const e=qt(),t=Lt();class n extends e.APIResource{create(s,o){const{betas:i,...a}=s;return this._client.post("/v1/complete",{body:a,timeout:this._client._options.timeout??6e5,...o,headers:(0,t.buildHeaders)([{...i?.toString()!=null?{"anthropic-beta":i?.toString()}:void 0},o?.headers]),stream:s.stream??!1})}}return Wo.Completions=n,Wo}var Ko={},$o={},G_;function jP(){if(G_)return $o;G_=1;var e,t,n,r,s,o,i,a,l,u,c,d,p,g,y,_,b,m,v,A,S,P;Object.defineProperty($o,"__esModule",{value:!0}),$o.MessageStream=void 0;const E=at(),w=qi(),I=Ya(),L=l0(),H=a0(),B="__json_buf";function F(O){return O.type==="tool_use"||O.type==="server_tool_use"}let j=class tc{constructor(){e.add(this),this.messages=[],this.receivedMessages=[],t.set(this,void 0),this.controller=new AbortController,n.set(this,void 0),r.set(this,()=>{}),s.set(this,()=>{}),o.set(this,void 0),i.set(this,()=>{}),a.set(this,()=>{}),l.set(this,{}),u.set(this,!1),c.set(this,!1),d.set(this,!1),p.set(this,!1),g.set(this,void 0),y.set(this,void 0),m.set(this,R=>{if(E.__classPrivateFieldSet(this,c,!0,"f"),(0,w.isAbortError)(R)&&(R=new I.APIUserAbortError),R instanceof I.APIUserAbortError)return E.__classPrivateFieldSet(this,d,!0,"f"),this._emit("abort",R);if(R instanceof I.AnthropicError)return this._emit("error",R);if(R instanceof Error){const T=new I.AnthropicError(R.message);return T.cause=R,this._emit("error",T)}return this._emit("error",new I.AnthropicError(String(R)))}),E.__classPrivateFieldSet(this,n,new Promise((R,T)=>{E.__classPrivateFieldSet(this,r,R,"f"),E.__classPrivateFieldSet(this,s,T,"f")}),"f"),E.__classPrivateFieldSet(this,o,new Promise((R,T)=>{E.__classPrivateFieldSet(this,i,R,"f"),E.__classPrivateFieldSet(this,a,T,"f")}),"f"),E.__classPrivateFieldGet(this,n,"f").catch(()=>{}),E.__classPrivateFieldGet(this,o,"f").catch(()=>{})}get response(){return E.__classPrivateFieldGet(this,g,"f")}get request_id(){return E.__classPrivateFieldGet(this,y,"f")}async withResponse(){E.__classPrivateFieldSet(this,p,!0,"f");const R=await E.__classPrivateFieldGet(this,n,"f");if(!R)throw new Error("Could not resolve a `Response` object");return{data:this,response:R,request_id:R.headers.get("request-id")}}static fromReadableStream(R){const T=new tc;return T._run(()=>T._fromReadableStream(R)),T}static createMessage(R,T,M){const k=new tc;for(const G of T.messages)k._addMessageParam(G);return k._run(()=>k._createMessage(R,{...T,stream:!0},{...M,headers:{...M?.headers,"X-Stainless-Helper-Method":"stream"}})),k}_run(R){R().then(()=>{this._emitFinal(),this._emit("end")},E.__classPrivateFieldGet(this,m,"f"))}_addMessageParam(R){this.messages.push(R)}_addMessage(R,T=!0){this.receivedMessages.push(R),T&&this._emit("message",R)}async _createMessage(R,T,M){const k=M?.signal;let G;k&&(k.aborted&&this.controller.abort(),G=this.controller.abort.bind(this.controller),k.addEventListener("abort",G));try{E.__classPrivateFieldGet(this,e,"m",v).call(this);const{response:V,data:W}=await R.create({...T,stream:!0},{...M,signal:this.controller.signal}).withResponse();this._connected(V);for await(const X of W)E.__classPrivateFieldGet(this,e,"m",A).call(this,X);if(W.controller.signal?.aborted)throw new I.APIUserAbortError;E.__classPrivateFieldGet(this,e,"m",S).call(this)}finally{k&&G&&k.removeEventListener("abort",G)}}_connected(R){this.ended||(E.__classPrivateFieldSet(this,g,R,"f"),E.__classPrivateFieldSet(this,y,R?.headers.get("request-id"),"f"),E.__classPrivateFieldGet(this,r,"f").call(this,R),this._emit("connect"))}get ended(){return E.__classPrivateFieldGet(this,u,"f")}get errored(){return E.__classPrivateFieldGet(this,c,"f")}get aborted(){return E.__classPrivateFieldGet(this,d,"f")}abort(){this.controller.abort()}on(R,T){return(E.__classPrivateFieldGet(this,l,"f")[R]||(E.__classPrivateFieldGet(this,l,"f")[R]=[])).push({listener:T}),this}off(R,T){const M=E.__classPrivateFieldGet(this,l,"f")[R];if(!M)return this;const k=M.findIndex(G=>G.listener===T);return k>=0&&M.splice(k,1),this}once(R,T){return(E.__classPrivateFieldGet(this,l,"f")[R]||(E.__classPrivateFieldGet(this,l,"f")[R]=[])).push({listener:T,once:!0}),this}emitted(R){return new Promise((T,M)=>{E.__classPrivateFieldSet(this,p,!0,"f"),R!=="error"&&this.once("error",M),this.once(R,T)})}async done(){E.__classPrivateFieldSet(this,p,!0,"f"),await E.__classPrivateFieldGet(this,o,"f")}get currentMessage(){return E.__classPrivateFieldGet(this,t,"f")}async finalMessage(){return await this.done(),E.__classPrivateFieldGet(this,e,"m",_).call(this)}async finalText(){return await this.done(),E.__classPrivateFieldGet(this,e,"m",b).call(this)}_emit(R,...T){if(E.__classPrivateFieldGet(this,u,"f"))return;R==="end"&&(E.__classPrivateFieldSet(this,u,!0,"f"),E.__classPrivateFieldGet(this,i,"f").call(this));const M=E.__classPrivateFieldGet(this,l,"f")[R];if(M&&(E.__classPrivateFieldGet(this,l,"f")[R]=M.filter(k=>!k.once),M.forEach(({listener:k})=>k(...T))),R==="abort"){const k=T[0];!E.__classPrivateFieldGet(this,p,"f")&&!M?.length&&Promise.reject(k),E.__classPrivateFieldGet(this,s,"f").call(this,k),E.__classPrivateFieldGet(this,a,"f").call(this,k),this._emit("end");return}if(R==="error"){const k=T[0];!E.__classPrivateFieldGet(this,p,"f")&&!M?.length&&Promise.reject(k),E.__classPrivateFieldGet(this,s,"f").call(this,k),E.__classPrivateFieldGet(this,a,"f").call(this,k),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",E.__classPrivateFieldGet(this,e,"m",_).call(this))}async _fromReadableStream(R,T){const M=T?.signal;let k;M&&(M.aborted&&this.controller.abort(),k=this.controller.abort.bind(this.controller),M.addEventListener("abort",k));try{E.__classPrivateFieldGet(this,e,"m",v).call(this),this._connected(null);const G=L.Stream.fromReadableStream(R,this.controller);for await(const V of G)E.__classPrivateFieldGet(this,e,"m",A).call(this,V);if(G.controller.signal?.aborted)throw new I.APIUserAbortError;E.__classPrivateFieldGet(this,e,"m",S).call(this)}finally{M&&k&&M.removeEventListener("abort",k)}}[(t=new WeakMap,n=new WeakMap,r=new WeakMap,s=new WeakMap,o=new WeakMap,i=new WeakMap,a=new WeakMap,l=new WeakMap,u=new WeakMap,c=new WeakMap,d=new WeakMap,p=new WeakMap,g=new WeakMap,y=new WeakMap,m=new WeakMap,e=new WeakSet,_=function(){if(this.receivedMessages.length===0)throw new I.AnthropicError("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},b=function(){if(this.receivedMessages.length===0)throw new I.AnthropicError("stream ended without producing a Message with role=assistant");const T=this.receivedMessages.at(-1).content.filter(M=>M.type==="text").map(M=>M.text);if(T.length===0)throw new I.AnthropicError("stream ended without producing a content block with type=text");return T.join(" ")},v=function(){this.ended||E.__classPrivateFieldSet(this,t,void 0,"f")},A=function(T){if(this.ended)return;const M=E.__classPrivateFieldGet(this,e,"m",P).call(this,T);switch(this._emit("streamEvent",T,M),T.type){case"content_block_delta":{const k=M.content.at(-1);switch(T.delta.type){case"text_delta":{k.type==="text"&&this._emit("text",T.delta.text,k.text||"");break}case"citations_delta":{k.type==="text"&&this._emit("citation",T.delta.citation,k.citations??[]);break}case"input_json_delta":{F(k)&&k.input&&this._emit("inputJson",T.delta.partial_json,k.input);break}case"thinking_delta":{k.type==="thinking"&&this._emit("thinking",T.delta.thinking,k.thinking);break}case"signature_delta":{k.type==="thinking"&&this._emit("signature",k.signature);break}default:T.delta}break}case"message_stop":{this._addMessageParam(M),this._addMessage(M,!0);break}case"content_block_stop":{this._emit("contentBlock",M.content.at(-1));break}case"message_start":{E.__classPrivateFieldSet(this,t,M,"f");break}}},S=function(){if(this.ended)throw new I.AnthropicError("stream has ended, this shouldn't happen");const T=E.__classPrivateFieldGet(this,t,"f");if(!T)throw new I.AnthropicError("request ended without sending any chunks");return E.__classPrivateFieldSet(this,t,void 0,"f"),T},P=function(T){let M=E.__classPrivateFieldGet(this,t,"f");if(T.type==="message_start"){if(M)throw new I.AnthropicError(`Unexpected event order, got ${T.type} before receiving "message_stop"`);return T.message}if(!M)throw new I.AnthropicError(`Unexpected event order, got ${T.type} before "message_start"`);switch(T.type){case"message_stop":return M;case"message_delta":return M.stop_reason=T.delta.stop_reason,M.stop_sequence=T.delta.stop_sequence,M.usage.output_tokens=T.usage.output_tokens,T.usage.input_tokens!=null&&(M.usage.input_tokens=T.usage.input_tokens),T.usage.cache_creation_input_tokens!=null&&(M.usage.cache_creation_input_tokens=T.usage.cache_creation_input_tokens),T.usage.cache_read_input_tokens!=null&&(M.usage.cache_read_input_tokens=T.usage.cache_read_input_tokens),T.usage.server_tool_use!=null&&(M.usage.server_tool_use=T.usage.server_tool_use),M;case"content_block_start":return M.content.push({...T.content_block}),M;case"content_block_delta":{const k=M.content.at(T.index);switch(T.delta.type){case"text_delta":{k?.type==="text"&&(M.content[T.index]={...k,text:(k.text||"")+T.delta.text});break}case"citations_delta":{k?.type==="text"&&(M.content[T.index]={...k,citations:[...k.citations??[],T.delta.citation]});break}case"input_json_delta":{if(k&&F(k)){let G=k[B]||"";G+=T.delta.partial_json;const V={...k};Object.defineProperty(V,B,{value:G,enumerable:!1,writable:!0}),G&&(V.input=(0,H.partialParse)(G)),M.content[T.index]=V}break}case"thinking_delta":{k?.type==="thinking"&&(M.content[T.index]={...k,thinking:k.thinking+T.delta.thinking});break}case"signature_delta":{k?.type==="thinking"&&(M.content[T.index]={...k,signature:T.delta.signature});break}default:T.delta}return M}case"content_block_stop":return M}},Symbol.asyncIterator)](){const R=[],T=[];let M=!1;return this.on("streamEvent",k=>{const G=T.shift();G?G.resolve(k):R.push(k)}),this.on("end",()=>{M=!0;for(const k of T)k.resolve(void 0);T.length=0}),this.on("abort",k=>{M=!0;for(const G of T)G.reject(k);T.length=0}),this.on("error",k=>{M=!0;for(const G of T)G.reject(k);T.length=0}),{next:async()=>R.length?{value:R.shift(),done:!1}:M?{value:void 0,done:!0}:new Promise((G,V)=>T.push({resolve:G,reject:V})).then(G=>G?{value:G,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new L.Stream(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};$o.MessageStream=j;function U(O){}return $o}var Yo={},V_;function B_(){if(V_)return Yo;V_=1,Object.defineProperty(Yo,"__esModule",{value:!0}),Yo.Batches=void 0;const e=qt(),t=An(),n=Lt(),r=u0(),s=Ya(),o=dr();class i extends e.APIResource{create(l,u){return this._client.post("/v1/messages/batches",{body:l,...u})}retrieve(l,u){return this._client.get((0,o.path)`/v1/messages/batches/${l}`,u)}list(l={},u){return this._client.getAPIList("/v1/messages/batches",t.Page,{query:l,...u})}delete(l,u){return this._client.delete((0,o.path)`/v1/messages/batches/${l}`,u)}cancel(l,u){return this._client.post((0,o.path)`/v1/messages/batches/${l}/cancel`,u)}async results(l,u){const c=await this.retrieve(l);if(!c.results_url)throw new s.AnthropicError(`No batch \`results_url\`; Has it finished processing? ${c.processing_status} - ${c.id}`);return this._client.get(c.results_url,{...u,headers:(0,n.buildHeaders)([{Accept:"application/binary"},u?.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((d,p)=>r.JSONLDecoder.fromResponse(p.response,p.controller))}}return Yo.Batches=i,Yo}var H_;function f0(){if(H_)return Ko;H_=1,Object.defineProperty(Ko,"__esModule",{value:!0}),Ko.Messages=void 0;const e=at(),t=qt(),n=jP(),r=e.__importStar(B_()),s=B_(),o=o0();class i extends t.APIResource{constructor(){super(...arguments),this.batches=new r.Batches(this._client)}create(u,c){u.model in a&&console.warn(`The model '${u.model}' is deprecated and will reach end-of-life on ${a[u.model]}
67
- Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let d=this._client._options.timeout;if(!u.stream&&d==null){const p=o.MODEL_NONSTREAMING_TOKENS[u.model]??void 0;d=this._client.calculateNonstreamingTimeout(u.max_tokens,p)}return this._client.post("/v1/messages",{body:u,timeout:d??6e5,...c,stream:u.stream??!1})}stream(u,c){return n.MessageStream.createMessage(this,u,c)}countTokens(u,c){return this._client.post("/v1/messages/count_tokens",{body:u,...c})}}Ko.Messages=i;const a={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025","claude-3-7-sonnet-latest":"February 19th, 2026","claude-3-7-sonnet-20250219":"February 19th, 2026"};return i.Batches=s.Batches,Ko}var zo={},J_;function p0(){if(J_)return zo;J_=1,Object.defineProperty(zo,"__esModule",{value:!0}),zo.Models=void 0;const e=qt(),t=An(),n=Lt(),r=dr();class s extends e.APIResource{retrieve(i,a={},l){const{betas:u}=a??{};return this._client.get((0,r.path)`/v1/models/${i}`,{...l,headers:(0,n.buildHeaders)([{...u?.toString()!=null?{"anthropic-beta":u?.toString()}:void 0},l?.headers])})}list(i={},a){const{betas:l,...u}=i??{};return this._client.getAPIList("/v1/models",t.Page,{query:u,...a,headers:(0,n.buildHeaders)([{...l?.toString()!=null?{"anthropic-beta":l?.toString()}:void 0},a?.headers])})}}return zo.Models=s,zo}var j_;function WP(){return j_||(j_=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.Models=e.Messages=e.Completions=e.Beta=void 0,at().__exportStar(BP(),e);var n=c0();Object.defineProperty(e,"Beta",{enumerable:!0,get:function(){return n.Beta}});var r=d0();Object.defineProperty(e,"Completions",{enumerable:!0,get:function(){return r.Completions}});var s=f0();Object.defineProperty(e,"Messages",{enumerable:!0,get:function(){return s.Messages}});var o=p0();Object.defineProperty(e,"Models",{enumerable:!0,get:function(){return o.Models}})})(Su)),Su}var Xo={},W_;function KP(){if(W_)return Xo;W_=1;var e={};Object.defineProperty(Xo,"__esModule",{value:!0}),Xo.readEnv=void 0;const t=n=>{if(typeof globalThis.process<"u")return e?.[n]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(n)?.trim()};return Xo.readEnv=t,Xo}var K_;function $_(){return K_||(K_=1,(function(e){var t,n,r,s;Object.defineProperty(e,"__esModule",{value:!0}),e.Anthropic=e.BaseAnthropic=e.AI_PROMPT=e.HUMAN_PROMPT=void 0;const o=at(),i=LP(),a=Vr(),l=UP(),u=qi(),c=Zm(),d=o.__importStar(Ei()),p=o.__importStar(GP()),g=Zb(),y=o.__importStar(Dt()),_=o.__importStar(An()),b=o.__importStar(s0()),m=o.__importStar(WP()),v=zd(),A=d0(),S=p0(),P=c0(),E=f0(),w=Zm(),I=Lt(),L=KP(),H=Yd(),B=Vr();e.HUMAN_PROMPT="\\n\\nHuman:",e.AI_PROMPT="\\n\\nAssistant:";class F{constructor({baseURL:O=(0,L.readEnv)("ANTHROPIC_BASE_URL"),apiKey:R=(0,L.readEnv)("ANTHROPIC_API_KEY")??null,authToken:T=(0,L.readEnv)("ANTHROPIC_AUTH_TOKEN")??null,...M}={}){t.add(this),r.set(this,void 0);const k={apiKey:R,authToken:T,...M,baseURL:O||"https://api.anthropic.com"};if(!k.dangerouslyAllowBrowser&&(0,w.isRunningInBrowser)())throw new y.AnthropicError(`It looks like you're running in a browser-like environment.
68
-
69
- This is disabled by default, as it risks exposing your secret API credentials to attackers.
70
- If you understand the risks and have appropriate mitigations in place,
71
- you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
72
-
73
- new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
74
- `);this.baseURL=k.baseURL,this.timeout=k.timeout??n.DEFAULT_TIMEOUT,this.logger=k.logger??console;const G="warn";this.logLevel=G,this.logLevel=(0,H.parseLogLevel)(k.logLevel,"ClientOptions.logLevel",this)??(0,H.parseLogLevel)((0,L.readEnv)("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this)??G,this.fetchOptions=k.fetchOptions,this.maxRetries=k.maxRetries??2,this.fetch=k.fetch??d.getDefaultFetch(),o.__classPrivateFieldSet(this,r,p.FallbackEncoder,"f"),this._options=k,this.apiKey=typeof R=="string"?R:null,this.authToken=T}withOptions(O){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,authToken:this.authToken,...O})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:O,nulls:R}){if(!(O.get("x-api-key")||O.get("authorization"))&&!(this.apiKey&&O.get("x-api-key"))&&!R.has("x-api-key")&&!(this.authToken&&O.get("authorization"))&&!R.has("authorization"))throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}async authHeaders(O){return(0,I.buildHeaders)([await this.apiKeyAuth(O),await this.bearerAuth(O)])}async apiKeyAuth(O){if(this.apiKey!=null)return(0,I.buildHeaders)([{"X-Api-Key":this.apiKey}])}async bearerAuth(O){if(this.authToken!=null)return(0,I.buildHeaders)([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(O){return Object.entries(O).filter(([R,T])=>typeof T<"u").map(([R,T])=>{if(typeof T=="string"||typeof T=="number"||typeof T=="boolean")return`${encodeURIComponent(R)}=${encodeURIComponent(T)}`;if(T===null)return`${encodeURIComponent(R)}=`;throw new y.AnthropicError(`Cannot stringify type ${typeof T}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${g.VERSION}`}defaultIdempotencyKey(){return`stainless-node-retry-${(0,i.uuid4)()}`}makeStatusError(O,R,T,M){return y.APIError.generate(O,R,T,M)}buildURL(O,R,T){const M=!o.__classPrivateFieldGet(this,t,"m",s).call(this)&&T||this.baseURL,k=(0,a.isAbsoluteURL)(O)?new URL(O):new URL(M+(M.endsWith("/")&&O.startsWith("/")?O.slice(1):O)),G=this.defaultQuery();return(0,B.isEmptyObj)(G)||(R={...G,...R}),typeof R=="object"&&R&&!Array.isArray(R)&&(k.search=this.stringifyQuery(R)),k.toString()}_calculateNonstreamingTimeout(O){if(3600*O/128e3>600)throw new y.AnthropicError("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600*1e3}async prepareOptions(O){}async prepareRequest(O,{url:R,options:T}){}get(O,R){return this.methodRequest("get",O,R)}post(O,R){return this.methodRequest("post",O,R)}patch(O,R){return this.methodRequest("patch",O,R)}put(O,R){return this.methodRequest("put",O,R)}delete(O,R){return this.methodRequest("delete",O,R)}methodRequest(O,R,T){return this.request(Promise.resolve(T).then(M=>({method:O,path:R,...M})))}request(O,R=null){return new v.APIPromise(this,this.makeRequest(O,R,void 0))}async makeRequest(O,R,T){const M=await O,k=M.maxRetries??this.maxRetries;R==null&&(R=k),await this.prepareOptions(M);const{req:G,url:V,timeout:W}=await this.buildRequest(M,{retryCount:k-R});await this.prepareRequest(G,{url:V,options:M});const X="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),Y=T===void 0?"":`, retryOf: ${T}`,Z=Date.now();if((0,H.loggerFor)(this).debug(`[${X}] sending request`,(0,H.formatRequestDetails)({retryOfRequestLogID:T,method:M.method,url:V,options:M,headers:G.headers})),M.signal?.aborted)throw new y.APIUserAbortError;const ne=new AbortController,re=await this.fetchWithTimeout(V,G,W,ne).catch(u.castToError),Ae=Date.now();if(re instanceof globalThis.Error){const ee=`retrying, ${R} attempts remaining`;if(M.signal?.aborted)throw new y.APIUserAbortError;const C=(0,u.isAbortError)(re)||/timed? ?out/i.test(String(re)+("cause"in re?String(re.cause):""));if(R)return(0,H.loggerFor)(this).info(`[${X}] connection ${C?"timed out":"failed"} - ${ee}`),(0,H.loggerFor)(this).debug(`[${X}] connection ${C?"timed out":"failed"} (${ee})`,(0,H.formatRequestDetails)({retryOfRequestLogID:T,url:V,durationMs:Ae-Z,message:re.message})),this.retryRequest(M,R,T??X);throw(0,H.loggerFor)(this).info(`[${X}] connection ${C?"timed out":"failed"} - error; no more retries left`),(0,H.loggerFor)(this).debug(`[${X}] connection ${C?"timed out":"failed"} (error; no more retries left)`,(0,H.formatRequestDetails)({retryOfRequestLogID:T,url:V,durationMs:Ae-Z,message:re.message})),C?new y.APIConnectionTimeoutError:new y.APIConnectionError({cause:re})}const le=[...re.headers.entries()].filter(([ee])=>ee==="request-id").map(([ee,C])=>", "+ee+": "+JSON.stringify(C)).join(""),we=`[${X}${Y}${le}] ${G.method} ${V} ${re.ok?"succeeded":"failed"} with status ${re.status} in ${Ae-Z}ms`;if(!re.ok){const ee=await this.shouldRetry(re);if(R&&ee){const q=`retrying, ${R} attempts remaining`;return await d.CancelReadableStream(re.body),(0,H.loggerFor)(this).info(`${we} - ${q}`),(0,H.loggerFor)(this).debug(`[${X}] response error (${q})`,(0,H.formatRequestDetails)({retryOfRequestLogID:T,url:re.url,status:re.status,headers:re.headers,durationMs:Ae-Z})),this.retryRequest(M,R,T??X,re.headers)}const C=ee?"error; no more retries left":"error; not retryable";(0,H.loggerFor)(this).info(`${we} - ${C}`);const D=await re.text().catch(q=>(0,u.castToError)(q).message),$=(0,a.safeJSON)(D),x=$?void 0:D;throw(0,H.loggerFor)(this).debug(`[${X}] response error (${C})`,(0,H.formatRequestDetails)({retryOfRequestLogID:T,url:re.url,status:re.status,headers:re.headers,message:x,durationMs:Date.now()-Z})),this.makeStatusError(re.status,$,x,re.headers)}return(0,H.loggerFor)(this).info(we),(0,H.loggerFor)(this).debug(`[${X}] response start`,(0,H.formatRequestDetails)({retryOfRequestLogID:T,url:re.url,status:re.status,headers:re.headers,durationMs:Ae-Z})),{response:re,options:M,controller:ne,requestLogID:X,retryOfRequestLogID:T,startTime:Z}}getAPIList(O,R,T){return this.requestAPIList(R,{method:"get",path:O,...T})}requestAPIList(O,R){const T=this.makeRequest(R,null,void 0);return new _.PagePromise(this,T,O)}async fetchWithTimeout(O,R,T,M){const{signal:k,method:G,...V}=R||{};k&&k.addEventListener("abort",()=>M.abort());const W=setTimeout(()=>M.abort(),T),X=globalThis.ReadableStream&&V.body instanceof globalThis.ReadableStream||typeof V.body=="object"&&V.body!==null&&Symbol.asyncIterator in V.body,Y={signal:M.signal,...X?{duplex:"half"}:{},method:"GET",...V};G&&(Y.method=G.toUpperCase());try{return await this.fetch.call(void 0,O,Y)}finally{clearTimeout(W)}}async shouldRetry(O){const R=O.headers.get("x-should-retry");return R==="true"?!0:R==="false"?!1:O.status===408||O.status===409||O.status===429||O.status>=500}async retryRequest(O,R,T,M){let k;const G=M?.get("retry-after-ms");if(G){const W=parseFloat(G);Number.isNaN(W)||(k=W)}const V=M?.get("retry-after");if(V&&!k){const W=parseFloat(V);Number.isNaN(W)?k=Date.parse(V)-Date.now():k=W*1e3}if(!(k&&0<=k&&k<60*1e3)){const W=O.maxRetries??this.maxRetries;k=this.calculateDefaultRetryTimeoutMillis(R,W)}return await(0,l.sleep)(k),this.makeRequest(O,R-1,T)}calculateDefaultRetryTimeoutMillis(O,R){const k=R-O,G=Math.min(.5*Math.pow(2,k),8),V=1-Math.random()*.25;return G*V*1e3}calculateNonstreamingTimeout(O,R){if(36e5*O/128e3>6e5||R!=null&&O>R)throw new y.AnthropicError("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 6e5}async buildRequest(O,{retryCount:R=0}={}){const T={...O},{method:M,path:k,query:G,defaultBaseURL:V}=T,W=this.buildURL(k,G,V);"timeout"in T&&(0,a.validatePositiveInteger)("timeout",T.timeout),T.timeout=T.timeout??this.timeout;const{bodyHeaders:X,body:Y}=this.buildBody({options:T}),Z=await this.buildHeaders({options:O,method:M,bodyHeaders:X,retryCount:R});return{req:{method:M,headers:Z,...T.signal&&{signal:T.signal},...globalThis.ReadableStream&&Y instanceof globalThis.ReadableStream&&{duplex:"half"},...Y&&{body:Y},...this.fetchOptions??{},...T.fetchOptions??{}},url:W,timeout:T.timeout}}async buildHeaders({options:O,method:R,bodyHeaders:T,retryCount:M}){let k={};this.idempotencyHeader&&R!=="get"&&(O.idempotencyKey||(O.idempotencyKey=this.defaultIdempotencyKey()),k[this.idempotencyHeader]=O.idempotencyKey);const G=(0,I.buildHeaders)([k,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(M),...O.timeout?{"X-Stainless-Timeout":String(Math.trunc(O.timeout/1e3))}:{},...(0,c.getPlatformHeaders)(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},await this.authHeaders(O),this._options.defaultHeaders,T,O.headers]);return this.validateHeaders(G),G.values}buildBody({options:{body:O,headers:R}}){if(!O)return{bodyHeaders:void 0,body:void 0};const T=(0,I.buildHeaders)([R]);return ArrayBuffer.isView(O)||O instanceof ArrayBuffer||O instanceof DataView||typeof O=="string"&&T.values.has("content-type")||globalThis.Blob&&O instanceof globalThis.Blob||O instanceof FormData||O instanceof URLSearchParams||globalThis.ReadableStream&&O instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:O}:typeof O=="object"&&(Symbol.asyncIterator in O||Symbol.iterator in O&&"next"in O&&typeof O.next=="function")?{bodyHeaders:void 0,body:d.ReadableStreamFrom(O)}:o.__classPrivateFieldGet(this,r,"f").call(this,{body:O,headers:T})}}e.BaseAnthropic=F,n=F,r=new WeakMap,t=new WeakSet,s=function(){return this.baseURL!=="https://api.anthropic.com"},F.Anthropic=n,F.HUMAN_PROMPT=e.HUMAN_PROMPT,F.AI_PROMPT=e.AI_PROMPT,F.DEFAULT_TIMEOUT=6e5,F.AnthropicError=y.AnthropicError,F.APIError=y.APIError,F.APIConnectionError=y.APIConnectionError,F.APIConnectionTimeoutError=y.APIConnectionTimeoutError,F.APIUserAbortError=y.APIUserAbortError,F.NotFoundError=y.NotFoundError,F.ConflictError=y.ConflictError,F.RateLimitError=y.RateLimitError,F.BadRequestError=y.BadRequestError,F.AuthenticationError=y.AuthenticationError,F.InternalServerError=y.InternalServerError,F.PermissionDeniedError=y.PermissionDeniedError,F.UnprocessableEntityError=y.UnprocessableEntityError,F.toFile=b.toFile;class j extends F{constructor(){super(...arguments),this.completions=new m.Completions(this),this.messages=new m.Messages(this),this.models=new m.Models(this),this.beta=new m.Beta(this)}}e.Anthropic=j,j.Completions=A.Completions,j.Messages=E.Messages,j.Models=S.Models,j.Beta=P.Beta})(yu)),yu}var Y_;function $P(){return Y_||(Y_=1,(function(e,t){t=e.exports=function(...l){return new t.default(...l)},Object.defineProperty(t,"__esModule",{value:!0}),t.UnprocessableEntityError=t.PermissionDeniedError=t.InternalServerError=t.AuthenticationError=t.BadRequestError=t.RateLimitError=t.ConflictError=t.NotFoundError=t.APIUserAbortError=t.APIConnectionTimeoutError=t.APIConnectionError=t.APIError=t.AnthropicError=t.PagePromise=t.AI_PROMPT=t.HUMAN_PROMPT=t.Anthropic=t.BaseAnthropic=t.APIPromise=t.toFile=t.default=void 0;var n=$_();Object.defineProperty(t,"default",{enumerable:!0,get:function(){return n.Anthropic}});var r=s0();Object.defineProperty(t,"toFile",{enumerable:!0,get:function(){return r.toFile}});var s=zd();Object.defineProperty(t,"APIPromise",{enumerable:!0,get:function(){return s.APIPromise}});var o=$_();Object.defineProperty(t,"BaseAnthropic",{enumerable:!0,get:function(){return o.BaseAnthropic}}),Object.defineProperty(t,"Anthropic",{enumerable:!0,get:function(){return o.Anthropic}}),Object.defineProperty(t,"HUMAN_PROMPT",{enumerable:!0,get:function(){return o.HUMAN_PROMPT}}),Object.defineProperty(t,"AI_PROMPT",{enumerable:!0,get:function(){return o.AI_PROMPT}});var i=An();Object.defineProperty(t,"PagePromise",{enumerable:!0,get:function(){return i.PagePromise}});var a=Dt();Object.defineProperty(t,"AnthropicError",{enumerable:!0,get:function(){return a.AnthropicError}}),Object.defineProperty(t,"APIError",{enumerable:!0,get:function(){return a.APIError}}),Object.defineProperty(t,"APIConnectionError",{enumerable:!0,get:function(){return a.APIConnectionError}}),Object.defineProperty(t,"APIConnectionTimeoutError",{enumerable:!0,get:function(){return a.APIConnectionTimeoutError}}),Object.defineProperty(t,"APIUserAbortError",{enumerable:!0,get:function(){return a.APIUserAbortError}}),Object.defineProperty(t,"NotFoundError",{enumerable:!0,get:function(){return a.NotFoundError}}),Object.defineProperty(t,"ConflictError",{enumerable:!0,get:function(){return a.ConflictError}}),Object.defineProperty(t,"RateLimitError",{enumerable:!0,get:function(){return a.RateLimitError}}),Object.defineProperty(t,"BadRequestError",{enumerable:!0,get:function(){return a.BadRequestError}}),Object.defineProperty(t,"AuthenticationError",{enumerable:!0,get:function(){return a.AuthenticationError}}),Object.defineProperty(t,"InternalServerError",{enumerable:!0,get:function(){return a.InternalServerError}}),Object.defineProperty(t,"PermissionDeniedError",{enumerable:!0,get:function(){return a.PermissionDeniedError}}),Object.defineProperty(t,"UnprocessableEntityError",{enumerable:!0,get:function(){return a.UnprocessableEntityError}})})(Ki,Ki.exports)),Ki.exports}var Cu={},z_;function YP(){return z_||(z_=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.convOpenAIToolsToAnthropicToolMessage=e.anthoropicTool2OpenAITool=e.openAIToolCall2AnthropicToolCall=e.anthoropicToolCall2OpenAIToolCall=void 0;const t=o=>{const{id:i,name:a,input:l}=o;return{id:i,type:"function",function:{name:a,arguments:(()=>{try{return JSON.stringify(l??{})}catch{return"{}"}})()}}};e.anthoropicToolCall2OpenAIToolCall=t;const n=o=>{const{id:i,function:a}=o,{name:l,arguments:u}=a??{};return{type:"tool_use",id:i,name:l,input:(()=>{try{return JSON.parse(u??"{}")}catch{return{}}})()}};e.openAIToolCall2AnthropicToolCall=n;const r=o=>{const i=o.content.filter(l=>l.type==="text").map(l=>l.text??"").join(" "),a=o.content.filter(l=>l.type==="tool_use").map(e.anthoropicToolCall2OpenAIToolCall);return a.length>0?{role:o.role,content:i,tool_calls:a}:{role:o.role,content:i}};e.anthoropicTool2OpenAITool=r;const s=o=>o.reduce((i,a)=>{if(a.role==="assistant"&&a.tool_calls){const l=[{type:"text",text:a.content||"run tools"}];a.tool_calls.map(e.openAIToolCall2AnthropicToolCall).forEach(u=>{l.push(u)}),i.push({role:"assistant",content:l})}else if(a.role==="tool"){const l=i[i.length-1];l?.role==="user"&&l?.content?.[0]?.type==="tool_result"?i[i.length-1].content.push({type:"tool_result",tool_use_id:a.tool_call_id,content:a.content}):i.push({role:"user",content:[{type:"tool_result",tool_use_id:a.tool_call_id,content:a.content}]})}else i.push(a);return i},[]);e.convOpenAIToolsToAnthropicToolMessage=s})(Cu)),Cu}var X_;function zP(){return X_||(X_=1,(function(e){var t=Io&&Io.__importDefault||function(c){return c&&c.__esModule?c:{default:c}};Object.defineProperty(e,"__esModule",{value:!0}),e.anthropicAgent=e.system_with_response_format=void 0;const n=t($P()),r=Di(),s=YP(),o=c=>{const{id:d,name:p,input:g}=c;return{id:d,name:p,arguments:g}},i=(c,d,p,g)=>{(0,r.llmMetaDataEndTime)(p);const y=c.content[0].text,b=(c.content.filter(E=>E.type==="tool_use")??[]).map(o),m=b[0]?b[0]:void 0,v=(0,s.anthoropicTool2OpenAITool)(c),A=(()=>{if(g&&y){const E=y.trim(),w=E.match(/```(?:\w+)?\s*([\s\S]*?)\s*```/),I=w?w[1].trim():E;try{const L=JSON.parse(I);if(typeof L=="object"&&L!==null)return L}catch{return null}}return null})(),{usage:S}=c,P=S?{prompt_tokens:S.input_tokens,completion_tokens:S.output_tokens,total_tokens:S.input_tokens+S.output_tokens}:{};return{...c,choices:[{message:v}],text:y,tool:m,tool_calls:b,message:v,messages:d,metadata:(0,r.convertMeta)(p),responseFormat:A,usage:{...S,...P}}},a=(c,d)=>d?c?["Please return the following json object for the specified content.",JSON.stringify(d,null,2),"","<description>",c,"</description>"].join(`
75
- `):["Please return the following json object for the specified content.",JSON.stringify(d,null,2)].join(`
76
- `):c;e.system_with_response_format=a;const l=async({params:c,namedInputs:d,filterParams:p,config:g})=>{const{verbose:y,system:_,temperature:b,tools:m,tool_choice:v,max_tokens:A,prompt:S,messages:P,response_format:E}={...c,...d},{apiKey:w,stream:I,dataStream:L,forWeb:H,model:B}={...c,...g||{}},F=(0,r.initLLMMetaData)(),j=(0,r.getMergeValue)(d,c,"mergeablePrompts",S),U=(0,r.getMergeValue)(d,c,"mergeableSystem",(0,e.system_with_response_format)(_,E)),O=P?P.map(X=>X):[],R=O[0]&&O[0].role==="system"?O[0].content:"";j&&O.push({role:"user",content:j}),y&&console.log(O);const T=m&&m.length>0?m.map(X=>{const{function:Y}=X,{name:Z,description:ne,parameters:re}=Y;return{name:Z,description:ne,input_schema:re}}):void 0,M=new n.default({apiKey:w,dangerouslyAllowBrowser:!!H}),k={model:B||"claude-sonnet-4-5",messages:(0,s.convOpenAIToolsToAnthropicToolMessage)(O.filter(X=>X.role!=="system")),tools:T,tool_choice:v,system:U||R,temperature:b??.7,max_tokens:A??8192};if(!I&&!L){const X=await M.messages.create(k);return i(X,O,F,!!E)}const G=await M.messages.create({...k,stream:!0}),V=[];let W=null;L&&p&&p.streamTokenCallback&&p.streamTokenCallback({type:"response.created",response:{}});for await(const X of G){if((0,r.llmMetaDataFirstTokenTime)(F),X.type==="message_start"&&(W=X.message),X.type==="content_block_start"&&(W&&W.content.push(X.content_block),V.push("")),X.type==="content_block_delta"){const{index:Y,delta:Z}=X;Z.type==="input_json_delta"&&(V[Y]=V[Y]+Z.partial_json),Z.type==="text_delta"&&(V[Y]=V[Y]+Z.text)}if(X.type==="content_block_delta"&&X.delta.type==="text_delta"){const Y=X.delta.text;p&&p.streamTokenCallback&&Y&&(L?p.streamTokenCallback({type:"response.in_progress",response:{output:[{type:"text",text:Y}]}}):p.streamTokenCallback(Y))}}if(L&&p&&p.streamTokenCallback&&p.streamTokenCallback({type:"response.completed",response:{}}),W===null)throw new Error("Anthoropic no response");return V.forEach((X,Y)=>{W.content[Y].type==="text"&&(W.content[Y].text=X),W.content[Y].type==="tool_use"&&(W.content[Y].input=JSON.parse(X))}),i(W,O,F,!!E)};e.anthropicAgent=l;const u={name:"anthropicAgent",agent:e.anthropicAgent,mock:e.anthropicAgent,inputs:{type:"object",properties:{model:{type:"string"},system:{type:"string"},max_tokens:{type:"number"},temperature:{type:"number"},prompt:{type:"string",description:"query string"},messages:{anyOf:[{type:"string"},{type:"integer"},{type:"object"},{type:"array"}],description:"chat messages"}}},output:{type:"object"},samples:[],description:"Anthropic Agent",category:["llm"],author:"Receptron team",repository:"https://github.com/receptron/graphai",source:"https://github.com/receptron/graphai/blob/main/llm_agents/anthropic_agent/src/anthropic_agent.ts",package:"@graphai/anthropic_agent",license:"MIT",stream:!0,environmentVariables:["ANTHROPIC_API_KEY"],npms:["@anthropic-ai/sdk"]};e.default=u})(Io)),Io}var Q_;function XP(){if(Q_)return $n;Q_=1;var e=$n&&$n.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty($n,"__esModule",{value:!0}),$n.anthropicAgent=void 0;const t=e(zP());return $n.anthropicAgent=t.default,$n}XP();var Qn={},Ru={},ci={exports:{}},Zn={},Qo={},Z_;function QP(){return Z_||(Z_=1,Object.defineProperty(Qo,"__esModule",{value:!0}),Qo.VERSION=void 0,Qo.VERSION="0.30.0"),Qo}var er={},Mu={};let nc=!1,oa,h0,g0,m0,_0,y0,v0,b0,A0,S0,w0,E0,T0;function ZP(e,t={auto:!1}){if(nc)throw new Error(`you must \`import 'groq-sdk/shims/${e.kind}'\` before importing anything else from groq-sdk`);if(oa)throw new Error(`can't \`import 'groq-sdk/shims/${e.kind}'\` after \`import 'groq-sdk/shims/${oa}'\``);nc=t.auto,oa=e.kind,h0=e.fetch,g0=e.Request,m0=e.Response,_0=e.Headers,y0=e.FormData,v0=e.Blob,b0=e.File,A0=e.ReadableStream,S0=e.getMultipartRequestOptions,w0=e.getDefaultAgent,E0=e.fileFromPath,T0=e.isFsReadStream}const eI=Object.freeze(Object.defineProperty({__proto__:null,get Blob(){return v0},get File(){return b0},get FormData(){return y0},get Headers(){return _0},get ReadableStream(){return A0},get Request(){return g0},get Response(){return m0},get auto(){return nc},get fetch(){return h0},get fileFromPath(){return E0},get getDefaultAgent(){return w0},get getMultipartRequestOptions(){return S0},get isFsReadStream(){return T0},get kind(){return oa},setShims:ZP},Symbol.toStringTag,{value:"Module"})),tI=Hd(eI);var tr={},Zo={},ei={},ey;function nI(){if(ey)return ei;ey=1,Object.defineProperty(ei,"__esModule",{value:!0}),ei.MultipartBody=void 0;let e=class{constructor(n){this.body=n}get[Symbol.toStringTag](){return"MultipartBody"}};return ei.MultipartBody=e,ei}var ty;function rI(){if(ty)return Zo;ty=1,Object.defineProperty(Zo,"__esModule",{value:!0}),Zo.getRuntime=void 0;const e=nI();function t({manuallyImported:n}={}){const r=n?"You may need to use polyfills":"Add one of these imports before your first `import … from 'groq-sdk'`:\n- `import 'groq-sdk/shims/node'` (if you're running on Node)\n- `import 'groq-sdk/shims/web'` (otherwise)\n";let s,o,i,a;try{s=fetch,o=Request,i=Response,a=Headers}catch(l){throw new Error(`this environment is missing the following Web Fetch API type: ${l.message}. ${r}`)}return{kind:"web",fetch:s,Request:o,Response:i,Headers:a,FormData:typeof FormData<"u"?FormData:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${r}`)}},Blob:typeof Blob<"u"?Blob:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${r}`)}},File:typeof File<"u"?File:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${r}`)}},ReadableStream:typeof ReadableStream<"u"?ReadableStream:class{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${r}`)}},getMultipartRequestOptions:async(l,u)=>({...u,body:new e.MultipartBody(l)}),getDefaultAgent:l=>{},fileFromPath:()=>{throw new Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/groq/groq-typescript#file-uploads")},isFsReadStream:l=>!1}}return Zo.getRuntime=t,Zo}var ny;function sI(){return ny||(ny=1,(function(e){var t=tr&&tr.__createBinding||(Object.create?(function(r,s,o,i){i===void 0&&(i=o);var a=Object.getOwnPropertyDescriptor(s,o);(!a||("get"in a?!s.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return s[o]}}),Object.defineProperty(r,i,a)}):(function(r,s,o,i){i===void 0&&(i=o),r[i]=s[o]})),n=tr&&tr.__exportStar||function(r,s){for(var o in r)o!=="default"&&!Object.prototype.hasOwnProperty.call(s,o)&&t(s,r,o)};Object.defineProperty(e,"__esModule",{value:!0}),n(rI(),e)})(tr)),tr}var ry;function Aa(){return ry||(ry=1,(function(e){const t=tI,n=sI();e.init=()=>{t.kind||t.setShims(n.getRuntime(),{auto:!0})};for(const r of Object.keys(t))Object.defineProperty(e,r,{get(){return t[r]}});e.init()})(Mu)),Mu}var Re={},sy;function Pi(){if(sy)return Re;sy=1,Object.defineProperty(Re,"__esModule",{value:!0}),Re.InternalServerError=Re.RateLimitError=Re.UnprocessableEntityError=Re.ConflictError=Re.NotFoundError=Re.PermissionDeniedError=Re.AuthenticationError=Re.BadRequestError=Re.APIConnectionTimeoutError=Re.APIConnectionError=Re.APIUserAbortError=Re.APIError=Re.GroqError=void 0;const e=Li();class t extends Error{}Re.GroqError=t;class n extends t{constructor(_,b,m,v){super(`${n.makeMessage(_,b,m)}`),this.status=_,this.headers=v,this.error=b}static makeMessage(_,b,m){const v=b?.message?typeof b.message=="string"?b.message:JSON.stringify(b.message):b?JSON.stringify(b):m;return _&&v?`${_} ${v}`:_?`${_} status code (no body)`:v||"(no status code or body)"}static generate(_,b,m,v){if(!_||!v)return new s({message:m,cause:(0,e.castToError)(b)});const A=b;return _===400?new i(_,A,m,v):_===401?new a(_,A,m,v):_===403?new l(_,A,m,v):_===404?new u(_,A,m,v):_===409?new c(_,A,m,v):_===422?new d(_,A,m,v):_===429?new p(_,A,m,v):_>=500?new g(_,A,m,v):new n(_,A,m,v)}}Re.APIError=n;class r extends n{constructor({message:_}={}){super(void 0,void 0,_||"Request was aborted.",void 0)}}Re.APIUserAbortError=r;class s extends n{constructor({message:_,cause:b}){super(void 0,void 0,_||"Connection error.",void 0),b&&(this.cause=b)}}Re.APIConnectionError=s;class o extends s{constructor({message:_}={}){super({message:_??"Request timed out."})}}Re.APIConnectionTimeoutError=o;class i extends n{}Re.BadRequestError=i;class a extends n{}Re.AuthenticationError=a;class l extends n{}Re.PermissionDeniedError=l;class u extends n{}Re.NotFoundError=u;class c extends n{}Re.ConflictError=c;class d extends n{}Re.UnprocessableEntityError=d;class p extends n{}Re.RateLimitError=p;class g extends n{}return Re.InternalServerError=g,Re}var oy;function oI(){if(oy)return er;oy=1,Object.defineProperty(er,"__esModule",{value:!0}),er.readableStreamAsyncIterable=er.Stream=void 0;const e=Aa(),t=Pi(),n=Pi();class r{constructor(u,c){this.iterator=u,this.controller=c}static fromSSEResponse(u,c){let d=!1;const p=new s;async function*g(){if(!u.body)throw c.abort(),new t.GroqError("Attempted to iterate over a response with no body");const _=new o,b=a(u.body);for await(const m of b)for(const v of _.decode(m)){const A=p.decode(v);A&&(yield A)}for(const m of _.flush()){const v=p.decode(m);v&&(yield v)}}async function*y(){if(d)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");d=!0;let _=!1;try{for await(const b of g())if(!_){if(b.data.startsWith("[DONE]")){_=!0;continue}if(b.event===null||b.event==="error"){let m;try{m=JSON.parse(b.data)}catch(v){throw console.error("Could not parse message into JSON:",b.data),console.error("From chunk:",b.raw),v}if(m&&m.error)throw new n.APIError(m.error.status_code,m.error,m.error.message,void 0);yield m}}_=!0}catch(b){if(b instanceof Error&&b.name==="AbortError")return;throw b}finally{_||c.abort()}}return new r(y,c)}static fromReadableStream(u,c){let d=!1;async function*p(){const y=new o,_=a(u);for await(const b of _)for(const m of y.decode(b))yield m;for(const b of y.flush())yield b}async function*g(){if(d)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");d=!0;let y=!1;try{for await(const _ of p())y||_&&(yield JSON.parse(_));y=!0}catch(_){if(_ instanceof Error&&_.name==="AbortError")return;throw _}finally{y||c.abort()}}return new r(g,c)}[Symbol.asyncIterator](){return this.iterator()}tee(){const u=[],c=[],d=this.iterator(),p=g=>({next:()=>{if(g.length===0){const y=d.next();u.push(y),c.push(y)}return g.shift()}});return[new r(()=>p(u),this.controller),new r(()=>p(c),this.controller)]}toReadableStream(){const u=this;let c;const d=new TextEncoder;return new e.ReadableStream({async start(){c=u[Symbol.asyncIterator]()},async pull(p){try{const{value:g,done:y}=await c.next();if(y)return p.close();const _=d.encode(JSON.stringify(g)+`
77
- `);p.enqueue(_)}catch(g){p.error(g)}},async cancel(){await c.return?.()}})}}er.Stream=r;class s{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(u){if(u.endsWith("\r")&&(u=u.substring(0,u.length-1)),!u){if(!this.event&&!this.data.length)return null;const g={event:this.event,data:this.data.join(`
78
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],g}if(this.chunks.push(u),u.startsWith(":"))return null;let[c,d,p]=i(u,":");return p.startsWith(" ")&&(p=p.substring(1)),c==="event"?this.event=p:c==="data"&&this.data.push(p),null}}class o{constructor(){this.buffer=[],this.trailingCR=!1}decode(u){let c=this.decodeText(u);if(this.trailingCR&&(c="\r"+c,this.trailingCR=!1),c.endsWith("\r")&&(this.trailingCR=!0,c=c.slice(0,-1)),!c)return[];const d=o.NEWLINE_CHARS.has(c[c.length-1]||"");let p=c.split(o.NEWLINE_REGEXP);return p.length===1&&!d?(this.buffer.push(p[0]),[]):(this.buffer.length>0&&(p=[this.buffer.join("")+p[0],...p.slice(1)],this.buffer=[]),d||(this.buffer=[p.pop()||""]),p)}decodeText(u){if(u==null)return"";if(typeof u=="string")return u;if(typeof Buffer<"u"){if(u instanceof Buffer)return u.toString();if(u instanceof Uint8Array)return Buffer.from(u).toString();throw new t.GroqError(`Unexpected: received non-Uint8Array (${u.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if(typeof TextDecoder<"u"){if(u instanceof Uint8Array||u instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(u);throw new t.GroqError(`Unexpected: received non-Uint8Array/ArrayBuffer (${u.constructor.name}) in a web platform. Please report this error.`)}throw new t.GroqError("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length&&!this.trailingCR)return[];const u=[this.buffer.join("")];return this.buffer=[],this.trailingCR=!1,u}}o.NEWLINE_CHARS=new Set([`
79
- `,"\r","\v","\f","","","","…","\u2028","\u2029"]),o.NEWLINE_REGEXP=/\r\n|[\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029]/g;function i(l,u){const c=l.indexOf(u);return c!==-1?[l.substring(0,c),u,l.substring(c+u.length)]:[l,"",""]}function a(l){if(l[Symbol.asyncIterator])return l;const u=l.getReader();return{async next(){try{const c=await u.read();return c?.done&&u.releaseLock(),c}catch(c){throw u.releaseLock(),c}},async return(){const c=u.cancel();return u.releaseLock(),await c,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}return er.readableStreamAsyncIterable=a,er}var Nu={},iy;function Sa(){return iy||(iy=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.createForm=e.multipartFormRequestOptions=e.maybeMultipartFormRequestOptions=e.isMultipartBody=e.toFile=e.isUploadable=e.isBlobLike=e.isFileLike=e.isResponseLike=e.fileFromPath=void 0;const t=Aa();var n=Aa();Object.defineProperty(e,"fileFromPath",{enumerable:!0,get:function(){return n.fileFromPath}});const r=A=>A!=null&&typeof A=="object"&&typeof A.url=="string"&&typeof A.blob=="function";e.isResponseLike=r;const s=A=>A!=null&&typeof A=="object"&&typeof A.name=="string"&&typeof A.lastModified=="number"&&(0,e.isBlobLike)(A);e.isFileLike=s;const o=A=>A!=null&&typeof A=="object"&&typeof A.size=="number"&&typeof A.type=="string"&&typeof A.text=="function"&&typeof A.slice=="function"&&typeof A.arrayBuffer=="function";e.isBlobLike=o;const i=A=>(0,e.isFileLike)(A)||(0,e.isResponseLike)(A)||(0,t.isFsReadStream)(A);e.isUploadable=i;async function a(A,S,P){if(A=await A,(0,e.isFileLike)(A))return A;if((0,e.isResponseLike)(A)){const w=await A.blob();S||(S=new URL(A.url).pathname.split(/[\\/]/).pop()??"unknown_file");const I=(0,e.isBlobLike)(w)?[await w.arrayBuffer()]:[w];return new t.File(I,S,P)}const E=await l(A);if(S||(S=c(A)??"unknown_file"),!P?.type){const w=E[0]?.type;typeof w=="string"&&(P={...P,type:w})}return new t.File(E,S,P)}e.toFile=a;async function l(A){let S=[];if(typeof A=="string"||ArrayBuffer.isView(A)||A instanceof ArrayBuffer)S.push(A);else if((0,e.isBlobLike)(A))S.push(await A.arrayBuffer());else if(p(A))for await(const P of A)S.push(P);else throw new Error(`Unexpected data type: ${typeof A}; constructor: ${A?.constructor?.name}; props: ${u(A)}`);return S}function u(A){return`[${Object.getOwnPropertyNames(A).map(P=>`"${P}"`).join(", ")}]`}function c(A){return d(A.name)||d(A.filename)||d(A.path)?.split(/[\\/]/).pop()}const d=A=>{if(typeof A=="string")return A;if(typeof Buffer<"u"&&A instanceof Buffer)return String(A)},p=A=>A!=null&&typeof A=="object"&&typeof A[Symbol.asyncIterator]=="function",g=A=>A&&typeof A=="object"&&A.body&&A[Symbol.toStringTag]==="MultipartBody";e.isMultipartBody=g;const y=async A=>{if(!m(A.body))return A;const S=await(0,e.createForm)(A.body);return(0,t.getMultipartRequestOptions)(S,A)};e.maybeMultipartFormRequestOptions=y;const _=async A=>{const S=await(0,e.createForm)(A.body);return(0,t.getMultipartRequestOptions)(S,A)};e.multipartFormRequestOptions=_;const b=async A=>{const S=new t.FormData;return await Promise.all(Object.entries(A||{}).map(([P,E])=>v(S,P,E))),S};e.createForm=b;const m=A=>{if((0,e.isUploadable)(A))return!0;if(Array.isArray(A))return A.some(m);if(A&&typeof A=="object"){for(const S in A)if(m(A[S]))return!0}return!1},v=async(A,S,P)=>{if(P!==void 0){if(P==null)throw new TypeError(`Received null for "${S}"; to pass null in FormData, you must use the string 'null'`);if(typeof P=="string"||typeof P=="number"||typeof P=="boolean")A.append(S,String(P));else if((0,e.isUploadable)(P)){const E=await a(P);A.append(S,E)}else if(Array.isArray(P))await Promise.all(P.map(E=>v(A,S+"[]",E)));else if(typeof P=="object")await Promise.all(Object.entries(P).map(([E,w])=>v(A,`${S}[${E}]`,w)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${P} instead`)}}})(Nu)),Nu}var ay;function Li(){return ay||(ay=1,(function(e){var t={},n=Zn&&Zn.__classPrivateFieldSet||function(x,N,q,J,K){if(J==="m")throw new TypeError("Private method is not writable");if(J==="a"&&!K)throw new TypeError("Private accessor was defined without a setter");if(typeof N=="function"?x!==N||!K:!N.has(x))throw new TypeError("Cannot write private member to an object whose class did not declare it");return J==="a"?K.call(x,q):K?K.value=q:N.set(x,q),q},r=Zn&&Zn.__classPrivateFieldGet||function(x,N,q,J){if(q==="a"&&!J)throw new TypeError("Private accessor was defined without a getter");if(typeof N=="function"?x!==N||!J:!N.has(x))throw new TypeError("Cannot read private member from an object whose class did not declare it");return q==="m"?J:q==="a"?J.call(x):J?J.value:N.get(x)},s,o;Object.defineProperty(e,"__esModule",{value:!0}),e.isObj=e.toBase64=e.getHeader=e.getRequiredHeader=e.isHeadersProtocol=e.isRunningInBrowser=e.debug=e.hasOwn=e.isEmptyObj=e.maybeCoerceBoolean=e.maybeCoerceFloat=e.maybeCoerceInteger=e.coerceBoolean=e.coerceFloat=e.coerceInteger=e.readEnv=e.ensurePresent=e.castToError=e.sleep=e.safeJSON=e.isRequestOptions=e.createResponseHeaders=e.PagePromise=e.AbstractPage=e.APIClient=e.APIPromise=e.createForm=e.multipartFormRequestOptions=e.maybeMultipartFormRequestOptions=void 0;const i=QP(),a=oI(),l=Pi(),u=Aa();(0,u.init)();const c=Sa();var d=Sa();Object.defineProperty(e,"maybeMultipartFormRequestOptions",{enumerable:!0,get:function(){return d.maybeMultipartFormRequestOptions}}),Object.defineProperty(e,"multipartFormRequestOptions",{enumerable:!0,get:function(){return d.multipartFormRequestOptions}}),Object.defineProperty(e,"createForm",{enumerable:!0,get:function(){return d.createForm}});async function p(x){const{response:N}=x;if(x.options.stream)return re("response",N.status,N.url,N.headers,N.body),x.options.__streamClass?x.options.__streamClass.fromSSEResponse(N,x.controller):a.Stream.fromSSEResponse(N,x.controller);if(N.status===204)return null;if(x.options.__binaryResponse)return N;const J=N.headers.get("content-type")?.split(";")[0]?.trim();if(J?.includes("application/json")||J?.endsWith("+json")){const z=await N.json();return re("response",N.status,N.url,N.headers,z),z}const Q=await N.text();return re("response",N.status,N.url,N.headers,Q),Q}class g extends Promise{constructor(N,q=p){super(J=>{J(null)}),this.responsePromise=N,this.parseResponse=q}_thenUnwrap(N){return new g(this.responsePromise,async q=>N(await this.parseResponse(q),q))}asResponse(){return this.responsePromise.then(N=>N.response)}async withResponse(){const[N,q]=await Promise.all([this.parse(),this.asResponse()]);return{data:N,response:q}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),this.parsedPromise}then(N,q){return this.parse().then(N,q)}catch(N){return this.parse().catch(N)}finally(N){return this.parse().finally(N)}}e.APIPromise=g;class y{constructor({baseURL:N,baseURLOverridden:q,maxRetries:J=2,timeout:K=6e4,httpAgent:Q,fetch:z}){s.set(this,void 0),this.baseURL=N,n(this,s,q,"f"),this.maxRetries=U("maxRetries",J),this.timeout=U("timeout",K),this.httpAgent=Q,this.fetch=z??u.fetch}authHeaders(N){return{}}defaultHeaders(N){return{Accept:"application/json",...["head","get"].includes(N.method)?{}:{"Content-Type":"application/json"},"User-Agent":this.getUserAgent(),...L(),...this.authHeaders(N)}}validateHeaders(N,q){}defaultIdempotencyKey(){return`stainless-node-retry-${Ae()}`}get(N,q){return this.methodRequest("get",N,q)}post(N,q){return this.methodRequest("post",N,q)}patch(N,q){return this.methodRequest("patch",N,q)}put(N,q){return this.methodRequest("put",N,q)}delete(N,q){return this.methodRequest("delete",N,q)}methodRequest(N,q,J){return this.request(Promise.resolve(J).then(async K=>{const Q=K&&(0,c.isBlobLike)(K?.body)?new DataView(await K.body.arrayBuffer()):K?.body instanceof DataView?K.body:K?.body instanceof ArrayBuffer?new DataView(K.body):K&&ArrayBuffer.isView(K?.body)?new DataView(K.body.buffer):K?.body;return{method:N,path:q,...K,body:Q}}))}getAPIList(N,q,J){return this.requestAPIList(q,{method:"get",path:N,...J})}calculateContentLength(N){if(typeof N=="string"){if(typeof Buffer<"u")return Buffer.byteLength(N,"utf8").toString();if(typeof TextEncoder<"u")return new TextEncoder().encode(N).length.toString()}else if(ArrayBuffer.isView(N))return N.byteLength.toString();return null}async buildRequest(N,{retryCount:q=0}={}){const J={...N},{method:K,path:Q,query:z,defaultBaseURL:ae,headers:te={}}=J,se=ArrayBuffer.isView(J.body)||J.__binaryRequest&&typeof J.body=="string"?J.body:(0,c.isMultipartBody)(J.body)?J.body.body:J.body?JSON.stringify(J.body,null,2):null,de=this.calculateContentLength(se),_e=this.buildURL(Q,z,ae);"timeout"in J&&U("timeout",J.timeout),J.timeout=J.timeout??this.timeout;const ge=J.httpAgent??this.httpAgent??(0,u.getDefaultAgent)(_e),pe=J.timeout+1e3;typeof ge?.options?.timeout=="number"&&pe>(ge.options.timeout??0)&&(ge.options.timeout=pe),this.idempotencyHeader&&K!=="get"&&(N.idempotencyKey||(N.idempotencyKey=this.defaultIdempotencyKey()),te[this.idempotencyHeader]=N.idempotencyKey);const Le=this.buildHeaders({options:J,headers:te,contentLength:de,retryCount:q});return{req:{method:K,...se&&{body:se},headers:Le,...ge&&{agent:ge},signal:J.signal??null},url:_e,timeout:J.timeout}}buildHeaders({options:N,headers:q,contentLength:J,retryCount:K}){const Q={};J&&(Q["content-length"]=J);const z=this.defaultHeaders(N);return ne(Q,z),ne(Q,q),(0,c.isMultipartBody)(N.body)&&u.kind!=="node"&&delete Q["content-type"],(0,e.getHeader)(z,"x-stainless-retry-count")===void 0&&(0,e.getHeader)(q,"x-stainless-retry-count")===void 0&&(Q["x-stainless-retry-count"]=String(K)),(0,e.getHeader)(z,"x-stainless-timeout")===void 0&&(0,e.getHeader)(q,"x-stainless-timeout")===void 0&&N.timeout&&(Q["x-stainless-timeout"]=String(Math.trunc(N.timeout/1e3))),this.validateHeaders(Q,q),Q}async prepareOptions(N){}async prepareRequest(N,{url:q,options:J}){}parseHeaders(N){return N?Symbol.iterator in N?Object.fromEntries(Array.from(N).map(q=>[...q])):{...N}:{}}makeStatusError(N,q,J,K){return l.APIError.generate(N,q,J,K)}request(N,q=null){return new g(this.makeRequest(N,q))}async makeRequest(N,q){const J=await N,K=J.maxRetries??this.maxRetries;q==null&&(q=K),await this.prepareOptions(J);const{req:Q,url:z,timeout:ae}=await this.buildRequest(J,{retryCount:K-q});if(await this.prepareRequest(Q,{url:z,options:J}),re("request",z,J,Q.headers),J.signal?.aborted)throw new l.APIUserAbortError;const te=new AbortController,se=await this.fetchWithTimeout(z,Q,ae,te).catch(e.castToError);if(se instanceof Error){if(J.signal?.aborted)throw new l.APIUserAbortError;if(q)return this.retryRequest(J,q);throw se.name==="AbortError"?new l.APIConnectionTimeoutError:new l.APIConnectionError({cause:se})}const de=(0,e.createResponseHeaders)(se.headers);if(!se.ok){if(q&&this.shouldRetry(se)){const je=`retrying, ${q} attempts remaining`;return re(`response (error; ${je})`,se.status,z,de),this.retryRequest(J,q,de)}const _e=await se.text().catch(je=>(0,e.castToError)(je).message),ge=(0,e.safeJSON)(_e),pe=ge?void 0:_e;throw re(`response (error; ${q?"(error; no more retries left)":"(error; not retryable)"})`,se.status,z,de,pe),this.makeStatusError(se.status,ge,pe,de)}return{response:se,options:J,controller:te}}requestAPIList(N,q){const J=this.makeRequest(q,null);return new b(this,J,N)}buildURL(N,q,J){const K=!r(this,s,"f")&&J||this.baseURL,Q=F(N)?new URL(N):new URL(K+(K.endsWith("/")&&N.startsWith("/")?N.slice(1):N)),z=this.defaultQuery();return Y(z)||(q={...z,...q}),typeof q=="object"&&q&&!Array.isArray(q)&&(Q.search=this.stringifyQuery(q)),Q.toString()}stringifyQuery(N){return Object.entries(N).filter(([q,J])=>typeof J<"u").map(([q,J])=>{if(typeof J=="string"||typeof J=="number"||typeof J=="boolean")return`${encodeURIComponent(q)}=${encodeURIComponent(J)}`;if(J===null)return`${encodeURIComponent(q)}=`;throw new l.GroqError(`Cannot stringify type ${typeof J}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}async fetchWithTimeout(N,q,J,K){const{signal:Q,...z}=q||{};Q&&Q.addEventListener("abort",()=>K.abort());const ae=setTimeout(()=>K.abort(),J),te={signal:K.signal,...z};return te.method&&(te.method=te.method.toUpperCase()),this.fetch.call(void 0,N,te).finally(()=>{clearTimeout(ae)})}shouldRetry(N){const q=N.headers.get("x-should-retry");return q==="true"?!0:q==="false"?!1:N.status===408||N.status===409||N.status===429||N.status>=500}async retryRequest(N,q,J){let K;const Q=J?.["retry-after-ms"];if(Q){const ae=parseFloat(Q);Number.isNaN(ae)||(K=ae)}const z=J?.["retry-after"];if(z&&!K){const ae=parseFloat(z);Number.isNaN(ae)?K=Date.parse(z)-Date.now():K=ae*1e3}if(!(K&&0<=K&&K<60*1e3)){const ae=N.maxRetries??this.maxRetries;K=this.calculateDefaultRetryTimeoutMillis(q,ae)}return await(0,e.sleep)(K),this.makeRequest(N,q-1)}calculateDefaultRetryTimeoutMillis(N,q){const Q=q-N,z=Math.min(.5*Math.pow(2,Q),8),ae=1-Math.random()*.25;return z*ae*1e3}getUserAgent(){return`${this.constructor.name}/JS ${i.VERSION}`}}e.APIClient=y,s=new WeakMap;class _{constructor(N,q,J,K){o.set(this,void 0),n(this,o,N,"f"),this.options=K,this.response=q,this.body=J}hasNextPage(){return this.getPaginatedItems().length?this.nextPageInfo()!=null:!1}async getNextPage(){const N=this.nextPageInfo();if(!N)throw new l.GroqError("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");const q={...this.options};if("params"in N&&typeof q.query=="object")q.query={...q.query,...N.params};else if("url"in N){const J=[...Object.entries(q.query||{}),...N.url.searchParams.entries()];for(const[K,Q]of J)N.url.searchParams.set(K,Q);q.query=void 0,q.path=N.url.toString()}return await r(this,o,"f").requestAPIList(this.constructor,q)}async*iterPages(){let N=this;for(yield N;N.hasNextPage();)N=await N.getNextPage(),yield N}async*[(o=new WeakMap,Symbol.asyncIterator)](){for await(const N of this.iterPages())for(const q of N.getPaginatedItems())yield q}}e.AbstractPage=_;class b extends g{constructor(N,q,J){super(q,async K=>new J(N,K.response,await p(K),K.options))}async*[Symbol.asyncIterator](){const N=await this;for await(const q of N)yield q}}e.PagePromise=b;const m=x=>new Proxy(Object.fromEntries(x.entries()),{get(N,q){const J=q.toString();return N[J.toLowerCase()]||N[J]}});e.createResponseHeaders=m;const v={method:!0,path:!0,query:!0,body:!0,headers:!0,defaultBaseURL:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},A=x=>typeof x=="object"&&x!==null&&!Y(x)&&Object.keys(x).every(N=>Z(v,N));e.isRequestOptions=A;const S=()=>{if(typeof Deno<"u"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":i.VERSION,"X-Stainless-OS":w(Deno.build.os),"X-Stainless-Arch":E(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":i.VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if(Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":i.VERSION,"X-Stainless-OS":w(process.platform),"X-Stainless-Arch":E(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};const x=P();return x?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":i.VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${x.browser}`,"X-Stainless-Runtime-Version":x.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":i.VERSION,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function P(){if(typeof navigator>"u"||!navigator)return null;const x=[{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:N,pattern:q}of x){const J=q.exec(navigator.userAgent);if(J){const K=J[1]||0,Q=J[2]||0,z=J[3]||0;return{browser:N,version:`${K}.${Q}.${z}`}}}return null}const E=x=>x==="x32"?"x32":x==="x86_64"||x==="x64"?"x64":x==="arm"?"arm":x==="aarch64"||x==="arm64"?"arm64":x?`other:${x}`:"unknown",w=x=>(x=x.toLowerCase(),x.includes("ios")?"iOS":x==="android"?"Android":x==="darwin"?"MacOS":x==="win32"?"Windows":x==="freebsd"?"FreeBSD":x==="openbsd"?"OpenBSD":x==="linux"?"Linux":x?`Other:${x}`:"Unknown");let I;const L=()=>I??(I=S()),H=x=>{try{return JSON.parse(x)}catch{return}};e.safeJSON=H;const B=/^[a-z][a-z0-9+.-]*:/i,F=x=>B.test(x),j=x=>new Promise(N=>setTimeout(N,x));e.sleep=j;const U=(x,N)=>{if(typeof N!="number"||!Number.isInteger(N))throw new l.GroqError(`${x} must be an integer`);if(N<0)throw new l.GroqError(`${x} must be a positive integer`);return N},O=x=>{if(x instanceof Error)return x;if(typeof x=="object"&&x!==null)try{return new Error(JSON.stringify(x))}catch{}return new Error(x)};e.castToError=O;const R=x=>{if(x==null)throw new l.GroqError(`Expected a value to be given but received ${x} instead.`);return x};e.ensurePresent=R;const T=x=>{if(typeof process<"u")return t?.[x]?.trim()??void 0;if(typeof Deno<"u")return Deno.env?.get?.(x)?.trim()};e.readEnv=T;const M=x=>{if(typeof x=="number")return Math.round(x);if(typeof x=="string")return parseInt(x,10);throw new l.GroqError(`Could not coerce ${x} (type: ${typeof x}) into a number`)};e.coerceInteger=M;const k=x=>{if(typeof x=="number")return x;if(typeof x=="string")return parseFloat(x);throw new l.GroqError(`Could not coerce ${x} (type: ${typeof x}) into a number`)};e.coerceFloat=k;const G=x=>typeof x=="boolean"?x:typeof x=="string"?x==="true":!!x;e.coerceBoolean=G;const V=x=>{if(x!==void 0)return(0,e.coerceInteger)(x)};e.maybeCoerceInteger=V;const W=x=>{if(x!==void 0)return(0,e.coerceFloat)(x)};e.maybeCoerceFloat=W;const X=x=>{if(x!==void 0)return(0,e.coerceBoolean)(x)};e.maybeCoerceBoolean=X;function Y(x){if(!x)return!0;for(const N in x)return!1;return!0}e.isEmptyObj=Y;function Z(x,N){return Object.prototype.hasOwnProperty.call(x,N)}e.hasOwn=Z;function ne(x,N){for(const q in N){if(!Z(N,q))continue;const J=q.toLowerCase();if(!J)continue;const K=N[q];K===null?delete x[J]:K!==void 0&&(x[J]=K)}}function re(x,...N){typeof process<"u"&&t?.DEBUG==="true"&&console.log(`Groq:DEBUG:${x}`,...N)}e.debug=re;const Ae=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,x=>{const N=Math.random()*16|0;return(x==="x"?N:N&3|8).toString(16)}),le=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";e.isRunningInBrowser=le;const we=x=>typeof x?.get=="function";e.isHeadersProtocol=we;const ee=(x,N)=>{const q=(0,e.getHeader)(x,N);if(q===void 0)throw new Error(`Could not find ${N} header`);return q};e.getRequiredHeader=ee;const C=(x,N)=>{const q=N.toLowerCase();if((0,e.isHeadersProtocol)(x)){const J=N[0]?.toUpperCase()+N.substring(1).replace(/([^\w])(\w)/g,(K,Q,z)=>Q+z.toUpperCase());for(const K of[N,q,N.toUpperCase(),J]){const Q=x.get(K);if(Q)return Q}}for(const[J,K]of Object.entries(x))if(J.toLowerCase()===q)return Array.isArray(K)?(K.length<=1||console.warn(`Received ${K.length} entries for the ${N} header, using the first entry.`),K[0]):K};e.getHeader=C;const D=x=>{if(!x)return"";if(typeof Buffer<"u")return Buffer.from(x).toString("base64");if(typeof btoa<"u")return btoa(x);throw new l.GroqError("Cannot generate b64 string; Expected `Buffer` or `btoa` to be defined")};e.toBase64=D;function $(x){return x!=null&&typeof x=="object"&&!Array.isArray(x)}e.isObj=$})(Zn)),Zn}var nr={},Fu={},ly;function iI(){return ly||(ly=1,Object.defineProperty(Fu,"__esModule",{value:!0})),Fu}var Et={},ti={},uy;function Ut(){if(uy)return ti;uy=1,Object.defineProperty(ti,"__esModule",{value:!0}),ti.APIResource=void 0;class e{constructor(n){this._client=n}}return ti.APIResource=e,ti}var ni={},cy;function dy(){if(cy)return ni;cy=1,Object.defineProperty(ni,"__esModule",{value:!0}),ni.Speech=void 0;const e=Ut();class t extends e.APIResource{create(r,s){return this._client.post("/openai/v1/audio/speech",{body:r,...s,headers:{Accept:"audio/wav",...s?.headers},__binaryResponse:!0})}}return ni.Speech=t,ni}var Tt={},fy;function py(){if(fy)return Tt;fy=1;var e=Tt&&Tt.__createBinding||(Object.create?(function(i,a,l,u){u===void 0&&(u=l);var c=Object.getOwnPropertyDescriptor(a,l);(!c||("get"in c?!a.__esModule:c.writable||c.configurable))&&(c={enumerable:!0,get:function(){return a[l]}}),Object.defineProperty(i,u,c)}):(function(i,a,l,u){u===void 0&&(u=l),i[u]=a[l]})),t=Tt&&Tt.__setModuleDefault||(Object.create?(function(i,a){Object.defineProperty(i,"default",{enumerable:!0,value:a})}):function(i,a){i.default=a}),n=Tt&&Tt.__importStar||function(i){if(i&&i.__esModule)return i;var a={};if(i!=null)for(var l in i)l!=="default"&&Object.prototype.hasOwnProperty.call(i,l)&&e(a,i,l);return t(a,i),a};Object.defineProperty(Tt,"__esModule",{value:!0}),Tt.Transcriptions=void 0;const r=Ut(),s=n(Li());class o extends r.APIResource{create(a,l){return this._client.post("/openai/v1/audio/transcriptions",s.multipartFormRequestOptions({body:a,...l}))}}return Tt.Transcriptions=o,Tt}var Pt={},hy;function gy(){if(hy)return Pt;hy=1;var e=Pt&&Pt.__createBinding||(Object.create?(function(i,a,l,u){u===void 0&&(u=l);var c=Object.getOwnPropertyDescriptor(a,l);(!c||("get"in c?!a.__esModule:c.writable||c.configurable))&&(c={enumerable:!0,get:function(){return a[l]}}),Object.defineProperty(i,u,c)}):(function(i,a,l,u){u===void 0&&(u=l),i[u]=a[l]})),t=Pt&&Pt.__setModuleDefault||(Object.create?(function(i,a){Object.defineProperty(i,"default",{enumerable:!0,value:a})}):function(i,a){i.default=a}),n=Pt&&Pt.__importStar||function(i){if(i&&i.__esModule)return i;var a={};if(i!=null)for(var l in i)l!=="default"&&Object.prototype.hasOwnProperty.call(i,l)&&e(a,i,l);return t(a,i),a};Object.defineProperty(Pt,"__esModule",{value:!0}),Pt.Translations=void 0;const r=Ut(),s=n(Li());class o extends r.APIResource{create(a,l){return this._client.post("/openai/v1/audio/translations",s.multipartFormRequestOptions({body:a,...l}))}}return Pt.Translations=o,Pt}var my;function P0(){if(my)return Et;my=1;var e=Et&&Et.__createBinding||(Object.create?(function(d,p,g,y){y===void 0&&(y=g);var _=Object.getOwnPropertyDescriptor(p,g);(!_||("get"in _?!p.__esModule:_.writable||_.configurable))&&(_={enumerable:!0,get:function(){return p[g]}}),Object.defineProperty(d,y,_)}):(function(d,p,g,y){y===void 0&&(y=g),d[y]=p[g]})),t=Et&&Et.__setModuleDefault||(Object.create?(function(d,p){Object.defineProperty(d,"default",{enumerable:!0,value:p})}):function(d,p){d.default=p}),n=Et&&Et.__importStar||function(d){if(d&&d.__esModule)return d;var p={};if(d!=null)for(var g in d)g!=="default"&&Object.prototype.hasOwnProperty.call(d,g)&&e(p,d,g);return t(p,d),p};Object.defineProperty(Et,"__esModule",{value:!0}),Et.Audio=void 0;const r=Ut(),s=n(dy()),o=dy(),i=n(py()),a=py(),l=n(gy()),u=gy();class c extends r.APIResource{constructor(){super(...arguments),this.speech=new s.Speech(this._client),this.transcriptions=new i.Transcriptions(this._client),this.translations=new l.Translations(this._client)}}return Et.Audio=c,c.Speech=o.Speech,c.Transcriptions=a.Transcriptions,c.Translations=u.Translations,Et}var ri={},_y;function I0(){if(_y)return ri;_y=1,Object.defineProperty(ri,"__esModule",{value:!0}),ri.Batches=void 0;const e=Ut();class t extends e.APIResource{create(r,s){return this._client.post("/openai/v1/batches",{body:r,...s})}retrieve(r,s){return this._client.get(`/openai/v1/batches/${r}`,s)}list(r){return this._client.get("/openai/v1/batches",r)}cancel(r,s){return this._client.post(`/openai/v1/batches/${r}/cancel`,s)}}return ri.Batches=t,ri}var It={},si={},yy;function vy(){if(yy)return si;yy=1,Object.defineProperty(si,"__esModule",{value:!0}),si.Completions=void 0;const e=Ut();class t extends e.APIResource{create(r,s){return this._client.post("/openai/v1/chat/completions",{body:r,...s,stream:r.stream??!1})}}return si.Completions=t,si}var by;function C0(){if(by)return It;by=1;var e=It&&It.__createBinding||(Object.create?(function(a,l,u,c){c===void 0&&(c=u);var d=Object.getOwnPropertyDescriptor(l,u);(!d||("get"in d?!l.__esModule:d.writable||d.configurable))&&(d={enumerable:!0,get:function(){return l[u]}}),Object.defineProperty(a,c,d)}):(function(a,l,u,c){c===void 0&&(c=u),a[c]=l[u]})),t=It&&It.__setModuleDefault||(Object.create?(function(a,l){Object.defineProperty(a,"default",{enumerable:!0,value:l})}):function(a,l){a.default=l}),n=It&&It.__importStar||function(a){if(a&&a.__esModule)return a;var l={};if(a!=null)for(var u in a)u!=="default"&&Object.prototype.hasOwnProperty.call(a,u)&&e(l,a,u);return t(l,a),l};Object.defineProperty(It,"__esModule",{value:!0}),It.Chat=void 0;const r=Ut(),s=n(vy()),o=vy();class i extends r.APIResource{constructor(){super(...arguments),this.completions=new s.Completions(this._client)}}return It.Chat=i,i.Completions=o.Completions,It}var oi={},Ay;function R0(){if(Ay)return oi;Ay=1,Object.defineProperty(oi,"__esModule",{value:!0}),oi.Completions=void 0;const e=Ut();class t extends e.APIResource{}return oi.Completions=t,oi}var ii={},Sy;function M0(){if(Sy)return ii;Sy=1,Object.defineProperty(ii,"__esModule",{value:!0}),ii.Embeddings=void 0;const e=Ut();class t extends e.APIResource{create(r,s){return this._client.post("/openai/v1/embeddings",{body:r,...s})}}return ii.Embeddings=t,ii}var Ct={},wy;function N0(){if(wy)return Ct;wy=1;var e=Ct&&Ct.__createBinding||(Object.create?(function(i,a,l,u){u===void 0&&(u=l);var c=Object.getOwnPropertyDescriptor(a,l);(!c||("get"in c?!a.__esModule:c.writable||c.configurable))&&(c={enumerable:!0,get:function(){return a[l]}}),Object.defineProperty(i,u,c)}):(function(i,a,l,u){u===void 0&&(u=l),i[u]=a[l]})),t=Ct&&Ct.__setModuleDefault||(Object.create?(function(i,a){Object.defineProperty(i,"default",{enumerable:!0,value:a})}):function(i,a){i.default=a}),n=Ct&&Ct.__importStar||function(i){if(i&&i.__esModule)return i;var a={};if(i!=null)for(var l in i)l!=="default"&&Object.prototype.hasOwnProperty.call(i,l)&&e(a,i,l);return t(a,i),a};Object.defineProperty(Ct,"__esModule",{value:!0}),Ct.Files=void 0;const r=Ut(),s=n(Li());class o extends r.APIResource{create(a,l){return this._client.post("/openai/v1/files",s.multipartFormRequestOptions({body:a,...l}))}list(a){return this._client.get("/openai/v1/files",a)}delete(a,l){return this._client.delete(`/openai/v1/files/${a}`,l)}content(a,l){return this._client.get(`/openai/v1/files/${a}/content`,{...l,headers:{Accept:"application/octet-stream",...l?.headers},__binaryResponse:!0})}info(a,l){return this._client.get(`/openai/v1/files/${a}`,l)}}return Ct.Files=o,Ct}var ai={},Ey;function F0(){if(Ey)return ai;Ey=1,Object.defineProperty(ai,"__esModule",{value:!0}),ai.Models=void 0;const e=Ut();class t extends e.APIResource{retrieve(r,s){return this._client.get(`/openai/v1/models/${r}`,s)}list(r){return this._client.get("/openai/v1/models",r)}delete(r,s){return this._client.delete(`/openai/v1/models/${r}`,s)}}return ai.Models=t,ai}var Ty;function aI(){return Ty||(Ty=1,(function(e){var t=nr&&nr.__createBinding||(Object.create?(function(c,d,p,g){g===void 0&&(g=p);var y=Object.getOwnPropertyDescriptor(d,p);(!y||("get"in y?!d.__esModule:y.writable||y.configurable))&&(y={enumerable:!0,get:function(){return d[p]}}),Object.defineProperty(c,g,y)}):(function(c,d,p,g){g===void 0&&(g=p),c[g]=d[p]})),n=nr&&nr.__exportStar||function(c,d){for(var p in c)p!=="default"&&!Object.prototype.hasOwnProperty.call(d,p)&&t(d,c,p)};Object.defineProperty(e,"__esModule",{value:!0}),e.Models=e.Files=e.Embeddings=e.Completions=e.Chat=e.Batches=e.Audio=void 0,n(iI(),e);var r=P0();Object.defineProperty(e,"Audio",{enumerable:!0,get:function(){return r.Audio}});var s=I0();Object.defineProperty(e,"Batches",{enumerable:!0,get:function(){return s.Batches}});var o=C0();Object.defineProperty(e,"Chat",{enumerable:!0,get:function(){return o.Chat}});var i=R0();Object.defineProperty(e,"Completions",{enumerable:!0,get:function(){return i.Completions}});var a=M0();Object.defineProperty(e,"Embeddings",{enumerable:!0,get:function(){return a.Embeddings}});var l=N0();Object.defineProperty(e,"Files",{enumerable:!0,get:function(){return l.Files}});var u=F0();Object.defineProperty(e,"Models",{enumerable:!0,get:function(){return u.Models}})})(nr)),nr}var Er=ci.exports,Py;function lI(){return Py||(Py=1,(function(e,t){var n=Er&&Er.__createBinding||(Object.create?(function(P,E,w,I){I===void 0&&(I=w);var L=Object.getOwnPropertyDescriptor(E,w);(!L||("get"in L?!E.__esModule:L.writable||L.configurable))&&(L={enumerable:!0,get:function(){return E[w]}}),Object.defineProperty(P,I,L)}):(function(P,E,w,I){I===void 0&&(I=w),P[I]=E[w]})),r=Er&&Er.__setModuleDefault||(Object.create?(function(P,E){Object.defineProperty(P,"default",{enumerable:!0,value:E})}):function(P,E){P.default=E}),s=Er&&Er.__importStar||function(P){if(P&&P.__esModule)return P;var E={};if(P!=null)for(var w in P)w!=="default"&&Object.prototype.hasOwnProperty.call(P,w)&&n(E,P,w);return r(E,P),E},o,i;Object.defineProperty(t,"__esModule",{value:!0}),t.UnprocessableEntityError=t.PermissionDeniedError=t.InternalServerError=t.AuthenticationError=t.BadRequestError=t.RateLimitError=t.ConflictError=t.NotFoundError=t.APIUserAbortError=t.APIConnectionTimeoutError=t.APIConnectionError=t.APIError=t.GroqError=t.fileFromPath=t.toFile=t.Groq=void 0;const a=s(Li()),l=s(Pi()),u=s(Sa()),c=s(aI()),d=I0(),p=R0(),g=M0(),y=N0(),_=F0(),b=P0(),m=C0();class v extends a.APIClient{constructor({baseURL:E=a.readEnv("GROQ_BASE_URL"),apiKey:w=a.readEnv("GROQ_API_KEY"),...I}={}){if(w===void 0)throw new l.GroqError("The GROQ_API_KEY environment variable is missing or empty; either provide it, or instantiate the Groq client with an apiKey option, like new Groq({ apiKey: 'My API Key' }).");const L={apiKey:w,...I,baseURL:E||"https://api.groq.com"};if(!L.dangerouslyAllowBrowser&&a.isRunningInBrowser())throw new l.GroqError(`It looks like you're running in a browser-like environment.
80
-
81
- This is disabled by default, as it risks exposing your secret API credentials to attackers.
82
- If you understand the risks and have appropriate mitigations in place,
83
- you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
84
-
85
- new Groq({ apiKey, dangerouslyAllowBrowser: true })`);super({baseURL:L.baseURL,baseURLOverridden:E?E!=="https://api.groq.com":!1,timeout:L.timeout??6e4,httpAgent:L.httpAgent,maxRetries:L.maxRetries,fetch:L.fetch}),o.add(this),this.completions=new c.Completions(this),this.chat=new c.Chat(this),this.embeddings=new c.Embeddings(this),this.audio=new c.Audio(this),this.models=new c.Models(this),this.batches=new c.Batches(this),this.files=new c.Files(this),this._options=L,this.apiKey=w}defaultQuery(){return this._options.defaultQuery}defaultHeaders(E){return{...super.defaultHeaders(E),...this._options.defaultHeaders}}authHeaders(E){return{Authorization:`Bearer ${this.apiKey}`}}}t.Groq=v,i=v,o=new WeakSet,v.Groq=i,v.DEFAULT_TIMEOUT=6e4,v.GroqError=l.GroqError,v.APIError=l.APIError,v.APIConnectionError=l.APIConnectionError,v.APIConnectionTimeoutError=l.APIConnectionTimeoutError,v.APIUserAbortError=l.APIUserAbortError,v.NotFoundError=l.NotFoundError,v.ConflictError=l.ConflictError,v.RateLimitError=l.RateLimitError,v.BadRequestError=l.BadRequestError,v.AuthenticationError=l.AuthenticationError,v.InternalServerError=l.InternalServerError,v.PermissionDeniedError=l.PermissionDeniedError,v.UnprocessableEntityError=l.UnprocessableEntityError,v.toFile=u.toFile,v.fileFromPath=u.fileFromPath,v.Completions=p.Completions,v.Chat=m.Chat,v.Embeddings=g.Embeddings,v.Audio=b.Audio,v.Models=_.Models,v.Batches=d.Batches,v.Files=y.Files;var A=Sa();Object.defineProperty(t,"toFile",{enumerable:!0,get:function(){return A.toFile}}),Object.defineProperty(t,"fileFromPath",{enumerable:!0,get:function(){return A.fileFromPath}});var S=Pi();Object.defineProperty(t,"GroqError",{enumerable:!0,get:function(){return S.GroqError}}),Object.defineProperty(t,"APIError",{enumerable:!0,get:function(){return S.APIError}}),Object.defineProperty(t,"APIConnectionError",{enumerable:!0,get:function(){return S.APIConnectionError}}),Object.defineProperty(t,"APIConnectionTimeoutError",{enumerable:!0,get:function(){return S.APIConnectionTimeoutError}}),Object.defineProperty(t,"APIUserAbortError",{enumerable:!0,get:function(){return S.APIUserAbortError}}),Object.defineProperty(t,"NotFoundError",{enumerable:!0,get:function(){return S.NotFoundError}}),Object.defineProperty(t,"ConflictError",{enumerable:!0,get:function(){return S.ConflictError}}),Object.defineProperty(t,"RateLimitError",{enumerable:!0,get:function(){return S.RateLimitError}}),Object.defineProperty(t,"BadRequestError",{enumerable:!0,get:function(){return S.BadRequestError}}),Object.defineProperty(t,"AuthenticationError",{enumerable:!0,get:function(){return S.AuthenticationError}}),Object.defineProperty(t,"InternalServerError",{enumerable:!0,get:function(){return S.InternalServerError}}),Object.defineProperty(t,"PermissionDeniedError",{enumerable:!0,get:function(){return S.PermissionDeniedError}}),Object.defineProperty(t,"UnprocessableEntityError",{enumerable:!0,get:function(){return S.UnprocessableEntityError}}),t=e.exports=v,t.default=v})(ci,ci.exports)),ci.exports}var Iy;function uI(){return Iy||(Iy=1,(function(e){var t={};Object.defineProperty(e,"__esModule",{value:!0}),e.groqAgent=void 0;const n=Oe(),r=lI(),s=Di(),o=(l,u,c)=>{const d=l?.choices[0]&&l?.choices[0].message?l?.choices[0].message:null,p=d&&d.content?d.content:null,y=(d?.tool_calls&&d?.tool_calls.length>0?d?.tool_calls:[]).map(b=>({id:b.id,name:b?.function?.name,arguments:(()=>{try{return JSON.parse(b?.function?.arguments)}catch{return}})()})),_=y[0]?y[0]:void 0;return d&&u.push(d),{...l,text:p,tool:_,tool_calls:y,message:d,messages:u,metadata:(0,s.convertMeta)(c)}},i=async({params:l,namedInputs:u,filterParams:c,config:d})=>{const{verbose:p,system:g,tools:y,tool_choice:_,max_tokens:b,temperature:m,prompt:v,messages:A}={...l,...u},{apiKey:S,stream:P,dataStream:E,forWeb:w,model:I}={...l,...d||{}},L=S??(process!==void 0?t.GROQ_API_KEY:void 0);(0,n.assert)(L!==void 0,"The GROQ_API_KEY environment variable adn apiKey is missing.");const H=new r.Groq({apiKey:S,dangerouslyAllowBrowser:!!w}),B=(0,s.initLLMMetaData)(),F=(0,s.getMergeValue)(u,l,"mergeablePrompts",v),j=(0,s.getMergeValue)(u,l,"mergeableSystem",g),U=(0,s.getMessages)(j,A);F&&U.push({role:"user",content:F}),p&&console.log(U);const T=P||E?{messages:U,model:I,temperature:m??.7,stream:!0}:{messages:U,model:I,temperature:m??.7};if(b&&(T.max_tokens=b),y&&(T.tools=y,T.tool_choice=_??"auto"),!T.stream){const X=await H.chat.completions.create(T);return(0,s.llmMetaDataEndTime)(B),o(X,U,B)}const M=await H.chat.completions.create(T);let k=null;const G=[];E&&c&&c.streamTokenCallback&&c.streamTokenCallback({type:"response.created",response:{}});for await(const X of M){(0,s.llmMetaDataFirstTokenTime)(B);const Y=X.choices[0].delta.content;Y&&(c&&c.streamTokenCallback&&(E?c.streamTokenCallback({type:"response.in_progress",response:{output:[{type:"text",text:Y}]}}):c.streamTokenCallback(Y)),G.push(Y)),k=X}E&&c&&c.streamTokenCallback&&c.streamTokenCallback({type:"response.completed",response:{}});const V=G.join(""),W={role:"assistant",content:V};return k&&(k.choices[0].message=W),U.push(W),(0,s.llmMetaDataEndTime)(B),{...k,text:V,message:W,messages:U,metadata:(0,s.convertMeta)(B)}};e.groqAgent=i;const a={name:"groqAgent",agent:e.groqAgent,mock:e.groqAgent,inputs:{type:"object",properties:{model:{type:"string"},system:{type:"string"},tools:{type:"object"},tool_choice:{anyOf:[{type:"string"},{type:"integer"},{type:"object"},{type:"array"}]},max_tokens:{type:"number"},verbose:{type:"boolean"},temperature:{type:"number"},stream:{type:"boolean"},prompt:{type:"string",description:"query string"},messages:{anyOf:[{type:"string"},{type:"integer"},{type:"object"},{type:"array"}],description:"chat messages"}}},output:{type:"object"},samples:[],description:"Groq Agent",category:["llm"],author:"Receptron team",repository:"https://github.com/receptron/graphai",source:"https://github.com/receptron/graphai/blob/main/agents/sleeper_agents/src/sleep_and_merge_agent.ts",package:"@graphai/groq_agent",license:"MIT",stream:!0,npms:["groq-sdk"],environmentVariables:["GROQ_API_KEY"]};e.default=a})(Ru)),Ru}var Cy;function cI(){if(Cy)return Qn;Cy=1;var e=Qn&&Qn.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(Qn,"__esModule",{value:!0}),Qn.groqAgent=void 0;const t=e(uI());return Qn.groqAgent=t.default,Qn}cI();var rr={},ku={};const dI=Object.prototype.toString,fI=e=>dI.call(e)==="[object Error]",pI=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function hI(e){if(!(e&&fI(e)&&e.name==="TypeError"&&typeof e.message=="string"))return!1;const{message:n,stack:r}=e;return n==="Load failed"?r===void 0||"__sentry_captured__"in e:n.startsWith("error sending request for url")?!0:pI.has(n)}function gI(e){if(typeof e=="number"){if(e<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(e))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(e!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function Yi(e,t,{min:n=0,allowInfinity:r=!1}={}){if(t!==void 0){if(typeof t!="number"||Number.isNaN(t))throw new TypeError(`Expected \`${e}\` to be a number${r?" or Infinity":""}.`);if(!r&&!Number.isFinite(t))throw new TypeError(`Expected \`${e}\` to be a finite number.`);if(t<n)throw new TypeError(`Expected \`${e}\` to be ≥ ${n}.`)}}class k0 extends Error{constructor(t){super(),t instanceof Error?(this.originalError=t,{message:t}=t):(this.originalError=new Error(t),this.originalError.stack=this.stack),this.name="AbortError",this.message=t}}function mI(e,t){const n=Math.max(1,e+1),r=t.randomize?Math.random()+1:1;let s=Math.round(r*t.minTimeout*t.factor**(n-1));return s=Math.min(s,t.maxTimeout),s}function Ry(e,t){return Number.isFinite(t)?t-(performance.now()-e):t}async function _I({error:e,attemptNumber:t,retriesConsumed:n,startTime:r,options:s}){const o=e instanceof Error?e:new TypeError(`Non-error was thrown: "${e}". You should only throw errors.`);if(o instanceof k0)throw o.originalError;const i=Number.isFinite(s.retries)?Math.max(0,s.retries-n):s.retries,a=s.maxRetryTime??Number.POSITIVE_INFINITY,l=Object.freeze({error:o,attemptNumber:t,retriesLeft:i,retriesConsumed:n});if(await s.onFailedAttempt(l),Ry(r,a)<=0)throw o;const u=await s.shouldConsumeRetry(l),c=Ry(r,a);if(c<=0||i<=0)throw o;if(o instanceof TypeError&&!hI(o)){if(u)throw o;return s.signal?.throwIfAborted(),!1}if(!await s.shouldRetry(l))throw o;if(!u)return s.signal?.throwIfAborted(),!1;const d=mI(n,s),p=Math.min(d,c);return s.signal?.throwIfAborted(),p>0&&await new Promise((g,y)=>{const _=()=>{clearTimeout(b),s.signal?.removeEventListener("abort",_),y(s.signal.reason)},b=setTimeout(()=>{s.signal?.removeEventListener("abort",_),g()},p);s.unref&&b.unref?.(),s.signal?.addEventListener("abort",_,{once:!0})}),s.signal?.throwIfAborted(),!0}async function yI(e,t={}){if(t={...t},gI(t.retries),Object.hasOwn(t,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");t.retries??=10,t.factor??=2,t.minTimeout??=1e3,t.maxTimeout??=Number.POSITIVE_INFINITY,t.maxRetryTime??=Number.POSITIVE_INFINITY,t.randomize??=!1,t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.shouldConsumeRetry??=()=>!0,Yi("factor",t.factor,{min:0,allowInfinity:!1}),Yi("minTimeout",t.minTimeout,{min:0,allowInfinity:!1}),Yi("maxTimeout",t.maxTimeout,{min:0,allowInfinity:!0}),Yi("maxRetryTime",t.maxRetryTime,{min:0,allowInfinity:!0}),t.factor>0||(t.factor=1),t.signal?.throwIfAborted();let n=0,r=0;const s=performance.now();for(;!Number.isFinite(t.retries)||r<=t.retries;){n++;try{t.signal?.throwIfAborted();const o=await e(n);return t.signal?.throwIfAborted(),o}catch(o){await _I({error:o,attemptNumber:n,retriesConsumed:r,startTime:s,options:t})&&r++}}throw new Error("Retry attempts exhausted without throwing an error.")}var vI={};let O0,x0;function bI(e){O0=e.geminiUrl,x0=e.vertexUrl}function AI(){return{geminiUrl:O0,vertexUrl:x0}}function SI(e,t,n,r){var s,o;if(!e?.baseUrl){const i=AI();return t?(s=i.vertexUrl)!==null&&s!==void 0?s:n:(o=i.geminiUrl)!==null&&o!==void 0?o:r}return e.baseUrl}class Sn{}function ie(e,t){const n=/\{([^}]+)\}/g;return e.replace(n,(r,s)=>{if(Object.prototype.hasOwnProperty.call(t,s)){const o=t[s];return o!=null?String(o):""}else throw new Error(`Key '${s}' not found in valueMap.`)})}function h(e,t,n){for(let o=0;o<t.length-1;o++){const i=t[o];if(i.endsWith("[]")){const a=i.slice(0,-2);if(!(a in e))if(Array.isArray(n))e[a]=Array.from({length:n.length},()=>({}));else throw new Error(`Value must be a list given an array path ${i}`);if(Array.isArray(e[a])){const l=e[a];if(Array.isArray(n))for(let u=0;u<l.length;u++){const c=l[u];h(c,t.slice(o+1),n[u])}else for(const u of l)h(u,t.slice(o+1),n)}return}else if(i.endsWith("[0]")){const a=i.slice(0,-3);a in e||(e[a]=[{}]);const l=e[a];h(l[0],t.slice(o+1),n);return}(!e[i]||typeof e[i]!="object")&&(e[i]={}),e=e[i]}const r=t[t.length-1],s=e[r];if(s!==void 0){if(!n||typeof n=="object"&&Object.keys(n).length===0||n===s)return;if(typeof s=="object"&&typeof n=="object"&&s!==null&&n!==null)Object.assign(s,n);else throw new Error(`Cannot set value for an existing key. Key: ${r}`)}else r==="_self"&&typeof n=="object"&&n!==null&&!Array.isArray(n)?Object.assign(e,n):e[r]=n}function f(e,t,n=void 0){try{if(t.length===1&&t[0]==="_self")return e;for(let r=0;r<t.length;r++){if(typeof e!="object"||e===null)return n;const s=t[r];if(s.endsWith("[]")){const o=s.slice(0,-2);if(o in e){const i=e[o];return Array.isArray(i)?i.map(a=>f(a,t.slice(r+1),n)):n}else return n}else e=e[s]}return e}catch(r){if(r instanceof TypeError)return n;throw r}}function wI(e,t){for(const[n,r]of Object.entries(t)){const s=n.split("."),o=r.split("."),i=new Set;let a=-1;for(let l=0;l<s.length;l++)if(s[l]==="*"){a=l;break}if(a!==-1&&o.length>a)for(let l=a;l<o.length;l++){const u=o[l];u!=="*"&&!u.endsWith("[]")&&!u.endsWith("[0]")&&i.add(u)}rc(e,s,o,0,i)}}function rc(e,t,n,r,s){if(r>=t.length||typeof e!="object"||e===null)return;const o=t[r];if(o.endsWith("[]")){const i=o.slice(0,-2),a=e;if(i in a&&Array.isArray(a[i]))for(const l of a[i])rc(l,t,n,r+1,s)}else if(o==="*"){if(typeof e=="object"&&e!==null&&!Array.isArray(e)){const i=e,a=Object.keys(i).filter(u=>!u.startsWith("_")&&!s.has(u)),l={};for(const u of a)l[u]=i[u];for(const[u,c]of Object.entries(l)){const d=[];for(const p of n.slice(r))p==="*"?d.push(u):d.push(p);h(i,d,c)}for(const u of a)delete i[u]}}else{const i=e;o in i&&rc(i[o],t,n,r+1,s)}}function Xd(e){if(typeof e!="string")throw new Error("fromImageBytes must be a string");return e}function EI(e){const t={},n=f(e,["operationName"]);n!=null&&h(t,["operationName"],n);const r=f(e,["resourceName"]);return r!=null&&h(t,["_url","resourceName"],r),t}function TI(e){const t={},n=f(e,["name"]);n!=null&&h(t,["name"],n);const r=f(e,["metadata"]);r!=null&&h(t,["metadata"],r);const s=f(e,["done"]);s!=null&&h(t,["done"],s);const o=f(e,["error"]);o!=null&&h(t,["error"],o);const i=f(e,["response","generateVideoResponse"]);return i!=null&&h(t,["response"],II(i)),t}function PI(e){const t={},n=f(e,["name"]);n!=null&&h(t,["name"],n);const r=f(e,["metadata"]);r!=null&&h(t,["metadata"],r);const s=f(e,["done"]);s!=null&&h(t,["done"],s);const o=f(e,["error"]);o!=null&&h(t,["error"],o);const i=f(e,["response"]);return i!=null&&h(t,["response"],CI(i)),t}function II(e){const t={},n=f(e,["generatedSamples"]);if(n!=null){let o=n;Array.isArray(o)&&(o=o.map(i=>RI(i))),h(t,["generatedVideos"],o)}const r=f(e,["raiMediaFilteredCount"]);r!=null&&h(t,["raiMediaFilteredCount"],r);const s=f(e,["raiMediaFilteredReasons"]);return s!=null&&h(t,["raiMediaFilteredReasons"],s),t}function CI(e){const t={},n=f(e,["videos"]);if(n!=null){let o=n;Array.isArray(o)&&(o=o.map(i=>MI(i))),h(t,["generatedVideos"],o)}const r=f(e,["raiMediaFilteredCount"]);r!=null&&h(t,["raiMediaFilteredCount"],r);const s=f(e,["raiMediaFilteredReasons"]);return s!=null&&h(t,["raiMediaFilteredReasons"],s),t}function RI(e){const t={},n=f(e,["video"]);return n!=null&&h(t,["video"],DI(n)),t}function MI(e){const t={},n=f(e,["_self"]);return n!=null&&h(t,["video"],qI(n)),t}function NI(e){const t={},n=f(e,["operationName"]);return n!=null&&h(t,["_url","operationName"],n),t}function FI(e){const t={},n=f(e,["operationName"]);return n!=null&&h(t,["_url","operationName"],n),t}function kI(e){const t={},n=f(e,["name"]);n!=null&&h(t,["name"],n);const r=f(e,["metadata"]);r!=null&&h(t,["metadata"],r);const s=f(e,["done"]);s!=null&&h(t,["done"],s);const o=f(e,["error"]);o!=null&&h(t,["error"],o);const i=f(e,["response"]);return i!=null&&h(t,["response"],OI(i)),t}function OI(e){const t={},n=f(e,["sdkHttpResponse"]);n!=null&&h(t,["sdkHttpResponse"],n);const r=f(e,["parent"]);r!=null&&h(t,["parent"],r);const s=f(e,["documentName"]);return s!=null&&h(t,["documentName"],s),t}function D0(e){const t={},n=f(e,["name"]);n!=null&&h(t,["name"],n);const r=f(e,["metadata"]);r!=null&&h(t,["metadata"],r);const s=f(e,["done"]);s!=null&&h(t,["done"],s);const o=f(e,["error"]);o!=null&&h(t,["error"],o);const i=f(e,["response"]);return i!=null&&h(t,["response"],xI(i)),t}function xI(e){const t={},n=f(e,["sdkHttpResponse"]);n!=null&&h(t,["sdkHttpResponse"],n);const r=f(e,["parent"]);r!=null&&h(t,["parent"],r);const s=f(e,["documentName"]);return s!=null&&h(t,["documentName"],s),t}function DI(e){const t={},n=f(e,["uri"]);n!=null&&h(t,["uri"],n);const r=f(e,["encodedVideo"]);r!=null&&h(t,["videoBytes"],Xd(r));const s=f(e,["encoding"]);return s!=null&&h(t,["mimeType"],s),t}function qI(e){const t={},n=f(e,["gcsUri"]);n!=null&&h(t,["uri"],n);const r=f(e,["bytesBase64Encoded"]);r!=null&&h(t,["videoBytes"],Xd(r));const s=f(e,["mimeType"]);return s!=null&&h(t,["mimeType"],s),t}var sc;(function(e){e.OUTCOME_UNSPECIFIED="OUTCOME_UNSPECIFIED",e.OUTCOME_OK="OUTCOME_OK",e.OUTCOME_FAILED="OUTCOME_FAILED",e.OUTCOME_DEADLINE_EXCEEDED="OUTCOME_DEADLINE_EXCEEDED"})(sc||(sc={}));var oc;(function(e){e.LANGUAGE_UNSPECIFIED="LANGUAGE_UNSPECIFIED",e.PYTHON="PYTHON"})(oc||(oc={}));var ic;(function(e){e.SCHEDULING_UNSPECIFIED="SCHEDULING_UNSPECIFIED",e.SILENT="SILENT",e.WHEN_IDLE="WHEN_IDLE",e.INTERRUPT="INTERRUPT"})(ic||(ic={}));var pn;(function(e){e.TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",e.STRING="STRING",e.NUMBER="NUMBER",e.INTEGER="INTEGER",e.BOOLEAN="BOOLEAN",e.ARRAY="ARRAY",e.OBJECT="OBJECT",e.NULL="NULL"})(pn||(pn={}));var ac;(function(e){e.API_SPEC_UNSPECIFIED="API_SPEC_UNSPECIFIED",e.SIMPLE_SEARCH="SIMPLE_SEARCH",e.ELASTIC_SEARCH="ELASTIC_SEARCH"})(ac||(ac={}));var lc;(function(e){e.AUTH_TYPE_UNSPECIFIED="AUTH_TYPE_UNSPECIFIED",e.NO_AUTH="NO_AUTH",e.API_KEY_AUTH="API_KEY_AUTH",e.HTTP_BASIC_AUTH="HTTP_BASIC_AUTH",e.GOOGLE_SERVICE_ACCOUNT_AUTH="GOOGLE_SERVICE_ACCOUNT_AUTH",e.OAUTH="OAUTH",e.OIDC_AUTH="OIDC_AUTH"})(lc||(lc={}));var uc;(function(e){e.HTTP_IN_UNSPECIFIED="HTTP_IN_UNSPECIFIED",e.HTTP_IN_QUERY="HTTP_IN_QUERY",e.HTTP_IN_HEADER="HTTP_IN_HEADER",e.HTTP_IN_PATH="HTTP_IN_PATH",e.HTTP_IN_BODY="HTTP_IN_BODY",e.HTTP_IN_COOKIE="HTTP_IN_COOKIE"})(uc||(uc={}));var cc;(function(e){e.PHISH_BLOCK_THRESHOLD_UNSPECIFIED="PHISH_BLOCK_THRESHOLD_UNSPECIFIED",e.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",e.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",e.BLOCK_HIGH_AND_ABOVE="BLOCK_HIGH_AND_ABOVE",e.BLOCK_HIGHER_AND_ABOVE="BLOCK_HIGHER_AND_ABOVE",e.BLOCK_VERY_HIGH_AND_ABOVE="BLOCK_VERY_HIGH_AND_ABOVE",e.BLOCK_ONLY_EXTREMELY_HIGH="BLOCK_ONLY_EXTREMELY_HIGH"})(cc||(cc={}));var dc;(function(e){e.UNSPECIFIED="UNSPECIFIED",e.BLOCKING="BLOCKING",e.NON_BLOCKING="NON_BLOCKING"})(dc||(dc={}));var fc;(function(e){e.MODE_UNSPECIFIED="MODE_UNSPECIFIED",e.MODE_DYNAMIC="MODE_DYNAMIC"})(fc||(fc={}));var pc;(function(e){e.MODE_UNSPECIFIED="MODE_UNSPECIFIED",e.AUTO="AUTO",e.ANY="ANY",e.NONE="NONE",e.VALIDATED="VALIDATED"})(pc||(pc={}));var hc;(function(e){e.THINKING_LEVEL_UNSPECIFIED="THINKING_LEVEL_UNSPECIFIED",e.LOW="LOW",e.MEDIUM="MEDIUM",e.HIGH="HIGH",e.MINIMAL="MINIMAL"})(hc||(hc={}));var gc;(function(e){e.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",e.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",e.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",e.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",e.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",e.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY",e.HARM_CATEGORY_IMAGE_HATE="HARM_CATEGORY_IMAGE_HATE",e.HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT="HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT",e.HARM_CATEGORY_IMAGE_HARASSMENT="HARM_CATEGORY_IMAGE_HARASSMENT",e.HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT="HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT",e.HARM_CATEGORY_JAILBREAK="HARM_CATEGORY_JAILBREAK"})(gc||(gc={}));var mc;(function(e){e.HARM_BLOCK_METHOD_UNSPECIFIED="HARM_BLOCK_METHOD_UNSPECIFIED",e.SEVERITY="SEVERITY",e.PROBABILITY="PROBABILITY"})(mc||(mc={}));var _c;(function(e){e.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",e.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",e.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",e.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",e.BLOCK_NONE="BLOCK_NONE",e.OFF="OFF"})(_c||(_c={}));var yc;(function(e){e.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",e.STOP="STOP",e.MAX_TOKENS="MAX_TOKENS",e.SAFETY="SAFETY",e.RECITATION="RECITATION",e.LANGUAGE="LANGUAGE",e.OTHER="OTHER",e.BLOCKLIST="BLOCKLIST",e.PROHIBITED_CONTENT="PROHIBITED_CONTENT",e.SPII="SPII",e.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",e.IMAGE_SAFETY="IMAGE_SAFETY",e.UNEXPECTED_TOOL_CALL="UNEXPECTED_TOOL_CALL",e.IMAGE_PROHIBITED_CONTENT="IMAGE_PROHIBITED_CONTENT",e.NO_IMAGE="NO_IMAGE",e.IMAGE_RECITATION="IMAGE_RECITATION",e.IMAGE_OTHER="IMAGE_OTHER"})(yc||(yc={}));var vc;(function(e){e.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",e.NEGLIGIBLE="NEGLIGIBLE",e.LOW="LOW",e.MEDIUM="MEDIUM",e.HIGH="HIGH"})(vc||(vc={}));var bc;(function(e){e.HARM_SEVERITY_UNSPECIFIED="HARM_SEVERITY_UNSPECIFIED",e.HARM_SEVERITY_NEGLIGIBLE="HARM_SEVERITY_NEGLIGIBLE",e.HARM_SEVERITY_LOW="HARM_SEVERITY_LOW",e.HARM_SEVERITY_MEDIUM="HARM_SEVERITY_MEDIUM",e.HARM_SEVERITY_HIGH="HARM_SEVERITY_HIGH"})(bc||(bc={}));var Ac;(function(e){e.URL_RETRIEVAL_STATUS_UNSPECIFIED="URL_RETRIEVAL_STATUS_UNSPECIFIED",e.URL_RETRIEVAL_STATUS_SUCCESS="URL_RETRIEVAL_STATUS_SUCCESS",e.URL_RETRIEVAL_STATUS_ERROR="URL_RETRIEVAL_STATUS_ERROR",e.URL_RETRIEVAL_STATUS_PAYWALL="URL_RETRIEVAL_STATUS_PAYWALL",e.URL_RETRIEVAL_STATUS_UNSAFE="URL_RETRIEVAL_STATUS_UNSAFE"})(Ac||(Ac={}));var Sc;(function(e){e.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",e.SAFETY="SAFETY",e.OTHER="OTHER",e.BLOCKLIST="BLOCKLIST",e.PROHIBITED_CONTENT="PROHIBITED_CONTENT",e.IMAGE_SAFETY="IMAGE_SAFETY",e.MODEL_ARMOR="MODEL_ARMOR",e.JAILBREAK="JAILBREAK"})(Sc||(Sc={}));var wc;(function(e){e.TRAFFIC_TYPE_UNSPECIFIED="TRAFFIC_TYPE_UNSPECIFIED",e.ON_DEMAND="ON_DEMAND",e.PROVISIONED_THROUGHPUT="PROVISIONED_THROUGHPUT"})(wc||(wc={}));var Ii;(function(e){e.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",e.TEXT="TEXT",e.IMAGE="IMAGE",e.AUDIO="AUDIO"})(Ii||(Ii={}));var Ec;(function(e){e.MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",e.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",e.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",e.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH"})(Ec||(Ec={}));var Tc;(function(e){e.TUNING_MODE_UNSPECIFIED="TUNING_MODE_UNSPECIFIED",e.TUNING_MODE_FULL="TUNING_MODE_FULL",e.TUNING_MODE_PEFT_ADAPTER="TUNING_MODE_PEFT_ADAPTER"})(Tc||(Tc={}));var Pc;(function(e){e.ADAPTER_SIZE_UNSPECIFIED="ADAPTER_SIZE_UNSPECIFIED",e.ADAPTER_SIZE_ONE="ADAPTER_SIZE_ONE",e.ADAPTER_SIZE_TWO="ADAPTER_SIZE_TWO",e.ADAPTER_SIZE_FOUR="ADAPTER_SIZE_FOUR",e.ADAPTER_SIZE_EIGHT="ADAPTER_SIZE_EIGHT",e.ADAPTER_SIZE_SIXTEEN="ADAPTER_SIZE_SIXTEEN",e.ADAPTER_SIZE_THIRTY_TWO="ADAPTER_SIZE_THIRTY_TWO"})(Pc||(Pc={}));var wa;(function(e){e.JOB_STATE_UNSPECIFIED="JOB_STATE_UNSPECIFIED",e.JOB_STATE_QUEUED="JOB_STATE_QUEUED",e.JOB_STATE_PENDING="JOB_STATE_PENDING",e.JOB_STATE_RUNNING="JOB_STATE_RUNNING",e.JOB_STATE_SUCCEEDED="JOB_STATE_SUCCEEDED",e.JOB_STATE_FAILED="JOB_STATE_FAILED",e.JOB_STATE_CANCELLING="JOB_STATE_CANCELLING",e.JOB_STATE_CANCELLED="JOB_STATE_CANCELLED",e.JOB_STATE_PAUSED="JOB_STATE_PAUSED",e.JOB_STATE_EXPIRED="JOB_STATE_EXPIRED",e.JOB_STATE_UPDATING="JOB_STATE_UPDATING",e.JOB_STATE_PARTIALLY_SUCCEEDED="JOB_STATE_PARTIALLY_SUCCEEDED"})(wa||(wa={}));var Ic;(function(e){e.TUNING_TASK_UNSPECIFIED="TUNING_TASK_UNSPECIFIED",e.TUNING_TASK_I2V="TUNING_TASK_I2V",e.TUNING_TASK_T2V="TUNING_TASK_T2V",e.TUNING_TASK_R2V="TUNING_TASK_R2V"})(Ic||(Ic={}));var Cc;(function(e){e.MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",e.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",e.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",e.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH",e.MEDIA_RESOLUTION_ULTRA_HIGH="MEDIA_RESOLUTION_ULTRA_HIGH"})(Cc||(Cc={}));var Ea;(function(e){e.COLLECTION="COLLECTION"})(Ea||(Ea={}));var Rc;(function(e){e.FEATURE_SELECTION_PREFERENCE_UNSPECIFIED="FEATURE_SELECTION_PREFERENCE_UNSPECIFIED",e.PRIORITIZE_QUALITY="PRIORITIZE_QUALITY",e.BALANCED="BALANCED",e.PRIORITIZE_COST="PRIORITIZE_COST"})(Rc||(Rc={}));var Mc;(function(e){e.ENVIRONMENT_UNSPECIFIED="ENVIRONMENT_UNSPECIFIED",e.ENVIRONMENT_BROWSER="ENVIRONMENT_BROWSER"})(Mc||(Mc={}));var Nc;(function(e){e.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",e.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",e.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",e.BLOCK_NONE="BLOCK_NONE"})(Nc||(Nc={}));var Fc;(function(e){e.DONT_ALLOW="DONT_ALLOW",e.ALLOW_ADULT="ALLOW_ADULT",e.ALLOW_ALL="ALLOW_ALL"})(Fc||(Fc={}));var kc;(function(e){e.auto="auto",e.en="en",e.ja="ja",e.ko="ko",e.hi="hi",e.zh="zh",e.pt="pt",e.es="es"})(kc||(kc={}));var Oc;(function(e){e.MASK_MODE_DEFAULT="MASK_MODE_DEFAULT",e.MASK_MODE_USER_PROVIDED="MASK_MODE_USER_PROVIDED",e.MASK_MODE_BACKGROUND="MASK_MODE_BACKGROUND",e.MASK_MODE_FOREGROUND="MASK_MODE_FOREGROUND",e.MASK_MODE_SEMANTIC="MASK_MODE_SEMANTIC"})(Oc||(Oc={}));var xc;(function(e){e.CONTROL_TYPE_DEFAULT="CONTROL_TYPE_DEFAULT",e.CONTROL_TYPE_CANNY="CONTROL_TYPE_CANNY",e.CONTROL_TYPE_SCRIBBLE="CONTROL_TYPE_SCRIBBLE",e.CONTROL_TYPE_FACE_MESH="CONTROL_TYPE_FACE_MESH"})(xc||(xc={}));var Dc;(function(e){e.SUBJECT_TYPE_DEFAULT="SUBJECT_TYPE_DEFAULT",e.SUBJECT_TYPE_PERSON="SUBJECT_TYPE_PERSON",e.SUBJECT_TYPE_ANIMAL="SUBJECT_TYPE_ANIMAL",e.SUBJECT_TYPE_PRODUCT="SUBJECT_TYPE_PRODUCT"})(Dc||(Dc={}));var qc;(function(e){e.EDIT_MODE_DEFAULT="EDIT_MODE_DEFAULT",e.EDIT_MODE_INPAINT_REMOVAL="EDIT_MODE_INPAINT_REMOVAL",e.EDIT_MODE_INPAINT_INSERTION="EDIT_MODE_INPAINT_INSERTION",e.EDIT_MODE_OUTPAINT="EDIT_MODE_OUTPAINT",e.EDIT_MODE_CONTROLLED_EDITING="EDIT_MODE_CONTROLLED_EDITING",e.EDIT_MODE_STYLE="EDIT_MODE_STYLE",e.EDIT_MODE_BGSWAP="EDIT_MODE_BGSWAP",e.EDIT_MODE_PRODUCT_IMAGE="EDIT_MODE_PRODUCT_IMAGE"})(qc||(qc={}));var Lc;(function(e){e.FOREGROUND="FOREGROUND",e.BACKGROUND="BACKGROUND",e.PROMPT="PROMPT",e.SEMANTIC="SEMANTIC",e.INTERACTIVE="INTERACTIVE"})(Lc||(Lc={}));var Uc;(function(e){e.ASSET="ASSET",e.STYLE="STYLE"})(Uc||(Uc={}));var Gc;(function(e){e.INSERT="INSERT",e.REMOVE="REMOVE",e.REMOVE_STATIC="REMOVE_STATIC",e.OUTPAINT="OUTPAINT"})(Gc||(Gc={}));var Vc;(function(e){e.OPTIMIZED="OPTIMIZED",e.LOSSLESS="LOSSLESS"})(Vc||(Vc={}));var Bc;(function(e){e.SUPERVISED_FINE_TUNING="SUPERVISED_FINE_TUNING",e.PREFERENCE_TUNING="PREFERENCE_TUNING",e.DISTILLATION="DISTILLATION"})(Bc||(Bc={}));var Hc;(function(e){e.STATE_UNSPECIFIED="STATE_UNSPECIFIED",e.STATE_PENDING="STATE_PENDING",e.STATE_ACTIVE="STATE_ACTIVE",e.STATE_FAILED="STATE_FAILED"})(Hc||(Hc={}));var Jc;(function(e){e.STATE_UNSPECIFIED="STATE_UNSPECIFIED",e.PROCESSING="PROCESSING",e.ACTIVE="ACTIVE",e.FAILED="FAILED"})(Jc||(Jc={}));var jc;(function(e){e.SOURCE_UNSPECIFIED="SOURCE_UNSPECIFIED",e.UPLOADED="UPLOADED",e.GENERATED="GENERATED",e.REGISTERED="REGISTERED"})(jc||(jc={}));var Wc;(function(e){e.TURN_COMPLETE_REASON_UNSPECIFIED="TURN_COMPLETE_REASON_UNSPECIFIED",e.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",e.RESPONSE_REJECTED="RESPONSE_REJECTED",e.NEED_MORE_INPUT="NEED_MORE_INPUT"})(Wc||(Wc={}));var Kc;(function(e){e.MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",e.TEXT="TEXT",e.IMAGE="IMAGE",e.VIDEO="VIDEO",e.AUDIO="AUDIO",e.DOCUMENT="DOCUMENT"})(Kc||(Kc={}));var $c;(function(e){e.VAD_SIGNAL_TYPE_UNSPECIFIED="VAD_SIGNAL_TYPE_UNSPECIFIED",e.VAD_SIGNAL_TYPE_SOS="VAD_SIGNAL_TYPE_SOS",e.VAD_SIGNAL_TYPE_EOS="VAD_SIGNAL_TYPE_EOS"})($c||($c={}));var Yc;(function(e){e.TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",e.ACTIVITY_START="ACTIVITY_START",e.ACTIVITY_END="ACTIVITY_END"})(Yc||(Yc={}));var zc;(function(e){e.START_SENSITIVITY_UNSPECIFIED="START_SENSITIVITY_UNSPECIFIED",e.START_SENSITIVITY_HIGH="START_SENSITIVITY_HIGH",e.START_SENSITIVITY_LOW="START_SENSITIVITY_LOW"})(zc||(zc={}));var Xc;(function(e){e.END_SENSITIVITY_UNSPECIFIED="END_SENSITIVITY_UNSPECIFIED",e.END_SENSITIVITY_HIGH="END_SENSITIVITY_HIGH",e.END_SENSITIVITY_LOW="END_SENSITIVITY_LOW"})(Xc||(Xc={}));var Qc;(function(e){e.ACTIVITY_HANDLING_UNSPECIFIED="ACTIVITY_HANDLING_UNSPECIFIED",e.START_OF_ACTIVITY_INTERRUPTS="START_OF_ACTIVITY_INTERRUPTS",e.NO_INTERRUPTION="NO_INTERRUPTION"})(Qc||(Qc={}));var Zc;(function(e){e.TURN_COVERAGE_UNSPECIFIED="TURN_COVERAGE_UNSPECIFIED",e.TURN_INCLUDES_ONLY_ACTIVITY="TURN_INCLUDES_ONLY_ACTIVITY",e.TURN_INCLUDES_ALL_INPUT="TURN_INCLUDES_ALL_INPUT"})(Zc||(Zc={}));var ed;(function(e){e.SCALE_UNSPECIFIED="SCALE_UNSPECIFIED",e.C_MAJOR_A_MINOR="C_MAJOR_A_MINOR",e.D_FLAT_MAJOR_B_FLAT_MINOR="D_FLAT_MAJOR_B_FLAT_MINOR",e.D_MAJOR_B_MINOR="D_MAJOR_B_MINOR",e.E_FLAT_MAJOR_C_MINOR="E_FLAT_MAJOR_C_MINOR",e.E_MAJOR_D_FLAT_MINOR="E_MAJOR_D_FLAT_MINOR",e.F_MAJOR_D_MINOR="F_MAJOR_D_MINOR",e.G_FLAT_MAJOR_E_FLAT_MINOR="G_FLAT_MAJOR_E_FLAT_MINOR",e.G_MAJOR_E_MINOR="G_MAJOR_E_MINOR",e.A_FLAT_MAJOR_F_MINOR="A_FLAT_MAJOR_F_MINOR",e.A_MAJOR_G_FLAT_MINOR="A_MAJOR_G_FLAT_MINOR",e.B_FLAT_MAJOR_G_MINOR="B_FLAT_MAJOR_G_MINOR",e.B_MAJOR_A_FLAT_MINOR="B_MAJOR_A_FLAT_MINOR"})(ed||(ed={}));var td;(function(e){e.MUSIC_GENERATION_MODE_UNSPECIFIED="MUSIC_GENERATION_MODE_UNSPECIFIED",e.QUALITY="QUALITY",e.DIVERSITY="DIVERSITY",e.VOCALIZATION="VOCALIZATION"})(td||(td={}));var ar;(function(e){e.PLAYBACK_CONTROL_UNSPECIFIED="PLAYBACK_CONTROL_UNSPECIFIED",e.PLAY="PLAY",e.PAUSE="PAUSE",e.STOP="STOP",e.RESET_CONTEXT="RESET_CONTEXT"})(ar||(ar={}));class LI{}class UI{}class GI{}function VI(e,t){return{inlineData:{data:e,mimeType:t}}}function BI(e,t){return{fileData:{fileUri:e,mimeType:t}}}class HI{}function JI(e,t,n){return Object.assign({fileData:{fileUri:e,mimeType:t}},n&&{mediaResolution:{level:n}})}function nd(e){return{text:e}}function jI(e,t){return{functionCall:{name:e,args:t}}}function WI(e,t,n,r=[]){return{functionResponse:Object.assign({id:e,name:t,response:n},r.length>0&&{parts:r})}}function KI(e,t,n){return Object.assign({inlineData:{data:e,mimeType:t}},n&&{mediaResolution:{level:n}})}function $I(e,t){return{codeExecutionResult:{outcome:e,output:t}}}function YI(e,t){return{executableCode:{code:e,language:t}}}function My(e){return typeof e=="object"&&e!==null?"fileData"in e||"text"in e||"functionCall"in e||"functionResponse"in e||"inlineData"in e||"videoMetadata"in e||"codeExecutionResult"in e||"executableCode"in e:!1}function q0(e){const t=[];if(typeof e=="string")t.push(nd(e));else if(My(e))t.push(e);else if(Array.isArray(e)){if(e.length===0)throw new Error("partOrString cannot be an empty array");for(const n of e)if(typeof n=="string")t.push(nd(n));else if(My(n))t.push(n);else throw new Error("element in PartUnion must be a Part object or string")}else throw new Error("partOrString must be a Part object, string, or array");return t}function zI(e){return{role:"user",parts:q0(e)}}function XI(e){return{role:"model",parts:q0(e)}}class Ta{constructor(t){const n={};for(const r of t.headers.entries())n[r[0]]=r[1];this.headers=n,this.responseInternal=t}json(){return this.responseInternal.json()}}class QI{}class ZI{}class Pr{get text(){var t,n,r,s,o,i,a,l;if(((s=(r=(n=(t=this.candidates)===null||t===void 0?void 0:t[0])===null||n===void 0?void 0:n.content)===null||r===void 0?void 0:r.parts)===null||s===void 0?void 0:s.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning text from the first one.");let u="",c=!1;const d=[];for(const p of(l=(a=(i=(o=this.candidates)===null||o===void 0?void 0:o[0])===null||i===void 0?void 0:i.content)===null||a===void 0?void 0:a.parts)!==null&&l!==void 0?l:[]){for(const[g,y]of Object.entries(p))g!=="text"&&g!=="thought"&&g!=="thoughtSignature"&&(y!==null||y!==void 0)&&d.push(g);if(typeof p.text=="string"){if(typeof p.thought=="boolean"&&p.thought)continue;c=!0,u+=p.text}}return d.length>0&&console.warn(`there are non-text parts ${d} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),c?u:void 0}get data(){var t,n,r,s,o,i,a,l;if(((s=(r=(n=(t=this.candidates)===null||t===void 0?void 0:t[0])===null||n===void 0?void 0:n.content)===null||r===void 0?void 0:r.parts)===null||s===void 0?void 0:s.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning data from the first one.");let u="";const c=[];for(const d of(l=(a=(i=(o=this.candidates)===null||o===void 0?void 0:o[0])===null||i===void 0?void 0:i.content)===null||a===void 0?void 0:a.parts)!==null&&l!==void 0?l:[]){for(const[p,g]of Object.entries(d))p!=="inlineData"&&(g!==null||g!==void 0)&&c.push(p);d.inlineData&&typeof d.inlineData.data=="string"&&(u+=atob(d.inlineData.data))}return c.length>0&&console.warn(`there are non-data parts ${c} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),u.length>0?btoa(u):void 0}get functionCalls(){var t,n,r,s,o,i,a,l;if(((s=(r=(n=(t=this.candidates)===null||t===void 0?void 0:t[0])===null||n===void 0?void 0:n.content)===null||r===void 0?void 0:r.parts)===null||s===void 0?void 0:s.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning function calls from the first one.");const u=(l=(a=(i=(o=this.candidates)===null||o===void 0?void 0:o[0])===null||i===void 0?void 0:i.content)===null||a===void 0?void 0:a.parts)===null||l===void 0?void 0:l.filter(c=>c.functionCall).map(c=>c.functionCall).filter(c=>c!==void 0);if(u?.length!==0)return u}get executableCode(){var t,n,r,s,o,i,a,l,u;if(((s=(r=(n=(t=this.candidates)===null||t===void 0?void 0:t[0])===null||n===void 0?void 0:n.content)===null||r===void 0?void 0:r.parts)===null||s===void 0?void 0:s.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning executable code from the first one.");const c=(l=(a=(i=(o=this.candidates)===null||o===void 0?void 0:o[0])===null||i===void 0?void 0:i.content)===null||a===void 0?void 0:a.parts)===null||l===void 0?void 0:l.filter(d=>d.executableCode).map(d=>d.executableCode).filter(d=>d!==void 0);if(c?.length!==0)return(u=c?.[0])===null||u===void 0?void 0:u.code}get codeExecutionResult(){var t,n,r,s,o,i,a,l,u;if(((s=(r=(n=(t=this.candidates)===null||t===void 0?void 0:t[0])===null||n===void 0?void 0:n.content)===null||r===void 0?void 0:r.parts)===null||s===void 0?void 0:s.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning code execution result from the first one.");const c=(l=(a=(i=(o=this.candidates)===null||o===void 0?void 0:o[0])===null||i===void 0?void 0:i.content)===null||a===void 0?void 0:a.parts)===null||l===void 0?void 0:l.filter(d=>d.codeExecutionResult).map(d=>d.codeExecutionResult).filter(d=>d!==void 0);if(c?.length!==0)return(u=c?.[0])===null||u===void 0?void 0:u.output}}class rd{}class sd{}class L0{}class U0{}class G0{}class V0{}class od{}class id{}class ad{}class B0{}class eC{}class Ci{_fromAPIResponse({apiResponse:t,_isVertexAI:n}){const r=new Ci;let s;const o=t;return n?s=PI(o):s=TI(o),Object.assign(r,s),r}}class ld{}class ud{}class cd{}class dd{}class H0{}class J0{}class j0{}class tC{}class za{_fromAPIResponse({apiResponse:t,_isVertexAI:n}){const r=new za,o=kI(t);return Object.assign(r,o),r}}class W0{}class K0{}class $0{}class Y0{}class nC{}class rC{}class sC{}class fd{}class oC{}class iC{toReferenceImageAPI(){return{referenceType:"REFERENCE_TYPE_RAW",referenceImage:this.referenceImage,referenceId:this.referenceId}}}class aC{toReferenceImageAPI(){return{referenceType:"REFERENCE_TYPE_MASK",referenceImage:this.referenceImage,referenceId:this.referenceId,maskImageConfig:this.config}}}class lC{toReferenceImageAPI(){return{referenceType:"REFERENCE_TYPE_CONTROL",referenceImage:this.referenceImage,referenceId:this.referenceId,controlImageConfig:this.config}}}class uC{toReferenceImageAPI(){return{referenceType:"REFERENCE_TYPE_STYLE",referenceImage:this.referenceImage,referenceId:this.referenceId,styleImageConfig:this.config}}}class cC{toReferenceImageAPI(){return{referenceType:"REFERENCE_TYPE_SUBJECT",referenceImage:this.referenceImage,referenceId:this.referenceId,subjectImageConfig:this.config}}}class dC{toReferenceImageAPI(){return{referenceType:"REFERENCE_TYPE_CONTENT",referenceImage:this.referenceImage,referenceId:this.referenceId}}}class z0{get text(){var t,n,r;let s="",o=!1;const i=[];for(const a of(r=(n=(t=this.serverContent)===null||t===void 0?void 0:t.modelTurn)===null||n===void 0?void 0:n.parts)!==null&&r!==void 0?r:[]){for(const[l,u]of Object.entries(a))l!=="text"&&l!=="thought"&&u!==null&&i.push(l);if(typeof a.text=="string"){if(typeof a.thought=="boolean"&&a.thought)continue;o=!0,s+=a.text}}return i.length>0&&console.warn(`there are non-text parts ${i} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),o?s:void 0}get data(){var t,n,r;let s="";const o=[];for(const i of(r=(n=(t=this.serverContent)===null||t===void 0?void 0:t.modelTurn)===null||n===void 0?void 0:n.parts)!==null&&r!==void 0?r:[]){for(const[a,l]of Object.entries(i))a!=="inlineData"&&l!==null&&o.push(a);i.inlineData&&typeof i.inlineData.data=="string"&&(s+=atob(i.inlineData.data))}return o.length>0&&console.warn(`there are non-data parts ${o} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),s.length>0?btoa(s):void 0}}class fC{}class pC{constructor(){this.functionResponses=[]}}class X0{get audioChunk(){if(this.serverContent&&this.serverContent.audioChunks&&this.serverContent.audioChunks.length>0)return this.serverContent.audioChunks[0]}}class hC{}class Xa{_fromAPIResponse({apiResponse:t,_isVertexAI:n}){const r=new Xa,o=D0(t);return Object.assign(r,o),r}}function Ee(e,t){if(!t||typeof t!="string")throw new Error("model is required and must be a string");if(t.includes("..")||t.includes("?")||t.includes("&"))throw new Error("invalid model parameter");if(e.isVertexAI()){if(t.startsWith("publishers/")||t.startsWith("projects/")||t.startsWith("models/"))return t;if(t.indexOf("/")>=0){const n=t.split("/",2);return`publishers/${n[0]}/models/${n[1]}`}else return`publishers/google/models/${t}`}else return t.startsWith("models/")||t.startsWith("tunedModels/")?t:`models/${t}`}function Q0(e,t){const n=Ee(e,t);return n?n.startsWith("publishers/")&&e.isVertexAI()?`projects/${e.getProject()}/locations/${e.getLocation()}/${n}`:n.startsWith("models/")&&e.isVertexAI()?`projects/${e.getProject()}/locations/${e.getLocation()}/publishers/google/${n}`:n:""}function Z0(e){return Array.isArray(e)?e.map(t=>Pa(t)):[Pa(e)]}function Pa(e){if(typeof e=="object"&&e!==null)return e;throw new Error(`Could not parse input as Blob. Unsupported blob type: ${typeof e}`)}function eA(e){const t=Pa(e);if(t.mimeType&&t.mimeType.startsWith("image/"))return t;throw new Error(`Unsupported mime type: ${t.mimeType}`)}function tA(e){const t=Pa(e);if(t.mimeType&&t.mimeType.startsWith("audio/"))return t;throw new Error(`Unsupported mime type: ${t.mimeType}`)}function Ny(e){if(e==null)throw new Error("PartUnion is required");if(typeof e=="object")return e;if(typeof e=="string")return{text:e};throw new Error(`Unsupported part type: ${typeof e}`)}function nA(e){if(e==null||Array.isArray(e)&&e.length===0)throw new Error("PartListUnion is required");return Array.isArray(e)?e.map(t=>Ny(t)):[Ny(e)]}function pd(e){return e!=null&&typeof e=="object"&&"parts"in e&&Array.isArray(e.parts)}function Fy(e){return e!=null&&typeof e=="object"&&"functionCall"in e}function ky(e){return e!=null&&typeof e=="object"&&"functionResponse"in e}function Qe(e){if(e==null)throw new Error("ContentUnion is required");return pd(e)?e:{role:"user",parts:nA(e)}}function Qd(e,t){if(!t)return[];if(e.isVertexAI()&&Array.isArray(t))return t.flatMap(n=>{const r=Qe(n);return r.parts&&r.parts.length>0&&r.parts[0].text!==void 0?[r.parts[0].text]:[]});if(e.isVertexAI()){const n=Qe(t);return n.parts&&n.parts.length>0&&n.parts[0].text!==void 0?[n.parts[0].text]:[]}return Array.isArray(t)?t.map(n=>Qe(n)):[Qe(t)]}function mt(e){if(e==null||Array.isArray(e)&&e.length===0)throw new Error("contents are required");if(!Array.isArray(e)){if(Fy(e)||ky(e))throw new Error("To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them");return[Qe(e)]}const t=[],n=[],r=pd(e[0]);for(const s of e){const o=pd(s);if(o!=r)throw new Error("Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them");if(o)t.push(s);else{if(Fy(s)||ky(s))throw new Error("To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them");n.push(s)}}return r||t.push({role:"user",parts:nA(n)}),t}function gC(e,t){e.includes("null")&&(t.nullable=!0);const n=e.filter(r=>r!=="null");if(n.length===1)t.type=Object.values(pn).includes(n[0].toUpperCase())?n[0].toUpperCase():pn.TYPE_UNSPECIFIED;else{t.anyOf=[];for(const r of n)t.anyOf.push({type:Object.values(pn).includes(r.toUpperCase())?r.toUpperCase():pn.TYPE_UNSPECIFIED})}}function Dr(e){const t={},n=["items"],r=["anyOf"],s=["properties"];if(e.type&&e.anyOf)throw new Error("type and anyOf cannot be both populated.");const o=e.anyOf;o!=null&&o.length==2&&(o[0].type==="null"?(t.nullable=!0,e=o[1]):o[1].type==="null"&&(t.nullable=!0,e=o[0])),e.type instanceof Array&&gC(e.type,t);for(const[i,a]of Object.entries(e))if(a!=null)if(i=="type"){if(a==="null")throw new Error("type: null can not be the only possible type for the field.");if(a instanceof Array)continue;t.type=Object.values(pn).includes(a.toUpperCase())?a.toUpperCase():pn.TYPE_UNSPECIFIED}else if(n.includes(i))t[i]=Dr(a);else if(r.includes(i)){const l=[];for(const u of a){if(u.type=="null"){t.nullable=!0;continue}l.push(Dr(u))}t[i]=l}else if(s.includes(i)){const l={};for(const[u,c]of Object.entries(a))l[u]=Dr(c);t[i]=l}else{if(i==="additionalProperties")continue;t[i]=a}return t}function Zd(e){return Dr(e)}function ef(e){if(typeof e=="object")return e;if(typeof e=="string")return{voiceConfig:{prebuiltVoiceConfig:{voiceName:e}}};throw new Error(`Unsupported speechConfig type: ${typeof e}`)}function tf(e){if("multiSpeakerVoiceConfig"in e)throw new Error("multiSpeakerVoiceConfig is not supported in the live API.");return e}function Jr(e){if(e.functionDeclarations)for(const t of e.functionDeclarations)t.parameters&&(Object.keys(t.parameters).includes("$schema")?t.parametersJsonSchema||(t.parametersJsonSchema=t.parameters,delete t.parameters):t.parameters=Dr(t.parameters)),t.response&&(Object.keys(t.response).includes("$schema")?t.responseJsonSchema||(t.responseJsonSchema=t.response,delete t.response):t.response=Dr(t.response));return e}function jr(e){if(e==null)throw new Error("tools is required");if(!Array.isArray(e))throw new Error("tools is required and must be an array of Tools");const t=[];for(const n of e)t.push(n);return t}function mC(e,t,n,r=1){const s=!t.startsWith(`${n}/`)&&t.split("/").length===r;return e.isVertexAI()?t.startsWith("projects/")?t:t.startsWith("locations/")?`projects/${e.getProject()}/${t}`:t.startsWith(`${n}/`)?`projects/${e.getProject()}/locations/${e.getLocation()}/${t}`:s?`projects/${e.getProject()}/locations/${e.getLocation()}/${n}/${t}`:t:s?`${n}/${t}`:t}function wn(e,t){if(typeof t!="string")throw new Error("name must be a string");return mC(e,t,"cachedContents")}function rA(e){switch(e){case"STATE_UNSPECIFIED":return"JOB_STATE_UNSPECIFIED";case"CREATING":return"JOB_STATE_RUNNING";case"ACTIVE":return"JOB_STATE_SUCCEEDED";case"FAILED":return"JOB_STATE_FAILED";default:return e}}function xn(e){return Xd(e)}function _C(e){return e!=null&&typeof e=="object"&&"name"in e}function yC(e){return e!=null&&typeof e=="object"&&"video"in e}function vC(e){return e!=null&&typeof e=="object"&&"uri"in e}function sA(e){var t;let n;if(_C(e)&&(n=e.name),!(vC(e)&&(n=e.uri,n===void 0))&&!(yC(e)&&(n=(t=e.video)===null||t===void 0?void 0:t.uri,n===void 0))){if(typeof e=="string"&&(n=e),n===void 0)throw new Error("Could not extract file name from the provided input.");if(n.startsWith("https://")){const s=n.split("files/")[1].match(/[a-z0-9]+/);if(s===null)throw new Error(`Could not extract file name from URI ${n}`);n=s[0]}else n.startsWith("files/")&&(n=n.split("files/")[1]);return n}}function oA(e,t){let n;return e.isVertexAI()?n=t?"publishers/google/models":"models":n=t?"models":"tunedModels",n}function iA(e){for(const t of["models","tunedModels","publisherModels"])if(bC(e,t))return e[t];return[]}function bC(e,t){return e!==null&&typeof e=="object"&&t in e}function AC(e,t={}){const n=e,r={name:n.name,description:n.description,parametersJsonSchema:n.inputSchema};return n.outputSchema&&(r.responseJsonSchema=n.outputSchema),t.behavior&&(r.behavior=t.behavior),{functionDeclarations:[r]}}function SC(e,t={}){const n=[],r=new Set;for(const s of e){const o=s.name;if(r.has(o))throw new Error(`Duplicate function name ${o} found in MCP tools. Please ensure function names are unique.`);r.add(o);const i=AC(s,t);i.functionDeclarations&&n.push(...i.functionDeclarations)}return{functionDeclarations:n}}function aA(e,t){let n;if(typeof t=="string")if(e.isVertexAI())if(t.startsWith("gs://"))n={format:"jsonl",gcsUri:[t]};else if(t.startsWith("bq://"))n={format:"bigquery",bigqueryUri:t};else throw new Error(`Unsupported string source for Vertex AI: ${t}`);else if(t.startsWith("files/"))n={fileName:t};else throw new Error(`Unsupported string source for Gemini API: ${t}`);else if(Array.isArray(t)){if(e.isVertexAI())throw new Error("InlinedRequest[] is not supported in Vertex AI.");n={inlinedRequests:t}}else n=t;const r=[n.gcsUri,n.bigqueryUri].filter(Boolean).length,s=[n.inlinedRequests,n.fileName].filter(Boolean).length;if(e.isVertexAI()){if(s>0||r!==1)throw new Error("Exactly one of `gcsUri` or `bigqueryUri` must be set for Vertex AI.")}else if(r>0||s!==1)throw new Error("Exactly one of `inlinedRequests`, `fileName`, must be set for Gemini API.");return n}function wC(e){if(typeof e!="string")return e;const t=e;if(t.startsWith("gs://"))return{format:"jsonl",gcsUri:t};if(t.startsWith("bq://"))return{format:"bigquery",bigqueryUri:t};throw new Error(`Unsupported destination: ${t}`)}function lA(e){if(typeof e!="object"||e===null)return{};const t=e,n=t.inlinedResponses;if(typeof n!="object"||n===null)return e;const s=n.inlinedResponses;if(!Array.isArray(s)||s.length===0)return e;let o=!1;for(const i of s){if(typeof i!="object"||i===null)continue;const l=i.response;if(typeof l!="object"||l===null)continue;if(l.embedding!==void 0){o=!0;break}}return o&&(t.inlinedEmbedContentResponses=t.inlinedResponses,delete t.inlinedResponses),e}function Wr(e,t){const n=t;if(!e.isVertexAI()){if(/batches\/[^/]+$/.test(n))return n.split("/").pop();throw new Error(`Invalid batch job name: ${n}.`)}if(/^projects\/[^/]+\/locations\/[^/]+\/batchPredictionJobs\/[^/]+$/.test(n))return n.split("/").pop();if(/^\d+$/.test(n))return n;throw new Error(`Invalid batch job name: ${n}.`)}function uA(e){const t=e;return t==="BATCH_STATE_UNSPECIFIED"?"JOB_STATE_UNSPECIFIED":t==="BATCH_STATE_PENDING"?"JOB_STATE_PENDING":t==="BATCH_STATE_RUNNING"?"JOB_STATE_RUNNING":t==="BATCH_STATE_SUCCEEDED"?"JOB_STATE_SUCCEEDED":t==="BATCH_STATE_FAILED"?"JOB_STATE_FAILED":t==="BATCH_STATE_CANCELLED"?"JOB_STATE_CANCELLED":t==="BATCH_STATE_EXPIRED"?"JOB_STATE_EXPIRED":t}function EC(e){const t={},n=f(e,["responsesFile"]);n!=null&&h(t,["fileName"],n);const r=f(e,["inlinedResponses","inlinedResponses"]);if(r!=null){let o=r;Array.isArray(o)&&(o=o.map(i=>sR(i))),h(t,["inlinedResponses"],o)}const s=f(e,["inlinedEmbedContentResponses","inlinedResponses"]);if(s!=null){let o=s;Array.isArray(o)&&(o=o.map(i=>i)),h(t,["inlinedEmbedContentResponses"],o)}return t}function TC(e){const t={},n=f(e,["predictionsFormat"]);n!=null&&h(t,["format"],n);const r=f(e,["gcsDestination","outputUriPrefix"]);r!=null&&h(t,["gcsUri"],r);const s=f(e,["bigqueryDestination","outputUri"]);return s!=null&&h(t,["bigqueryUri"],s),t}function PC(e){const t={},n=f(e,["format"]);n!=null&&h(t,["predictionsFormat"],n);const r=f(e,["gcsUri"]);r!=null&&h(t,["gcsDestination","outputUriPrefix"],r);const s=f(e,["bigqueryUri"]);if(s!=null&&h(t,["bigqueryDestination","outputUri"],s),f(e,["fileName"])!==void 0)throw new Error("fileName parameter is not supported in Vertex AI.");if(f(e,["inlinedResponses"])!==void 0)throw new Error("inlinedResponses parameter is not supported in Vertex AI.");if(f(e,["inlinedEmbedContentResponses"])!==void 0)throw new Error("inlinedEmbedContentResponses parameter is not supported in Vertex AI.");return t}function ia(e){const t={},n=f(e,["name"]);n!=null&&h(t,["name"],n);const r=f(e,["metadata","displayName"]);r!=null&&h(t,["displayName"],r);const s=f(e,["metadata","state"]);s!=null&&h(t,["state"],uA(s));const o=f(e,["metadata","createTime"]);o!=null&&h(t,["createTime"],o);const i=f(e,["metadata","endTime"]);i!=null&&h(t,["endTime"],i);const a=f(e,["metadata","updateTime"]);a!=null&&h(t,["updateTime"],a);const l=f(e,["metadata","model"]);l!=null&&h(t,["model"],l);const u=f(e,["metadata","output"]);return u!=null&&h(t,["dest"],EC(lA(u))),t}function hd(e){const t={},n=f(e,["name"]);n!=null&&h(t,["name"],n);const r=f(e,["displayName"]);r!=null&&h(t,["displayName"],r);const s=f(e,["state"]);s!=null&&h(t,["state"],uA(s));const o=f(e,["error"]);o!=null&&h(t,["error"],o);const i=f(e,["createTime"]);i!=null&&h(t,["createTime"],i);const a=f(e,["startTime"]);a!=null&&h(t,["startTime"],a);const l=f(e,["endTime"]);l!=null&&h(t,["endTime"],l);const u=f(e,["updateTime"]);u!=null&&h(t,["updateTime"],u);const c=f(e,["model"]);c!=null&&h(t,["model"],c);const d=f(e,["inputConfig"]);d!=null&&h(t,["src"],IC(d));const p=f(e,["outputConfig"]);p!=null&&h(t,["dest"],TC(lA(p)));const g=f(e,["completionStats"]);return g!=null&&h(t,["completionStats"],g),t}function IC(e){const t={},n=f(e,["instancesFormat"]);n!=null&&h(t,["format"],n);const r=f(e,["gcsSource","uris"]);r!=null&&h(t,["gcsUri"],r);const s=f(e,["bigquerySource","inputUri"]);return s!=null&&h(t,["bigqueryUri"],s),t}function CC(e,t){const n={};if(f(t,["format"])!==void 0)throw new Error("format parameter is not supported in Gemini API.");if(f(t,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is not supported in Gemini API.");if(f(t,["bigqueryUri"])!==void 0)throw new Error("bigqueryUri parameter is not supported in Gemini API.");const r=f(t,["fileName"]);r!=null&&h(n,["fileName"],r);const s=f(t,["inlinedRequests"]);if(s!=null){let o=s;Array.isArray(o)&&(o=o.map(i=>rR(e,i))),h(n,["requests","requests"],o)}return n}function RC(e){const t={},n=f(e,["format"]);n!=null&&h(t,["instancesFormat"],n);const r=f(e,["gcsUri"]);r!=null&&h(t,["gcsSource","uris"],r);const s=f(e,["bigqueryUri"]);if(s!=null&&h(t,["bigquerySource","inputUri"],s),f(e,["fileName"])!==void 0)throw new Error("fileName parameter is not supported in Vertex AI.");if(f(e,["inlinedRequests"])!==void 0)throw new Error("inlinedRequests parameter is not supported in Vertex AI.");return t}function MC(e){const t={},n=f(e,["data"]);if(n!=null&&h(t,["data"],n),f(e,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");const r=f(e,["mimeType"]);return r!=null&&h(t,["mimeType"],r),t}function NC(e,t){const n={},r=f(t,["name"]);return r!=null&&h(n,["_url","name"],Wr(e,r)),n}function FC(e,t){const n={},r=f(t,["name"]);return r!=null&&h(n,["_url","name"],Wr(e,r)),n}function kC(e){const t={},n=f(e,["content"]);n!=null&&h(t,["content"],n);const r=f(e,["citationMetadata"]);r!=null&&h(t,["citationMetadata"],OC(r));const s=f(e,["tokenCount"]);s!=null&&h(t,["tokenCount"],s);const o=f(e,["finishReason"]);o!=null&&h(t,["finishReason"],o);const i=f(e,["avgLogprobs"]);i!=null&&h(t,["avgLogprobs"],i);const a=f(e,["groundingMetadata"]);a!=null&&h(t,["groundingMetadata"],a);const l=f(e,["index"]);l!=null&&h(t,["index"],l);const u=f(e,["logprobsResult"]);u!=null&&h(t,["logprobsResult"],u);const c=f(e,["safetyRatings"]);if(c!=null){let p=c;Array.isArray(p)&&(p=p.map(g=>g)),h(t,["safetyRatings"],p)}const d=f(e,["urlContextMetadata"]);return d!=null&&h(t,["urlContextMetadata"],d),t}function OC(e){const t={},n=f(e,["citationSources"]);if(n!=null){let r=n;Array.isArray(r)&&(r=r.map(s=>s)),h(t,["citations"],r)}return t}function cA(e){const t={},n=f(e,["parts"]);if(n!=null){let s=n;Array.isArray(s)&&(s=s.map(o=>dR(o))),h(t,["parts"],s)}const r=f(e,["role"]);return r!=null&&h(t,["role"],r),t}function xC(e,t){const n={},r=f(e,["displayName"]);if(t!==void 0&&r!=null&&h(t,["batch","displayName"],r),f(e,["dest"])!==void 0)throw new Error("dest parameter is not supported in Gemini API.");return n}function DC(e,t){const n={},r=f(e,["displayName"]);t!==void 0&&r!=null&&h(t,["displayName"],r);const s=f(e,["dest"]);return t!==void 0&&s!=null&&h(t,["outputConfig"],PC(wC(s))),n}function Oy(e,t){const n={},r=f(t,["model"]);r!=null&&h(n,["_url","model"],Ee(e,r));const s=f(t,["src"]);s!=null&&h(n,["batch","inputConfig"],CC(e,aA(e,s)));const o=f(t,["config"]);return o!=null&&xC(o,n),n}function qC(e,t){const n={},r=f(t,["model"]);r!=null&&h(n,["model"],Ee(e,r));const s=f(t,["src"]);s!=null&&h(n,["inputConfig"],RC(aA(e,s)));const o=f(t,["config"]);return o!=null&&DC(o,n),n}function LC(e,t){const n={},r=f(e,["displayName"]);return t!==void 0&&r!=null&&h(t,["batch","displayName"],r),n}function UC(e,t){const n={},r=f(t,["model"]);r!=null&&h(n,["_url","model"],Ee(e,r));const s=f(t,["src"]);s!=null&&h(n,["batch","inputConfig"],WC(e,s));const o=f(t,["config"]);return o!=null&&LC(o,n),n}function GC(e,t){const n={},r=f(t,["name"]);return r!=null&&h(n,["_url","name"],Wr(e,r)),n}function VC(e,t){const n={},r=f(t,["name"]);return r!=null&&h(n,["_url","name"],Wr(e,r)),n}function BC(e){const t={},n=f(e,["sdkHttpResponse"]);n!=null&&h(t,["sdkHttpResponse"],n);const r=f(e,["name"]);r!=null&&h(t,["name"],r);const s=f(e,["done"]);s!=null&&h(t,["done"],s);const o=f(e,["error"]);return o!=null&&h(t,["error"],o),t}function HC(e){const t={},n=f(e,["sdkHttpResponse"]);n!=null&&h(t,["sdkHttpResponse"],n);const r=f(e,["name"]);r!=null&&h(t,["name"],r);const s=f(e,["done"]);s!=null&&h(t,["done"],s);const o=f(e,["error"]);return o!=null&&h(t,["error"],o),t}function JC(e,t){const n={},r=f(t,["contents"]);if(r!=null){let o=Qd(e,r);Array.isArray(o)&&(o=o.map(i=>i)),h(n,["requests[]","request","content"],o)}const s=f(t,["config"]);return s!=null&&(h(n,["_self"],jC(s,n)),wI(n,{"requests[].*":"requests[].request.*"})),n}function jC(e,t){const n={},r=f(e,["taskType"]);t!==void 0&&r!=null&&h(t,["requests[]","taskType"],r);const s=f(e,["title"]);t!==void 0&&s!=null&&h(t,["requests[]","title"],s);const o=f(e,["outputDimensionality"]);if(t!==void 0&&o!=null&&h(t,["requests[]","outputDimensionality"],o),f(e,["mimeType"])!==void 0)throw new Error("mimeType parameter is not supported in Gemini API.");if(f(e,["autoTruncate"])!==void 0)throw new Error("autoTruncate parameter is not supported in Gemini API.");return n}function WC(e,t){const n={},r=f(t,["fileName"]);r!=null&&h(n,["file_name"],r);const s=f(t,["inlinedRequests"]);return s!=null&&h(n,["requests"],JC(e,s)),n}function KC(e){const t={};if(f(e,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");const n=f(e,["fileUri"]);n!=null&&h(t,["fileUri"],n);const r=f(e,["mimeType"]);return r!=null&&h(t,["mimeType"],r),t}function $C(e){const t={},n=f(e,["id"]);n!=null&&h(t,["id"],n);const r=f(e,["args"]);r!=null&&h(t,["args"],r);const s=f(e,["name"]);if(s!=null&&h(t,["name"],s),f(e,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is not supported in Gemini API.");if(f(e,["willContinue"])!==void 0)throw new Error("willContinue parameter is not supported in Gemini API.");return t}function YC(e){const t={},n=f(e,["allowedFunctionNames"]);n!=null&&h(t,["allowedFunctionNames"],n);const r=f(e,["mode"]);if(r!=null&&h(t,["mode"],r),f(e,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is not supported in Gemini API.");return t}function zC(e,t,n){const r={},s=f(t,["systemInstruction"]);n!==void 0&&s!=null&&h(n,["systemInstruction"],cA(Qe(s)));const o=f(t,["temperature"]);o!=null&&h(r,["temperature"],o);const i=f(t,["topP"]);i!=null&&h(r,["topP"],i);const a=f(t,["topK"]);a!=null&&h(r,["topK"],a);const l=f(t,["candidateCount"]);l!=null&&h(r,["candidateCount"],l);const u=f(t,["maxOutputTokens"]);u!=null&&h(r,["maxOutputTokens"],u);const c=f(t,["stopSequences"]);c!=null&&h(r,["stopSequences"],c);const d=f(t,["responseLogprobs"]);d!=null&&h(r,["responseLogprobs"],d);const p=f(t,["logprobs"]);p!=null&&h(r,["logprobs"],p);const g=f(t,["presencePenalty"]);g!=null&&h(r,["presencePenalty"],g);const y=f(t,["frequencyPenalty"]);y!=null&&h(r,["frequencyPenalty"],y);const _=f(t,["seed"]);_!=null&&h(r,["seed"],_);const b=f(t,["responseMimeType"]);b!=null&&h(r,["responseMimeType"],b);const m=f(t,["responseSchema"]);m!=null&&h(r,["responseSchema"],Zd(m));const v=f(t,["responseJsonSchema"]);if(v!=null&&h(r,["responseJsonSchema"],v),f(t,["routingConfig"])!==void 0)throw new Error("routingConfig parameter is not supported in Gemini API.");if(f(t,["modelSelectionConfig"])!==void 0)throw new Error("modelSelectionConfig parameter is not supported in Gemini API.");const A=f(t,["safetySettings"]);if(n!==void 0&&A!=null){let j=A;Array.isArray(j)&&(j=j.map(U=>fR(U))),h(n,["safetySettings"],j)}const S=f(t,["tools"]);if(n!==void 0&&S!=null){let j=jr(S);Array.isArray(j)&&(j=j.map(U=>hR(Jr(U)))),h(n,["tools"],j)}const P=f(t,["toolConfig"]);if(n!==void 0&&P!=null&&h(n,["toolConfig"],pR(P)),f(t,["labels"])!==void 0)throw new Error("labels parameter is not supported in Gemini API.");const E=f(t,["cachedContent"]);n!==void 0&&E!=null&&h(n,["cachedContent"],wn(e,E));const w=f(t,["responseModalities"]);w!=null&&h(r,["responseModalities"],w);const I=f(t,["mediaResolution"]);I!=null&&h(r,["mediaResolution"],I);const L=f(t,["speechConfig"]);if(L!=null&&h(r,["speechConfig"],ef(L)),f(t,["audioTimestamp"])!==void 0)throw new Error("audioTimestamp parameter is not supported in Gemini API.");const H=f(t,["thinkingConfig"]);H!=null&&h(r,["thinkingConfig"],H);const B=f(t,["imageConfig"]);B!=null&&h(r,["imageConfig"],nR(B));const F=f(t,["enableEnhancedCivicAnswers"]);if(F!=null&&h(r,["enableEnhancedCivicAnswers"],F),f(t,["modelArmorConfig"])!==void 0)throw new Error("modelArmorConfig parameter is not supported in Gemini API.");return r}function XC(e){const t={},n=f(e,["sdkHttpResponse"]);n!=null&&h(t,["sdkHttpResponse"],n);const r=f(e,["candidates"]);if(r!=null){let l=r;Array.isArray(l)&&(l=l.map(u=>kC(u))),h(t,["candidates"],l)}const s=f(e,["modelVersion"]);s!=null&&h(t,["modelVersion"],s);const o=f(e,["promptFeedback"]);o!=null&&h(t,["promptFeedback"],o);const i=f(e,["responseId"]);i!=null&&h(t,["responseId"],i);const a=f(e,["usageMetadata"]);return a!=null&&h(t,["usageMetadata"],a),t}function QC(e,t){const n={},r=f(t,["name"]);return r!=null&&h(n,["_url","name"],Wr(e,r)),n}function ZC(e,t){const n={},r=f(t,["name"]);return r!=null&&h(n,["_url","name"],Wr(e,r)),n}function eR(e){const t={};if(f(e,["authConfig"])!==void 0)throw new Error("authConfig parameter is not supported in Gemini API.");const n=f(e,["enableWidget"]);return n!=null&&h(t,["enableWidget"],n),t}function tR(e){const t={};if(f(e,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is not supported in Gemini API.");if(f(e,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is not supported in Gemini API.");const n=f(e,["timeRangeFilter"]);return n!=null&&h(t,["timeRangeFilter"],n),t}function nR(e){const t={},n=f(e,["aspectRatio"]);n!=null&&h(t,["aspectRatio"],n);const r=f(e,["imageSize"]);if(r!=null&&h(t,["imageSize"],r),f(e,["personGeneration"])!==void 0)throw new Error("personGeneration parameter is not supported in Gemini API.");if(f(e,["outputMimeType"])!==void 0)throw new Error("outputMimeType parameter is not supported in Gemini API.");if(f(e,["outputCompressionQuality"])!==void 0)throw new Error("outputCompressionQuality parameter is not supported in Gemini API.");return t}function rR(e,t){const n={},r=f(t,["model"]);r!=null&&h(n,["request","model"],Ee(e,r));const s=f(t,["contents"]);if(s!=null){let a=mt(s);Array.isArray(a)&&(a=a.map(l=>cA(l))),h(n,["request","contents"],a)}const o=f(t,["metadata"]);o!=null&&h(n,["metadata"],o);const i=f(t,["config"]);return i!=null&&h(n,["request","generationConfig"],zC(e,i,f(n,["request"],{}))),n}function sR(e){const t={},n=f(e,["response"]);n!=null&&h(t,["response"],XC(n));const r=f(e,["metadata"]);r!=null&&h(t,["metadata"],r);const s=f(e,["error"]);return s!=null&&h(t,["error"],s),t}function oR(e,t){const n={},r=f(e,["pageSize"]);t!==void 0&&r!=null&&h(t,["_query","pageSize"],r);const s=f(e,["pageToken"]);if(t!==void 0&&s!=null&&h(t,["_query","pageToken"],s),f(e,["filter"])!==void 0)throw new Error("filter parameter is not supported in Gemini API.");return n}function iR(e,t){const n={},r=f(e,["pageSize"]);t!==void 0&&r!=null&&h(t,["_query","pageSize"],r);const s=f(e,["pageToken"]);t!==void 0&&s!=null&&h(t,["_query","pageToken"],s);const o=f(e,["filter"]);return t!==void 0&&o!=null&&h(t,["_query","filter"],o),n}function aR(e){const t={},n=f(e,["config"]);return n!=null&&oR(n,t),t}function lR(e){const t={},n=f(e,["config"]);return n!=null&&iR(n,t),t}function uR(e){const t={},n=f(e,["sdkHttpResponse"]);n!=null&&h(t,["sdkHttpResponse"],n);const r=f(e,["nextPageToken"]);r!=null&&h(t,["nextPageToken"],r);const s=f(e,["operations"]);if(s!=null){let o=s;Array.isArray(o)&&(o=o.map(i=>ia(i))),h(t,["batchJobs"],o)}return t}function cR(e){const t={},n=f(e,["sdkHttpResponse"]);n!=null&&h(t,["sdkHttpResponse"],n);const r=f(e,["nextPageToken"]);r!=null&&h(t,["nextPageToken"],r);const s=f(e,["batchPredictionJobs"]);if(s!=null){let o=s;Array.isArray(o)&&(o=o.map(i=>hd(i))),h(t,["batchJobs"],o)}return t}function dR(e){const t={},n=f(e,["mediaResolution"]);n!=null&&h(t,["mediaResolution"],n);const r=f(e,["codeExecutionResult"]);r!=null&&h(t,["codeExecutionResult"],r);const s=f(e,["executableCode"]);s!=null&&h(t,["executableCode"],s);const o=f(e,["fileData"]);o!=null&&h(t,["fileData"],KC(o));const i=f(e,["functionCall"]);i!=null&&h(t,["functionCall"],$C(i));const a=f(e,["functionResponse"]);a!=null&&h(t,["functionResponse"],a);const l=f(e,["inlineData"]);l!=null&&h(t,["inlineData"],MC(l));const u=f(e,["text"]);u!=null&&h(t,["text"],u);const c=f(e,["thought"]);c!=null&&h(t,["thought"],c);const d=f(e,["thoughtSignature"]);d!=null&&h(t,["thoughtSignature"],d);const p=f(e,["videoMetadata"]);return p!=null&&h(t,["videoMetadata"],p),t}function fR(e){const t={},n=f(e,["category"]);if(n!=null&&h(t,["category"],n),f(e,["method"])!==void 0)throw new Error("method parameter is not supported in Gemini API.");const r=f(e,["threshold"]);return r!=null&&h(t,["threshold"],r),t}function pR(e){const t={},n=f(e,["retrievalConfig"]);n!=null&&h(t,["retrievalConfig"],n);const r=f(e,["functionCallingConfig"]);return r!=null&&h(t,["functionCallingConfig"],YC(r)),t}function hR(e){const t={};if(f(e,["retrieval"])!==void 0)throw new Error("retrieval parameter is not supported in Gemini API.");const n=f(e,["computerUse"]);n!=null&&h(t,["computerUse"],n);const r=f(e,["fileSearch"]);r!=null&&h(t,["fileSearch"],r);const s=f(e,["codeExecution"]);if(s!=null&&h(t,["codeExecution"],s),f(e,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");const o=f(e,["functionDeclarations"]);if(o!=null){let c=o;Array.isArray(c)&&(c=c.map(d=>d)),h(t,["functionDeclarations"],c)}const i=f(e,["googleMaps"]);i!=null&&h(t,["googleMaps"],eR(i));const a=f(e,["googleSearch"]);a!=null&&h(t,["googleSearch"],tR(a));const l=f(e,["googleSearchRetrieval"]);l!=null&&h(t,["googleSearchRetrieval"],l);const u=f(e,["urlContext"]);return u!=null&&h(t,["urlContext"],u),t}var zt;(function(e){e.PAGED_ITEM_BATCH_JOBS="batchJobs",e.PAGED_ITEM_MODELS="models",e.PAGED_ITEM_TUNING_JOBS="tuningJobs",e.PAGED_ITEM_FILES="files",e.PAGED_ITEM_CACHED_CONTENTS="cachedContents",e.PAGED_ITEM_FILE_SEARCH_STORES="fileSearchStores",e.PAGED_ITEM_DOCUMENTS="documents"})(zt||(zt={}));class Dn{constructor(t,n,r,s){this.pageInternal=[],this.paramsInternal={},this.requestInternal=n,this.init(t,r,s)}init(t,n,r){var s,o;this.nameInternal=t,this.pageInternal=n[this.nameInternal]||[],this.sdkHttpResponseInternal=n?.sdkHttpResponse,this.idxInternal=0;let i={config:{}};!r||Object.keys(r).length===0?i={config:{}}:typeof r=="object"?i=Object.assign({},r):i=r,i.config&&(i.config.pageToken=n.nextPageToken),this.paramsInternal=i,this.pageInternalSize=(o=(s=i.config)===null||s===void 0?void 0:s.pageSize)!==null&&o!==void 0?o:this.pageInternal.length}initNextPage(t){this.init(this.nameInternal,t,this.paramsInternal)}get page(){return this.pageInternal}get name(){return this.nameInternal}get pageSize(){return this.pageInternalSize}get sdkHttpResponse(){return this.sdkHttpResponseInternal}get params(){return this.paramsInternal}get pageLength(){return this.pageInternal.length}getItem(t){return this.pageInternal[t]}[Symbol.asyncIterator](){return{next:async()=>{if(this.idxInternal>=this.pageLength)if(this.hasNextPage())await this.nextPage();else return{value:void 0,done:!0};const t=this.getItem(this.idxInternal);return this.idxInternal+=1,{value:t,done:!1}},return:async()=>({value:void 0,done:!0})}}async nextPage(){if(!this.hasNextPage())throw new Error("No more pages to fetch.");const t=await this.requestInternal(this.params);return this.initNextPage(t),this.page}hasNextPage(){var t;return((t=this.params.config)===null||t===void 0?void 0:t.pageToken)!==void 0}}class dA extends Sn{constructor(t){super(),this.apiClient=t,this.list=async(n={})=>new Dn(zt.PAGED_ITEM_BATCH_JOBS,r=>this.listInternal(r),await this.listInternal(n),n),this.create=async n=>(this.apiClient.isVertexAI()&&(n.config=this.formatDestination(n.src,n.config)),this.createInternal(n)),this.createEmbeddings=async n=>{if(console.warn("batches.createEmbeddings() is experimental and may change without notice."),this.apiClient.isVertexAI())throw new Error("Vertex AI does not support batches.createEmbeddings.");return this.createEmbeddingsInternal(n)}}createInlinedGenerateContentRequest(t){const n=Oy(this.apiClient,t),r=n._url,s=ie("{model}:batchGenerateContent",r),a=n.batch.inputConfig.requests,l=a.requests,u=[];for(const c of l){const d=Object.assign({},c);if(d.systemInstruction){const p=d.systemInstruction;delete d.systemInstruction;const g=d.request;g.systemInstruction=p,d.request=g}u.push(d)}return a.requests=u,delete n.config,delete n._url,delete n._query,{path:s,body:n}}getGcsUri(t){if(typeof t=="string")return t.startsWith("gs://")?t:void 0;if(!Array.isArray(t)&&t.gcsUri&&t.gcsUri.length>0)return t.gcsUri[0]}getBigqueryUri(t){if(typeof t=="string")return t.startsWith("bq://")?t:void 0;if(!Array.isArray(t))return t.bigqueryUri}formatDestination(t,n){const r=n?Object.assign({},n):{},s=Date.now().toString();if(r.displayName||(r.displayName=`genaiBatchJob_${s}`),r.dest===void 0){const o=this.getGcsUri(t),i=this.getBigqueryUri(t);if(o)o.endsWith(".jsonl")?r.dest=`${o.slice(0,-6)}/dest`:r.dest=`${o}_dest_${s}`;else if(i)r.dest=`${i}_dest_${s}`;else throw new Error("Unsupported source for Vertex AI: No GCS or BigQuery URI found.")}return r}async createInternal(t){var n,r,s,o;let i,a="",l={};if(this.apiClient.isVertexAI()){const u=qC(this.apiClient,t);return a=ie("batchPredictionJobs",u._url),l=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json()),i.then(c=>hd(c))}else{const u=Oy(this.apiClient,t);return a=ie("{model}:batchGenerateContent",u._url),l=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(s=t.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(o=t.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json()),i.then(c=>ia(c))}}async createEmbeddingsInternal(t){var n,r;let s,o="",i={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const a=UC(this.apiClient,t);return o=ie("{model}:asyncBatchEmbedContent",a._url),i=a._query,delete a._url,delete a._query,s=this.apiClient.request({path:o,queryParams:i,body:JSON.stringify(a),httpMethod:"POST",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal}).then(l=>l.json()),s.then(l=>ia(l))}}async get(t){var n,r,s,o;let i,a="",l={};if(this.apiClient.isVertexAI()){const u=ZC(this.apiClient,t);return a=ie("batchPredictionJobs/{name}",u._url),l=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json()),i.then(c=>hd(c))}else{const u=QC(this.apiClient,t);return a=ie("batches/{name}",u._url),l=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(s=t.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(o=t.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json()),i.then(c=>ia(c))}}async cancel(t){var n,r,s,o;let i="",a={};if(this.apiClient.isVertexAI()){const l=FC(this.apiClient,t);i=ie("batchPredictionJobs/{name}:cancel",l._url),a=l._query,delete l._url,delete l._query,await this.apiClient.request({path:i,queryParams:a,body:JSON.stringify(l),httpMethod:"POST",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal})}else{const l=NC(this.apiClient,t);i=ie("batches/{name}:cancel",l._url),a=l._query,delete l._url,delete l._query,await this.apiClient.request({path:i,queryParams:a,body:JSON.stringify(l),httpMethod:"POST",httpOptions:(s=t.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(o=t.config)===null||o===void 0?void 0:o.abortSignal})}}async listInternal(t){var n,r,s,o;let i,a="",l={};if(this.apiClient.isVertexAI()){const u=lR(t);return a=ie("batchPredictionJobs",u._url),l=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json().then(d=>{const p=d;return p.sdkHttpResponse={headers:c.headers},p})),i.then(c=>{const d=cR(c),p=new fd;return Object.assign(p,d),p})}else{const u=aR(t);return a=ie("batches",u._url),l=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(s=t.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(o=t.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json().then(d=>{const p=d;return p.sdkHttpResponse={headers:c.headers},p})),i.then(c=>{const d=uR(c),p=new fd;return Object.assign(p,d),p})}}async delete(t){var n,r,s,o;let i,a="",l={};if(this.apiClient.isVertexAI()){const u=VC(this.apiClient,t);return a=ie("batchPredictionJobs/{name}",u._url),l=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"DELETE",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json().then(d=>{const p=d;return p.sdkHttpResponse={headers:c.headers},p})),i.then(c=>HC(c))}else{const u=GC(this.apiClient,t);return a=ie("batches/{name}",u._url),l=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"DELETE",httpOptions:(s=t.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(o=t.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json().then(d=>{const p=d;return p.sdkHttpResponse={headers:c.headers},p})),i.then(c=>BC(c))}}}function gR(e){const t={},n=f(e,["data"]);if(n!=null&&h(t,["data"],n),f(e,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");const r=f(e,["mimeType"]);return r!=null&&h(t,["mimeType"],r),t}function xy(e){const t={},n=f(e,["parts"]);if(n!=null){let s=n;Array.isArray(s)&&(s=s.map(o=>LR(o))),h(t,["parts"],s)}const r=f(e,["role"]);return r!=null&&h(t,["role"],r),t}function mR(e,t){const n={},r=f(e,["ttl"]);t!==void 0&&r!=null&&h(t,["ttl"],r);const s=f(e,["expireTime"]);t!==void 0&&s!=null&&h(t,["expireTime"],s);const o=f(e,["displayName"]);t!==void 0&&o!=null&&h(t,["displayName"],o);const i=f(e,["contents"]);if(t!==void 0&&i!=null){let c=mt(i);Array.isArray(c)&&(c=c.map(d=>xy(d))),h(t,["contents"],c)}const a=f(e,["systemInstruction"]);t!==void 0&&a!=null&&h(t,["systemInstruction"],xy(Qe(a)));const l=f(e,["tools"]);if(t!==void 0&&l!=null){let c=l;Array.isArray(c)&&(c=c.map(d=>GR(d))),h(t,["tools"],c)}const u=f(e,["toolConfig"]);if(t!==void 0&&u!=null&&h(t,["toolConfig"],UR(u)),f(e,["kmsKeyName"])!==void 0)throw new Error("kmsKeyName parameter is not supported in Gemini API.");return n}function _R(e,t){const n={},r=f(e,["ttl"]);t!==void 0&&r!=null&&h(t,["ttl"],r);const s=f(e,["expireTime"]);t!==void 0&&s!=null&&h(t,["expireTime"],s);const o=f(e,["displayName"]);t!==void 0&&o!=null&&h(t,["displayName"],o);const i=f(e,["contents"]);if(t!==void 0&&i!=null){let d=mt(i);Array.isArray(d)&&(d=d.map(p=>p)),h(t,["contents"],d)}const a=f(e,["systemInstruction"]);t!==void 0&&a!=null&&h(t,["systemInstruction"],Qe(a));const l=f(e,["tools"]);if(t!==void 0&&l!=null){let d=l;Array.isArray(d)&&(d=d.map(p=>VR(p))),h(t,["tools"],d)}const u=f(e,["toolConfig"]);t!==void 0&&u!=null&&h(t,["toolConfig"],u);const c=f(e,["kmsKeyName"]);return t!==void 0&&c!=null&&h(t,["encryption_spec","kmsKeyName"],c),n}function yR(e,t){const n={},r=f(t,["model"]);r!=null&&h(n,["model"],Q0(e,r));const s=f(t,["config"]);return s!=null&&mR(s,n),n}function vR(e,t){const n={},r=f(t,["model"]);r!=null&&h(n,["model"],Q0(e,r));const s=f(t,["config"]);return s!=null&&_R(s,n),n}function bR(e,t){const n={},r=f(t,["name"]);return r!=null&&h(n,["_url","name"],wn(e,r)),n}function AR(e,t){const n={},r=f(t,["name"]);return r!=null&&h(n,["_url","name"],wn(e,r)),n}function SR(e){const t={},n=f(e,["sdkHttpResponse"]);return n!=null&&h(t,["sdkHttpResponse"],n),t}function wR(e){const t={},n=f(e,["sdkHttpResponse"]);return n!=null&&h(t,["sdkHttpResponse"],n),t}function ER(e){const t={};if(f(e,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");const n=f(e,["fileUri"]);n!=null&&h(t,["fileUri"],n);const r=f(e,["mimeType"]);return r!=null&&h(t,["mimeType"],r),t}function TR(e){const t={},n=f(e,["id"]);n!=null&&h(t,["id"],n);const r=f(e,["args"]);r!=null&&h(t,["args"],r);const s=f(e,["name"]);if(s!=null&&h(t,["name"],s),f(e,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is not supported in Gemini API.");if(f(e,["willContinue"])!==void 0)throw new Error("willContinue parameter is not supported in Gemini API.");return t}function PR(e){const t={},n=f(e,["allowedFunctionNames"]);n!=null&&h(t,["allowedFunctionNames"],n);const r=f(e,["mode"]);if(r!=null&&h(t,["mode"],r),f(e,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is not supported in Gemini API.");return t}function IR(e){const t={},n=f(e,["description"]);n!=null&&h(t,["description"],n);const r=f(e,["name"]);r!=null&&h(t,["name"],r);const s=f(e,["parameters"]);s!=null&&h(t,["parameters"],s);const o=f(e,["parametersJsonSchema"]);o!=null&&h(t,["parametersJsonSchema"],o);const i=f(e,["response"]);i!=null&&h(t,["response"],i);const a=f(e,["responseJsonSchema"]);if(a!=null&&h(t,["responseJsonSchema"],a),f(e,["behavior"])!==void 0)throw new Error("behavior parameter is not supported in Vertex AI.");return t}function CR(e,t){const n={},r=f(t,["name"]);return r!=null&&h(n,["_url","name"],wn(e,r)),n}function RR(e,t){const n={},r=f(t,["name"]);return r!=null&&h(n,["_url","name"],wn(e,r)),n}function MR(e){const t={};if(f(e,["authConfig"])!==void 0)throw new Error("authConfig parameter is not supported in Gemini API.");const n=f(e,["enableWidget"]);return n!=null&&h(t,["enableWidget"],n),t}function NR(e){const t={};if(f(e,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is not supported in Gemini API.");if(f(e,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is not supported in Gemini API.");const n=f(e,["timeRangeFilter"]);return n!=null&&h(t,["timeRangeFilter"],n),t}function FR(e,t){const n={},r=f(e,["pageSize"]);t!==void 0&&r!=null&&h(t,["_query","pageSize"],r);const s=f(e,["pageToken"]);return t!==void 0&&s!=null&&h(t,["_query","pageToken"],s),n}function kR(e,t){const n={},r=f(e,["pageSize"]);t!==void 0&&r!=null&&h(t,["_query","pageSize"],r);const s=f(e,["pageToken"]);return t!==void 0&&s!=null&&h(t,["_query","pageToken"],s),n}function OR(e){const t={},n=f(e,["config"]);return n!=null&&FR(n,t),t}function xR(e){const t={},n=f(e,["config"]);return n!=null&&kR(n,t),t}function DR(e){const t={},n=f(e,["sdkHttpResponse"]);n!=null&&h(t,["sdkHttpResponse"],n);const r=f(e,["nextPageToken"]);r!=null&&h(t,["nextPageToken"],r);const s=f(e,["cachedContents"]);if(s!=null){let o=s;Array.isArray(o)&&(o=o.map(i=>i)),h(t,["cachedContents"],o)}return t}function qR(e){const t={},n=f(e,["sdkHttpResponse"]);n!=null&&h(t,["sdkHttpResponse"],n);const r=f(e,["nextPageToken"]);r!=null&&h(t,["nextPageToken"],r);const s=f(e,["cachedContents"]);if(s!=null){let o=s;Array.isArray(o)&&(o=o.map(i=>i)),h(t,["cachedContents"],o)}return t}function LR(e){const t={},n=f(e,["mediaResolution"]);n!=null&&h(t,["mediaResolution"],n);const r=f(e,["codeExecutionResult"]);r!=null&&h(t,["codeExecutionResult"],r);const s=f(e,["executableCode"]);s!=null&&h(t,["executableCode"],s);const o=f(e,["fileData"]);o!=null&&h(t,["fileData"],ER(o));const i=f(e,["functionCall"]);i!=null&&h(t,["functionCall"],TR(i));const a=f(e,["functionResponse"]);a!=null&&h(t,["functionResponse"],a);const l=f(e,["inlineData"]);l!=null&&h(t,["inlineData"],gR(l));const u=f(e,["text"]);u!=null&&h(t,["text"],u);const c=f(e,["thought"]);c!=null&&h(t,["thought"],c);const d=f(e,["thoughtSignature"]);d!=null&&h(t,["thoughtSignature"],d);const p=f(e,["videoMetadata"]);return p!=null&&h(t,["videoMetadata"],p),t}function UR(e){const t={},n=f(e,["retrievalConfig"]);n!=null&&h(t,["retrievalConfig"],n);const r=f(e,["functionCallingConfig"]);return r!=null&&h(t,["functionCallingConfig"],PR(r)),t}function GR(e){const t={};if(f(e,["retrieval"])!==void 0)throw new Error("retrieval parameter is not supported in Gemini API.");const n=f(e,["computerUse"]);n!=null&&h(t,["computerUse"],n);const r=f(e,["fileSearch"]);r!=null&&h(t,["fileSearch"],r);const s=f(e,["codeExecution"]);if(s!=null&&h(t,["codeExecution"],s),f(e,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");const o=f(e,["functionDeclarations"]);if(o!=null){let c=o;Array.isArray(c)&&(c=c.map(d=>d)),h(t,["functionDeclarations"],c)}const i=f(e,["googleMaps"]);i!=null&&h(t,["googleMaps"],MR(i));const a=f(e,["googleSearch"]);a!=null&&h(t,["googleSearch"],NR(a));const l=f(e,["googleSearchRetrieval"]);l!=null&&h(t,["googleSearchRetrieval"],l);const u=f(e,["urlContext"]);return u!=null&&h(t,["urlContext"],u),t}function VR(e){const t={},n=f(e,["retrieval"]);n!=null&&h(t,["retrieval"],n);const r=f(e,["computerUse"]);if(r!=null&&h(t,["computerUse"],r),f(e,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is not supported in Vertex AI.");const s=f(e,["codeExecution"]);s!=null&&h(t,["codeExecution"],s);const o=f(e,["enterpriseWebSearch"]);o!=null&&h(t,["enterpriseWebSearch"],o);const i=f(e,["functionDeclarations"]);if(i!=null){let d=i;Array.isArray(d)&&(d=d.map(p=>IR(p))),h(t,["functionDeclarations"],d)}const a=f(e,["googleMaps"]);a!=null&&h(t,["googleMaps"],a);const l=f(e,["googleSearch"]);l!=null&&h(t,["googleSearch"],l);const u=f(e,["googleSearchRetrieval"]);u!=null&&h(t,["googleSearchRetrieval"],u);const c=f(e,["urlContext"]);return c!=null&&h(t,["urlContext"],c),t}function BR(e,t){const n={},r=f(e,["ttl"]);t!==void 0&&r!=null&&h(t,["ttl"],r);const s=f(e,["expireTime"]);return t!==void 0&&s!=null&&h(t,["expireTime"],s),n}function HR(e,t){const n={},r=f(e,["ttl"]);t!==void 0&&r!=null&&h(t,["ttl"],r);const s=f(e,["expireTime"]);return t!==void 0&&s!=null&&h(t,["expireTime"],s),n}function JR(e,t){const n={},r=f(t,["name"]);r!=null&&h(n,["_url","name"],wn(e,r));const s=f(t,["config"]);return s!=null&&BR(s,n),n}function jR(e,t){const n={},r=f(t,["name"]);r!=null&&h(n,["_url","name"],wn(e,r));const s=f(t,["config"]);return s!=null&&HR(s,n),n}class fA extends Sn{constructor(t){super(),this.apiClient=t,this.list=async(n={})=>new Dn(zt.PAGED_ITEM_CACHED_CONTENTS,r=>this.listInternal(r),await this.listInternal(n),n)}async create(t){var n,r,s,o;let i,a="",l={};if(this.apiClient.isVertexAI()){const u=vR(this.apiClient,t);return a=ie("cachedContents",u._url),l=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json()),i.then(c=>c)}else{const u=yR(this.apiClient,t);return a=ie("cachedContents",u._url),l=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(s=t.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(o=t.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json()),i.then(c=>c)}}async get(t){var n,r,s,o;let i,a="",l={};if(this.apiClient.isVertexAI()){const u=RR(this.apiClient,t);return a=ie("{name}",u._url),l=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json()),i.then(c=>c)}else{const u=CR(this.apiClient,t);return a=ie("{name}",u._url),l=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(s=t.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(o=t.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json()),i.then(c=>c)}}async delete(t){var n,r,s,o;let i,a="",l={};if(this.apiClient.isVertexAI()){const u=AR(this.apiClient,t);return a=ie("{name}",u._url),l=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"DELETE",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json().then(d=>{const p=d;return p.sdkHttpResponse={headers:c.headers},p})),i.then(c=>{const d=wR(c),p=new cd;return Object.assign(p,d),p})}else{const u=bR(this.apiClient,t);return a=ie("{name}",u._url),l=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"DELETE",httpOptions:(s=t.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(o=t.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json().then(d=>{const p=d;return p.sdkHttpResponse={headers:c.headers},p})),i.then(c=>{const d=SR(c),p=new cd;return Object.assign(p,d),p})}}async update(t){var n,r,s,o;let i,a="",l={};if(this.apiClient.isVertexAI()){const u=jR(this.apiClient,t);return a=ie("{name}",u._url),l=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"PATCH",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json()),i.then(c=>c)}else{const u=JR(this.apiClient,t);return a=ie("{name}",u._url),l=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"PATCH",httpOptions:(s=t.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(o=t.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json()),i.then(c=>c)}}async listInternal(t){var n,r,s,o;let i,a="",l={};if(this.apiClient.isVertexAI()){const u=xR(t);return a=ie("cachedContents",u._url),l=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json().then(d=>{const p=d;return p.sdkHttpResponse={headers:c.headers},p})),i.then(c=>{const d=qR(c),p=new dd;return Object.assign(p,d),p})}else{const u=OR(t);return a=ie("cachedContents",u._url),l=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(s=t.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(o=t.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json().then(d=>{const p=d;return p.sdkHttpResponse={headers:c.headers},p})),i.then(c=>{const d=DR(c),p=new dd;return Object.assign(p,d),p})}}}function Ia(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,r=Object.getOwnPropertySymbols(e);s<r.length;s++)t.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(e,r[s])&&(n[r[s]]=e[r[s]]);return n}function Dy(e){var t=typeof Symbol=="function"&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length=="number")return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function me(e){return this instanceof me?(this.v=e,this):new me(e)}function Ft(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(e,t||[]),s,o=[];return s=Object.create((typeof AsyncIterator=="function"?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",i),s[Symbol.asyncIterator]=function(){return this},s;function i(g){return function(y){return Promise.resolve(y).then(g,d)}}function a(g,y){r[g]&&(s[g]=function(_){return new Promise(function(b,m){o.push([g,_,b,m])>1||l(g,_)})},y&&(s[g]=y(s[g])))}function l(g,y){try{u(r[g](y))}catch(_){p(o[0][3],_)}}function u(g){g.value instanceof me?Promise.resolve(g.value.v).then(c,d):p(o[0][2],g)}function c(g){l("next",g)}function d(g){l("throw",g)}function p(g,y){g(y),o.shift(),o.length&&l(o[0][0],o[0][1])}}function kt(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof Dy=="function"?Dy(e):e[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(o){n[o]=e[o]&&function(i){return new Promise(function(a,l){i=e[o](i),s(a,l,i.done,i.value)})}}function s(o,i,a,l){Promise.resolve(l).then(function(u){o({value:u,done:a})},i)}}function WR(e){var t;if(e.candidates==null||e.candidates.length===0)return!1;const n=(t=e.candidates[0])===null||t===void 0?void 0:t.content;return n===void 0?!1:pA(n)}function pA(e){if(e.parts===void 0||e.parts.length===0)return!1;for(const t of e.parts)if(t===void 0||Object.keys(t).length===0)return!1;return!0}function KR(e){if(e.length!==0){for(const t of e)if(t.role!=="user"&&t.role!=="model")throw new Error(`Role must be user or model, but got ${t.role}.`)}}function qy(e){if(e===void 0||e.length===0)return[];const t=[],n=e.length;let r=0;for(;r<n;)if(e[r].role==="user")t.push(e[r]),r++;else{const s=[];let o=!0;for(;r<n&&e[r].role==="model";)s.push(e[r]),o&&!pA(e[r])&&(o=!1),r++;o?t.push(...s):t.pop()}return t}class hA{constructor(t,n){this.modelsModule=t,this.apiClient=n}create(t){return new gA(this.apiClient,this.modelsModule,t.model,t.config,structuredClone(t.history))}}class gA{constructor(t,n,r,s={},o=[]){this.apiClient=t,this.modelsModule=n,this.model=r,this.config=s,this.history=o,this.sendPromise=Promise.resolve(),KR(o)}async sendMessage(t){var n;await this.sendPromise;const r=Qe(t.message),s=this.modelsModule.generateContent({model:this.model,contents:this.getHistory(!0).concat(r),config:(n=t.config)!==null&&n!==void 0?n:this.config});return this.sendPromise=(async()=>{var o,i,a;const l=await s,u=(i=(o=l.candidates)===null||o===void 0?void 0:o[0])===null||i===void 0?void 0:i.content,c=l.automaticFunctionCallingHistory,d=this.getHistory(!0).length;let p=[];c!=null&&(p=(a=c.slice(d))!==null&&a!==void 0?a:[]);const g=u?[u]:[];this.recordHistory(r,g,p)})(),await this.sendPromise.catch(()=>{this.sendPromise=Promise.resolve()}),s}async sendMessageStream(t){var n;await this.sendPromise;const r=Qe(t.message),s=this.modelsModule.generateContentStream({model:this.model,contents:this.getHistory(!0).concat(r),config:(n=t.config)!==null&&n!==void 0?n:this.config});this.sendPromise=s.then(()=>{}).catch(()=>{});const o=await s;return this.processStreamResponse(o,r)}getHistory(t=!1){const n=t?qy(this.history):this.history;return structuredClone(n)}processStreamResponse(t,n){return Ft(this,arguments,function*(){var s,o,i,a,l,u;const c=[];try{for(var d=!0,p=kt(t),g;g=yield me(p.next()),s=g.done,!s;d=!0){a=g.value,d=!1;const y=a;if(WR(y)){const _=(u=(l=y.candidates)===null||l===void 0?void 0:l[0])===null||u===void 0?void 0:u.content;_!==void 0&&c.push(_)}yield yield me(y)}}catch(y){o={error:y}}finally{try{!d&&!s&&(i=p.return)&&(yield me(i.call(p)))}finally{if(o)throw o.error}}this.recordHistory(n,c)})}recordHistory(t,n,r){let s=[];n.length>0&&n.every(o=>o.role!==void 0)?s=n:s.push({role:"model",parts:[]}),r&&r.length>0?this.history.push(...qy(r)):this.history.push(t),this.history.push(...s)}}class Br extends Error{constructor(t){super(t.message),this.name="ApiError",this.status=t.status,Object.setPrototypeOf(this,Br.prototype)}}function $R(e){const t={},n=f(e,["file"]);return n!=null&&h(t,["file"],n),t}function YR(e){const t={},n=f(e,["sdkHttpResponse"]);return n!=null&&h(t,["sdkHttpResponse"],n),t}function zR(e){const t={},n=f(e,["name"]);return n!=null&&h(t,["_url","file"],sA(n)),t}function XR(e){const t={},n=f(e,["sdkHttpResponse"]);return n!=null&&h(t,["sdkHttpResponse"],n),t}function QR(e){const t={},n=f(e,["name"]);return n!=null&&h(t,["_url","file"],sA(n)),t}function ZR(e){const t={},n=f(e,["uris"]);return n!=null&&h(t,["uris"],n),t}function eM(e,t){const n={},r=f(e,["pageSize"]);t!==void 0&&r!=null&&h(t,["_query","pageSize"],r);const s=f(e,["pageToken"]);return t!==void 0&&s!=null&&h(t,["_query","pageToken"],s),n}function tM(e){const t={},n=f(e,["config"]);return n!=null&&eM(n,t),t}function nM(e){const t={},n=f(e,["sdkHttpResponse"]);n!=null&&h(t,["sdkHttpResponse"],n);const r=f(e,["nextPageToken"]);r!=null&&h(t,["nextPageToken"],r);const s=f(e,["files"]);if(s!=null){let o=s;Array.isArray(o)&&(o=o.map(i=>i)),h(t,["files"],o)}return t}function rM(e){const t={},n=f(e,["sdkHttpResponse"]);n!=null&&h(t,["sdkHttpResponse"],n);const r=f(e,["files"]);if(r!=null){let s=r;Array.isArray(s)&&(s=s.map(o=>o)),h(t,["files"],s)}return t}class mA extends Sn{constructor(t){super(),this.apiClient=t,this.list=async(n={})=>new Dn(zt.PAGED_ITEM_FILES,r=>this.listInternal(r),await this.listInternal(n),n)}async upload(t){if(this.apiClient.isVertexAI())throw new Error("Vertex AI does not support uploading files. You can share files through a GCS bucket.");return this.apiClient.uploadFile(t.file,t.config).then(n=>n)}async download(t){await this.apiClient.downloadFile(t)}async registerFiles(t){throw new Error("registerFiles is only supported in Node.js environments.")}async _registerFiles(t){return this.registerFilesInternal(t)}async listInternal(t){var n,r;let s,o="",i={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const a=tM(t);return o=ie("files",a._url),i=a._query,delete a._url,delete a._query,s=this.apiClient.request({path:o,queryParams:i,body:JSON.stringify(a),httpMethod:"GET",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal}).then(l=>l.json().then(u=>{const c=u;return c.sdkHttpResponse={headers:l.headers},c})),s.then(l=>{const u=nM(l),c=new W0;return Object.assign(c,u),c})}}async createInternal(t){var n,r;let s,o="",i={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const a=$R(t);return o=ie("upload/v1beta/files",a._url),i=a._query,delete a._url,delete a._query,s=this.apiClient.request({path:o,queryParams:i,body:JSON.stringify(a),httpMethod:"POST",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal}).then(l=>l.json()),s.then(l=>{const u=YR(l),c=new K0;return Object.assign(c,u),c})}}async get(t){var n,r;let s,o="",i={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const a=QR(t);return o=ie("files/{file}",a._url),i=a._query,delete a._url,delete a._query,s=this.apiClient.request({path:o,queryParams:i,body:JSON.stringify(a),httpMethod:"GET",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal}).then(l=>l.json()),s.then(l=>l)}}async delete(t){var n,r;let s,o="",i={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const a=zR(t);return o=ie("files/{file}",a._url),i=a._query,delete a._url,delete a._query,s=this.apiClient.request({path:o,queryParams:i,body:JSON.stringify(a),httpMethod:"DELETE",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal}).then(l=>l.json().then(u=>{const c=u;return c.sdkHttpResponse={headers:l.headers},c})),s.then(l=>{const u=XR(l),c=new $0;return Object.assign(c,u),c})}}async registerFilesInternal(t){var n,r;let s,o="",i={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const a=ZR(t);return o=ie("files:register",a._url),i=a._query,delete a._url,delete a._query,s=this.apiClient.request({path:o,queryParams:i,body:JSON.stringify(a),httpMethod:"POST",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal}).then(l=>l.json()),s.then(l=>{const u=rM(l),c=new Y0;return Object.assign(c,u),c})}}}function aa(e){const t={},n=f(e,["data"]);if(n!=null&&h(t,["data"],n),f(e,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");const r=f(e,["mimeType"]);return r!=null&&h(t,["mimeType"],r),t}function sM(e){const t={},n=f(e,["parts"]);if(n!=null){let s=n;Array.isArray(s)&&(s=s.map(o=>bM(o))),h(t,["parts"],s)}const r=f(e,["role"]);return r!=null&&h(t,["role"],r),t}function oM(e){const t={};if(f(e,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");const n=f(e,["fileUri"]);n!=null&&h(t,["fileUri"],n);const r=f(e,["mimeType"]);return r!=null&&h(t,["mimeType"],r),t}function iM(e){const t={},n=f(e,["id"]);n!=null&&h(t,["id"],n);const r=f(e,["args"]);r!=null&&h(t,["args"],r);const s=f(e,["name"]);if(s!=null&&h(t,["name"],s),f(e,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is not supported in Gemini API.");if(f(e,["willContinue"])!==void 0)throw new Error("willContinue parameter is not supported in Gemini API.");return t}function aM(e){const t={},n=f(e,["description"]);n!=null&&h(t,["description"],n);const r=f(e,["name"]);r!=null&&h(t,["name"],r);const s=f(e,["parameters"]);s!=null&&h(t,["parameters"],s);const o=f(e,["parametersJsonSchema"]);o!=null&&h(t,["parametersJsonSchema"],o);const i=f(e,["response"]);i!=null&&h(t,["response"],i);const a=f(e,["responseJsonSchema"]);if(a!=null&&h(t,["responseJsonSchema"],a),f(e,["behavior"])!==void 0)throw new Error("behavior parameter is not supported in Vertex AI.");return t}function lM(e){const t={},n=f(e,["modelSelectionConfig"]);n!=null&&h(t,["modelConfig"],n);const r=f(e,["responseJsonSchema"]);r!=null&&h(t,["responseJsonSchema"],r);const s=f(e,["audioTimestamp"]);s!=null&&h(t,["audioTimestamp"],s);const o=f(e,["candidateCount"]);o!=null&&h(t,["candidateCount"],o);const i=f(e,["enableAffectiveDialog"]);i!=null&&h(t,["enableAffectiveDialog"],i);const a=f(e,["frequencyPenalty"]);a!=null&&h(t,["frequencyPenalty"],a);const l=f(e,["logprobs"]);l!=null&&h(t,["logprobs"],l);const u=f(e,["maxOutputTokens"]);u!=null&&h(t,["maxOutputTokens"],u);const c=f(e,["mediaResolution"]);c!=null&&h(t,["mediaResolution"],c);const d=f(e,["presencePenalty"]);d!=null&&h(t,["presencePenalty"],d);const p=f(e,["responseLogprobs"]);p!=null&&h(t,["responseLogprobs"],p);const g=f(e,["responseMimeType"]);g!=null&&h(t,["responseMimeType"],g);const y=f(e,["responseModalities"]);y!=null&&h(t,["responseModalities"],y);const _=f(e,["responseSchema"]);_!=null&&h(t,["responseSchema"],_);const b=f(e,["routingConfig"]);b!=null&&h(t,["routingConfig"],b);const m=f(e,["seed"]);m!=null&&h(t,["seed"],m);const v=f(e,["speechConfig"]);v!=null&&h(t,["speechConfig"],v);const A=f(e,["stopSequences"]);A!=null&&h(t,["stopSequences"],A);const S=f(e,["temperature"]);S!=null&&h(t,["temperature"],S);const P=f(e,["thinkingConfig"]);P!=null&&h(t,["thinkingConfig"],P);const E=f(e,["topK"]);E!=null&&h(t,["topK"],E);const w=f(e,["topP"]);if(w!=null&&h(t,["topP"],w),f(e,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is not supported in Vertex AI.");return t}function uM(e){const t={};if(f(e,["authConfig"])!==void 0)throw new Error("authConfig parameter is not supported in Gemini API.");const n=f(e,["enableWidget"]);return n!=null&&h(t,["enableWidget"],n),t}function cM(e){const t={};if(f(e,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is not supported in Gemini API.");if(f(e,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is not supported in Gemini API.");const n=f(e,["timeRangeFilter"]);return n!=null&&h(t,["timeRangeFilter"],n),t}function dM(e,t){const n={},r=f(e,["generationConfig"]);t!==void 0&&r!=null&&h(t,["setup","generationConfig"],r);const s=f(e,["responseModalities"]);t!==void 0&&s!=null&&h(t,["setup","generationConfig","responseModalities"],s);const o=f(e,["temperature"]);t!==void 0&&o!=null&&h(t,["setup","generationConfig","temperature"],o);const i=f(e,["topP"]);t!==void 0&&i!=null&&h(t,["setup","generationConfig","topP"],i);const a=f(e,["topK"]);t!==void 0&&a!=null&&h(t,["setup","generationConfig","topK"],a);const l=f(e,["maxOutputTokens"]);t!==void 0&&l!=null&&h(t,["setup","generationConfig","maxOutputTokens"],l);const u=f(e,["mediaResolution"]);t!==void 0&&u!=null&&h(t,["setup","generationConfig","mediaResolution"],u);const c=f(e,["seed"]);t!==void 0&&c!=null&&h(t,["setup","generationConfig","seed"],c);const d=f(e,["speechConfig"]);t!==void 0&&d!=null&&h(t,["setup","generationConfig","speechConfig"],tf(d));const p=f(e,["thinkingConfig"]);t!==void 0&&p!=null&&h(t,["setup","generationConfig","thinkingConfig"],p);const g=f(e,["enableAffectiveDialog"]);t!==void 0&&g!=null&&h(t,["setup","generationConfig","enableAffectiveDialog"],g);const y=f(e,["systemInstruction"]);t!==void 0&&y!=null&&h(t,["setup","systemInstruction"],sM(Qe(y)));const _=f(e,["tools"]);if(t!==void 0&&_!=null){let E=jr(_);Array.isArray(E)&&(E=E.map(w=>SM(Jr(w)))),h(t,["setup","tools"],E)}const b=f(e,["sessionResumption"]);t!==void 0&&b!=null&&h(t,["setup","sessionResumption"],AM(b));const m=f(e,["inputAudioTranscription"]);t!==void 0&&m!=null&&h(t,["setup","inputAudioTranscription"],m);const v=f(e,["outputAudioTranscription"]);t!==void 0&&v!=null&&h(t,["setup","outputAudioTranscription"],v);const A=f(e,["realtimeInputConfig"]);t!==void 0&&A!=null&&h(t,["setup","realtimeInputConfig"],A);const S=f(e,["contextWindowCompression"]);t!==void 0&&S!=null&&h(t,["setup","contextWindowCompression"],S);const P=f(e,["proactivity"]);if(t!==void 0&&P!=null&&h(t,["setup","proactivity"],P),f(e,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is not supported in Gemini API.");return n}function fM(e,t){const n={},r=f(e,["generationConfig"]);t!==void 0&&r!=null&&h(t,["setup","generationConfig"],lM(r));const s=f(e,["responseModalities"]);t!==void 0&&s!=null&&h(t,["setup","generationConfig","responseModalities"],s);const o=f(e,["temperature"]);t!==void 0&&o!=null&&h(t,["setup","generationConfig","temperature"],o);const i=f(e,["topP"]);t!==void 0&&i!=null&&h(t,["setup","generationConfig","topP"],i);const a=f(e,["topK"]);t!==void 0&&a!=null&&h(t,["setup","generationConfig","topK"],a);const l=f(e,["maxOutputTokens"]);t!==void 0&&l!=null&&h(t,["setup","generationConfig","maxOutputTokens"],l);const u=f(e,["mediaResolution"]);t!==void 0&&u!=null&&h(t,["setup","generationConfig","mediaResolution"],u);const c=f(e,["seed"]);t!==void 0&&c!=null&&h(t,["setup","generationConfig","seed"],c);const d=f(e,["speechConfig"]);t!==void 0&&d!=null&&h(t,["setup","generationConfig","speechConfig"],tf(d));const p=f(e,["thinkingConfig"]);t!==void 0&&p!=null&&h(t,["setup","generationConfig","thinkingConfig"],p);const g=f(e,["enableAffectiveDialog"]);t!==void 0&&g!=null&&h(t,["setup","generationConfig","enableAffectiveDialog"],g);const y=f(e,["systemInstruction"]);t!==void 0&&y!=null&&h(t,["setup","systemInstruction"],Qe(y));const _=f(e,["tools"]);if(t!==void 0&&_!=null){let w=jr(_);Array.isArray(w)&&(w=w.map(I=>wM(Jr(I)))),h(t,["setup","tools"],w)}const b=f(e,["sessionResumption"]);t!==void 0&&b!=null&&h(t,["setup","sessionResumption"],b);const m=f(e,["inputAudioTranscription"]);t!==void 0&&m!=null&&h(t,["setup","inputAudioTranscription"],m);const v=f(e,["outputAudioTranscription"]);t!==void 0&&v!=null&&h(t,["setup","outputAudioTranscription"],v);const A=f(e,["realtimeInputConfig"]);t!==void 0&&A!=null&&h(t,["setup","realtimeInputConfig"],A);const S=f(e,["contextWindowCompression"]);t!==void 0&&S!=null&&h(t,["setup","contextWindowCompression"],S);const P=f(e,["proactivity"]);t!==void 0&&P!=null&&h(t,["setup","proactivity"],P);const E=f(e,["explicitVadSignal"]);return t!==void 0&&E!=null&&h(t,["setup","explicitVadSignal"],E),n}function pM(e,t){const n={},r=f(t,["model"]);r!=null&&h(n,["setup","model"],Ee(e,r));const s=f(t,["config"]);return s!=null&&h(n,["config"],dM(s,n)),n}function hM(e,t){const n={},r=f(t,["model"]);r!=null&&h(n,["setup","model"],Ee(e,r));const s=f(t,["config"]);return s!=null&&h(n,["config"],fM(s,n)),n}function gM(e){const t={},n=f(e,["musicGenerationConfig"]);return n!=null&&h(t,["musicGenerationConfig"],n),t}function mM(e){const t={},n=f(e,["weightedPrompts"]);if(n!=null){let r=n;Array.isArray(r)&&(r=r.map(s=>s)),h(t,["weightedPrompts"],r)}return t}function _M(e){const t={},n=f(e,["media"]);if(n!=null){let u=Z0(n);Array.isArray(u)&&(u=u.map(c=>aa(c))),h(t,["mediaChunks"],u)}const r=f(e,["audio"]);r!=null&&h(t,["audio"],aa(tA(r)));const s=f(e,["audioStreamEnd"]);s!=null&&h(t,["audioStreamEnd"],s);const o=f(e,["video"]);o!=null&&h(t,["video"],aa(eA(o)));const i=f(e,["text"]);i!=null&&h(t,["text"],i);const a=f(e,["activityStart"]);a!=null&&h(t,["activityStart"],a);const l=f(e,["activityEnd"]);return l!=null&&h(t,["activityEnd"],l),t}function yM(e){const t={},n=f(e,["media"]);if(n!=null){let u=Z0(n);Array.isArray(u)&&(u=u.map(c=>c)),h(t,["mediaChunks"],u)}const r=f(e,["audio"]);r!=null&&h(t,["audio"],tA(r));const s=f(e,["audioStreamEnd"]);s!=null&&h(t,["audioStreamEnd"],s);const o=f(e,["video"]);o!=null&&h(t,["video"],eA(o));const i=f(e,["text"]);i!=null&&h(t,["text"],i);const a=f(e,["activityStart"]);a!=null&&h(t,["activityStart"],a);const l=f(e,["activityEnd"]);return l!=null&&h(t,["activityEnd"],l),t}function vM(e){const t={},n=f(e,["setupComplete"]);n!=null&&h(t,["setupComplete"],n);const r=f(e,["serverContent"]);r!=null&&h(t,["serverContent"],r);const s=f(e,["toolCall"]);s!=null&&h(t,["toolCall"],s);const o=f(e,["toolCallCancellation"]);o!=null&&h(t,["toolCallCancellation"],o);const i=f(e,["usageMetadata"]);i!=null&&h(t,["usageMetadata"],EM(i));const a=f(e,["goAway"]);a!=null&&h(t,["goAway"],a);const l=f(e,["sessionResumptionUpdate"]);l!=null&&h(t,["sessionResumptionUpdate"],l);const u=f(e,["voiceActivityDetectionSignal"]);u!=null&&h(t,["voiceActivityDetectionSignal"],u);const c=f(e,["voiceActivity"]);return c!=null&&h(t,["voiceActivity"],TM(c)),t}function bM(e){const t={},n=f(e,["mediaResolution"]);n!=null&&h(t,["mediaResolution"],n);const r=f(e,["codeExecutionResult"]);r!=null&&h(t,["codeExecutionResult"],r);const s=f(e,["executableCode"]);s!=null&&h(t,["executableCode"],s);const o=f(e,["fileData"]);o!=null&&h(t,["fileData"],oM(o));const i=f(e,["functionCall"]);i!=null&&h(t,["functionCall"],iM(i));const a=f(e,["functionResponse"]);a!=null&&h(t,["functionResponse"],a);const l=f(e,["inlineData"]);l!=null&&h(t,["inlineData"],aa(l));const u=f(e,["text"]);u!=null&&h(t,["text"],u);const c=f(e,["thought"]);c!=null&&h(t,["thought"],c);const d=f(e,["thoughtSignature"]);d!=null&&h(t,["thoughtSignature"],d);const p=f(e,["videoMetadata"]);return p!=null&&h(t,["videoMetadata"],p),t}function AM(e){const t={},n=f(e,["handle"]);if(n!=null&&h(t,["handle"],n),f(e,["transparent"])!==void 0)throw new Error("transparent parameter is not supported in Gemini API.");return t}function SM(e){const t={};if(f(e,["retrieval"])!==void 0)throw new Error("retrieval parameter is not supported in Gemini API.");const n=f(e,["computerUse"]);n!=null&&h(t,["computerUse"],n);const r=f(e,["fileSearch"]);r!=null&&h(t,["fileSearch"],r);const s=f(e,["codeExecution"]);if(s!=null&&h(t,["codeExecution"],s),f(e,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");const o=f(e,["functionDeclarations"]);if(o!=null){let c=o;Array.isArray(c)&&(c=c.map(d=>d)),h(t,["functionDeclarations"],c)}const i=f(e,["googleMaps"]);i!=null&&h(t,["googleMaps"],uM(i));const a=f(e,["googleSearch"]);a!=null&&h(t,["googleSearch"],cM(a));const l=f(e,["googleSearchRetrieval"]);l!=null&&h(t,["googleSearchRetrieval"],l);const u=f(e,["urlContext"]);return u!=null&&h(t,["urlContext"],u),t}function wM(e){const t={},n=f(e,["retrieval"]);n!=null&&h(t,["retrieval"],n);const r=f(e,["computerUse"]);if(r!=null&&h(t,["computerUse"],r),f(e,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is not supported in Vertex AI.");const s=f(e,["codeExecution"]);s!=null&&h(t,["codeExecution"],s);const o=f(e,["enterpriseWebSearch"]);o!=null&&h(t,["enterpriseWebSearch"],o);const i=f(e,["functionDeclarations"]);if(i!=null){let d=i;Array.isArray(d)&&(d=d.map(p=>aM(p))),h(t,["functionDeclarations"],d)}const a=f(e,["googleMaps"]);a!=null&&h(t,["googleMaps"],a);const l=f(e,["googleSearch"]);l!=null&&h(t,["googleSearch"],l);const u=f(e,["googleSearchRetrieval"]);u!=null&&h(t,["googleSearchRetrieval"],u);const c=f(e,["urlContext"]);return c!=null&&h(t,["urlContext"],c),t}function EM(e){const t={},n=f(e,["promptTokenCount"]);n!=null&&h(t,["promptTokenCount"],n);const r=f(e,["cachedContentTokenCount"]);r!=null&&h(t,["cachedContentTokenCount"],r);const s=f(e,["candidatesTokenCount"]);s!=null&&h(t,["responseTokenCount"],s);const o=f(e,["toolUsePromptTokenCount"]);o!=null&&h(t,["toolUsePromptTokenCount"],o);const i=f(e,["thoughtsTokenCount"]);i!=null&&h(t,["thoughtsTokenCount"],i);const a=f(e,["totalTokenCount"]);a!=null&&h(t,["totalTokenCount"],a);const l=f(e,["promptTokensDetails"]);if(l!=null){let g=l;Array.isArray(g)&&(g=g.map(y=>y)),h(t,["promptTokensDetails"],g)}const u=f(e,["cacheTokensDetails"]);if(u!=null){let g=u;Array.isArray(g)&&(g=g.map(y=>y)),h(t,["cacheTokensDetails"],g)}const c=f(e,["candidatesTokensDetails"]);if(c!=null){let g=c;Array.isArray(g)&&(g=g.map(y=>y)),h(t,["responseTokensDetails"],g)}const d=f(e,["toolUsePromptTokensDetails"]);if(d!=null){let g=d;Array.isArray(g)&&(g=g.map(y=>y)),h(t,["toolUsePromptTokensDetails"],g)}const p=f(e,["trafficType"]);return p!=null&&h(t,["trafficType"],p),t}function TM(e){const t={},n=f(e,["type"]);return n!=null&&h(t,["voiceActivityType"],n),t}function PM(e,t){const n={},r=f(e,["data"]);if(r!=null&&h(n,["data"],r),f(e,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");const s=f(e,["mimeType"]);return s!=null&&h(n,["mimeType"],s),n}function IM(e,t){const n={},r=f(e,["content"]);r!=null&&h(n,["content"],r);const s=f(e,["citationMetadata"]);s!=null&&h(n,["citationMetadata"],CM(s));const o=f(e,["tokenCount"]);o!=null&&h(n,["tokenCount"],o);const i=f(e,["finishReason"]);i!=null&&h(n,["finishReason"],i);const a=f(e,["avgLogprobs"]);a!=null&&h(n,["avgLogprobs"],a);const l=f(e,["groundingMetadata"]);l!=null&&h(n,["groundingMetadata"],l);const u=f(e,["index"]);u!=null&&h(n,["index"],u);const c=f(e,["logprobsResult"]);c!=null&&h(n,["logprobsResult"],c);const d=f(e,["safetyRatings"]);if(d!=null){let g=d;Array.isArray(g)&&(g=g.map(y=>y)),h(n,["safetyRatings"],g)}const p=f(e,["urlContextMetadata"]);return p!=null&&h(n,["urlContextMetadata"],p),n}function CM(e,t){const n={},r=f(e,["citationSources"]);if(r!=null){let s=r;Array.isArray(s)&&(s=s.map(o=>o)),h(n,["citations"],s)}return n}function RM(e,t,n){const r={},s=f(t,["model"]);s!=null&&h(r,["_url","model"],Ee(e,s));const o=f(t,["contents"]);if(o!=null){let i=mt(o);Array.isArray(i)&&(i=i.map(a=>a)),h(r,["contents"],i)}return r}function MM(e,t){const n={},r=f(e,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);const s=f(e,["tokensInfo"]);if(s!=null){let o=s;Array.isArray(o)&&(o=o.map(i=>i)),h(n,["tokensInfo"],o)}return n}function NM(e,t){const n={},r=f(e,["values"]);r!=null&&h(n,["values"],r);const s=f(e,["statistics"]);return s!=null&&h(n,["statistics"],FM(s)),n}function FM(e,t){const n={},r=f(e,["truncated"]);r!=null&&h(n,["truncated"],r);const s=f(e,["token_count"]);return s!=null&&h(n,["tokenCount"],s),n}function Qa(e,t){const n={},r=f(e,["parts"]);if(r!=null){let o=r;Array.isArray(o)&&(o=o.map(i=>VN(i))),h(n,["parts"],o)}const s=f(e,["role"]);return s!=null&&h(n,["role"],s),n}function kM(e,t){const n={},r=f(e,["controlType"]);r!=null&&h(n,["controlType"],r);const s=f(e,["enableControlImageComputation"]);return s!=null&&h(n,["computeControl"],s),n}function OM(e,t){const n={};if(f(e,["systemInstruction"])!==void 0)throw new Error("systemInstruction parameter is not supported in Gemini API.");if(f(e,["tools"])!==void 0)throw new Error("tools parameter is not supported in Gemini API.");if(f(e,["generationConfig"])!==void 0)throw new Error("generationConfig parameter is not supported in Gemini API.");return n}function xM(e,t,n){const r={},s=f(e,["systemInstruction"]);t!==void 0&&s!=null&&h(t,["systemInstruction"],Qe(s));const o=f(e,["tools"]);if(t!==void 0&&o!=null){let a=o;Array.isArray(a)&&(a=a.map(l=>bA(l))),h(t,["tools"],a)}const i=f(e,["generationConfig"]);return t!==void 0&&i!=null&&h(t,["generationConfig"],PN(i)),r}function DM(e,t,n){const r={},s=f(t,["model"]);s!=null&&h(r,["_url","model"],Ee(e,s));const o=f(t,["contents"]);if(o!=null){let a=mt(o);Array.isArray(a)&&(a=a.map(l=>Qa(l))),h(r,["contents"],a)}const i=f(t,["config"]);return i!=null&&OM(i),r}function qM(e,t,n){const r={},s=f(t,["model"]);s!=null&&h(r,["_url","model"],Ee(e,s));const o=f(t,["contents"]);if(o!=null){let a=mt(o);Array.isArray(a)&&(a=a.map(l=>l)),h(r,["contents"],a)}const i=f(t,["config"]);return i!=null&&xM(i,r),r}function LM(e,t){const n={},r=f(e,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);const s=f(e,["totalTokens"]);s!=null&&h(n,["totalTokens"],s);const o=f(e,["cachedContentTokenCount"]);return o!=null&&h(n,["cachedContentTokenCount"],o),n}function UM(e,t){const n={},r=f(e,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);const s=f(e,["totalTokens"]);return s!=null&&h(n,["totalTokens"],s),n}function GM(e,t,n){const r={},s=f(t,["model"]);return s!=null&&h(r,["_url","name"],Ee(e,s)),r}function VM(e,t,n){const r={},s=f(t,["model"]);return s!=null&&h(r,["_url","name"],Ee(e,s)),r}function BM(e,t){const n={},r=f(e,["sdkHttpResponse"]);return r!=null&&h(n,["sdkHttpResponse"],r),n}function HM(e,t){const n={},r=f(e,["sdkHttpResponse"]);return r!=null&&h(n,["sdkHttpResponse"],r),n}function JM(e,t,n){const r={},s=f(e,["outputGcsUri"]);t!==void 0&&s!=null&&h(t,["parameters","storageUri"],s);const o=f(e,["negativePrompt"]);t!==void 0&&o!=null&&h(t,["parameters","negativePrompt"],o);const i=f(e,["numberOfImages"]);t!==void 0&&i!=null&&h(t,["parameters","sampleCount"],i);const a=f(e,["aspectRatio"]);t!==void 0&&a!=null&&h(t,["parameters","aspectRatio"],a);const l=f(e,["guidanceScale"]);t!==void 0&&l!=null&&h(t,["parameters","guidanceScale"],l);const u=f(e,["seed"]);t!==void 0&&u!=null&&h(t,["parameters","seed"],u);const c=f(e,["safetyFilterLevel"]);t!==void 0&&c!=null&&h(t,["parameters","safetySetting"],c);const d=f(e,["personGeneration"]);t!==void 0&&d!=null&&h(t,["parameters","personGeneration"],d);const p=f(e,["includeSafetyAttributes"]);t!==void 0&&p!=null&&h(t,["parameters","includeSafetyAttributes"],p);const g=f(e,["includeRaiReason"]);t!==void 0&&g!=null&&h(t,["parameters","includeRaiReason"],g);const y=f(e,["language"]);t!==void 0&&y!=null&&h(t,["parameters","language"],y);const _=f(e,["outputMimeType"]);t!==void 0&&_!=null&&h(t,["parameters","outputOptions","mimeType"],_);const b=f(e,["outputCompressionQuality"]);t!==void 0&&b!=null&&h(t,["parameters","outputOptions","compressionQuality"],b);const m=f(e,["addWatermark"]);t!==void 0&&m!=null&&h(t,["parameters","addWatermark"],m);const v=f(e,["labels"]);t!==void 0&&v!=null&&h(t,["labels"],v);const A=f(e,["editMode"]);t!==void 0&&A!=null&&h(t,["parameters","editMode"],A);const S=f(e,["baseSteps"]);return t!==void 0&&S!=null&&h(t,["parameters","editConfig","baseSteps"],S),r}function jM(e,t,n){const r={},s=f(t,["model"]);s!=null&&h(r,["_url","model"],Ee(e,s));const o=f(t,["prompt"]);o!=null&&h(r,["instances[0]","prompt"],o);const i=f(t,["referenceImages"]);if(i!=null){let l=i;Array.isArray(l)&&(l=l.map(u=>KN(u))),h(r,["instances[0]","referenceImages"],l)}const a=f(t,["config"]);return a!=null&&JM(a,r),r}function WM(e,t){const n={},r=f(e,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);const s=f(e,["predictions"]);if(s!=null){let o=s;Array.isArray(o)&&(o=o.map(i=>Za(i))),h(n,["generatedImages"],o)}return n}function KM(e,t,n){const r={},s=f(e,["taskType"]);t!==void 0&&s!=null&&h(t,["requests[]","taskType"],s);const o=f(e,["title"]);t!==void 0&&o!=null&&h(t,["requests[]","title"],o);const i=f(e,["outputDimensionality"]);if(t!==void 0&&i!=null&&h(t,["requests[]","outputDimensionality"],i),f(e,["mimeType"])!==void 0)throw new Error("mimeType parameter is not supported in Gemini API.");if(f(e,["autoTruncate"])!==void 0)throw new Error("autoTruncate parameter is not supported in Gemini API.");return r}function $M(e,t,n){const r={},s=f(e,["taskType"]);t!==void 0&&s!=null&&h(t,["instances[]","task_type"],s);const o=f(e,["title"]);t!==void 0&&o!=null&&h(t,["instances[]","title"],o);const i=f(e,["outputDimensionality"]);t!==void 0&&i!=null&&h(t,["parameters","outputDimensionality"],i);const a=f(e,["mimeType"]);t!==void 0&&a!=null&&h(t,["instances[]","mimeType"],a);const l=f(e,["autoTruncate"]);return t!==void 0&&l!=null&&h(t,["parameters","autoTruncate"],l),r}function YM(e,t,n){const r={},s=f(t,["model"]);s!=null&&h(r,["_url","model"],Ee(e,s));const o=f(t,["contents"]);if(o!=null){let l=Qd(e,o);Array.isArray(l)&&(l=l.map(u=>u)),h(r,["requests[]","content"],l)}const i=f(t,["config"]);i!=null&&KM(i,r);const a=f(t,["model"]);return a!==void 0&&h(r,["requests[]","model"],Ee(e,a)),r}function zM(e,t,n){const r={},s=f(t,["model"]);s!=null&&h(r,["_url","model"],Ee(e,s));const o=f(t,["contents"]);if(o!=null){let a=Qd(e,o);Array.isArray(a)&&(a=a.map(l=>l)),h(r,["instances[]","content"],a)}const i=f(t,["config"]);return i!=null&&$M(i,r),r}function XM(e,t){const n={},r=f(e,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);const s=f(e,["embeddings"]);if(s!=null){let i=s;Array.isArray(i)&&(i=i.map(a=>a)),h(n,["embeddings"],i)}const o=f(e,["metadata"]);return o!=null&&h(n,["metadata"],o),n}function QM(e,t){const n={},r=f(e,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);const s=f(e,["predictions[]","embeddings"]);if(s!=null){let i=s;Array.isArray(i)&&(i=i.map(a=>NM(a))),h(n,["embeddings"],i)}const o=f(e,["metadata"]);return o!=null&&h(n,["metadata"],o),n}function ZM(e,t){const n={},r=f(e,["endpoint"]);r!=null&&h(n,["name"],r);const s=f(e,["deployedModelId"]);return s!=null&&h(n,["deployedModelId"],s),n}function eN(e,t){const n={};if(f(e,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");const r=f(e,["fileUri"]);r!=null&&h(n,["fileUri"],r);const s=f(e,["mimeType"]);return s!=null&&h(n,["mimeType"],s),n}function tN(e,t){const n={},r=f(e,["id"]);r!=null&&h(n,["id"],r);const s=f(e,["args"]);s!=null&&h(n,["args"],s);const o=f(e,["name"]);if(o!=null&&h(n,["name"],o),f(e,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is not supported in Gemini API.");if(f(e,["willContinue"])!==void 0)throw new Error("willContinue parameter is not supported in Gemini API.");return n}function nN(e,t){const n={},r=f(e,["allowedFunctionNames"]);r!=null&&h(n,["allowedFunctionNames"],r);const s=f(e,["mode"]);if(s!=null&&h(n,["mode"],s),f(e,["streamFunctionCallArguments"])!==void 0)throw new Error("streamFunctionCallArguments parameter is not supported in Gemini API.");return n}function rN(e,t){const n={},r=f(e,["description"]);r!=null&&h(n,["description"],r);const s=f(e,["name"]);s!=null&&h(n,["name"],s);const o=f(e,["parameters"]);o!=null&&h(n,["parameters"],o);const i=f(e,["parametersJsonSchema"]);i!=null&&h(n,["parametersJsonSchema"],i);const a=f(e,["response"]);a!=null&&h(n,["response"],a);const l=f(e,["responseJsonSchema"]);if(l!=null&&h(n,["responseJsonSchema"],l),f(e,["behavior"])!==void 0)throw new Error("behavior parameter is not supported in Vertex AI.");return n}function sN(e,t,n,r){const s={},o=f(t,["systemInstruction"]);n!==void 0&&o!=null&&h(n,["systemInstruction"],Qa(Qe(o)));const i=f(t,["temperature"]);i!=null&&h(s,["temperature"],i);const a=f(t,["topP"]);a!=null&&h(s,["topP"],a);const l=f(t,["topK"]);l!=null&&h(s,["topK"],l);const u=f(t,["candidateCount"]);u!=null&&h(s,["candidateCount"],u);const c=f(t,["maxOutputTokens"]);c!=null&&h(s,["maxOutputTokens"],c);const d=f(t,["stopSequences"]);d!=null&&h(s,["stopSequences"],d);const p=f(t,["responseLogprobs"]);p!=null&&h(s,["responseLogprobs"],p);const g=f(t,["logprobs"]);g!=null&&h(s,["logprobs"],g);const y=f(t,["presencePenalty"]);y!=null&&h(s,["presencePenalty"],y);const _=f(t,["frequencyPenalty"]);_!=null&&h(s,["frequencyPenalty"],_);const b=f(t,["seed"]);b!=null&&h(s,["seed"],b);const m=f(t,["responseMimeType"]);m!=null&&h(s,["responseMimeType"],m);const v=f(t,["responseSchema"]);v!=null&&h(s,["responseSchema"],Zd(v));const A=f(t,["responseJsonSchema"]);if(A!=null&&h(s,["responseJsonSchema"],A),f(t,["routingConfig"])!==void 0)throw new Error("routingConfig parameter is not supported in Gemini API.");if(f(t,["modelSelectionConfig"])!==void 0)throw new Error("modelSelectionConfig parameter is not supported in Gemini API.");const S=f(t,["safetySettings"]);if(n!==void 0&&S!=null){let U=S;Array.isArray(U)&&(U=U.map(O=>$N(O))),h(n,["safetySettings"],U)}const P=f(t,["tools"]);if(n!==void 0&&P!=null){let U=jr(P);Array.isArray(U)&&(U=U.map(O=>tF(Jr(O)))),h(n,["tools"],U)}const E=f(t,["toolConfig"]);if(n!==void 0&&E!=null&&h(n,["toolConfig"],eF(E)),f(t,["labels"])!==void 0)throw new Error("labels parameter is not supported in Gemini API.");const w=f(t,["cachedContent"]);n!==void 0&&w!=null&&h(n,["cachedContent"],wn(e,w));const I=f(t,["responseModalities"]);I!=null&&h(s,["responseModalities"],I);const L=f(t,["mediaResolution"]);L!=null&&h(s,["mediaResolution"],L);const H=f(t,["speechConfig"]);if(H!=null&&h(s,["speechConfig"],ef(H)),f(t,["audioTimestamp"])!==void 0)throw new Error("audioTimestamp parameter is not supported in Gemini API.");const B=f(t,["thinkingConfig"]);B!=null&&h(s,["thinkingConfig"],B);const F=f(t,["imageConfig"]);F!=null&&h(s,["imageConfig"],NN(F));const j=f(t,["enableEnhancedCivicAnswers"]);if(j!=null&&h(s,["enableEnhancedCivicAnswers"],j),f(t,["modelArmorConfig"])!==void 0)throw new Error("modelArmorConfig parameter is not supported in Gemini API.");return s}function oN(e,t,n,r){const s={},o=f(t,["systemInstruction"]);n!==void 0&&o!=null&&h(n,["systemInstruction"],Qe(o));const i=f(t,["temperature"]);i!=null&&h(s,["temperature"],i);const a=f(t,["topP"]);a!=null&&h(s,["topP"],a);const l=f(t,["topK"]);l!=null&&h(s,["topK"],l);const u=f(t,["candidateCount"]);u!=null&&h(s,["candidateCount"],u);const c=f(t,["maxOutputTokens"]);c!=null&&h(s,["maxOutputTokens"],c);const d=f(t,["stopSequences"]);d!=null&&h(s,["stopSequences"],d);const p=f(t,["responseLogprobs"]);p!=null&&h(s,["responseLogprobs"],p);const g=f(t,["logprobs"]);g!=null&&h(s,["logprobs"],g);const y=f(t,["presencePenalty"]);y!=null&&h(s,["presencePenalty"],y);const _=f(t,["frequencyPenalty"]);_!=null&&h(s,["frequencyPenalty"],_);const b=f(t,["seed"]);b!=null&&h(s,["seed"],b);const m=f(t,["responseMimeType"]);m!=null&&h(s,["responseMimeType"],m);const v=f(t,["responseSchema"]);v!=null&&h(s,["responseSchema"],Zd(v));const A=f(t,["responseJsonSchema"]);A!=null&&h(s,["responseJsonSchema"],A);const S=f(t,["routingConfig"]);S!=null&&h(s,["routingConfig"],S);const P=f(t,["modelSelectionConfig"]);P!=null&&h(s,["modelConfig"],P);const E=f(t,["safetySettings"]);if(n!==void 0&&E!=null){let M=E;Array.isArray(M)&&(M=M.map(k=>k)),h(n,["safetySettings"],M)}const w=f(t,["tools"]);if(n!==void 0&&w!=null){let M=jr(w);Array.isArray(M)&&(M=M.map(k=>bA(Jr(k)))),h(n,["tools"],M)}const I=f(t,["toolConfig"]);n!==void 0&&I!=null&&h(n,["toolConfig"],I);const L=f(t,["labels"]);n!==void 0&&L!=null&&h(n,["labels"],L);const H=f(t,["cachedContent"]);n!==void 0&&H!=null&&h(n,["cachedContent"],wn(e,H));const B=f(t,["responseModalities"]);B!=null&&h(s,["responseModalities"],B);const F=f(t,["mediaResolution"]);F!=null&&h(s,["mediaResolution"],F);const j=f(t,["speechConfig"]);j!=null&&h(s,["speechConfig"],ef(j));const U=f(t,["audioTimestamp"]);U!=null&&h(s,["audioTimestamp"],U);const O=f(t,["thinkingConfig"]);O!=null&&h(s,["thinkingConfig"],O);const R=f(t,["imageConfig"]);if(R!=null&&h(s,["imageConfig"],FN(R)),f(t,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is not supported in Vertex AI.");const T=f(t,["modelArmorConfig"]);return n!==void 0&&T!=null&&h(n,["modelArmorConfig"],T),s}function Ly(e,t,n){const r={},s=f(t,["model"]);s!=null&&h(r,["_url","model"],Ee(e,s));const o=f(t,["contents"]);if(o!=null){let a=mt(o);Array.isArray(a)&&(a=a.map(l=>Qa(l))),h(r,["contents"],a)}const i=f(t,["config"]);return i!=null&&h(r,["generationConfig"],sN(e,i,r)),r}function Uy(e,t,n){const r={},s=f(t,["model"]);s!=null&&h(r,["_url","model"],Ee(e,s));const o=f(t,["contents"]);if(o!=null){let a=mt(o);Array.isArray(a)&&(a=a.map(l=>l)),h(r,["contents"],a)}const i=f(t,["config"]);return i!=null&&h(r,["generationConfig"],oN(e,i,r)),r}function Gy(e,t){const n={},r=f(e,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);const s=f(e,["candidates"]);if(s!=null){let u=s;Array.isArray(u)&&(u=u.map(c=>IM(c))),h(n,["candidates"],u)}const o=f(e,["modelVersion"]);o!=null&&h(n,["modelVersion"],o);const i=f(e,["promptFeedback"]);i!=null&&h(n,["promptFeedback"],i);const a=f(e,["responseId"]);a!=null&&h(n,["responseId"],a);const l=f(e,["usageMetadata"]);return l!=null&&h(n,["usageMetadata"],l),n}function Vy(e,t){const n={},r=f(e,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);const s=f(e,["candidates"]);if(s!=null){let c=s;Array.isArray(c)&&(c=c.map(d=>d)),h(n,["candidates"],c)}const o=f(e,["createTime"]);o!=null&&h(n,["createTime"],o);const i=f(e,["modelVersion"]);i!=null&&h(n,["modelVersion"],i);const a=f(e,["promptFeedback"]);a!=null&&h(n,["promptFeedback"],a);const l=f(e,["responseId"]);l!=null&&h(n,["responseId"],l);const u=f(e,["usageMetadata"]);return u!=null&&h(n,["usageMetadata"],u),n}function iN(e,t,n){const r={};if(f(e,["outputGcsUri"])!==void 0)throw new Error("outputGcsUri parameter is not supported in Gemini API.");if(f(e,["negativePrompt"])!==void 0)throw new Error("negativePrompt parameter is not supported in Gemini API.");const s=f(e,["numberOfImages"]);t!==void 0&&s!=null&&h(t,["parameters","sampleCount"],s);const o=f(e,["aspectRatio"]);t!==void 0&&o!=null&&h(t,["parameters","aspectRatio"],o);const i=f(e,["guidanceScale"]);if(t!==void 0&&i!=null&&h(t,["parameters","guidanceScale"],i),f(e,["seed"])!==void 0)throw new Error("seed parameter is not supported in Gemini API.");const a=f(e,["safetyFilterLevel"]);t!==void 0&&a!=null&&h(t,["parameters","safetySetting"],a);const l=f(e,["personGeneration"]);t!==void 0&&l!=null&&h(t,["parameters","personGeneration"],l);const u=f(e,["includeSafetyAttributes"]);t!==void 0&&u!=null&&h(t,["parameters","includeSafetyAttributes"],u);const c=f(e,["includeRaiReason"]);t!==void 0&&c!=null&&h(t,["parameters","includeRaiReason"],c);const d=f(e,["language"]);t!==void 0&&d!=null&&h(t,["parameters","language"],d);const p=f(e,["outputMimeType"]);t!==void 0&&p!=null&&h(t,["parameters","outputOptions","mimeType"],p);const g=f(e,["outputCompressionQuality"]);if(t!==void 0&&g!=null&&h(t,["parameters","outputOptions","compressionQuality"],g),f(e,["addWatermark"])!==void 0)throw new Error("addWatermark parameter is not supported in Gemini API.");if(f(e,["labels"])!==void 0)throw new Error("labels parameter is not supported in Gemini API.");const y=f(e,["imageSize"]);if(t!==void 0&&y!=null&&h(t,["parameters","sampleImageSize"],y),f(e,["enhancePrompt"])!==void 0)throw new Error("enhancePrompt parameter is not supported in Gemini API.");return r}function aN(e,t,n){const r={},s=f(e,["outputGcsUri"]);t!==void 0&&s!=null&&h(t,["parameters","storageUri"],s);const o=f(e,["negativePrompt"]);t!==void 0&&o!=null&&h(t,["parameters","negativePrompt"],o);const i=f(e,["numberOfImages"]);t!==void 0&&i!=null&&h(t,["parameters","sampleCount"],i);const a=f(e,["aspectRatio"]);t!==void 0&&a!=null&&h(t,["parameters","aspectRatio"],a);const l=f(e,["guidanceScale"]);t!==void 0&&l!=null&&h(t,["parameters","guidanceScale"],l);const u=f(e,["seed"]);t!==void 0&&u!=null&&h(t,["parameters","seed"],u);const c=f(e,["safetyFilterLevel"]);t!==void 0&&c!=null&&h(t,["parameters","safetySetting"],c);const d=f(e,["personGeneration"]);t!==void 0&&d!=null&&h(t,["parameters","personGeneration"],d);const p=f(e,["includeSafetyAttributes"]);t!==void 0&&p!=null&&h(t,["parameters","includeSafetyAttributes"],p);const g=f(e,["includeRaiReason"]);t!==void 0&&g!=null&&h(t,["parameters","includeRaiReason"],g);const y=f(e,["language"]);t!==void 0&&y!=null&&h(t,["parameters","language"],y);const _=f(e,["outputMimeType"]);t!==void 0&&_!=null&&h(t,["parameters","outputOptions","mimeType"],_);const b=f(e,["outputCompressionQuality"]);t!==void 0&&b!=null&&h(t,["parameters","outputOptions","compressionQuality"],b);const m=f(e,["addWatermark"]);t!==void 0&&m!=null&&h(t,["parameters","addWatermark"],m);const v=f(e,["labels"]);t!==void 0&&v!=null&&h(t,["labels"],v);const A=f(e,["imageSize"]);t!==void 0&&A!=null&&h(t,["parameters","sampleImageSize"],A);const S=f(e,["enhancePrompt"]);return t!==void 0&&S!=null&&h(t,["parameters","enhancePrompt"],S),r}function lN(e,t,n){const r={},s=f(t,["model"]);s!=null&&h(r,["_url","model"],Ee(e,s));const o=f(t,["prompt"]);o!=null&&h(r,["instances[0]","prompt"],o);const i=f(t,["config"]);return i!=null&&iN(i,r),r}function uN(e,t,n){const r={},s=f(t,["model"]);s!=null&&h(r,["_url","model"],Ee(e,s));const o=f(t,["prompt"]);o!=null&&h(r,["instances[0]","prompt"],o);const i=f(t,["config"]);return i!=null&&aN(i,r),r}function cN(e,t){const n={},r=f(e,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);const s=f(e,["predictions"]);if(s!=null){let i=s;Array.isArray(i)&&(i=i.map(a=>SN(a))),h(n,["generatedImages"],i)}const o=f(e,["positivePromptSafetyAttributes"]);return o!=null&&h(n,["positivePromptSafetyAttributes"],yA(o)),n}function dN(e,t){const n={},r=f(e,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);const s=f(e,["predictions"]);if(s!=null){let i=s;Array.isArray(i)&&(i=i.map(a=>Za(a))),h(n,["generatedImages"],i)}const o=f(e,["positivePromptSafetyAttributes"]);return o!=null&&h(n,["positivePromptSafetyAttributes"],vA(o)),n}function fN(e,t,n){const r={},s=f(e,["numberOfVideos"]);if(t!==void 0&&s!=null&&h(t,["parameters","sampleCount"],s),f(e,["outputGcsUri"])!==void 0)throw new Error("outputGcsUri parameter is not supported in Gemini API.");if(f(e,["fps"])!==void 0)throw new Error("fps parameter is not supported in Gemini API.");const o=f(e,["durationSeconds"]);if(t!==void 0&&o!=null&&h(t,["parameters","durationSeconds"],o),f(e,["seed"])!==void 0)throw new Error("seed parameter is not supported in Gemini API.");const i=f(e,["aspectRatio"]);t!==void 0&&i!=null&&h(t,["parameters","aspectRatio"],i);const a=f(e,["resolution"]);t!==void 0&&a!=null&&h(t,["parameters","resolution"],a);const l=f(e,["personGeneration"]);if(t!==void 0&&l!=null&&h(t,["parameters","personGeneration"],l),f(e,["pubsubTopic"])!==void 0)throw new Error("pubsubTopic parameter is not supported in Gemini API.");const u=f(e,["negativePrompt"]);t!==void 0&&u!=null&&h(t,["parameters","negativePrompt"],u);const c=f(e,["enhancePrompt"]);if(t!==void 0&&c!=null&&h(t,["parameters","enhancePrompt"],c),f(e,["generateAudio"])!==void 0)throw new Error("generateAudio parameter is not supported in Gemini API.");const d=f(e,["lastFrame"]);t!==void 0&&d!=null&&h(t,["instances[0]","lastFrame"],el(d));const p=f(e,["referenceImages"]);if(t!==void 0&&p!=null){let g=p;Array.isArray(g)&&(g=g.map(y=>hF(y))),h(t,["instances[0]","referenceImages"],g)}if(f(e,["mask"])!==void 0)throw new Error("mask parameter is not supported in Gemini API.");if(f(e,["compressionQuality"])!==void 0)throw new Error("compressionQuality parameter is not supported in Gemini API.");return r}function pN(e,t,n){const r={},s=f(e,["numberOfVideos"]);t!==void 0&&s!=null&&h(t,["parameters","sampleCount"],s);const o=f(e,["outputGcsUri"]);t!==void 0&&o!=null&&h(t,["parameters","storageUri"],o);const i=f(e,["fps"]);t!==void 0&&i!=null&&h(t,["parameters","fps"],i);const a=f(e,["durationSeconds"]);t!==void 0&&a!=null&&h(t,["parameters","durationSeconds"],a);const l=f(e,["seed"]);t!==void 0&&l!=null&&h(t,["parameters","seed"],l);const u=f(e,["aspectRatio"]);t!==void 0&&u!=null&&h(t,["parameters","aspectRatio"],u);const c=f(e,["resolution"]);t!==void 0&&c!=null&&h(t,["parameters","resolution"],c);const d=f(e,["personGeneration"]);t!==void 0&&d!=null&&h(t,["parameters","personGeneration"],d);const p=f(e,["pubsubTopic"]);t!==void 0&&p!=null&&h(t,["parameters","pubsubTopic"],p);const g=f(e,["negativePrompt"]);t!==void 0&&g!=null&&h(t,["parameters","negativePrompt"],g);const y=f(e,["enhancePrompt"]);t!==void 0&&y!=null&&h(t,["parameters","enhancePrompt"],y);const _=f(e,["generateAudio"]);t!==void 0&&_!=null&&h(t,["parameters","generateAudio"],_);const b=f(e,["lastFrame"]);t!==void 0&&b!=null&&h(t,["instances[0]","lastFrame"],Gt(b));const m=f(e,["referenceImages"]);if(t!==void 0&&m!=null){let S=m;Array.isArray(S)&&(S=S.map(P=>gF(P))),h(t,["instances[0]","referenceImages"],S)}const v=f(e,["mask"]);t!==void 0&&v!=null&&h(t,["instances[0]","mask"],pF(v));const A=f(e,["compressionQuality"]);return t!==void 0&&A!=null&&h(t,["parameters","compressionQuality"],A),r}function hN(e,t){const n={},r=f(e,["name"]);r!=null&&h(n,["name"],r);const s=f(e,["metadata"]);s!=null&&h(n,["metadata"],s);const o=f(e,["done"]);o!=null&&h(n,["done"],o);const i=f(e,["error"]);i!=null&&h(n,["error"],i);const a=f(e,["response","generateVideoResponse"]);return a!=null&&h(n,["response"],yN(a)),n}function gN(e,t){const n={},r=f(e,["name"]);r!=null&&h(n,["name"],r);const s=f(e,["metadata"]);s!=null&&h(n,["metadata"],s);const o=f(e,["done"]);o!=null&&h(n,["done"],o);const i=f(e,["error"]);i!=null&&h(n,["error"],i);const a=f(e,["response"]);return a!=null&&h(n,["response"],vN(a)),n}function mN(e,t,n){const r={},s=f(t,["model"]);s!=null&&h(r,["_url","model"],Ee(e,s));const o=f(t,["prompt"]);o!=null&&h(r,["instances[0]","prompt"],o);const i=f(t,["image"]);i!=null&&h(r,["instances[0]","image"],el(i));const a=f(t,["video"]);a!=null&&h(r,["instances[0]","video"],AA(a));const l=f(t,["source"]);l!=null&&bN(l,r);const u=f(t,["config"]);return u!=null&&fN(u,r),r}function _N(e,t,n){const r={},s=f(t,["model"]);s!=null&&h(r,["_url","model"],Ee(e,s));const o=f(t,["prompt"]);o!=null&&h(r,["instances[0]","prompt"],o);const i=f(t,["image"]);i!=null&&h(r,["instances[0]","image"],Gt(i));const a=f(t,["video"]);a!=null&&h(r,["instances[0]","video"],SA(a));const l=f(t,["source"]);l!=null&&AN(l,r);const u=f(t,["config"]);return u!=null&&pN(u,r),r}function yN(e,t){const n={},r=f(e,["generatedSamples"]);if(r!=null){let i=r;Array.isArray(i)&&(i=i.map(a=>EN(a))),h(n,["generatedVideos"],i)}const s=f(e,["raiMediaFilteredCount"]);s!=null&&h(n,["raiMediaFilteredCount"],s);const o=f(e,["raiMediaFilteredReasons"]);return o!=null&&h(n,["raiMediaFilteredReasons"],o),n}function vN(e,t){const n={},r=f(e,["videos"]);if(r!=null){let i=r;Array.isArray(i)&&(i=i.map(a=>TN(a))),h(n,["generatedVideos"],i)}const s=f(e,["raiMediaFilteredCount"]);s!=null&&h(n,["raiMediaFilteredCount"],s);const o=f(e,["raiMediaFilteredReasons"]);return o!=null&&h(n,["raiMediaFilteredReasons"],o),n}function bN(e,t,n){const r={},s=f(e,["prompt"]);t!==void 0&&s!=null&&h(t,["instances[0]","prompt"],s);const o=f(e,["image"]);t!==void 0&&o!=null&&h(t,["instances[0]","image"],el(o));const i=f(e,["video"]);return t!==void 0&&i!=null&&h(t,["instances[0]","video"],AA(i)),r}function AN(e,t,n){const r={},s=f(e,["prompt"]);t!==void 0&&s!=null&&h(t,["instances[0]","prompt"],s);const o=f(e,["image"]);t!==void 0&&o!=null&&h(t,["instances[0]","image"],Gt(o));const i=f(e,["video"]);return t!==void 0&&i!=null&&h(t,["instances[0]","video"],SA(i)),r}function SN(e,t){const n={},r=f(e,["_self"]);r!=null&&h(n,["image"],kN(r));const s=f(e,["raiFilteredReason"]);s!=null&&h(n,["raiFilteredReason"],s);const o=f(e,["_self"]);return o!=null&&h(n,["safetyAttributes"],yA(o)),n}function Za(e,t){const n={},r=f(e,["_self"]);r!=null&&h(n,["image"],_A(r));const s=f(e,["raiFilteredReason"]);s!=null&&h(n,["raiFilteredReason"],s);const o=f(e,["_self"]);o!=null&&h(n,["safetyAttributes"],vA(o));const i=f(e,["prompt"]);return i!=null&&h(n,["enhancedPrompt"],i),n}function wN(e,t){const n={},r=f(e,["_self"]);r!=null&&h(n,["mask"],_A(r));const s=f(e,["labels"]);if(s!=null){let o=s;Array.isArray(o)&&(o=o.map(i=>i)),h(n,["labels"],o)}return n}function EN(e,t){const n={},r=f(e,["video"]);return r!=null&&h(n,["video"],dF(r)),n}function TN(e,t){const n={},r=f(e,["_self"]);return r!=null&&h(n,["video"],fF(r)),n}function PN(e,t){const n={},r=f(e,["modelSelectionConfig"]);r!=null&&h(n,["modelConfig"],r);const s=f(e,["responseJsonSchema"]);s!=null&&h(n,["responseJsonSchema"],s);const o=f(e,["audioTimestamp"]);o!=null&&h(n,["audioTimestamp"],o);const i=f(e,["candidateCount"]);i!=null&&h(n,["candidateCount"],i);const a=f(e,["enableAffectiveDialog"]);a!=null&&h(n,["enableAffectiveDialog"],a);const l=f(e,["frequencyPenalty"]);l!=null&&h(n,["frequencyPenalty"],l);const u=f(e,["logprobs"]);u!=null&&h(n,["logprobs"],u);const c=f(e,["maxOutputTokens"]);c!=null&&h(n,["maxOutputTokens"],c);const d=f(e,["mediaResolution"]);d!=null&&h(n,["mediaResolution"],d);const p=f(e,["presencePenalty"]);p!=null&&h(n,["presencePenalty"],p);const g=f(e,["responseLogprobs"]);g!=null&&h(n,["responseLogprobs"],g);const y=f(e,["responseMimeType"]);y!=null&&h(n,["responseMimeType"],y);const _=f(e,["responseModalities"]);_!=null&&h(n,["responseModalities"],_);const b=f(e,["responseSchema"]);b!=null&&h(n,["responseSchema"],b);const m=f(e,["routingConfig"]);m!=null&&h(n,["routingConfig"],m);const v=f(e,["seed"]);v!=null&&h(n,["seed"],v);const A=f(e,["speechConfig"]);A!=null&&h(n,["speechConfig"],A);const S=f(e,["stopSequences"]);S!=null&&h(n,["stopSequences"],S);const P=f(e,["temperature"]);P!=null&&h(n,["temperature"],P);const E=f(e,["thinkingConfig"]);E!=null&&h(n,["thinkingConfig"],E);const w=f(e,["topK"]);w!=null&&h(n,["topK"],w);const I=f(e,["topP"]);if(I!=null&&h(n,["topP"],I),f(e,["enableEnhancedCivicAnswers"])!==void 0)throw new Error("enableEnhancedCivicAnswers parameter is not supported in Vertex AI.");return n}function IN(e,t,n){const r={},s=f(t,["model"]);return s!=null&&h(r,["_url","name"],Ee(e,s)),r}function CN(e,t,n){const r={},s=f(t,["model"]);return s!=null&&h(r,["_url","name"],Ee(e,s)),r}function RN(e,t){const n={};if(f(e,["authConfig"])!==void 0)throw new Error("authConfig parameter is not supported in Gemini API.");const r=f(e,["enableWidget"]);return r!=null&&h(n,["enableWidget"],r),n}function MN(e,t){const n={};if(f(e,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is not supported in Gemini API.");if(f(e,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is not supported in Gemini API.");const r=f(e,["timeRangeFilter"]);return r!=null&&h(n,["timeRangeFilter"],r),n}function NN(e,t){const n={},r=f(e,["aspectRatio"]);r!=null&&h(n,["aspectRatio"],r);const s=f(e,["imageSize"]);if(s!=null&&h(n,["imageSize"],s),f(e,["personGeneration"])!==void 0)throw new Error("personGeneration parameter is not supported in Gemini API.");if(f(e,["outputMimeType"])!==void 0)throw new Error("outputMimeType parameter is not supported in Gemini API.");if(f(e,["outputCompressionQuality"])!==void 0)throw new Error("outputCompressionQuality parameter is not supported in Gemini API.");return n}function FN(e,t){const n={},r=f(e,["aspectRatio"]);r!=null&&h(n,["aspectRatio"],r);const s=f(e,["imageSize"]);s!=null&&h(n,["imageSize"],s);const o=f(e,["personGeneration"]);o!=null&&h(n,["personGeneration"],o);const i=f(e,["outputMimeType"]);i!=null&&h(n,["imageOutputOptions","mimeType"],i);const a=f(e,["outputCompressionQuality"]);return a!=null&&h(n,["imageOutputOptions","compressionQuality"],a),n}function kN(e,t){const n={},r=f(e,["bytesBase64Encoded"]);r!=null&&h(n,["imageBytes"],xn(r));const s=f(e,["mimeType"]);return s!=null&&h(n,["mimeType"],s),n}function _A(e,t){const n={},r=f(e,["gcsUri"]);r!=null&&h(n,["gcsUri"],r);const s=f(e,["bytesBase64Encoded"]);s!=null&&h(n,["imageBytes"],xn(s));const o=f(e,["mimeType"]);return o!=null&&h(n,["mimeType"],o),n}function el(e,t){const n={};if(f(e,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is not supported in Gemini API.");const r=f(e,["imageBytes"]);r!=null&&h(n,["bytesBase64Encoded"],xn(r));const s=f(e,["mimeType"]);return s!=null&&h(n,["mimeType"],s),n}function Gt(e,t){const n={},r=f(e,["gcsUri"]);r!=null&&h(n,["gcsUri"],r);const s=f(e,["imageBytes"]);s!=null&&h(n,["bytesBase64Encoded"],xn(s));const o=f(e,["mimeType"]);return o!=null&&h(n,["mimeType"],o),n}function ON(e,t,n,r){const s={},o=f(t,["pageSize"]);n!==void 0&&o!=null&&h(n,["_query","pageSize"],o);const i=f(t,["pageToken"]);n!==void 0&&i!=null&&h(n,["_query","pageToken"],i);const a=f(t,["filter"]);n!==void 0&&a!=null&&h(n,["_query","filter"],a);const l=f(t,["queryBase"]);return n!==void 0&&l!=null&&h(n,["_url","models_url"],oA(e,l)),s}function xN(e,t,n,r){const s={},o=f(t,["pageSize"]);n!==void 0&&o!=null&&h(n,["_query","pageSize"],o);const i=f(t,["pageToken"]);n!==void 0&&i!=null&&h(n,["_query","pageToken"],i);const a=f(t,["filter"]);n!==void 0&&a!=null&&h(n,["_query","filter"],a);const l=f(t,["queryBase"]);return n!==void 0&&l!=null&&h(n,["_url","models_url"],oA(e,l)),s}function DN(e,t,n){const r={},s=f(t,["config"]);return s!=null&&ON(e,s,r),r}function qN(e,t,n){const r={},s=f(t,["config"]);return s!=null&&xN(e,s,r),r}function LN(e,t){const n={},r=f(e,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);const s=f(e,["nextPageToken"]);s!=null&&h(n,["nextPageToken"],s);const o=f(e,["_self"]);if(o!=null){let i=iA(o);Array.isArray(i)&&(i=i.map(a=>gd(a))),h(n,["models"],i)}return n}function UN(e,t){const n={},r=f(e,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);const s=f(e,["nextPageToken"]);s!=null&&h(n,["nextPageToken"],s);const o=f(e,["_self"]);if(o!=null){let i=iA(o);Array.isArray(i)&&(i=i.map(a=>md(a))),h(n,["models"],i)}return n}function GN(e,t){const n={},r=f(e,["maskMode"]);r!=null&&h(n,["maskMode"],r);const s=f(e,["segmentationClasses"]);s!=null&&h(n,["maskClasses"],s);const o=f(e,["maskDilation"]);return o!=null&&h(n,["dilation"],o),n}function gd(e,t){const n={},r=f(e,["name"]);r!=null&&h(n,["name"],r);const s=f(e,["displayName"]);s!=null&&h(n,["displayName"],s);const o=f(e,["description"]);o!=null&&h(n,["description"],o);const i=f(e,["version"]);i!=null&&h(n,["version"],i);const a=f(e,["_self"]);a!=null&&h(n,["tunedModelInfo"],nF(a));const l=f(e,["inputTokenLimit"]);l!=null&&h(n,["inputTokenLimit"],l);const u=f(e,["outputTokenLimit"]);u!=null&&h(n,["outputTokenLimit"],u);const c=f(e,["supportedGenerationMethods"]);c!=null&&h(n,["supportedActions"],c);const d=f(e,["temperature"]);d!=null&&h(n,["temperature"],d);const p=f(e,["maxTemperature"]);p!=null&&h(n,["maxTemperature"],p);const g=f(e,["topP"]);g!=null&&h(n,["topP"],g);const y=f(e,["topK"]);y!=null&&h(n,["topK"],y);const _=f(e,["thinking"]);return _!=null&&h(n,["thinking"],_),n}function md(e,t){const n={},r=f(e,["name"]);r!=null&&h(n,["name"],r);const s=f(e,["displayName"]);s!=null&&h(n,["displayName"],s);const o=f(e,["description"]);o!=null&&h(n,["description"],o);const i=f(e,["versionId"]);i!=null&&h(n,["version"],i);const a=f(e,["deployedModels"]);if(a!=null){let p=a;Array.isArray(p)&&(p=p.map(g=>ZM(g))),h(n,["endpoints"],p)}const l=f(e,["labels"]);l!=null&&h(n,["labels"],l);const u=f(e,["_self"]);u!=null&&h(n,["tunedModelInfo"],rF(u));const c=f(e,["defaultCheckpointId"]);c!=null&&h(n,["defaultCheckpointId"],c);const d=f(e,["checkpoints"]);if(d!=null){let p=d;Array.isArray(p)&&(p=p.map(g=>g)),h(n,["checkpoints"],p)}return n}function VN(e,t){const n={},r=f(e,["mediaResolution"]);r!=null&&h(n,["mediaResolution"],r);const s=f(e,["codeExecutionResult"]);s!=null&&h(n,["codeExecutionResult"],s);const o=f(e,["executableCode"]);o!=null&&h(n,["executableCode"],o);const i=f(e,["fileData"]);i!=null&&h(n,["fileData"],eN(i));const a=f(e,["functionCall"]);a!=null&&h(n,["functionCall"],tN(a));const l=f(e,["functionResponse"]);l!=null&&h(n,["functionResponse"],l);const u=f(e,["inlineData"]);u!=null&&h(n,["inlineData"],PM(u));const c=f(e,["text"]);c!=null&&h(n,["text"],c);const d=f(e,["thought"]);d!=null&&h(n,["thought"],d);const p=f(e,["thoughtSignature"]);p!=null&&h(n,["thoughtSignature"],p);const g=f(e,["videoMetadata"]);return g!=null&&h(n,["videoMetadata"],g),n}function BN(e,t){const n={},r=f(e,["productImage"]);return r!=null&&h(n,["image"],Gt(r)),n}function HN(e,t,n){const r={},s=f(e,["numberOfImages"]);t!==void 0&&s!=null&&h(t,["parameters","sampleCount"],s);const o=f(e,["baseSteps"]);t!==void 0&&o!=null&&h(t,["parameters","baseSteps"],o);const i=f(e,["outputGcsUri"]);t!==void 0&&i!=null&&h(t,["parameters","storageUri"],i);const a=f(e,["seed"]);t!==void 0&&a!=null&&h(t,["parameters","seed"],a);const l=f(e,["safetyFilterLevel"]);t!==void 0&&l!=null&&h(t,["parameters","safetySetting"],l);const u=f(e,["personGeneration"]);t!==void 0&&u!=null&&h(t,["parameters","personGeneration"],u);const c=f(e,["addWatermark"]);t!==void 0&&c!=null&&h(t,["parameters","addWatermark"],c);const d=f(e,["outputMimeType"]);t!==void 0&&d!=null&&h(t,["parameters","outputOptions","mimeType"],d);const p=f(e,["outputCompressionQuality"]);t!==void 0&&p!=null&&h(t,["parameters","outputOptions","compressionQuality"],p);const g=f(e,["enhancePrompt"]);t!==void 0&&g!=null&&h(t,["parameters","enhancePrompt"],g);const y=f(e,["labels"]);return t!==void 0&&y!=null&&h(t,["labels"],y),r}function JN(e,t,n){const r={},s=f(t,["model"]);s!=null&&h(r,["_url","model"],Ee(e,s));const o=f(t,["source"]);o!=null&&WN(o,r);const i=f(t,["config"]);return i!=null&&HN(i,r),r}function jN(e,t){const n={},r=f(e,["predictions"]);if(r!=null){let s=r;Array.isArray(s)&&(s=s.map(o=>Za(o))),h(n,["generatedImages"],s)}return n}function WN(e,t,n){const r={},s=f(e,["prompt"]);t!==void 0&&s!=null&&h(t,["instances[0]","prompt"],s);const o=f(e,["personImage"]);t!==void 0&&o!=null&&h(t,["instances[0]","personImage","image"],Gt(o));const i=f(e,["productImages"]);if(t!==void 0&&i!=null){let a=i;Array.isArray(a)&&(a=a.map(l=>BN(l))),h(t,["instances[0]","productImages"],a)}return r}function KN(e,t){const n={},r=f(e,["referenceImage"]);r!=null&&h(n,["referenceImage"],Gt(r));const s=f(e,["referenceId"]);s!=null&&h(n,["referenceId"],s);const o=f(e,["referenceType"]);o!=null&&h(n,["referenceType"],o);const i=f(e,["maskImageConfig"]);i!=null&&h(n,["maskImageConfig"],GN(i));const a=f(e,["controlImageConfig"]);a!=null&&h(n,["controlImageConfig"],kM(a));const l=f(e,["styleImageConfig"]);l!=null&&h(n,["styleImageConfig"],l);const u=f(e,["subjectImageConfig"]);return u!=null&&h(n,["subjectImageConfig"],u),n}function yA(e,t){const n={},r=f(e,["safetyAttributes","categories"]);r!=null&&h(n,["categories"],r);const s=f(e,["safetyAttributes","scores"]);s!=null&&h(n,["scores"],s);const o=f(e,["contentType"]);return o!=null&&h(n,["contentType"],o),n}function vA(e,t){const n={},r=f(e,["safetyAttributes","categories"]);r!=null&&h(n,["categories"],r);const s=f(e,["safetyAttributes","scores"]);s!=null&&h(n,["scores"],s);const o=f(e,["contentType"]);return o!=null&&h(n,["contentType"],o),n}function $N(e,t){const n={},r=f(e,["category"]);if(r!=null&&h(n,["category"],r),f(e,["method"])!==void 0)throw new Error("method parameter is not supported in Gemini API.");const s=f(e,["threshold"]);return s!=null&&h(n,["threshold"],s),n}function YN(e,t){const n={},r=f(e,["image"]);return r!=null&&h(n,["image"],Gt(r)),n}function zN(e,t,n){const r={},s=f(e,["mode"]);t!==void 0&&s!=null&&h(t,["parameters","mode"],s);const o=f(e,["maxPredictions"]);t!==void 0&&o!=null&&h(t,["parameters","maxPredictions"],o);const i=f(e,["confidenceThreshold"]);t!==void 0&&i!=null&&h(t,["parameters","confidenceThreshold"],i);const a=f(e,["maskDilation"]);t!==void 0&&a!=null&&h(t,["parameters","maskDilation"],a);const l=f(e,["binaryColorThreshold"]);t!==void 0&&l!=null&&h(t,["parameters","binaryColorThreshold"],l);const u=f(e,["labels"]);return t!==void 0&&u!=null&&h(t,["labels"],u),r}function XN(e,t,n){const r={},s=f(t,["model"]);s!=null&&h(r,["_url","model"],Ee(e,s));const o=f(t,["source"]);o!=null&&ZN(o,r);const i=f(t,["config"]);return i!=null&&zN(i,r),r}function QN(e,t){const n={},r=f(e,["predictions"]);if(r!=null){let s=r;Array.isArray(s)&&(s=s.map(o=>wN(o))),h(n,["generatedMasks"],s)}return n}function ZN(e,t,n){const r={},s=f(e,["prompt"]);t!==void 0&&s!=null&&h(t,["instances[0]","prompt"],s);const o=f(e,["image"]);t!==void 0&&o!=null&&h(t,["instances[0]","image"],Gt(o));const i=f(e,["scribbleImage"]);return t!==void 0&&i!=null&&h(t,["instances[0]","scribble"],YN(i)),r}function eF(e,t){const n={},r=f(e,["retrievalConfig"]);r!=null&&h(n,["retrievalConfig"],r);const s=f(e,["functionCallingConfig"]);return s!=null&&h(n,["functionCallingConfig"],nN(s)),n}function tF(e,t){const n={};if(f(e,["retrieval"])!==void 0)throw new Error("retrieval parameter is not supported in Gemini API.");const r=f(e,["computerUse"]);r!=null&&h(n,["computerUse"],r);const s=f(e,["fileSearch"]);s!=null&&h(n,["fileSearch"],s);const o=f(e,["codeExecution"]);if(o!=null&&h(n,["codeExecution"],o),f(e,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");const i=f(e,["functionDeclarations"]);if(i!=null){let d=i;Array.isArray(d)&&(d=d.map(p=>p)),h(n,["functionDeclarations"],d)}const a=f(e,["googleMaps"]);a!=null&&h(n,["googleMaps"],RN(a));const l=f(e,["googleSearch"]);l!=null&&h(n,["googleSearch"],MN(l));const u=f(e,["googleSearchRetrieval"]);u!=null&&h(n,["googleSearchRetrieval"],u);const c=f(e,["urlContext"]);return c!=null&&h(n,["urlContext"],c),n}function bA(e,t){const n={},r=f(e,["retrieval"]);r!=null&&h(n,["retrieval"],r);const s=f(e,["computerUse"]);if(s!=null&&h(n,["computerUse"],s),f(e,["fileSearch"])!==void 0)throw new Error("fileSearch parameter is not supported in Vertex AI.");const o=f(e,["codeExecution"]);o!=null&&h(n,["codeExecution"],o);const i=f(e,["enterpriseWebSearch"]);i!=null&&h(n,["enterpriseWebSearch"],i);const a=f(e,["functionDeclarations"]);if(a!=null){let p=a;Array.isArray(p)&&(p=p.map(g=>rN(g))),h(n,["functionDeclarations"],p)}const l=f(e,["googleMaps"]);l!=null&&h(n,["googleMaps"],l);const u=f(e,["googleSearch"]);u!=null&&h(n,["googleSearch"],u);const c=f(e,["googleSearchRetrieval"]);c!=null&&h(n,["googleSearchRetrieval"],c);const d=f(e,["urlContext"]);return d!=null&&h(n,["urlContext"],d),n}function nF(e,t){const n={},r=f(e,["baseModel"]);r!=null&&h(n,["baseModel"],r);const s=f(e,["createTime"]);s!=null&&h(n,["createTime"],s);const o=f(e,["updateTime"]);return o!=null&&h(n,["updateTime"],o),n}function rF(e,t){const n={},r=f(e,["labels","google-vertex-llm-tuning-base-model-id"]);r!=null&&h(n,["baseModel"],r);const s=f(e,["createTime"]);s!=null&&h(n,["createTime"],s);const o=f(e,["updateTime"]);return o!=null&&h(n,["updateTime"],o),n}function sF(e,t,n){const r={},s=f(e,["displayName"]);t!==void 0&&s!=null&&h(t,["displayName"],s);const o=f(e,["description"]);t!==void 0&&o!=null&&h(t,["description"],o);const i=f(e,["defaultCheckpointId"]);return t!==void 0&&i!=null&&h(t,["defaultCheckpointId"],i),r}function oF(e,t,n){const r={},s=f(e,["displayName"]);t!==void 0&&s!=null&&h(t,["displayName"],s);const o=f(e,["description"]);t!==void 0&&o!=null&&h(t,["description"],o);const i=f(e,["defaultCheckpointId"]);return t!==void 0&&i!=null&&h(t,["defaultCheckpointId"],i),r}function iF(e,t,n){const r={},s=f(t,["model"]);s!=null&&h(r,["_url","name"],Ee(e,s));const o=f(t,["config"]);return o!=null&&sF(o,r),r}function aF(e,t,n){const r={},s=f(t,["model"]);s!=null&&h(r,["_url","model"],Ee(e,s));const o=f(t,["config"]);return o!=null&&oF(o,r),r}function lF(e,t,n){const r={},s=f(e,["outputGcsUri"]);t!==void 0&&s!=null&&h(t,["parameters","storageUri"],s);const o=f(e,["safetyFilterLevel"]);t!==void 0&&o!=null&&h(t,["parameters","safetySetting"],o);const i=f(e,["personGeneration"]);t!==void 0&&i!=null&&h(t,["parameters","personGeneration"],i);const a=f(e,["includeRaiReason"]);t!==void 0&&a!=null&&h(t,["parameters","includeRaiReason"],a);const l=f(e,["outputMimeType"]);t!==void 0&&l!=null&&h(t,["parameters","outputOptions","mimeType"],l);const u=f(e,["outputCompressionQuality"]);t!==void 0&&u!=null&&h(t,["parameters","outputOptions","compressionQuality"],u);const c=f(e,["enhanceInputImage"]);t!==void 0&&c!=null&&h(t,["parameters","upscaleConfig","enhanceInputImage"],c);const d=f(e,["imagePreservationFactor"]);t!==void 0&&d!=null&&h(t,["parameters","upscaleConfig","imagePreservationFactor"],d);const p=f(e,["labels"]);t!==void 0&&p!=null&&h(t,["labels"],p);const g=f(e,["numberOfImages"]);t!==void 0&&g!=null&&h(t,["parameters","sampleCount"],g);const y=f(e,["mode"]);return t!==void 0&&y!=null&&h(t,["parameters","mode"],y),r}function uF(e,t,n){const r={},s=f(t,["model"]);s!=null&&h(r,["_url","model"],Ee(e,s));const o=f(t,["image"]);o!=null&&h(r,["instances[0]","image"],Gt(o));const i=f(t,["upscaleFactor"]);i!=null&&h(r,["parameters","upscaleConfig","upscaleFactor"],i);const a=f(t,["config"]);return a!=null&&lF(a,r),r}function cF(e,t){const n={},r=f(e,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);const s=f(e,["predictions"]);if(s!=null){let o=s;Array.isArray(o)&&(o=o.map(i=>Za(i))),h(n,["generatedImages"],o)}return n}function dF(e,t){const n={},r=f(e,["uri"]);r!=null&&h(n,["uri"],r);const s=f(e,["encodedVideo"]);s!=null&&h(n,["videoBytes"],xn(s));const o=f(e,["encoding"]);return o!=null&&h(n,["mimeType"],o),n}function fF(e,t){const n={},r=f(e,["gcsUri"]);r!=null&&h(n,["uri"],r);const s=f(e,["bytesBase64Encoded"]);s!=null&&h(n,["videoBytes"],xn(s));const o=f(e,["mimeType"]);return o!=null&&h(n,["mimeType"],o),n}function pF(e,t){const n={},r=f(e,["image"]);r!=null&&h(n,["_self"],Gt(r));const s=f(e,["maskMode"]);return s!=null&&h(n,["maskMode"],s),n}function hF(e,t){const n={},r=f(e,["image"]);r!=null&&h(n,["image"],el(r));const s=f(e,["referenceType"]);return s!=null&&h(n,["referenceType"],s),n}function gF(e,t){const n={},r=f(e,["image"]);r!=null&&h(n,["image"],Gt(r));const s=f(e,["referenceType"]);return s!=null&&h(n,["referenceType"],s),n}function AA(e,t){const n={},r=f(e,["uri"]);r!=null&&h(n,["uri"],r);const s=f(e,["videoBytes"]);s!=null&&h(n,["encodedVideo"],xn(s));const o=f(e,["mimeType"]);return o!=null&&h(n,["encoding"],o),n}function SA(e,t){const n={},r=f(e,["uri"]);r!=null&&h(n,["gcsUri"],r);const s=f(e,["videoBytes"]);s!=null&&h(n,["bytesBase64Encoded"],xn(s));const o=f(e,["mimeType"]);return o!=null&&h(n,["mimeType"],o),n}function mF(e,t){const n={},r=f(e,["displayName"]);return t!==void 0&&r!=null&&h(t,["displayName"],r),n}function _F(e){const t={},n=f(e,["config"]);return n!=null&&mF(n,t),t}function yF(e,t){const n={},r=f(e,["force"]);return t!==void 0&&r!=null&&h(t,["_query","force"],r),n}function vF(e){const t={},n=f(e,["name"]);n!=null&&h(t,["_url","name"],n);const r=f(e,["config"]);return r!=null&&yF(r,t),t}function bF(e){const t={},n=f(e,["name"]);return n!=null&&h(t,["_url","name"],n),t}function AF(e,t){const n={},r=f(e,["customMetadata"]);if(t!==void 0&&r!=null){let o=r;Array.isArray(o)&&(o=o.map(i=>i)),h(t,["customMetadata"],o)}const s=f(e,["chunkingConfig"]);return t!==void 0&&s!=null&&h(t,["chunkingConfig"],s),n}function SF(e){const t={},n=f(e,["name"]);n!=null&&h(t,["name"],n);const r=f(e,["metadata"]);r!=null&&h(t,["metadata"],r);const s=f(e,["done"]);s!=null&&h(t,["done"],s);const o=f(e,["error"]);o!=null&&h(t,["error"],o);const i=f(e,["response"]);return i!=null&&h(t,["response"],EF(i)),t}function wF(e){const t={},n=f(e,["fileSearchStoreName"]);n!=null&&h(t,["_url","file_search_store_name"],n);const r=f(e,["fileName"]);r!=null&&h(t,["fileName"],r);const s=f(e,["config"]);return s!=null&&AF(s,t),t}function EF(e){const t={},n=f(e,["sdkHttpResponse"]);n!=null&&h(t,["sdkHttpResponse"],n);const r=f(e,["parent"]);r!=null&&h(t,["parent"],r);const s=f(e,["documentName"]);return s!=null&&h(t,["documentName"],s),t}function TF(e,t){const n={},r=f(e,["pageSize"]);t!==void 0&&r!=null&&h(t,["_query","pageSize"],r);const s=f(e,["pageToken"]);return t!==void 0&&s!=null&&h(t,["_query","pageToken"],s),n}function PF(e){const t={},n=f(e,["config"]);return n!=null&&TF(n,t),t}function IF(e){const t={},n=f(e,["sdkHttpResponse"]);n!=null&&h(t,["sdkHttpResponse"],n);const r=f(e,["nextPageToken"]);r!=null&&h(t,["nextPageToken"],r);const s=f(e,["fileSearchStores"]);if(s!=null){let o=s;Array.isArray(o)&&(o=o.map(i=>i)),h(t,["fileSearchStores"],o)}return t}function wA(e,t){const n={},r=f(e,["mimeType"]);t!==void 0&&r!=null&&h(t,["mimeType"],r);const s=f(e,["displayName"]);t!==void 0&&s!=null&&h(t,["displayName"],s);const o=f(e,["customMetadata"]);if(t!==void 0&&o!=null){let a=o;Array.isArray(a)&&(a=a.map(l=>l)),h(t,["customMetadata"],a)}const i=f(e,["chunkingConfig"]);return t!==void 0&&i!=null&&h(t,["chunkingConfig"],i),n}function CF(e){const t={},n=f(e,["fileSearchStoreName"]);n!=null&&h(t,["_url","file_search_store_name"],n);const r=f(e,["config"]);return r!=null&&wA(r,t),t}function RF(e){const t={},n=f(e,["sdkHttpResponse"]);return n!=null&&h(t,["sdkHttpResponse"],n),t}const MF="Content-Type",NF="X-Server-Timeout",FF="User-Agent",_d="x-goog-api-client",kF="1.41.0",OF=`google-genai-sdk/${kF}`,xF="v1beta1",DF="v1beta",qF=5,LF=[408,429,500,502,503,504];class UF{constructor(t){var n,r,s;this.clientOptions=Object.assign({},t),this.customBaseUrl=(n=t.httpOptions)===null||n===void 0?void 0:n.baseUrl,this.clientOptions.vertexai&&(this.clientOptions.project&&this.clientOptions.location?this.clientOptions.apiKey=void 0:this.clientOptions.apiKey&&(this.clientOptions.project=void 0,this.clientOptions.location=void 0));const o={};if(this.clientOptions.vertexai){if(!this.clientOptions.location&&!this.clientOptions.apiKey&&!this.customBaseUrl&&(this.clientOptions.location="global"),!(this.clientOptions.project&&this.clientOptions.location||this.clientOptions.apiKey)&&!this.customBaseUrl)throw new Error("Authentication is not set up. Please provide either a project and location, or an API key, or a custom base URL.");const a=t.project&&t.location||!!t.apiKey;this.customBaseUrl&&!a?(o.baseUrl=this.customBaseUrl,this.clientOptions.project=void 0,this.clientOptions.location=void 0):this.clientOptions.apiKey||this.clientOptions.location==="global"?o.baseUrl="https://aiplatform.googleapis.com/":this.clientOptions.project&&this.clientOptions.location&&(o.baseUrl=`https://${this.clientOptions.location}-aiplatform.googleapis.com/`),o.apiVersion=(r=this.clientOptions.apiVersion)!==null&&r!==void 0?r:xF}else{if(!this.clientOptions.apiKey)throw new Br({message:"API key must be set when using the Gemini API.",status:403});o.apiVersion=(s=this.clientOptions.apiVersion)!==null&&s!==void 0?s:DF,o.baseUrl="https://generativelanguage.googleapis.com/"}o.headers=this.getDefaultHeaders(),this.clientOptions.httpOptions=o,t.httpOptions&&(this.clientOptions.httpOptions=this.patchHttpOptions(o,t.httpOptions))}isVertexAI(){var t;return(t=this.clientOptions.vertexai)!==null&&t!==void 0?t:!1}getProject(){return this.clientOptions.project}getLocation(){return this.clientOptions.location}getCustomBaseUrl(){return this.customBaseUrl}async getAuthHeaders(){const t=new Headers;return await this.clientOptions.auth.addAuthHeaders(t),t}getApiVersion(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.apiVersion!==void 0)return this.clientOptions.httpOptions.apiVersion;throw new Error("API version is not set.")}getBaseUrl(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.baseUrl!==void 0)return this.clientOptions.httpOptions.baseUrl;throw new Error("Base URL is not set.")}getRequestUrl(){return this.getRequestUrlInternal(this.clientOptions.httpOptions)}getHeaders(){if(this.clientOptions.httpOptions&&this.clientOptions.httpOptions.headers!==void 0)return this.clientOptions.httpOptions.headers;throw new Error("Headers are not set.")}getRequestUrlInternal(t){if(!t||t.baseUrl===void 0||t.apiVersion===void 0)throw new Error("HTTP options are not correctly set.");const r=[t.baseUrl.endsWith("/")?t.baseUrl.slice(0,-1):t.baseUrl];return t.apiVersion&&t.apiVersion!==""&&r.push(t.apiVersion),r.join("/")}getBaseResourcePath(){return`projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`}getApiKey(){return this.clientOptions.apiKey}getWebsocketBaseUrl(){const t=this.getBaseUrl(),n=new URL(t);return n.protocol=n.protocol=="http:"?"ws":"wss",n.toString()}setBaseUrl(t){if(this.clientOptions.httpOptions)this.clientOptions.httpOptions.baseUrl=t;else throw new Error("HTTP options are not correctly set.")}constructUrl(t,n,r){const s=[this.getRequestUrlInternal(n)];return r&&s.push(this.getBaseResourcePath()),t!==""&&s.push(t),new URL(`${s.join("/")}`)}shouldPrependVertexProjectPath(t,n){return!(n.baseUrl&&n.baseUrlResourceScope===Ea.COLLECTION||this.clientOptions.apiKey||!this.clientOptions.vertexai||t.path.startsWith("projects/")||t.httpMethod==="GET"&&t.path.startsWith("publishers/google/models"))}async request(t){let n=this.clientOptions.httpOptions;t.httpOptions&&(n=this.patchHttpOptions(this.clientOptions.httpOptions,t.httpOptions));const r=this.shouldPrependVertexProjectPath(t,n),s=this.constructUrl(t.path,n,r);if(t.queryParams)for(const[i,a]of Object.entries(t.queryParams))s.searchParams.append(i,String(a));let o={};if(t.httpMethod==="GET"){if(t.body&&t.body!=="{}")throw new Error("Request body should be empty for GET request, but got non empty request body")}else o.body=t.body;return o=await this.includeExtraHttpOptionsToRequestInit(o,n,s.toString(),t.abortSignal),this.unaryApiCall(s,o,t.httpMethod)}patchHttpOptions(t,n){const r=JSON.parse(JSON.stringify(t));for(const[s,o]of Object.entries(n))typeof o=="object"?r[s]=Object.assign(Object.assign({},r[s]),o):o!==void 0&&(r[s]=o);return r}async requestStream(t){let n=this.clientOptions.httpOptions;t.httpOptions&&(n=this.patchHttpOptions(this.clientOptions.httpOptions,t.httpOptions));const r=this.shouldPrependVertexProjectPath(t,n),s=this.constructUrl(t.path,n,r);(!s.searchParams.has("alt")||s.searchParams.get("alt")!=="sse")&&s.searchParams.set("alt","sse");let o={};return o.body=t.body,o=await this.includeExtraHttpOptionsToRequestInit(o,n,s.toString(),t.abortSignal),this.streamApiCall(s,o,t.httpMethod)}async includeExtraHttpOptionsToRequestInit(t,n,r,s){if(n&&n.timeout||s){const o=new AbortController,i=o.signal;if(n.timeout&&n?.timeout>0){const a=setTimeout(()=>o.abort(),n.timeout);a&&typeof a.unref=="function"&&a.unref()}s&&s.addEventListener("abort",()=>{o.abort()}),t.signal=i}return n&&n.extraBody!==null&&GF(t,n.extraBody),t.headers=await this.getHeadersInternal(n,r),t}async unaryApiCall(t,n,r){return this.apiCall(t.toString(),Object.assign(Object.assign({},n),{method:r})).then(async s=>(await By(s),new Ta(s))).catch(s=>{throw s instanceof Error?s:new Error(JSON.stringify(s))})}async streamApiCall(t,n,r){return this.apiCall(t.toString(),Object.assign(Object.assign({},n),{method:r})).then(async s=>(await By(s),this.processStreamResponse(s))).catch(s=>{throw s instanceof Error?s:new Error(JSON.stringify(s))})}processStreamResponse(t){return Ft(this,arguments,function*(){var r;const s=(r=t?.body)===null||r===void 0?void 0:r.getReader(),o=new TextDecoder("utf-8");if(!s)throw new Error("Response body is empty");try{let i="";const a="data:",l=[`
86
-
87
- `,"\r\r",`\r
88
- \r
89
- `];for(;;){const{done:u,value:c}=yield me(s.read());if(u){if(i.trim().length>0)throw new Error("Incomplete JSON segment at the end");break}const d=o.decode(c,{stream:!0});try{const y=JSON.parse(d);if("error"in y){const _=JSON.parse(JSON.stringify(y.error)),b=_.status,m=_.code,v=`got status: ${b}. ${JSON.stringify(y)}`;if(m>=400&&m<600)throw new Br({message:v,status:m})}}catch(y){if(y.name==="ApiError")throw y}i+=d;let p=-1,g=0;for(;;){p=-1,g=0;for(const b of l){const m=i.indexOf(b);m!==-1&&(p===-1||m<p)&&(p=m,g=b.length)}if(p===-1)break;const y=i.substring(0,p);i=i.substring(p+g);const _=y.trim();if(_.startsWith(a)){const b=_.substring(a.length).trim();try{const m=new Response(b,{headers:t?.headers,status:t?.status,statusText:t?.statusText});yield yield me(new Ta(m))}catch(m){throw new Error(`exception parsing stream chunk ${b}. ${m}`)}}}}}finally{s.releaseLock()}})}async apiCall(t,n){var r;if(!this.clientOptions.httpOptions||!this.clientOptions.httpOptions.retryOptions)return fetch(t,n);const s=this.clientOptions.httpOptions.retryOptions;return yI(async()=>{const i=await fetch(t,n);if(i.ok)return i;throw LF.includes(i.status)?new Error(`Retryable HTTP Error: ${i.statusText}`):new k0(`Non-retryable exception ${i.statusText} sending request`)},{retries:((r=s.attempts)!==null&&r!==void 0?r:qF)-1})}getDefaultHeaders(){const t={},n=OF+" "+this.clientOptions.userAgentExtra;return t[FF]=n,t[_d]=n,t[MF]="application/json",t}async getHeadersInternal(t,n){const r=new Headers;if(t&&t.headers){for(const[s,o]of Object.entries(t.headers))r.append(s,o);t.timeout&&t.timeout>0&&r.append(NF,String(Math.ceil(t.timeout/1e3)))}return await this.clientOptions.auth.addAuthHeaders(r,n),r}getFileName(t){var n;let r="";return typeof t=="string"&&(r=t.replace(/[/\\]+$/,""),r=(n=r.split(/[/\\]/).pop())!==null&&n!==void 0?n:""),r}async uploadFile(t,n){var r;const s={};n!=null&&(s.mimeType=n.mimeType,s.name=n.name,s.displayName=n.displayName),s.name&&!s.name.startsWith("files/")&&(s.name=`files/${s.name}`);const o=this.clientOptions.uploader,i=await o.stat(t);s.sizeBytes=String(i.size);const a=(r=n?.mimeType)!==null&&r!==void 0?r:i.type;if(a===void 0||a==="")throw new Error("Can not determine mimeType. Please provide mimeType in the config.");s.mimeType=a;const l={file:s},u=this.getFileName(t),c=ie("upload/v1beta/files",l._url),d=await this.fetchUploadUrl(c,s.sizeBytes,s.mimeType,u,l,n?.httpOptions);return o.upload(t,d,this)}async uploadFileToFileSearchStore(t,n,r){var s;const o=this.clientOptions.uploader,i=await o.stat(n),a=String(i.size),l=(s=r?.mimeType)!==null&&s!==void 0?s:i.type;if(l===void 0||l==="")throw new Error("Can not determine mimeType. Please provide mimeType in the config.");const u=`upload/v1beta/${t}:uploadToFileSearchStore`,c=this.getFileName(n),d={};r!=null&&wA(r,d);const p=await this.fetchUploadUrl(u,a,l,c,d,r?.httpOptions);return o.uploadToFileSearchStore(n,p,this)}async downloadFile(t){await this.clientOptions.downloader.download(t,this)}async fetchUploadUrl(t,n,r,s,o,i){var a;let l={};i?l=i:l={apiVersion:"",headers:Object.assign({"Content-Type":"application/json","X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${n}`,"X-Goog-Upload-Header-Content-Type":`${r}`},s?{"X-Goog-Upload-File-Name":s}:{})};const u=await this.request({path:t,body:JSON.stringify(o),httpMethod:"POST",httpOptions:l});if(!u||!u?.headers)throw new Error("Server did not return an HttpResponse or the returned HttpResponse did not have headers.");const c=(a=u?.headers)===null||a===void 0?void 0:a["x-goog-upload-url"];if(c===void 0)throw new Error("Failed to get upload url. Server did not return the x-google-upload-url in the headers");return c}}async function By(e){var t;if(e===void 0)throw new Error("response is undefined");if(!e.ok){const n=e.status;let r;!((t=e.headers.get("content-type"))===null||t===void 0)&&t.includes("application/json")?r=await e.json():r={error:{message:await e.text(),code:e.status,status:e.statusText}};const s=JSON.stringify(r);throw n>=400&&n<600?new Br({message:s,status:n}):new Error(s)}}function GF(e,t){if(!t||Object.keys(t).length===0)return;if(e.body instanceof Blob){console.warn("includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.");return}let n={};if(typeof e.body=="string"&&e.body.length>0)try{const o=JSON.parse(e.body);if(typeof o=="object"&&o!==null&&!Array.isArray(o))n=o;else{console.warn("includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.");return}}catch{console.warn("includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.");return}function r(o,i){const a=Object.assign({},o);for(const l in i)if(Object.prototype.hasOwnProperty.call(i,l)){const u=i[l],c=a[l];u&&typeof u=="object"&&!Array.isArray(u)&&c&&typeof c=="object"&&!Array.isArray(c)?a[l]=r(c,u):(c&&u&&typeof c!=typeof u&&console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${l}". Original type: ${typeof c}, New type: ${typeof u}. Overwriting.`),a[l]=u)}return a}const s=r(n,t);e.body=JSON.stringify(s)}const VF="mcp_used/unknown";let EA=!1;function TA(e){for(const t of e)if(BF(t)||typeof t=="object"&&"inputSchema"in t)return!0;return EA}function PA(e){var t;const n=(t=e[_d])!==null&&t!==void 0?t:"";e[_d]=(n+` ${VF}`).trimStart()}function BF(e){return e!==null&&typeof e=="object"&&e instanceof Ri}function HF(e){return Ft(this,arguments,function*(n,r=100){let s,o=0;for(;o<r;){const i=yield me(n.listTools({cursor:s}));for(const a of i.tools)yield yield me(a),o++;if(!i.nextCursor)break;s=i.nextCursor}})}class Ri{constructor(t=[],n){this.mcpTools=[],this.functionNameToMcpClient={},this.mcpClients=t,this.config=n}static create(t,n){return new Ri(t,n)}async initialize(){var t,n,r,s;if(this.mcpTools.length>0)return;const o={},i=[];for(const c of this.mcpClients)try{for(var a=!0,l=(n=void 0,kt(HF(c))),u;u=await l.next(),t=u.done,!t;a=!0){s=u.value,a=!1;const d=s;i.push(d);const p=d.name;if(o[p])throw new Error(`Duplicate function name ${p} found in MCP tools. Please ensure function names are unique.`);o[p]=c}}catch(d){n={error:d}}finally{try{!a&&!t&&(r=l.return)&&await r.call(l)}finally{if(n)throw n.error}}this.mcpTools=i,this.functionNameToMcpClient=o}async tool(){return await this.initialize(),SC(this.mcpTools,this.config)}async callTool(t){await this.initialize();const n=[];for(const r of t)if(r.name in this.functionNameToMcpClient){const s=this.functionNameToMcpClient[r.name];let o;this.config.timeout&&(o={timeout:this.config.timeout});const i=await s.callTool({name:r.name,arguments:r.args},void 0,o);n.push({functionResponse:{name:r.name,response:i.isError?{error:i}:i}})}return n}}function JF(e){return e!==null&&typeof e=="object"&&"listTools"in e&&typeof e.listTools=="function"}function jF(...e){if(EA=!0,e.length===0)throw new Error("No MCP clients provided");const t=e[e.length-1];return JF(t)?Ri.create(e,{}):Ri.create(e.slice(0,e.length-1),t)}async function WF(e,t,n){const r=new X0;let s;n.data instanceof Blob?s=JSON.parse(await n.data.text()):s=JSON.parse(n.data),Object.assign(r,s),t(r)}class KF{constructor(t,n,r){this.apiClient=t,this.auth=n,this.webSocketFactory=r}async connect(t){var n,r;if(this.apiClient.isVertexAI())throw new Error("Live music is not supported for Vertex AI.");console.warn("Live music generation is experimental and may change in future versions.");const s=this.apiClient.getWebsocketBaseUrl(),o=this.apiClient.getApiVersion(),i=zF(this.apiClient.getDefaultHeaders()),a=this.apiClient.getApiKey(),l=`${s}/ws/google.ai.generativelanguage.${o}.GenerativeService.BidiGenerateMusic?key=${a}`;let u=()=>{};const c=new Promise(A=>{u=A}),d=t.callbacks,p=function(){u({})},g=this.apiClient,y={onopen:p,onmessage:A=>{WF(g,d.onmessage,A)},onerror:(n=d?.onerror)!==null&&n!==void 0?n:function(A){},onclose:(r=d?.onclose)!==null&&r!==void 0?r:function(A){}},_=this.webSocketFactory.create(l,YF(i),y);_.connect(),await c;const v={setup:{model:Ee(this.apiClient,t.model)}};return _.send(JSON.stringify(v)),new $F(_,this.apiClient)}}class $F{constructor(t,n){this.conn=t,this.apiClient=n}async setWeightedPrompts(t){if(!t.weightedPrompts||Object.keys(t.weightedPrompts).length===0)throw new Error("Weighted prompts must be set and contain at least one entry.");const n=mM(t);this.conn.send(JSON.stringify({clientContent:n}))}async setMusicGenerationConfig(t){t.musicGenerationConfig||(t.musicGenerationConfig={});const n=gM(t);this.conn.send(JSON.stringify(n))}sendPlaybackControl(t){const n={playbackControl:t};this.conn.send(JSON.stringify(n))}play(){this.sendPlaybackControl(ar.PLAY)}pause(){this.sendPlaybackControl(ar.PAUSE)}stop(){this.sendPlaybackControl(ar.STOP)}resetContext(){this.sendPlaybackControl(ar.RESET_CONTEXT)}close(){this.conn.close()}}function YF(e){const t={};return e.forEach((n,r)=>{t[r]=n}),t}function zF(e){const t=new Headers;for(const[n,r]of Object.entries(e))t.append(n,r);return t}const XF="FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.";async function QF(e,t,n){const r=new z0;let s;n.data instanceof Blob?s=await n.data.text():n.data instanceof ArrayBuffer?s=new TextDecoder().decode(n.data):s=n.data;const o=JSON.parse(s);if(e.isVertexAI()){const i=vM(o);Object.assign(r,i)}else Object.assign(r,o);t(r)}class IA{constructor(t,n,r){this.apiClient=t,this.auth=n,this.webSocketFactory=r,this.music=new KF(this.apiClient,this.auth,this.webSocketFactory)}async connect(t){var n,r,s,o,i,a;if(t.config&&t.config.httpOptions)throw new Error("The Live module does not support httpOptions at request-level in LiveConnectConfig yet. Please use the client-level httpOptions configuration instead.");const l=this.apiClient.getWebsocketBaseUrl(),u=this.apiClient.getApiVersion();let c;const d=this.apiClient.getHeaders();t.config&&t.config.tools&&TA(t.config.tools)&&PA(d);const p=tk(d);if(this.apiClient.isVertexAI()){const L=this.apiClient.getProject(),H=this.apiClient.getLocation(),B=this.apiClient.getApiKey(),F=!!L&&!!H||!!B;this.apiClient.getCustomBaseUrl()&&!F?c=l:(c=`${l}/ws/google.cloud.aiplatform.${u}.LlmBidiService/BidiGenerateContent`,await this.auth.addAuthHeaders(p,c))}else{const L=this.apiClient.getApiKey();let H="BidiGenerateContent",B="key";L?.startsWith("auth_tokens/")&&(console.warn("Warning: Ephemeral token support is experimental and may change in future versions."),u!=="v1alpha"&&console.warn("Warning: The SDK's ephemeral token support is in v1alpha only. Please use const ai = new GoogleGenAI({apiKey: token.name, httpOptions: { apiVersion: 'v1alpha' }}); before session connection."),H="BidiGenerateContentConstrained",B="access_token"),c=`${l}/ws/google.ai.generativelanguage.${u}.GenerativeService.${H}?${B}=${L}`}let g=()=>{};const y=new Promise(L=>{g=L}),_=t.callbacks,b=function(){var L;(L=_?.onopen)===null||L===void 0||L.call(_),g({})},m=this.apiClient,v={onopen:b,onmessage:L=>{QF(m,_.onmessage,L)},onerror:(n=_?.onerror)!==null&&n!==void 0?n:function(L){},onclose:(r=_?.onclose)!==null&&r!==void 0?r:function(L){}},A=this.webSocketFactory.create(c,ek(p),v);A.connect(),await y;let S=Ee(this.apiClient,t.model);if(this.apiClient.isVertexAI()&&S.startsWith("publishers/")){const L=this.apiClient.getProject(),H=this.apiClient.getLocation();L&&H&&(S=`projects/${L}/locations/${H}/`+S)}let P={};this.apiClient.isVertexAI()&&((s=t.config)===null||s===void 0?void 0:s.responseModalities)===void 0&&(t.config===void 0?t.config={responseModalities:[Ii.AUDIO]}:t.config.responseModalities=[Ii.AUDIO]),!((o=t.config)===null||o===void 0)&&o.generationConfig&&console.warn("Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. This will become an error in a future version (not before Q3 2025).");const E=(a=(i=t.config)===null||i===void 0?void 0:i.tools)!==null&&a!==void 0?a:[],w=[];for(const L of E)if(this.isCallableTool(L)){const H=L;w.push(await H.tool())}else w.push(L);w.length>0&&(t.config.tools=w);const I={model:S,config:t.config,callbacks:t.callbacks};return this.apiClient.isVertexAI()?P=hM(this.apiClient,I):P=pM(this.apiClient,I),delete P.config,A.send(JSON.stringify(P)),new CA(A,this.apiClient)}isCallableTool(t){return"callTool"in t&&typeof t.callTool=="function"}}const ZF={turnComplete:!0};class CA{constructor(t,n){this.conn=t,this.apiClient=n}tLiveClientContent(t,n){if(n.turns!==null&&n.turns!==void 0){let r=[];try{r=mt(n.turns),t.isVertexAI()||(r=r.map(s=>Qa(s)))}catch{throw new Error(`Failed to parse client content "turns", type: '${typeof n.turns}'`)}return{clientContent:{turns:r,turnComplete:n.turnComplete}}}return{clientContent:{turnComplete:n.turnComplete}}}tLiveClienttToolResponse(t,n){let r=[];if(n.functionResponses==null)throw new Error("functionResponses is required.");if(Array.isArray(n.functionResponses)?r=n.functionResponses:r=[n.functionResponses],r.length===0)throw new Error("functionResponses is required.");for(const o of r){if(typeof o!="object"||o===null||!("name"in o)||!("response"in o))throw new Error(`Could not parse function response, type '${typeof o}'.`);if(!t.isVertexAI()&&!("id"in o))throw new Error(XF)}return{toolResponse:{functionResponses:r}}}sendClientContent(t){t=Object.assign(Object.assign({},ZF),t);const n=this.tLiveClientContent(this.apiClient,t);this.conn.send(JSON.stringify(n))}sendRealtimeInput(t){let n={};this.apiClient.isVertexAI()?n={realtimeInput:yM(t)}:n={realtimeInput:_M(t)},this.conn.send(JSON.stringify(n))}sendToolResponse(t){if(t.functionResponses==null)throw new Error("Tool response parameters are required.");const n=this.tLiveClienttToolResponse(this.apiClient,t);this.conn.send(JSON.stringify(n))}close(){this.conn.close()}}function ek(e){const t={};return e.forEach((n,r)=>{t[r]=n}),t}function tk(e){const t=new Headers;for(const[n,r]of Object.entries(e))t.append(n,r);return t}const Hy=10;function Jy(e){var t,n,r;if(!((t=e?.automaticFunctionCalling)===null||t===void 0)&&t.disable)return!0;let s=!1;for(const i of(n=e?.tools)!==null&&n!==void 0?n:[])if(qr(i)){s=!0;break}if(!s)return!0;const o=(r=e?.automaticFunctionCalling)===null||r===void 0?void 0:r.maximumRemoteCalls;return o&&(o<0||!Number.isInteger(o))||o==0?(console.warn("Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:",o),!0):!1}function qr(e){return"callTool"in e&&typeof e.callTool=="function"}function nk(e){var t,n,r;return(r=(n=(t=e.config)===null||t===void 0?void 0:t.tools)===null||n===void 0?void 0:n.some(s=>qr(s)))!==null&&r!==void 0?r:!1}function jy(e){var t;const n=[];return!((t=e?.config)===null||t===void 0)&&t.tools&&e.config.tools.forEach((r,s)=>{if(qr(r))return;const o=r;o.functionDeclarations&&o.functionDeclarations.length>0&&n.push(s)}),n}function Wy(e){var t;return!(!((t=e?.automaticFunctionCalling)===null||t===void 0)&&t.ignoreCallHistory)}class RA extends Sn{constructor(t){super(),this.apiClient=t,this.generateContent=async n=>{var r,s,o,i,a;const l=await this.processParamsMaybeAddMcpUsage(n);if(this.maybeMoveToResponseJsonSchem(n),!nk(n)||Jy(n.config))return await this.generateContentInternal(l);const u=jy(n);if(u.length>0){const _=u.map(b=>`tools[${b}]`).join(", ");throw new Error(`Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations is not yet supported. Incompatible tools found at ${_}.`)}let c,d;const p=mt(l.contents),g=(o=(s=(r=l.config)===null||r===void 0?void 0:r.automaticFunctionCalling)===null||s===void 0?void 0:s.maximumRemoteCalls)!==null&&o!==void 0?o:Hy;let y=0;for(;y<g&&(c=await this.generateContentInternal(l),!(!c.functionCalls||c.functionCalls.length===0));){const _=c.candidates[0].content,b=[];for(const m of(a=(i=n.config)===null||i===void 0?void 0:i.tools)!==null&&a!==void 0?a:[])if(qr(m)){const A=await m.callTool(c.functionCalls);b.push(...A)}y++,d={role:"user",parts:b},l.contents=mt(l.contents),l.contents.push(_),l.contents.push(d),Wy(l.config)&&(p.push(_),p.push(d))}return Wy(l.config)&&(c.automaticFunctionCallingHistory=p),c},this.generateContentStream=async n=>{var r,s,o,i,a;if(this.maybeMoveToResponseJsonSchem(n),Jy(n.config)){const d=await this.processParamsMaybeAddMcpUsage(n);return await this.generateContentStreamInternal(d)}const l=jy(n);if(l.length>0){const d=l.map(p=>`tools[${p}]`).join(", ");throw new Error(`Incompatible tools found at ${d}. Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations" is not yet supported.`)}const u=(o=(s=(r=n?.config)===null||r===void 0?void 0:r.toolConfig)===null||s===void 0?void 0:s.functionCallingConfig)===null||o===void 0?void 0:o.streamFunctionCallArguments,c=(a=(i=n?.config)===null||i===void 0?void 0:i.automaticFunctionCalling)===null||a===void 0?void 0:a.disable;if(u&&!c)throw new Error("Running in streaming mode with 'streamFunctionCallArguments' enabled, this feature is not compatible with automatic function calling (AFC). Please set 'config.automaticFunctionCalling.disable' to true to disable AFC or leave 'config.toolConfig.functionCallingConfig.streamFunctionCallArguments' to be undefined or set to false to disable streaming function call arguments feature.");return await this.processAfcStream(n)},this.generateImages=async n=>await this.generateImagesInternal(n).then(r=>{var s;let o;const i=[];if(r?.generatedImages)for(const l of r.generatedImages)l&&l?.safetyAttributes&&((s=l?.safetyAttributes)===null||s===void 0?void 0:s.contentType)==="Positive Prompt"?o=l?.safetyAttributes:i.push(l);let a;return o?a={generatedImages:i,positivePromptSafetyAttributes:o,sdkHttpResponse:r.sdkHttpResponse}:a={generatedImages:i,sdkHttpResponse:r.sdkHttpResponse},a}),this.list=async n=>{var r;const i={config:Object.assign(Object.assign({},{queryBase:!0}),n?.config)};if(this.apiClient.isVertexAI()&&!i.config.queryBase){if(!((r=i.config)===null||r===void 0)&&r.filter)throw new Error("Filtering tuned models list for Vertex AI is not currently supported");i.config.filter="labels.tune-type:*"}return new Dn(zt.PAGED_ITEM_MODELS,a=>this.listInternal(a),await this.listInternal(i),i)},this.editImage=async n=>{const r={model:n.model,prompt:n.prompt,referenceImages:[],config:n.config};return n.referenceImages&&n.referenceImages&&(r.referenceImages=n.referenceImages.map(s=>s.toReferenceImageAPI())),await this.editImageInternal(r)},this.upscaleImage=async n=>{let r={numberOfImages:1,mode:"upscale"};n.config&&(r=Object.assign(Object.assign({},r),n.config));const s={model:n.model,image:n.image,upscaleFactor:n.upscaleFactor,config:r};return await this.upscaleImageInternal(s)},this.generateVideos=async n=>{var r,s,o,i,a,l;if((n.prompt||n.image||n.video)&&n.source)throw new Error("Source and prompt/image/video are mutually exclusive. Please only use source.");return this.apiClient.isVertexAI()||(!((r=n.video)===null||r===void 0)&&r.uri&&(!((s=n.video)===null||s===void 0)&&s.videoBytes)?n.video={uri:n.video.uri,mimeType:n.video.mimeType}:!((i=(o=n.source)===null||o===void 0?void 0:o.video)===null||i===void 0)&&i.uri&&(!((l=(a=n.source)===null||a===void 0?void 0:a.video)===null||l===void 0)&&l.videoBytes)&&(n.source.video={uri:n.source.video.uri,mimeType:n.source.video.mimeType})),await this.generateVideosInternal(n)}}maybeMoveToResponseJsonSchem(t){t.config&&t.config.responseSchema&&(t.config.responseJsonSchema||Object.keys(t.config.responseSchema).includes("$schema")&&(t.config.responseJsonSchema=t.config.responseSchema,delete t.config.responseSchema))}async processParamsMaybeAddMcpUsage(t){var n,r,s;const o=(n=t.config)===null||n===void 0?void 0:n.tools;if(!o)return t;const i=await Promise.all(o.map(async l=>qr(l)?await l.tool():l)),a={model:t.model,contents:t.contents,config:Object.assign(Object.assign({},t.config),{tools:i})};if(a.config.tools=i,t.config&&t.config.tools&&TA(t.config.tools)){const l=(s=(r=t.config.httpOptions)===null||r===void 0?void 0:r.headers)!==null&&s!==void 0?s:{};let u=Object.assign({},l);Object.keys(u).length===0&&(u=this.apiClient.getDefaultHeaders()),PA(u),a.config.httpOptions=Object.assign(Object.assign({},t.config.httpOptions),{headers:u})}return a}async initAfcToolsMap(t){var n,r,s;const o=new Map;for(const i of(r=(n=t.config)===null||n===void 0?void 0:n.tools)!==null&&r!==void 0?r:[])if(qr(i)){const a=i,l=await a.tool();for(const u of(s=l.functionDeclarations)!==null&&s!==void 0?s:[]){if(!u.name)throw new Error("Function declaration name is required.");if(o.has(u.name))throw new Error(`Duplicate tool declaration name: ${u.name}`);o.set(u.name,a)}}return o}async processAfcStream(t){var n,r,s;const o=(s=(r=(n=t.config)===null||n===void 0?void 0:n.automaticFunctionCalling)===null||r===void 0?void 0:r.maximumRemoteCalls)!==null&&s!==void 0?s:Hy;let i=!1,a=0;const l=await this.initAfcToolsMap(t);return(function(u,c,d){return Ft(this,arguments,function*(){for(var p,g,y,_,b,m;a<o;){i&&(a++,i=!1);const P=yield me(u.processParamsMaybeAddMcpUsage(d)),E=yield me(u.generateContentStreamInternal(P)),w=[],I=[];try{for(var v=!0,A=(g=void 0,kt(E)),S;S=yield me(A.next()),p=S.done,!p;v=!0){_=S.value,v=!1;const L=_;if(yield yield me(L),L.candidates&&(!((b=L.candidates[0])===null||b===void 0)&&b.content)){I.push(L.candidates[0].content);for(const H of(m=L.candidates[0].content.parts)!==null&&m!==void 0?m:[])if(a<o&&H.functionCall){if(!H.functionCall.name)throw new Error("Function call name was not returned by the model.");if(c.has(H.functionCall.name)){const B=yield me(c.get(H.functionCall.name).callTool([H.functionCall]));w.push(...B)}else throw new Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${c.keys()}, mising tool: ${H.functionCall.name}`)}}}}catch(L){g={error:L}}finally{try{!v&&!p&&(y=A.return)&&(yield me(y.call(A)))}finally{if(g)throw g.error}}if(w.length>0){i=!0;const L=new Pr;L.candidates=[{content:{role:"user",parts:w}}],yield yield me(L);const H=[];H.push(...I),H.push({role:"user",parts:w});const B=mt(d.contents).concat(H);d.contents=B}else break}})})(this,l,t)}async generateContentInternal(t){var n,r,s,o;let i,a="",l={};if(this.apiClient.isVertexAI()){const u=Uy(this.apiClient,t);return a=ie("{model}:generateContent",u._url),l=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json().then(d=>{const p=d;return p.sdkHttpResponse={headers:c.headers},p})),i.then(c=>{const d=Vy(c),p=new Pr;return Object.assign(p,d),p})}else{const u=Ly(this.apiClient,t);return a=ie("{model}:generateContent",u._url),l=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(s=t.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(o=t.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json().then(d=>{const p=d;return p.sdkHttpResponse={headers:c.headers},p})),i.then(c=>{const d=Gy(c),p=new Pr;return Object.assign(p,d),p})}}async generateContentStreamInternal(t){var n,r,s,o;let i,a="",l={};if(this.apiClient.isVertexAI()){const u=Uy(this.apiClient,t);return a=ie("{model}:streamGenerateContent?alt=sse",u._url),l=u._query,delete u._url,delete u._query,i=this.apiClient.requestStream({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal}),i.then(function(d){return Ft(this,arguments,function*(){var p,g,y,_;try{for(var b=!0,m=kt(d),v;v=yield me(m.next()),p=v.done,!p;b=!0){_=v.value,b=!1;const A=_,S=Vy(yield me(A.json()),t);S.sdkHttpResponse={headers:A.headers};const P=new Pr;Object.assign(P,S),yield yield me(P)}}catch(A){g={error:A}}finally{try{!b&&!p&&(y=m.return)&&(yield me(y.call(m)))}finally{if(g)throw g.error}}})})}else{const u=Ly(this.apiClient,t);return a=ie("{model}:streamGenerateContent?alt=sse",u._url),l=u._query,delete u._url,delete u._query,i=this.apiClient.requestStream({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(s=t.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(o=t.config)===null||o===void 0?void 0:o.abortSignal}),i.then(function(d){return Ft(this,arguments,function*(){var p,g,y,_;try{for(var b=!0,m=kt(d),v;v=yield me(m.next()),p=v.done,!p;b=!0){_=v.value,b=!1;const A=_,S=Gy(yield me(A.json()),t);S.sdkHttpResponse={headers:A.headers};const P=new Pr;Object.assign(P,S),yield yield me(P)}}catch(A){g={error:A}}finally{try{!b&&!p&&(y=m.return)&&(yield me(y.call(m)))}finally{if(g)throw g.error}}})})}}async embedContent(t){var n,r,s,o;let i,a="",l={};if(this.apiClient.isVertexAI()){const u=zM(this.apiClient,t);return a=ie("{model}:predict",u._url),l=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json().then(d=>{const p=d;return p.sdkHttpResponse={headers:c.headers},p})),i.then(c=>{const d=QM(c),p=new rd;return Object.assign(p,d),p})}else{const u=YM(this.apiClient,t);return a=ie("{model}:batchEmbedContents",u._url),l=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(s=t.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(o=t.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json().then(d=>{const p=d;return p.sdkHttpResponse={headers:c.headers},p})),i.then(c=>{const d=XM(c),p=new rd;return Object.assign(p,d),p})}}async generateImagesInternal(t){var n,r,s,o;let i,a="",l={};if(this.apiClient.isVertexAI()){const u=uN(this.apiClient,t);return a=ie("{model}:predict",u._url),l=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json().then(d=>{const p=d;return p.sdkHttpResponse={headers:c.headers},p})),i.then(c=>{const d=dN(c),p=new sd;return Object.assign(p,d),p})}else{const u=lN(this.apiClient,t);return a=ie("{model}:predict",u._url),l=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(s=t.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(o=t.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json().then(d=>{const p=d;return p.sdkHttpResponse={headers:c.headers},p})),i.then(c=>{const d=cN(c),p=new sd;return Object.assign(p,d),p})}}async editImageInternal(t){var n,r;let s,o="",i={};if(this.apiClient.isVertexAI()){const a=jM(this.apiClient,t);return o=ie("{model}:predict",a._url),i=a._query,delete a._url,delete a._query,s=this.apiClient.request({path:o,queryParams:i,body:JSON.stringify(a),httpMethod:"POST",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal}).then(l=>l.json().then(u=>{const c=u;return c.sdkHttpResponse={headers:l.headers},c})),s.then(l=>{const u=WM(l),c=new L0;return Object.assign(c,u),c})}else throw new Error("This method is only supported by the Vertex AI.")}async upscaleImageInternal(t){var n,r;let s,o="",i={};if(this.apiClient.isVertexAI()){const a=uF(this.apiClient,t);return o=ie("{model}:predict",a._url),i=a._query,delete a._url,delete a._query,s=this.apiClient.request({path:o,queryParams:i,body:JSON.stringify(a),httpMethod:"POST",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal}).then(l=>l.json().then(u=>{const c=u;return c.sdkHttpResponse={headers:l.headers},c})),s.then(l=>{const u=cF(l),c=new U0;return Object.assign(c,u),c})}else throw new Error("This method is only supported by the Vertex AI.")}async recontextImage(t){var n,r;let s,o="",i={};if(this.apiClient.isVertexAI()){const a=JN(this.apiClient,t);return o=ie("{model}:predict",a._url),i=a._query,delete a._url,delete a._query,s=this.apiClient.request({path:o,queryParams:i,body:JSON.stringify(a),httpMethod:"POST",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal}).then(l=>l.json()),s.then(l=>{const u=jN(l),c=new G0;return Object.assign(c,u),c})}else throw new Error("This method is only supported by the Vertex AI.")}async segmentImage(t){var n,r;let s,o="",i={};if(this.apiClient.isVertexAI()){const a=XN(this.apiClient,t);return o=ie("{model}:predict",a._url),i=a._query,delete a._url,delete a._query,s=this.apiClient.request({path:o,queryParams:i,body:JSON.stringify(a),httpMethod:"POST",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal}).then(l=>l.json()),s.then(l=>{const u=QN(l),c=new V0;return Object.assign(c,u),c})}else throw new Error("This method is only supported by the Vertex AI.")}async get(t){var n,r,s,o;let i,a="",l={};if(this.apiClient.isVertexAI()){const u=CN(this.apiClient,t);return a=ie("{name}",u._url),l=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json()),i.then(c=>md(c))}else{const u=IN(this.apiClient,t);return a=ie("{name}",u._url),l=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(s=t.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(o=t.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json()),i.then(c=>gd(c))}}async listInternal(t){var n,r,s,o;let i,a="",l={};if(this.apiClient.isVertexAI()){const u=qN(this.apiClient,t);return a=ie("{models_url}",u._url),l=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json().then(d=>{const p=d;return p.sdkHttpResponse={headers:c.headers},p})),i.then(c=>{const d=UN(c),p=new od;return Object.assign(p,d),p})}else{const u=DN(this.apiClient,t);return a=ie("{models_url}",u._url),l=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(s=t.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(o=t.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json().then(d=>{const p=d;return p.sdkHttpResponse={headers:c.headers},p})),i.then(c=>{const d=LN(c),p=new od;return Object.assign(p,d),p})}}async update(t){var n,r,s,o;let i,a="",l={};if(this.apiClient.isVertexAI()){const u=aF(this.apiClient,t);return a=ie("{model}",u._url),l=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"PATCH",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json()),i.then(c=>md(c))}else{const u=iF(this.apiClient,t);return a=ie("{name}",u._url),l=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"PATCH",httpOptions:(s=t.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(o=t.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json()),i.then(c=>gd(c))}}async delete(t){var n,r,s,o;let i,a="",l={};if(this.apiClient.isVertexAI()){const u=VM(this.apiClient,t);return a=ie("{name}",u._url),l=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"DELETE",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json().then(d=>{const p=d;return p.sdkHttpResponse={headers:c.headers},p})),i.then(c=>{const d=HM(c),p=new id;return Object.assign(p,d),p})}else{const u=GM(this.apiClient,t);return a=ie("{name}",u._url),l=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"DELETE",httpOptions:(s=t.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(o=t.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json().then(d=>{const p=d;return p.sdkHttpResponse={headers:c.headers},p})),i.then(c=>{const d=BM(c),p=new id;return Object.assign(p,d),p})}}async countTokens(t){var n,r,s,o;let i,a="",l={};if(this.apiClient.isVertexAI()){const u=qM(this.apiClient,t);return a=ie("{model}:countTokens",u._url),l=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json().then(d=>{const p=d;return p.sdkHttpResponse={headers:c.headers},p})),i.then(c=>{const d=UM(c),p=new ad;return Object.assign(p,d),p})}else{const u=DM(this.apiClient,t);return a=ie("{model}:countTokens",u._url),l=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(s=t.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(o=t.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json().then(d=>{const p=d;return p.sdkHttpResponse={headers:c.headers},p})),i.then(c=>{const d=LM(c),p=new ad;return Object.assign(p,d),p})}}async computeTokens(t){var n,r;let s,o="",i={};if(this.apiClient.isVertexAI()){const a=RM(this.apiClient,t);return o=ie("{model}:computeTokens",a._url),i=a._query,delete a._url,delete a._query,s=this.apiClient.request({path:o,queryParams:i,body:JSON.stringify(a),httpMethod:"POST",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal}).then(l=>l.json().then(u=>{const c=u;return c.sdkHttpResponse={headers:l.headers},c})),s.then(l=>{const u=MM(l),c=new B0;return Object.assign(c,u),c})}else throw new Error("This method is only supported by the Vertex AI.")}async generateVideosInternal(t){var n,r,s,o;let i,a="",l={};if(this.apiClient.isVertexAI()){const u=_N(this.apiClient,t);return a=ie("{model}:predictLongRunning",u._url),l=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json()),i.then(c=>{const d=gN(c),p=new Ci;return Object.assign(p,d),p})}else{const u=mN(this.apiClient,t);return a=ie("{model}:predictLongRunning",u._url),l=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(s=t.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(o=t.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json()),i.then(c=>{const d=hN(c),p=new Ci;return Object.assign(p,d),p})}}}class MA extends Sn{constructor(t){super(),this.apiClient=t}async getVideosOperation(t){const n=t.operation,r=t.config;if(n.name===void 0||n.name==="")throw new Error("Operation name is required.");if(this.apiClient.isVertexAI()){const s=n.name.split("/operations/")[0];let o;r&&"httpOptions"in r&&(o=r.httpOptions);const i=await this.fetchPredictVideosOperationInternal({operationName:n.name,resourceName:s,config:{httpOptions:o}});return n._fromAPIResponse({apiResponse:i,_isVertexAI:!0})}else{const s=await this.getVideosOperationInternal({operationName:n.name,config:r});return n._fromAPIResponse({apiResponse:s,_isVertexAI:!1})}}async get(t){const n=t.operation,r=t.config;if(n.name===void 0||n.name==="")throw new Error("Operation name is required.");if(this.apiClient.isVertexAI()){const s=n.name.split("/operations/")[0];let o;r&&"httpOptions"in r&&(o=r.httpOptions);const i=await this.fetchPredictVideosOperationInternal({operationName:n.name,resourceName:s,config:{httpOptions:o}});return n._fromAPIResponse({apiResponse:i,_isVertexAI:!0})}else{const s=await this.getVideosOperationInternal({operationName:n.name,config:r});return n._fromAPIResponse({apiResponse:s,_isVertexAI:!1})}}async getVideosOperationInternal(t){var n,r,s,o;let i,a="",l={};if(this.apiClient.isVertexAI()){const u=FI(t);return a=ie("{operationName}",u._url),l=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json()),i}else{const u=NI(t);return a=ie("{operationName}",u._url),l=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(s=t.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(o=t.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json()),i}}async fetchPredictVideosOperationInternal(t){var n,r;let s,o="",i={};if(this.apiClient.isVertexAI()){const a=EI(t);return o=ie("{resourceName}:fetchPredictOperation",a._url),i=a._query,delete a._url,delete a._query,s=this.apiClient.request({path:o,queryParams:i,body:JSON.stringify(a),httpMethod:"POST",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal}).then(l=>l.json()),s}else throw new Error("This method is only supported by the Vertex AI.")}}function rk(e){const t={},n=f(e,["data"]);if(n!=null&&h(t,["data"],n),f(e,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");const r=f(e,["mimeType"]);return r!=null&&h(t,["mimeType"],r),t}function sk(e){const t={},n=f(e,["parts"]);if(n!=null){let s=n;Array.isArray(s)&&(s=s.map(o=>pk(o))),h(t,["parts"],s)}const r=f(e,["role"]);return r!=null&&h(t,["role"],r),t}function ok(e,t,n){const r={},s=f(t,["expireTime"]);n!==void 0&&s!=null&&h(n,["expireTime"],s);const o=f(t,["newSessionExpireTime"]);n!==void 0&&o!=null&&h(n,["newSessionExpireTime"],o);const i=f(t,["uses"]);n!==void 0&&i!=null&&h(n,["uses"],i);const a=f(t,["liveConnectConstraints"]);n!==void 0&&a!=null&&h(n,["bidiGenerateContentSetup"],fk(e,a));const l=f(t,["lockAdditionalFields"]);return n!==void 0&&l!=null&&h(n,["fieldMask"],l),r}function ik(e,t){const n={},r=f(t,["config"]);return r!=null&&h(n,["config"],ok(e,r,n)),n}function ak(e){const t={};if(f(e,["displayName"])!==void 0)throw new Error("displayName parameter is not supported in Gemini API.");const n=f(e,["fileUri"]);n!=null&&h(t,["fileUri"],n);const r=f(e,["mimeType"]);return r!=null&&h(t,["mimeType"],r),t}function lk(e){const t={},n=f(e,["id"]);n!=null&&h(t,["id"],n);const r=f(e,["args"]);r!=null&&h(t,["args"],r);const s=f(e,["name"]);if(s!=null&&h(t,["name"],s),f(e,["partialArgs"])!==void 0)throw new Error("partialArgs parameter is not supported in Gemini API.");if(f(e,["willContinue"])!==void 0)throw new Error("willContinue parameter is not supported in Gemini API.");return t}function uk(e){const t={};if(f(e,["authConfig"])!==void 0)throw new Error("authConfig parameter is not supported in Gemini API.");const n=f(e,["enableWidget"]);return n!=null&&h(t,["enableWidget"],n),t}function ck(e){const t={};if(f(e,["excludeDomains"])!==void 0)throw new Error("excludeDomains parameter is not supported in Gemini API.");if(f(e,["blockingConfidence"])!==void 0)throw new Error("blockingConfidence parameter is not supported in Gemini API.");const n=f(e,["timeRangeFilter"]);return n!=null&&h(t,["timeRangeFilter"],n),t}function dk(e,t){const n={},r=f(e,["generationConfig"]);t!==void 0&&r!=null&&h(t,["setup","generationConfig"],r);const s=f(e,["responseModalities"]);t!==void 0&&s!=null&&h(t,["setup","generationConfig","responseModalities"],s);const o=f(e,["temperature"]);t!==void 0&&o!=null&&h(t,["setup","generationConfig","temperature"],o);const i=f(e,["topP"]);t!==void 0&&i!=null&&h(t,["setup","generationConfig","topP"],i);const a=f(e,["topK"]);t!==void 0&&a!=null&&h(t,["setup","generationConfig","topK"],a);const l=f(e,["maxOutputTokens"]);t!==void 0&&l!=null&&h(t,["setup","generationConfig","maxOutputTokens"],l);const u=f(e,["mediaResolution"]);t!==void 0&&u!=null&&h(t,["setup","generationConfig","mediaResolution"],u);const c=f(e,["seed"]);t!==void 0&&c!=null&&h(t,["setup","generationConfig","seed"],c);const d=f(e,["speechConfig"]);t!==void 0&&d!=null&&h(t,["setup","generationConfig","speechConfig"],tf(d));const p=f(e,["thinkingConfig"]);t!==void 0&&p!=null&&h(t,["setup","generationConfig","thinkingConfig"],p);const g=f(e,["enableAffectiveDialog"]);t!==void 0&&g!=null&&h(t,["setup","generationConfig","enableAffectiveDialog"],g);const y=f(e,["systemInstruction"]);t!==void 0&&y!=null&&h(t,["setup","systemInstruction"],sk(Qe(y)));const _=f(e,["tools"]);if(t!==void 0&&_!=null){let E=jr(_);Array.isArray(E)&&(E=E.map(w=>gk(Jr(w)))),h(t,["setup","tools"],E)}const b=f(e,["sessionResumption"]);t!==void 0&&b!=null&&h(t,["setup","sessionResumption"],hk(b));const m=f(e,["inputAudioTranscription"]);t!==void 0&&m!=null&&h(t,["setup","inputAudioTranscription"],m);const v=f(e,["outputAudioTranscription"]);t!==void 0&&v!=null&&h(t,["setup","outputAudioTranscription"],v);const A=f(e,["realtimeInputConfig"]);t!==void 0&&A!=null&&h(t,["setup","realtimeInputConfig"],A);const S=f(e,["contextWindowCompression"]);t!==void 0&&S!=null&&h(t,["setup","contextWindowCompression"],S);const P=f(e,["proactivity"]);if(t!==void 0&&P!=null&&h(t,["setup","proactivity"],P),f(e,["explicitVadSignal"])!==void 0)throw new Error("explicitVadSignal parameter is not supported in Gemini API.");return n}function fk(e,t){const n={},r=f(t,["model"]);r!=null&&h(n,["setup","model"],Ee(e,r));const s=f(t,["config"]);return s!=null&&h(n,["config"],dk(s,n)),n}function pk(e){const t={},n=f(e,["mediaResolution"]);n!=null&&h(t,["mediaResolution"],n);const r=f(e,["codeExecutionResult"]);r!=null&&h(t,["codeExecutionResult"],r);const s=f(e,["executableCode"]);s!=null&&h(t,["executableCode"],s);const o=f(e,["fileData"]);o!=null&&h(t,["fileData"],ak(o));const i=f(e,["functionCall"]);i!=null&&h(t,["functionCall"],lk(i));const a=f(e,["functionResponse"]);a!=null&&h(t,["functionResponse"],a);const l=f(e,["inlineData"]);l!=null&&h(t,["inlineData"],rk(l));const u=f(e,["text"]);u!=null&&h(t,["text"],u);const c=f(e,["thought"]);c!=null&&h(t,["thought"],c);const d=f(e,["thoughtSignature"]);d!=null&&h(t,["thoughtSignature"],d);const p=f(e,["videoMetadata"]);return p!=null&&h(t,["videoMetadata"],p),t}function hk(e){const t={},n=f(e,["handle"]);if(n!=null&&h(t,["handle"],n),f(e,["transparent"])!==void 0)throw new Error("transparent parameter is not supported in Gemini API.");return t}function gk(e){const t={};if(f(e,["retrieval"])!==void 0)throw new Error("retrieval parameter is not supported in Gemini API.");const n=f(e,["computerUse"]);n!=null&&h(t,["computerUse"],n);const r=f(e,["fileSearch"]);r!=null&&h(t,["fileSearch"],r);const s=f(e,["codeExecution"]);if(s!=null&&h(t,["codeExecution"],s),f(e,["enterpriseWebSearch"])!==void 0)throw new Error("enterpriseWebSearch parameter is not supported in Gemini API.");const o=f(e,["functionDeclarations"]);if(o!=null){let c=o;Array.isArray(c)&&(c=c.map(d=>d)),h(t,["functionDeclarations"],c)}const i=f(e,["googleMaps"]);i!=null&&h(t,["googleMaps"],uk(i));const a=f(e,["googleSearch"]);a!=null&&h(t,["googleSearch"],ck(a));const l=f(e,["googleSearchRetrieval"]);l!=null&&h(t,["googleSearchRetrieval"],l);const u=f(e,["urlContext"]);return u!=null&&h(t,["urlContext"],u),t}function mk(e){const t=[];for(const n in e)if(Object.prototype.hasOwnProperty.call(e,n)){const r=e[n];if(typeof r=="object"&&r!=null&&Object.keys(r).length>0){const s=Object.keys(r).map(o=>`${n}.${o}`);t.push(...s)}else t.push(n)}return t.join(",")}function _k(e,t){let n=null;const r=e.bidiGenerateContentSetup;if(typeof r=="object"&&r!==null&&"setup"in r){const o=r.setup;typeof o=="object"&&o!==null?(e.bidiGenerateContentSetup=o,n=o):delete e.bidiGenerateContentSetup}else r!==void 0&&delete e.bidiGenerateContentSetup;const s=e.fieldMask;if(n){const o=mk(n);if(Array.isArray(t?.lockAdditionalFields)&&t?.lockAdditionalFields.length===0)o?e.fieldMask=o:delete e.fieldMask;else if(t?.lockAdditionalFields&&t.lockAdditionalFields.length>0&&s!==null&&Array.isArray(s)&&s.length>0){const i=["temperature","topK","topP","maxOutputTokens","responseModalities","seed","speechConfig"];let a=[];s.length>0&&(a=s.map(u=>i.includes(u)?`generationConfig.${u}`:u));const l=[];o&&l.push(o),a.length>0&&l.push(...a),l.length>0?e.fieldMask=l.join(","):delete e.fieldMask}else delete e.fieldMask}else s!==null&&Array.isArray(s)&&s.length>0?e.fieldMask=s.join(","):delete e.fieldMask;return e}class NA extends Sn{constructor(t){super(),this.apiClient=t}async create(t){var n,r;let s,o="",i={};if(this.apiClient.isVertexAI())throw new Error("The client.tokens.create method is only supported by the Gemini Developer API.");{const a=ik(this.apiClient,t);o=ie("auth_tokens",a._url),i=a._query,delete a.config,delete a._url,delete a._query;const l=_k(a,t.config);return s=this.apiClient.request({path:o,queryParams:i,body:JSON.stringify(l),httpMethod:"POST",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal}).then(u=>u.json()),s.then(u=>u)}}}function yk(e,t){const n={},r=f(e,["force"]);return t!==void 0&&r!=null&&h(t,["_query","force"],r),n}function vk(e){const t={},n=f(e,["name"]);n!=null&&h(t,["_url","name"],n);const r=f(e,["config"]);return r!=null&&yk(r,t),t}function bk(e){const t={},n=f(e,["name"]);return n!=null&&h(t,["_url","name"],n),t}function Ak(e,t){const n={},r=f(e,["pageSize"]);t!==void 0&&r!=null&&h(t,["_query","pageSize"],r);const s=f(e,["pageToken"]);return t!==void 0&&s!=null&&h(t,["_query","pageToken"],s),n}function Sk(e){const t={},n=f(e,["parent"]);n!=null&&h(t,["_url","parent"],n);const r=f(e,["config"]);return r!=null&&Ak(r,t),t}function wk(e){const t={},n=f(e,["sdkHttpResponse"]);n!=null&&h(t,["sdkHttpResponse"],n);const r=f(e,["nextPageToken"]);r!=null&&h(t,["nextPageToken"],r);const s=f(e,["documents"]);if(s!=null){let o=s;Array.isArray(o)&&(o=o.map(i=>i)),h(t,["documents"],o)}return t}class Ek extends Sn{constructor(t){super(),this.apiClient=t,this.list=async n=>new Dn(zt.PAGED_ITEM_DOCUMENTS,r=>this.listInternal({parent:n.parent,config:r.config}),await this.listInternal(n),n)}async get(t){var n,r;let s,o="",i={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const a=bk(t);return o=ie("{name}",a._url),i=a._query,delete a._url,delete a._query,s=this.apiClient.request({path:o,queryParams:i,body:JSON.stringify(a),httpMethod:"GET",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal}).then(l=>l.json()),s.then(l=>l)}}async delete(t){var n,r;let s="",o={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const i=vk(t);s=ie("{name}",i._url),o=i._query,delete i._url,delete i._query,await this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(i),httpMethod:"DELETE",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal})}}async listInternal(t){var n,r;let s,o="",i={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const a=Sk(t);return o=ie("{parent}/documents",a._url),i=a._query,delete a._url,delete a._query,s=this.apiClient.request({path:o,queryParams:i,body:JSON.stringify(a),httpMethod:"GET",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal}).then(l=>l.json()),s.then(l=>{const u=wk(l),c=new H0;return Object.assign(c,u),c})}}}class Tk extends Sn{constructor(t,n=new Ek(t)){super(),this.apiClient=t,this.documents=n,this.list=async(r={})=>new Dn(zt.PAGED_ITEM_FILE_SEARCH_STORES,s=>this.listInternal(s),await this.listInternal(r),r)}async uploadToFileSearchStore(t){if(this.apiClient.isVertexAI())throw new Error("Vertex AI does not support uploading files to a file search store.");return this.apiClient.uploadFileToFileSearchStore(t.fileSearchStoreName,t.file,t.config)}async create(t){var n,r;let s,o="",i={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const a=_F(t);return o=ie("fileSearchStores",a._url),i=a._query,delete a._url,delete a._query,s=this.apiClient.request({path:o,queryParams:i,body:JSON.stringify(a),httpMethod:"POST",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal}).then(l=>l.json()),s.then(l=>l)}}async get(t){var n,r;let s,o="",i={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const a=bF(t);return o=ie("{name}",a._url),i=a._query,delete a._url,delete a._query,s=this.apiClient.request({path:o,queryParams:i,body:JSON.stringify(a),httpMethod:"GET",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal}).then(l=>l.json()),s.then(l=>l)}}async delete(t){var n,r;let s="",o={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const i=vF(t);s=ie("{name}",i._url),o=i._query,delete i._url,delete i._query,await this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(i),httpMethod:"DELETE",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal})}}async listInternal(t){var n,r;let s,o="",i={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const a=PF(t);return o=ie("fileSearchStores",a._url),i=a._query,delete a._url,delete a._query,s=this.apiClient.request({path:o,queryParams:i,body:JSON.stringify(a),httpMethod:"GET",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal}).then(l=>l.json()),s.then(l=>{const u=IF(l),c=new J0;return Object.assign(c,u),c})}}async uploadToFileSearchStoreInternal(t){var n,r;let s,o="",i={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const a=CF(t);return o=ie("upload/v1beta/{file_search_store_name}:uploadToFileSearchStore",a._url),i=a._query,delete a._url,delete a._query,s=this.apiClient.request({path:o,queryParams:i,body:JSON.stringify(a),httpMethod:"POST",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal}).then(l=>l.json()),s.then(l=>{const u=RF(l),c=new j0;return Object.assign(c,u),c})}}async importFile(t){var n,r;let s,o="",i={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const a=wF(t);return o=ie("{file_search_store_name}:importFile",a._url),i=a._query,delete a._url,delete a._query,s=this.apiClient.request({path:o,queryParams:i,body:JSON.stringify(a),httpMethod:"POST",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal}).then(l=>l.json()),s.then(l=>{const u=SF(l),c=new za;return Object.assign(c,u),c})}}}let FA=function(){const{crypto:e}=globalThis;if(e?.randomUUID)return FA=e.randomUUID.bind(e),e.randomUUID();const t=new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^n()&15>>+r/4).toString(16))};const Pk=()=>FA();function yd(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}const vd=e=>{if(e instanceof Error)return e;if(typeof e=="object"&&e!==null){try{if(Object.prototype.toString.call(e)==="[object Error]"){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 yt extends Error{}class ot extends yt{constructor(t,n,r,s){super(`${ot.makeMessage(t,n,r)}`),this.status=t,this.headers=s,this.error=n}static makeMessage(t,n,r){const s=n?.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):r;return t&&s?`${t} ${s}`:t?`${t} status code (no body)`:s||"(no status code or body)"}static generate(t,n,r,s){if(!t||!s)return new tl({message:r,cause:vd(n)});const o=n;return t===400?new OA(t,o,r,s):t===401?new xA(t,o,r,s):t===403?new DA(t,o,r,s):t===404?new qA(t,o,r,s):t===409?new LA(t,o,r,s):t===422?new UA(t,o,r,s):t===429?new GA(t,o,r,s):t>=500?new VA(t,o,r,s):new ot(t,o,r,s)}}class bd extends ot{constructor({message:t}={}){super(void 0,void 0,t||"Request was aborted.",void 0)}}class tl extends ot{constructor({message:t,cause:n}){super(void 0,void 0,t||"Connection error.",void 0),n&&(this.cause=n)}}class kA extends tl{constructor({message:t}={}){super({message:t??"Request timed out."})}}class OA extends ot{}class xA extends ot{}class DA extends ot{}class qA extends ot{}class LA extends ot{}class UA extends ot{}class GA extends ot{}class VA extends ot{}const Ik=/^[a-z][a-z0-9+.-]*:/i,Ck=e=>Ik.test(e);let Ad=e=>(Ad=Array.isArray,Ad(e));const Rk=Ad;let Mk=Rk;const Ky=Mk;function Nk(e){if(!e)return!0;for(const t in e)return!1;return!0}function Fk(e,t){return Object.prototype.hasOwnProperty.call(e,t)}const kk=(e,t)=>{if(typeof t!="number"||!Number.isInteger(t))throw new yt(`${e} must be an integer`);if(t<0)throw new yt(`${e} must be a positive integer`);return t},Ok=e=>{try{return JSON.parse(e)}catch{return}};const xk=e=>new Promise(t=>setTimeout(t,e));const Ir="0.0.1";function Dk(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}const qk=()=>{var e,t,n,r,s;const o=Dk();if(o==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ir,"X-Stainless-OS":Yy(Deno.build.os),"X-Stainless-Arch":$y(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:(t=(e=Deno.version)===null||e===void 0?void 0:e.deno)!==null&&t!==void 0?t:"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ir,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(o==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ir,"X-Stainless-OS":Yy((n=globalThis.process.platform)!==null&&n!==void 0?n:"unknown"),"X-Stainless-Arch":$y((r=globalThis.process.arch)!==null&&r!==void 0?r:"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":(s=globalThis.process.version)!==null&&s!==void 0?s:"unknown"};const i=Lk();return i?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ir,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${i.browser}`,"X-Stainless-Runtime-Version":i.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ir,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Lk(){if(typeof navigator>"u"||!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 r=n.exec(navigator.userAgent);if(r){const s=r[1]||0,o=r[2]||0,i=r[3]||0;return{browser:t,version:`${s}.${o}.${i}`}}}return null}const $y=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",Yy=e=>(e=e.toLowerCase(),e.includes("ios")?"iOS":e==="android"?"Android":e==="darwin"?"MacOS":e==="win32"?"Windows":e==="freebsd"?"FreeBSD":e==="openbsd"?"OpenBSD":e==="linux"?"Linux":e?`Other:${e}`:"Unknown");let zi;const Uk=()=>zi??(zi=qk());function Gk(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new GeminiNextGenAPIClient({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function BA(...e){const t=globalThis.ReadableStream;if(typeof t>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function Vk(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return BA({start(){},async pull(n){const{done:r,value:s}=await t.next();r?n.close():n.enqueue(s)},async cancel(){var n;await((n=t.return)===null||n===void 0?void 0:n.call(t))}})}function HA(e){if(e[Symbol.asyncIterator])return e;const t=e.getReader();return{async next(){try{const n=await t.read();return n?.done&&t.releaseLock(),n}catch(n){throw t.releaseLock(),n}},async return(){const n=t.cancel();return t.releaseLock(),await n,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Bk(e){var t,n;if(e===null||typeof e!="object")return;if(e[Symbol.asyncIterator]){await((n=(t=e[Symbol.asyncIterator]()).return)===null||n===void 0?void 0:n.call(t));return}const r=e.getReader(),s=r.cancel();r.releaseLock(),await s}const Hk=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)});const JA=()=>{var e;if(typeof File>"u"){const{process:t}=globalThis,n=typeof((e=t?.versions)===null||e===void 0?void 0:e.node)=="string"&&parseInt(t.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(n?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Ou(e,t,n){return JA(),new File(e,t??"unknown_file",n)}function Jk(e){return(typeof e=="object"&&e!==null&&("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 jk=e=>e!=null&&typeof e=="object"&&typeof e[Symbol.asyncIterator]=="function";const jA=e=>e!=null&&typeof e=="object"&&typeof e.size=="number"&&typeof e.type=="string"&&typeof e.text=="function"&&typeof e.slice=="function"&&typeof e.arrayBuffer=="function",Wk=e=>e!=null&&typeof e=="object"&&typeof e.name=="string"&&typeof e.lastModified=="number"&&jA(e),Kk=e=>e!=null&&typeof e=="object"&&typeof e.url=="string"&&typeof e.blob=="function";async function $k(e,t,n){if(JA(),e=await e,Wk(e))return e instanceof File?e:Ou([await e.arrayBuffer()],e.name);if(Kk(e)){const s=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),Ou(await Sd(s),t,n)}const r=await Sd(e);if(t||(t=Jk(e)),!n?.type){const s=r.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof s=="string"&&(n=Object.assign(Object.assign({},n),{type:s}))}return Ou(r,t,n)}async function Sd(e){var t,n,r,s,o;let i=[];if(typeof e=="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)i.push(e);else if(jA(e))i.push(e instanceof Blob?e:await e.arrayBuffer());else if(jk(e))try{for(var a=!0,l=kt(e),u;u=await l.next(),t=u.done,!t;a=!0){s=u.value,a=!1;const c=s;i.push(...await Sd(c))}}catch(c){n={error:c}}finally{try{!a&&!t&&(r=l.return)&&await r.call(l)}finally{if(n)throw n.error}}else{const c=(o=e?.constructor)===null||o===void 0?void 0:o.name;throw new Error(`Unexpected data type: ${typeof e}${c?`; constructor: ${c}`:""}${Yk(e)}`)}return i}function Yk(e){return typeof e!="object"||e===null?"":`; props: [${Object.getOwnPropertyNames(e).map(n=>`"${n}"`).join(", ")}]`}class WA{constructor(t){this._client=t}}WA._key=[];function KA(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const zy=Object.freeze(Object.create(null)),zk=(e=KA)=>(function(n,...r){if(n.length===1)return n[0];let s=!1;const o=[],i=n.reduce((c,d,p)=>{var g,y,_;/[?#]/.test(d)&&(s=!0);const b=r[p];let m=(s?encodeURIComponent:e)(""+b);return p!==r.length&&(b==null||typeof b=="object"&&b.toString===((_=Object.getPrototypeOf((y=Object.getPrototypeOf((g=b.hasOwnProperty)!==null&&g!==void 0?g:zy))!==null&&y!==void 0?y:zy))===null||_===void 0?void 0:_.toString))&&(m=b+"",o.push({start:c.length+d.length,length:m.length,error:`Value of type ${Object.prototype.toString.call(b).slice(8,-1)} is not a valid path parameter`})),c+d+(p===r.length?"":m)},""),a=i.split(/[?#]/,1)[0],l=new RegExp("(?<=^|\\/)(?:\\.|%2e){1,2}(?=\\/|$)","gi");let u;for(;(u=l.exec(a))!==null;)o.push({start:u.index,length:u[0].length,error:`Value "${u[0]}" can't be safely passed as a path parameter`});if(o.sort((c,d)=>c.start-d.start),o.length>0){let c=0;const d=o.reduce((p,g)=>{const y=" ".repeat(g.start-c),_="^".repeat(g.length);return c=g.start+g.length,p+y+_},"");throw new yt(`Path parameters result in path with invalid segments:
90
- ${o.map(p=>p.error).join(`
91
- `)}
92
- ${i}
93
- ${d}`)}return i}),Xi=zk(KA);class $A extends WA{create(t,n){var r;const{api_version:s=this._client.apiVersion}=t,o=Ia(t,["api_version"]);if("model"in o&&"agent_config"in o)throw new yt("Invalid request: specified `model` and `agent_config`. If specifying `model`, use `generation_config`.");if("agent"in o&&"generation_config"in o)throw new yt("Invalid request: specified `agent` and `generation_config`. If specifying `agent`, use `agent_config`.");return this._client.post(Xi`/${s}/interactions`,Object.assign(Object.assign({body:o},n),{stream:(r=t.stream)!==null&&r!==void 0?r:!1}))}delete(t,n={},r){const{api_version:s=this._client.apiVersion}=n??{};return this._client.delete(Xi`/${s}/interactions/${t}`,r)}cancel(t,n={},r){const{api_version:s=this._client.apiVersion}=n??{};return this._client.post(Xi`/${s}/interactions/${t}/cancel`,r)}get(t,n={},r){var s;const o=n??{},{api_version:i=this._client.apiVersion}=o,a=Ia(o,["api_version"]);return this._client.get(Xi`/${i}/interactions/${t}`,Object.assign(Object.assign({query:a},r),{stream:(s=n?.stream)!==null&&s!==void 0?s:!1}))}}$A._key=Object.freeze(["interactions"]);class YA extends $A{}function Xk(e){let t=0;for(const s of e)t+=s.length;const n=new Uint8Array(t);let r=0;for(const s of e)n.set(s,r),r+=s.length;return n}let Qi;function nf(e){let t;return(Qi??(t=new globalThis.TextEncoder,Qi=t.encode.bind(t)))(e)}let Zi;function Xy(e){let t;return(Zi??(t=new globalThis.TextDecoder,Zi=t.decode.bind(t)))(e)}class nl{constructor(){this.buffer=new Uint8Array,this.carriageReturnIndex=null}decode(t){if(t==null)return[];const n=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?nf(t):t;this.buffer=Xk([this.buffer,n]);const r=[];let s;for(;(s=Qk(this.buffer,this.carriageReturnIndex))!=null;){if(s.carriage&&this.carriageReturnIndex==null){this.carriageReturnIndex=s.index;continue}if(this.carriageReturnIndex!=null&&(s.index!==this.carriageReturnIndex+1||s.carriage)){r.push(Xy(this.buffer.subarray(0,this.carriageReturnIndex-1))),this.buffer=this.buffer.subarray(this.carriageReturnIndex),this.carriageReturnIndex=null;continue}const o=this.carriageReturnIndex!==null?s.preceding-1:s.preceding,i=Xy(this.buffer.subarray(0,o));r.push(i),this.buffer=this.buffer.subarray(s.index),this.carriageReturnIndex=null}return r}flush(){return this.buffer.length?this.decode(`
94
- `):[]}}nl.NEWLINE_CHARS=new Set([`
95
- `,"\r"]);nl.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Qk(e,t){for(let s=t??0;s<e.length;s++){if(e[s]===10)return{preceding:s,index:s+1,carriage:!1};if(e[s]===13)return{preceding:s,index:s+1,carriage:!0}}return null}function Zk(e){for(let r=0;r<e.length-1;r++){if(e[r]===10&&e[r+1]===10||e[r]===13&&e[r+1]===13)return r+2;if(e[r]===13&&e[r+1]===10&&r+3<e.length&&e[r+2]===13&&e[r+3]===10)return r+4}return-1}const Ca={off:0,error:200,warn:300,info:400,debug:500},Qy=(e,t,n)=>{if(e){if(Fk(Ca,e))return e;nt(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(Ca))}`)}};function di(){}function ea(e,t,n){return!t||Ca[e]>Ca[n]?di:t[e].bind(t)}const eO={error:di,warn:di,info:di,debug:di};let Zy=new WeakMap;function nt(e){var t;const n=e.logger,r=(t=e.logLevel)!==null&&t!==void 0?t:"off";if(!n)return eO;const s=Zy.get(n);if(s&&s[0]===r)return s[1];const o={error:ea("error",n,r),warn:ea("warn",n,r),info:ea("info",n,r),debug:ea("debug",n,r)};return Zy.set(n,[r,o]),o}const or=e=>(e.options&&(e.options=Object.assign({},e.options),delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([t,n])=>[t,t.toLowerCase()==="x-goog-api-key"||t.toLowerCase()==="authorization"||t.toLowerCase()==="cookie"||t.toLowerCase()==="set-cookie"?"***":n]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);class Rr{constructor(t,n,r){this.iterator=t,this.controller=n,this.client=r}static fromSSEResponse(t,n,r){let s=!1;const o=r?nt(r):console;function i(){return Ft(this,arguments,function*(){var l,u,c,d;if(s)throw new yt("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let p=!1;try{try{for(var g=!0,y=kt(tO(t,n)),_;_=yield me(y.next()),l=_.done,!l;g=!0){d=_.value,g=!1;const b=d;if(!p)if(b.data.startsWith("[DONE]")){p=!0;continue}else try{yield yield me(JSON.parse(b.data))}catch(m){throw o.error("Could not parse message into JSON:",b.data),o.error("From chunk:",b.raw),m}}}catch(b){u={error:b}}finally{try{!g&&!l&&(c=y.return)&&(yield me(c.call(y)))}finally{if(u)throw u.error}}p=!0}catch(b){if(yd(b))return yield me(void 0);throw b}finally{p||n.abort()}})}return new Rr(i,n,r)}static fromReadableStream(t,n,r){let s=!1;function o(){return Ft(this,arguments,function*(){var l,u,c,d;const p=new nl,g=HA(t);try{for(var y=!0,_=kt(g),b;b=yield me(_.next()),l=b.done,!l;y=!0){d=b.value,y=!1;const m=d;for(const v of p.decode(m))yield yield me(v)}}catch(m){u={error:m}}finally{try{!y&&!l&&(c=_.return)&&(yield me(c.call(_)))}finally{if(u)throw u.error}}for(const m of p.flush())yield yield me(m)})}function i(){return Ft(this,arguments,function*(){var l,u,c,d;if(s)throw new yt("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let p=!1;try{try{for(var g=!0,y=kt(o()),_;_=yield me(y.next()),l=_.done,!l;g=!0){d=_.value,g=!1;const b=d;p||b&&(yield yield me(JSON.parse(b)))}}catch(b){u={error:b}}finally{try{!g&&!l&&(c=y.return)&&(yield me(c.call(y)))}finally{if(u)throw u.error}}p=!0}catch(b){if(yd(b))return yield me(void 0);throw b}finally{p||n.abort()}})}return new Rr(i,n,r)}[Symbol.asyncIterator](){return this.iterator()}tee(){const t=[],n=[],r=this.iterator(),s=o=>({next:()=>{if(o.length===0){const i=r.next();t.push(i),n.push(i)}return o.shift()}});return[new Rr(()=>s(t),this.controller,this.client),new Rr(()=>s(n),this.controller,this.client)]}toReadableStream(){const t=this;let n;return BA({async start(){n=t[Symbol.asyncIterator]()},async pull(r){try{const{value:s,done:o}=await n.next();if(o)return r.close();const i=nf(JSON.stringify(s)+`
96
- `);r.enqueue(i)}catch(s){r.error(s)}},async cancel(){var r;await((r=n.return)===null||r===void 0?void 0:r.call(n))}})}}function tO(e,t){return Ft(this,arguments,function*(){var r,s,o,i;if(!e.body)throw t.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new yt("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new yt("Attempted to iterate over a response with no body");const a=new rO,l=new nl,u=HA(e.body);try{for(var c=!0,d=kt(nO(u)),p;p=yield me(d.next()),r=p.done,!r;c=!0){i=p.value,c=!1;const g=i;for(const y of l.decode(g)){const _=a.decode(y);_&&(yield yield me(_))}}}catch(g){s={error:g}}finally{try{!c&&!r&&(o=d.return)&&(yield me(o.call(d)))}finally{if(s)throw s.error}}for(const g of l.flush()){const y=a.decode(g);y&&(yield yield me(y))}})}function nO(e){return Ft(this,arguments,function*(){var n,r,s,o;let i=new Uint8Array;try{for(var a=!0,l=kt(e),u;u=yield me(l.next()),n=u.done,!n;a=!0){o=u.value,a=!1;const c=o;if(c==null)continue;const d=c instanceof ArrayBuffer?new Uint8Array(c):typeof c=="string"?nf(c):c;let p=new Uint8Array(i.length+d.length);p.set(i),p.set(d,i.length),i=p;let g;for(;(g=Zk(i))!==-1;)yield yield me(i.slice(0,g)),i=i.slice(g)}}catch(c){r={error:c}}finally{try{!a&&!n&&(s=l.return)&&(yield me(s.call(l)))}finally{if(r)throw r.error}}i.length>0&&(yield yield me(i))})}class rO{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(t){if(t.endsWith("\r")&&(t=t.substring(0,t.length-1)),!t){if(!this.event&&!this.data.length)return null;const o={event:this.event,data:this.data.join(`
97
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(t),t.startsWith(":"))return null;let[n,r,s]=sO(t,":");return s.startsWith(" ")&&(s=s.substring(1)),n==="event"?this.event=s:n==="data"&&this.data.push(s),null}}function sO(e,t){const n=e.indexOf(t);return n!==-1?[e.substring(0,n),t,e.substring(n+t.length)]:[e,"",""]}async function oO(e,t){const{response:n,requestLogID:r,retryOfRequestLogID:s,startTime:o}=t,i=await(async()=>{var a;if(t.options.stream)return nt(e).debug("response",n.status,n.url,n.headers,n.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(n,t.controller,e):Rr.fromSSEResponse(n,t.controller,e);if(n.status===204)return null;if(t.options.__binaryResponse)return n;const l=n.headers.get("content-type"),u=(a=l?.split(";")[0])===null||a===void 0?void 0:a.trim();return u?.includes("application/json")||u?.endsWith("+json")?n.headers.get("content-length")==="0"?void 0:await n.json():await n.text()})();return nt(e).debug(`[${r}] response parsed`,or({retryOfRequestLogID:s,url:n.url,status:n.status,body:i,durationMs:Date.now()-o})),i}class rf extends Promise{constructor(t,n,r=oO){super(s=>{s(null)}),this.responsePromise=n,this.parseResponse=r,this.client=t}_thenUnwrap(t){return new rf(this.client,this.responsePromise,async(n,r)=>t(await this.parseResponse(n,r),r))}asResponse(){return this.responsePromise.then(t=>t.response)}async withResponse(){const[t,n]=await Promise.all([this.parse(),this.asResponse()]);return{data:t,response:n}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(t=>this.parseResponse(this.client,t))),this.parsedPromise}then(t,n){return this.parse().then(t,n)}catch(t){return this.parse().catch(t)}finally(t){return this.parse().finally(t)}}const zA=Symbol("brand.privateNullableHeaders");function*iO(e){if(!e)return;if(zA in e){const{values:r,nulls:s}=e;yield*r.entries();for(const o of s)yield[o,null];return}let t=!1,n;e instanceof Headers?n=e.entries():Ky(e)?n=e:(t=!0,n=Object.entries(e??{}));for(let r of n){const s=r[0];if(typeof s!="string")throw new TypeError("expected header name to be a string");const o=Ky(r[1])?r[1]:[r[1]];let i=!1;for(const a of o)a!==void 0&&(t&&!i&&(i=!0,yield[s,null]),yield[s,a])}}const li=e=>{const t=new Headers,n=new Set;for(const r of e){const s=new Set;for(const[o,i]of iO(r)){const a=o.toLowerCase();s.has(a)||(t.delete(o),s.add(a)),i===null?(t.delete(o),n.add(a)):(t.append(o,i),n.delete(a))}}return{[zA]:!0,values:t,nulls:n}};const xu=e=>{var t,n,r,s,o,i;if(typeof globalThis.process<"u")return(r=(n=(t=vI)===null||t===void 0?void 0:t[e])===null||n===void 0?void 0:n.trim())!==null&&r!==void 0?r:void 0;if(typeof globalThis.Deno<"u")return(i=(o=(s=globalThis.Deno.env)===null||s===void 0?void 0:s.get)===null||o===void 0?void 0:o.call(s,e))===null||i===void 0?void 0:i.trim()};var XA;class rl{constructor(t){var n,r,s,o,i,a,l,{baseURL:u=xu("GEMINI_NEXT_GEN_API_BASE_URL"),apiKey:c=(n=xu("GEMINI_API_KEY"))!==null&&n!==void 0?n:null,apiVersion:d="v1beta"}=t,p=Ia(t,["baseURL","apiKey","apiVersion"]);const g=Object.assign(Object.assign({apiKey:c,apiVersion:d},p),{baseURL:u||"https://generativelanguage.googleapis.com"});this.baseURL=g.baseURL,this.timeout=(r=g.timeout)!==null&&r!==void 0?r:rl.DEFAULT_TIMEOUT,this.logger=(s=g.logger)!==null&&s!==void 0?s:console;const y="warn";this.logLevel=y,this.logLevel=(i=(o=Qy(g.logLevel,"ClientOptions.logLevel",this))!==null&&o!==void 0?o:Qy(xu("GEMINI_NEXT_GEN_API_LOG"),"process.env['GEMINI_NEXT_GEN_API_LOG']",this))!==null&&i!==void 0?i:y,this.fetchOptions=g.fetchOptions,this.maxRetries=(a=g.maxRetries)!==null&&a!==void 0?a:2,this.fetch=(l=g.fetch)!==null&&l!==void 0?l:Gk(),this.encoder=Hk,this._options=g,this.apiKey=c,this.apiVersion=d,this.clientAdapter=g.clientAdapter}withOptions(t){return new this.constructor(Object.assign(Object.assign(Object.assign({},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,apiVersion:this.apiVersion}),t))}baseURLOverridden(){return this.baseURL!=="https://generativelanguage.googleapis.com"}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:t,nulls:n}){if(!(t.has("authorization")||t.has("x-goog-api-key"))&&!(this.apiKey&&t.get("x-goog-api-key"))&&!n.has("x-goog-api-key"))throw new Error('Could not resolve authentication method. Expected the apiKey to be set. Or for the "x-goog-api-key" headers to be explicitly omitted')}async authHeaders(t){const n=li([t.headers]);if(!(n.values.has("authorization")||n.values.has("x-goog-api-key"))){if(this.apiKey)return li([{"x-goog-api-key":this.apiKey}]);if(this.clientAdapter.isVertexAI())return li([await this.clientAdapter.getAuthHeaders()])}}stringifyQuery(t){return Object.entries(t).filter(([n,r])=>typeof r<"u").map(([n,r])=>{if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return`${encodeURIComponent(n)}=${encodeURIComponent(r)}`;if(r===null)return`${encodeURIComponent(n)}=`;throw new yt(`Cannot stringify type ${typeof r}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${Ir}`}defaultIdempotencyKey(){return`stainless-node-retry-${Pk()}`}makeStatusError(t,n,r,s){return ot.generate(t,n,r,s)}buildURL(t,n,r){const s=!this.baseURLOverridden()&&r||this.baseURL,o=Ck(t)?new URL(t):new URL(s+(s.endsWith("/")&&t.startsWith("/")?t.slice(1):t)),i=this.defaultQuery();return Nk(i)||(n=Object.assign(Object.assign({},i),n)),typeof n=="object"&&n&&!Array.isArray(n)&&(o.search=this.stringifyQuery(n)),o.toString()}async prepareOptions(t){if(this.clientAdapter&&this.clientAdapter.isVertexAI()&&!t.path.startsWith(`/${this.apiVersion}/projects/`)){const n=t.path.slice(this.apiVersion.length+1);t.path=`/${this.apiVersion}/projects/${this.clientAdapter.getProject()}/locations/${this.clientAdapter.getLocation()}${n}`}}async prepareRequest(t,{url:n,options:r}){}get(t,n){return this.methodRequest("get",t,n)}post(t,n){return this.methodRequest("post",t,n)}patch(t,n){return this.methodRequest("patch",t,n)}put(t,n){return this.methodRequest("put",t,n)}delete(t,n){return this.methodRequest("delete",t,n)}methodRequest(t,n,r){return this.request(Promise.resolve(r).then(s=>Object.assign({method:t,path:n},s)))}request(t,n=null){return new rf(this,this.makeRequest(t,n,void 0))}async makeRequest(t,n,r){var s,o,i;const a=await t,l=(s=a.maxRetries)!==null&&s!==void 0?s:this.maxRetries;n==null&&(n=l),await this.prepareOptions(a);const{req:u,url:c,timeout:d}=await this.buildRequest(a,{retryCount:l-n});await this.prepareRequest(u,{url:c,options:a});const p="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),g=r===void 0?"":`, retryOf: ${r}`,y=Date.now();if(nt(this).debug(`[${p}] sending request`,or({retryOfRequestLogID:r,method:a.method,url:c,options:a,headers:u.headers})),!((o=a.signal)===null||o===void 0)&&o.aborted)throw new bd;const _=new AbortController,b=await this.fetchWithTimeout(c,u,d,_).catch(vd),m=Date.now();if(b instanceof globalThis.Error){const A=`retrying, ${n} attempts remaining`;if(!((i=a.signal)===null||i===void 0)&&i.aborted)throw new bd;const S=yd(b)||/timed? ?out/i.test(String(b)+("cause"in b?String(b.cause):""));if(n)return nt(this).info(`[${p}] connection ${S?"timed out":"failed"} - ${A}`),nt(this).debug(`[${p}] connection ${S?"timed out":"failed"} (${A})`,or({retryOfRequestLogID:r,url:c,durationMs:m-y,message:b.message})),this.retryRequest(a,n,r??p);throw nt(this).info(`[${p}] connection ${S?"timed out":"failed"} - error; no more retries left`),nt(this).debug(`[${p}] connection ${S?"timed out":"failed"} (error; no more retries left)`,or({retryOfRequestLogID:r,url:c,durationMs:m-y,message:b.message})),S?new kA:new tl({cause:b})}const v=`[${p}${g}] ${u.method} ${c} ${b.ok?"succeeded":"failed"} with status ${b.status} in ${m-y}ms`;if(!b.ok){const A=await this.shouldRetry(b);if(n&&A){const L=`retrying, ${n} attempts remaining`;return await Bk(b.body),nt(this).info(`${v} - ${L}`),nt(this).debug(`[${p}] response error (${L})`,or({retryOfRequestLogID:r,url:b.url,status:b.status,headers:b.headers,durationMs:m-y})),this.retryRequest(a,n,r??p,b.headers)}const S=A?"error; no more retries left":"error; not retryable";nt(this).info(`${v} - ${S}`);const P=await b.text().catch(L=>vd(L).message),E=Ok(P),w=E?void 0:P;throw nt(this).debug(`[${p}] response error (${S})`,or({retryOfRequestLogID:r,url:b.url,status:b.status,headers:b.headers,message:w,durationMs:Date.now()-y})),this.makeStatusError(b.status,E,w,b.headers)}return nt(this).info(v),nt(this).debug(`[${p}] response start`,or({retryOfRequestLogID:r,url:b.url,status:b.status,headers:b.headers,durationMs:m-y})),{response:b,options:a,controller:_,requestLogID:p,retryOfRequestLogID:r,startTime:y}}async fetchWithTimeout(t,n,r,s){const o=n||{},{signal:i,method:a}=o,l=Ia(o,["signal","method"]),u=this._makeAbort(s);i&&i.addEventListener("abort",u,{once:!0});const c=setTimeout(u,r),d=globalThis.ReadableStream&&l.body instanceof globalThis.ReadableStream||typeof l.body=="object"&&l.body!==null&&Symbol.asyncIterator in l.body,p=Object.assign(Object.assign(Object.assign({signal:s.signal},d?{duplex:"half"}:{}),{method:"GET"}),l);a&&(p.method=a.toUpperCase());try{return await this.fetch.call(void 0,t,p)}finally{clearTimeout(c)}}async shouldRetry(t){const n=t.headers.get("x-should-retry");return n==="true"?!0:n==="false"?!1:t.status===408||t.status===409||t.status===429||t.status>=500}async retryRequest(t,n,r,s){var o;let i;const a=s?.get("retry-after-ms");if(a){const u=parseFloat(a);Number.isNaN(u)||(i=u)}const l=s?.get("retry-after");if(l&&!i){const u=parseFloat(l);Number.isNaN(u)?i=Date.parse(l)-Date.now():i=u*1e3}if(!(i&&0<=i&&i<60*1e3)){const u=(o=t.maxRetries)!==null&&o!==void 0?o:this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(n,u)}return await xk(i),this.makeRequest(t,n-1,r)}calculateDefaultRetryTimeoutMillis(t,n){const o=n-t,i=Math.min(.5*Math.pow(2,o),8),a=1-Math.random()*.25;return i*a*1e3}async buildRequest(t,{retryCount:n=0}={}){var r,s,o;const i=Object.assign({},t),{method:a,path:l,query:u,defaultBaseURL:c}=i,d=this.buildURL(l,u,c);"timeout"in i&&kk("timeout",i.timeout),i.timeout=(r=i.timeout)!==null&&r!==void 0?r:this.timeout;const{bodyHeaders:p,body:g}=this.buildBody({options:i}),y=await this.buildHeaders({options:t,method:a,bodyHeaders:p,retryCount:n});return{req:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({method:a,headers:y},i.signal&&{signal:i.signal}),globalThis.ReadableStream&&g instanceof globalThis.ReadableStream&&{duplex:"half"}),g&&{body:g}),(s=this.fetchOptions)!==null&&s!==void 0?s:{}),(o=i.fetchOptions)!==null&&o!==void 0?o:{}),url:d,timeout:i.timeout}}async buildHeaders({options:t,method:n,bodyHeaders:r,retryCount:s}){let o={};this.idempotencyHeader&&n!=="get"&&(t.idempotencyKey||(t.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=t.idempotencyKey);const i=await this.authHeaders(t);let a=li([o,Object.assign(Object.assign({Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s)},t.timeout?{"X-Stainless-Timeout":String(Math.trunc(t.timeout/1e3))}:{}),Uk()),this._options.defaultHeaders,r,t.headers,i]);return this.validateHeaders(a),a.values}_makeAbort(t){return()=>t.abort()}buildBody({options:{body:t,headers:n}}){if(!t)return{bodyHeaders:void 0,body:void 0};const r=li([n]);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t=="string"&&r.values.has("content-type")||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||globalThis.ReadableStream&&t instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:t}:typeof t=="object"&&(Symbol.asyncIterator in t||Symbol.iterator in t&&"next"in t&&typeof t.next=="function")?{bodyHeaders:void 0,body:Vk(t)}:this.encoder({body:t,headers:r})}}rl.DEFAULT_TIMEOUT=6e4;class Je extends rl{constructor(){super(...arguments),this.interactions=new YA(this)}}XA=Je;Je.GeminiNextGenAPIClient=XA;Je.GeminiNextGenAPIClientError=yt;Je.APIError=ot;Je.APIConnectionError=tl;Je.APIConnectionTimeoutError=kA;Je.APIUserAbortError=bd;Je.NotFoundError=qA;Je.ConflictError=LA;Je.RateLimitError=GA;Je.BadRequestError=OA;Je.AuthenticationError=xA;Je.InternalServerError=VA;Je.PermissionDeniedError=DA;Je.UnprocessableEntityError=UA;Je.toFile=$k;Je.Interactions=YA;function aO(e,t){const n={},r=f(e,["name"]);return r!=null&&h(n,["_url","name"],r),n}function lO(e,t){const n={},r=f(e,["name"]);return r!=null&&h(n,["_url","name"],r),n}function uO(e,t){const n={},r=f(e,["sdkHttpResponse"]);return r!=null&&h(n,["sdkHttpResponse"],r),n}function cO(e,t){const n={},r=f(e,["sdkHttpResponse"]);return r!=null&&h(n,["sdkHttpResponse"],r),n}function dO(e,t,n){const r={};if(f(e,["validationDataset"])!==void 0)throw new Error("validationDataset parameter is not supported in Gemini API.");const s=f(e,["tunedModelDisplayName"]);if(t!==void 0&&s!=null&&h(t,["displayName"],s),f(e,["description"])!==void 0)throw new Error("description parameter is not supported in Gemini API.");const o=f(e,["epochCount"]);t!==void 0&&o!=null&&h(t,["tuningTask","hyperparameters","epochCount"],o);const i=f(e,["learningRateMultiplier"]);if(i!=null&&h(r,["tuningTask","hyperparameters","learningRateMultiplier"],i),f(e,["exportLastCheckpointOnly"])!==void 0)throw new Error("exportLastCheckpointOnly parameter is not supported in Gemini API.");if(f(e,["preTunedModelCheckpointId"])!==void 0)throw new Error("preTunedModelCheckpointId parameter is not supported in Gemini API.");if(f(e,["adapterSize"])!==void 0)throw new Error("adapterSize parameter is not supported in Gemini API.");if(f(e,["tuningMode"])!==void 0)throw new Error("tuningMode parameter is not supported in Gemini API.");if(f(e,["customBaseModel"])!==void 0)throw new Error("customBaseModel parameter is not supported in Gemini API.");const a=f(e,["batchSize"]);t!==void 0&&a!=null&&h(t,["tuningTask","hyperparameters","batchSize"],a);const l=f(e,["learningRate"]);if(t!==void 0&&l!=null&&h(t,["tuningTask","hyperparameters","learningRate"],l),f(e,["labels"])!==void 0)throw new Error("labels parameter is not supported in Gemini API.");if(f(e,["beta"])!==void 0)throw new Error("beta parameter is not supported in Gemini API.");if(f(e,["baseTeacherModel"])!==void 0)throw new Error("baseTeacherModel parameter is not supported in Gemini API.");if(f(e,["tunedTeacherModelSource"])!==void 0)throw new Error("tunedTeacherModelSource parameter is not supported in Gemini API.");if(f(e,["sftLossWeightMultiplier"])!==void 0)throw new Error("sftLossWeightMultiplier parameter is not supported in Gemini API.");if(f(e,["outputUri"])!==void 0)throw new Error("outputUri parameter is not supported in Gemini API.");if(f(e,["encryptionSpec"])!==void 0)throw new Error("encryptionSpec parameter is not supported in Gemini API.");return r}function fO(e,t,n){const r={};let s=f(n,["config","method"]);if(s===void 0&&(s="SUPERVISED_FINE_TUNING"),s==="SUPERVISED_FINE_TUNING"){const E=f(e,["validationDataset"]);t!==void 0&&E!=null&&h(t,["supervisedTuningSpec"],Du(E))}else if(s==="PREFERENCE_TUNING"){const E=f(e,["validationDataset"]);t!==void 0&&E!=null&&h(t,["preferenceOptimizationSpec"],Du(E))}else if(s==="DISTILLATION"){const E=f(e,["validationDataset"]);t!==void 0&&E!=null&&h(t,["distillationSpec"],Du(E))}const o=f(e,["tunedModelDisplayName"]);t!==void 0&&o!=null&&h(t,["tunedModelDisplayName"],o);const i=f(e,["description"]);t!==void 0&&i!=null&&h(t,["description"],i);let a=f(n,["config","method"]);if(a===void 0&&(a="SUPERVISED_FINE_TUNING"),a==="SUPERVISED_FINE_TUNING"){const E=f(e,["epochCount"]);t!==void 0&&E!=null&&h(t,["supervisedTuningSpec","hyperParameters","epochCount"],E)}else if(a==="PREFERENCE_TUNING"){const E=f(e,["epochCount"]);t!==void 0&&E!=null&&h(t,["preferenceOptimizationSpec","hyperParameters","epochCount"],E)}else if(a==="DISTILLATION"){const E=f(e,["epochCount"]);t!==void 0&&E!=null&&h(t,["distillationSpec","hyperParameters","epochCount"],E)}let l=f(n,["config","method"]);if(l===void 0&&(l="SUPERVISED_FINE_TUNING"),l==="SUPERVISED_FINE_TUNING"){const E=f(e,["learningRateMultiplier"]);t!==void 0&&E!=null&&h(t,["supervisedTuningSpec","hyperParameters","learningRateMultiplier"],E)}else if(l==="PREFERENCE_TUNING"){const E=f(e,["learningRateMultiplier"]);t!==void 0&&E!=null&&h(t,["preferenceOptimizationSpec","hyperParameters","learningRateMultiplier"],E)}else if(l==="DISTILLATION"){const E=f(e,["learningRateMultiplier"]);t!==void 0&&E!=null&&h(t,["distillationSpec","hyperParameters","learningRateMultiplier"],E)}let u=f(n,["config","method"]);if(u===void 0&&(u="SUPERVISED_FINE_TUNING"),u==="SUPERVISED_FINE_TUNING"){const E=f(e,["exportLastCheckpointOnly"]);t!==void 0&&E!=null&&h(t,["supervisedTuningSpec","exportLastCheckpointOnly"],E)}else if(u==="PREFERENCE_TUNING"){const E=f(e,["exportLastCheckpointOnly"]);t!==void 0&&E!=null&&h(t,["preferenceOptimizationSpec","exportLastCheckpointOnly"],E)}else if(u==="DISTILLATION"){const E=f(e,["exportLastCheckpointOnly"]);t!==void 0&&E!=null&&h(t,["distillationSpec","exportLastCheckpointOnly"],E)}let c=f(n,["config","method"]);if(c===void 0&&(c="SUPERVISED_FINE_TUNING"),c==="SUPERVISED_FINE_TUNING"){const E=f(e,["adapterSize"]);t!==void 0&&E!=null&&h(t,["supervisedTuningSpec","hyperParameters","adapterSize"],E)}else if(c==="PREFERENCE_TUNING"){const E=f(e,["adapterSize"]);t!==void 0&&E!=null&&h(t,["preferenceOptimizationSpec","hyperParameters","adapterSize"],E)}else if(c==="DISTILLATION"){const E=f(e,["adapterSize"]);t!==void 0&&E!=null&&h(t,["distillationSpec","hyperParameters","adapterSize"],E)}let d=f(n,["config","method"]);if(d===void 0&&(d="SUPERVISED_FINE_TUNING"),d==="SUPERVISED_FINE_TUNING"){const E=f(e,["tuningMode"]);t!==void 0&&E!=null&&h(t,["supervisedTuningSpec","tuningMode"],E)}const p=f(e,["customBaseModel"]);t!==void 0&&p!=null&&h(t,["customBaseModel"],p);let g=f(n,["config","method"]);if(g===void 0&&(g="SUPERVISED_FINE_TUNING"),g==="SUPERVISED_FINE_TUNING"){const E=f(e,["batchSize"]);t!==void 0&&E!=null&&h(t,["supervisedTuningSpec","hyperParameters","batchSize"],E)}let y=f(n,["config","method"]);if(y===void 0&&(y="SUPERVISED_FINE_TUNING"),y==="SUPERVISED_FINE_TUNING"){const E=f(e,["learningRate"]);t!==void 0&&E!=null&&h(t,["supervisedTuningSpec","hyperParameters","learningRate"],E)}const _=f(e,["labels"]);t!==void 0&&_!=null&&h(t,["labels"],_);const b=f(e,["beta"]);t!==void 0&&b!=null&&h(t,["preferenceOptimizationSpec","hyperParameters","beta"],b);const m=f(e,["baseTeacherModel"]);t!==void 0&&m!=null&&h(t,["distillationSpec","baseTeacherModel"],m);const v=f(e,["tunedTeacherModelSource"]);t!==void 0&&v!=null&&h(t,["distillationSpec","tunedTeacherModelSource"],v);const A=f(e,["sftLossWeightMultiplier"]);t!==void 0&&A!=null&&h(t,["distillationSpec","hyperParameters","sftLossWeightMultiplier"],A);const S=f(e,["outputUri"]);t!==void 0&&S!=null&&h(t,["outputUri"],S);const P=f(e,["encryptionSpec"]);return t!==void 0&&P!=null&&h(t,["encryptionSpec"],P),r}function pO(e,t){const n={},r=f(e,["baseModel"]);r!=null&&h(n,["baseModel"],r);const s=f(e,["preTunedModel"]);s!=null&&h(n,["preTunedModel"],s);const o=f(e,["trainingDataset"]);o!=null&&EO(o);const i=f(e,["config"]);return i!=null&&dO(i,n),n}function hO(e,t){const n={},r=f(e,["baseModel"]);r!=null&&h(n,["baseModel"],r);const s=f(e,["preTunedModel"]);s!=null&&h(n,["preTunedModel"],s);const o=f(e,["trainingDataset"]);o!=null&&TO(o,n,t);const i=f(e,["config"]);return i!=null&&fO(i,n,t),n}function gO(e,t){const n={},r=f(e,["name"]);return r!=null&&h(n,["_url","name"],r),n}function mO(e,t){const n={},r=f(e,["name"]);return r!=null&&h(n,["_url","name"],r),n}function _O(e,t,n){const r={},s=f(e,["pageSize"]);t!==void 0&&s!=null&&h(t,["_query","pageSize"],s);const o=f(e,["pageToken"]);t!==void 0&&o!=null&&h(t,["_query","pageToken"],o);const i=f(e,["filter"]);return t!==void 0&&i!=null&&h(t,["_query","filter"],i),r}function yO(e,t,n){const r={},s=f(e,["pageSize"]);t!==void 0&&s!=null&&h(t,["_query","pageSize"],s);const o=f(e,["pageToken"]);t!==void 0&&o!=null&&h(t,["_query","pageToken"],o);const i=f(e,["filter"]);return t!==void 0&&i!=null&&h(t,["_query","filter"],i),r}function vO(e,t){const n={},r=f(e,["config"]);return r!=null&&_O(r,n),n}function bO(e,t){const n={},r=f(e,["config"]);return r!=null&&yO(r,n),n}function AO(e,t){const n={},r=f(e,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);const s=f(e,["nextPageToken"]);s!=null&&h(n,["nextPageToken"],s);const o=f(e,["tunedModels"]);if(o!=null){let i=o;Array.isArray(i)&&(i=i.map(a=>QA(a))),h(n,["tuningJobs"],i)}return n}function SO(e,t){const n={},r=f(e,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);const s=f(e,["nextPageToken"]);s!=null&&h(n,["nextPageToken"],s);const o=f(e,["tuningJobs"]);if(o!=null){let i=o;Array.isArray(i)&&(i=i.map(a=>wd(a))),h(n,["tuningJobs"],i)}return n}function wO(e,t){const n={},r=f(e,["name"]);r!=null&&h(n,["model"],r);const s=f(e,["name"]);return s!=null&&h(n,["endpoint"],s),n}function EO(e,t){const n={};if(f(e,["gcsUri"])!==void 0)throw new Error("gcsUri parameter is not supported in Gemini API.");if(f(e,["vertexDatasetResource"])!==void 0)throw new Error("vertexDatasetResource parameter is not supported in Gemini API.");const r=f(e,["examples"]);if(r!=null){let s=r;Array.isArray(s)&&(s=s.map(o=>o)),h(n,["examples","examples"],s)}return n}function TO(e,t,n){const r={};let s=f(n,["config","method"]);if(s===void 0&&(s="SUPERVISED_FINE_TUNING"),s==="SUPERVISED_FINE_TUNING"){const i=f(e,["gcsUri"]);t!==void 0&&i!=null&&h(t,["supervisedTuningSpec","trainingDatasetUri"],i)}else if(s==="PREFERENCE_TUNING"){const i=f(e,["gcsUri"]);t!==void 0&&i!=null&&h(t,["preferenceOptimizationSpec","trainingDatasetUri"],i)}else if(s==="DISTILLATION"){const i=f(e,["gcsUri"]);t!==void 0&&i!=null&&h(t,["distillationSpec","promptDatasetUri"],i)}let o=f(n,["config","method"]);if(o===void 0&&(o="SUPERVISED_FINE_TUNING"),o==="SUPERVISED_FINE_TUNING"){const i=f(e,["vertexDatasetResource"]);t!==void 0&&i!=null&&h(t,["supervisedTuningSpec","trainingDatasetUri"],i)}else if(o==="PREFERENCE_TUNING"){const i=f(e,["vertexDatasetResource"]);t!==void 0&&i!=null&&h(t,["preferenceOptimizationSpec","trainingDatasetUri"],i)}else if(o==="DISTILLATION"){const i=f(e,["vertexDatasetResource"]);t!==void 0&&i!=null&&h(t,["distillationSpec","promptDatasetUri"],i)}if(f(e,["examples"])!==void 0)throw new Error("examples parameter is not supported in Vertex AI.");return r}function QA(e,t){const n={},r=f(e,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);const s=f(e,["name"]);s!=null&&h(n,["name"],s);const o=f(e,["state"]);o!=null&&h(n,["state"],rA(o));const i=f(e,["createTime"]);i!=null&&h(n,["createTime"],i);const a=f(e,["tuningTask","startTime"]);a!=null&&h(n,["startTime"],a);const l=f(e,["tuningTask","completeTime"]);l!=null&&h(n,["endTime"],l);const u=f(e,["updateTime"]);u!=null&&h(n,["updateTime"],u);const c=f(e,["description"]);c!=null&&h(n,["description"],c);const d=f(e,["baseModel"]);d!=null&&h(n,["baseModel"],d);const p=f(e,["_self"]);return p!=null&&h(n,["tunedModel"],wO(p)),n}function wd(e,t){const n={},r=f(e,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);const s=f(e,["name"]);s!=null&&h(n,["name"],s);const o=f(e,["state"]);o!=null&&h(n,["state"],rA(o));const i=f(e,["createTime"]);i!=null&&h(n,["createTime"],i);const a=f(e,["startTime"]);a!=null&&h(n,["startTime"],a);const l=f(e,["endTime"]);l!=null&&h(n,["endTime"],l);const u=f(e,["updateTime"]);u!=null&&h(n,["updateTime"],u);const c=f(e,["error"]);c!=null&&h(n,["error"],c);const d=f(e,["description"]);d!=null&&h(n,["description"],d);const p=f(e,["baseModel"]);p!=null&&h(n,["baseModel"],p);const g=f(e,["tunedModel"]);g!=null&&h(n,["tunedModel"],g);const y=f(e,["preTunedModel"]);y!=null&&h(n,["preTunedModel"],y);const _=f(e,["supervisedTuningSpec"]);_!=null&&h(n,["supervisedTuningSpec"],_);const b=f(e,["preferenceOptimizationSpec"]);b!=null&&h(n,["preferenceOptimizationSpec"],b);const m=f(e,["distillationSpec"]);m!=null&&h(n,["distillationSpec"],m);const v=f(e,["tuningDataStats"]);v!=null&&h(n,["tuningDataStats"],v);const A=f(e,["encryptionSpec"]);A!=null&&h(n,["encryptionSpec"],A);const S=f(e,["partnerModelTuningSpec"]);S!=null&&h(n,["partnerModelTuningSpec"],S);const P=f(e,["customBaseModel"]);P!=null&&h(n,["customBaseModel"],P);const E=f(e,["experiment"]);E!=null&&h(n,["experiment"],E);const w=f(e,["labels"]);w!=null&&h(n,["labels"],w);const I=f(e,["outputUri"]);I!=null&&h(n,["outputUri"],I);const L=f(e,["pipelineJob"]);L!=null&&h(n,["pipelineJob"],L);const H=f(e,["serviceAccount"]);H!=null&&h(n,["serviceAccount"],H);const B=f(e,["tunedModelDisplayName"]);B!=null&&h(n,["tunedModelDisplayName"],B);const F=f(e,["veoTuningSpec"]);return F!=null&&h(n,["veoTuningSpec"],F),n}function PO(e,t){const n={},r=f(e,["sdkHttpResponse"]);r!=null&&h(n,["sdkHttpResponse"],r);const s=f(e,["name"]);s!=null&&h(n,["name"],s);const o=f(e,["metadata"]);o!=null&&h(n,["metadata"],o);const i=f(e,["done"]);i!=null&&h(n,["done"],i);const a=f(e,["error"]);return a!=null&&h(n,["error"],a),n}function Du(e,t){const n={},r=f(e,["gcsUri"]);r!=null&&h(n,["validationDatasetUri"],r);const s=f(e,["vertexDatasetResource"]);return s!=null&&h(n,["validationDatasetUri"],s),n}class IO extends Sn{constructor(t){super(),this.apiClient=t,this.list=async(n={})=>new Dn(zt.PAGED_ITEM_TUNING_JOBS,r=>this.listInternal(r),await this.listInternal(n),n),this.get=async n=>await this.getInternal(n),this.tune=async n=>{var r;if(this.apiClient.isVertexAI())if(n.baseModel.startsWith("projects/")){const s={tunedModelName:n.baseModel};!((r=n.config)===null||r===void 0)&&r.preTunedModelCheckpointId&&(s.checkpointId=n.config.preTunedModelCheckpointId);const o=Object.assign(Object.assign({},n),{preTunedModel:s});return o.baseModel=void 0,await this.tuneInternal(o)}else{const s=Object.assign({},n);return await this.tuneInternal(s)}else{const s=Object.assign({},n),o=await this.tuneMldevInternal(s);let i="";return o.metadata!==void 0&&o.metadata.tunedModel!==void 0?i=o.metadata.tunedModel:o.name!==void 0&&o.name.includes("/operations/")&&(i=o.name.split("/operations/")[0]),{name:i,state:wa.JOB_STATE_QUEUED}}}}async getInternal(t){var n,r,s,o;let i,a="",l={};if(this.apiClient.isVertexAI()){const u=mO(t);return a=ie("{name}",u._url),l=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json().then(d=>{const p=d;return p.sdkHttpResponse={headers:c.headers},p})),i.then(c=>wd(c))}else{const u=gO(t);return a=ie("{name}",u._url),l=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(s=t.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(o=t.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json().then(d=>{const p=d;return p.sdkHttpResponse={headers:c.headers},p})),i.then(c=>QA(c))}}async listInternal(t){var n,r,s,o;let i,a="",l={};if(this.apiClient.isVertexAI()){const u=bO(t);return a=ie("tuningJobs",u._url),l=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json().then(d=>{const p=d;return p.sdkHttpResponse={headers:c.headers},p})),i.then(c=>{const d=SO(c),p=new ld;return Object.assign(p,d),p})}else{const u=vO(t);return a=ie("tunedModels",u._url),l=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"GET",httpOptions:(s=t.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(o=t.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json().then(d=>{const p=d;return p.sdkHttpResponse={headers:c.headers},p})),i.then(c=>{const d=AO(c),p=new ld;return Object.assign(p,d),p})}}async cancel(t){var n,r,s,o;let i,a="",l={};if(this.apiClient.isVertexAI()){const u=lO(t);return a=ie("{name}:cancel",u._url),l=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal}).then(c=>c.json().then(d=>{const p=d;return p.sdkHttpResponse={headers:c.headers},p})),i.then(c=>{const d=cO(c),p=new ud;return Object.assign(p,d),p})}else{const u=aO(t);return a=ie("{name}:cancel",u._url),l=u._query,delete u._url,delete u._query,i=this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"POST",httpOptions:(s=t.config)===null||s===void 0?void 0:s.httpOptions,abortSignal:(o=t.config)===null||o===void 0?void 0:o.abortSignal}).then(c=>c.json().then(d=>{const p=d;return p.sdkHttpResponse={headers:c.headers},p})),i.then(c=>{const d=uO(c),p=new ud;return Object.assign(p,d),p})}}async tuneInternal(t){var n,r;let s,o="",i={};if(this.apiClient.isVertexAI()){const a=hO(t,t);return o=ie("tuningJobs",a._url),i=a._query,delete a._url,delete a._query,s=this.apiClient.request({path:o,queryParams:i,body:JSON.stringify(a),httpMethod:"POST",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal}).then(l=>l.json().then(u=>{const c=u;return c.sdkHttpResponse={headers:l.headers},c})),s.then(l=>wd(l))}else throw new Error("This method is only supported by the Vertex AI.")}async tuneMldevInternal(t){var n,r;let s,o="",i={};if(this.apiClient.isVertexAI())throw new Error("This method is only supported by the Gemini Developer API.");{const a=pO(t);return o=ie("tunedModels",a._url),i=a._query,delete a._url,delete a._query,s=this.apiClient.request({path:o,queryParams:i,body:JSON.stringify(a),httpMethod:"POST",httpOptions:(n=t.config)===null||n===void 0?void 0:n.httpOptions,abortSignal:(r=t.config)===null||r===void 0?void 0:r.abortSignal}).then(l=>l.json().then(u=>{const c=u;return c.sdkHttpResponse={headers:l.headers},c})),s.then(l=>PO(l))}}}class CO{async download(t,n){throw new Error("Download to file is not supported in the browser, please use a browser compliant download like an <a> tag.")}}const RO=1024*1024*8,MO=3,NO=1e3,FO=2,Ra="x-goog-upload-status";async function kO(e,t,n){var r;const s=await ZA(e,t,n),o=await s?.json();if(((r=s?.headers)===null||r===void 0?void 0:r[Ra])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");return o.file}async function OO(e,t,n){var r;const s=await ZA(e,t,n),o=await s?.json();if(((r=s?.headers)===null||r===void 0?void 0:r[Ra])!=="final")throw new Error("Failed to upload file: Upload status is not finalized.");const i=D0(o),a=new Xa;return Object.assign(a,i),a}async function ZA(e,t,n){var r,s;let o=0,i=0,a=new Ta(new Response),l="upload";for(o=e.size;i<o;){const u=Math.min(RO,o-i),c=e.slice(i,i+u);i+u>=o&&(l+=", finalize");let d=0,p=NO;for(;d<MO&&(a=await n.request({path:"",body:c,httpMethod:"POST",httpOptions:{apiVersion:"",baseUrl:t,headers:{"X-Goog-Upload-Command":l,"X-Goog-Upload-Offset":String(i),"Content-Length":String(u)}}}),!(!((r=a?.headers)===null||r===void 0)&&r[Ra]));)d++,await DO(p),p=p*FO;if(i+=u,((s=a?.headers)===null||s===void 0?void 0:s[Ra])!=="active")break;if(o<=i)throw new Error("All content has been uploaded, but the upload status is not finalized.")}return a}async function xO(e){return{size:e.size,type:e.type}}function DO(e){return new Promise(t=>setTimeout(t,e))}class qO{async upload(t,n,r){if(typeof t=="string")throw new Error("File path is not supported in browser uploader.");return await kO(t,n,r)}async uploadToFileSearchStore(t,n,r){if(typeof t=="string")throw new Error("File path is not supported in browser uploader.");return await OO(t,n,r)}async stat(t){if(typeof t=="string")throw new Error("File path is not supported in browser uploader.");return await xO(t)}}class LO{create(t,n,r){return new UO(t,n,r)}}class UO{constructor(t,n,r){this.url=t,this.headers=n,this.callbacks=r}connect(){this.ws=new WebSocket(this.url),this.ws.onopen=this.callbacks.onopen,this.ws.onerror=this.callbacks.onerror,this.ws.onclose=this.callbacks.onclose,this.ws.onmessage=this.callbacks.onmessage}send(t){if(this.ws===void 0)throw new Error("WebSocket is not connected");this.ws.send(t)}close(){if(this.ws===void 0)throw new Error("WebSocket is not connected");this.ws.close()}}const ev="x-goog-api-key";class GO{constructor(t){this.apiKey=t}async addAuthHeaders(t,n){if(t.get(ev)===null){if(this.apiKey.startsWith("auth_tokens/"))throw new Error("Ephemeral tokens are only supported by the live API.");if(!this.apiKey)throw new Error("API key is missing. Please provide a valid API key.");t.append(ev,this.apiKey)}}}const VO="gl-node/";class BO{get interactions(){var t;if(this._interactions!==void 0)return this._interactions;console.warn("GoogleGenAI.interactions: Interactions usage is experimental and may change in future versions.");const n=this.httpOptions;n?.extraBody&&console.warn("GoogleGenAI.interactions: Client level httpOptions.extraBody is not supported by the interactions client and will be ignored.");const r=new Je({baseURL:this.apiClient.getBaseUrl(),apiKey:this.apiKey,apiVersion:this.apiClient.getApiVersion(),clientAdapter:this.apiClient,defaultHeaders:this.apiClient.getDefaultHeaders(),timeout:n?.timeout,maxRetries:(t=n?.retryOptions)===null||t===void 0?void 0:t.attempts});return this._interactions=r.interactions,this._interactions}constructor(t){var n;if(t.apiKey==null)throw new Error("An API Key must be set when running in a browser");if(t.project||t.location)throw new Error("Vertex AI project based authentication is not supported on browser runtimes. Please do not provide a project or location.");this.vertexai=(n=t.vertexai)!==null&&n!==void 0?n:!1,this.apiKey=t.apiKey;const r=SI(t.httpOptions,t.vertexai,void 0,void 0);r&&(t.httpOptions?t.httpOptions.baseUrl=r:t.httpOptions={baseUrl:r}),this.apiVersion=t.apiVersion,this.httpOptions=t.httpOptions;const s=new GO(this.apiKey);this.apiClient=new UF({auth:s,apiVersion:this.apiVersion,apiKey:this.apiKey,vertexai:this.vertexai,httpOptions:this.httpOptions,userAgentExtra:VO+"web",uploader:new qO,downloader:new CO}),this.models=new RA(this.apiClient),this.live=new IA(this.apiClient,s,new LO),this.batches=new dA(this.apiClient),this.chats=new hA(this.models,this.apiClient),this.caches=new fA(this.apiClient),this.files=new mA(this.apiClient),this.operations=new MA(this.apiClient),this.authTokens=new NA(this.apiClient),this.tunings=new IO(this.apiClient),this.fileSearchStores=new Tk(this.apiClient)}}const HO=Object.freeze(Object.defineProperty({__proto__:null,get ActivityHandling(){return Qc},get AdapterSize(){return Pc},ApiError:Br,get ApiSpec(){return ac},get AuthType(){return lc},Batches:dA,get Behavior(){return dc},get BlockedReason(){return Sc},Caches:fA,CancelTuningJobResponse:ud,Chat:gA,Chats:hA,ComputeTokensResponse:B0,ContentReferenceImage:dC,ControlReferenceImage:lC,get ControlReferenceType(){return xc},CountTokensResponse:ad,CreateFileResponse:K0,DeleteCachedContentResponse:cd,DeleteFileResponse:$0,DeleteModelResponse:id,get DocumentState(){return Hc},get DynamicRetrievalConfigMode(){return fc},EditImageResponse:L0,get EditMode(){return qc},EmbedContentResponse:rd,get EndSensitivity(){return Xc},get Environment(){return Mc},get FeatureSelectionPreference(){return Rc},get FileSource(){return jc},get FileState(){return Jc},Files:mA,get FinishReason(){return yc},get FunctionCallingConfigMode(){return pc},FunctionResponse:HI,FunctionResponseBlob:LI,FunctionResponseFileData:UI,FunctionResponsePart:GI,get FunctionResponseScheduling(){return ic},GenerateContentResponse:Pr,GenerateContentResponsePromptFeedback:QI,GenerateContentResponseUsageMetadata:ZI,GenerateImagesResponse:sd,GenerateVideosOperation:Ci,GenerateVideosResponse:eC,GoogleGenAI:BO,get HarmBlockMethod(){return mc},get HarmBlockThreshold(){return _c},get HarmCategory(){return gc},get HarmProbability(){return vc},get HarmSeverity(){return bc},get HttpElementLocation(){return uc},HttpResponse:Ta,get ImagePromptLanguage(){return kc},ImportFileOperation:za,ImportFileResponse:tC,InlinedEmbedContentResponse:sC,InlinedResponse:nC,get JobState(){return wa},get Language(){return oc},ListBatchJobsResponse:fd,ListCachedContentsResponse:dd,ListDocumentsResponse:H0,ListFileSearchStoresResponse:J0,ListFilesResponse:W0,ListModelsResponse:od,ListTuningJobsResponse:ld,Live:IA,LiveClientToolResponse:fC,get LiveMusicPlaybackControl(){return ar},LiveMusicServerMessage:X0,LiveSendToolResponseParameters:pC,LiveServerMessage:z0,MaskReferenceImage:aC,get MaskReferenceMode(){return Oc},get MediaModality(){return Kc},get MediaResolution(){return Ec},get Modality(){return Ii},Models:RA,get MusicGenerationMode(){return td},Operations:MA,get Outcome(){return sc},get PagedItem(){return zt},Pager:Dn,get PartMediaResolutionLevel(){return Cc},get PersonGeneration(){return Fc},get PhishBlockThreshold(){return cc},RawReferenceImage:iC,RecontextImageResponse:G0,RegisterFilesResponse:Y0,ReplayResponse:oC,get ResourceScope(){return Ea},get SafetyFilterLevel(){return Nc},get Scale(){return ed},SegmentImageResponse:V0,get SegmentMode(){return Lc},Session:CA,SingleEmbedContentResponse:rC,get StartSensitivity(){return zc},StyleReferenceImage:uC,SubjectReferenceImage:cC,get SubjectReferenceType(){return Dc},get ThinkingLevel(){return hc},Tokens:NA,get TrafficType(){return wc},get TuningMethod(){return Bc},get TuningMode(){return Tc},get TuningTask(){return Ic},get TurnCompleteReason(){return Wc},get TurnCoverage(){return Zc},get Type(){return pn},UploadToFileSearchStoreOperation:Xa,UploadToFileSearchStoreResponse:hC,UploadToFileSearchStoreResumableResponse:j0,UpscaleImageResponse:U0,get UrlRetrievalStatus(){return Ac},get VadSignalType(){return $c},get VideoCompressionQuality(){return Vc},get VideoGenerationMaskMode(){return Gc},get VideoGenerationReferenceType(){return Uc},get VoiceActivityType(){return Yc},createFunctionResponsePartFromBase64:VI,createFunctionResponsePartFromUri:BI,createModelContent:XI,createPartFromBase64:KI,createPartFromCodeExecutionResult:$I,createPartFromExecutableCode:YI,createPartFromFunctionCall:jI,createPartFromFunctionResponse:WI,createPartFromText:nd,createPartFromUri:JI,createUserContent:zI,mcpToTool:jF,setDefaultBaseUrls:bI},Symbol.toStringTag,{value:"Module"})),JO=Hd(HO);var tv;function jO(){return tv||(tv=1,(function(e){var t={};Object.defineProperty(e,"__esModule",{value:!0}),e.geminiAgent=void 0;const n=Oe(),r=JO,s=Di(),o=(l,u,c,d)=>{const p=l.text,g={role:"assistant",content:p},y=u.length>0?u:l.functionCalls;y&&(g.tool_calls=y.map(A=>({function:{name:A.name,arguments:JSON.stringify(A.args)}})));const _=y?y.map(A=>({id:"dummy",name:A.name??"",arguments:A.args??{}})):[],b=_&&_[0]?_[0]:void 0;c.push(g);const m=l.usageMetadata,v=m?{prompt_tokens:m.promptTokenCount??m.prompt_tokens,completion_tokens:m.candidatesTokenCount??m.completionTokenCount??m.completion_tokens,total_tokens:m.totalTokenCount??m.total_tokens}:{};return{...l,choices:[{message:g}],text:p,tool:b,tool_calls:_,message:g,messages:c,metadata:(0,s.convertMeta)(d),usage:m?{...m,...v}:void 0}},i=async({params:l,namedInputs:u,config:c,filterParams:d})=>{const{system:p,temperature:g,tools:y,max_tokens:_,prompt:b,messages:m,response_format:v,tool_choice:A}={...l,...u},{apiKey:S,stream:P,dataStream:E,model:w}={...l,...c||{}},I=(0,s.initLLMMetaData)(),L=(0,s.getMergeValue)(u,l,"mergeablePrompts",b),H=(0,s.getMergeValue)(u,l,"mergeableSystem",p),B=(0,s.getMessages)(H,m);L&&B.push({role:"user",content:L});const F=B.pop();if(!F)return[];const j=S??(typeof process<"u"&&typeof t<"u"?t.GOOGLE_GENAI_API_KEY:null);(0,n.assert)(!!j,"GOOGLE_GENAI_API_KEY is missing in the environment.");const U=new r.GoogleGenAI({apiKey:j}),O=[{category:r.HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,threshold:r.HarmBlockThreshold.BLOCK_ONLY_HIGH}],R={maxOutputTokens:_,safetySettings:O,temperature:g};if(y){const k=y.map(G=>G.function);R.tools=[{functionDeclarations:k}]}if(A){let k;switch(A){case"auto":k=r.FunctionCallingConfigMode.AUTO;break;case"any":k=r.FunctionCallingConfigMode.ANY;break;case"none":k=r.FunctionCallingConfigMode.NONE;break;case"validated":k=r.FunctionCallingConfigMode.VALIDATED;break;default:k=r.FunctionCallingConfigMode.MODE_UNSPECIFIED;break}if(k==r.FunctionCallingConfigMode.MODE_UNSPECIFIED)n.GraphAILogger.warn("tool_choice should be `auto (default)`, `any`, `none` or `validated (preview)`");else{const G={mode:k};(k===r.FunctionCallingConfigMode.ANY||k===r.FunctionCallingConfigMode.VALIDATED)&&(G.allowedFunctionNames=y?.map(V=>V.function.name)),R.toolConfig={functionCallingConfig:G}}}v&&(v.type==="schema"?(R.responseMimeType="application/json",R.responseSchema=v.json_schema.schema):v.type==="json_schema"?(R.responseMimeType="application/json",R.responseJsonSchema=v.json_schema.schema):n.GraphAILogger.warn("response_format.type should be `schema` or `json_schema`"),v.json_schema.strict!==void 0&&n.GraphAILogger.warn("Gemini does not support 'strict' option, ignoring..."));const T=U.chats.create({model:w||"gemini-2.5-flash",config:R,history:B.map(k=>{const G=k.role==="assistant"?"model":k.role;return G==="system"?{role:"user",parts:[{text:"System Message: "+k.content}]}:{role:G,parts:[{text:k.content}]}})});if(B.push(F),P||E){E&&d&&d.streamTokenCallback&&d.streamTokenCallback({type:"response.created",response:{}});const k=await T.sendMessageStream({message:F.content});let G;const V=[];for await(const W of k){(0,s.llmMetaDataFirstTokenTime)(I),W.functionCalls&&V.push(...W.functionCalls);const X=W.text;G=W,d&&d.streamTokenCallback&&X&&(E?d.streamTokenCallback({type:"response.in_progress",response:{output:[{type:"text",text:X}]}}):d.streamTokenCallback(X))}return G?(E&&d&&d.streamTokenCallback&&d.streamTokenCallback({type:"response.completed",response:{}}),(0,s.llmMetaDataEndTime)(I),o(G,V,B,I)):[]}const M=await T.sendMessage({message:F.content});return(0,s.llmMetaDataEndTime)(I),o(M,[],B,I)};e.geminiAgent=i;const a={name:"geminiAgent",agent:e.geminiAgent,mock:e.geminiAgent,inputs:{type:"object",properties:{model:{type:"string"},system:{type:"string"},tools:{type:"object"},tool_choice:{type:"string"},max_tokens:{type:"number"},temperature:{type:"number"},prompt:{type:"string",description:"query string"},messages:{anyOf:[{type:"string"},{type:"integer"},{type:"object"},{type:"array"}],description:"chat messages"}}},output:{type:"object"},samples:[],description:"Gemini Agent",category:["llm"],author:"Receptron team",repository:"https://github.com/receptron/graphai",source:"https://github.com/receptron/graphai/blob/main/llm_agents/gemini_agent/src/gemini_agent.ts",package:"@graphai/gemini_agent",license:"MIT",stream:!0,npms:["@google/genai"],environmentVariables:["GOOGLE_GENAI_API_KEY"]};e.default=a})(ku)),ku}var nv;function WO(){if(nv)return rr;nv=1;var e=rr&&rr.__importDefault||function(n){return n&&n.__esModule?n:{default:n}};Object.defineProperty(rr,"__esModule",{value:!0}),rr.geminiAgent=void 0;const t=e(jO());return rr.geminiAgent=t.default,rr}WO();_T.config({quiet:!0});const KO=(e,t)=>{const n=[],r=e.text||"";if(!r.trim())return"";n.push(`[${t}] ${r}`);const s=e.meta;return s&&(s.tags&&s.tags.length>0&&n.push(` Tags: ${s.tags.join(", ")}`),s.context&&n.push(` Context: ${s.context}`),s.keywords&&s.keywords.length>0&&n.push(` Keywords: ${s.keywords.join(", ")}`),s.expectedQuestions&&s.expectedQuestions.length>0&&n.push(` Can answer: ${s.expectedQuestions.join("; ")}`)),n.join(`
98
- `)},$O=e=>{const t=e.scriptMeta;if(!t)return"";const n=[];return t.background&&n.push(`Background: ${t.background}`),t.audience&&n.push(`Target audience: ${t.audience}`),t.prerequisites&&t.prerequisites.length>0&&n.push(`Prerequisites: ${t.prerequisites.join(", ")}`),t.goals&&t.goals.length>0&&n.push(`Goals: ${t.goals.join("; ")}`),t.keywords&&t.keywords.length>0&&n.push(`Keywords: ${t.keywords.join(", ")}`),t.references&&t.references.length>0&&(n.push("References:"),t.references.forEach(r=>{const s=r.title||r.url,o=r.description?` - ${r.description}`:"";n.push(` - [${r.type||"web"}] ${s}: ${r.url}${o}`)})),t.faq&&t.faq.length>0&&(n.push("FAQ:"),t.faq.forEach(r=>{n.push(` Q: ${r.question}`),n.push(` A: ${r.answer}`)})),t.author&&n.push(`Author: ${t.author}`),n.length>0?n.join(`
99
- `):""},YO=e=>{const t=[];t.push(`# Script: ${e.title}`),t.push(`Language: ${e.lang}`),t.push("");const n=$O(e);n&&(t.push("## About this content"),t.push(n),t.push(""));const r=new Map;return e.beats.forEach((s,o)=>{const i=KO(s,o);if(!i)return;const a=s.meta?.section||"main";r.has(a)||r.set(a,[]),r.get(a).push(i)}),r.forEach((s,o)=>{t.push(`## Section: ${o}`),s.forEach(i=>t.push(i)),t.push("")}),t.join(`
100
- `)},zO=`You are answering questions based on the content provided.
101
- - Answer based ONLY on the information in the provided content
102
- - If the answer cannot be found in the content, say so clearly
103
- - Be concise and direct in your answers
104
- - Do not make up information that is not in the content
105
- - You may reference previous conversation when answering follow-up questions
106
- - If references are available and the user asks for more details, mention which reference could provide more information
107
- - When you suggest fetching a reference for more details, include [SUGGEST_FETCH: <url>] in your response`,XO="https://api.openai.com/v1/chat/completions",QO="gpt-4o-mini",rv=3e4;function sv(e){if(!e.startsWith("data: "))return null;const t=e.slice(6);if(t==="[DONE]")return null;try{return JSON.parse(t).choices?.[0]?.delta?.content??null}catch{return null}}async function ZO(e,t,n){const r=new AbortController;let s=setTimeout(()=>r.abort(),rv);function o(){clearTimeout(s),s=setTimeout(()=>r.abort(),rv)}const i=t.signal?AbortSignal.any([t.signal,r.signal]):r.signal;try{const a=await fetch(XO,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.apiKey}`},body:JSON.stringify({model:t.model??QO,messages:e,stream:!0}),signal:i});if(!a.ok){const p=await a.text();throw new Error(`OpenAI API error (${a.status}): ${p}`)}if(!a.body)throw new Error("Response body is null");const l=a.body.getReader(),u=new TextDecoder,c=[];let d="";for(;;){const{done:p,value:g}=await l.read();if(p)break;d+=u.decode(g,{stream:!0});const y=d.split(`
108
- `);d=y.pop()??"",y.forEach(_=>{const b=sv(_.trim());b&&(c.push(b),n(b),o())})}if(d.trim()){const p=sv(d.trim());p&&(c.push(p),n(p))}return c.join("")}finally{clearTimeout(s)}}const ex={class:"fixed right-0 top-0 h-full w-96 bg-gray-800 border-l border-gray-700 flex flex-col z-50 shadow-2xl"},tx={class:"flex items-center justify-between px-4 py-3 border-b border-gray-700"},nx={class:"flex gap-2"},rx=["disabled"],sx={key:0,class:"text-center text-gray-500 text-sm mt-8"},ox={key:1,class:"flex justify-start"},ix={class:"max-w-[85%] px-3 py-2 rounded-lg text-sm bg-gray-700 text-gray-200 whitespace-pre-wrap break-words"},ax={key:2,class:"flex justify-start"},lx={key:3,class:"p-2 bg-red-900/50 text-red-300 rounded text-xs"},ux={class:"border-t border-gray-700 p-3"},cx={class:"flex gap-2"},dx=["disabled"],fx={class:"flex flex-col gap-1"},px=["disabled"],hx=24e3,gx=ki({__name:"QAChat",props:{viewData:{},currentPage:{},bundleId:{}},emits:["close"],setup(e,{emit:t}){const n=e,r=t,s=be(""),o=be([]),i=be(!1),a=be(""),l=be(null),u=be(null),c=be(null),d=new Map;pt(()=>n.bundleId,(P,E)=>{E&&(a.value&&o.value.push({role:"assistant",content:a.value}),d.set(E,[...o.value])),l.value?.abort(),i.value=!1,a.value="",c.value=null,o.value=d.get(P)??[],b()});const p=xe(()=>"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");function g(P){let E=0;const w=[];for(let I=P.length-1;I>=0&&(E+=P[I].content.length,!(E>hx));I--)w.unshift(P[I]);return w}const y=xe(()=>{const P=YO(n.viewData);return{role:"system",content:`${zO}
109
-
110
- ---
111
-
112
- ${P}
113
-
114
- The user is currently viewing beat ${n.currentPage}.`}}),_=xe(()=>o.value.filter(P=>P.role!=="system"));function b(){ca(()=>{u.value&&(u.value.scrollTop=u.value.scrollHeight)})}pt(a,b);async function m(){const P=s.value.trim();if(!P||i.value)return;c.value=null;const E={role:"user",content:P};s.value="",await ca(),o.value.push(E),b(),i.value=!0,a.value="";const w=new AbortController;l.value=w;const I=[y.value,...g(o.value)];try{const L=await ZO(I,{apiKey:p.value,signal:w.signal},H=>{a.value+=H});o.value.push({role:"assistant",content:L})}catch(L){L instanceof DOMException&&L.name==="AbortError"?a.value&&o.value.push({role:"assistant",content:a.value}):c.value=L instanceof Error?L.message:"Failed to get response"}finally{i.value=!1,a.value="",l.value=null,b()}}function v(){l.value?.abort()}function A(){o.value=[],a.value="",c.value=null,d.delete(n.bundleId)}function S(P){P.isComposing||P.key==="Enter"&&!P.shiftKey&&(P.preventDefault(),m())}return Ua(()=>{l.value?.abort()}),(P,E)=>(ue(),fe("div",ex,[oe("div",tx,[E[2]||(E[2]=oe("h2",{class:"text-sm font-semibold text-white"},"Q&A Chat",-1)),oe("div",nx,[oe("button",{onClick:A,disabled:o.value.length===0&&!i.value,class:"px-2 py-1 text-xs rounded cursor-pointer transition-colors border-none bg-gray-700 text-gray-300 hover:bg-gray-600 disabled:opacity-50 disabled:cursor-not-allowed"}," Clear ",8,rx),oe("button",{onClick:E[0]||(E[0]=w=>r("close")),class:"px-2 py-1 text-xs rounded cursor-pointer transition-colors border-none bg-gray-700 text-gray-300 hover:bg-gray-600"}," Close ")])]),oe("div",{ref_key:"messagesContainer",ref:u,class:"flex-1 overflow-y-auto p-4 space-y-3"},[_.value.length===0&&!i.value?(ue(),fe("div",sx," Ask a question about this presentation. ")):Be("",!0),(ue(!0),fe(He,null,mi(_.value,(w,I)=>(ue(),fe("div",{key:I,class:Rt(["flex",w.role==="user"?"justify-end":"justify-start"])},[oe("div",{class:Rt(["max-w-[85%] px-3 py-2 rounded-lg text-sm whitespace-pre-wrap break-words",w.role==="user"?"bg-blue-600 text-white":"bg-gray-700 text-gray-200"])},Ue(w.content),3)],2))),128)),i.value&&a.value?(ue(),fe("div",ox,[oe("div",ix,[Wt(Ue(a.value)+" ",1),E[3]||(E[3]=oe("span",{class:"animate-pulse"},"|",-1))])])):Be("",!0),i.value&&!a.value?(ue(),fe("div",ax,[...E[4]||(E[4]=[oe("div",{class:"px-3 py-2 rounded-lg text-sm bg-gray-700 text-gray-400"},[oe("span",{class:"animate-pulse"},"Thinking...")],-1)])])):Be("",!0),c.value?(ue(),fe("div",lx,Ue(c.value),1)):Be("",!0)],512),oe("div",ux,[oe("div",cx,[Cr(oe("textarea",{"onUpdate:modelValue":E[1]||(E[1]=w=>s.value=w),onKeydown:S,disabled:i.value,rows:"2",class:"flex-1 bg-gray-700 border border-gray-600 text-white px-3 py-2 rounded text-sm resize-none focus:outline-none focus:border-blue-500 disabled:opacity-50",placeholder:"Ask about this presentation..."},null,40,dx),[[db,s.value]]),oe("div",fx,[i.value?(ue(),fe("button",{key:1,onClick:v,class:"px-3 py-2 rounded text-sm cursor-pointer transition-colors border-none bg-red-600 text-white hover:bg-red-700"}," Stop ")):(ue(),fe("button",{key:0,onClick:m,disabled:!s.value.trim(),class:"px-3 py-2 rounded text-sm cursor-pointer transition-colors border-none bg-blue-600 text-white hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed"}," Send ",8,px))])])])]))}}),mx={class:"min-h-screen flex flex-col bg-gray-900 text-white"},_x={class:"bg-gray-800 border-b border-gray-700"},yx={class:"flex items-center gap-6 px-6 py-3"},vx={key:0,class:"flex gap-2 flex-wrap"},bx=["onClick"],Ax={key:0,class:"flex items-center gap-6 px-6 py-2 bg-gray-750 border-t border-gray-700"},Sx={class:"flex items-center gap-2 text-sm text-gray-300"},wx=["disabled"],Ex=["value"],Tx={class:"flex items-center gap-2 text-sm text-gray-300"},Px=["disabled"],Ix=["value"],Cx={key:0,class:"text-center p-8 text-gray-400"},Rx={key:1,class:"text-center p-8 text-red-400"},Mx={key:2,class:"text-center p-8 text-gray-500"},Nx={key:3,class:"w-full max-w-5xl mx-auto"},Fx={key:0,class:"mb-4 p-4 bg-gray-800 rounded-lg"},kx={class:"flex items-center gap-4 mb-4"},Ox={class:"text-sm text-gray-300"},xx={class:"text-white font-medium"},Dx={class:"text-sm text-gray-400"},qx={class:"text-sm text-gray-400"},Lx={key:0,class:"mb-4 p-2 bg-red-900 text-red-200 rounded text-sm"},Ux={class:"flex items-center gap-4 mb-4"},Gx=["disabled"],Vx={key:2,class:"w-56 px-6 py-2 text-sm text-gray-400 flex items-center justify-center"},Bx=["disabled"],Hx=["disabled"],Jx=["disabled"],jx={class:"mt-2"},Wx={class:"text-white [--mulmo-text-bg:#1f2937] [--mulmo-text-secondary:#bbb]"},Kx=ki({__name:"App",setup(e){const t=be([]),n=be(null),r=be(!0),s=be(null),o=be(null),i=be(0),a=be("en"),l=be("en"),u=be(!1),c=be(!1),d=be(!1),p=be(null),g=be([]),y=be(new Map),_=be(new Map),b=be(!1),m=be(null),v=be(!1),A=xe(()=>(o.value?.beats?.length??0)>0),S=xe(()=>!0),P=xe(()=>{if(o.value?.lang)return o.value.lang;const Y=o.value?.beats?.[0]?.audioSources;if(Y){const Z=Object.keys(Y);return Z.includes("ja")?"ja":Z.find(ne=>ne!=="en")||Z[0]||"en"}return"en"}),E=xe({get:()=>{if(_.value.has(i.value))return _.value.get(i.value)||"";const Y=o.value?.beats?.[i.value];return Y&&(Y.multiLinguals?.[P.value]||Y.text)||""},set:Y=>{_.value.set(i.value,Y)}}),w=xe(()=>o.value?.beats?.[0]?.audioSources?Object.keys(o.value.beats[0].audioSources):["en"]),I=xe(()=>o.value?.beats?.[0]?.multiLinguals?Object.keys(o.value.beats[0].multiLinguals):["en"]),L=xe(()=>n.value?`/bundles/${n.value}`:"");pa(async()=>{try{const Y=await fetch("/api/bundles");if(!Y.ok)throw new Error("Failed to load bundles");t.value=await Y.json(),t.value.length>0&&(n.value=t.value[0].path)}catch(Y){s.value=Y instanceof Error?Y.message:"Unknown error"}finally{r.value=!1}}),pt(n,async Y=>{if(!Y){o.value=null;return}try{const Z=await fetch(`/bundles/${Y}/mulmo_view.json`);if(!Z.ok)throw new Error("Failed to load bundle data");o.value=await Z.json(),i.value=0;const ne=o.value?.beats?.[0]?.audioSources?Object.keys(o.value.beats[0].audioSources):["en"],re=o.value?.beats?.[0]?.multiLinguals?Object.keys(o.value.beats[0].multiLinguals):["en"];ne.includes(a.value)||(a.value=ne[0]||"en"),re.includes(l.value)||(l.value=re[0]||"en")}catch(Z){s.value=Z instanceof Error?Z.message:"Unknown error",o.value=null}});function H(Y){n.value=Y}function B(Y){i.value=Y}const F=xe(()=>o.value?.beats?.length||0),j=xe(()=>y.value.size),U=xe(()=>_.value.size);async function O(){if(u.value)await T(),u.value=!1;else{m.value=null;try{(await navigator.mediaDevices.getUserMedia({audio:!0})).getTracks().forEach(Z=>Z.stop()),u.value=!0,y.value=new Map,_.value=new Map}catch(Y){m.value=Y instanceof Error?Y.message:"Failed to access microphone"}}}async function R(){if(!c.value){m.value=null,g.value=[];try{const Y=await navigator.mediaDevices.getUserMedia({audio:!0}),Z=new MediaRecorder(Y,{mimeType:"audio/webm"});Z.ondataavailable=ne=>{ne.data.size>0&&g.value.push(ne.data)},Z.onstop=()=>{const ne=new Blob(g.value,{type:"audio/webm"});y.value.set(i.value,ne),Y.getTracks().forEach(re=>re.stop())},p.value=Z,Z.start(),c.value=!0}catch(Y){m.value=Y instanceof Error?Y.message:"Failed to start recording"}}}async function T(){if(!c.value||!p.value)return;const Y=i.value;return new Promise(Z=>{p.value?(p.value.onstop=async()=>{const ne=new Blob(g.value,{type:"audio/webm"});y.value.set(Y,ne),p.value?.stream.getTracks().forEach(re=>re.stop()),c.value=!1,p.value=null,await M(Y,ne),Z()},p.value.stop()):Z()})}async function M(Y,Z){d.value=!0,m.value=null;try{const ne=await V(Z),Ae=await(await fetch("/api/transcribe",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({audioBase64:ne,lang:P.value})})).json();if(Ae.success&&Ae.text){const le=E.value,we=le?`${le}
115
- ${Ae.text}`:Ae.text;_.value.set(Y,we)}else m.value=Ae.error||"Transcription failed"}catch(ne){m.value=ne instanceof Error?ne.message:"Transcription failed"}finally{d.value=!1}}async function k(){await T(),i.value<F.value-1&&i.value++}async function G(){await T(),i.value>0&&i.value--}function V(Y){return new Promise((Z,ne)=>{const re=new FileReader;re.onloadend=()=>{const Ae=re.result.split(",")[1];Z(Ae)},re.onerror=ne,re.readAsDataURL(Y)})}async function W(){if(!(!n.value||y.value.size===0&&_.value.size===0)){b.value=!0,m.value=null;try{const Y=new Set;y.value.forEach((ne,re)=>Y.add(re)),_.value.forEach((ne,re)=>Y.add(re));for(const ne of Y){const re=o.value?.beats?.[ne],Ae=re?.multiLinguals?.[P.value]||re?.text||"",le=_.value.get(ne)??Ae;if(y.value.has(ne)){const we=y.value.get(ne),ee=await V(we),D=await(await fetch("/api/save-beat-text",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({bundlePath:n.value,beatIndex:ne,langKey:P.value,audioBase64:ee,text:le})})).json();if(!D.success)throw new Error(D.error||`Failed to save beat ${ne+1}`)}else{const ee=await(await fetch("/api/save-beat-text",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({bundlePath:n.value,beatIndex:ne,langKey:P.value,text:le})})).json();if(!ee.success)throw new Error(ee.error||`Failed to save text for beat ${ne+1}`)}}const Z=await fetch(`/bundles/${n.value}/mulmo_view.json`);Z.ok&&(o.value=await Z.json()),u.value=!1,y.value=new Map,_.value=new Map,a.value=P.value,l.value=P.value}catch(Y){m.value=Y instanceof Error?Y.message:"Failed to save recordings"}finally{b.value=!1}}}function X(){y.value=new Map,_.value=new Map,u.value=!1}return(Y,Z)=>(ue(),fe("div",mx,[oe("header",_x,[oe("div",yx,[Z[7]||(Z[7]=oe("h1",{class:"text-lg font-semibold whitespace-nowrap"},"MulmoViewer Preview",-1)),t.value.length>0?(ue(),fe("nav",vx,[(ue(!0),fe(He,null,mi(t.value,ne=>(ue(),fe("button",{key:ne.path,class:Rt(["px-3 py-1.5 rounded text-sm cursor-pointer transition-colors border-none",n.value===ne.path?"bg-blue-600 text-white":"bg-gray-700 text-gray-300 hover:bg-gray-600"]),onClick:re=>H(ne.path)},Ue(ne.name),11,bx))),128))])):Be("",!0)]),o.value?(ue(),fe("div",Ax,[oe("label",Sx,[Z[8]||(Z[8]=Wt(" Audio: ",-1)),Cr(oe("select",{"onUpdate:modelValue":Z[0]||(Z[0]=ne=>a.value=ne),class:"bg-gray-700 border border-gray-600 text-white px-2 py-1 rounded text-sm cursor-pointer hover:bg-gray-600",disabled:u.value},[(ue(!0),fe(He,null,mi(w.value,ne=>(ue(),fe("option",{key:ne,value:ne},Ue(ne.toUpperCase()),9,Ex))),128))],8,wx),[[Uf,a.value]])]),oe("label",Tx,[Z[9]||(Z[9]=Wt(" Text: ",-1)),Cr(oe("select",{"onUpdate:modelValue":Z[1]||(Z[1]=ne=>l.value=ne),class:"bg-gray-700 border border-gray-600 text-white px-2 py-1 rounded text-sm cursor-pointer hover:bg-gray-600",disabled:u.value},[(ue(!0),fe(He,null,mi(I.value,ne=>(ue(),fe("option",{key:ne,value:ne},Ue(ne.toUpperCase()),9,Ix))),128))],8,Px),[[Uf,l.value]])]),Z[10]||(Z[10]=oe("div",{class:"flex-1"},null,-1)),A.value&&S.value?(ue(),fe("button",{key:0,onClick:Z[2]||(Z[2]=ne=>v.value=!v.value),class:Rt(["px-3 py-1.5 rounded text-sm cursor-pointer transition-colors border-none",v.value?"bg-purple-600 text-white hover:bg-purple-700":"bg-purple-500 text-white hover:bg-purple-600"])}," Q&A Chat ",2)):Be("",!0),oe("button",{onClick:O,class:Rt(["px-3 py-1.5 rounded text-sm cursor-pointer transition-colors border-none",u.value?"bg-red-600 text-white hover:bg-red-700":"bg-green-600 text-white hover:bg-green-700"])},Ue(u.value?"Exit Edit Mode":"Edit Mode"),3)])):Be("",!0)]),oe("main",{class:Rt(["flex-1 flex items-start justify-center p-4 transition-[margin]",v.value?"mr-96":""])},[r.value?(ue(),fe("div",Cx,"Loading bundles...")):s.value?(ue(),fe("div",Rx,Ue(s.value),1)):t.value.length===0?(ue(),fe("div",Mx,[...Z[11]||(Z[11]=[Wt(" No bundles found in output/ directory. ",-1),oe("p",{class:"mt-2"},[Wt(" Run "),oe("code",{class:"bg-gray-800 px-2 py-1 rounded font-mono text-sm"},"yarn run cli bundle <file>"),Wt(" to generate a bundle. ")],-1)])])):o.value?(ue(),fe("div",Nx,[u.value?(ue(),fe("div",Fx,[oe("div",kx,[oe("span",Ox,[Z[12]||(Z[12]=Wt(" Lang: ",-1)),oe("span",xx,Ue(P.value.toUpperCase()),1)]),oe("span",Dx," Beat "+Ue(i.value+1)+" / "+Ue(F.value),1),oe("span",qx," Edited: "+Ue(U.value),1)]),m.value?(ue(),fe("div",Lx,Ue(m.value),1)):Be("",!0),oe("div",Ux,[oe("button",{onClick:G,disabled:i.value===0||c.value||d.value,class:"px-4 py-2 rounded text-sm cursor-pointer transition-colors border-none disabled:opacity-50 disabled:cursor-not-allowed bg-gray-600 text-white hover:bg-gray-500"}," Prev ",8,Gx),!c.value&&!d.value?(ue(),fe("button",{key:0,onClick:R,class:"w-56 px-6 py-2 rounded text-sm cursor-pointer transition-colors border-none bg-red-600 text-white hover:bg-red-700 flex items-center justify-center gap-2"},[...Z[13]||(Z[13]=[oe("span",{class:"w-3 h-3 bg-white rounded-full"},null,-1),Wt(" Voice Input ",-1)])])):c.value?(ue(),fe("button",{key:1,onClick:T,class:"w-56 px-6 py-2 rounded text-sm cursor-pointer transition-colors border-none bg-gray-600 text-white hover:bg-gray-500 flex items-center justify-center gap-2"},[...Z[14]||(Z[14]=[oe("span",{class:"w-3 h-3 bg-red-500 rounded-sm animate-pulse"},null,-1),Wt(" Stop ",-1)])])):(ue(),fe("span",Vx," Transcribing... ")),oe("button",{onClick:k,disabled:i.value>=F.value-1||c.value||d.value,class:"px-4 py-2 rounded text-sm cursor-pointer transition-colors border-none disabled:opacity-50 disabled:cursor-not-allowed bg-gray-600 text-white hover:bg-gray-500"}," Next ",8,Bx),Z[15]||(Z[15]=oe("div",{class:"flex-1"},null,-1)),oe("button",{onClick:X,disabled:b.value||c.value||d.value,class:"px-4 py-2 rounded text-sm cursor-pointer transition-colors border-none bg-gray-600 text-white hover:bg-gray-500"}," Discard ",8,Hx),oe("button",{onClick:W,disabled:j.value===0&&U.value===0||b.value||c.value||d.value,class:"px-4 py-2 rounded text-sm cursor-pointer transition-colors border-none disabled:opacity-50 disabled:cursor-not-allowed bg-blue-600 text-white hover:bg-blue-700"},Ue(b.value?"Saving...":`Save All (${U.value})`),9,Jx)]),oe("div",jx,[Z[16]||(Z[16]=oe("label",{class:"block text-sm text-gray-400 mb-1"}," Text (editable - voice input appends): ",-1)),Cr(oe("textarea",{"onUpdate:modelValue":Z[3]||(Z[3]=ne=>E.value=ne),rows:"4",class:"w-full bg-gray-700 border border-gray-600 text-white px-3 py-2 rounded text-sm resize-vertical focus:outline-none focus:border-blue-500",placeholder:"Text will appear here after recording..."},null,512),[[db,E.value]])])])):Be("",!0),oe("div",Wx,[(ue(),Ur(Dd(uT),{key:u.value?`recording-${i.value}`:"viewer","data-set":o.value,"base-path":L.value,"init-page":i.value,"audio-lang":a.value,"onUpdate:audioLang":Z[4]||(Z[4]=ne=>a.value=ne),"text-lang":l.value,"onUpdate:textLang":Z[5]||(Z[5]=ne=>l.value=ne),"auto-play":!1,onUpdatedPage:B},null,8,["data-set","base-path","init-page","audio-lang","text-lang"]))])])):Be("",!0)],2),o.value?Cr((ue(),Ur(gx,{key:0,"view-data":o.value,"current-page":i.value,"bundle-id":n.value??"",onClose:Z[6]||(Z[6]=ne=>v.value=!1)},null,8,["view-data","current-page","bundle-id"])),[[cb,v.value]]):Be("",!0)]))}});mE(Kx).mount("#app");