@ax-llm/ax 15.1.1 → 16.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.global.js CHANGED
@@ -1,67 +1,67 @@
1
- "use strict";var ax=(()=>{var ju=Object.create;var Sr=Object.defineProperty;var zu=Object.getOwnPropertyDescriptor;var qu=Object.getOwnPropertyNames;var Hu=Object.getPrototypeOf,Ku=Object.prototype.hasOwnProperty;var Vu=(s=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(s,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):s)(function(s){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var Or=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),Wu=(s,e)=>{for(var t in e)Sr(s,t,{get:e[t],enumerable:!0})},Di=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of qu(e))!Ku.call(s,r)&&r!==t&&Sr(s,r,{get:()=>e[r],enumerable:!(n=zu(e,r))||n.enumerable});return s};var $n=(s,e,t)=>(t=s!=null?ju(Hu(s)):{},Di(e||!s||!s.__esModule?Sr(t,"default",{value:s,enumerable:!0}):t,s)),Ju=s=>Di(Sr({},"__esModule",{value:!0}),s);var Pl=Or((ai,li)=>{"use strict";(function(s,e){typeof ai=="object"&&typeof li<"u"?li.exports=e():typeof define=="function"&&define.amd?define(e):(s=typeof globalThis<"u"?globalThis:s||self).dayjs=e()})(ai,function(){"use strict";var s=1e3,e=6e4,t=36e5,n="millisecond",r="second",o="minute",i="hour",a="day",l="week",u="month",c="quarter",p="year",d="date",m="Invalid Date",g=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,f=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,h={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(I){var v=["th","st","nd","rd"],T=I%100;return"["+I+(v[(T-20)%10]||v[T]||v[0])+"]"}},x=function(I,v,T){var w=String(I);return!w||w.length>=v?I:""+Array(v+1-w.length).join(T)+I},A={s:x,z:function(I){var v=-I.utcOffset(),T=Math.abs(v),w=Math.floor(T/60),C=T%60;return(v<=0?"+":"-")+x(w,2,"0")+":"+x(C,2,"0")},m:function I(v,T){if(v.date()<T.date())return-I(T,v);var w=12*(T.year()-v.year())+(T.month()-v.month()),C=v.clone().add(w,u),E=T-C<0,_=v.clone().add(w+(E?-1:1),u);return+(-(w+(T-C)/(E?C-_:_-C))||0)},a:function(I){return I<0?Math.ceil(I)||0:Math.floor(I)},p:function(I){return{M:u,y:p,w:l,d:a,D:d,h:i,m:o,s:r,ms:n,Q:c}[I]||String(I||"").toLowerCase().replace(/s$/,"")},u:function(I){return I===void 0}},y="en",b={};b[y]=h;var k="$isDayjsObject",S=function(I){return I instanceof F||!(!I||!I[k])},M=function I(v,T,w){var C;if(!v)return y;if(typeof v=="string"){var E=v.toLowerCase();b[E]&&(C=E),T&&(b[E]=T,C=E);var _=v.split("-");if(!C&&_.length>1)return I(_[0])}else{var $=v.name;b[$]=v,C=$}return!w&&C&&(y=C),C||!w&&y},R=function(I,v){if(S(I))return I.clone();var T=typeof v=="object"?v:{};return T.date=I,T.args=arguments,new F(T)},O=A;O.l=M,O.i=S,O.w=function(I,v){return R(I,{locale:v.$L,utc:v.$u,x:v.$x,$offset:v.$offset})};var F=function(){function I(T){this.$L=M(T.locale,null,!0),this.parse(T),this.$x=this.$x||T.x||{},this[k]=!0}var v=I.prototype;return v.parse=function(T){this.$d=function(w){var C=w.date,E=w.utc;if(C===null)return new Date(NaN);if(O.u(C))return new Date;if(C instanceof Date)return new Date(C);if(typeof C=="string"&&!/Z$/i.test(C)){var _=C.match(g);if(_){var $=_[2]-1||0,L=(_[7]||"0").substring(0,3);return E?new Date(Date.UTC(_[1],$,_[3]||1,_[4]||0,_[5]||0,_[6]||0,L)):new Date(_[1],$,_[3]||1,_[4]||0,_[5]||0,_[6]||0,L)}}return new Date(C)}(T),this.init()},v.init=function(){var T=this.$d;this.$y=T.getFullYear(),this.$M=T.getMonth(),this.$D=T.getDate(),this.$W=T.getDay(),this.$H=T.getHours(),this.$m=T.getMinutes(),this.$s=T.getSeconds(),this.$ms=T.getMilliseconds()},v.$utils=function(){return O},v.isValid=function(){return this.$d.toString()!==m},v.isSame=function(T,w){var C=R(T);return this.startOf(w)<=C&&C<=this.endOf(w)},v.isAfter=function(T,w){return R(T)<this.startOf(w)},v.isBefore=function(T,w){return this.endOf(w)<R(T)},v.$g=function(T,w,C){return O.u(T)?this[w]:this.set(C,T)},v.unix=function(){return Math.floor(this.valueOf()/1e3)},v.valueOf=function(){return this.$d.getTime()},v.startOf=function(T,w){var C=this,E=!!O.u(w)||w,_=O.p(T),$=function(ye,Z){var Ae=O.w(C.$u?Date.UTC(C.$y,Z,ye):new Date(C.$y,Z,ye),C);return E?Ae:Ae.endOf(a)},L=function(ye,Z){return O.w(C.toDate()[ye].apply(C.toDate("s"),(E?[0,0,0,0]:[23,59,59,999]).slice(Z)),C)},D=this.$W,q=this.$M,H=this.$D,ce="set"+(this.$u?"UTC":"");switch(_){case p:return E?$(1,0):$(31,11);case u:return E?$(1,q):$(0,q+1);case l:var ne=this.$locale().weekStart||0,xe=(D<ne?D+7:D)-ne;return $(E?H-xe:H+(6-xe),q);case a:case d:return L(ce+"Hours",0);case i:return L(ce+"Minutes",1);case o:return L(ce+"Seconds",2);case r:return L(ce+"Milliseconds",3);default:return this.clone()}},v.endOf=function(T){return this.startOf(T,!1)},v.$set=function(T,w){var C,E=O.p(T),_="set"+(this.$u?"UTC":""),$=(C={},C[a]=_+"Date",C[d]=_+"Date",C[u]=_+"Month",C[p]=_+"FullYear",C[i]=_+"Hours",C[o]=_+"Minutes",C[r]=_+"Seconds",C[n]=_+"Milliseconds",C)[E],L=E===a?this.$D+(w-this.$W):w;if(E===u||E===p){var D=this.clone().set(d,1);D.$d[$](L),D.init(),this.$d=D.set(d,Math.min(this.$D,D.daysInMonth())).$d}else $&&this.$d[$](L);return this.init(),this},v.set=function(T,w){return this.clone().$set(T,w)},v.get=function(T){return this[O.p(T)]()},v.add=function(T,w){var C,E=this;T=Number(T);var _=O.p(w),$=function(q){var H=R(E);return O.w(H.date(H.date()+Math.round(q*T)),E)};if(_===u)return this.set(u,this.$M+T);if(_===p)return this.set(p,this.$y+T);if(_===a)return $(1);if(_===l)return $(7);var L=(C={},C[o]=e,C[i]=t,C[r]=s,C)[_]||1,D=this.$d.getTime()+T*L;return O.w(D,this)},v.subtract=function(T,w){return this.add(-1*T,w)},v.format=function(T){var w=this,C=this.$locale();if(!this.isValid())return C.invalidDate||m;var E=T||"YYYY-MM-DDTHH:mm:ssZ",_=O.z(this),$=this.$H,L=this.$m,D=this.$M,q=C.weekdays,H=C.months,ce=C.meridiem,ne=function(Z,Ae,ge,ke){return Z&&(Z[Ae]||Z(w,E))||ge[Ae].slice(0,ke)},xe=function(Z){return O.s($%12||12,Z,"0")},ye=ce||function(Z,Ae,ge){var ke=Z<12?"AM":"PM";return ge?ke.toLowerCase():ke};return E.replace(f,function(Z,Ae){return Ae||function(ge){switch(ge){case"YY":return String(w.$y).slice(-2);case"YYYY":return O.s(w.$y,4,"0");case"M":return D+1;case"MM":return O.s(D+1,2,"0");case"MMM":return ne(C.monthsShort,D,H,3);case"MMMM":return ne(H,D);case"D":return w.$D;case"DD":return O.s(w.$D,2,"0");case"d":return String(w.$W);case"dd":return ne(C.weekdaysMin,w.$W,q,2);case"ddd":return ne(C.weekdaysShort,w.$W,q,3);case"dddd":return q[w.$W];case"H":return String($);case"HH":return O.s($,2,"0");case"h":return xe(1);case"hh":return xe(2);case"a":return ye($,L,!0);case"A":return ye($,L,!1);case"m":return String(L);case"mm":return O.s(L,2,"0");case"s":return String(w.$s);case"ss":return O.s(w.$s,2,"0");case"SSS":return O.s(w.$ms,3,"0");case"Z":return _}return null}(Z)||_.replace(":","")})},v.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},v.diff=function(T,w,C){var E,_=this,$=O.p(w),L=R(T),D=(L.utcOffset()-this.utcOffset())*e,q=this-L,H=function(){return O.m(_,L)};switch($){case p:E=H()/12;break;case u:E=H();break;case c:E=H()/3;break;case l:E=(q-D)/6048e5;break;case a:E=(q-D)/864e5;break;case i:E=q/t;break;case o:E=q/e;break;case r:E=q/s;break;default:E=q}return C?E:O.a(E)},v.daysInMonth=function(){return this.endOf(u).$D},v.$locale=function(){return b[this.$L]},v.locale=function(T,w){if(!T)return this.$L;var C=this.clone(),E=M(T,w,!0);return E&&(C.$L=E),C},v.clone=function(){return O.w(this.$d,this)},v.toDate=function(){return new Date(this.valueOf())},v.toJSON=function(){return this.isValid()?this.toISOString():null},v.toISOString=function(){return this.$d.toISOString()},v.toString=function(){return this.$d.toUTCString()},I}(),P=F.prototype;return R.prototype=P,[["$ms",n],["$s",r],["$m",o],["$H",i],["$W",a],["$M",u],["$y",p],["$D",d]].forEach(function(I){P[I[1]]=function(v){return this.$g(v,I[0],I[1])}}),R.extend=function(I,v){return I.$i||(I(v,F,R),I.$i=!0),R},R.locale=M,R.isDayjs=S,R.unix=function(I){return R(1e3*I)},R.en=b[y],R.Ls=b,R.p={},R})});var Fl=Or((ui,ci)=>{"use strict";(function(s,e){typeof ui=="object"&&typeof ci<"u"?ci.exports=e():typeof define=="function"&&define.amd?define(e):(s=typeof globalThis<"u"?globalThis:s||self).dayjs_plugin_customParseFormat=e()})(ui,function(){"use strict";var s={LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"},e=/(\[[^[]*\])|([-_:/.,()\s]+)|(A|a|Q|YYYY|YY?|ww?|MM?M?M?|Do|DD?|hh?|HH?|mm?|ss?|S{1,3}|z|ZZ?)/g,t=/\d/,n=/\d\d/,r=/\d\d?/,o=/\d*[^-_:/,()\s\d]+/,i={},a=function(g){return(g=+g)+(g>68?1900:2e3)},l=function(g){return function(f){this[g]=+f}},u=[/[+-]\d\d:?(\d\d)?|Z/,function(g){(this.zone||(this.zone={})).offset=function(f){if(!f||f==="Z")return 0;var h=f.match(/([+-]|\d\d)/g),x=60*h[1]+(+h[2]||0);return x===0?0:h[0]==="+"?-x:x}(g)}],c=function(g){var f=i[g];return f&&(f.indexOf?f:f.s.concat(f.f))},p=function(g,f){var h,x=i.meridiem;if(x){for(var A=1;A<=24;A+=1)if(g.indexOf(x(A,0,f))>-1){h=A>12;break}}else h=g===(f?"pm":"PM");return h},d={A:[o,function(g){this.afternoon=p(g,!1)}],a:[o,function(g){this.afternoon=p(g,!0)}],Q:[t,function(g){this.month=3*(g-1)+1}],S:[t,function(g){this.milliseconds=100*+g}],SS:[n,function(g){this.milliseconds=10*+g}],SSS:[/\d{3}/,function(g){this.milliseconds=+g}],s:[r,l("seconds")],ss:[r,l("seconds")],m:[r,l("minutes")],mm:[r,l("minutes")],H:[r,l("hours")],h:[r,l("hours")],HH:[r,l("hours")],hh:[r,l("hours")],D:[r,l("day")],DD:[n,l("day")],Do:[o,function(g){var f=i.ordinal,h=g.match(/\d+/);if(this.day=h[0],f)for(var x=1;x<=31;x+=1)f(x).replace(/\[|\]/g,"")===g&&(this.day=x)}],w:[r,l("week")],ww:[n,l("week")],M:[r,l("month")],MM:[n,l("month")],MMM:[o,function(g){var f=c("months"),h=(c("monthsShort")||f.map(function(x){return x.slice(0,3)})).indexOf(g)+1;if(h<1)throw new Error;this.month=h%12||h}],MMMM:[o,function(g){var f=c("months").indexOf(g)+1;if(f<1)throw new Error;this.month=f%12||f}],Y:[/[+-]?\d+/,l("year")],YY:[n,function(g){this.year=a(g)}],YYYY:[/\d{4}/,l("year")],Z:u,ZZ:u};function m(g){var f,h;f=g,h=i&&i.formats;for(var x=(g=f.replace(/(\[[^\]]+])|(LTS?|l{1,4}|L{1,4})/g,function(R,O,F){var P=F&&F.toUpperCase();return O||h[F]||s[F]||h[P].replace(/(\[[^\]]+])|(MMMM|MM|DD|dddd)/g,function(I,v,T){return v||T.slice(1)})})).match(e),A=x.length,y=0;y<A;y+=1){var b=x[y],k=d[b],S=k&&k[0],M=k&&k[1];x[y]=M?{regex:S,parser:M}:b.replace(/^\[|\]$/g,"")}return function(R){for(var O={},F=0,P=0;F<A;F+=1){var I=x[F];if(typeof I=="string")P+=I.length;else{var v=I.regex,T=I.parser,w=R.slice(P),C=v.exec(w)[0];T.call(O,C),R=R.replace(C,"")}}return function(E){var _=E.afternoon;if(_!==void 0){var $=E.hours;_?$<12&&(E.hours+=12):$===12&&(E.hours=0),delete E.afternoon}}(O),O}}return function(g,f,h){h.p.customParseFormat=!0,g&&g.parseTwoDigitYear&&(a=g.parseTwoDigitYear);var x=f.prototype,A=x.parse;x.parse=function(y){var b=y.date,k=y.utc,S=y.args;this.$u=k;var M=S[1];if(typeof M=="string"){var R=S[2]===!0,O=S[3]===!0,F=R||O,P=S[2];O&&(P=S[2]),i=this.$locale(),!R&&P&&(i=h.Ls[P]),this.$d=function(w,C,E,_){try{if(["x","X"].indexOf(C)>-1)return new Date((C==="X"?1e3:1)*w);var $=m(C)(w),L=$.year,D=$.month,q=$.day,H=$.hours,ce=$.minutes,ne=$.seconds,xe=$.milliseconds,ye=$.zone,Z=$.week,Ae=new Date,ge=q||(L||D?1:Ae.getDate()),ke=L||Ae.getFullYear(),he=0;L&&!D||(he=D>0?D-1:Ae.getMonth());var ve,V=H||0,re=ce||0,U=ne||0,z=xe||0;return ye?new Date(Date.UTC(ke,he,ge,V,re,U,z+60*ye.offset*1e3)):E?new Date(Date.UTC(ke,he,ge,V,re,U,z)):(ve=new Date(ke,he,ge,V,re,U,z),Z&&(ve=_(ve).week(Z).toDate()),ve)}catch{return new Date("")}}(b,M,k,h),this.init(),P&&P!==!0&&(this.$L=this.locale(P).$L),F&&b!=this.format(M)&&(this.$d=new Date("")),i={}}else if(M instanceof Array)for(var I=M.length,v=1;v<=I;v+=1){S[1]=M[v-1];var T=h.apply(this,S);if(T.isValid()){this.$d=T.$d,this.$L=T.$L,this.init();break}v===I&&(this.$d=new Date(""))}else A.call(this,y)}}})});var _l=Or((pi,di)=>{"use strict";(function(s,e){typeof pi=="object"&&typeof di<"u"?di.exports=e():typeof define=="function"&&define.amd?define(e):(s=typeof globalThis<"u"?globalThis:s||self).dayjs_plugin_timezone=e()})(pi,function(){"use strict";var s={year:0,month:1,day:2,hour:3,minute:4,second:5},e={};return function(t,n,r){var o,i=function(c,p,d){d===void 0&&(d={});var m=new Date(c),g=function(f,h){h===void 0&&(h={});var x=h.timeZoneName||"short",A=f+"|"+x,y=e[A];return y||(y=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:f,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",timeZoneName:x}),e[A]=y),y}(p,d);return g.formatToParts(m)},a=function(c,p){for(var d=i(c,p),m=[],g=0;g<d.length;g+=1){var f=d[g],h=f.type,x=f.value,A=s[h];A>=0&&(m[A]=parseInt(x,10))}var y=m[3],b=y===24?0:y,k=m[0]+"-"+m[1]+"-"+m[2]+" "+b+":"+m[4]+":"+m[5]+":000",S=+c;return(r.utc(k).valueOf()-(S-=S%1e3))/6e4},l=n.prototype;l.tz=function(c,p){c===void 0&&(c=o);var d,m=this.utcOffset(),g=this.toDate(),f=g.toLocaleString("en-US",{timeZone:c}),h=Math.round((g-new Date(f))/1e3/60),x=15*-Math.round(g.getTimezoneOffset()/15)-h;if(!Number(x))d=this.utcOffset(0,p);else if(d=r(f,{locale:this.$L}).$set("millisecond",this.$ms).utcOffset(x,!0),p){var A=d.utcOffset();d=d.add(m-A,"minute")}return d.$x.$timezone=c,d},l.offsetName=function(c){var p=this.$x.$timezone||r.tz.guess(),d=i(this.valueOf(),p,{timeZoneName:c}).find(function(m){return m.type.toLowerCase()==="timezonename"});return d&&d.value};var u=l.startOf;l.startOf=function(c,p){if(!this.$x||!this.$x.$timezone)return u.call(this,c,p);var d=r(this.format("YYYY-MM-DD HH:mm:ss:SSS"),{locale:this.$L});return u.call(d,c,p).tz(this.$x.$timezone,!0)},r.tz=function(c,p,d){var m=d&&p,g=d||p||o,f=a(+r(),g);if(typeof c!="string")return r(c).tz(g);var h=function(b,k,S){var M=b-60*k*1e3,R=a(M,S);if(k===R)return[M,k];var O=a(M-=60*(R-k)*1e3,S);return R===O?[M,R]:[b-60*Math.min(R,O)*1e3,Math.max(R,O)]}(r.utc(c,m).valueOf(),f,g),x=h[0],A=h[1],y=r(x).utcOffset(A);return y.$x.$timezone=g,y},r.tz.guess=function(){return Intl.DateTimeFormat().resolvedOptions().timeZone},r.tz.setDefault=function(c){o=c}}})});var $l=Or((mi,gi)=>{"use strict";(function(s,e){typeof mi=="object"&&typeof gi<"u"?gi.exports=e():typeof define=="function"&&define.amd?define(e):(s=typeof globalThis<"u"?globalThis:s||self).dayjs_plugin_utc=e()})(mi,function(){"use strict";var s="minute",e=/[+-]\d\d(?::?\d\d)?/g,t=/([+-]|\d\d)/g;return function(n,r,o){var i=r.prototype;o.utc=function(m){var g={date:m,utc:!0,args:arguments};return new r(g)},i.utc=function(m){var g=o(this.toDate(),{locale:this.$L,utc:!0});return m?g.add(this.utcOffset(),s):g},i.local=function(){return o(this.toDate(),{locale:this.$L,utc:!1})};var a=i.parse;i.parse=function(m){m.utc&&(this.$u=!0),this.$utils().u(m.$offset)||(this.$offset=m.$offset),a.call(this,m)};var l=i.init;i.init=function(){if(this.$u){var m=this.$d;this.$y=m.getUTCFullYear(),this.$M=m.getUTCMonth(),this.$D=m.getUTCDate(),this.$W=m.getUTCDay(),this.$H=m.getUTCHours(),this.$m=m.getUTCMinutes(),this.$s=m.getUTCSeconds(),this.$ms=m.getUTCMilliseconds()}else l.call(this)};var u=i.utcOffset;i.utcOffset=function(m,g){var f=this.$utils().u;if(f(m))return this.$u?0:f(this.$offset)?u.call(this):this.$offset;if(typeof m=="string"&&(m=function(y){y===void 0&&(y="");var b=y.match(e);if(!b)return null;var k=(""+b[0]).match(t)||["-",0,0],S=k[0],M=60*+k[1]+ +k[2];return M===0?0:S==="+"?M:-M}(m),m===null))return this;var h=Math.abs(m)<=16?60*m:m,x=this;if(g)return x.$offset=h,x.$u=m===0,x;if(m!==0){var A=this.$u?this.toDate().getTimezoneOffset():-1*this.utcOffset();(x=this.local().add(h+A,s)).$offset=h,x.$x.$localOffset=A}else x=this.utc();return x};var c=i.format;i.format=function(m){var g=m||(this.$u?"YYYY-MM-DDTHH:mm:ss[Z]":"");return c.call(this,g)},i.valueOf=function(){var m=this.$utils().u(this.$offset)?0:this.$offset+(this.$x.$localOffset||this.$d.getTimezoneOffset());return this.$d.valueOf()-6e4*m},i.isUTC=function(){return!!this.$u},i.toISOString=function(){return this.toDate().toISOString()},i.toString=function(){return this.toDate().toUTCString()};var p=i.toDate;i.toDate=function(m){return m==="s"&&this.$offset?o(this.format("YYYY-MM-DD HH:mm:ss:SSS")).toDate():p.call(this)};var d=i.diff;i.diff=function(m,g,f){if(m&&this.$u===m.$u)return d.call(this,m,g,f);var h=this.local(),x=o(m).local();return d.call(h,x,g,f)}}})});var Hp={};Wu(Hp,{AxACE:()=>Yo,AxACEOptimizedProgram:()=>br,AxAI:()=>sr,AxAIAnthropic:()=>Kt,AxAIAnthropicModel:()=>zn,AxAIAnthropicVertexModel:()=>qn,AxAIAzureOpenAI:()=>Qt,AxAICohere:()=>Zt,AxAICohereEmbedModel:()=>Wn,AxAICohereModel:()=>Vn,AxAIDeepSeek:()=>Xt,AxAIDeepSeekModel:()=>Jn,AxAIGoogleGemini:()=>en,AxAIGoogleGeminiEmbedModel:()=>Jr,AxAIGoogleGeminiEmbedTypes:()=>Ds,AxAIGoogleGeminiModel:()=>Yn,AxAIGoogleGeminiSafetyCategory:()=>Yr,AxAIGoogleGeminiSafetyThreshold:()=>Qr,AxAIGrok:()=>mn,AxAIGrokEmbedModels:()=>Ys,AxAIGrokModel:()=>or,AxAIGroq:()=>nn,AxAIGroqModel:()=>Qn,AxAIHuggingFace:()=>rn,AxAIHuggingFaceModel:()=>no,AxAIMistral:()=>on,AxAIMistralEmbedModels:()=>js,AxAIMistralModel:()=>Zn,AxAIOllama:()=>sn,AxAIOpenAI:()=>Yt,AxAIOpenAIBase:()=>Te,AxAIOpenAIEmbedModel:()=>Vt,AxAIOpenAIModel:()=>Kn,AxAIOpenAIResponses:()=>ln,AxAIOpenAIResponsesBase:()=>Xn,AxAIOpenAIResponsesImpl:()=>an,AxAIOpenAIResponsesModel:()=>Wt,AxAIOpenRouter:()=>un,AxAIRefusalError:()=>fe,AxAIReka:()=>cn,AxAIRekaModel:()=>tr,AxAIServiceAbortedError:()=>Ut,AxAIServiceAuthenticationError:()=>At,AxAIServiceError:()=>Fe,AxAIServiceNetworkError:()=>De,AxAIServiceResponseError:()=>xt,AxAIServiceStatusError:()=>Ke,AxAIServiceStreamTerminatedError:()=>Ye,AxAIServiceTimeoutError:()=>ot,AxAITogether:()=>pn,AxAIWebLLM:()=>dn,AxAIWebLLMModel:()=>rr,AxAgent:()=>wr,AxApacheTika:()=>Uo,AxAssertionError:()=>pt,AxBalancer:()=>qr,AxBaseAI:()=>we,AxBaseOptimizer:()=>je,AxBootstrapFewShot:()=>vn,AxContentProcessingError:()=>st,AxDB:()=>fo,AxDBBase:()=>Ze,AxDBCloudflare:()=>gn,AxDBManager:()=>xo,AxDBMemory:()=>Ot,AxDBPinecone:()=>hn,AxDBWeaviate:()=>fn,AxDefaultCostTracker:()=>fr,AxDefaultResultReranker:()=>Go,AxDockerSession:()=>ns,AxEmbeddingAdapter:()=>rs,AxEvalUtil:()=>pu,AxFlow:()=>Tr,AxFlowDependencyAnalyzer:()=>Sn,AxFlowExecutionPlanner:()=>kn,AxFlowSubContextImpl:()=>Pn,AxFlowTypedSubContextImpl:()=>es,AxFluentFieldType:()=>Oe,AxFunctionError:()=>lr,AxFunctionProcessor:()=>cr,AxGEPA:()=>wn,AxGEPAFlow:()=>Qo,AxGen:()=>Ce,AxGenerateError:()=>gr,AxHFDataLoader:()=>Jo,AxInstanceRegistry:()=>bn,AxJudge:()=>Tn,AxLLMRequestTypeValues:()=>Is,AxLearn:()=>Wo,AxMCPClient:()=>os,AxMCPHTTPSSETransport:()=>as,AxMCPStreambleHTTPTransport:()=>is,AxMediaNotSupportedError:()=>Qe,AxMemory:()=>xn,AxMiPRO:()=>Xo,AxMockAIService:()=>so,AxMultiServiceRouter:()=>io,AxOptimizedProgramImpl:()=>mt,AxProgram:()=>Et,AxPromptTemplate:()=>Nt,AxProviderRouter:()=>co,AxRateLimiterTokenUsage:()=>tn,AxSignature:()=>be,AxSignatureBuilder:()=>dr,AxSimpleClassifier:()=>jo,AxSimpleClassifierClass:()=>Bo,AxSpanKindValues:()=>Ts,AxStopFunctionCallException:()=>$t,AxStringUtil:()=>Lo,AxSynth:()=>Rn,AxTestPrompt:()=>zo,AxTokenLimitError:()=>Nn,AxTraceLogger:()=>Cn,agent:()=>$u,ai:()=>ll,ax:()=>_e,axAIAnthropicDefaultConfig:()=>Ms,axAIAnthropicVertexDefaultConfig:()=>Da,axAIAzureOpenAIBestConfig:()=>Ba,axAIAzureOpenAICreativeConfig:()=>Ga,axAIAzureOpenAIDefaultConfig:()=>Ps,axAIAzureOpenAIFastConfig:()=>Ua,axAICohereCreativeConfig:()=>Ka,axAICohereDefaultConfig:()=>$s,axAIDeepSeekCodeConfig:()=>Va,axAIDeepSeekDefaultConfig:()=>Ns,axAIGoogleGeminiDefaultConfig:()=>Gs,axAIGoogleGeminiDefaultCreativeConfig:()=>Ja,axAIGrokBestConfig:()=>al,axAIGrokDefaultConfig:()=>ho,axAIHuggingFaceCreativeConfig:()=>Ya,axAIHuggingFaceDefaultConfig:()=>Bs,axAIMistralBestConfig:()=>Qa,axAIMistralDefaultConfig:()=>oo,axAIOllamaDefaultConfig:()=>zs,axAIOllamaDefaultCreativeConfig:()=>Za,axAIOpenAIBestConfig:()=>Br,axAIOpenAICreativeConfig:()=>jr,axAIOpenAIDefaultConfig:()=>Ft,axAIOpenAIFastConfig:()=>zr,axAIOpenAIResponsesBestConfig:()=>Xa,axAIOpenAIResponsesCreativeConfig:()=>el,axAIOpenAIResponsesDefaultConfig:()=>er,axAIOpenRouterDefaultConfig:()=>Hs,axAIRekaBestConfig:()=>rl,axAIRekaCreativeConfig:()=>ol,axAIRekaDefaultConfig:()=>nr,axAIRekaFastConfig:()=>sl,axAITogetherDefaultConfig:()=>Vs,axAIWebLLMCreativeConfig:()=>il,axAIWebLLMDefaultConfig:()=>Js,axAnalyzeChatPromptRequirements:()=>tl,axAnalyzeRequestRequirements:()=>_t,axBaseAIDefaultConfig:()=>ie,axBaseAIDefaultCreativeConfig:()=>Se,axCheckMetricsHealth:()=>ul,axCreateDefaultColorLogger:()=>bs,axCreateDefaultOptimizerColorLogger:()=>ki,axCreateDefaultOptimizerTextLogger:()=>gu,axCreateDefaultTextLogger:()=>aa,axCreateFlowColorLogger:()=>Ir,axCreateFlowTextLogger:()=>Tu,axDefaultFlowLogger:()=>Cu,axDefaultMetricsConfig:()=>ei,axDefaultOptimizerLogger:()=>hr,axDefaultOptimizerMetricsConfig:()=>Mi,axGetCompatibilityReport:()=>ja,axGetFormatCompatibility:()=>qa,axGetMetricsConfig:()=>pl,axGetOptimizerMetricsConfig:()=>fu,axGetProvidersWithMediaSupport:()=>za,axGlobals:()=>te,axModelInfoAnthropic:()=>Hn,axModelInfoCohere:()=>Vr,axModelInfoDeepSeek:()=>Wr,axModelInfoGoogleGemini:()=>Zr,axModelInfoGrok:()=>go,axModelInfoGroq:()=>eo,axModelInfoHuggingFace:()=>to,axModelInfoMistral:()=>ro,axModelInfoOpenAI:()=>Jt,axModelInfoOpenAIResponses:()=>Ur,axModelInfoReka:()=>uo,axModelInfoTogether:()=>po,axModelInfoWebLLM:()=>mo,axProcessContentForProvider:()=>lo,axRAG:()=>Nu,axScoreProvidersForRequest:()=>Hr,axSelectOptimalProvider:()=>Kr,axSpanAttributes:()=>Y,axSpanEvents:()=>it,axUpdateMetricsConfig:()=>cl,axUpdateOptimizerMetricsConfig:()=>hu,axValidateChatRequestMessage:()=>Ht,axValidateChatResponseResult:()=>Gr,axValidateProviderCapabilities:()=>Fs,f:()=>ue,flow:()=>ts,s:()=>xu});function We({model:s,modelInfo:e,models:t}){let n=t?.find(u=>u.key===s),r=n&&"model"in n?n.model:s,o=e.find(u=>u.name===s);if(o)return o;let i=e.find(u=>u.name===r);if(i)return i;let a=r.replace(/^(anthropic\.|openai\.)/,"").replace(/-latest$/,"").replace(/-\d{8}$/,"").replace(/-v\d+:\d+$/,"").replace(/@\d{8}$/,"").replace(/-\d{2,}(-[a-zA-Z0-9-]+)?$/,"").replace(/-v\d+@\d{8}$/,"").replace(/-v\d+$/,""),l=e.find(u=>u.name===a);return l||null}var cs=(()=>{if(globalThis.crypto&&typeof globalThis.crypto.randomUUID=="function")return globalThis.crypto;throw new Error("Web Crypto API with randomUUID support not available. Requires Node.js 16+ or modern browser.")})();function Pe(){return cs.randomUUID()}async function Yu(s){let e=new TextEncoder,t=typeof s=="string"?e.encode(s):s,n=await cs.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}var us=class{data="";update(e){return this.data+=e,this}digest(e){if(e!=="hex")throw new Error("Only hex encoding is supported");let n=new TextEncoder().encode(this.data),r=0;for(let o=0;o<n.length;o++){let i=n[o];r=(r<<5)-r+i,r=r&r}return Math.abs(r).toString(16).padStart(8,"0")}async digestAsync(){return Yu(this.data)}};function Je(s){if(s!=="sha256")throw new Error("Only SHA-256 algorithm is supported");return new us}function Li(){return cs}var kr=class extends TransformStream{buffer="";currentEvent={rawData:""};dataParser;onError;constructor(e={}){super({transform:(t,n)=>this.handleChunk(t,n),flush:t=>this.handleFlush(t)}),this.dataParser=e.dataParser||JSON.parse,this.onError=e.onError||((t,n)=>{console.warn("Failed to parse event data:",t),console.log("Raw data that failed to parse:",n)})}handleChunk(e,t){this.buffer+=e,this.processBuffer(t)}handleFlush(e){this.processBuffer(e),this.currentEvent.rawData&&this.processEvent(e)}processBuffer(e){let n=this.buffer.replace(/\r\n|\r/g,`
1
+ "use strict";var ax=(()=>{var Hu=Object.create;var Or=Object.defineProperty;var Ku=Object.getOwnPropertyDescriptor;var Vu=Object.getOwnPropertyNames;var Wu=Object.getPrototypeOf,Ju=Object.prototype.hasOwnProperty;var Yu=(i=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(i,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):i)(function(i){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+i+'" is not supported')});var kr=(i,e)=>()=>(e||i((e={exports:{}}).exports,e),e.exports),Qu=(i,e)=>{for(var t in e)Or(i,t,{get:e[t],enumerable:!0})},Li=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Vu(e))!Ju.call(i,r)&&r!==t&&Or(i,r,{get:()=>e[r],enumerable:!(n=Ku(e,r))||n.enumerable});return i};var $n=(i,e,t)=>(t=i!=null?Hu(Wu(i)):{},Li(e||!i||!i.__esModule?Or(t,"default",{value:i,enumerable:!0}):t,i)),Xu=i=>Li(Or({},"__esModule",{value:!0}),i);var Nl=kr((ui,ci)=>{"use strict";(function(i,e){typeof ui=="object"&&typeof ci<"u"?ci.exports=e():typeof define=="function"&&define.amd?define(e):(i=typeof globalThis<"u"?globalThis:i||self).dayjs=e()})(ui,function(){"use strict";var i=1e3,e=6e4,t=36e5,n="millisecond",r="second",o="minute",s="hour",a="day",l="week",u="month",c="quarter",p="year",d="date",m="Invalid Date",g=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,h=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,f={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(T){var v=["th","st","nd","rd"],C=T%100;return"["+T+(v[(C-20)%10]||v[C]||v[0])+"]"}},x=function(T,v,C){var O=String(T);return!O||O.length>=v?T:""+Array(v+1-O.length).join(C)+T},A={s:x,z:function(T){var v=-T.utcOffset(),C=Math.abs(v),O=Math.floor(C/60),I=C%60;return(v<=0?"+":"-")+x(O,2,"0")+":"+x(I,2,"0")},m:function T(v,C){if(v.date()<C.date())return-T(C,v);var O=12*(C.year()-v.year())+(C.month()-v.month()),I=v.clone().add(O,u),P=C-I<0,_=v.clone().add(O+(P?-1:1),u);return+(-(O+(C-I)/(P?I-_:_-I))||0)},a:function(T){return T<0?Math.ceil(T)||0:Math.floor(T)},p:function(T){return{M:u,y:p,w:l,d:a,D:d,h:s,m:o,s:r,ms:n,Q:c}[T]||String(T||"").toLowerCase().replace(/s$/,"")},u:function(T){return T===void 0}},y="en",b={};b[y]=f;var S="$isDayjsObject",w=function(T){return T instanceof F||!(!T||!T[S])},M=function T(v,C,O){var I;if(!v)return y;if(typeof v=="string"){var P=v.toLowerCase();b[P]&&(I=P),C&&(b[P]=C,I=P);var _=v.split("-");if(!I&&_.length>1)return T(_[0])}else{var $=v.name;b[$]=v,I=$}return!O&&I&&(y=I),I||!O&&y},R=function(T,v){if(w(T))return T.clone();var C=typeof v=="object"?v:{};return C.date=T,C.args=arguments,new F(C)},k=A;k.l=M,k.i=w,k.w=function(T,v){return R(T,{locale:v.$L,utc:v.$u,x:v.$x,$offset:v.$offset})};var F=function(){function T(C){this.$L=M(C.locale,null,!0),this.parse(C),this.$x=this.$x||C.x||{},this[S]=!0}var v=T.prototype;return v.parse=function(C){this.$d=function(O){var I=O.date,P=O.utc;if(I===null)return new Date(NaN);if(k.u(I))return new Date;if(I instanceof Date)return new Date(I);if(typeof I=="string"&&!/Z$/i.test(I)){var _=I.match(g);if(_){var $=_[2]-1||0,N=(_[7]||"0").substring(0,3);return P?new Date(Date.UTC(_[1],$,_[3]||1,_[4]||0,_[5]||0,_[6]||0,N)):new Date(_[1],$,_[3]||1,_[4]||0,_[5]||0,_[6]||0,N)}}return new Date(I)}(C),this.init()},v.init=function(){var C=this.$d;this.$y=C.getFullYear(),this.$M=C.getMonth(),this.$D=C.getDate(),this.$W=C.getDay(),this.$H=C.getHours(),this.$m=C.getMinutes(),this.$s=C.getSeconds(),this.$ms=C.getMilliseconds()},v.$utils=function(){return k},v.isValid=function(){return this.$d.toString()!==m},v.isSame=function(C,O){var I=R(C);return this.startOf(O)<=I&&I<=this.endOf(O)},v.isAfter=function(C,O){return R(C)<this.startOf(O)},v.isBefore=function(C,O){return this.endOf(O)<R(C)},v.$g=function(C,O,I){return k.u(C)?this[O]:this.set(I,C)},v.unix=function(){return Math.floor(this.valueOf()/1e3)},v.valueOf=function(){return this.$d.getTime()},v.startOf=function(C,O){var I=this,P=!!k.u(O)||O,_=k.p(C),$=function(ce,ie){var fe=k.w(I.$u?Date.UTC(I.$y,ie,ce):new Date(I.$y,ie,ce),I);return P?fe:fe.endOf(a)},N=function(ce,ie){return k.w(I.toDate()[ce].apply(I.toDate("s"),(P?[0,0,0,0]:[23,59,59,999]).slice(ie)),I)},L=this.$W,z=this.$M,H=this.$D,te="set"+(this.$u?"UTC":"");switch(_){case p:return P?$(1,0):$(31,11);case u:return P?$(1,z):$(0,z+1);case l:var de=this.$locale().weekStart||0,be=(L<de?L+7:L)-de;return $(P?H-be:H+(6-be),z);case a:case d:return N(te+"Hours",0);case s:return N(te+"Minutes",1);case o:return N(te+"Seconds",2);case r:return N(te+"Milliseconds",3);default:return this.clone()}},v.endOf=function(C){return this.startOf(C,!1)},v.$set=function(C,O){var I,P=k.p(C),_="set"+(this.$u?"UTC":""),$=(I={},I[a]=_+"Date",I[d]=_+"Date",I[u]=_+"Month",I[p]=_+"FullYear",I[s]=_+"Hours",I[o]=_+"Minutes",I[r]=_+"Seconds",I[n]=_+"Milliseconds",I)[P],N=P===a?this.$D+(O-this.$W):O;if(P===u||P===p){var L=this.clone().set(d,1);L.$d[$](N),L.init(),this.$d=L.set(d,Math.min(this.$D,L.daysInMonth())).$d}else $&&this.$d[$](N);return this.init(),this},v.set=function(C,O){return this.clone().$set(C,O)},v.get=function(C){return this[k.p(C)]()},v.add=function(C,O){var I,P=this;C=Number(C);var _=k.p(O),$=function(z){var H=R(P);return k.w(H.date(H.date()+Math.round(z*C)),P)};if(_===u)return this.set(u,this.$M+C);if(_===p)return this.set(p,this.$y+C);if(_===a)return $(1);if(_===l)return $(7);var N=(I={},I[o]=e,I[s]=t,I[r]=i,I)[_]||1,L=this.$d.getTime()+C*N;return k.w(L,this)},v.subtract=function(C,O){return this.add(-1*C,O)},v.format=function(C){var O=this,I=this.$locale();if(!this.isValid())return I.invalidDate||m;var P=C||"YYYY-MM-DDTHH:mm:ssZ",_=k.z(this),$=this.$H,N=this.$m,L=this.$M,z=I.weekdays,H=I.months,te=I.meridiem,de=function(ie,fe,Ae,pe){return ie&&(ie[fe]||ie(O,P))||Ae[fe].slice(0,pe)},be=function(ie){return k.s($%12||12,ie,"0")},ce=te||function(ie,fe,Ae){var pe=ie<12?"AM":"PM";return Ae?pe.toLowerCase():pe};return P.replace(h,function(ie,fe){return fe||function(Ae){switch(Ae){case"YY":return String(O.$y).slice(-2);case"YYYY":return k.s(O.$y,4,"0");case"M":return L+1;case"MM":return k.s(L+1,2,"0");case"MMM":return de(I.monthsShort,L,H,3);case"MMMM":return de(H,L);case"D":return O.$D;case"DD":return k.s(O.$D,2,"0");case"d":return String(O.$W);case"dd":return de(I.weekdaysMin,O.$W,z,2);case"ddd":return de(I.weekdaysShort,O.$W,z,3);case"dddd":return z[O.$W];case"H":return String($);case"HH":return k.s($,2,"0");case"h":return be(1);case"hh":return be(2);case"a":return ce($,N,!0);case"A":return ce($,N,!1);case"m":return String(N);case"mm":return k.s(N,2,"0");case"s":return String(O.$s);case"ss":return k.s(O.$s,2,"0");case"SSS":return k.s(O.$ms,3,"0");case"Z":return _}return null}(ie)||_.replace(":","")})},v.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},v.diff=function(C,O,I){var P,_=this,$=k.p(O),N=R(C),L=(N.utcOffset()-this.utcOffset())*e,z=this-N,H=function(){return k.m(_,N)};switch($){case p:P=H()/12;break;case u:P=H();break;case c:P=H()/3;break;case l:P=(z-L)/6048e5;break;case a:P=(z-L)/864e5;break;case s:P=z/t;break;case o:P=z/e;break;case r:P=z/i;break;default:P=z}return I?P:k.a(P)},v.daysInMonth=function(){return this.endOf(u).$D},v.$locale=function(){return b[this.$L]},v.locale=function(C,O){if(!C)return this.$L;var I=this.clone(),P=M(C,O,!0);return P&&(I.$L=P),I},v.clone=function(){return k.w(this.$d,this)},v.toDate=function(){return new Date(this.valueOf())},v.toJSON=function(){return this.isValid()?this.toISOString():null},v.toISOString=function(){return this.$d.toISOString()},v.toString=function(){return this.$d.toUTCString()},T}(),E=F.prototype;return R.prototype=E,[["$ms",n],["$s",r],["$m",o],["$H",s],["$W",a],["$M",u],["$y",p],["$D",d]].forEach(function(T){E[T[1]]=function(v){return this.$g(v,T[0],T[1])}}),R.extend=function(T,v){return T.$i||(T(v,F,R),T.$i=!0),R},R.locale=M,R.isDayjs=w,R.unix=function(T){return R(1e3*T)},R.en=b[y],R.Ls=b,R.p={},R})});var Dl=kr((pi,di)=>{"use strict";(function(i,e){typeof pi=="object"&&typeof di<"u"?di.exports=e():typeof define=="function"&&define.amd?define(e):(i=typeof globalThis<"u"?globalThis:i||self).dayjs_plugin_customParseFormat=e()})(pi,function(){"use strict";var i={LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"},e=/(\[[^[]*\])|([-_:/.,()\s]+)|(A|a|Q|YYYY|YY?|ww?|MM?M?M?|Do|DD?|hh?|HH?|mm?|ss?|S{1,3}|z|ZZ?)/g,t=/\d/,n=/\d\d/,r=/\d\d?/,o=/\d*[^-_:/,()\s\d]+/,s={},a=function(g){return(g=+g)+(g>68?1900:2e3)},l=function(g){return function(h){this[g]=+h}},u=[/[+-]\d\d:?(\d\d)?|Z/,function(g){(this.zone||(this.zone={})).offset=function(h){if(!h||h==="Z")return 0;var f=h.match(/([+-]|\d\d)/g),x=60*f[1]+(+f[2]||0);return x===0?0:f[0]==="+"?-x:x}(g)}],c=function(g){var h=s[g];return h&&(h.indexOf?h:h.s.concat(h.f))},p=function(g,h){var f,x=s.meridiem;if(x){for(var A=1;A<=24;A+=1)if(g.indexOf(x(A,0,h))>-1){f=A>12;break}}else f=g===(h?"pm":"PM");return f},d={A:[o,function(g){this.afternoon=p(g,!1)}],a:[o,function(g){this.afternoon=p(g,!0)}],Q:[t,function(g){this.month=3*(g-1)+1}],S:[t,function(g){this.milliseconds=100*+g}],SS:[n,function(g){this.milliseconds=10*+g}],SSS:[/\d{3}/,function(g){this.milliseconds=+g}],s:[r,l("seconds")],ss:[r,l("seconds")],m:[r,l("minutes")],mm:[r,l("minutes")],H:[r,l("hours")],h:[r,l("hours")],HH:[r,l("hours")],hh:[r,l("hours")],D:[r,l("day")],DD:[n,l("day")],Do:[o,function(g){var h=s.ordinal,f=g.match(/\d+/);if(this.day=f[0],h)for(var x=1;x<=31;x+=1)h(x).replace(/\[|\]/g,"")===g&&(this.day=x)}],w:[r,l("week")],ww:[n,l("week")],M:[r,l("month")],MM:[n,l("month")],MMM:[o,function(g){var h=c("months"),f=(c("monthsShort")||h.map(function(x){return x.slice(0,3)})).indexOf(g)+1;if(f<1)throw new Error;this.month=f%12||f}],MMMM:[o,function(g){var h=c("months").indexOf(g)+1;if(h<1)throw new Error;this.month=h%12||h}],Y:[/[+-]?\d+/,l("year")],YY:[n,function(g){this.year=a(g)}],YYYY:[/\d{4}/,l("year")],Z:u,ZZ:u};function m(g){var h,f;h=g,f=s&&s.formats;for(var x=(g=h.replace(/(\[[^\]]+])|(LTS?|l{1,4}|L{1,4})/g,function(R,k,F){var E=F&&F.toUpperCase();return k||f[F]||i[F]||f[E].replace(/(\[[^\]]+])|(MMMM|MM|DD|dddd)/g,function(T,v,C){return v||C.slice(1)})})).match(e),A=x.length,y=0;y<A;y+=1){var b=x[y],S=d[b],w=S&&S[0],M=S&&S[1];x[y]=M?{regex:w,parser:M}:b.replace(/^\[|\]$/g,"")}return function(R){for(var k={},F=0,E=0;F<A;F+=1){var T=x[F];if(typeof T=="string")E+=T.length;else{var v=T.regex,C=T.parser,O=R.slice(E),I=v.exec(O)[0];C.call(k,I),R=R.replace(I,"")}}return function(P){var _=P.afternoon;if(_!==void 0){var $=P.hours;_?$<12&&(P.hours+=12):$===12&&(P.hours=0),delete P.afternoon}}(k),k}}return function(g,h,f){f.p.customParseFormat=!0,g&&g.parseTwoDigitYear&&(a=g.parseTwoDigitYear);var x=h.prototype,A=x.parse;x.parse=function(y){var b=y.date,S=y.utc,w=y.args;this.$u=S;var M=w[1];if(typeof M=="string"){var R=w[2]===!0,k=w[3]===!0,F=R||k,E=w[2];k&&(E=w[2]),s=this.$locale(),!R&&E&&(s=f.Ls[E]),this.$d=function(O,I,P,_){try{if(["x","X"].indexOf(I)>-1)return new Date((I==="X"?1e3:1)*O);var $=m(I)(O),N=$.year,L=$.month,z=$.day,H=$.hours,te=$.minutes,de=$.seconds,be=$.milliseconds,ce=$.zone,ie=$.week,fe=new Date,Ae=z||(N||L?1:fe.getDate()),pe=N||fe.getFullYear(),ve=0;N&&!L||(ve=L>0?L-1:fe.getMonth());var qe,Y=H||0,ne=te||0,U=de||0,q=be||0;return ce?new Date(Date.UTC(pe,ve,Ae,Y,ne,U,q+60*ce.offset*1e3)):P?new Date(Date.UTC(pe,ve,Ae,Y,ne,U,q)):(qe=new Date(pe,ve,Ae,Y,ne,U,q),ie&&(qe=_(qe).week(ie).toDate()),qe)}catch{return new Date("")}}(b,M,S,f),this.init(),E&&E!==!0&&(this.$L=this.locale(E).$L),F&&b!=this.format(M)&&(this.$d=new Date("")),s={}}else if(M instanceof Array)for(var T=M.length,v=1;v<=T;v+=1){w[1]=M[v-1];var C=f.apply(this,w);if(C.isValid()){this.$d=C.$d,this.$L=C.$L,this.init();break}v===T&&(this.$d=new Date(""))}else A.call(this,y)}}})});var Gl=kr((mi,gi)=>{"use strict";(function(i,e){typeof mi=="object"&&typeof gi<"u"?gi.exports=e():typeof define=="function"&&define.amd?define(e):(i=typeof globalThis<"u"?globalThis:i||self).dayjs_plugin_timezone=e()})(mi,function(){"use strict";var i={year:0,month:1,day:2,hour:3,minute:4,second:5},e={};return function(t,n,r){var o,s=function(c,p,d){d===void 0&&(d={});var m=new Date(c),g=function(h,f){f===void 0&&(f={});var x=f.timeZoneName||"short",A=h+"|"+x,y=e[A];return y||(y=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:h,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",timeZoneName:x}),e[A]=y),y}(p,d);return g.formatToParts(m)},a=function(c,p){for(var d=s(c,p),m=[],g=0;g<d.length;g+=1){var h=d[g],f=h.type,x=h.value,A=i[f];A>=0&&(m[A]=parseInt(x,10))}var y=m[3],b=y===24?0:y,S=m[0]+"-"+m[1]+"-"+m[2]+" "+b+":"+m[4]+":"+m[5]+":000",w=+c;return(r.utc(S).valueOf()-(w-=w%1e3))/6e4},l=n.prototype;l.tz=function(c,p){c===void 0&&(c=o);var d,m=this.utcOffset(),g=this.toDate(),h=g.toLocaleString("en-US",{timeZone:c}),f=Math.round((g-new Date(h))/1e3/60),x=15*-Math.round(g.getTimezoneOffset()/15)-f;if(!Number(x))d=this.utcOffset(0,p);else if(d=r(h,{locale:this.$L}).$set("millisecond",this.$ms).utcOffset(x,!0),p){var A=d.utcOffset();d=d.add(m-A,"minute")}return d.$x.$timezone=c,d},l.offsetName=function(c){var p=this.$x.$timezone||r.tz.guess(),d=s(this.valueOf(),p,{timeZoneName:c}).find(function(m){return m.type.toLowerCase()==="timezonename"});return d&&d.value};var u=l.startOf;l.startOf=function(c,p){if(!this.$x||!this.$x.$timezone)return u.call(this,c,p);var d=r(this.format("YYYY-MM-DD HH:mm:ss:SSS"),{locale:this.$L});return u.call(d,c,p).tz(this.$x.$timezone,!0)},r.tz=function(c,p,d){var m=d&&p,g=d||p||o,h=a(+r(),g);if(typeof c!="string")return r(c).tz(g);var f=function(b,S,w){var M=b-60*S*1e3,R=a(M,w);if(S===R)return[M,S];var k=a(M-=60*(R-S)*1e3,w);return R===k?[M,R]:[b-60*Math.min(R,k)*1e3,Math.max(R,k)]}(r.utc(c,m).valueOf(),h,g),x=f[0],A=f[1],y=r(x).utcOffset(A);return y.$x.$timezone=g,y},r.tz.guess=function(){return Intl.DateTimeFormat().resolvedOptions().timeZone},r.tz.setDefault=function(c){o=c}}})});var Ll=kr((hi,fi)=>{"use strict";(function(i,e){typeof hi=="object"&&typeof fi<"u"?fi.exports=e():typeof define=="function"&&define.amd?define(e):(i=typeof globalThis<"u"?globalThis:i||self).dayjs_plugin_utc=e()})(hi,function(){"use strict";var i="minute",e=/[+-]\d\d(?::?\d\d)?/g,t=/([+-]|\d\d)/g;return function(n,r,o){var s=r.prototype;o.utc=function(m){var g={date:m,utc:!0,args:arguments};return new r(g)},s.utc=function(m){var g=o(this.toDate(),{locale:this.$L,utc:!0});return m?g.add(this.utcOffset(),i):g},s.local=function(){return o(this.toDate(),{locale:this.$L,utc:!1})};var a=s.parse;s.parse=function(m){m.utc&&(this.$u=!0),this.$utils().u(m.$offset)||(this.$offset=m.$offset),a.call(this,m)};var l=s.init;s.init=function(){if(this.$u){var m=this.$d;this.$y=m.getUTCFullYear(),this.$M=m.getUTCMonth(),this.$D=m.getUTCDate(),this.$W=m.getUTCDay(),this.$H=m.getUTCHours(),this.$m=m.getUTCMinutes(),this.$s=m.getUTCSeconds(),this.$ms=m.getUTCMilliseconds()}else l.call(this)};var u=s.utcOffset;s.utcOffset=function(m,g){var h=this.$utils().u;if(h(m))return this.$u?0:h(this.$offset)?u.call(this):this.$offset;if(typeof m=="string"&&(m=function(y){y===void 0&&(y="");var b=y.match(e);if(!b)return null;var S=(""+b[0]).match(t)||["-",0,0],w=S[0],M=60*+S[1]+ +S[2];return M===0?0:w==="+"?M:-M}(m),m===null))return this;var f=Math.abs(m)<=16?60*m:m,x=this;if(g)return x.$offset=f,x.$u=m===0,x;if(m!==0){var A=this.$u?this.toDate().getTimezoneOffset():-1*this.utcOffset();(x=this.local().add(f+A,i)).$offset=f,x.$x.$localOffset=A}else x=this.utc();return x};var c=s.format;s.format=function(m){var g=m||(this.$u?"YYYY-MM-DDTHH:mm:ss[Z]":"");return c.call(this,g)},s.valueOf=function(){var m=this.$utils().u(this.$offset)?0:this.$offset+(this.$x.$localOffset||this.$d.getTimezoneOffset());return this.$d.valueOf()-6e4*m},s.isUTC=function(){return!!this.$u},s.toISOString=function(){return this.toDate().toISOString()},s.toString=function(){return this.toDate().toUTCString()};var p=s.toDate;s.toDate=function(m){return m==="s"&&this.$offset?o(this.format("YYYY-MM-DD HH:mm:ss:SSS")).toDate():p.call(this)};var d=s.diff;s.diff=function(m,g,h){if(m&&this.$u===m.$u)return d.call(this,m,g,h);var f=this.local(),x=o(m).local();return d.call(f,x,g,h)}}})});var Jp={};Qu(Jp,{AxACE:()=>Qo,AxACEOptimizedProgram:()=>Ir,AxAI:()=>sr,AxAIAnthropic:()=>Kt,AxAIAnthropicModel:()=>qn,AxAIAnthropicVertexModel:()=>zn,AxAIAzureOpenAI:()=>Qt,AxAICohere:()=>Xt,AxAICohereEmbedModel:()=>Wn,AxAICohereModel:()=>Vn,AxAIDeepSeek:()=>Zt,AxAIDeepSeekModel:()=>Jn,AxAIGoogleGemini:()=>en,AxAIGoogleGeminiEmbedModel:()=>Yr,AxAIGoogleGeminiEmbedTypes:()=>Ls,AxAIGoogleGeminiModel:()=>Yn,AxAIGoogleGeminiSafetyCategory:()=>Qr,AxAIGoogleGeminiSafetyThreshold:()=>Xr,AxAIGrok:()=>mn,AxAIGrokEmbedModels:()=>Xs,AxAIGrokModel:()=>or,AxAIGroq:()=>nn,AxAIGroqModel:()=>Qn,AxAIHuggingFace:()=>rn,AxAIHuggingFaceModel:()=>ro,AxAIMistral:()=>on,AxAIMistralEmbedModels:()=>zs,AxAIMistralModel:()=>Xn,AxAIOllama:()=>sn,AxAIOpenAI:()=>Yt,AxAIOpenAIBase:()=>Te,AxAIOpenAIEmbedModel:()=>Vt,AxAIOpenAIModel:()=>Kn,AxAIOpenAIResponses:()=>ln,AxAIOpenAIResponsesBase:()=>Zn,AxAIOpenAIResponsesImpl:()=>an,AxAIOpenAIResponsesModel:()=>Wt,AxAIOpenRouter:()=>un,AxAIRefusalError:()=>xe,AxAIReka:()=>cn,AxAIRekaModel:()=>tr,AxAIServiceAbortedError:()=>Ut,AxAIServiceAuthenticationError:()=>At,AxAIServiceError:()=>Pe,AxAIServiceNetworkError:()=>Ge,AxAIServiceResponseError:()=>xt,AxAIServiceStatusError:()=>Ve,AxAIServiceStreamTerminatedError:()=>Ye,AxAIServiceTimeoutError:()=>ot,AxAITogether:()=>pn,AxAIWebLLM:()=>dn,AxAIWebLLMModel:()=>rr,AxAgent:()=>Rr,AxApacheTika:()=>Bo,AxAssertionError:()=>pt,AxBalancer:()=>Hr,AxBaseAI:()=>we,AxBaseOptimizer:()=>je,AxBootstrapFewShot:()=>vn,AxContentProcessingError:()=>st,AxDB:()=>xo,AxDBBase:()=>Xe,AxDBCloudflare:()=>gn,AxDBManager:()=>Ao,AxDBMemory:()=>Ot,AxDBPinecone:()=>hn,AxDBWeaviate:()=>fn,AxDefaultCostTracker:()=>xr,AxDefaultResultReranker:()=>Uo,AxDockerSession:()=>rs,AxEmbeddingAdapter:()=>os,AxEvalUtil:()=>gu,AxFlow:()=>Cr,AxFlowDependencyAnalyzer:()=>Sn,AxFlowExecutionPlanner:()=>kn,AxFlowSubContextImpl:()=>Pn,AxFlowTypedSubContextImpl:()=>ts,AxFluentFieldType:()=>Oe,AxFunctionError:()=>lr,AxFunctionProcessor:()=>cr,AxGEPA:()=>wn,AxGEPAFlow:()=>Xo,AxGen:()=>Ce,AxGenerateError:()=>hr,AxHFDataLoader:()=>Yo,AxInstanceRegistry:()=>bn,AxJudge:()=>Tn,AxLLMRequestTypeValues:()=>Ts,AxLearn:()=>Jo,AxMCPClient:()=>ss,AxMCPHTTPSSETransport:()=>ls,AxMCPStreambleHTTPTransport:()=>as,AxMediaNotSupportedError:()=>Qe,AxMemory:()=>xn,AxMiPRO:()=>es,AxMockAIService:()=>io,AxMultiServiceRouter:()=>ao,AxOptimizedProgramImpl:()=>mt,AxProgram:()=>Et,AxPromptTemplate:()=>Nt,AxProviderRouter:()=>po,AxRateLimiterTokenUsage:()=>tn,AxSignature:()=>ye,AxSignatureBuilder:()=>dr,AxSimpleClassifier:()=>qo,AxSimpleClassifierClass:()=>jo,AxSpanKindValues:()=>Cs,AxStopFunctionCallException:()=>$t,AxStringUtil:()=>Lo,AxSynth:()=>Rn,AxTestPrompt:()=>zo,AxTokenLimitError:()=>Nn,AxTraceLogger:()=>Cn,agent:()=>Gu,ai:()=>dl,ax:()=>_e,axAIAnthropicDefaultConfig:()=>Ps,axAIAnthropicVertexDefaultConfig:()=>Ua,axAIAzureOpenAIBestConfig:()=>za,axAIAzureOpenAICreativeConfig:()=>ja,axAIAzureOpenAIDefaultConfig:()=>_s,axAIAzureOpenAIFastConfig:()=>qa,axAICohereCreativeConfig:()=>Ja,axAICohereDefaultConfig:()=>Ds,axAIDeepSeekCodeConfig:()=>Ya,axAIDeepSeekDefaultConfig:()=>Gs,axAIGoogleGeminiDefaultConfig:()=>Bs,axAIGoogleGeminiDefaultCreativeConfig:()=>Za,axAIGrokBestConfig:()=>pl,axAIGrokDefaultConfig:()=>fo,axAIHuggingFaceCreativeConfig:()=>el,axAIHuggingFaceDefaultConfig:()=>qs,axAIMistralBestConfig:()=>tl,axAIMistralDefaultConfig:()=>so,axAIOllamaDefaultConfig:()=>Hs,axAIOllamaDefaultCreativeConfig:()=>nl,axAIOpenAIBestConfig:()=>jr,axAIOpenAICreativeConfig:()=>qr,axAIOpenAIDefaultConfig:()=>Ft,axAIOpenAIFastConfig:()=>zr,axAIOpenAIResponsesBestConfig:()=>rl,axAIOpenAIResponsesCreativeConfig:()=>ol,axAIOpenAIResponsesDefaultConfig:()=>er,axAIOpenRouterDefaultConfig:()=>Vs,axAIRekaBestConfig:()=>al,axAIRekaCreativeConfig:()=>ll,axAIRekaDefaultConfig:()=>nr,axAIRekaFastConfig:()=>ul,axAITogetherDefaultConfig:()=>Js,axAIWebLLMCreativeConfig:()=>cl,axAIWebLLMDefaultConfig:()=>Qs,axAnalyzeChatPromptRequirements:()=>sl,axAnalyzeRequestRequirements:()=>_t,axBaseAIDefaultConfig:()=>se,axBaseAIDefaultCreativeConfig:()=>Se,axCheckMetricsHealth:()=>ml,axCreateDefaultColorLogger:()=>Is,axCreateDefaultOptimizerColorLogger:()=>Ei,axCreateDefaultOptimizerTextLogger:()=>xu,axCreateDefaultTextLogger:()=>ua,axCreateFlowColorLogger:()=>Tr,axCreateFlowTextLogger:()=>Ru,axDefaultFlowLogger:()=>vu,axDefaultMetricsConfig:()=>ni,axDefaultOptimizerLogger:()=>fr,axDefaultOptimizerMetricsConfig:()=>Pi,axGetCompatibilityReport:()=>Ha,axGetFormatCompatibility:()=>Va,axGetMetricsConfig:()=>hl,axGetOptimizerMetricsConfig:()=>yu,axGetProvidersWithMediaSupport:()=>Ka,axGlobals:()=>ee,axModelInfoAnthropic:()=>Hn,axModelInfoCohere:()=>Wr,axModelInfoDeepSeek:()=>Jr,axModelInfoGoogleGemini:()=>Zr,axModelInfoGrok:()=>ho,axModelInfoGroq:()=>to,axModelInfoHuggingFace:()=>no,axModelInfoMistral:()=>oo,axModelInfoOpenAI:()=>Jt,axModelInfoOpenAIResponses:()=>Br,axModelInfoReka:()=>co,axModelInfoTogether:()=>mo,axModelInfoWebLLM:()=>go,axProcessContentForProvider:()=>uo,axRAG:()=>Lu,axScoreProvidersForRequest:()=>Kr,axSelectOptimalProvider:()=>Vr,axSpanAttributes:()=>J,axSpanEvents:()=>it,axUpdateMetricsConfig:()=>gl,axUpdateOptimizerMetricsConfig:()=>Au,axValidateChatRequestMessage:()=>Ht,axValidateChatResponseResult:()=>Ur,axValidateProviderCapabilities:()=>$s,f:()=>ue,flow:()=>ns,s:()=>bu});function Je({model:i,modelInfo:e,models:t}){let n=t?.find(u=>u.key===i),r=n&&"model"in n?n.model:i,o=e.find(u=>u.name===i);if(o)return o;let s=e.find(u=>u.name===r);if(s)return s;let a=r.replace(/^(anthropic\.|openai\.)/,"").replace(/-latest$/,"").replace(/-\d{8}$/,"").replace(/-v\d+:\d+$/,"").replace(/@\d{8}$/,"").replace(/-\d{2,}(-[a-zA-Z0-9-]+)?$/,"").replace(/-v\d+@\d{8}$/,"").replace(/-v\d+$/,""),l=e.find(u=>u.name===a);return l||null}var ps=(()=>{if(globalThis.crypto&&typeof globalThis.crypto.randomUUID=="function")return globalThis.crypto;throw new Error("Web Crypto API with randomUUID support not available. Requires Node.js 16+ or modern browser.")})();function Ee(){return ps.randomUUID()}async function Zu(i){let e=new TextEncoder,t=typeof i=="string"?e.encode(i):i,n=await ps.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}var cs=class{data="";update(e){return this.data+=e,this}digest(e){if(e!=="hex")throw new Error("Only hex encoding is supported");let n=new TextEncoder().encode(this.data),r=0;for(let o=0;o<n.length;o++){let s=n[o];r=(r<<5)-r+s,r=r&r}return Math.abs(r).toString(16).padStart(8,"0")}async digestAsync(){return Zu(this.data)}};function De(i){if(i!=="sha256")throw new Error("Only SHA-256 algorithm is supported");return new cs}function Ui(){return ps}var Mr=class extends TransformStream{buffer="";currentEvent={rawData:""};dataParser;onError;constructor(e={}){super({transform:(t,n)=>this.handleChunk(t,n),flush:t=>this.handleFlush(t)}),this.dataParser=e.dataParser||JSON.parse,this.onError=e.onError||((t,n)=>{console.warn("Failed to parse event data:",t),console.log("Raw data that failed to parse:",n)})}handleChunk(e,t){this.buffer+=e,this.processBuffer(t)}handleFlush(e){this.processBuffer(e),this.currentEvent.rawData&&this.processEvent(e)}processBuffer(e){let n=this.buffer.replace(/\r\n|\r/g,`
2
2
  `).split(`
3
3
  `);this.buffer=n.pop()||"";for(let r of n)r===""?this.processEvent(e):this.parseLine(r)}parseLine(e){if(e.startsWith(":"))return;let t=e.indexOf(":");if(t===-1){this.currentEvent.rawData+=(this.currentEvent.rawData&&!this.currentEvent.rawData.endsWith(`
4
4
  `)?`
5
5
  `:"")+e.trim();return}let n=e.slice(0,t).trim(),r=e.slice(t+1).trim();switch(n){case"event":this.currentEvent.event=r;break;case"data":this.currentEvent.rawData+=(this.currentEvent.rawData&&!this.currentEvent.rawData.endsWith(`
6
6
  `)?`
7
- `:"")+r;break;case"id":this.currentEvent.id=r;break;case"retry":{let o=Number.parseInt(r,10);Number.isNaN(o)||(this.currentEvent.retry=o);break}}}processEvent(e){if(this.currentEvent.rawData){if(this.currentEvent.event||(this.currentEvent.event="message"),this.currentEvent.rawData.trim()==="[DONE]"){this.currentEvent={rawData:""};return}try{let t=this.dataParser(this.currentEvent.rawData);e.enqueue(t)}catch(t){this.onError(t,this.currentEvent.rawData)}this.currentEvent={rawData:""}}}};var ps=class{decoder;constructor(){this.decoder=new TextDecoder}transform(e,t){if(!(e instanceof ArrayBuffer||ArrayBuffer.isView(e)))throw new TypeError("Input data must be a BufferSource");let n=this.decoder.decode(e,{stream:!0});n.length!==0&&t.enqueue(n)}flush(e){let t=this.decoder.decode();t.length!==0&&e.enqueue(t)}},Mr=class extends TransformStream{constructor(){super(new ps)}};var Qu={maxRetries:3,initialDelayMs:1e3,maxDelayMs:6e4,backoffFactor:2,retryableStatusCodes:[500,408,429,502,503,504]},Zu=globalThis.TextDecoderStream??Mr,Fe=class extends Error{constructor(t,n,r,o,i={}){super(t);this.url=n;this.requestBody=r;this.responseBody=o;this.name="AxAIServiceError",this.timestamp=new Date().toISOString(),this.errorId=Pe(),this.context=i,this.stack=this.toString()}timestamp;errorId;context;toString(){return[`${this.name}: ${this.message}`,`URL: ${this.url}`,`Request Body: ${JSON.stringify(this.requestBody,null,2)}`,`Response Body: ${JSON.stringify(this.responseBody,null,2)}`,`Context: ${JSON.stringify(this.context,null,2)}`,`Timestamp: ${this.timestamp}`,`Error ID: ${this.errorId}`].join(`
8
- `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},Ke=class extends Fe{constructor(t,n,r,o,i,a,l){let u=l?` (after ${l} retries)`:"";super(`HTTP ${t} - ${n}${u}`,r,o,{httpStatus:t,httpStatusText:n,responseBody:i,...a});this.status=t;this.statusText=n;this.name="AxAIServiceStatusError"}},De=class extends Fe{constructor(t,n,r,o,i){super(`Network Error: ${t.message}`,n,r,o,{originalErrorName:t.name,originalErrorStack:t.stack,...i});this.originalError=t;this.name="AxAIServiceNetworkError",this.stack=t.stack}},xt=class extends Fe{constructor(e,t,n,r){super(e,t,n,void 0,r),this.name="AxAIServiceResponseError"}},Ye=class extends Fe{constructor(t,n,r,o){super("Stream terminated unexpectedly by remote host",t,n,void 0,{lastChunk:r,...o});this.lastChunk=r;this.name="AxAIServiceStreamTerminatedError"}},ot=class extends Fe{constructor(e,t,n,r){super(`Request timed out after ${t}ms`,e,n,void 0,{timeoutMs:t,...r}),this.name="AxAIServiceTimeoutError"}},Nn=class extends Ke{constructor(e,t,n,r,o,i){super(e,t,n,r,o,i),this.name="AxTokenLimitError"}},Ut=class extends Fe{constructor(e,t,n,r){super(`Request aborted${t?`: ${t}`:""}`,e,n,void 0,{abortReason:t,...r}),this.name="AxAIServiceAbortedError"}},At=class extends Fe{constructor(e,t,n,r){super("Authentication failed",e,t,n,r),this.name="AxAIServiceAuthenticationError"}},fe=class extends Error{constructor(t,n,r){super(`Model refused to fulfill request: ${t}`);this.refusalMessage=t;this.model=n;this.requestId=r;this.name="AxAIRefusalError",this.timestamp=new Date().toISOString(),this.errorId=Pe()}timestamp;errorId;toString(){return[`${this.name}: ${this.message}`,`Refusal: ${this.refusalMessage}`,this.model?`Model: ${this.model}`:"",this.requestId?`Request ID: ${this.requestId}`:"",`Timestamp: ${this.timestamp}`,`Error ID: ${this.errorId}`].filter(Boolean).join(`
9
- `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},Qe=class extends Error{constructor(t,n,r=!1){super(`${t} not supported by ${n}${r?" (fallback available)":""}`);this.mediaType=t;this.provider=n;this.fallbackAvailable=r;this.name="AxMediaNotSupportedError",this.timestamp=new Date().toISOString(),this.errorId=Pe()}timestamp;errorId;toString(){return[`${this.name}: ${this.message}`,`Media Type: ${this.mediaType}`,`Provider: ${this.provider}`,`Fallback Available: ${this.fallbackAvailable}`,`Timestamp: ${this.timestamp}`,`Error ID: ${this.errorId}`].join(`
10
- `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},st=class extends Error{constructor(t,n,r){super(`Failed to process ${n} during ${r}: ${t.message}`);this.originalError=t;this.contentType=n;this.processingStep=r;this.name="AxContentProcessingError",this.timestamp=new Date().toISOString(),this.errorId=Pe()}timestamp;errorId;toString(){return[`${this.name}: ${this.message}`,`Content Type: ${this.contentType}`,`Processing Step: ${this.processingStep}`,`Original Error: ${this.originalError.message}`,`Timestamp: ${this.timestamp}`,`Error ID: ${this.errorId}`].join(`
11
- `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}};async function ds(s){try{return s.headers.get("content-type")?.includes("application/json")?await s.json():await s.clone().text()}catch(e){return`[ReadableStream - read failed: ${e.message}]`}}function Gi(s,e){return Math.min(e.maxDelayMs,e.initialDelayMs*e.backoffFactor**s)*(.75+Math.random()*.5)}function Xu(s){if(!s)return;let e=Number(s);if(!Number.isNaN(e))return e*1e3;let t=Date.parse(s);if(!Number.isNaN(t)){let n=t-Date.now();return Math.max(0,n)}}function ec(){return{startTime:Date.now(),retryCount:0}}function Ui(s){s.retryCount++,s.lastRetryTime=Date.now()}function Bi(s,e,t,n){return t>=n.maxRetries?!1:e&&n.retryableStatusCodes.includes(e)?!0:s instanceof De&&!(s instanceof At)}var Ue=async(s,e)=>{if(s.localCall)return await s.localCall(e,s.stream);if(!s.url)throw new Error("API URL is required when localCall is not provided");let t={...Qu,...s.retry},n=s.timeout,r=ec(),o=s.verbose??!1,i,a=new URL(s.url),l=`${[a.pathname,s.name].filter(Boolean).join("/").replace(/\/+/g,"/")}${a.search}`,u=new URL(l,a);if(s.corsProxy){let d=u.href;u=new URL(`${s.corsProxy}?url=${encodeURIComponent(d)}`)}let c=Pe();if(s.validateRequest&&!await s.validateRequest(e))throw new xt("Invalid request data",u.href,e,{validation:"request"});s.span?.setAttributes({"http.request.method":s.put?"PUT":"POST","url.full":u.href,"request.id":c,"request.startTime":r.startTime});let p=0;for(;;){let d=new AbortController;if(s.abortSignal){if(s.abortSignal.aborted)throw new Ut(u.href,s.abortSignal.reason,e,{metrics:r});let m=()=>{d.abort(s.abortSignal.reason||"User aborted request")};s.abortSignal.addEventListener("abort",m,{once:!0});let g=d.abort.bind(d);d.abort=f=>{s.abortSignal.removeEventListener("abort",m),g(f)}}n&&(i=setTimeout(()=>{d.abort("Request timeout")},n));try{o&&console.log(`
7
+ `:"")+r;break;case"id":this.currentEvent.id=r;break;case"retry":{let o=Number.parseInt(r,10);Number.isNaN(o)||(this.currentEvent.retry=o);break}}}processEvent(e){if(this.currentEvent.rawData){if(this.currentEvent.event||(this.currentEvent.event="message"),this.currentEvent.rawData.trim()==="[DONE]"){this.currentEvent={rawData:""};return}try{let t=this.dataParser(this.currentEvent.rawData);e.enqueue(t)}catch(t){this.onError(t,this.currentEvent.rawData)}this.currentEvent={rawData:""}}}};var ds=class{decoder;constructor(){this.decoder=new TextDecoder}transform(e,t){if(!(e instanceof ArrayBuffer||ArrayBuffer.isView(e)))throw new TypeError("Input data must be a BufferSource");let n=this.decoder.decode(e,{stream:!0});n.length!==0&&t.enqueue(n)}flush(e){let t=this.decoder.decode();t.length!==0&&e.enqueue(t)}},Er=class extends TransformStream{constructor(){super(new ds)}};var ec={maxRetries:3,initialDelayMs:1e3,maxDelayMs:6e4,backoffFactor:2,retryableStatusCodes:[500,408,429,502,503,504]},tc=globalThis.TextDecoderStream??Er,Pe=class extends Error{constructor(t,n,r,o,s={}){super(t);this.url=n;this.requestBody=r;this.responseBody=o;this.name="AxAIServiceError",this.timestamp=new Date().toISOString(),this.errorId=Ee(),this.context=s,this.stack=this.toString()}timestamp;errorId;context;toString(){return[`${this.name}: ${this.message}`,`URL: ${this.url}`,`Request Body: ${JSON.stringify(this.requestBody,null,2)}`,`Response Body: ${JSON.stringify(this.responseBody,null,2)}`,`Context: ${JSON.stringify(this.context,null,2)}`,`Timestamp: ${this.timestamp}`,`Error ID: ${this.errorId}`].join(`
8
+ `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},Ve=class extends Pe{constructor(t,n,r,o,s,a,l){let u=l?` (after ${l} retries)`:"";super(`HTTP ${t} - ${n}${u}`,r,o,{httpStatus:t,httpStatusText:n,responseBody:s,...a});this.status=t;this.statusText=n;this.name="AxAIServiceStatusError"}},Ge=class extends Pe{constructor(t,n,r,o,s){super(`Network Error: ${t.message}`,n,r,o,{originalErrorName:t.name,originalErrorStack:t.stack,...s});this.originalError=t;this.name="AxAIServiceNetworkError",this.stack=t.stack}},xt=class extends Pe{constructor(e,t,n,r){super(e,t,n,void 0,r),this.name="AxAIServiceResponseError"}},Ye=class extends Pe{constructor(t,n,r,o){super("Stream terminated unexpectedly by remote host",t,n,void 0,{lastChunk:r,...o});this.lastChunk=r;this.name="AxAIServiceStreamTerminatedError"}},ot=class extends Pe{constructor(e,t,n,r){super(`Request timed out after ${t}ms`,e,n,void 0,{timeoutMs:t,...r}),this.name="AxAIServiceTimeoutError"}},Nn=class extends Ve{constructor(e,t,n,r,o,s){super(e,t,n,r,o,s),this.name="AxTokenLimitError"}},Ut=class extends Pe{constructor(e,t,n,r){super(`Request aborted${t?`: ${t}`:""}`,e,n,void 0,{abortReason:t,...r}),this.name="AxAIServiceAbortedError"}},At=class extends Pe{constructor(e,t,n,r){super("Authentication failed",e,t,n,r),this.name="AxAIServiceAuthenticationError"}},xe=class extends Error{constructor(t,n,r){super(`Model refused to fulfill request: ${t}`);this.refusalMessage=t;this.model=n;this.requestId=r;this.name="AxAIRefusalError",this.timestamp=new Date().toISOString(),this.errorId=Ee()}timestamp;errorId;toString(){return[`${this.name}: ${this.message}`,`Refusal: ${this.refusalMessage}`,this.model?`Model: ${this.model}`:"",this.requestId?`Request ID: ${this.requestId}`:"",`Timestamp: ${this.timestamp}`,`Error ID: ${this.errorId}`].filter(Boolean).join(`
9
+ `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},Qe=class extends Error{constructor(t,n,r=!1){super(`${t} not supported by ${n}${r?" (fallback available)":""}`);this.mediaType=t;this.provider=n;this.fallbackAvailable=r;this.name="AxMediaNotSupportedError",this.timestamp=new Date().toISOString(),this.errorId=Ee()}timestamp;errorId;toString(){return[`${this.name}: ${this.message}`,`Media Type: ${this.mediaType}`,`Provider: ${this.provider}`,`Fallback Available: ${this.fallbackAvailable}`,`Timestamp: ${this.timestamp}`,`Error ID: ${this.errorId}`].join(`
10
+ `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},st=class extends Error{constructor(t,n,r){super(`Failed to process ${n} during ${r}: ${t.message}`);this.originalError=t;this.contentType=n;this.processingStep=r;this.name="AxContentProcessingError",this.timestamp=new Date().toISOString(),this.errorId=Ee()}timestamp;errorId;toString(){return[`${this.name}: ${this.message}`,`Content Type: ${this.contentType}`,`Processing Step: ${this.processingStep}`,`Original Error: ${this.originalError.message}`,`Timestamp: ${this.timestamp}`,`Error ID: ${this.errorId}`].join(`
11
+ `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}};async function ms(i){try{return i.headers.get("content-type")?.includes("application/json")?await i.json():await i.clone().text()}catch(e){return`[ReadableStream - read failed: ${e.message}]`}}function Bi(i,e){return Math.min(e.maxDelayMs,e.initialDelayMs*e.backoffFactor**i)*(.75+Math.random()*.5)}function nc(i){if(!i)return;let e=Number(i);if(!Number.isNaN(e))return e*1e3;let t=Date.parse(i);if(!Number.isNaN(t)){let n=t-Date.now();return Math.max(0,n)}}function rc(){return{startTime:Date.now(),retryCount:0}}function ji(i){i.retryCount++,i.lastRetryTime=Date.now()}function qi(i,e,t,n){return t>=n.maxRetries?!1:e&&n.retryableStatusCodes.includes(e)?!0:i instanceof Ge&&!(i instanceof At)}var Fe=async(i,e)=>{if(i.localCall)return await i.localCall(e,i.stream);if(!i.url)throw new Error("API URL is required when localCall is not provided");let t={...ec,...i.retry},n=i.timeout,r=rc(),o=i.verbose??!1,s,a=new URL(i.url),l=`${[a.pathname,i.name].filter(Boolean).join("/").replace(/\/+/g,"/")}${a.search}`,u=new URL(l,a);if(i.corsProxy){let d=u.href;u=new URL(`${i.corsProxy}?url=${encodeURIComponent(d)}`)}let c=Ee();if(i.validateRequest&&!await i.validateRequest(e))throw new xt("Invalid request data",u.href,e,{validation:"request"});i.span?.setAttributes({"http.request.method":i.put?"PUT":"POST","url.full":u.href,"request.id":c,"request.startTime":r.startTime});let p=0;for(;;){let d=new AbortController;if(i.abortSignal){if(i.abortSignal.aborted)throw new Ut(u.href,i.abortSignal.reason,e,{metrics:r});let m=()=>{d.abort(i.abortSignal.reason||"User aborted request")};i.abortSignal.addEventListener("abort",m,{once:!0});let g=d.abort.bind(d);d.abort=h=>{i.abortSignal.removeEventListener("abort",m),g(h)}}n&&(s=setTimeout(()=>{d.abort("Request timeout")},n));try{o&&console.log(`
12
12
  --- [AxAI API Request] ---
13
13
  `,`URL: ${u.href}
14
- `,`Method: ${s.put?"PUT":"POST"}
15
- `,"Headers:",JSON.stringify({"Content-Type":"application/json","X-Request-ID":c,"X-Retry-Count":p.toString(),...s.headers},null,2),`
14
+ `,`Method: ${i.put?"PUT":"POST"}
15
+ `,"Headers:",JSON.stringify({"Content-Type":"application/json","X-Request-ID":c,"X-Retry-Count":p.toString(),...i.headers},null,2),`
16
16
  Body:`,JSON.stringify(e,null,2),`
17
17
  ------------------------
18
- `);let m=await(s.fetch??fetch)(u,{method:s.put?"PUT":"POST",headers:{"Content-Type":"application/json","X-Request-ID":c,"X-Retry-Count":p.toString(),...s.headers},body:JSON.stringify(e),signal:d.signal});if(i&&clearTimeout(i),m.status===401||m.status===403){let y=await ds(m);throw new At(u.href,e,y,{metrics:r})}if(m.status===400){let y=await ds(m),b=y,k=!1;if(b?.error?.code==="context_length_exceeded")k=!0;else if(b?.type==="invalid_request_error"&&(b?.error?.message?.includes("prompt is too long")||b?.error?.message?.includes("max_tokens")||b?.error?.message?.includes("token limit")))k=!0;else if(b?.error?.code===400&&b?.error?.status==="INVALID_ARGUMENT"&&(b?.error?.message?.includes("token")||b?.error?.message?.includes("limit")))k=!0;else{let S=JSON.stringify(y).toLowerCase();(S.includes("token")&&S.includes("limit")||S.includes("context length")||S.includes("prompt is too long"))&&(k=!0)}if(k)throw new Nn(m.status,m.statusText,u.href,e,y,{metrics:r})}if(m.status>=400&&Bi(new Error,m.status,p,t)){let y=Gi(p,t),b=Xu(m.headers.get("Retry-After"));b!==void 0&&b<=t.maxDelayMs&&(y=b,o&&console.log(`[AxAI] Respecting Retry-After header: ${y}ms`)),p++,Ui(r),s.span?.addEvent("retry",{attempt:p,delay:y,status:m.status,"metrics.startTime":r.startTime,"metrics.retryCount":r.retryCount,"metrics.lastRetryTime":r.lastRetryTime}),await new Promise(k=>setTimeout(k,y));continue}if(m.status>=400){let y=await ds(m);throw new Ke(m.status,m.statusText,u.href,e,y,{metrics:r},p>0?p:void 0)}if(!s.stream){let y=await m.json();if(o&&console.log(`
18
+ `);let m=await(i.fetch??fetch)(u,{method:i.put?"PUT":"POST",headers:{"Content-Type":"application/json","X-Request-ID":c,"X-Retry-Count":p.toString(),...i.headers},body:JSON.stringify(e),signal:d.signal});if(s&&clearTimeout(s),m.status===401||m.status===403){let y=await ms(m);throw new At(u.href,e,y,{metrics:r})}if(m.status===400){let y=await ms(m),b=y,S=!1;if(b?.error?.code==="context_length_exceeded")S=!0;else if(b?.type==="invalid_request_error"&&(b?.error?.message?.includes("prompt is too long")||b?.error?.message?.includes("max_tokens")||b?.error?.message?.includes("token limit")))S=!0;else if(b?.error?.code===400&&b?.error?.status==="INVALID_ARGUMENT"&&(b?.error?.message?.includes("token")||b?.error?.message?.includes("limit")))S=!0;else{let w=JSON.stringify(y).toLowerCase();(w.includes("token")&&w.includes("limit")||w.includes("context length")||w.includes("prompt is too long"))&&(S=!0)}if(S)throw new Nn(m.status,m.statusText,u.href,e,y,{metrics:r})}if(m.status>=400&&qi(new Error,m.status,p,t)){let y=Bi(p,t),b=nc(m.headers.get("Retry-After"));b!==void 0&&b<=t.maxDelayMs&&(y=b,o&&console.log(`[AxAI] Respecting Retry-After header: ${y}ms`)),p++,ji(r),i.span?.addEvent("retry",{attempt:p,delay:y,status:m.status,"metrics.startTime":r.startTime,"metrics.retryCount":r.retryCount,"metrics.lastRetryTime":r.lastRetryTime}),await new Promise(S=>setTimeout(S,y));continue}if(m.status>=400){let y=await ms(m);throw new Ve(m.status,m.statusText,u.href,e,y,{metrics:r},p>0?p:void 0)}if(!i.stream){let y=await m.json();if(o&&console.log(`
19
19
  --- [AxAI API Response] ---
20
20
  `,`Status: ${m.status} ${m.statusText}
21
21
  `,"Body:",JSON.stringify(y,null,2),`
22
22
  -------------------------
23
- `),s.validateResponse&&!await s.validateResponse(y))throw new xt("Invalid response data",u.href,e,{validation:"response"});return s.span?.setAttributes({"response.time":Date.now()-r.startTime,"response.retries":r.retryCount}),y}if(o&&console.log(`
23
+ `),i.validateResponse&&!await i.validateResponse(y))throw new xt("Invalid response data",u.href,e,{validation:"response"});return i.span?.setAttributes({"response.time":Date.now()-r.startTime,"response.retries":r.retryCount}),y}if(o&&console.log(`
24
24
  --- [AxAI API Streaming Response Started] ---
25
25
  `,`Status: ${m.status} ${m.statusText}
26
26
  `,`
27
27
  -------------------------------------------
28
- `),!m.body)throw new xt("Response body is null",u.href,e,{metrics:r});let g,f=0;if(typeof window<"u"&&typeof EventSource<"u")return new ReadableStream({start(y){let b=m.body.getReader(),k=new TextDecoder,S="";async function M(){try{for(;;){let{done:R,value:O}=await b.read();if(R){A=!0,y.close();break}S+=k.decode(O,{stream:!0});let F=S.split(`
29
-
30
- `);S=F.pop()||"";for(let P of F){if(!P.trim())continue;let I=P.split(`
31
- `),v="",T="message";for(let w of I)w.startsWith("data: ")?v=w.slice(6):w.startsWith("event: ")&&(T=w.slice(7));if(v){if(v==="[DONE]"){y.close();return}try{let w=JSON.parse(v);g=w,f++,r.streamChunks=f,r.lastChunkTime=Date.now(),y.enqueue(w),s.span?.addEvent("stream.chunk",{"stream.chunks":f,"stream.duration":Date.now()-r.startTime,"response.retries":r.retryCount,"sse.event.type":T})}catch(w){o&&console.warn("Skipping non-JSON SSE data:",v,w)}}}}}catch(R){let O=R,F={...r,streamDuration:Date.now()-r.startTime};O.name==="AbortError"||O.message?.includes("aborted")?y.error(new Ye(u.href,e,g,{streamMetrics:F})):y.error(new De(O,u.href,e,"[ReadableStream - consumed during streaming]",{streamMetrics:F}))}finally{b.releaseLock()}}M()}});let x=new TransformStream({transform(y,b){g=y,f++,r.streamChunks=f,r.lastChunkTime=Date.now(),b.enqueue(y),s.span?.addEvent("stream.chunk",{"stream.chunks":f,"stream.duration":Date.now()-r.startTime,"response.retries":r.retryCount})}}),A=!1;return new ReadableStream({start(y){let b=m.body.pipeThrough(new Zu).pipeThrough(new kr).pipeThrough(x).getReader();async function k(){try{for(;;){let{done:S,value:M}=await b.read();if(S){A||(A=!0,y.close());break}if(A)break;y.enqueue(M)}}catch(S){let M=S,R={...r,streamDuration:Date.now()-r.startTime};throw M.name==="AbortError"||M.message?.includes("aborted")?y.error(new Ye(u.href,e,g,{streamMetrics:R})):M instanceof TypeError&&M.message.includes("cancelled")?y.error(new Ye(u.href,e,g,{streamMetrics:R,cancelReason:"Stream cancelled by client"})):y.error(new De(M,u.href,e,"[ReadableStream - consumed during streaming]",{streamMetrics:R})),M}finally{i&&clearTimeout(i),b.releaseLock()}}k()},cancel(){A=!0}})}catch(m){if(m instanceof Error&&m.name==="AbortError")throw s.abortSignal?.aborted?new Ut(u.href,s.abortSignal.reason,e,{metrics:r}):new ot(u.href,n||0,e,{metrics:r});let g=m;if(!(m instanceof Fe)&&m instanceof Error&&(g=new De(m,u.href,e,void 0,{metrics:r})),s.span?.isRecording()&&(s.span.recordException(g),s.span.setAttributes({"error.time":Date.now()-r.startTime,"error.retries":r.retryCount})),g instanceof De&&Bi(g,void 0,p,t)){let f=Gi(p,t);p++,Ui(r),s.span?.addEvent("retry",{attempt:p,delay:f,error:g.message,"metrics.startTime":r.startTime,"metrics.retryCount":r.retryCount,"metrics.lastRetryTime":r.lastRetryTime}),await new Promise(h=>setTimeout(h,f));continue}throw g instanceof Fe&&(g.context.metrics=r),g}finally{i!==void 0&&clearTimeout(i)}}};var ji=typeof globalThis=="object"?globalThis:global;var yt="1.9.0";var zi=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function tc(s){var e=new Set([s]),t=new Set,n=s.match(zi);if(!n)return function(){return!1};var r={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(r.prerelease!=null)return function(l){return l===s};function o(a){return t.add(a),!1}function i(a){return e.add(a),!0}return function(l){if(e.has(l))return!0;if(t.has(l))return!1;var u=l.match(zi);if(!u)return o(l);var c={major:+u[1],minor:+u[2],patch:+u[3],prerelease:u[4]};return c.prerelease!=null||r.major!==c.major?o(l):r.major===0?r.minor===c.minor&&r.patch<=c.patch?i(l):o(l):r.minor<=c.minor?i(l):o(l)}}var qi=tc(yt);var nc=yt.split(".")[0],Dn=Symbol.for("opentelemetry.js.api."+nc),Ln=ji;function Bt(s,e,t,n){var r;n===void 0&&(n=!1);var o=Ln[Dn]=(r=Ln[Dn])!==null&&r!==void 0?r:{version:yt};if(!n&&o[s]){var i=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+s);return t.error(i.stack||i.message),!1}if(o.version!==yt){var i=new Error("@opentelemetry/api: Registration of version v"+o.version+" for "+s+" does not match previously registered API v"+yt);return t.error(i.stack||i.message),!1}return o[s]=e,t.debug("@opentelemetry/api: Registered a global for "+s+" v"+yt+"."),!0}function bt(s){var e,t,n=(e=Ln[Dn])===null||e===void 0?void 0:e.version;if(!(!n||!qi(n)))return(t=Ln[Dn])===null||t===void 0?void 0:t[s]}function jt(s,e){e.debug("@opentelemetry/api: Unregistering a global for "+s+" v"+yt+".");var t=Ln[Dn];t&&delete t[s]}var rc=function(s,e){var t=typeof Symbol=="function"&&s[Symbol.iterator];if(!t)return s;var n=t.call(s),r,o=[],i;try{for(;(e===void 0||e-- >0)&&!(r=n.next()).done;)o.push(r.value)}catch(a){i={error:a}}finally{try{r&&!r.done&&(t=n.return)&&t.call(n)}finally{if(i)throw i.error}}return o},oc=function(s,e,t){if(t||arguments.length===2)for(var n=0,r=e.length,o;n<r;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return s.concat(o||Array.prototype.slice.call(e))},Hi=function(){function s(e){this._namespace=e.namespace||"DiagComponentLogger"}return s.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Gn("debug",this._namespace,e)},s.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Gn("error",this._namespace,e)},s.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Gn("info",this._namespace,e)},s.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Gn("warn",this._namespace,e)},s.prototype.verbose=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Gn("verbose",this._namespace,e)},s}();function Gn(s,e,t){var n=bt("diag");if(n)return t.unshift(e),n[s].apply(n,oc([],rc(t),!1))}var Le;(function(s){s[s.NONE=0]="NONE",s[s.ERROR=30]="ERROR",s[s.WARN=50]="WARN",s[s.INFO=60]="INFO",s[s.DEBUG=70]="DEBUG",s[s.VERBOSE=80]="VERBOSE",s[s.ALL=9999]="ALL"})(Le||(Le={}));function Ki(s,e){s<Le.NONE?s=Le.NONE:s>Le.ALL&&(s=Le.ALL),e=e||{};function t(n,r){var o=e[n];return typeof o=="function"&&s>=r?o.bind(e):function(){}}return{error:t("error",Le.ERROR),warn:t("warn",Le.WARN),info:t("info",Le.INFO),debug:t("debug",Le.DEBUG),verbose:t("verbose",Le.VERBOSE)}}var sc=function(s,e){var t=typeof Symbol=="function"&&s[Symbol.iterator];if(!t)return s;var n=t.call(s),r,o=[],i;try{for(;(e===void 0||e-- >0)&&!(r=n.next()).done;)o.push(r.value)}catch(a){i={error:a}}finally{try{r&&!r.done&&(t=n.return)&&t.call(n)}finally{if(i)throw i.error}}return o},ic=function(s,e,t){if(t||arguments.length===2)for(var n=0,r=e.length,o;n<r;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return s.concat(o||Array.prototype.slice.call(e))},ac="diag",zt=function(){function s(){function e(r){return function(){for(var o=[],i=0;i<arguments.length;i++)o[i]=arguments[i];var a=bt("diag");if(a)return a[r].apply(a,ic([],sc(o),!1))}}var t=this,n=function(r,o){var i,a,l;if(o===void 0&&(o={logLevel:Le.INFO}),r===t){var u=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return t.error((i=u.stack)!==null&&i!==void 0?i:u.message),!1}typeof o=="number"&&(o={logLevel:o});var c=bt("diag"),p=Ki((a=o.logLevel)!==null&&a!==void 0?a:Le.INFO,r);if(c&&!o.suppressOverrideMessage){var d=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";c.warn("Current logger will be overwritten from "+d),p.warn("Current logger will overwrite one already registered from "+d)}return Bt("diag",p,t,!0)};t.setLogger=n,t.disable=function(){jt(ac,t)},t.createComponentLogger=function(r){return new Hi(r)},t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error")}return s.instance=function(){return this._instance||(this._instance=new s),this._instance},s}();function Vi(s){return Symbol.for(s)}var lc=function(){function s(e){var t=this;t._currentContext=e?new Map(e):new Map,t.getValue=function(n){return t._currentContext.get(n)},t.setValue=function(n,r){var o=new s(t._currentContext);return o._currentContext.set(n,r),o},t.deleteValue=function(n){var r=new s(t._currentContext);return r._currentContext.delete(n),r}}return s}(),Wi=new lc;var uc=function(s,e){var t=typeof Symbol=="function"&&s[Symbol.iterator];if(!t)return s;var n=t.call(s),r,o=[],i;try{for(;(e===void 0||e-- >0)&&!(r=n.next()).done;)o.push(r.value)}catch(a){i={error:a}}finally{try{r&&!r.done&&(t=n.return)&&t.call(n)}finally{if(i)throw i.error}}return o},cc=function(s,e,t){if(t||arguments.length===2)for(var n=0,r=e.length,o;n<r;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return s.concat(o||Array.prototype.slice.call(e))},Ji=function(){function s(){}return s.prototype.active=function(){return Wi},s.prototype.with=function(e,t,n){for(var r=[],o=3;o<arguments.length;o++)r[o-3]=arguments[o];return t.call.apply(t,cc([n],uc(r),!1))},s.prototype.bind=function(e,t){return t},s.prototype.enable=function(){return this},s.prototype.disable=function(){return this},s}();var pc=function(s,e){var t=typeof Symbol=="function"&&s[Symbol.iterator];if(!t)return s;var n=t.call(s),r,o=[],i;try{for(;(e===void 0||e-- >0)&&!(r=n.next()).done;)o.push(r.value)}catch(a){i={error:a}}finally{try{r&&!r.done&&(t=n.return)&&t.call(n)}finally{if(i)throw i.error}}return o},dc=function(s,e,t){if(t||arguments.length===2)for(var n=0,r=e.length,o;n<r;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return s.concat(o||Array.prototype.slice.call(e))},ms="context",mc=new Ji,qt=function(){function s(){}return s.getInstance=function(){return this._instance||(this._instance=new s),this._instance},s.prototype.setGlobalContextManager=function(e){return Bt(ms,e,zt.instance())},s.prototype.active=function(){return this._getContextManager().active()},s.prototype.with=function(e,t,n){for(var r,o=[],i=3;i<arguments.length;i++)o[i-3]=arguments[i];return(r=this._getContextManager()).with.apply(r,dc([e,t,n],pc(o),!1))},s.prototype.bind=function(e,t){return this._getContextManager().bind(e,t)},s.prototype._getContextManager=function(){return bt(ms)||mc},s.prototype.disable=function(){this._getContextManager().disable(),jt(ms,zt.instance())},s}();var Er;(function(s){s[s.NONE=0]="NONE",s[s.SAMPLED=1]="SAMPLED"})(Er||(Er={}));var gs="0000000000000000",hs="00000000000000000000000000000000",Yi={traceId:hs,spanId:gs,traceFlags:Er.NONE};var Rt=function(){function s(e){e===void 0&&(e=Yi),this._spanContext=e}return s.prototype.spanContext=function(){return this._spanContext},s.prototype.setAttribute=function(e,t){return this},s.prototype.setAttributes=function(e){return this},s.prototype.addEvent=function(e,t){return this},s.prototype.addLink=function(e){return this},s.prototype.addLinks=function(e){return this},s.prototype.setStatus=function(e){return this},s.prototype.updateName=function(e){return this},s.prototype.end=function(e){},s.prototype.isRecording=function(){return!1},s.prototype.recordException=function(e,t){},s}();var fs=Vi("OpenTelemetry Context Key SPAN");function Pr(s){return s.getValue(fs)||void 0}function Qi(){return Pr(qt.getInstance().active())}function Un(s,e){return s.setValue(fs,e)}function Zi(s){return s.deleteValue(fs)}function Xi(s,e){return Un(s,new Rt(e))}function Fr(s){var e;return(e=Pr(s))===null||e===void 0?void 0:e.spanContext()}var gc=/^([0-9a-f]{32})$/i,hc=/^[0-9a-f]{16}$/i;function fc(s){return gc.test(s)&&s!==hs}function xc(s){return hc.test(s)&&s!==gs}function _r(s){return fc(s.traceId)&&xc(s.spanId)}function ea(s){return new Rt(s)}var xs=qt.getInstance(),$r=function(){function s(){}return s.prototype.startSpan=function(e,t,n){n===void 0&&(n=xs.active());var r=!!t?.root;if(r)return new Rt;var o=n&&Fr(n);return Ac(o)&&_r(o)?new Rt(o):new Rt},s.prototype.startActiveSpan=function(e,t,n,r){var o,i,a;if(!(arguments.length<2)){arguments.length===2?a=t:arguments.length===3?(o=t,a=n):(o=t,i=n,a=r);var l=i??xs.active(),u=this.startSpan(e,o,l),c=Un(l,u);return xs.with(c,a,void 0,u)}},s}();function Ac(s){return typeof s=="object"&&typeof s.spanId=="string"&&typeof s.traceId=="string"&&typeof s.traceFlags=="number"}var yc=new $r,ta=function(){function s(e,t,n,r){this._provider=e,this.name=t,this.version=n,this.options=r}return s.prototype.startSpan=function(e,t,n){return this._getTracer().startSpan(e,t,n)},s.prototype.startActiveSpan=function(e,t,n,r){var o=this._getTracer();return Reflect.apply(o.startActiveSpan,o,arguments)},s.prototype._getTracer=function(){if(this._delegate)return this._delegate;var e=this._provider.getDelegateTracer(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):yc},s}();var na=function(){function s(){}return s.prototype.getTracer=function(e,t,n){return new $r},s}();var bc=new na,As=function(){function s(){}return s.prototype.getTracer=function(e,t,n){var r;return(r=this.getDelegateTracer(e,t,n))!==null&&r!==void 0?r:new ta(this,e,t,n)},s.prototype.getDelegate=function(){var e;return(e=this._delegate)!==null&&e!==void 0?e:bc},s.prototype.setDelegate=function(e){this._delegate=e},s.prototype.getDelegateTracer=function(e,t,n){var r;return(r=this._delegate)===null||r===void 0?void 0:r.getTracer(e,t,n)},s}();var Be;(function(s){s[s.INTERNAL=0]="INTERNAL",s[s.SERVER=1]="SERVER",s[s.CLIENT=2]="CLIENT",s[s.PRODUCER=3]="PRODUCER",s[s.CONSUMER=4]="CONSUMER"})(Be||(Be={}));var vt=qt.getInstance();var ys="trace",ra=function(){function s(){this._proxyTracerProvider=new As,this.wrapSpanContext=ea,this.isSpanContextValid=_r,this.deleteSpan=Zi,this.getSpan=Pr,this.getActiveSpan=Qi,this.getSpanContext=Fr,this.setSpan=Un,this.setSpanContext=Xi}return s.getInstance=function(){return this._instance||(this._instance=new s),this._instance},s.prototype.setGlobalTracerProvider=function(e){var t=Bt(ys,this._proxyTracerProvider,zt.instance());return t&&this._proxyTracerProvider.setDelegate(e),t},s.prototype.getTracerProvider=function(){return bt(ys)||this._proxyTracerProvider},s.prototype.getTracer=function(e,t){return this.getTracerProvider().getTracer(e,t)},s.prototype.disable=function(){jt(ys,zt.instance()),this._proxyTracerProvider=new As},s}();var Bn=ra.getInstance();var te={signatureStrict:!0,useStructuredPrompt:!0,tracer:void 0,meter:void 0,logger:void 0,optimizerLogger:void 0,debug:void 0,abortSignal:void 0,cachingFunction:void 0,functionResultFormatter:s=>typeof s=="string"?s:s==null?"":JSON.stringify(s,null,2)};var Ge=class{ANSI_WHITE_BRIGHT="\x1B[97m";ANSI_GREEN_BRIGHT="\x1B[92m";ANSI_BLUE_BRIGHT="\x1B[94m";ANSI_RED_BRIGHT="\x1B[91m";ANSI_YELLOW_BRIGHT="\x1B[93m";ANSI_YELLOW="\x1B[93m";ANSI_RED="\x1B[91m";ANSI_RESET="\x1B[0m";ANSI_ORANGE="\x1B[38;5;208m";ANSI_WHITE="\x1B[37m";ANSI_CYAN_BRIGHT="\x1B[96m";ANSI_MAGENTA_BRIGHT="\x1B[95m";ANSI_GRAY="\x1B[90m";ANSI_GREEN="\x1B[32m";ANSI_CYAN="\x1B[36m";ANSI_MAGENTA="\x1B[35m";ANSI_BLUE="\x1B[34m";ANSI_YELLOW_DIM="\x1B[33m";colorize(e,t){return`${t}${e}${this.ANSI_RESET}`}whiteBright(e){return this.colorize(e,this.ANSI_WHITE_BRIGHT)}greenBright(e){return this.colorize(e,this.ANSI_GREEN_BRIGHT)}blueBright(e){return this.colorize(e,this.ANSI_BLUE_BRIGHT)}redBright(e){return this.colorize(e,this.ANSI_RED_BRIGHT)}white(e){return this.colorize(e,this.ANSI_WHITE)}yellow(e){return this.colorize(e,this.ANSI_YELLOW)}yellowBright(e){return this.colorize(e,this.ANSI_YELLOW_BRIGHT)}red(e){return this.colorize(e,this.ANSI_RED)}orange(e){return this.colorize(e,this.ANSI_ORANGE)}cyanBright(e){return this.colorize(e,this.ANSI_CYAN_BRIGHT)}magentaBright(e){return this.colorize(e,this.ANSI_MAGENTA_BRIGHT)}gray(e){return this.colorize(e,this.ANSI_GRAY)}green(e){return this.colorize(e,this.ANSI_GREEN)}cyan(e){return this.colorize(e,this.ANSI_CYAN)}magenta(e){return this.colorize(e,this.ANSI_MAGENTA)}blue(e){return this.colorize(e,this.ANSI_BLUE)}yellowDim(e){return this.colorize(e,this.ANSI_YELLOW_DIM)}};var hm=new Ge,oa=s=>{console.log(s)},sa=(s,e,t)=>{let n=(r,o)=>t&&o&&o in t?t[o](r):r;switch(s.role){case"system":return`${n("[ SYSTEM ]","magentaBright")}
32
- ${n(s.content,"magenta")}`;case"function":return`${n("[ FUNCTION RESULT ]","yellow")}
33
- ${n(s.result??"[No result]","yellowDim")}`;case"user":{let r=`${n("[ USER ]","greenBright")}
34
- `;if(typeof s.content=="string")return r+n(s.content,"green");let o=s.content.map(i=>{if(i.type==="text")return n(i.text,"green");if(i.type==="image"){let a=e?"[Image]":`[Image: ${i.image}]`;return n(a,"green")}if(i.type==="audio"){let a=e?"[Audio]":`[Audio: ${i.data}]`;return n(a,"green")}return n("[Unknown content type]","gray")});return r+o.join(`
35
- `)}case"assistant":{let r=n("[ ASSISTANT","cyanBright");s.name&&(r+=` ${s.name}`),r+=" ]";let o=`${r}
36
- `;return s.content&&(o+=`${n(s.content,"cyan")}
37
- `),s.functionCalls&&s.functionCalls.length>0&&(o+=`${n("[ FUNCTION CALLS ]","yellow")}
38
- `,s.functionCalls.forEach((i,a)=>{let l=typeof i.function.params=="string"?i.function.params:JSON.stringify(i.function.params,null,2);o+=n(`${a+1}. ${i.function.name}(${l}) [id: ${i.id}]`,"yellowDim"),a<(s.functionCalls?.length??0)-1&&(o+=`
28
+ `),!m.body)throw new xt("Response body is null",u.href,e,{metrics:r});let g,h=0;if(typeof window<"u"&&typeof EventSource<"u")return new ReadableStream({start(y){let b=m.body.getReader(),S=new TextDecoder,w="";async function M(){try{for(;;){let{done:R,value:k}=await b.read();if(R){A=!0,y.close();break}w+=S.decode(k,{stream:!0});let F=w.split(`
29
+
30
+ `);w=F.pop()||"";for(let E of F){if(!E.trim())continue;let T=E.split(`
31
+ `),v="",C="message";for(let O of T)O.startsWith("data: ")?v=O.slice(6):O.startsWith("event: ")&&(C=O.slice(7));if(v){if(v==="[DONE]"){y.close();return}try{let O=JSON.parse(v);g=O,h++,r.streamChunks=h,r.lastChunkTime=Date.now(),y.enqueue(O),i.span?.addEvent("stream.chunk",{"stream.chunks":h,"stream.duration":Date.now()-r.startTime,"response.retries":r.retryCount,"sse.event.type":C})}catch(O){o&&console.warn("Skipping non-JSON SSE data:",v,O)}}}}}catch(R){let k=R,F={...r,streamDuration:Date.now()-r.startTime};k.name==="AbortError"||k.message?.includes("aborted")?y.error(new Ye(u.href,e,g,{streamMetrics:F})):y.error(new Ge(k,u.href,e,"[ReadableStream - consumed during streaming]",{streamMetrics:F}))}finally{b.releaseLock()}}M()}});let x=new TransformStream({transform(y,b){g=y,h++,r.streamChunks=h,r.lastChunkTime=Date.now(),b.enqueue(y),i.span?.addEvent("stream.chunk",{"stream.chunks":h,"stream.duration":Date.now()-r.startTime,"response.retries":r.retryCount})}}),A=!1;return new ReadableStream({start(y){let b=m.body.pipeThrough(new tc).pipeThrough(new Mr).pipeThrough(x).getReader();async function S(){try{for(;;){let{done:w,value:M}=await b.read();if(w){A||(A=!0,y.close());break}if(A)break;y.enqueue(M)}}catch(w){let M=w,R={...r,streamDuration:Date.now()-r.startTime};throw M.name==="AbortError"||M.message?.includes("aborted")?y.error(new Ye(u.href,e,g,{streamMetrics:R})):M instanceof TypeError&&M.message.includes("cancelled")?y.error(new Ye(u.href,e,g,{streamMetrics:R,cancelReason:"Stream cancelled by client"})):y.error(new Ge(M,u.href,e,"[ReadableStream - consumed during streaming]",{streamMetrics:R})),M}finally{s&&clearTimeout(s),b.releaseLock()}}S()},cancel(){A=!0}})}catch(m){if(m instanceof Error&&m.name==="AbortError")throw i.abortSignal?.aborted?new Ut(u.href,i.abortSignal.reason,e,{metrics:r}):new ot(u.href,n||0,e,{metrics:r});let g=m;if(!(m instanceof Pe)&&m instanceof Error&&(g=new Ge(m,u.href,e,void 0,{metrics:r})),i.span?.isRecording()&&(i.span.recordException(g),i.span.setAttributes({"error.time":Date.now()-r.startTime,"error.retries":r.retryCount})),g instanceof Ge&&qi(g,void 0,p,t)){let h=Bi(p,t);p++,ji(r),i.span?.addEvent("retry",{attempt:p,delay:h,error:g.message,"metrics.startTime":r.startTime,"metrics.retryCount":r.retryCount,"metrics.lastRetryTime":r.lastRetryTime}),await new Promise(f=>setTimeout(f,h));continue}throw g instanceof Pe&&(g.context.metrics=r),g}finally{s!==void 0&&clearTimeout(s)}}};var zi=typeof globalThis=="object"?globalThis:global;var yt="1.9.0";var Hi=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function oc(i){var e=new Set([i]),t=new Set,n=i.match(Hi);if(!n)return function(){return!1};var r={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(r.prerelease!=null)return function(l){return l===i};function o(a){return t.add(a),!1}function s(a){return e.add(a),!0}return function(l){if(e.has(l))return!0;if(t.has(l))return!1;var u=l.match(Hi);if(!u)return o(l);var c={major:+u[1],minor:+u[2],patch:+u[3],prerelease:u[4]};return c.prerelease!=null||r.major!==c.major?o(l):r.major===0?r.minor===c.minor&&r.patch<=c.patch?s(l):o(l):r.minor<=c.minor?s(l):o(l)}}var Ki=oc(yt);var sc=yt.split(".")[0],Dn=Symbol.for("opentelemetry.js.api."+sc),Gn=zi;function Bt(i,e,t,n){var r;n===void 0&&(n=!1);var o=Gn[Dn]=(r=Gn[Dn])!==null&&r!==void 0?r:{version:yt};if(!n&&o[i]){var s=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+i);return t.error(s.stack||s.message),!1}if(o.version!==yt){var s=new Error("@opentelemetry/api: Registration of version v"+o.version+" for "+i+" does not match previously registered API v"+yt);return t.error(s.stack||s.message),!1}return o[i]=e,t.debug("@opentelemetry/api: Registered a global for "+i+" v"+yt+"."),!0}function bt(i){var e,t,n=(e=Gn[Dn])===null||e===void 0?void 0:e.version;if(!(!n||!Ki(n)))return(t=Gn[Dn])===null||t===void 0?void 0:t[i]}function jt(i,e){e.debug("@opentelemetry/api: Unregistering a global for "+i+" v"+yt+".");var t=Gn[Dn];t&&delete t[i]}var ic=function(i,e){var t=typeof Symbol=="function"&&i[Symbol.iterator];if(!t)return i;var n=t.call(i),r,o=[],s;try{for(;(e===void 0||e-- >0)&&!(r=n.next()).done;)o.push(r.value)}catch(a){s={error:a}}finally{try{r&&!r.done&&(t=n.return)&&t.call(n)}finally{if(s)throw s.error}}return o},ac=function(i,e,t){if(t||arguments.length===2)for(var n=0,r=e.length,o;n<r;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return i.concat(o||Array.prototype.slice.call(e))},Vi=function(){function i(e){this._namespace=e.namespace||"DiagComponentLogger"}return i.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ln("debug",this._namespace,e)},i.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ln("error",this._namespace,e)},i.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ln("info",this._namespace,e)},i.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ln("warn",this._namespace,e)},i.prototype.verbose=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ln("verbose",this._namespace,e)},i}();function Ln(i,e,t){var n=bt("diag");if(n)return t.unshift(e),n[i].apply(n,ac([],ic(t),!1))}var Le;(function(i){i[i.NONE=0]="NONE",i[i.ERROR=30]="ERROR",i[i.WARN=50]="WARN",i[i.INFO=60]="INFO",i[i.DEBUG=70]="DEBUG",i[i.VERBOSE=80]="VERBOSE",i[i.ALL=9999]="ALL"})(Le||(Le={}));function Wi(i,e){i<Le.NONE?i=Le.NONE:i>Le.ALL&&(i=Le.ALL),e=e||{};function t(n,r){var o=e[n];return typeof o=="function"&&i>=r?o.bind(e):function(){}}return{error:t("error",Le.ERROR),warn:t("warn",Le.WARN),info:t("info",Le.INFO),debug:t("debug",Le.DEBUG),verbose:t("verbose",Le.VERBOSE)}}var lc=function(i,e){var t=typeof Symbol=="function"&&i[Symbol.iterator];if(!t)return i;var n=t.call(i),r,o=[],s;try{for(;(e===void 0||e-- >0)&&!(r=n.next()).done;)o.push(r.value)}catch(a){s={error:a}}finally{try{r&&!r.done&&(t=n.return)&&t.call(n)}finally{if(s)throw s.error}}return o},uc=function(i,e,t){if(t||arguments.length===2)for(var n=0,r=e.length,o;n<r;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return i.concat(o||Array.prototype.slice.call(e))},cc="diag",qt=function(){function i(){function e(r){return function(){for(var o=[],s=0;s<arguments.length;s++)o[s]=arguments[s];var a=bt("diag");if(a)return a[r].apply(a,uc([],lc(o),!1))}}var t=this,n=function(r,o){var s,a,l;if(o===void 0&&(o={logLevel:Le.INFO}),r===t){var u=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return t.error((s=u.stack)!==null&&s!==void 0?s:u.message),!1}typeof o=="number"&&(o={logLevel:o});var c=bt("diag"),p=Wi((a=o.logLevel)!==null&&a!==void 0?a:Le.INFO,r);if(c&&!o.suppressOverrideMessage){var d=(l=new Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";c.warn("Current logger will be overwritten from "+d),p.warn("Current logger will overwrite one already registered from "+d)}return Bt("diag",p,t,!0)};t.setLogger=n,t.disable=function(){jt(cc,t)},t.createComponentLogger=function(r){return new Vi(r)},t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error")}return i.instance=function(){return this._instance||(this._instance=new i),this._instance},i}();function Ji(i){return Symbol.for(i)}var pc=function(){function i(e){var t=this;t._currentContext=e?new Map(e):new Map,t.getValue=function(n){return t._currentContext.get(n)},t.setValue=function(n,r){var o=new i(t._currentContext);return o._currentContext.set(n,r),o},t.deleteValue=function(n){var r=new i(t._currentContext);return r._currentContext.delete(n),r}}return i}(),Yi=new pc;var dc=function(i,e){var t=typeof Symbol=="function"&&i[Symbol.iterator];if(!t)return i;var n=t.call(i),r,o=[],s;try{for(;(e===void 0||e-- >0)&&!(r=n.next()).done;)o.push(r.value)}catch(a){s={error:a}}finally{try{r&&!r.done&&(t=n.return)&&t.call(n)}finally{if(s)throw s.error}}return o},mc=function(i,e,t){if(t||arguments.length===2)for(var n=0,r=e.length,o;n<r;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return i.concat(o||Array.prototype.slice.call(e))},Qi=function(){function i(){}return i.prototype.active=function(){return Yi},i.prototype.with=function(e,t,n){for(var r=[],o=3;o<arguments.length;o++)r[o-3]=arguments[o];return t.call.apply(t,mc([n],dc(r),!1))},i.prototype.bind=function(e,t){return t},i.prototype.enable=function(){return this},i.prototype.disable=function(){return this},i}();var gc=function(i,e){var t=typeof Symbol=="function"&&i[Symbol.iterator];if(!t)return i;var n=t.call(i),r,o=[],s;try{for(;(e===void 0||e-- >0)&&!(r=n.next()).done;)o.push(r.value)}catch(a){s={error:a}}finally{try{r&&!r.done&&(t=n.return)&&t.call(n)}finally{if(s)throw s.error}}return o},hc=function(i,e,t){if(t||arguments.length===2)for(var n=0,r=e.length,o;n<r;n++)(o||!(n in e))&&(o||(o=Array.prototype.slice.call(e,0,n)),o[n]=e[n]);return i.concat(o||Array.prototype.slice.call(e))},gs="context",fc=new Qi,zt=function(){function i(){}return i.getInstance=function(){return this._instance||(this._instance=new i),this._instance},i.prototype.setGlobalContextManager=function(e){return Bt(gs,e,qt.instance())},i.prototype.active=function(){return this._getContextManager().active()},i.prototype.with=function(e,t,n){for(var r,o=[],s=3;s<arguments.length;s++)o[s-3]=arguments[s];return(r=this._getContextManager()).with.apply(r,hc([e,t,n],gc(o),!1))},i.prototype.bind=function(e,t){return this._getContextManager().bind(e,t)},i.prototype._getContextManager=function(){return bt(gs)||fc},i.prototype.disable=function(){this._getContextManager().disable(),jt(gs,qt.instance())},i}();var Pr;(function(i){i[i.NONE=0]="NONE",i[i.SAMPLED=1]="SAMPLED"})(Pr||(Pr={}));var hs="0000000000000000",fs="00000000000000000000000000000000",Xi={traceId:fs,spanId:hs,traceFlags:Pr.NONE};var Rt=function(){function i(e){e===void 0&&(e=Xi),this._spanContext=e}return i.prototype.spanContext=function(){return this._spanContext},i.prototype.setAttribute=function(e,t){return this},i.prototype.setAttributes=function(e){return this},i.prototype.addEvent=function(e,t){return this},i.prototype.addLink=function(e){return this},i.prototype.addLinks=function(e){return this},i.prototype.setStatus=function(e){return this},i.prototype.updateName=function(e){return this},i.prototype.end=function(e){},i.prototype.isRecording=function(){return!1},i.prototype.recordException=function(e,t){},i}();var xs=Ji("OpenTelemetry Context Key SPAN");function Fr(i){return i.getValue(xs)||void 0}function Zi(){return Fr(zt.getInstance().active())}function Un(i,e){return i.setValue(xs,e)}function ea(i){return i.deleteValue(xs)}function ta(i,e){return Un(i,new Rt(e))}function _r(i){var e;return(e=Fr(i))===null||e===void 0?void 0:e.spanContext()}var xc=/^([0-9a-f]{32})$/i,Ac=/^[0-9a-f]{16}$/i;function yc(i){return xc.test(i)&&i!==fs}function bc(i){return Ac.test(i)&&i!==hs}function $r(i){return yc(i.traceId)&&bc(i.spanId)}function na(i){return new Rt(i)}var As=zt.getInstance(),Nr=function(){function i(){}return i.prototype.startSpan=function(e,t,n){n===void 0&&(n=As.active());var r=!!t?.root;if(r)return new Rt;var o=n&&_r(n);return Ic(o)&&$r(o)?new Rt(o):new Rt},i.prototype.startActiveSpan=function(e,t,n,r){var o,s,a;if(!(arguments.length<2)){arguments.length===2?a=t:arguments.length===3?(o=t,a=n):(o=t,s=n,a=r);var l=s??As.active(),u=this.startSpan(e,o,l),c=Un(l,u);return As.with(c,a,void 0,u)}},i}();function Ic(i){return typeof i=="object"&&typeof i.spanId=="string"&&typeof i.traceId=="string"&&typeof i.traceFlags=="number"}var Tc=new Nr,ra=function(){function i(e,t,n,r){this._provider=e,this.name=t,this.version=n,this.options=r}return i.prototype.startSpan=function(e,t,n){return this._getTracer().startSpan(e,t,n)},i.prototype.startActiveSpan=function(e,t,n,r){var o=this._getTracer();return Reflect.apply(o.startActiveSpan,o,arguments)},i.prototype._getTracer=function(){if(this._delegate)return this._delegate;var e=this._provider.getDelegateTracer(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):Tc},i}();var oa=function(){function i(){}return i.prototype.getTracer=function(e,t,n){return new Nr},i}();var Cc=new oa,ys=function(){function i(){}return i.prototype.getTracer=function(e,t,n){var r;return(r=this.getDelegateTracer(e,t,n))!==null&&r!==void 0?r:new ra(this,e,t,n)},i.prototype.getDelegate=function(){var e;return(e=this._delegate)!==null&&e!==void 0?e:Cc},i.prototype.setDelegate=function(e){this._delegate=e},i.prototype.getDelegateTracer=function(e,t,n){var r;return(r=this._delegate)===null||r===void 0?void 0:r.getTracer(e,t,n)},i}();var Be;(function(i){i[i.INTERNAL=0]="INTERNAL",i[i.SERVER=1]="SERVER",i[i.CLIENT=2]="CLIENT",i[i.PRODUCER=3]="PRODUCER",i[i.CONSUMER=4]="CONSUMER"})(Be||(Be={}));var vt=zt.getInstance();var bs="trace",sa=function(){function i(){this._proxyTracerProvider=new ys,this.wrapSpanContext=na,this.isSpanContextValid=$r,this.deleteSpan=ea,this.getSpan=Fr,this.getActiveSpan=Zi,this.getSpanContext=_r,this.setSpan=Un,this.setSpanContext=ta}return i.getInstance=function(){return this._instance||(this._instance=new i),this._instance},i.prototype.setGlobalTracerProvider=function(e){var t=Bt(bs,this._proxyTracerProvider,qt.instance());return t&&this._proxyTracerProvider.setDelegate(e),t},i.prototype.getTracerProvider=function(){return bt(bs)||this._proxyTracerProvider},i.prototype.getTracer=function(e,t){return this.getTracerProvider().getTracer(e,t)},i.prototype.disable=function(){jt(bs,qt.instance()),this._proxyTracerProvider=new ys},i}();var Bn=sa.getInstance();var ee={signatureStrict:!0,useStructuredPrompt:!0,tracer:void 0,meter:void 0,logger:void 0,optimizerLogger:void 0,debug:void 0,abortSignal:void 0,cachingFunction:void 0,functionResultFormatter:i=>typeof i=="string"?i:i==null?"":JSON.stringify(i,null,2)};var Ue=class{ANSI_WHITE_BRIGHT="\x1B[97m";ANSI_GREEN_BRIGHT="\x1B[92m";ANSI_BLUE_BRIGHT="\x1B[94m";ANSI_RED_BRIGHT="\x1B[91m";ANSI_YELLOW_BRIGHT="\x1B[93m";ANSI_YELLOW="\x1B[93m";ANSI_RED="\x1B[91m";ANSI_RESET="\x1B[0m";ANSI_ORANGE="\x1B[38;5;208m";ANSI_WHITE="\x1B[37m";ANSI_CYAN_BRIGHT="\x1B[96m";ANSI_MAGENTA_BRIGHT="\x1B[95m";ANSI_GRAY="\x1B[90m";ANSI_GREEN="\x1B[32m";ANSI_CYAN="\x1B[36m";ANSI_MAGENTA="\x1B[35m";ANSI_BLUE="\x1B[34m";ANSI_YELLOW_DIM="\x1B[33m";colorize(e,t){return`${t}${e}${this.ANSI_RESET}`}whiteBright(e){return this.colorize(e,this.ANSI_WHITE_BRIGHT)}greenBright(e){return this.colorize(e,this.ANSI_GREEN_BRIGHT)}blueBright(e){return this.colorize(e,this.ANSI_BLUE_BRIGHT)}redBright(e){return this.colorize(e,this.ANSI_RED_BRIGHT)}white(e){return this.colorize(e,this.ANSI_WHITE)}yellow(e){return this.colorize(e,this.ANSI_YELLOW)}yellowBright(e){return this.colorize(e,this.ANSI_YELLOW_BRIGHT)}red(e){return this.colorize(e,this.ANSI_RED)}orange(e){return this.colorize(e,this.ANSI_ORANGE)}cyanBright(e){return this.colorize(e,this.ANSI_CYAN_BRIGHT)}magentaBright(e){return this.colorize(e,this.ANSI_MAGENTA_BRIGHT)}gray(e){return this.colorize(e,this.ANSI_GRAY)}green(e){return this.colorize(e,this.ANSI_GREEN)}cyan(e){return this.colorize(e,this.ANSI_CYAN)}magenta(e){return this.colorize(e,this.ANSI_MAGENTA)}blue(e){return this.colorize(e,this.ANSI_BLUE)}yellowDim(e){return this.colorize(e,this.ANSI_YELLOW_DIM)}};var ym=new Ue,ia=i=>{console.log(i)},aa=(i,e,t)=>{let n=(r,o)=>t&&o&&o in t?t[o](r):r;switch(i.role){case"system":return`${n("[ SYSTEM ]","magentaBright")}
32
+ ${n(i.content,"magenta")}`;case"function":return`${n("[ FUNCTION RESULT ]","yellow")}
33
+ ${n(i.result??"[No result]","yellowDim")}`;case"user":{let r=`${n("[ USER ]","greenBright")}
34
+ `;if(typeof i.content=="string")return r+n(i.content,"green");let o=i.content.map(s=>{if(s.type==="text")return n(s.text,"green");if(s.type==="image"){let a=e?"[Image]":`[Image: ${s.image}]`;return n(a,"green")}if(s.type==="audio"){let a=e?"[Audio]":`[Audio: ${s.data}]`;return n(a,"green")}return n("[Unknown content type]","gray")});return r+o.join(`
35
+ `)}case"assistant":{let r=n("[ ASSISTANT","cyanBright");i.name&&(r+=` ${i.name}`),r+=" ]";let o=`${r}
36
+ `;return i.content&&(o+=`${n(i.content,"cyan")}
37
+ `),i.functionCalls&&i.functionCalls.length>0&&(o+=`${n("[ FUNCTION CALLS ]","yellow")}
38
+ `,i.functionCalls.forEach((s,a)=>{let l=typeof s.function.params=="string"?s.function.params:JSON.stringify(s.function.params,null,2);o+=n(`${a+1}. ${s.function.name}(${l}) [id: ${s.id}]`,"yellowDim"),a<(i.functionCalls?.length??0)-1&&(o+=`
39
39
  `)}),o+=`
40
- `),!s.content&&(!s.functionCalls||s.functionCalls.length===0)&&(o+=n("[No content]","gray")),o}default:return`${n("[ UNKNOWN ]","redBright")}
41
- ${n(JSON.stringify(s),"gray")}`}},bs=(s=oa)=>{let e=new Ge,t=e.gray(`${"\u2500".repeat(60)}
40
+ `),!i.content&&(!i.functionCalls||i.functionCalls.length===0)&&(o+=n("[No content]","gray")),o}default:return`${n("[ UNKNOWN ]","redBright")}
41
+ ${n(JSON.stringify(i),"gray")}`}},Is=(i=ia)=>{let e=new Ue,t=e.gray(`${"\u2500".repeat(60)}
42
42
  `);return n=>{let r=n,o="";switch(r.name){case"ChatRequestChatPrompt":o=`
43
43
  ${e.blueBright(`[ CHAT REQUEST Step ${r.step} ]`)}
44
44
  ${t}
45
- `,r.value.forEach((i,a)=>{o+=sa(i,void 0,e),a<r.value.length-1&&(o+=`
45
+ `,r.value.forEach((s,a)=>{o+=aa(s,void 0,e),a<r.value.length-1&&(o+=`
46
46
  ${t}
47
47
  `)}),o+=`
48
48
  ${t}`;break;case"FunctionResults":o=`
49
49
  ${e.yellow("[ FUNCTION RESULTS ]")}
50
- `,r.value.forEach((i,a)=>{o+=e.yellowDim(`Function: ${i.functionId}
51
- Result: ${i.result}`),a<r.value.length-1&&(o+=`
50
+ `,r.value.forEach((s,a)=>{o+=e.yellowDim(`Function: ${s.functionId}
51
+ Result: ${s.result}`),a<r.value.length-1&&(o+=`
52
52
  ${t}
53
53
  `)});break;case"ChatResponseResults":o=`
54
54
  ${e.cyanBright("[ CHAT RESPONSE ]")}
55
- `,r.value.forEach((i,a)=>{let l=[],u=i.thoughtBlocks?.some(c=>c.encrypted);i.thought&&l.push(e.gray(`[THOUGHT${u?" (redacted)":""}]
56
- ${i.thought}`)),i.content&&l.push(e.cyan(i.content)),l.length===0&&l.push(e.gray("[No content]")),o+=l.join(`
55
+ `,r.value.forEach((s,a)=>{let l=[],u=s.thoughtBlocks?.some(c=>c.encrypted);s.thought&&l.push(e.gray(`[THOUGHT${u?" (redacted)":""}]
56
+ ${s.thought}`)),s.content&&l.push(e.cyan(s.content)),l.length===0&&l.push(e.gray("[No content]")),o+=l.join(`
57
57
  `),a<r.value.length-1&&(o+=`
58
58
  ${t}
59
- `)});break;case"ChatResponseStreamingResult":{let i=r.value.thought,a=i||r.value.delta||r.value.content||"";o=i?e.gray(`[THOUGHT]
60
- ${i}`):e.cyanBright(a);break}case"ChatResponseStreamingDoneResult":{o=`
59
+ `)});break;case"ChatResponseStreamingResult":{let s=r.value.thought,a=s||r.value.delta||r.value.content||"";o=s?e.gray(`[THOUGHT]
60
+ ${s}`):e.cyanBright(a);break}case"ChatResponseStreamingDoneResult":{o=`
61
61
  ${e.cyanBright("[ CHAT RESPONSE ]")}
62
62
  ${t}
63
- `,r.value.content&&(o+=e.cyanBright(r.value.content));let i=r.value.thoughtBlocks?.some(a=>a.encrypted);r.value.thought&&(o+=`
64
- `,o+=e.gray(`[THOUGHT${i?" (redacted)":""}]
63
+ `,r.value.content&&(o+=e.cyanBright(r.value.content));let s=r.value.thoughtBlocks?.some(a=>a.encrypted);r.value.thought&&(o+=`
64
+ `,o+=e.gray(`[THOUGHT${s?" (redacted)":""}]
65
65
  `+r.value.thought)),r.value.functionCalls&&(o+=e.cyanBright(JSON.stringify(r.value.functionCalls,null,2)));break}case"FunctionError":o=`
66
66
  ${e.redBright(`[ FUNCTION ERROR #${r.index} ]`)}
67
67
  ${t}
@@ -80,48 +80,48 @@ ${e.green(`Selected sample ${r.selectedIndex+1} of ${r.sampleCount} (${r.latency
80
80
  ${t}
81
81
  ${e.white(r.value)}`;break;case"EmbedRequest":o=`${e.orange(`[ EMBED REQUEST ${r.embedModel} ]`)}
82
82
  ${t}
83
- `,r.value.forEach((i,a)=>{o+=e.white(`Text ${a+1}: ${i.substring(0,100)}${i.length>100?"...":""}`),a<r.value.length-1&&(o+=`
83
+ `,r.value.forEach((s,a)=>{o+=e.white(`Text ${a+1}: ${s.substring(0,100)}${s.length>100?"...":""}`),a<r.value.length-1&&(o+=`
84
84
  ${t}
85
85
  `)});break;case"EmbedResponse":o=`${e.orange(`[ EMBED RESPONSE (${r.totalEmbeddings} embeddings) ]`)}
86
86
  ${t}
87
- `,r.value.forEach((i,a)=>{o+=e.white(`Embedding ${a+1}: [${i.sample.join(", ")}${i.truncated?", ...":""}] (length: ${i.length})`),a<r.value.length-1&&(o+=`
87
+ `,r.value.forEach((s,a)=>{o+=e.white(`Embedding ${a+1}: [${s.sample.join(", ")}${s.truncated?", ...":""}] (length: ${s.length})`),a<r.value.length-1&&(o+=`
88
88
  ${t}
89
89
  `)});break;case"ChatResponseUsage":{o=`${e.greenBright(`
90
90
  [ CHAT RESPONSE USAGE ]`)}
91
- `;let i=r.value;o+=`${e.white("AI:")} ${i.ai}
92
- `,o+=`${e.white("Model:")} ${i.model}
93
- `,i.tokens&&(o+=`${e.white("Total Tokens:")} ${i.tokens.totalTokens}
94
- `,o+=`${e.white("Prompt Tokens:")} ${i.tokens.promptTokens}
95
- `,o+=`${e.white("Completion Tokens:")} ${i.tokens.completionTokens}
96
- `,i.tokens.thoughtsTokens!==void 0&&(o+=`${e.white("Thoughts Tokens:")} ${i.tokens.thoughtsTokens}
97
- `),i.tokens.reasoningTokens!==void 0&&(o+=`${e.white("Reasoning Tokens:")} ${i.tokens.reasoningTokens}
98
- `),i.tokens.cacheCreationTokens!==void 0&&(o+=`${e.white("Cache Creation Tokens:")} ${i.tokens.cacheCreationTokens}
99
- `),i.tokens.cacheReadTokens!==void 0&&(o+=`${e.white("Cache Read Tokens:")} ${i.tokens.cacheReadTokens}
100
- `),i.tokens.serviceTier!==void 0&&(o+=`${e.white("Service Tier:")} ${i.tokens.serviceTier}
91
+ `;let s=r.value;o+=`${e.white("AI:")} ${s.ai}
92
+ `,o+=`${e.white("Model:")} ${s.model}
93
+ `,s.tokens&&(o+=`${e.white("Total Tokens:")} ${s.tokens.totalTokens}
94
+ `,o+=`${e.white("Prompt Tokens:")} ${s.tokens.promptTokens}
95
+ `,o+=`${e.white("Completion Tokens:")} ${s.tokens.completionTokens}
96
+ `,s.tokens.thoughtsTokens!==void 0&&(o+=`${e.white("Thoughts Tokens:")} ${s.tokens.thoughtsTokens}
97
+ `),s.tokens.reasoningTokens!==void 0&&(o+=`${e.white("Reasoning Tokens:")} ${s.tokens.reasoningTokens}
98
+ `),s.tokens.cacheCreationTokens!==void 0&&(o+=`${e.white("Cache Creation Tokens:")} ${s.tokens.cacheCreationTokens}
99
+ `),s.tokens.cacheReadTokens!==void 0&&(o+=`${e.white("Cache Read Tokens:")} ${s.tokens.cacheReadTokens}
100
+ `),s.tokens.serviceTier!==void 0&&(o+=`${e.white("Service Tier:")} ${s.tokens.serviceTier}
101
101
  `)),o+=t;break}case"ChatResponseCitations":{o=`${e.blueBright(`
102
102
  [ CHAT RESPONSE CITATIONS ]`)}
103
- `,r.value.forEach(i=>{o+=`${e.white("- ")}${e.cyan(i.title||i.url)}
104
- `,i.description&&(o+=` ${e.gray(i.description)}
105
- `)}),o+=t;break}default:o=e.gray(JSON.stringify(r,null,2))}s(o)}},ia=bs(),aa=(s=oa)=>{let e="\u2500".repeat(60);return t=>{let n=t,r="";switch(n.name){case"ChatRequestChatPrompt":r=`
103
+ `,r.value.forEach(s=>{o+=`${e.white("- ")}${e.cyan(s.title||s.url)}
104
+ `,s.description&&(o+=` ${e.gray(s.description)}
105
+ `)}),o+=t;break}default:o=e.gray(JSON.stringify(r,null,2))}i(o)}},la=Is(),ua=(i=ia)=>{let e="\u2500".repeat(60);return t=>{let n=t,r="";switch(n.name){case"ChatRequestChatPrompt":r=`
106
106
  [ CHAT REQUEST Step ${n.step} ]
107
107
  ${e}
108
- `,n.value.forEach((o,i)=>{r+=sa(o),i<n.value.length-1&&(r+=`
108
+ `,n.value.forEach((o,s)=>{r+=aa(o),s<n.value.length-1&&(r+=`
109
109
  ${e}
110
110
  `)}),r+=`
111
111
  ${e}`;break;case"FunctionResults":r=`
112
112
  [ FUNCTION RESULTS ]
113
113
  ${e}
114
- `,n.value.forEach((o,i)=>{r+=`Function: ${o.functionId}
115
- Result: ${o.result}`,i<n.value.length-1&&(r+=`
114
+ `,n.value.forEach((o,s)=>{r+=`Function: ${o.functionId}
115
+ Result: ${o.result}`,s<n.value.length-1&&(r+=`
116
116
  ${e}
117
117
  `)});break;case"ChatResponseResults":r=`
118
118
  [ CHAT RESPONSE ]
119
- `,n.value.forEach((o,i)=>{let a=[],l=o.thoughtBlocks?.some(u=>u.encrypted);o.thought&&a.push(`[thought${l?" (redacted)":""}] ${o.thought}`),o.content&&a.push(o.content),a.length===0&&a.push("[No content]"),r+=a.join(`
120
- `),i<n.value.length-1&&(r+=`
119
+ `,n.value.forEach((o,s)=>{let a=[],l=o.thoughtBlocks?.some(u=>u.encrypted);o.thought&&a.push(`[thought${l?" (redacted)":""}] ${o.thought}`),o.content&&a.push(o.content),a.length===0&&a.push("[No content]"),r+=a.join(`
120
+ `),s<n.value.length-1&&(r+=`
121
121
  ${e}
122
122
  `)});break;case"ChatResponseStreamingResult":return;case"ChatResponseStreamingDoneResult":{r=`
123
123
  [ CHAT RESPONSE ]
124
- `,n.value.content&&(r+=n.value.content);let o=n.value.thoughtBlocks?.some(i=>i.encrypted);n.value.thought&&(r+=`
124
+ `,n.value.content&&(r+=n.value.content);let o=n.value.thoughtBlocks?.some(s=>s.encrypted);n.value.thought&&(r+=`
125
125
  `,r+=`[thought${o?" (redacted)":""}] `+n.value.thought),n.value.functionCalls&&(r+=JSON.stringify(n.value.functionCalls,null,2));break}case"FunctionError":r=`
126
126
  [ FUNCTION ERROR #${n.index} ]
127
127
  ${e}
@@ -140,11 +140,11 @@ Selected sample ${n.selectedIndex+1} of ${n.sampleCount} (${n.latency.toFixed(2)
140
140
  ${e}
141
141
  ${n.value}`;break;case"EmbedRequest":r=`[ EMBED REQUEST ${n.embedModel} ]
142
142
  ${e}
143
- `,n.value.forEach((o,i)=>{r+=`Text ${i+1}: ${o.substring(0,100)}${o.length>100?"...":""}`,i<n.value.length-1&&(r+=`
143
+ `,n.value.forEach((o,s)=>{r+=`Text ${s+1}: ${o.substring(0,100)}${o.length>100?"...":""}`,s<n.value.length-1&&(r+=`
144
144
  ${e}
145
145
  `)});break;case"EmbedResponse":r=`[ EMBED RESPONSE (${n.totalEmbeddings} embeddings) ]
146
146
  ${e}
147
- `,n.value.forEach((o,i)=>{r+=`Embedding ${i+1}: [${o.sample.join(", ")}${o.truncated?", ...":""}] (length: ${o.length})`,i<n.value.length-1&&(r+=`
147
+ `,n.value.forEach((o,s)=>{r+=`Embedding ${s+1}: [${o.sample.join(", ")}${o.truncated?", ...":""}] (length: ${o.length})`,s<n.value.length-1&&(r+=`
148
148
  ${e}
149
149
  `)});break;case"ChatResponseUsage":{r=`
150
150
  [ CHAT RESPONSE USAGE ]
@@ -164,23 +164,23 @@ ${e}
164
164
  `,n.value.forEach(o=>{r+=`- ${o.title||o.url}
165
165
  `,o.description&&(r+=` ${o.description}
166
166
  `)}),r+=`${e}
167
- `;break}default:r=JSON.stringify(n,null,2)}s(r)}};var Y={LLM_SYSTEM:"gen_ai.system",LLM_OPERATION_NAME:"gen_ai.operation.name",LLM_REQUEST_MODEL:"gen_ai.request.model",LLM_REQUEST_MAX_TOKENS:"gen_ai.request.max_tokens",LLM_REQUEST_TEMPERATURE:"gen_ai.request.temperature",LLM_REQUEST_TOP_K:"gen_ai.request.top_k",LLM_REQUEST_FREQUENCY_PENALTY:"gen_ai.request.frequency_penalty",LLM_REQUEST_PRESENCE_PENALTY:"gen_ai.request.presence_penalty",LLM_REQUEST_STOP_SEQUENCES:"gen_ai.request.stop_sequences",LLM_REQUEST_LLM_IS_STREAMING:"gen_ai.request.llm_is_streaming",LLM_REQUEST_TOP_P:"gen_ai.request.top_p",LLM_USAGE_INPUT_TOKENS:"gen_ai.usage.input_tokens",LLM_USAGE_OUTPUT_TOKENS:"gen_ai.usage.output_tokens",LLM_USAGE_TOTAL_TOKENS:"gen_ai.usage.total_tokens",LLM_USAGE_THOUGHTS_TOKENS:"gen_ai.usage.thoughts_tokens",DB_SYSTEM:"db.system",DB_TABLE:"db.table",DB_NAMESPACE:"db.namespace",DB_ID:"db.id",DB_QUERY_TEXT:"db.query.text",DB_VECTOR:"db.vector",DB_OPERATION_NAME:"db.operation.name",DB_VECTOR_QUERY_TOP_K:"db.vector.query.top_k",DB_QUERY_EMBEDDINGS:"db.query.embeddings",DB_QUERY_RESULT:"db.query.result",DB_QUERY_EMBEDDINGS_VECTOR:"db.query.embeddings.vector",DB_QUERY_RESULT_ID:"db.query.result.id",DB_QUERY_RESULT_SCORE:"db.query.result.score",DB_QUERY_RESULT_DISTANCE:"db.query.result.distance",DB_QUERY_RESULT_METADATA:"db.query.result.metadata",DB_QUERY_RESULT_VECTOR:"db.query.result.vector",DB_QUERY_RESULT_DOCUMENT:"db.query.result.document"},it={GEN_AI_USER_MESSAGE:"gen_ai.user.message",GEN_AI_SYSTEM_MESSAGE:"gen_ai.system.message",GEN_AI_ASSISTANT_MESSAGE:"gen_ai.assistant.message",GEN_AI_TOOL_MESSAGE:"gen_ai.tool.message",GEN_AI_CHOICE:"gen_ai.choice",GEN_AI_USAGE:"gen_ai.usage"},Is=(r=>(r.COMPLETION="completion",r.CHAT="chat",r.RERANK="rerank",r.UNKNOWN="unknown",r))(Is||{}),Ts=(o=>(o.WORKFLOW="workflow",o.TASK="task",o.AGENT="agent",o.TOOL="tool",o.UNKNOWN="unknown",o))(Ts||{});var Cs=class{buffer;doneCallback;transformFn;constructor(e,t){this.transformFn=e,this.doneCallback=t,this.buffer=t?[]:void 0}async transform(e,t){let n=this.transformFn(e);n&&(t.enqueue(n),this.buffer?.push(n))}async flush(e){await this.doneCallback?.(this.buffer??[]),e.terminate()}},Nr=class extends TransformStream{constructor(e,t){super(new Cs(e,t))}};function Dr(s,e){for(let t of e){let n=s.find(r=>r.id===t.id);n?(typeof t.function.name=="string"&&t.function.name.length>0&&(n.function.name+=t.function.name),typeof t.function.params=="string"&&t.function.params.length>0&&(n.function.params+=t.function.params),typeof t.function.params=="object"&&(n.function.params=t.function.params)):s.push(t)}}var la=(s,e,t,n)=>{let r=n?s.filter(i=>i.role!=="system"):[...s];t({name:"ChatRequestChatPrompt",step:e,value:r})};var ua=(s,e)=>{if(!s.results)return;let t={name:"ChatResponseResults",value:s.results};e(t)};function ca(s,e){let t=new Map;for(let n of s)for(let r of n.results){if(!r)continue;let o=t.get(r.index);o?(r.content&&(o.content=(o.content??"")+r.content),r.thought&&(o.thought=(o.thought??"")+r.thought),r.finishReason&&(o.finishReason=r.finishReason),r.functionCalls&&(o.functionCalls?Dr(o.functionCalls,structuredClone(r.functionCalls)):o.functionCalls=structuredClone(r.functionCalls))):(o=structuredClone(r),t.set(r.index,o))}for(let n of t.values()){let r={name:"ChatResponseStreamingDoneResult",index:n.index,value:n};e(r)}}var pa=(s,e)=>{e({name:"FunctionResults",value:s})},ws=(s,e,t,n)=>{n({name:"FunctionError",index:e,fixingInstructions:t,error:s})},da=(s,e,t,n)=>{n({name:"ValidationError",index:e,fixingInstructions:t,error:s})},ma=(s,e,t,n)=>{n({name:"AssertionError",index:e,fixingInstructions:t,error:s})},ga=(s,e,t)=>{t({name:"RefusalError",index:e,error:s})};var ha=(s,e,t)=>{t({name:"EmbedRequest",embedModel:e,value:s})},fa=(s,e)=>{let t=s.slice(0,3).map(r=>({length:r.length,sample:r.slice(0,5),truncated:r.length>5})),n={name:"EmbedResponse",totalEmbeddings:s.length,value:t};e(n)},xa=(s,e,t,n)=>{n({name:"ResultPickerUsed",sampleCount:s,selectedIndex:e,latency:t})};var Rs=s=>{let e={};for(let[t,n]of Object.entries(s))if(n!=null){let r=String(n);e[t]=r.length>100?r.substring(0,100):r}return e},Lr,Aa=s=>{if(Lr)return Lr;if(s)return Lr=Ic(s),Lr};var Ic=s=>({latencyHistogram:s.createHistogram("ax_llm_request_duration_ms",{description:"Duration of LLM requests in milliseconds",unit:"ms"}),errorCounter:s.createCounter("ax_llm_errors_total",{description:"Total number of LLM request errors"}),requestCounter:s.createCounter("ax_llm_requests_total",{description:"Total number of LLM requests"}),tokenCounter:s.createCounter("ax_llm_tokens_total",{description:"Total number of LLM tokens consumed"}),inputTokenCounter:s.createCounter("ax_llm_input_tokens_total",{description:"Total number of input/prompt tokens consumed"}),outputTokenCounter:s.createCounter("ax_llm_output_tokens_total",{description:"Total number of output/completion tokens generated"}),errorRateGauge:s.createGauge("ax_llm_error_rate",{description:"Current error rate as a percentage (0-100)"}),meanLatencyGauge:s.createGauge("ax_llm_mean_latency_ms",{description:"Mean latency of LLM requests in milliseconds",unit:"ms"}),p95LatencyGauge:s.createGauge("ax_llm_p95_latency_ms",{description:"95th percentile latency of LLM requests in milliseconds",unit:"ms"}),p99LatencyGauge:s.createGauge("ax_llm_p99_latency_ms",{description:"99th percentile latency of LLM requests in milliseconds",unit:"ms"}),streamingRequestsCounter:s.createCounter("ax_llm_streaming_requests_total",{description:"Total number of streaming LLM requests"}),functionCallsCounter:s.createCounter("ax_llm_function_calls_total",{description:"Total number of function/tool calls made"}),functionCallLatencyHistogram:s.createHistogram("ax_llm_function_call_latency_ms",{description:"Latency of function calls in milliseconds",unit:"ms"}),requestSizeHistogram:s.createHistogram("ax_llm_request_size_bytes",{description:"Size of LLM request payloads in bytes",unit:"By"}),responseSizeHistogram:s.createHistogram("ax_llm_response_size_bytes",{description:"Size of LLM response payloads in bytes",unit:"By"}),temperatureGauge:s.createGauge("ax_llm_temperature_gauge",{description:"Temperature setting used for LLM requests"}),maxTokensGauge:s.createGauge("ax_llm_max_tokens_gauge",{description:"Maximum tokens setting used for LLM requests"}),estimatedCostCounter:s.createCounter("ax_llm_estimated_cost_total",{description:"Estimated cost of LLM requests in USD",unit:"$"}),promptLengthHistogram:s.createHistogram("ax_llm_prompt_length_chars",{description:"Length of prompts in characters"}),contextWindowUsageGauge:s.createGauge("ax_llm_context_window_usage_ratio",{description:"Context window utilization ratio (0-1)"}),timeoutsCounter:s.createCounter("ax_llm_timeouts_total",{description:"Total number of timed out LLM requests"}),abortsCounter:s.createCounter("ax_llm_aborts_total",{description:"Total number of aborted LLM requests"}),thinkingBudgetUsageCounter:s.createCounter("ax_llm_thinking_budget_usage_total",{description:"Total thinking budget tokens used"}),multimodalRequestsCounter:s.createCounter("ax_llm_multimodal_requests_total",{description:"Total number of multimodal requests (with images/audio)"})}),ya=(s,e,t,n,r)=>{try{if(s.latencyHistogram){let o=Rs({operation:e,ai_service:n,...r?{model:r}:{}});s.latencyHistogram.record(t,o)}}catch(o){console.warn("Failed to record latency metric:",o)}},ba=(s,e,t,n,r,o,i)=>{let a={operation:e,ai_service:o,...i?{model:i}:{}};s.meanLatencyGauge&&s.meanLatencyGauge.record(t,a),s.p95LatencyGauge&&s.p95LatencyGauge.record(n,a),s.p99LatencyGauge&&s.p99LatencyGauge.record(r,a)},Ia=(s,e,t,n)=>{try{if(s.errorCounter){let r=Rs({operation:e,ai_service:t,...n?{model:n}:{}});s.errorCounter.add(1,r)}}catch(r){console.warn("Failed to record error metric:",r)}},Ta=(s,e,t,n,r)=>{s.errorRateGauge&&s.errorRateGauge.record(t*100,{operation:e,ai_service:n,...r?{model:r}:{}})},Ca=(s,e,t,n)=>{s.requestCounter&&s.requestCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{}})},jn=(s,e,t,n,r)=>{try{let o=Rs({ai_service:n,...r?{model:r}:{}});s.tokenCounter&&s.tokenCounter.add(t,{token_type:e,...o}),e==="input"&&s.inputTokenCounter&&s.inputTokenCounter.add(t,o),e==="output"&&s.outputTokenCounter&&s.outputTokenCounter.add(t,o)}catch(o){console.warn("Failed to record token metric:",o)}},wa=(s,e,t,n,r)=>{t&&s.streamingRequestsCounter&&s.streamingRequestsCounter.add(1,{operation:e,ai_service:n,...r?{model:r}:{}})},Ra=(s,e,t,n,r)=>{let o={function_name:e,...n?{ai_service:n}:{},...r?{model:r}:{}};s.functionCallsCounter&&s.functionCallsCounter.add(1,o),t&&s.functionCallLatencyHistogram&&s.functionCallLatencyHistogram.record(t,o)},vs=(s,e,t,n,r)=>{s.requestSizeHistogram&&s.requestSizeHistogram.record(t,{operation:e,ai_service:n,...r?{model:r}:{}})},Ss=(s,e,t,n,r)=>{s.responseSizeHistogram&&s.responseSizeHistogram.record(t,{operation:e,ai_service:n,...r?{model:r}:{}})},va=(s,e,t,n,r)=>{let o={...n?{ai_service:n}:{},...r?{model:r}:{}};e!==void 0&&s.temperatureGauge&&s.temperatureGauge.record(e,o),t!==void 0&&s.maxTokensGauge&&s.maxTokensGauge.record(t,o)},Os=(s,e,t,n,r)=>{s.estimatedCostCounter&&s.estimatedCostCounter.add(t,{operation:e,ai_service:n,...r?{model:r}:{}})},Sa=(s,e,t,n)=>{s.promptLengthHistogram&&s.promptLengthHistogram.record(e,{ai_service:t,...n?{model:n}:{}})},Oa=(s,e,t,n)=>{s.contextWindowUsageGauge&&s.contextWindowUsageGauge.record(e,{ai_service:t,...n?{model:n}:{}})},ka=(s,e,t,n)=>{s.timeoutsCounter&&s.timeoutsCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{}})},Ma=(s,e,t,n)=>{s.abortsCounter&&s.abortsCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{}})},Ea=(s,e,t,n)=>{s.thinkingBudgetUsageCounter&&s.thinkingBudgetUsageCounter.add(e,{ai_service:t,...n?{model:n}:{}})},Pa=(s,e,t,n,r)=>{(e||t)&&s.multimodalRequestsCounter&&s.multimodalRequestsCounter.add(1,{ai_service:n,has_images:e.toString(),has_audio:t.toString(),...r?{model:r}:{}})};function Fa(s){try{return JSON.stringify(s,null,2)}catch{return String(s)}}function at(s,e={}){let t=[s];throw e.fieldPath!==void 0&&t.push(`Field: ${e.fieldPath}`),e.value!==void 0&&t.push(`Value: ${Fa(e.value)}`),e.note&&t.push(`Note: ${e.note}`),e.item!==void 0&&t.push(`Chat item: ${Fa(e.item)}`),new Error(t.join(`
168
- `))}function Ht(s){let e=n=>JSON.stringify(n,null,2);if(!s)throw new Error(`Chat request message item cannot be null or undefined, received: ${e(s)}`);let t=typeof s=="object"&&s!==null&&"role"in s&&typeof s.role=="string"?s.role:void 0;if(!t)throw new Error(`Chat request message must have a role, received: ${e(t)}`);switch(t){case"system":{let n=typeof s=="object"&&s!==null&&"content"in s&&typeof s.content=="string"?s.content:void 0;if(!n||n.trim()==="")throw new Error(`System message content cannot be empty or whitespace-only, received: ${e(n)}`);break}case"user":{let n=typeof s=="object"&&s!==null&&"content"in s?s.content:void 0;if(n===void 0)throw new Error(`User message content cannot be undefined, received: ${e(n)}`);if(typeof n=="string"){if(n.trim()==="")throw new Error(`User message content cannot be empty or whitespace-only, received: ${e(n)}`)}else if(Array.isArray(n)){if(n.length===0)throw new Error(`User message content array cannot be empty, received: ${e(n)}`);for(let r=0;r<n.length;r++){let o=n[r];if(!o||typeof o!="object")throw new Error(`User message content item at index ${r} must be an object, received: ${e(o)}`);let i=typeof o=="object"&&o!==null&&"type"in o&&typeof o.type=="string"?o.type:void 0;if(!i)throw new Error(`User message content item at index ${r} must have a type, received: ${e(i)}`);switch(i){case"text":{let a="text"in o&&typeof o.text=="string"?o.text:void 0;if(!a||a.trim()==="")throw new Error(`User message text content at index ${r} cannot be empty or whitespace-only, received: ${e(a)}`);break}case"image":{let a="image"in o&&typeof o.image=="string"?o.image:void 0,l="mimeType"in o&&typeof o.mimeType=="string"?o.mimeType:void 0;if(!a||a.trim()==="")throw new Error(`User message image content at index ${r} cannot be empty, received: ${e(a)}`);if(!l||l.trim()==="")throw new Error(`User message image content at index ${r} must have a mimeType, received: ${e(l)}`);break}case"audio":{let a="data"in o&&typeof o.data=="string"?o.data:void 0;if(!a||a.trim()==="")throw new Error(`User message audio content at index ${r} cannot be empty, received: ${e(a)}`);break}case"file":{let a="fileUri"in o&&typeof o.fileUri=="string",l="data"in o&&typeof o.data=="string";if(!a&&!l)throw new Error(`User message file content at index ${r} must have either 'data' or 'fileUri', received: ${e(o)}`);if(a&&l)throw new Error(`User message file content at index ${r} cannot have both 'data' and 'fileUri', received: ${e(o)}`);if(a){let c=o.fileUri;if(!c||c.trim()==="")throw new Error(`User message file content at index ${r} fileUri cannot be empty, received: ${e(c)}`)}if(l){let c=o.data;if(!c||c.trim()==="")throw new Error(`User message file content at index ${r} data cannot be empty, received: ${e(c)}`)}let u="mimeType"in o&&typeof o.mimeType=="string"?o.mimeType:null;if(!u||u.trim()==="")throw new Error(`User message file content at index ${r} must have a mimeType, received: ${e(u)}`);break}case"url":{let a="url"in o&&typeof o.url=="string"?o.url:void 0;if(!a||a.trim()==="")throw new Error(`User message url content at index ${r} cannot be empty, received: ${e(a)}`);break}default:throw new Error(`User message content item at index ${r} has unsupported type: ${e(i)}`)}}}else throw new Error(`User message content must be a string or array of content objects, received: ${e(n)}`);break}case"assistant":{let n=typeof s=="object"&&s!==null&&"content"in s?s.content:void 0,r=typeof s=="object"&&s!==null&&"functionCalls"in s?s.functionCalls:void 0,o=typeof s=="object"&&s!==null&&"thoughtBlocks"in s?s.thoughtBlocks:void 0,i=typeof n=="string"&&n.trim()!=="",a=Array.isArray(r)&&r.length>0,l=Array.isArray(o)&&o.length>0;if(!i&&!a&&!l&&at("Assistant message must include non-empty content, at least one function call, or thought blocks",{fieldPath:"content | functionCalls | thoughtBlocks",value:{content:n,functionCalls:r,thoughtBlocks:o},item:s}),n!==void 0&&typeof n!="string"&&at("Assistant message content must be a string",{fieldPath:"content",value:n,item:s}),r!==void 0&&!Array.isArray(r)&&at("Assistant message functionCalls must be an array when provided",{fieldPath:"functionCalls",value:r,item:s}),Array.isArray(r))for(let u=0;u<r.length;u++){let c=r[u];if((!c||typeof c!="object")&&at("functionCalls entry must be an object",{fieldPath:`functionCalls[${u}]`,value:c,item:s}),(!("id"in c)||typeof c.id!="string"||c.id.trim()==="")&&at("functionCalls entry must include a non-empty string id",{fieldPath:`functionCalls[${u}].id`,value:c.id,item:s}),(!("type"in c)||c.type!=="function")&&at("functionCalls entry must have type 'function'",{fieldPath:`functionCalls[${u}].type`,value:c.type,item:s}),!("function"in c)||!c.function)at("functionCalls entry must include a function object",{fieldPath:`functionCalls[${u}].function`,value:c.function,item:s});else{let p=c.function;(!("name"in p)||typeof p.name!="string"||p.name.trim()==="")&&at("functionCalls entry must include a non-empty function name",{fieldPath:`functionCalls[${u}].function.name`,value:p?.name,item:s}),p.params!==void 0&&typeof p.params!="string"&&typeof p.params!="object"&&at("functionCalls entry params must be a string or object when provided",{fieldPath:`functionCalls[${u}].function.params`,value:p.params,item:s})}}if(s.name!==void 0){let u=s.name;(typeof u!="string"||u.trim()==="")&&at("Assistant message name must be a non-empty string when provided",{fieldPath:"name",value:u,item:s})}break}case"function":{let n=typeof s=="object"&&s!==null&&"functionId"in s&&typeof s.functionId=="string"?s.functionId:void 0,r=typeof s=="object"&&s!==null&&"result"in s?s.result:void 0;if(!n||n.trim()==="")throw new Error(`Function message must have a non-empty functionId, received: ${e(n)}`);if(r==null)throw new Error(`Function message must have a result, received: ${e(r)}`);if(typeof r!="string")throw new Error(`Function message result must be a string, received: ${e(r)}`);s.isError!==void 0&&typeof s.isError!="boolean"&&at("Function message isError must be a boolean when provided",{fieldPath:"isError",value:s.isError,item:s});break}default:throw new Error(`Unsupported message role: ${e(t)}`)}}function Gr(s){let e=n=>JSON.stringify(n,null,2),t=Array.isArray(s)?s:[s];if(t.length===0)throw new Error(`Chat response results cannot be empty, received: ${e(t)}`);for(let n=0;n<t.length;n++){let r=t[n];if(!r)throw new Error(`Chat response result at index ${n} cannot be null or undefined, received: ${e(r)}`);if(typeof r.index!="number")throw new Error(`Chat response result at index ${n} must have a numeric index, received: ${e(r.index)}`);if(r.index<0)throw new Error(`Chat response result at index ${n} must have a non-negative index, received: ${e(r.index)}`);if(!r.content&&!r.thought&&(!r.thoughtBlocks||r.thoughtBlocks.length===0)&&!r.functionCalls&&!r.finishReason)throw new Error(`Chat response result at index ${n} must have at least one of: content, thought, thoughtBlocks, functionCalls, or finishReason, received: ${e({content:r.content,thought:r.thought,thoughtBlocks:r.thoughtBlocks,functionCalls:r.functionCalls,finishReason:r.finishReason})}`);if(r.content!==void 0&&typeof r.content!="string")throw new Error(`Chat response result content at index ${n} must be a string, received: ${e(r.content)}`);if(r.thought!==void 0&&typeof r.thought!="string")throw new Error(`Chat response result thought at index ${n} must be a string, received: ${e(r.thought)}`);if(r.thoughtBlocks!==void 0){if(!Array.isArray(r.thoughtBlocks))throw new Error(`Chat response result thoughtBlocks at index ${n} must be an array, received: ${e(r.thoughtBlocks)}`);for(let o=0;o<r.thoughtBlocks.length;o++){let i=r.thoughtBlocks[o];if(typeof i!="object"||i===null)throw new Error(`Chat response result thoughtBlocks[${o}] at index ${n} must be an object, received: ${e(i)}`);if(typeof i.data!="string")throw new Error(`Chat response result thoughtBlocks[${o}].data at index ${n} must be a string, received: ${e(i.data)}`);if(typeof i.encrypted!="boolean")throw new Error(`Chat response result thoughtBlocks[${o}].encrypted at index ${n} must be a boolean, received: ${e(i.encrypted)}`);if(i.signature!==void 0&&typeof i.signature!="string")throw new Error(`Chat response result thoughtBlocks[${o}].signature at index ${n} must be a string when provided, received: ${e(i.signature)}`)}}if(r.name!==void 0){if(typeof r.name!="string")throw new Error(`Chat response result name at index ${n} must be a string, received: ${e(r.name)}`);if(r.name.trim()==="")throw new Error(`Chat response result name at index ${n} cannot be empty or whitespace-only, received: ${e(r.name)}`)}if(r.annotations!==void 0){if(!Array.isArray(r.annotations))throw new Error(`Chat response result annotations at index ${n} must be an array, received: ${e(r.annotations)}`);for(let o=0;o<r.annotations.length;o++){let i=r.annotations[o];if(!i||typeof i!="object")throw new Error(`Chat response result annotation at index ${n}[${o}] must be an object, received: ${e(i)}`);if(i.type!=="url_citation")throw new Error(`Chat response result annotation at index ${n}[${o}] must have type 'url_citation', received: ${e(i.type)}`);if(!i.url_citation||typeof i.url_citation!="object")throw new Error(`Chat response result annotation at index ${n}[${o}] must have a valid url_citation object, received: ${e(i.url_citation)}`);if(typeof i.url_citation.url!="string")throw new Error(`Chat response result annotation at index ${n}[${o}] url_citation.url must be a string, received: ${e(i.url_citation.url)}`)}}if(r.id!==void 0){if(typeof r.id!="string")throw new Error(`Chat response result id at index ${n} must be a string, received: ${e(r.id)}`);if(r.id.trim()==="")throw new Error(`Chat response result id at index ${n} cannot be empty or whitespace-only, received: ${e(r.id)}`)}if(r.functionCalls!==void 0){if(!Array.isArray(r.functionCalls))throw new Error(`Chat response result functionCalls at index ${n} must be an array, received: ${e(r.functionCalls)}`);for(let o=0;o<r.functionCalls.length;o++){let i=r.functionCalls[o];if(!i)throw new Error(`Function call at index ${o} in result ${n} cannot be null or undefined, received: ${e(i)}`);if(!i.id||typeof i.id!="string"||i.id.trim()==="")throw new Error(`Function call at index ${o} in result ${n} must have a non-empty string id, received: ${e(i.id)}`);if(i.type!=="function")throw new Error(`Function call at index ${o} in result ${n} must have type 'function', received: ${e(i.type)}`);if(!i.function)throw new Error(`Function call at index ${o} in result ${n} must have a function object, received: ${e(i.function)}`);if(!i.function.name||typeof i.function.name!="string"||i.function.name.trim()==="")throw new Error(`Function call at index ${o} in result ${n} must have a non-empty function name, received: ${e(i.function.name)}`);if(i.function.params!==void 0&&typeof i.function.params!="string"&&typeof i.function.params!="object")throw new Error(`Function call params at index ${o} in result ${n} must be a string or object, received: ${e(i.function.params)}`)}}if(r.finishReason!==void 0){let o=["stop","length","function_call","content_filter","error"];if(!o.includes(r.finishReason))throw new Error(`Chat response result finishReason at index ${n} must be one of: ${o.join(", ")}, received: ${e(r.finishReason)}`)}}}var ie=()=>structuredClone({temperature:0}),Se=()=>structuredClone({temperature:.4,frequencyPenalty:.2}),we=class{constructor(e,{name:t,apiURL:n,headers:r,modelInfo:o,defaults:i,options:a={},supportFor:l,models:u}){this.aiImpl=e;this.name=t,this.apiURL=n||"",this.headers=r,this.supportFor=l,this.tracer=a.tracer??te.tracer,this.meter=a.meter??te.meter,this.modelInfo=o,this.models=u,this.id=Pe();let c=this.getModel(i.model)??i.model,p=this.getEmbedModel(i.embedModel)??i.embedModel;if(this.defaults={model:c,embedModel:p},!i.model||typeof i.model!="string"||i.model==="")throw new Error("No model defined");this.setOptions(a),u&&Cc(u)}#e=!1;#t=!1;rt;fetch;tracer;meter;timeout;excludeContentFromTrace;models;abortSignal;logger=te.logger??ia;corsProxy;retry;modelInfo;modelUsage;embedModelUsage;defaults;lastUsedModelConfig;lastUsedChatModel;lastUsedEmbedModel;apiURL;name;id;headers;supportFor;metrics={latency:{chat:{mean:0,p95:0,p99:0,samples:[]},embed:{mean:0,p95:0,p99:0,samples:[]}},errors:{chat:{count:0,rate:0,total:0},embed:{count:0,rate:0,total:0}}};getMetricsInstruments(){return Aa(this.meter)}setName(e){this.name=e}getId(){return this.id}setAPIURL(e){this.apiURL=e}setHeaders(e){this.headers=e}get debug(){return this.#e}setOptions(e){this.#e=e.debug??te.debug??!1,this.#t=e.verbose??!1,this.rt=e.rateLimiter,this.fetch=e.fetch,this.timeout=e.timeout,this.tracer=e.tracer??te.tracer,this.meter=e.meter??te.meter,this.excludeContentFromTrace=e.excludeContentFromTrace,this.abortSignal=e.abortSignal,this.logger=e.logger??te.logger??this.logger,this.corsProxy=e.corsProxy,this.retry=e.retry}getOptions(){return{debug:this.#e,verbose:this.#t,rateLimiter:this.rt,fetch:this.fetch,tracer:this.tracer,meter:this.meter,timeout:this.timeout,excludeContentFromTrace:this.excludeContentFromTrace,abortSignal:this.abortSignal,logger:this.logger,corsProxy:this.corsProxy,retry:this.retry}}getLogger(){return this.logger}getModelList(){let e=[];for(let t of this.models??[])t.isInternal||("model"in t&&t.model&&e.push({key:t.key,description:t.description,model:t.model}),"embedModel"in t&&t.embedModel&&e.push({key:t.key,description:t.description,embedModel:t.embedModel}));return e}getName(){return this.name}getFeatures(e){return typeof this.supportFor=="function"?this.supportFor(e??this.defaults.model):this.supportFor}getLastUsedChatModel(){return this.lastUsedChatModel}getLastUsedEmbedModel(){return this.lastUsedEmbedModel}getLastUsedModelConfig(){return this.lastUsedModelConfig}calculatePercentile(e,t){if(e.length===0)return 0;let n=[...e].sort((o,i)=>o-i),r=Math.ceil(t/100*n.length)-1;return n[r]??0}updateLatencyMetrics(e,t){let n=this.metrics.latency[e];n.samples.push(t),n.samples.length>1e3&&n.samples.shift(),n.mean=n.samples.reduce((o,i)=>o+i,0)/n.samples.length,n.p95=this.calculatePercentile(n.samples,95),n.p99=this.calculatePercentile(n.samples,99);let r=this.getMetricsInstruments();if(r){let o=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;ya(r,e,t,this.name,o),ba(r,e,n.mean,n.p95,n.p99,this.name,o)}}updateErrorMetrics(e,t){let n=this.metrics.errors[e];n.total++,t&&n.count++,n.rate=n.count/n.total;let r=this.getMetricsInstruments();if(r){let o=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;Ca(r,e,this.name,o),t&&Ia(r,e,this.name,o),Ta(r,e,n.rate,this.name,o)}}recordTokenUsage(e){let t=this.getMetricsInstruments();if(t&&e?.tokens){let{promptTokens:n,completionTokens:r,totalTokens:o,thoughtsTokens:i}=e.tokens;n&&jn(t,"input",n,this.name,e.model),r&&jn(t,"output",r,this.name,e.model),o&&jn(t,"total",o,this.name,e.model),i&&jn(t,"thoughts",i,this.name,e.model)}}calculateRequestSize(e){try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return 0}}calculateResponseSize(e){try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return 0}}detectMultimodalContent(e){let t=!1,n=!1;if(e.chatPrompt&&Array.isArray(e.chatPrompt)){for(let r of e.chatPrompt)if(r.role==="user"&&Array.isArray(r.content))for(let o of r.content)o.type==="image"?t=!0:o.type==="audio"&&(n=!0)}return{hasImages:t,hasAudio:n}}calculatePromptLength(e){let t=0;if(e.chatPrompt&&Array.isArray(e.chatPrompt))for(let n of e.chatPrompt)if(n.role==="system"||n.role==="assistant")n.content&&(t+=n.content.length);else if(n.role==="user"){if(typeof n.content=="string")t+=n.content.length;else if(Array.isArray(n.content))for(let r of n.content)r.type==="text"&&(t+=r.text.length)}else n.role==="function"&&n.result&&(t+=n.result.length);return t}calculateContextWindowUsage(e,t){if(!t?.tokens?.promptTokens)return 0;let n=this.modelInfo.find(r=>r.name===e);return n?.contextWindow?t.tokens.promptTokens/n.contextWindow:0}estimateCost(e,t){if(!t?.tokens)return 0;let n=this.modelInfo.find(l=>l.name===e);if(!n||!n.promptTokenCostPer1M&&!n.completionTokenCostPer1M)return 0;let{promptTokens:r=0,completionTokens:o=0}=t.tokens,i=n.promptTokenCostPer1M||0,a=n.completionTokenCostPer1M||0;return r*i/1e6+o*a/1e6}estimateCostByName(e,t){if(!t?.tokens)return 0;let n=this.modelInfo.find(l=>l.name===e);if(!n||!n.promptTokenCostPer1M&&!n.completionTokenCostPer1M)return 0;let{promptTokens:r=0,completionTokens:o=0}=t.tokens,i=n.promptTokenCostPer1M||0,a=n.completionTokenCostPer1M||0;return r*i/1e6+o*a/1e6}recordFunctionCallMetrics(e,t){let n=this.getMetricsInstruments();if(!(!n||!e))for(let r of e)r&&typeof r=="object"&&"function"in r&&r.function&&typeof r.function=="object"&&"name"in r.function&&Ra(n,r.function.name,void 0,this.name,t)}recordTimeoutMetric(e){let t=this.getMetricsInstruments();if(t){let n=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;ka(t,e,this.name,n)}}recordAbortMetric(e){let t=this.getMetricsInstruments();if(t){let n=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;Ma(t,e,this.name,n)}}recordChatMetrics(e,t,n){let r=this.getMetricsInstruments();if(!r)return;let o=this.lastUsedChatModel,i=this.lastUsedModelConfig,a=i?.stream??!1;wa(r,"chat",a,this.name,o);let{hasImages:l,hasAudio:u}=this.detectMultimodalContent(e);Pa(r,l,u,this.name,o);let c=this.calculatePromptLength(e);Sa(r,c,this.name,o),va(r,i?.temperature,i?.maxTokens,this.name,o),t?.thinkingTokenBudget&&this.modelUsage?.tokens?.thoughtsTokens&&Ea(r,this.modelUsage.tokens.thoughtsTokens,this.name,o);let p=this.calculateRequestSize(e);if(vs(r,"chat",p,this.name,o),n&&!a){let d=n,m=this.calculateResponseSize(d);if(Ss(r,"chat",m,this.name,o),d.results)for(let h of d.results)h.functionCalls&&this.recordFunctionCallMetrics(h.functionCalls,this.lastUsedChatModel);let g=this.calculateContextWindowUsage(this.lastUsedChatModel,d.modelUsage);g>0&&Oa(r,g,this.name,o);let f=this.estimateCost(this.lastUsedChatModel,d.modelUsage);f>0&&Os(r,"chat",f,this.name,o)}}recordEmbedMetrics(e,t){let n=this.getMetricsInstruments();if(!n)return;let r=this.lastUsedEmbedModel,o=this.calculateRequestSize(e);vs(n,"embed",o,this.name,r);let i=this.calculateResponseSize(t);Ss(n,"embed",i,this.name,r);let a=this.estimateCostByName(r,t.modelUsage);a>0&&Os(n,"embed",a,this.name,r)}getMetrics(){return structuredClone(this.metrics)}async chat(e,t){let n=performance.now(),r=!1,o,i=this.getModelByKey(e.model),a=i?i.thinkingTokenBudget:void 0,l={...i?{thinkingTokenBudget:a,showThoughts:i.showThoughts,stream:i.stream,debug:i.debug,useExpensiveModel:i.useExpensiveModel}:void 0,...Object.fromEntries(Object.entries(t??{}).filter(([,u])=>u!==void 0))};try{return o=await this._chat1(e,l),o}catch(u){throw r=!0,u instanceof Error&&(u.message.includes("timeout")||u.name==="TimeoutError"?this.recordTimeoutMetric("chat"):(u.message.includes("abort")||u.name==="AbortError")&&this.recordAbortMetric("chat")),u}finally{let u=performance.now()-n;this.updateLatencyMetrics("chat",u),this.updateErrorMetrics("chat",r),r||this.recordChatMetrics(e,l,o)}}async _chat1(e,t){let n=this.getModel(e.model)??e.model??this.defaults.model;if(Array.isArray(e.chatPrompt))for(let u of e.chatPrompt)Ht(u);let r=this.getModelByKey(e.model),o={...this.aiImpl.getModelConfig(),...r?r.modelConfig:void 0,...e.modelConfig},i=this.modelInfo.find(u=>u.name===n);if(i?.notSupported?.temperature&&"temperature"in o&&delete o.temperature,i?.notSupported?.topP&&"topP"in o&&delete o.topP,t?.thinkingTokenBudget&&!this.getFeatures(n).hasThinkingBudget)throw new Error(`Model ${n} does not support thinkingTokenBudget.`);if(t?.showThoughts&&!this.getFeatures(n).hasShowThoughts)throw new Error(`Model ${n} does not support showThoughts.`);if(this.modelInfo.find(u=>u.name===n)?.isExpensive&&t?.useExpensiveModel!=="yes")throw new Error(`Model ${n} is marked as expensive and requires explicit confirmation. Set useExpensiveModel: "yes" to proceed.`);return o.stream=(t?.stream!==void 0?t.stream:o.stream)??!0,this.getFeatures(n).streaming||(o.stream=!1),this.tracer?await this.tracer.startActiveSpan("AI Chat Request",{kind:Be.SERVER,attributes:{[Y.LLM_SYSTEM]:this.name,[Y.LLM_OPERATION_NAME]:"chat",[Y.LLM_REQUEST_MODEL]:n,[Y.LLM_REQUEST_MAX_TOKENS]:o.maxTokens??"Not set",[Y.LLM_REQUEST_TEMPERATURE]:o.temperature,[Y.LLM_REQUEST_TOP_P]:o.topP??"Not set",[Y.LLM_REQUEST_TOP_K]:o.topK??"Not set",[Y.LLM_REQUEST_FREQUENCY_PENALTY]:o.frequencyPenalty??"Not set",[Y.LLM_REQUEST_PRESENCE_PENALTY]:o.presencePenalty??"Not set",[Y.LLM_REQUEST_STOP_SEQUENCES]:o.stopSequences?.join(", ")??"Not set",[Y.LLM_REQUEST_LLM_IS_STREAMING]:o.stream??"Not set"}},t?.traceContext??vt.active(),async u=>await this._chat2(n,o,e,t,u)):await this._chat2(n,o,e,t)}cleanupFunctionSchema(e){let t={...e};if(t.parameters){let n={...t.parameters};Array.isArray(n.required)&&n.required.length===0&&delete n.required,n.properties&&Object.keys(n.properties).length===0&&delete n.properties,Object.keys(n).length===0||Object.keys(n).length===1&&n.type==="object"?delete t.parameters:t.parameters=n}return t}async _chat2(e,t,n,r,o){if(!this.aiImpl.createChatReq)throw new Error("createChatReq not implemented");let i=r?.debug??this.#e,a=r?.verbose??this.#t,l;n.functions&&n.functions.length>0&&(l=n.functions.map(A=>this.cleanupFunctionSchema(A)));let u={...n,model:e,functions:l,modelConfig:t};this.lastUsedChatModel=e,this.lastUsedModelConfig=t,i&&la(u.chatPrompt,r?.stepIndex??0,r?.logger??this.logger,r?.debugHideSystemPrompt);let c=this.getFeatures(e).functions,p=r?.functionCallMode??"auto",m=p==="prompt"||p==="auto"&&!c?{...u,chatPrompt:u.chatPrompt.map(A=>{if(A.role==="assistant"){let{content:y,name:b,cache:k}=A;return{role:"assistant",content:y,name:b,cache:k}}return A.role==="function"?{role:"user",content:A.result}:A}),functions:[]}:u,g=async()=>{let[A,y]=await this.aiImpl.createChatReq(m,r);return o?.isRecording()&&Tc(n,o,this.excludeContentFromTrace),await Ue({name:A.name,url:this.apiURL,localCall:A.localCall,headers:await this.buildHeaders(A.headers),stream:t.stream,timeout:this.timeout,verbose:a,fetch:this.fetch,span:o,abortSignal:r?.abortSignal??this.abortSignal,corsProxy:this.corsProxy,retry:r?.retry??this.retry},y)},f=r?.rateLimiter??this.rt,h=f?await f(g,{modelUsage:this.modelUsage}):await g();if(t.stream){if(!this.aiImpl.createChatStreamResp)throw new Error("createChatStreamResp not implemented");let A=this.aiImpl.createChatStreamResp.bind(this),y=M=>R=>{let O=A(R,M);if(O.sessionId=r?.sessionId,!O.modelUsage){let F=this.aiImpl.getTokenUsage();F&&(O.modelUsage={ai:this.name,model:e,tokens:F})}return this.modelUsage=O.modelUsage,this.recordTokenUsage(O.modelUsage),o?.isRecording()&&_a(O,o,this.excludeContentFromTrace),O},b=async M=>{o?.isRecording()&&o.end(),i&&ca(M,r?.logger??this.logger)};if(typeof window<"u"){let M=h,R={},O=[],F=r?.abortSignal??this.abortSignal;return new ReadableStream({start:P=>{let I=M.getReader(),v=()=>{try{I.cancel().catch(()=>{})}catch{}try{this.recordAbortMetric("chat")}catch{}try{o?.isRecording()&&o.end()}catch{}try{P.error(new DOMException("Aborted","AbortError"))}catch{P.error(new Error("Aborted"))}};if(F){if(F.aborted){v();return}F.addEventListener("abort",v,{once:!0})}async function T(){try{for(;;){let{done:w,value:C}=await I.read();if(w){b&&await b(O),P.close();break}let E=y(R)(C);E&&(O.push(E),P.enqueue(E))}}catch(w){if(P.error(w),o?.isRecording())try{o.end()}catch{}}finally{if(I.releaseLock(),F)try{F.removeEventListener("abort",v)}catch{}}}T()}})}return h.pipeThrough(new Nr(y({}),b))}if(!this.aiImpl.createChatResp)throw new Error("createChatResp not implemented");let x=this.aiImpl.createChatResp(h);if(x.sessionId=r?.sessionId,!x.modelUsage){let A=this.aiImpl.getTokenUsage();A&&(x.modelUsage={ai:this.name,model:e,tokens:A})}return x.modelUsage&&(this.modelUsage=x.modelUsage,this.recordTokenUsage(x.modelUsage)),o?.isRecording()&&(_a(x,o,this.excludeContentFromTrace),o.end()),i&&ua(x,r?.logger??this.logger),x}async embed(e,t){let n=performance.now(),r=!1,o,i=this.getModelByKey(e.embedModel),a={...i?{thinkingTokenBudget:i.thinkingTokenBudget,showThoughts:i.showThoughts,stream:i.stream,debug:i.debug,useExpensiveModel:i.useExpensiveModel}:void 0,...t};try{return o=await this._embed1(e,a),o}catch(l){throw r=!0,l instanceof Error&&(l.message.includes("timeout")||l.name==="TimeoutError"?this.recordTimeoutMetric("embed"):(l.message.includes("abort")||l.name==="AbortError")&&this.recordAbortMetric("embed")),l}finally{let l=performance.now()-n;this.updateLatencyMetrics("embed",l),this.updateErrorMetrics("embed",r),!r&&o&&this.recordEmbedMetrics(e,o)}}async _embed1(e,t){let n=this.getEmbedModel(e.embedModel)??e.embedModel??this.defaults.embedModel;if(!n)throw new Error("No embed model defined");return this.tracer?await this.tracer.startActiveSpan("AI Embed Request",{kind:Be.SERVER,attributes:{[Y.LLM_SYSTEM]:this.name,[Y.LLM_OPERATION_NAME]:"embeddings",[Y.LLM_REQUEST_MODEL]:n}},t?.traceContext??vt.active(),async r=>await this._embed2(n,e,t,r)):await this._embed2(n,e,t)}async _embed2(e,t,n,r){if(!this.aiImpl.createEmbedReq)throw new Error("createEmbedReq not implemented");if(!this.aiImpl.createEmbedResp)throw new Error("createEmbedResp not implemented");let o=this.aiImpl.createEmbedReq.bind(this.aiImpl),i=n?.debug??this.#e,a=n?.verbose??this.#t,l={...t,embedModel:e};this.lastUsedEmbedModel=e,i&&ha(l.texts??[],e,n?.logger??this.logger);let u=async()=>{let[m,g]=await o(l);return await Ue({name:m.name,url:this.apiURL,localCall:m.localCall,headers:await this.buildHeaders(m.headers),verbose:a,fetch:this.fetch,timeout:this.timeout,span:r,abortSignal:n?.abortSignal??this.abortSignal,corsProxy:this.corsProxy,retry:n?.retry??this.retry},g)},c=n?.rateLimiter??this.rt,p=c?await c(u,{modelUsage:this.embedModelUsage}):await u(),d=this.aiImpl.createEmbedResp?.(p);if(d.sessionId=n?.sessionId,!d.modelUsage){let m=this.aiImpl.getTokenUsage();m&&(d.modelUsage={ai:this.name,model:e,tokens:m})}return this.embedModelUsage=d.modelUsage,this.recordTokenUsage(d.modelUsage),r?.isRecording()&&d.modelUsage?.tokens&&r.addEvent(it.GEN_AI_USAGE,{[Y.LLM_USAGE_INPUT_TOKENS]:d.modelUsage.tokens.promptTokens,[Y.LLM_USAGE_OUTPUT_TOKENS]:d.modelUsage.tokens.completionTokens??0,[Y.LLM_USAGE_TOTAL_TOKENS]:d.modelUsage.tokens.totalTokens}),i&&fa(d.embeddings,n?.logger??this.logger),r?.end(),d}async buildHeaders(e={}){return{...e,...await this.headers()}}getModelByKey(e){return e?this.models?.find(n=>n.key===e):void 0}getModel(e){let t=this.getModelByKey(e);return t&&"model"in t?t.model:void 0}getEmbedModel(e){let t=this.getModelByKey(e);return t&&"embedModel"in t?t.embedModel:void 0}};function Tc(s,e,t){let n=[];if(s.chatPrompt&&Array.isArray(s.chatPrompt)&&s.chatPrompt.length>0)for(let o of s.chatPrompt)switch(o.role){case"system":if(o.content){let i={};t||(i.content=o.content),e.addEvent(it.GEN_AI_SYSTEM_MESSAGE,i)}break;case"user":if(typeof o.content=="string")n.push(o.content);else if(Array.isArray(o.content))for(let i of o.content)i.type==="text"&&n.push(i.text);break;case"assistant":{let i=o.functionCalls?.map(a=>({id:a.id,type:a.type,function:a.function.name,arguments:a.function.params}));if(i&&i.length>0){let a={function_calls:JSON.stringify(i,null,2)};!t&&o.content&&(a.content=o.content),e.addEvent(it.GEN_AI_ASSISTANT_MESSAGE,a)}else if(o.content){let a={};t||(a.content=o.content),e.addEvent(it.GEN_AI_ASSISTANT_MESSAGE,a)}break}case"function":{let i={id:o.functionId};t||(i.content=o.result),e.addEvent(it.GEN_AI_TOOL_MESSAGE,i);break}}let r={};t||(r.content=n.join(`
169
- `)),e.addEvent(it.GEN_AI_USER_MESSAGE,r)}function _a(s,e,t){if(s.modelUsage?.tokens){let n=s.modelUsage.tokens.thoughtsTokens?{[Y.LLM_USAGE_THOUGHTS_TOKENS]:s.modelUsage.tokens.thoughtsTokens}:{};e.addEvent(it.GEN_AI_USAGE,{[Y.LLM_USAGE_INPUT_TOKENS]:s.modelUsage.tokens.promptTokens,[Y.LLM_USAGE_OUTPUT_TOKENS]:s.modelUsage.tokens.completionTokens??0,[Y.LLM_USAGE_TOTAL_TOKENS]:s.modelUsage.tokens.totalTokens,...n})}if(s.results)for(let n=0;n<s.results.length;n++){let r=s.results[n];if(!r||!r.content&&!r.thought&&!r.functionCalls?.length&&!r.finishReason)continue;let o=r.functionCalls?.map(a=>({id:a.id,type:a.type,function:a.function.name,arguments:a.function.params})),i={};o&&o.length>0?(t||(i.content=r.content),i.tool_calls=o):t||(i.content=r.content??""),e.addEvent(it.GEN_AI_CHOICE,{finish_reason:r.finishReason,index:n,message:JSON.stringify(i,null,2)})}}function $a(s){let e=0;for(let t of s){if(!t||typeof t!="object")throw new Error(`AxMessage array validation failed: Item at index ${e} is not a valid message object`);if(t.role!=="user"&&t.role!=="assistant")throw new Error(`AxMessage array validation failed: Item at index ${e} has invalid role: ${t.role}`);e++}}function Cc(s){let e=new Set;for(let t of s){if(e.has(t.key))throw new Error(`Duplicate model key detected: "${t.key}". Each model key must be unique.`);e.add(t.key)}}var zn=(g=>(g.Claude45Opus="claude-opus-4-5-20251101",g.Claude41Opus="claude-opus-4-1-20250805",g.Claude4Opus="claude-opus-4-20250514",g.Claude4Sonnet="claude-sonnet-4-20250514",g.Claude45Sonnet="claude-sonnet-4-5-20250929",g.Claude45Haiku="claude-haiku-4-5",g.Claude37Sonnet="claude-3-7-sonnet-latest",g.Claude35Sonnet="claude-3-5-sonnet-latest",g.Claude35Haiku="claude-3-5-haiku-latest",g.Claude3Opus="claude-3-opus-latest",g.Claude3Sonnet="claude-3-sonnet-20240229",g.Claude3Haiku="claude-3-haiku-20240307",g.Claude21="claude-2.1",g.ClaudeInstant12="claude-instant-1.2",g))(zn||{}),qn=(d=>(d.Claude45Opus="claude-opus-4-5@20251101",d.Claude41Opus="claude-opus-4-1@20250805",d.Claude4Opus="claude-opus-4@20250514",d.Claude45Sonnet="claude-sonnet-4-5@20250929",d.Claude4Sonnet="claude-sonnet-4@20250514",d.Claude37Sonnet="claude-3-7-sonnet@20250219",d.Claude35SonnetV2="claude-3-5-sonnet-v2@20241022",d.Claude45Haiku="claude-haiku-4-5@20251001",d.Claude35Haiku="claude-3-5-haiku@20241022",d.Claude35Sonnet="claude-3-5-sonnet@20240620",d.Claude3Opus="claude-3-opus@20240229",d.Claude3Haiku="claude-3-haiku@20240307",d))(qn||{});var Hn=[{name:"claude-opus-4-5-20251101",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:25,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-5@20251101",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:25,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4-5-20250929",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:2e5,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4-5@20250929",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:2e5,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-haiku-4-5",currency:"usd",promptTokenCostPer1M:1,completionTokenCostPer1M:5,maxTokens:2e5,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-haiku-4-5@20251001",currency:"usd",promptTokenCostPer1M:1,completionTokenCostPer1M:5,maxTokens:2e5,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-opus-4-1-20250805",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-1@20250805",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-20250514",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4@20250514",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4-20250514",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4@20250514",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-3-7-sonnet-latest",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-3-7-sonnet@20250219",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-3-5-sonnet-latest",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:8192,supported:{structuredOutputs:!0}},{name:"claude-3-5-sonnet@20240620",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:8192,supported:{structuredOutputs:!0}},{name:"claude-3-5-sonnet-v2@20241022",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:8192,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-3-5-haiku-latest",currency:"usd",promptTokenCostPer1M:.8,completionTokenCostPer1M:4,maxTokens:8192},{name:"claude-3-5-haiku@20241022",currency:"usd",promptTokenCostPer1M:1,completionTokenCostPer1M:5,maxTokens:8192},{name:"claude-3-opus-latest",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:4096,supported:{structuredOutputs:!0}},{name:"claude-3-opus@20240229",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:4096,supported:{structuredOutputs:!0}},{name:"claude-3-sonnet-20240229",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:4096,supported:{structuredOutputs:!0}},{name:"claude-3-haiku-20240307",currency:"usd",promptTokenCostPer1M:.25,completionTokenCostPer1M:1.25,maxTokens:4096},{name:"claude-3-haiku@20240307",currency:"usd",promptTokenCostPer1M:.25,completionTokenCostPer1M:1.25,maxTokens:4096},{name:"claude-2.1",currency:"usd",promptTokenCostPer1M:8,completionTokenCostPer1M:25,maxTokens:4096},{name:"claude-instant-1.2",currency:"usd",promptTokenCostPer1M:.8,completionTokenCostPer1M:2.24,maxTokens:4096}];var St=s=>{if(!s||typeof s!="object")return s;let e={...s};if(e.type==="object"||Array.isArray(e.type)&&e.type.includes("object")){if(!e.properties||Object.keys(e.properties).length===0)throw new Error("Anthropic models do not support arbitrary JSON objects (e.g. f.json() or f.object() with no properties) in structured outputs. Please use f.string() and instruct the model to return a JSON string, or define the expected structure with f.object({ ... })");e.additionalProperties===void 0&&(e.additionalProperties=!1)}return delete e.optional,e.properties&&typeof e.properties=="object"&&(e.properties=Object.fromEntries(Object.entries(e.properties).map(([n,r])=>[n,St(r)]))),e.items&&(e.items=St(e.items)),Array.isArray(e.anyOf)&&(e.anyOf=e.anyOf.map(n=>St(n))),Array.isArray(e.allOf)&&(e.allOf=e.allOf.map(n=>St(n))),Array.isArray(e.oneOf)&&(e.oneOf=e.oneOf.map(n=>St(n))),e},Ms=()=>structuredClone({model:"claude-3-7-sonnet-latest",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},...ie()}),Da=()=>structuredClone({model:"claude-3-7-sonnet@20250219",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},...ie()}),ks=class{constructor(e,t){this.config=e;this.isVertex=t}tokensUsed;currentPromptConfig;usedStructuredOutput=!1;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens??4096,temperature:e.temperature,topP:e.topP,topK:e.topK,stream:e.stream,stopSequences:e.stopSequences,endSequences:e.endSequences,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,n:e.n}}createChatReq=async(e,t)=>{this.currentPromptConfig=t;let n=e.model,r=e.modelConfig?.stream??this.config.stream,o;this.isVertex?o={name:r?`/models/${n}:streamRawPredict?alt=sse`:`/models/${n}:rawPredict`}:o={name:"/messages"};let i;if(e.functionCall&&e.functions&&e.functions.length>0)if(typeof e.functionCall=="string")switch(e.functionCall){case"auto":i={tool_choice:{type:"auto"}};break;case"required":i={tool_choice:{type:"any"}};break;case"none":throw new Error("functionCall none not supported")}else if("function"in e.functionCall)i={tool_choice:{type:"tool",name:e.functionCall.function.name}};else throw new Error("Invalid function call type, must be string or object");let a=e.chatPrompt.filter(R=>R.role==="system").map(R=>({type:"text",text:R.content,...R.cache?{cache_control:{type:"ephemeral"}}:{}})),l=e.chatPrompt.filter(R=>R.role!=="system"),u=e.functions?.map(R=>{let O={type:"object",properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]},F=R.parameters?St(R.parameters):void 0;return F===void 0||F&&typeof F=="object"&&Object.keys(F).length===0?F={...O}:F&&typeof F=="object"&&F.type==="object"&&(!("properties"in F)||!F.properties||Object.keys(F.properties).length===0)&&(F={...F,properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]}),{name:R.name,description:R.description,input_schema:F}}),p=(this.config.tools??[]).map(R=>R&&typeof R=="object"&&"type"in R?R:{name:R.name,description:R.description,input_schema:R.input_schema?St(R.input_schema):void 0,...R.cache_control?{cache_control:R.cache_control}:{}}),d=[...u??[],...p];d.length===0&&(d=void 0);let m=e.modelConfig?.maxTokens??this.config.maxTokens,g=e.modelConfig?.stopSequences??this.config.stopSequences,f=e.modelConfig?.temperature,h=e.modelConfig?.topP,x=e.modelConfig?.topK??this.config.topK,A=e.modelConfig?.n??this.config.n;if(A&&A>1)throw new Error("Anthropic does not support sampling (n > 1)");let y;if(this.config.thinking?.budget_tokens&&(y=this.config.thinking),t?.thinkingTokenBudget){let R=this.config.thinkingTokenBudgetLevels;switch(t.thinkingTokenBudget){case"none":y=void 0;break;case"minimal":y={type:"enabled",budget_tokens:R?.minimal??1024};break;case"low":y={type:"enabled",budget_tokens:R?.low??5e3};break;case"medium":y={type:"enabled",budget_tokens:R?.medium??1e4};break;case"high":y={type:"enabled",budget_tokens:R?.high??2e4};break;case"highest":y={type:"enabled",budget_tokens:R?.highest??32e3};break}}if(!y&&t?.thinkingTokenBudget===void 0){let R=this.config.thinkingTokenBudgetLevels}let b=wc(l,!!y);b.some(R=>R.role==="assistant"&&Array.isArray(R.content)&&R.content.length>0&&R.content[0]?.type==="tool_use")&&(y=void 0);let S;if(this.usedStructuredOutput=!1,e.responseFormat&&e.responseFormat.type==="json_schema"&&e.responseFormat.schema){let R=e.responseFormat.schema.schema||e.responseFormat.schema;S={type:"json_schema",schema:St(R)},this.usedStructuredOutput=!0}let M={...this.isVertex?{anthropic_version:"vertex-2023-10-16"}:{model:n},...m?{max_tokens:m}:{},...g&&g.length>0?{stop_sequences:g}:{},...f!==void 0&&!y?{temperature:f}:{},...h!==void 0&&(!y||h>=.95)?{top_p:h}:{},...x&&!y?{top_k:x}:{},...i,...d?{tools:d}:{},...r?{stream:!0}:{},...a?{system:a}:{},...y?{thinking:y}:{},...S?{output_format:S}:{},messages:b};return[o,M]};createChatResp=e=>{if(e.type==="error")throw new fe(e.error.message,void 0,void 0);let t=Na(e.stop_reason),n=this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1,r="",o=[],i=[],a=[];for(let c of e.content)switch(c.type){case"text":if(r+=c.text??"",Array.isArray(c.citations))for(let p of c.citations)p?.url&&a.push({url:String(p.url),title:typeof p.title=="string"?p.title:void 0,snippet:typeof p.cited_text=="string"?p.cited_text:void 0});break;case"thinking":if(n){let p=c.thinking??"",d=c.signature;i.push({data:p,encrypted:!1,...typeof d=="string"?{signature:d}:{}})}break;case"redacted_thinking":if(n){let p=c.data??"",d=c.signature;i.push({data:p,encrypted:!0,...typeof d=="string"?{signature:d}:{}})}break;case"tool_use":o.push({id:c.id,type:"function",function:{name:c.name,params:c.input}});break}let l={index:0,id:e.id,finishReason:t};r&&(l.content=r),i.length>0&&(l.thoughtBlocks=i,l.thought=i.map(c=>c.data).join("")),o.length>0&&(l.functionCalls=o),a.length>0&&(l.citations=a);let u=[l];return this.tokensUsed={promptTokens:e.usage.input_tokens,completionTokens:e.usage.output_tokens,totalTokens:e.usage.input_tokens+e.usage.output_tokens+(e.usage.cache_creation_input_tokens||0)+(e.usage.cache_read_input_tokens||0),cacheCreationTokens:e.usage.cache_creation_input_tokens,cacheReadTokens:e.usage.cache_read_input_tokens},{results:u,remoteId:e.id}};createChatStreamResp=(e,t)=>{if(!("type"in e))throw new Error("Invalid Anthropic streaming event");let n=t;if(n.indexIdMap||(n.indexIdMap={}),e.type==="error"){let{error:o}=e;throw new fe(o.message,void 0,void 0)}let r=0;if(e.type==="message_start"){let{message:o}=e,i=[{index:r,content:"",id:o.id}];return this.tokensUsed={promptTokens:o.usage?.input_tokens??0,completionTokens:o.usage?.output_tokens??0,totalTokens:(o.usage?.input_tokens??0)+(o.usage?.output_tokens??0)+(o.usage?.cache_creation_input_tokens??0)+(o.usage?.cache_read_input_tokens??0),cacheCreationTokens:o.usage?.cache_creation_input_tokens,cacheReadTokens:o.usage?.cache_read_input_tokens},{results:i}}if(e.type==="content_block_start"){let{content_block:o}=e;if(o.type==="text"){let i=[];if(Array.isArray(o.citations))for(let a of o.citations)a?.url&&i.push({url:String(a.url),title:typeof a.title=="string"?a.title:void 0,snippet:typeof a.cited_text=="string"?a.cited_text:void 0});return{results:[{index:r,content:o.text,...i.length?{citations:i}:{}}]}}if(o.type==="thinking")return this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1?{results:[{index:r,thought:o.thinking,thoughtBlocks:[{data:o.thinking,encrypted:!1}]}]}:{results:[{index:r,content:""}]};if(o.type==="tool_use"&&typeof o.id=="string"&&typeof e.index=="number"&&!n.indexIdMap[e.index]){n.indexIdMap[e.index]=o.id;let i=[{id:o.id,type:"function",function:{name:o.name,params:""}}];return{results:[{index:r,functionCalls:i}]}}if(o.type==="web_search_tool_result"||o.type==="server_tool_use")return{results:[{index:r,content:""}]}}if(e.type==="content_block_delta"){let{delta:o}=e;if(o.type==="citations_delta"){let i=o.citation;if(i&&typeof i.url=="string"&&i.url.length>0){let a=[{url:String(i.url),title:typeof i.title=="string"?i.title:void 0,snippet:typeof i.cited_text=="string"?i.cited_text:void 0}];return{results:[{index:r,content:"",citations:a}]}}return{results:[{index:r,content:""}]}}if(o.type==="text_delta"){let i=[];if(Array.isArray(o.citations))for(let a of o.citations)a?.url&&i.push({url:String(a.url),title:typeof a.title=="string"?a.title:void 0,snippet:typeof a.cited_text=="string"?a.cited_text:void 0});return{results:[{index:r,content:o.text,...i.length?{citations:i}:{}}]}}if(o.type==="thinking_delta")return this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1?{results:[{index:r,thought:o.thinking,thoughtBlocks:[{data:o.thinking,encrypted:!1}]}]}:{results:[{index:r,content:""}]};if(o.type==="signature_delta")return{results:[{index:r,thoughtBlocks:[{data:"",encrypted:!1,signature:o.signature}]}]};if(o.type==="input_json_delta"){let i=n.indexIdMap[e.index];if(!i)return{results:[{index:r,content:""}]};let a=[{id:i,type:"function",function:{name:"",params:o.partial_json}}];return{results:[{index:r,functionCalls:a}]}}}if(e.type==="message_delta"){let{delta:o,usage:i}=e;return this.tokensUsed={promptTokens:this.tokensUsed?.promptTokens??0,completionTokens:i.output_tokens,totalTokens:(this.tokensUsed?.promptTokens??0)+i.output_tokens+(this.tokensUsed?.cacheCreationTokens??0)+(this.tokensUsed?.cacheReadTokens??0),cacheCreationTokens:this.tokensUsed?.cacheCreationTokens,cacheReadTokens:this.tokensUsed?.cacheReadTokens},{results:[{index:r,content:"",finishReason:Na(o.stop_reason)}]}}return{results:[{index:r,content:""}]}}},Kt=class s extends we{static create(e){return new s(e)}constructor({apiKey:e,projectId:t,region:n,config:r,options:o,models:i}){let a=t!==void 0&&n!==void 0,l,u;if(a){if(!e)throw new Error("Anthropic Vertex API key not set");if(typeof e!="function")throw new Error("Anthropic Vertex API key must be a function for token-based authentication");l=`https://${n==="global"?"aiplatform":`${n}-aiplatform`}.googleapis.com/v1/projects/${t}/locations/${n}/publishers/anthropic/`,u=async()=>({Authorization:`Bearer ${await e()}`,"anthropic-beta":"web-search-2025-03-05"})}else{if(!e)throw new Error("Anthropic API key not set");l="https://api.anthropic.com/v1",u=async()=>({"anthropic-version":"2023-06-01","anthropic-beta":"structured-outputs-2025-11-13, web-search-2025-03-05","x-api-key":typeof e=="function"?await e():e})}let c={...Ms(),...r},p=new ks(c,a),d=g=>{let f=We({model:g,modelInfo:Hn,models:i});return{functions:!0,streaming:!0,hasThinkingBudget:f?.supported?.thinkingBudget??!1,hasShowThoughts:f?.supported?.showThoughts??!1,structuredOutputs:f?.supported?.structuredOutputs??!1,functionCot:!0,media:{images:{supported:!0,formats:["image/jpeg","image/png","image/gif","image/webp"],maxSize:5*1024*1024,detailLevels:["high","low","auto"]},audio:{supported:!1,formats:[],maxDuration:0},files:{supported:!1,formats:[],maxSize:0,uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!0,types:["ephemeral"]},thinking:f?.supported?.thinkingBudget??!1,multiTurn:!0}},m=i?.map(g=>{let f=g,h=f?.config;if(!h)return g;let x={};h.maxTokens!==void 0&&(x.maxTokens=h.maxTokens),h.temperature!==void 0&&(x.temperature=h.temperature),h.topP!==void 0&&(x.topP=h.topP),h.topK!==void 0&&(x.topK=h.topK),h.presencePenalty!==void 0&&(x.presencePenalty=h.presencePenalty),h.frequencyPenalty!==void 0&&(x.frequencyPenalty=h.frequencyPenalty),h.stopSequences!==void 0&&(x.stopSequences=h.stopSequences),h.endSequences!==void 0&&(x.endSequences=h.endSequences),h.stream!==void 0&&(x.stream=h.stream),h.n!==void 0&&(x.n=h.n);let A={...f};Object.keys(x).length>0&&(A.modelConfig={...f.modelConfig??{},...x});let y=h.thinking?.thinkingTokenBudget;if(typeof y=="number"){let b=c.thinkingTokenBudgetLevels,k=[["minimal",b?.minimal??200],["low",b?.low??800],["medium",b?.medium??5e3],["high",b?.high??1e4],["highest",b?.highest??24500]],S="minimal",M=Number.POSITIVE_INFINITY;for(let[R,O]of k){let F=Math.abs(y-O);F<M&&(M=F,S=R)}A.thinkingTokenBudget=S}return h.thinking?.includeThoughts!==void 0&&(A.showThoughts=!!h.thinking.includeThoughts),A});super(p,{name:"Anthropic",apiURL:l,headers:u,modelInfo:Hn,defaults:{model:c.model},options:o,supportFor:d,models:m??i})}};function wc(s,e){let t=s.map(r=>{switch(r.role){case"function":return{role:"user",content:[{type:"tool_result",content:r.result,tool_use_id:r.functionId,...r.isError?{is_error:!0}:{},...r.cache?{cache:{type:"ephemeral"}}:{}}]};case"user":return typeof r.content=="string"?{role:"user",content:r.content}:{role:"user",content:r.content.map(i=>{switch(i.type){case"text":return{type:"text",text:i.text,...i.cache?{cache_control:{type:"ephemeral"}}:{}};case"image":return{type:"image",source:{type:"base64",media_type:i.mimeType,data:i.image},...i.cache?{cache_control:{type:"ephemeral"}}:{}};default:throw new Error("Invalid content type")}})};case"assistant":{let o="",i=[],a=r.thoughtBlocks;if(Array.isArray(a)&&a.length>0)for(let l of a)l.encrypted?i.push(l.signature?{type:"redacted_thinking",data:l.data,signature:l.signature}:{type:"redacted_thinking",data:l.data}):i.push(l.signature?{type:"thinking",thinking:l.data,signature:l.signature}:{type:"thinking",thinking:l.data});return typeof r.content=="string"&&(i.length>0?o=[...i,{type:"text",text:r.content}]:o=r.content),typeof r.functionCalls<"u"&&(o=r.functionCalls.map(l=>{let u={};if(typeof l.function.params=="string"){let c=l.function.params;if(c.trim().length===0)u={};else try{u=JSON.parse(c)}catch{throw new Error(`Failed to parse function params JSON: ${c}`)}}else typeof l.function.params=="object"&&(u=l.function.params);return{type:"tool_use",id:l.id,name:l.function.name,input:u,...r.cache?{cache_control:{type:"ephemeral"}}:{}}}),Array.isArray(o)&&i.length>0&&(o=[...i,...o])),{role:"assistant",content:o}}default:throw new Error("Invalid role")}}),n=Rc(t);return vc(n)}function Rc(s){let e=[];for(let[t,n]of s.entries()){if(n.role!=="assistant"){e.push(n);continue}if(t>0&&s.at(t-1)?.role==="assistant"){let r=e.pop();e.push({...r||{},...n})}else e.push(n)}return e}function vc(s){return s.map(e=>e.role==="assistant"&&typeof e.content=="string"?{...e,content:e.content.replace(/\s+$/,"")}:e)}function Na(s){if(s)switch(s){case"stop_sequence":return"stop";case"max_tokens":return"length";case"tool_use":return"function_call";case"end_turn":return"stop";default:return"stop"}}var Kn=(I=>(I.GPT4="gpt-4",I.GPT41="gpt-4.1",I.GPT41Mini="gpt-4.1-mini",I.GPT41Nano="gpt-4.1-nano",I.GPT4O="gpt-4o",I.GPT4OMini="gpt-4o-mini",I.GPT4ChatGPT4O="chatgpt-4o-latest",I.GPT4Turbo="gpt-4-turbo",I.GPT35Turbo="gpt-3.5-turbo",I.GPT35TurboInstruct="gpt-3.5-turbo-instruct",I.GPT35TextDavinci002="text-davinci-002",I.GPT3TextBabbage002="text-babbage-002",I.GPT3TextAda001="text-ada-001",I.GPT5="gpt-5",I.GPT5Nano="gpt-5-nano",I.GPT5Mini="gpt-5-mini",I.GPT5Chat="gpt-5-chat",I.GPT5Pro="gpt-5-pro",I.GPT51="gpt-5.1",I.GPT51ChatLatest="gpt-5.1-chat-latest",I.GPT52="gpt-5.2",I.GPT52ChatLatest="gpt-5.2-chat-latest",I.GPT52Pro="gpt-5.2-pro",I.O1="o1",I.O1Mini="o1-mini",I.O3="o3",I.O3Mini="o3-mini",I.O4Mini="o4-mini",I))(Kn||{}),Vt=(n=>(n.TextEmbeddingAda002="text-embedding-ada-002",n.TextEmbedding3Small="text-embedding-3-small",n.TextEmbedding3Large="text-embedding-3-large",n))(Vt||{});var Wt=(T=>(T.GPT4="gpt-4",T.GPT41="gpt-4.1",T.GPT41Mini="gpt-4.1-mini",T.GPT41Nano="gpt-4.1-nano",T.GPT4O="gpt-4o",T.GPT4OMini="gpt-4o-mini",T.GPT4ChatGPT4O="chatgpt-4o-latest",T.GPT4Turbo="gpt-4-turbo",T.GPT35Turbo="gpt-3.5-turbo",T.GPT35TurboInstruct="gpt-3.5-turbo-instruct",T.GPT35TextDavinci002="text-davinci-002",T.GPT3TextBabbage002="text-babbage-002",T.GPT3TextAda001="text-ada-001",T.GPT5="gpt-5",T.GPT5Nano="gpt-5-nano",T.GPT5Mini="gpt-5-mini",T.GPT5Chat="gpt-5-chat",T.GPT5Pro="gpt-5-pro",T.GPT51="gpt-5.1",T.GPT51ChatLatest="gpt-5.1-chat-latest",T.GPT52="gpt-5.2",T.GPT52ChatLatest="gpt-5.2-chat-latest",T.GPT52Pro="gpt-5.2-pro",T.O1Pro="o1-pro",T.O1="o1",T.O1Mini="o1-mini",T.O3Pro="o3-pro",T.O3="o3",T.O3Mini="o3-mini",T.O4Mini="o4-mini",T))(Wt||{});var Jt=[{name:"gpt-4",currency:"usd",promptTokenCostPer1M:30,completionTokenCostPer1M:60},{name:"gpt-4.1",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8,supported:{structuredOutputs:!0}},{name:"gpt-4.1-mini",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1.6,supported:{structuredOutputs:!0}},{name:"gpt-4.1-nano",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.4,supported:{structuredOutputs:!0}},{name:"gpt-4o",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15,supported:{structuredOutputs:!0}},{name:"gpt-4o-mini",currency:"usd",promptTokenCostPer1M:.15,completionTokenCostPer1M:.6,supported:{structuredOutputs:!0}},{name:"chatgpt-4o-latest",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15,supported:{structuredOutputs:!0}},{name:"gpt-4-turbo",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,supported:{structuredOutputs:!0}},{name:"gpt-3.5-turbo",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5},{name:"gpt-5-nano",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5-mini",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:6,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5-chat",currency:"usd",promptTokenCostPer1M:12,completionTokenCostPer1M:36,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:60,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5-pro",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:120,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.1",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.1-chat-latest",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.2",currency:"usd",promptTokenCostPer1M:1.75,completionTokenCostPer1M:14,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.2-chat-latest",currency:"usd",promptTokenCostPer1M:1.75,completionTokenCostPer1M:14,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.2-pro",currency:"usd",promptTokenCostPer1M:21,completionTokenCostPer1M:168,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"o1",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{structuredOutputs:!0}},{name:"o1-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:14.4,supported:{structuredOutputs:!0}},{name:"o3",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{structuredOutputs:!0}},{name:"o4-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,supported:{structuredOutputs:!0}},{name:"text-embedding-ada-002",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.1},{name:"text-embedding-3-small",currency:"usd",promptTokenCostPer1M:.02,completionTokenCostPer1M:.02},{name:"text-embedding-3-large",currency:"usd",promptTokenCostPer1M:.13,completionTokenCostPer1M:.13}],Ur=[{name:"gpt-4",currency:"usd",promptTokenCostPer1M:30,completionTokenCostPer1M:60},{name:"gpt-4.1",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8,supported:{structuredOutputs:!0}},{name:"gpt-4.1-mini",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1.6,supported:{structuredOutputs:!0}},{name:"gpt-4.1-nano",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.4,supported:{structuredOutputs:!0}},{name:"gpt-4o",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15,supported:{structuredOutputs:!0}},{name:"gpt-4o-mini",currency:"usd",promptTokenCostPer1M:.15,completionTokenCostPer1M:.6,supported:{structuredOutputs:!0}},{name:"chatgpt-4o-latest",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15,supported:{structuredOutputs:!0}},{name:"gpt-4-turbo",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,supported:{structuredOutputs:!0}},{name:"gpt-3.5-turbo",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5},{name:"gpt-5-nano",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5-mini",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:6,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5-chat",currency:"usd",promptTokenCostPer1M:12,completionTokenCostPer1M:36,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:60,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5-pro",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:120,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.1",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.1-chat-latest",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.2",currency:"usd",promptTokenCostPer1M:1.75,completionTokenCostPer1M:14,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.2-chat-latest",currency:"usd",promptTokenCostPer1M:1.75,completionTokenCostPer1M:14,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.2-pro",currency:"usd",promptTokenCostPer1M:21,completionTokenCostPer1M:168,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"o1-pro",currency:"usd",promptTokenCostPer1M:150,completionTokenCostPer1M:600,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0},isExpensive:!0},{name:"o1",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"o3-pro",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:80,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0},isExpensive:!0},{name:"o3",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"o3-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"o4-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}}];var Sc=s=>{let e=["o1","o1-mini","o3","o3-mini","o4-mini","o1-pro","o3-pro"];return e.includes(s)||e.includes(s)},Ft=()=>structuredClone({model:"gpt-5-mini",embedModel:"text-embedding-3-small",...ie()}),Br=()=>structuredClone({...Ft(),model:"gpt-5"}),jr=()=>structuredClone({model:"gpt-5-mini",embedModel:"text-embedding-3-small",...Se()}),zr=()=>({...Ft(),model:"gpt-5-nano"}),Es=class{constructor(e,t,n){this.config=e;this.streamingUsage=t;this.chatReqUpdater=n}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,endSequences:e.endSequences,topP:e.topP,n:e.n,stream:e.stream}}createChatReq=(e,t)=>{let n=e.model;if(!e.chatPrompt||e.chatPrompt.length===0)throw new Error("Chat prompt is empty");let r={name:"/chat/completions"},o=e.functions?.map(m=>({type:"function",function:{name:m.name,description:m.description,parameters:m.parameters}})),i=!e.functionCall&&e.functions&&e.functions.length>0?"auto":e.functionCall,a=Oc(e),l=e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,u=e.modelConfig?.stream??this.config.stream,c=this.config.store,p=Sc(n),d={model:n,messages:a,...e.responseFormat?{response_format:e.responseFormat.type==="json_schema"?{type:"json_schema",json_schema:e.responseFormat.schema}:e.responseFormat}:this.config?.responseFormat?{response_format:{type:this.config.responseFormat}}:{},...o?{tools:o}:{},...i?{tool_choice:i}:{},...p?{}:{...(e.modelConfig?.maxTokens??this.config.maxTokens)!==void 0?{max_completion_tokens:e.modelConfig?.maxTokens??this.config.maxTokens}:{},...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{top_p:e.modelConfig.topP}:{},...(e.modelConfig?.n??this.config.n)!==void 0?{n:e.modelConfig?.n??this.config.n}:{},...(e.modelConfig?.presencePenalty??this.config.presencePenalty)!==void 0?{presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty}:{},...l!==void 0?{frequency_penalty:l}:{}},...(e.modelConfig?.stopSequences??this.config.stop)&&(e.modelConfig?.stopSequences??this.config.stop).length>0?{stop:e.modelConfig?.stopSequences??this.config.stop}:{},...this.config.logitBias!==void 0?{logit_bias:this.config.logitBias}:{},...u&&this.streamingUsage?{stream:!0,stream_options:{include_usage:!0}}:{},...c?{store:c}:{},...this.config.serviceTier?{service_tier:this.config.serviceTier}:{},...this.config.user?{user:this.config.user}:{}};if(this.config.reasoningEffort&&(d.reasoning_effort=this.config.reasoningEffort),this.config.webSearchOptions&&(d.web_search_options={...this.config.webSearchOptions.searchContextSize&&{search_context_size:this.config.webSearchOptions.searchContextSize},...this.config.webSearchOptions.userLocation&&{user_location:{approximate:{type:"approximate",...this.config.webSearchOptions.userLocation.approximate.city&&{city:this.config.webSearchOptions.userLocation.approximate.city},...this.config.webSearchOptions.userLocation.approximate.country&&{country:this.config.webSearchOptions.userLocation.approximate.country},...this.config.webSearchOptions.userLocation.approximate.region&&{region:this.config.webSearchOptions.userLocation.approximate.region},...this.config.webSearchOptions.userLocation.approximate.timezone&&{timezone:this.config.webSearchOptions.userLocation.approximate.timezone}}}}}),t?.thinkingTokenBudget)switch(t.thinkingTokenBudget){case"none":d.reasoning_effort=void 0;break;case"minimal":d.reasoning_effort="minimal";break;case"low":d.reasoning_effort="medium";break;case"medium":d.reasoning_effort="high";break;case"high":d.reasoning_effort="high";break;case"highest":d.reasoning_effort="high";break}if(!d.reasoning_effort&&t?.thinkingTokenBudget)switch(t.thinkingTokenBudget){case"minimal":d.reasoning_effort="minimal";break;case"low":d.reasoning_effort="medium";break;case"medium":case"high":case"highest":d.reasoning_effort="high";break}return this.chatReqUpdater&&(d=this.chatReqUpdater(d)),[r,d]};createEmbedReq=e=>{let t=e.embedModel;if(!t)throw new Error("Embed model not set");if(!e.texts||e.texts.length===0)throw new Error("Embed texts is empty");let n={name:"/embeddings"},r={model:t,input:e.texts,dimensions:this.config.dimensions};return[n,r]};createChatResp(e){let{id:t,usage:n,choices:r,error:o}=e;if(o)throw o;return this.tokensUsed=n?{promptTokens:n.prompt_tokens,completionTokens:n.completion_tokens,totalTokens:n.total_tokens}:void 0,{results:r.map(a=>{if(a.message.refusal)throw new fe(a.message.refusal,e.model,e.id);let l=La(a.finish_reason),u=a.message.tool_calls?.map(({id:c,function:{arguments:p,name:d}})=>({id:c,type:"function",function:{name:d,params:p}}));return{index:a.index,id:`${a.index}`,content:a.message.content??void 0,thought:a.message.reasoning_content,citations:a.message.annotations?.filter(c=>c?.type==="url_citation"&&c.url_citation).map(c=>({url:c.url_citation?.url,title:c.url_citation?.title,description:c.url_citation?.description})),functionCalls:u,finishReason:l}}),remoteId:t}}createChatStreamResp(e,t){let{id:n,usage:r,choices:o}=e;this.tokensUsed=r?{promptTokens:r.prompt_tokens,completionTokens:r.completion_tokens,totalTokens:r.total_tokens}:void 0;let i=t;return i.indexIdMap||(i.indexIdMap={}),{results:o.map(({index:l,delta:{content:u,role:c,refusal:p,tool_calls:d,reasoning_content:m,annotations:g},finish_reason:f})=>{if(p)throw new fe(p,void 0,n);let h=La(f),x=d?.map(({id:A,index:y,function:{name:b,arguments:k}})=>{typeof A=="string"&&typeof y=="number"&&!i.indexIdMap[y]&&(i.indexIdMap[y]=A);let S=i.indexIdMap[y];return S?{id:S,type:"function",function:{name:b,params:k}}:null}).filter(A=>A!==null);return{index:l,content:u??void 0,role:c,thought:m,citations:g?.filter(A=>A?.type==="url_citation"&&A.url_citation).map(A=>({url:A.url_citation?.url,title:A.url_citation?.title,description:A.url_citation?.description})),functionCalls:x,finishReason:h,id:n}})}}createEmbedResp(e){let{data:t,usage:n}=e;return this.tokensUsed=n?{promptTokens:n.prompt_tokens,completionTokens:n.completion_tokens,totalTokens:n.total_tokens}:void 0,{embeddings:t.map(r=>r.embedding)}}},La=s=>{switch(s){case"stop":return"stop";case"length":return"length";case"content_filter":return"error";case"tool_calls":return"function_call"}};function Oc(s){return s.chatPrompt.map(t=>{switch(t.role){case"system":return{role:"system",content:t.content};case"user":{let n=Array.isArray(t.content)?t.content.map(r=>{switch(r.type){case"text":return{type:"text",text:r.text};case"image":return{type:"image_url",image_url:{url:`data:${r.mimeType};base64,${r.image}`,details:r.details??"auto"}};case"audio":return{type:"input_audio",input_audio:{data:r.data,format:r.format==="wav"?"wav":void 0}};default:throw new Error("Invalid content type")}}):t.content;return{role:"user",...t.name?{name:t.name}:{},content:n}}case"assistant":{let n=t.functionCalls?.map(r=>({id:r.id,type:"function",function:{name:r.function.name,arguments:typeof r.function.params=="object"?JSON.stringify(r.function.params):r.function.params}}));if(n&&n.length>0)return{role:"assistant",...t.content?{content:t.content}:{},name:t.name,tool_calls:n};if(t.content===void 0)throw new Error("Assistant content is required when no tool calls are provided");return{role:"assistant",content:t.content,...t.name?{name:t.name}:{}}}case"function":return{role:"tool",content:t.result,tool_call_id:t.functionId};default:throw new Error("Invalid role")}})}var Te=class extends we{constructor({apiKey:e,config:t,options:n,apiURL:r,modelInfo:o,models:i,chatReqUpdater:a,supportFor:l}){if(!e||e==="")throw new Error("OpenAI API key not set");let u=new Es(t,n?.streamingUsage??!0,a);super(u,{name:"OpenAI",apiURL:r||"https://api.openai.com/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:o,defaults:{model:t.model,embedModel:t.embedModel},options:n,supportFor:l,models:i})}},Yt=class extends Te{constructor({apiKey:e,apiURL:t,config:n,options:r,models:o,modelInfo:i}){if(!e||e==="")throw new Error("OpenAI API key not set");i=[...Jt,...i??[]];let a=u=>{let c=We({model:u,modelInfo:i,models:o});return{functions:!0,streaming:!0,hasThinkingBudget:c?.supported?.thinkingBudget??!1,hasShowThoughts:c?.supported?.showThoughts??!1,structuredOutputs:c?.supported?.structuredOutputs??!1,media:{images:{supported:!0,formats:["image/jpeg","image/png","image/gif","image/webp"],maxSize:20*1024*1024,detailLevels:["high","low","auto"]},audio:{supported:!0,formats:["wav","mp3","ogg"],maxDuration:25*60},files:{supported:!0,formats:["text/plain","application/pdf","image/jpeg","image/png"],maxSize:512*1024*1024,uploadMethod:"upload"},urls:{supported:!1,webSearch:!0,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:c?.supported?.thinkingBudget??!1,multiTurn:!0}},l=o?.map(u=>{let c=u,p=c?.config;if(!p)return u;let d={};p.maxTokens!==void 0&&(d.maxTokens=p.maxTokens),p.temperature!==void 0&&(d.temperature=p.temperature),p.topP!==void 0&&(d.topP=p.topP),p.presencePenalty!==void 0&&(d.presencePenalty=p.presencePenalty),p.frequencyPenalty!==void 0&&(d.frequencyPenalty=p.frequencyPenalty);let m=p.stopSequences??p.stop;m!==void 0&&(d.stopSequences=m),p.n!==void 0&&(d.n=p.n),p.stream!==void 0&&(d.stream=p.stream);let g={...c};Object.keys(d).length>0&&(g.modelConfig={...c.modelConfig??{},...d});let f=p?.thinking?.thinkingTokenBudget;if(typeof f=="number"){let h=[["minimal",200],["low",800],["medium",5e3],["high",1e4],["highest",24500]],x="minimal",A=Number.POSITIVE_INFINITY;for(let[y,b]of h){let k=Math.abs(f-b);k<A&&(A=k,x=y)}g.thinkingTokenBudget=x}return p?.thinking?.includeThoughts!==void 0&&(g.showThoughts=!!p.thinking.includeThoughts),g});super({apiKey:e,apiURL:t,config:{...Ft(),...n},options:r,modelInfo:i,models:l??o,supportFor:a}),super.setName("OpenAI")}};var kc=s=>{let e=s.trim();if(!e)return e;if(e.includes("api-version=")){let t=e.indexOf("api-version="),n=e.slice(t);return new URLSearchParams(n).get("api-version")??e}return e},Mc=s=>{let e=s.match(/^(\d{4}-\d{2}-\d{2})/);return e?e[1]>="2024-08-01":!1},Ps=Ft,Ga=jr,Ua=zr,Ba=Br,Qt=class extends Te{constructor({apiKey:e,resourceName:t,deploymentName:n,version:r="api-version=2024-02-15-preview",config:o,options:i,models:a,modelInfo:l}){if(!e||e==="")throw new Error("Azure OpenAPI API key not set");if(!t||t==="")throw new Error("Azure OpenAPI resource name not set");if(!n||n==="")throw new Error("Azure OpenAPI deployment id not set");let u={...Ps(),...o},c=kc(r),p=Mc(c);l=[...Jt,...l??[]];let d=g=>{let f=We({model:g,modelInfo:l,models:a});return{functions:!0,streaming:!0,hasThinkingBudget:f?.supported?.thinkingBudget??!1,hasShowThoughts:f?.supported?.showThoughts??!1,structuredOutputs:p&&(f?.supported?.structuredOutputs??!1),functionCot:!1,media:{images:{supported:!0,formats:["image/jpeg","image/png","image/gif","image/webp"],maxSize:20*1024*1024,detailLevels:["high","low","auto"]},audio:{supported:!1,formats:[],maxDuration:0},files:{supported:!1,formats:[],maxSize:0,uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:f?.supported?.thinkingBudget??!1,multiTurn:!0}};super({apiKey:e,config:u,options:i,models:a,modelInfo:l,supportFor:d});let m=t.includes("://")?t:`https://${t}.openai.azure.com/`;super.setName("Azure OpenAI"),super.setAPIURL(new URL(`/openai/deployments/${n}?api-version=${c}`,m).href),super.setHeaders(async()=>({"api-key":e}))}};var qr=class s{services;currentServiceIndex=0;currentService;debug;initialBackoffMs;maxBackoffMs;maxRetries;serviceFailures=new Map;constructor(e,t){if(e.length===0)throw new Error("No AI services provided.");Ec(e),this.services=[...e].sort(t?.comparator??s.metricComparator);let n=this.services[this.currentServiceIndex];if(n===void 0)throw new Error("Error initializing the AI services.");this.currentService=n,this.debug=t?.debug??!0,this.initialBackoffMs=t?.initialBackoffMs??1e3,this.maxBackoffMs=t?.maxBackoffMs??32e3,this.maxRetries=t?.maxRetries??3}static create(e,t){return new s(e,t)}getLastUsedChatModel(){return this.currentService.getLastUsedChatModel()}getLastUsedEmbedModel(){return this.currentService.getLastUsedEmbedModel()}getLastUsedModelConfig(){return this.currentService.getLastUsedModelConfig()}static inputOrderComparator=()=>0;static metricComparator=(e,t)=>{let n=e.getMetrics(),r=t.getMetrics();return n.latency.chat.mean-r.latency.chat.mean};getModelList(){for(let e of this.services){let t=e.getModelList();if(t)return t}}getNextService(e,t){let n=t+1,r=e[n];return r===void 0?{service:void 0,index:n}:{service:r,index:n}}reset(){this.currentServiceIndex=0;let e=this.services[this.currentServiceIndex];if(e===void 0)throw new Error("No AI services provided.");this.currentService=e}getName(){return this.currentService.getName()}getId(){return this.currentService.getId()}getFeatures(e){let t={functions:!1,streaming:!1,thinking:!1,multiTurn:!1,structuredOutputs:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]}};for(let n of this.services){let r=n.getFeatures(e);r.functions&&(t.functions=!0),r.streaming&&(t.streaming=!0),r.thinking&&(t.thinking=!0),r.multiTurn&&(t.multiTurn=!0),r.structuredOutputs&&(t.structuredOutputs=!0),r.functionCot&&(t.functionCot=!0),r.hasThinkingBudget&&(t.hasThinkingBudget=!0),r.hasShowThoughts&&(t.hasShowThoughts=!0),r.media.images.supported&&(t.media.images.supported=!0),t.media.images.formats=Array.from(new Set([...t.media.images.formats,...r.media.images.formats])),r.media.audio.supported&&(t.media.audio.supported=!0),t.media.audio.formats=Array.from(new Set([...t.media.audio.formats,...r.media.audio.formats])),r.media.files.supported&&(t.media.files.supported=!0),t.media.files.formats=Array.from(new Set([...t.media.files.formats,...r.media.files.formats])),r.media.files.uploadMethod!=="none"&&(t.media.files.uploadMethod=r.media.files.uploadMethod),r.media.urls.supported&&(t.media.urls.supported=!0),r.media.urls.webSearch&&(t.media.urls.webSearch=!0),r.media.urls.contextFetching&&(t.media.urls.contextFetching=!0),r.caching.supported&&(t.caching.supported=!0),t.caching.types=Array.from(new Set([...t.caching.types,...r.caching.types]))}return t}getMetrics(){let e={latency:{chat:{mean:0,p95:0,p99:0,samples:[]},embed:{mean:0,p95:0,p99:0,samples:[]}},errors:{chat:{count:0,rate:0,total:0},embed:{count:0,rate:0,total:0}}},t=0,n=0,r=0,o=0;for(let i of this.services){let a=i.getMetrics();e.errors.chat.count+=a.errors.chat.count,e.errors.chat.total+=a.errors.chat.total,e.errors.embed.count+=a.errors.embed.count,e.errors.embed.total+=a.errors.embed.total;let l=a.latency.chat.samples.length;l>0&&(t+=a.latency.chat.mean*l,n+=l);let u=a.latency.embed.samples.length;u>0&&(r+=a.latency.embed.mean*u,o+=u)}e.errors.chat.total>0&&(e.errors.chat.rate=e.errors.chat.count/e.errors.chat.total),e.errors.embed.total>0&&(e.errors.embed.rate=e.errors.embed.count/e.errors.embed.total),n>0&&(e.latency.chat.mean=t/n),o>0&&(e.latency.embed.mean=r/o);for(let i of this.services){let a=i.getMetrics();e.latency.chat.p95=Math.max(e.latency.chat.p95,a.latency.chat.p95),e.latency.chat.p99=Math.max(e.latency.chat.p99,a.latency.chat.p99),e.latency.embed.p95=Math.max(e.latency.embed.p95,a.latency.embed.p95),e.latency.embed.p99=Math.max(e.latency.embed.p99,a.latency.embed.p99)}return e}canRetryService(e){let t=this.serviceFailures.get(e.getId());if(!t)return!0;let{retries:n,lastFailureTime:r}=t,o=Date.now()-r,i=Math.min(this.initialBackoffMs*2**n,this.maxBackoffMs);return o>=i}handleFailure(e,t){let r=(this.serviceFailures.get(e.getId())?.retries??0)+1;this.serviceFailures.set(e.getId(),{retries:r,lastFailureTime:Date.now()}),this.debug&&console.warn(`AxBalancer: Service ${e.getName()} failed (retry ${r}/${this.maxRetries})`,t)}handleSuccess(e){this.serviceFailures.delete(e.getId())}async chat(e,t){let n=e.responseFormat?.type==="json_schema",r=e.capabilities,o=r?.requiresImages,i=r?.requiresAudio,a=this.services,l=e.model;if((n||o||i)&&(a=this.services.filter(p=>{let d=p.getFeatures(l);return!(n&&!d.structuredOutputs||o&&!d.media.images.supported||i&&!d.media.audio.supported)}),a.length===0)){let p=[];throw n&&p.push("structured outputs"),o&&p.push("images"),i&&p.push("audio"),new Error(`No services available that support required capabilities: ${p.join(", ")}.`)}let u=0,c=a[u];if(!c)throw new Error("No matching AI services available for request.");for(this.currentService=c;;){if(!this.canRetryService(c)){let p=this.getNextService(a,u);if(!p.service)throw new Error(`All candidate services exhausted (tried ${a.length} service(s))`);c=p.service,u=p.index,this.currentService=c;continue}try{let p=await c.chat(e,t);return this.handleSuccess(c),p}catch(p){if(!(p instanceof Fe))throw p;switch(p.constructor){case At:throw p;case Ke:{if(![408,429,500,502,503,504].includes(p.status))throw p;break}case De:break;case xt:break;case Ye:break;case ot:break;default:throw p}if(this.handleFailure(c,p),(this.serviceFailures.get(c.getId())?.retries??0)>=this.maxRetries){let m=this.getNextService(a,u);if(this.debug&&console.warn(`AxBalancer: Switching to service ${m.service?.getName()??"none"}`,p),!m.service)throw p;c=m.service,u=m.index,this.currentService=c}}}}async embed(e,t){this.reset();let n=this.currentServiceIndex;for(;;){if(!this.canRetryService(this.currentService)){let r=this.getNextService(this.services,n);if(!r.service)throw new Error(`All services exhausted (tried ${this.services.length} service(s))`);this.currentService=r.service,n=r.index,this.currentServiceIndex=n;continue}try{let r=await this.currentService.embed(e,t);return this.handleSuccess(this.currentService),r}catch(r){if(!(r instanceof Fe)||r instanceof Ke&&![408,429,500,502,503,504].includes(r.status)||r instanceof At)throw r;if(this.handleFailure(this.currentService,r),(this.serviceFailures.get(this.currentService.getId())?.retries??0)>=this.maxRetries){let i=this.getNextService(this.services,n);if(!i.service)throw r;this.currentService=i.service,n=i.index,this.currentServiceIndex=n}}}}setOptions(e){for(let t of this.services)t.setOptions(e);this.currentService.setOptions(e),this.debug=e.debug??this.debug}getOptions(){return this.currentService.getOptions()}getLogger(){return this.currentService.getLogger()}};function Ec(s){let e=s.find(r=>r.getModelList()!==void 0);if(!e)return;let t=e.getModelList();if(!t)throw new Error("No model list found in any service.");let n=new Set(t.map(r=>r.key));for(let r=0;r<s.length;r++){let o=s[r];if(!o)throw new Error(`Service at index ${r} is undefined`);let i=o.getModelList();if(!i)throw new Error(`Service at index ${r} (${o.getName()}) has no model list while another service does.`);let a=new Set(i.map(l=>l.key));for(let l of n)if(!a.has(l))throw new Error(`Service at index ${r} (${o.getName()}) is missing model "${l}"`);for(let l of a)if(!n.has(l))throw new Error(`Service at index ${r} (${o.getName()}) has extra model "${l}"`)}}function _t(s){let e=!1,t=!1,n=!1,r=!1,o=!1,i=!1,a=!1,l=new Set,u=0;if(s.chatPrompt&&Array.isArray(s.chatPrompt))for(let c of s.chatPrompt){if(c.role==="user"&&Array.isArray(c.content))for(let p of c.content)switch(l.add(p.type),p.type){case"image":e=!0,p.cache&&(a=!0),u+=85;break;case"audio":t=!0,p.cache&&(a=!0),u+=p.duration||60;break;case"file":n=!0,p.cache&&(a=!0),u+=Math.ceil((p.extractedText?.length||1e3)/4);break;case"url":r=!0,p.cache&&(a=!0),u+=Math.ceil((p.cachedContent?.length||2e3)/4);break;case"text":p.cache&&(a=!0),u+=Math.ceil(p.text.length/4);break}else"content"in c&&typeof c.content=="string"&&(u+=Math.ceil(c.content.length/4));"cache"in c&&c.cache&&(a=!0)}return s.functions&&s.functions.length>0&&(o=!0),s.modelConfig?.stream===!0&&(i=!0),s.capabilities&&(s.capabilities.requiresImages&&(e=!0),s.capabilities.requiresAudio&&(t=!0),s.capabilities.requiresFiles&&(n=!0),s.capabilities.requiresWebSearch&&(r=!0)),{hasImages:e,hasAudio:t,hasFiles:n,hasUrls:r,requiresFunctions:o,requiresStreaming:i,requiresCaching:a,contentTypes:l,estimatedTokens:u}}function Fs(s,e){let t=s.getFeatures(),n=[],r=[],o=[];if(e.hasImages&&!t.media.images.supported&&(n.push("Image support"),o.push("Use altText for images or imageToText service")),e.hasAudio&&!t.media.audio.supported&&(n.push("Audio support"),o.push("Pre-transcribe audio or use transcription field")),e.hasFiles&&!t.media.files.supported&&(n.push("File support"),o.push("Pre-extract text content or use extractedText field")),e.hasUrls&&!t.media.urls.supported&&(n.push("URL/Web search support"),o.push("Pre-fetch content or use cachedContent field")),e.requiresFunctions&&!t.functions&&n.push("Function calling"),e.requiresStreaming&&!t.streaming&&(n.push("Streaming responses"),o.push("Use non-streaming mode")),e.requiresCaching&&!t.caching.supported&&(n.push("Content caching"),o.push("Repeated content will not be cached")),e.hasImages&&t.media.images.supported){let a=t.media.images.maxSize;a&&a<10*1024*1024&&r.push(`Image size limit is ${Math.round(a/(1024*1024))}MB`)}if(e.hasAudio&&t.media.audio.supported){let a=t.media.audio.maxDuration;a&&a<600&&r.push(`Audio duration limit is ${Math.round(a/60)} minutes`)}return{isSupported:n.length===0,missingCapabilities:n,warnings:r,alternatives:o}}function Hr(s,e){return s.map(t=>{let n=t.getFeatures(),r=Fs(t,e),o=0,i=[];return o+=10,e.hasImages&&n.media.images.supported&&(o+=25,i.push("Images"),n.media.images.detailLevels?.includes("high")&&(o+=5),n.media.images.maxSize&&n.media.images.maxSize>10*1024*1024&&(o+=3)),e.hasAudio&&n.media.audio.supported&&(o+=25,i.push("Audio"),n.media.audio.maxDuration&&n.media.audio.maxDuration>600&&(o+=5)),e.hasFiles&&n.media.files.supported&&(o+=25,i.push("Files"),n.media.files.uploadMethod==="cloud"&&(o+=3)),e.hasUrls&&n.media.urls.supported&&(o+=25,i.push("URLs"),n.media.urls.webSearch&&(o+=5)),e.requiresFunctions&&n.functions&&(o+=15,i.push("Functions"),n.functionCot&&(o+=3)),e.requiresStreaming&&n.streaming&&(o+=10,i.push("Streaming")),e.requiresCaching&&n.caching.supported&&(o+=8,i.push("Caching"),n.caching.types.includes("persistent")&&(o+=3)),n.thinking&&(o+=2),n.multiTurn&&(o+=2),n.hasThinkingBudget&&(o+=1),n.hasShowThoughts&&(o+=1),o-=r.missingCapabilities.length*10,{provider:t,score:o,missingCapabilities:r.missingCapabilities,supportedCapabilities:i}}).sort((t,n)=>n.score-t.score)}function Kr(s,e,t={}){if(e.length===0)throw new Error("No providers available");let n=_t(s),r=Hr(e,n);if(t.requireExactMatch){let o=r.filter(i=>i.missingCapabilities.length===0);if(o.length===0)throw new Error(`No providers fully support the request requirements: ${r[0]?.missingCapabilities.join(", ")||"unknown requirements"}`);return o[0].provider}if(!t.allowDegradation){let o=r[0];if(o.missingCapabilities.length>0)throw new Error(`Best available provider (${o.provider.getName()}) is missing: ${o.missingCapabilities.join(", ")}`)}return r[0].provider}function ja(s,e){let t=_t(s),n=Hr(e,t),r=n[0]?.provider||null,o=[t.hasImages&&"images",t.hasAudio&&"audio",t.hasFiles&&"files",t.hasUrls&&"URLs",t.requiresFunctions&&"functions",t.requiresStreaming&&"streaming",t.requiresCaching&&"caching"].filter(Boolean).length,i=r?n[0].supportedCapabilities.length:0,a=r?`${r.getName()} supports ${i}/${o} requirements (${Math.round(i/Math.max(o,1)*100)}% compatibility)`:"No suitable providers found";return{requirements:t,providerScores:n,recommendedProvider:r,summary:a}}function za(s,e){return s.filter(t=>t.getFeatures().media[e].supported)}function qa(s,e){let t={};for(let n of s){let o=n.getFeatures().media[e];if(o.supported)for(let i of o.formats)t[i]||(t[i]=[]),t[i].push(n)}return t}var Vn=(r=>(r.CommandRPlus="command-r-plus",r.CommandR="command-r",r.Command="command",r.CommandLight="command-light",r))(Vn||{}),Wn=(r=>(r.EmbedEnglishV30="embed-english-v3.0",r.EmbedEnglishLightV30="embed-english-light-v3.0",r.EmbedMultiLingualV30="embed-multilingual-v3.0",r.EmbedMultiLingualLightV30="embed-multilingual-light-v3.0",r))(Wn||{});var Vr=[{name:"command-r-plus",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15},{name:"command-r",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5},{name:"command",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5},{name:"command-light",currency:"usd",promptTokenCostPer1M:.3,completionTokenCostPer1M:.6},{name:"embed-english-light-v3.0",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.1},{name:"embed-english-v3.0",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.1},{name:"embed-multilingual-v3.0",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.1},{name:"embed-multilingual-light-v3.0",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.1}];var $s=()=>structuredClone({model:"command-r-plus",embedModel:"embed-english-v3.0",...ie()}),Ka=()=>structuredClone({model:"command-r",embedModel:"embed-english-v3.0",...Se()}),_s=class{constructor(e){this.config=e}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,frequencyPenalty:e.frequencyPenalty,presencePenalty:e.presencePenalty,endSequences:e.endSequences,stopSequences:e.stopSequences,stream:e.stream,n:e.n}}createChatReq(e){let t=e.model,n=e.chatPrompt.at(-1),r=e.chatPrompt.slice(0,-1),o;n&&n.role==="user"&&typeof n.content=="string"&&(o=n?.content);let i=Pc(r),a=e.functions?.map(p=>{let d={};if(p.parameters?.properties)for(let[m,g]of Object.entries(p.parameters.properties))d[m]={description:g.description,type:g.type,required:p.parameters.required?.includes(m)??!1};return{name:p.name,description:p.description,parameter_definitions:d}}),l=e.chatPrompt.filter(p=>p.role==="function").map(p=>{let d=a?.find(m=>m.name===p.functionId);if(!d)throw new Error("Function not found");return{call:{name:d.name,parameters:d.parameter_definitions},outputs:[{result:p.result??""}]}}),u={name:"/chat"},c={message:o,model:t,tools:a,...l&&!o?{tool_results:l}:{},chat_history:i,max_tokens:e.modelConfig?.maxTokens??this.config.maxTokens,...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},k:e.modelConfig?.topK??this.config.topK,...e.modelConfig?.topP!==void 0?{p:e.modelConfig.topP}:{},frequency_penalty:e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty,end_sequences:this.config.endSequences,stop_sequences:e.modelConfig?.stopSequences??this.config.stopSequences};return[u,c]}createEmbedReq=e=>{let t=e.embedModel;if(!t)throw new Error("Embed model not set");if(!e.texts||e.texts.length===0)throw new Error("Embed texts is empty");let n={name:"/embed"},r={model:t,texts:e.texts??[],input_type:"classification",truncate:""};return[n,r]};createChatResp=e=>{this.tokensUsed=e.meta.billed_units?{promptTokens:e.meta.billed_units.input_tokens,completionTokens:e.meta.billed_units.output_tokens,totalTokens:e.meta.billed_units.input_tokens+e.meta.billed_units.output_tokens}:void 0;let t;if("finish_reason"in e)switch(e.finish_reason){case"COMPLETE":t="stop";break;case"MAX_TOKENS":t="length";break;case"ERROR":throw new Error("Finish reason: ERROR");case"ERROR_TOXIC":throw new Error("Finish reason: CONTENT_FILTER");default:t="stop";break}let n;return"tool_calls"in e&&(n=e.tool_calls?.map(o=>({id:o.name,type:"function",function:{name:o.name,params:o.parameters}}))),{results:[{index:0,id:e.generation_id,content:e.text,functionCalls:n,finishReason:t}],remoteId:e.response_id}};createChatStreamResp=(e,t)=>{let n=t;e.event_type==="stream-start"&&(n.generation_id=e.generation_id),this.tokensUsed={promptTokens:0,completionTokens:e.meta.billed_units?.output_tokens??0,totalTokens:e.meta.billed_units?.output_tokens??0};let{results:r}=this.createChatResp(e),o=r[0];if(!o)throw new Error("No result");return o.id=n.generation_id??"",{results:r}};createEmbedResp(e){return{remoteId:e.id,embeddings:e.embeddings}}},Zt=class extends we{constructor({apiKey:e,config:t,options:n,models:r}){if(!e||e==="")throw new Error("Cohere API key not set");let o={...$s(),...t},i=new _s(o),a=r?.map(l=>{let u=l,c=u?.config;if(!c)return l;let p={};c.maxTokens!==void 0&&(p.maxTokens=c.maxTokens),c.temperature!==void 0&&(p.temperature=c.temperature),c.topP!==void 0&&(p.topP=c.topP),c.topK!==void 0&&(p.topK=c.topK),c.presencePenalty!==void 0&&(p.presencePenalty=c.presencePenalty),c.frequencyPenalty!==void 0&&(p.frequencyPenalty=c.frequencyPenalty),c.stopSequences!==void 0&&(p.stopSequences=c.stopSequences),c.endSequences!==void 0&&(p.endSequences=c.endSequences),c.stream!==void 0&&(p.stream=c.stream),c.n!==void 0&&(p.n=c.n);let d={...u};return Object.keys(p).length>0&&(d.modelConfig={...u.modelConfig??{},...p}),d});super(i,{name:"Cohere",apiURL:"https://api.cohere.ai/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:Vr,defaults:{model:o.model},supportFor:{functions:!0,streaming:!0,media:{images:{supported:!1,formats:[],maxSize:0,detailLevels:[]},audio:{supported:!1,formats:[],maxDuration:0},files:{supported:!1,formats:[],maxSize:0,uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0},options:n,models:a??r})}};function Pc(s){return s.map(e=>{let t="";if(e.role==="system"||e.role==="assistant"||e.role==="user")if(typeof e.content=="string")t=e.content;else throw new Error("Multi-modal content not supported");switch(e.role){case"user":return{role:"USER",message:t};case"system":return{role:"SYSTEM",message:t};case"assistant":{let n=Ha(e.functionCalls);return{role:"CHATBOT",message:t,tool_calls:n}}case"function":{let n=s.map(i=>{if(i.role==="assistant")return i.functionCalls?.find(a=>a.id===e.functionId)}).filter(i=>i!==void 0),r=Ha(n)?.at(0);if(!r)throw new Error("Function call not found");let o=[{result:e.result}];return{role:"TOOL",tool_results:[{call:r,outputs:o}]}}default:throw new Error("Unknown role")}})}function Ha(s){return s?.map(e=>{let t;if(typeof e.function.params=="string"){let n=e.function.params;if(n.trim().length===0)t={};else try{t=JSON.parse(n)}catch{throw new Error(`Failed to parse function params JSON: ${n}`)}}else t=e.function.params;return{name:e.function.name,parameters:t}})}var Jn=(n=>(n.DeepSeekChat="deepseek-chat",n.DeepSeekCoder="deepseek-coder",n.DeepSeekReasoner="deepseek-reasoner",n))(Jn||{});var Wr=[{name:"deepseek-chat",currency:"USD",promptTokenCostPer1M:.27,completionTokenCostPer1M:1.1},{name:"deepseek-reasoner",currency:"USD",promptTokenCostPer1M:.55,completionTokenCostPer1M:2.19}];var Ns=()=>structuredClone({model:"deepseek-chat",...ie()}),Va=()=>structuredClone({model:"deepseek-coder",...Se()}),Xt=class extends Te{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("DeepSeek API key not set");let i={...Ns(),...t};o=[...Wr,...o??[]],super({apiKey:e,config:i,options:n,apiURL:"https://api.deepseek.com",modelInfo:o,supportFor:{functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0},models:r}),super.setName("DeepSeek")}};var Yn=(A=>(A.Gemini3Flash="gemini-3-flash-preview",A.Gemini3Pro="gemini-3-pro-preview",A.Gemini3ProImage="gemini-3-pro-image-preview",A.Gemini25Pro="gemini-2.5-pro",A.Gemini25Flash="gemini-2.5-flash",A.Gemini25FlashLite="gemini-2.5-flash-lite",A.Gemini20Flash="gemini-2.0-flash",A.Gemini20FlashLite="gemini-2.0-flash-lite",A.Gemini20ProExp="gemini-2.0-pro-exp-02-05",A.Gemini20FlashThinkingExp="gemini-2.0-flash-thinking-exp-01-21",A.Gemini1Pro="gemini-1.0-pro",A.Gemini15Flash="gemini-1.5-flash",A.Gemini15Flash002="gemini-1.5-flash-002",A.Gemini15Flash8B="gemini-1.5-flash-8b",A.Gemini15Pro="gemini-1.5-pro",A.GeminiFlashLatest="gemini-flash-latest",A.GeminiFlashLiteLatest="gemini-flash-lite-latest",A.GeminiProLatest="gemini-pro-latest",A))(Yn||{}),Jr=(o=>(o.GeminiEmbedding001="gemini-embedding-001",o.GeminiEmbedding="gemini-embedding-exp",o.TextEmbeddingLarge="text-embedding-large-exp-03-07",o.TextEmbedding004="text-embedding-004",o.TextEmbedding005="text-embedding-005",o))(Jr||{}),Yr=(r=>(r.HarmCategoryHarassment="HARM_CATEGORY_HARASSMENT",r.HarmCategoryHateSpeech="HARM_CATEGORY_HATE_SPEECH",r.HarmCategorySexuallyExplicit="HARM_CATEGORY_SEXUALLY_EXPLICIT",r.HarmCategoryDangerousContent="HARM_CATEGORY_DANGEROUS_CONTENT",r))(Yr||{}),Qr=(o=>(o.BlockNone="BLOCK_NONE",o.BlockOnlyHigh="BLOCK_ONLY_HIGH",o.BlockMediumAndAbove="BLOCK_MEDIUM_AND_ABOVE",o.BlockLowAndAbove="BLOCK_LOW_AND_ABOVE",o.BlockDefault="HARM_BLOCK_THRESHOLD_UNSPECIFIED",o))(Qr||{}),Ds=(l=>(l.SemanticSimilarity="SEMANTIC_SIMILARITY",l.Classification="CLASSIFICATION",l.Clustering="CLUSTERING",l.RetrievalDocument="RETRIEVAL_DOCUMENT",l.RetrievalQuery="RETRIEVAL_QUERY",l.QuestionAnswering="QUESTION_ANSWERING",l.FactVerification="FACT_VERIFICATION",l.CodeRetrievalQuery="CODE_RETRIEVAL_QUERY",l))(Ds||{});var Zr=[{name:"gemini-3-flash-preview",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.5,completionTokenCostPer1M:3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-3-pro-preview",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2,completionTokenCostPer1M:12,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-3-pro-image-preview",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2,completionTokenCostPer1M:.134,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.5-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2.5,completionTokenCostPer1M:15,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.0-pro-exp-02-05",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.0-flash-thinking-exp-01-21",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.5-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:15,completionTokenCostPer1M:3.5,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.5-flash-lite",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.1,completionTokenCostPer1M:.4,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.0-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.01,completionTokenCostPer1M:.4,supported:{structuredOutputs:!0}},{name:"gemini-2.0-flash-lite",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0,supported:{structuredOutputs:!0}},{name:"gemini-1.5-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.075,completionTokenCostPer1M:.3,supported:{structuredOutputs:!0}},{name:"gemini-1.5-flash-8b",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.0375,completionTokenCostPer1M:.15,supported:{structuredOutputs:!0}},{name:"gemini-1.5-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:1.25,completionTokenCostPer1M:5,supported:{structuredOutputs:!0}},{name:"gemini-1.0-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5,supported:{structuredOutputs:!0}},{name:"gemini-flash-latest",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.075,completionTokenCostPer1M:.3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-flash-lite-latest",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-pro-latest",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:1.25,completionTokenCostPer1M:5,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}}];var Xr=s=>{if(!s||typeof s!="object")return s;let e={...s};return delete e.additionalProperties,delete e.default,delete e.optional,delete e.maximum,delete e.oneOf,delete e.anyOf,e.properties&&typeof e.properties=="object"&&(e.properties=Object.fromEntries(Object.entries(e.properties).map(([t,n])=>[t,Xr(n)]))),e.items&&(e.items=Xr(e.items)),e},Wa=[{category:"HARM_CATEGORY_HARASSMENT",threshold:"BLOCK_NONE"},{category:"HARM_CATEGORY_HATE_SPEECH",threshold:"BLOCK_NONE"},{category:"HARM_CATEGORY_SEXUALLY_EXPLICIT",threshold:"BLOCK_NONE"},{category:"HARM_CATEGORY_DANGEROUS_CONTENT",threshold:"BLOCK_NONE"}],Gs=()=>structuredClone({model:"gemini-2.5-flash",embedModel:"text-embedding-005",safetySettings:Wa,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},...ie()}),Ja=()=>structuredClone({model:"gemini-2.0-flash",embedModel:"text-embedding-005",safetySettings:Wa,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},...Se()}),Ls=class{constructor(e,t,n,r,o){this.config=e;this.isVertex=t;this.endpointId=n;this.apiKey=r;this.options=o;if(!this.isVertex&&this.config.autoTruncate)throw new Error("Auto truncate is not supported for GoogleGemini")}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,endSequences:e.endSequences,stream:e.stream,n:e.n}}createChatReq=async(e,t)=>{let n=e.model,r=e.modelConfig?.stream??this.config.stream;if(!e.chatPrompt||e.chatPrompt.length===0)throw new Error("Chat prompt is empty");let o;if(this.endpointId?o={name:r?`/${this.endpointId}:streamGenerateContent?alt=sse`:`/${this.endpointId}:generateContent`}:o={name:r?`/models/${n}:streamGenerateContent?alt=sse`:`/models/${n}:generateContent`},!this.isVertex){let x=r?"&":"?",A=typeof this.apiKey=="function"?await this.apiKey():this.apiKey;o.name+=`${x}key=${A}`}let i=e.chatPrompt.filter(x=>x.role==="system").map(x=>x.content),a=i.length>0?{role:"user",parts:[{text:i.join(" ")}]}:void 0,l=[],u=e.chatPrompt.filter(x=>x.role!=="system");for(let x=0;x<u.length;x++){let A=u[x];switch(A.role){case"user":{let y=Array.isArray(A.content)?A.content.map((b,k)=>{switch(b.type){case"text":return{text:b.text};case"image":return{inlineData:{mimeType:b.mimeType,data:b.image}};case"audio":return{inlineData:{mimeType:`audio/${b.format??"mp3"}`,data:b.data}};case"file":return"fileUri"in b?{fileData:{mimeType:b.mimeType,fileUri:b.fileUri}}:{inlineData:{mimeType:b.mimeType,data:b.data}};default:throw new Error(`Chat prompt content type not supported (index: ${k})`)}}):[{text:A.content}];l.push({role:"user",parts:y});break}case"assistant":{let y=[],b=A.thoughtBlocks,k=A.functionCalls&&A.functionCalls.length>0,S=b?.[0],M=b?.map(O=>O.data).join("")??"",R=S?.signature;if(M&&y.push({...k?{}:{thought:!0},text:M,...R&&!k?{thought_signature:R}:{}}),A.functionCalls){let O=A.functionCalls.map((F,P)=>{let I;if(typeof F.function.params=="string"){let T=F.function.params;if(T.trim().length===0)I={};else try{I=JSON.parse(T)}catch{throw new Error(`Failed to parse function params JSON: ${T}`)}}else I=F.function.params;let v={functionCall:{name:F.function.name,args:I}};return R&&P===0&&(v.thought_signature=R),v});y.push(...O)}if(A.content&&y.push({text:A.content}),y.length===0)throw new Error("Assistant content is empty");l.push({role:"model",parts:y});break}case"function":{let y=[],b=A,k=x;for(;;){if(!("functionId"in b))throw new Error(`Chat prompt functionId is empty (index: ${k})`);if(y.push({functionResponse:{name:b.functionId,response:{result:b.result}}}),k+1<u.length&&u[k+1].role==="function")k++,b=u[k];else break}x=k,l.push({role:"user",parts:y});break}default:throw new Error(`Invalid role: ${JSON.stringify(A)} (index: ${x})`)}}let c=[];if(e.functions&&e.functions.length>0){let x=e.functions.map(A=>{let y={type:"object",properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]},b=A.parameters?Xr(A.parameters):void 0;return b===void 0||b&&typeof b=="object"&&Object.keys(b).length===0?b={...y}:b&&typeof b=="object"&&b.type==="object"&&(!("properties"in b)||!b.properties||Object.keys(b.properties).length===0)&&(b={...b,properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]}),{...A,parameters:b}});c.push({function_declarations:x})}if(this.options?.codeExecution&&c.push({code_execution:{}}),this.options?.googleSearchRetrieval&&c.push({google_search_retrieval:{dynamic_retrieval_config:this.options.googleSearchRetrieval}}),this.options?.googleSearch&&c.push({google_search:{}}),this.options?.googleMaps){let x=this.options.googleMaps,A=x?.enableWidget!==void 0?{enableWidget:x.enableWidget}:{};c.push({google_maps:A})}this.options?.urlContext&&c.push({url_context:{}}),c.length===0&&(c=void 0);let p,d=Array.isArray(c)?c.some(x=>x&&Array.isArray(x.function_declarations)&&x.function_declarations.length>0):!1;if(e.functionCall)if(e.functionCall==="none")p={function_calling_config:{mode:"NONE"}};else if(e.functionCall==="auto")p={function_calling_config:{mode:"AUTO"}};else if(e.functionCall==="required")p={function_calling_config:{mode:"ANY"}};else{let x=e.functionCall.function?.name?{allowedFunctionNames:[e.functionCall.function.name]}:{};p={function_calling_config:{mode:"ANY"},...x}}else d&&(p={function_calling_config:{mode:"AUTO"}});this.options?.retrievalConfig&&(p={...p??{},retrievalConfig:{...this.options.retrievalConfig.latLng?{latLng:this.options.retrievalConfig.latLng}:{}}});let m={};if(this.config.thinking?.includeThoughts&&(m.includeThoughts=!0),this.config.thinking?.thinkingTokenBudget&&(m.thinkingBudget=this.config.thinking.thinkingTokenBudget),this.config.thinking?.thinkingLevel&&(m.thinkingLevel=this.config.thinking.thinkingLevel),t?.thinkingTokenBudget){let x=this.config.thinkingTokenBudgetLevels,A=n.includes("gemini-3");switch(t.thinkingTokenBudget){case"none":m.thinkingBudget=0,m.includeThoughts=!1,delete m.thinkingLevel;break;case"minimal":m.thinkingBudget=x?.minimal??200,A&&(m.thinkingLevel="low");break;case"low":m.thinkingBudget=x?.low??800,A&&(m.thinkingLevel="low");break;case"medium":m.thinkingBudget=x?.medium??5e3,A&&(m.thinkingLevel="high");break;case"high":m.thinkingBudget=x?.high??1e4,A&&(m.thinkingLevel="high");break;case"highest":m.thinkingBudget=x?.highest??24500,A&&(m.thinkingLevel="high");break}}m.thinkingLevel&&delete m.thinkingBudget,t?.showThoughts!==void 0&&t?.thinkingTokenBudget!=="none"&&(m.includeThoughts=t.showThoughts);let g={maxOutputTokens:e.modelConfig?.maxTokens??this.config.maxTokens,...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{topP:e.modelConfig.topP}:{},topK:e.modelConfig?.topK??this.config.topK,frequencyPenalty:e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,candidateCount:1,stopSequences:e.modelConfig?.stopSequences??this.config.stopSequences,responseMimeType:"text/plain",...Object.keys(m).length>0?{thinkingConfig:m}:{}};if(e.responseFormat){if(g.responseMimeType="application/json",e.responseFormat.type==="json_schema"&&e.responseFormat.schema){let x=e.responseFormat.schema.schema||e.responseFormat.schema;g.responseSchema=Xr(x)}}else this.config.responseFormat&&this.config.responseFormat==="json_object"&&(g.responseMimeType="application/json");let f=this.config.safetySettings;return[o,{contents:l,tools:c,toolConfig:p,systemInstruction:a,generationConfig:g,safetySettings:f}]};createEmbedReq=async e=>{let t=e.embedModel;if(!t)throw new Error("Embed model not set");if(!e.texts||e.texts.length===0)throw new Error("Embed texts is empty");let n,r;if(this.isVertex)this.endpointId?n={name:`/${this.endpointId}:predict`}:n={name:`/models/${t}:predict`},r={instances:e.texts.map(o=>({content:o,...this.config.embedType&&{taskType:this.config.embedType}})),parameters:{autoTruncate:this.config.autoTruncate,outputDimensionality:this.config.dimensions}};else{let o=typeof this.apiKey=="function"?this.apiKey():this.apiKey;n={name:`/models/${t}:batchEmbedContents?key=${o}`},r={requests:e.texts.map(i=>({model:`models/${t}`,content:{parts:[{text:i}]},outputDimensionality:this.config.dimensions,...this.config.embedType&&{taskType:this.config.embedType}}))}}return[n,r]};createChatResp=e=>{let t,n=e.candidates?.map(o=>{let i={index:0};switch(o.finishReason){case"MAX_TOKENS":i.finishReason="length";break;case"STOP":i.finishReason="stop";break;case"SAFETY":throw new fe("Content was blocked due to safety settings",void 0,void 0);case"RECITATION":throw new fe("Content was blocked due to recitation policy",void 0,void 0);case"MALFORMED_FUNCTION_CALL":throw new fe("Function call was malformed and blocked",void 0,void 0);case"UNEXPECTED_TOOL_CALL":throw new fe("Unexpected tool call",void 0,void 0);case"FINISH_REASON_UNSPECIFIED":throw new fe("Finish reason unspecified",void 0,void 0);case"BLOCKLIST":throw new fe("Content was blocked due to blocklist",void 0,void 0);case"PROHIBITED_CONTENT":throw new fe("Content was blocked due to prohibited content",void 0,void 0);case"SPII":throw new fe("Content was blocked due to SPII",void 0,void 0);case"OTHER":throw new fe("Other finish reason",void 0,void 0)}if(!o.content||!o.content.parts)return i;for(let u of o.content.parts){if("text"in u){if("thought"in u&&u.thought||u.thought===!0){i.thought=u.text;let c=u.thoughtSignature||u.thought_signature;i.thoughtBlocks||(i.thoughtBlocks=[]),i.thoughtBlocks.push({data:u.text,encrypted:!1,...c?{signature:c}:{}})}else i.content=u.text;continue}if("functionCall"in u){let c=u.thoughtSignature||u.thought_signature;if(c)if(!i.thoughtBlocks||i.thoughtBlocks.length===0)i.thoughtBlocks=[{data:"",encrypted:!1,signature:c}];else{let p=i.thoughtBlocks[i.thoughtBlocks.length-1];p&&!p.signature&&(p.signature=c)}i.functionCalls=[...i.functionCalls??[],{id:Pe(),type:"function",function:{name:u.functionCall.name,params:u.functionCall.args}}]}}let a=o.citationMetadata?.citations;if(Array.isArray(a)&&a.length){let u=c=>c?`${c.year}-${String(c.month).padStart(2,"0")}-${String(c.day).padStart(2,"0")}`:void 0;i.citations=a.filter(c=>typeof c?.uri=="string").map(c=>({url:c.uri,title:c.title,license:c.license,publicationDate:u(c.publicationDate)}))}let l=o.groundingMetadata;if(l){if(Array.isArray(l.groundingChunks)){let u=l.groundingChunks.map(c=>c?.maps).filter(c=>c&&typeof c.uri=="string").map(c=>({url:c.uri,title:c.title}));u.length&&(i.citations=[...i.citations??[],...u])}typeof l.googleMapsWidgetContextToken=="string"&&(t=l.googleMapsWidgetContextToken)}return i});e.usageMetadata&&(this.tokensUsed={totalTokens:e.usageMetadata.totalTokenCount,promptTokens:e.usageMetadata.promptTokenCount,completionTokens:e.usageMetadata.candidatesTokenCount,thoughtsTokens:e.usageMetadata.thoughtsTokenCount});let r={results:n};return t&&(r.providerMetadata={...r.providerMetadata,google:{...r.providerMetadata?.google??{},mapsWidgetContextToken:t}}),r};createChatStreamResp=e=>this.createChatResp(e);createEmbedResp=e=>{let t;return this.isVertex?t=e.predictions.map(n=>n.embeddings.values):t=e.embeddings.map(n=>n.values),{embeddings:t}}},en=class s extends we{static create(e){return new s(e)}constructor({apiKey:e,projectId:t,region:n,endpointId:r,config:o,options:i,models:a,modelInfo:l}){let u=t!==void 0&&n!==void 0,c,p;if(u){if(!e)throw new Error("GoogleGemini Vertex API key not set");if(typeof e!="function")throw new Error("GoogleGemini Vertex API key must be a function for token-based authentication");let h;r?h="endpoints":h="publishers/google",c=`https://${n==="global"?"aiplatform":`${n}-aiplatform`}.googleapis.com/v1/projects/${t}/locations/${n}/${h}`,p=async()=>({Authorization:`Bearer ${typeof e=="function"?await e():e}`})}else{if(!e)throw new Error("GoogleGemini AI API key not set");c="https://generativelanguage.googleapis.com/v1beta",p=async()=>({})}let d={...Gs(),...o},m=new Ls(d,u,r,e,i);l=[...Zr,...l??[]];let g=h=>{let x=We({model:h,modelInfo:l,models:a});return{functions:!0,streaming:!0,hasThinkingBudget:x?.supported?.thinkingBudget??!1,hasShowThoughts:x?.supported?.showThoughts??!1,structuredOutputs:x?.supported?.structuredOutputs??!1,media:{images:{supported:!0,formats:["image/jpeg","image/png","image/gif","image/webp"],maxSize:20*1024*1024,detailLevels:["high","low","auto"]},audio:{supported:!0,formats:["wav","mp3","aac","ogg"],maxDuration:9.5*60},files:{supported:!0,formats:["application/pdf","text/plain","text/csv","text/html","text/xml"],maxSize:2*1024*1024*1024,uploadMethod:"cloud"},urls:{supported:!0,webSearch:!0,contextFetching:!0}},caching:{supported:!1,types:[]},thinking:x?.supported?.thinkingBudget??!1,multiTurn:!0}},f=a?.map(h=>{let x=h,A=x?.config;if(!A)return h;let y={};A.maxTokens!==void 0&&(y.maxTokens=A.maxTokens),A.temperature!==void 0&&(y.temperature=A.temperature),A.topP!==void 0&&(y.topP=A.topP),A.topK!==void 0&&(y.topK=A.topK),A.presencePenalty!==void 0&&(y.presencePenalty=A.presencePenalty),A.frequencyPenalty!==void 0&&(y.frequencyPenalty=A.frequencyPenalty),A.stopSequences!==void 0&&(y.stopSequences=A.stopSequences),A.endSequences!==void 0&&(y.endSequences=A.endSequences),A.stream!==void 0&&(y.stream=A.stream),A.n!==void 0&&(y.n=A.n);let b={...x};Object.keys(y).length>0&&(b.modelConfig={...x.modelConfig??{},...y});let k=A.thinking?.thinkingTokenBudget;if(typeof k=="number"){let S=d.thinkingTokenBudgetLevels,M=[["minimal",S?.minimal??200],["low",S?.low??800],["medium",S?.medium??5e3],["high",S?.high??1e4],["highest",S?.highest??24500]],R="minimal",O=Number.POSITIVE_INFINITY;for(let[F,P]of M){let I=Math.abs(k-P);I<O&&(O=I,R=F)}b.thinkingTokenBudget=R}return A.thinking?.includeThoughts!==void 0&&(b.showThoughts=!!A.thinking.includeThoughts),b});super(m,{name:"GoogleGeminiAI",apiURL:c,headers:p,modelInfo:l,defaults:{model:d.model,embedModel:d.embedModel},options:i,supportFor:g,models:f??a})}};var Fc=new Ge,tn=class{options;maxTokens;refillRate;currentTokens;lastRefillTime;constructor(e,t,n){this.maxTokens=e,this.refillRate=t,this.currentTokens=e,this.lastRefillTime=Date.now(),this.options=n}refillTokens(){let e=Date.now(),n=(e-this.lastRefillTime)/1e3*this.refillRate;this.currentTokens=Math.min(this.maxTokens,this.currentTokens+n),this.lastRefillTime=e}async waitUntilTokensAvailable(e){if(this.refillTokens(),this.currentTokens>=e){this.currentTokens-=e;return}return this.options?.debug&&console.log(Fc.red(`Rate limiter: Waiting for ${e-this.currentTokens} tokens`)),await new Promise(t=>setTimeout(t,100)),this.waitUntilTokensAvailable(e)}async acquire(e){await this.waitUntilTokensAvailable(e)}};var Qn=(r=>(r.Llama3_8B="llama3-8b-8192",r.Llama33_70B="llama-3.3-70b-versatile",r.Mixtral_8x7B="mixtral-8x7b-32768",r.Gemma2_9B="gemma2-9b-it",r))(Qn||{});var eo=[{name:"gemma2-9b-it",currency:"usd",characterIsToken:!0,promptTokenCostPer1M:.2,completionTokenCostPer1M:.2},{name:"llama-3.3-70b-versatile",currency:"usd",characterIsToken:!0,promptTokenCostPer1M:.59,completionTokenCostPer1M:.79},{name:"llama3-8b-8192",currency:"usd",characterIsToken:!0,promptTokenCostPer1M:.05,completionTokenCostPer1M:.08},{name:"mixtral-8x7b-32768",currency:"usd",characterIsToken:!0,promptTokenCostPer1M:.24,completionTokenCostPer1M:.24}];var _c=()=>structuredClone({model:"llama-3.3-70b-versatile",...ie()}),nn=class extends Te{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("Groq API key not set");let i={..._c(),...t},a={...n,streamingUsage:!1};o=[...eo,...o??[]];let l={functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0};super({apiKey:e,config:i,options:a,modelInfo:o,apiURL:"https://api.groq.com/openai/v1",models:r,supportFor:l}),super.setName("Groq"),this.setOptions(a)}setOptions=e=>{let t=this.newRateLimiter(e);super.setOptions({...e,rateLimiter:t})};newRateLimiter=e=>{if(e?.rateLimiter)return e.rateLimiter;let t=e?.tokensPerMinute??4800,n=new tn(t,t/60,{debug:e?.debug});return async(o,i)=>{let a=i.modelUsage?.tokens?.totalTokens||0;return await n.acquire(a),await o()}}};var to=[];var no=(e=>(e.MetaLlama270BChatHF="meta-llama/Llama-2-70b-chat-hf",e))(no||{});var Bs=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...ie()}),Ya=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...Se()}),Us=class{constructor(e){this.config=e}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,n:e.n,presencePenalty:e.presencePenalty}}createChatReq=e=>{let t=e.model,n=e.functions?`Functions:
167
+ `;break}default:r=JSON.stringify(n,null,2)}i(r)}};var J={LLM_SYSTEM:"gen_ai.system",LLM_OPERATION_NAME:"gen_ai.operation.name",LLM_REQUEST_MODEL:"gen_ai.request.model",LLM_REQUEST_MAX_TOKENS:"gen_ai.request.max_tokens",LLM_REQUEST_TEMPERATURE:"gen_ai.request.temperature",LLM_REQUEST_TOP_K:"gen_ai.request.top_k",LLM_REQUEST_FREQUENCY_PENALTY:"gen_ai.request.frequency_penalty",LLM_REQUEST_PRESENCE_PENALTY:"gen_ai.request.presence_penalty",LLM_REQUEST_STOP_SEQUENCES:"gen_ai.request.stop_sequences",LLM_REQUEST_LLM_IS_STREAMING:"gen_ai.request.llm_is_streaming",LLM_REQUEST_TOP_P:"gen_ai.request.top_p",LLM_USAGE_INPUT_TOKENS:"gen_ai.usage.input_tokens",LLM_USAGE_OUTPUT_TOKENS:"gen_ai.usage.output_tokens",LLM_USAGE_TOTAL_TOKENS:"gen_ai.usage.total_tokens",LLM_USAGE_THOUGHTS_TOKENS:"gen_ai.usage.thoughts_tokens",DB_SYSTEM:"db.system",DB_TABLE:"db.table",DB_NAMESPACE:"db.namespace",DB_ID:"db.id",DB_QUERY_TEXT:"db.query.text",DB_VECTOR:"db.vector",DB_OPERATION_NAME:"db.operation.name",DB_VECTOR_QUERY_TOP_K:"db.vector.query.top_k",DB_QUERY_EMBEDDINGS:"db.query.embeddings",DB_QUERY_RESULT:"db.query.result",DB_QUERY_EMBEDDINGS_VECTOR:"db.query.embeddings.vector",DB_QUERY_RESULT_ID:"db.query.result.id",DB_QUERY_RESULT_SCORE:"db.query.result.score",DB_QUERY_RESULT_DISTANCE:"db.query.result.distance",DB_QUERY_RESULT_METADATA:"db.query.result.metadata",DB_QUERY_RESULT_VECTOR:"db.query.result.vector",DB_QUERY_RESULT_DOCUMENT:"db.query.result.document"},it={GEN_AI_USER_MESSAGE:"gen_ai.user.message",GEN_AI_SYSTEM_MESSAGE:"gen_ai.system.message",GEN_AI_ASSISTANT_MESSAGE:"gen_ai.assistant.message",GEN_AI_TOOL_MESSAGE:"gen_ai.tool.message",GEN_AI_CHOICE:"gen_ai.choice",GEN_AI_USAGE:"gen_ai.usage"},Ts=(r=>(r.COMPLETION="completion",r.CHAT="chat",r.RERANK="rerank",r.UNKNOWN="unknown",r))(Ts||{}),Cs=(o=>(o.WORKFLOW="workflow",o.TASK="task",o.AGENT="agent",o.TOOL="tool",o.UNKNOWN="unknown",o))(Cs||{});var ws=class{buffer;doneCallback;transformFn;constructor(e,t){this.transformFn=e,this.doneCallback=t,this.buffer=t?[]:void 0}async transform(e,t){let n=this.transformFn(e);n&&(t.enqueue(n),this.buffer?.push(n))}async flush(e){await this.doneCallback?.(this.buffer??[]),e.terminate()}},Dr=class extends TransformStream{constructor(e,t){super(new ws(e,t))}};function Gr(i,e){for(let t of e){let n=i.find(r=>r.id===t.id);n?(typeof t.function.name=="string"&&t.function.name.length>0&&(n.function.name+=t.function.name),typeof t.function.params=="string"&&t.function.params.length>0&&(n.function.params+=t.function.params),typeof t.function.params=="object"&&(n.function.params=t.function.params)):i.push(t)}}var ca=(i,e,t,n)=>{let r=n?i.filter(s=>s.role!=="system"):[...i];t({name:"ChatRequestChatPrompt",step:e,value:r})};var pa=(i,e)=>{if(!i.results)return;let t={name:"ChatResponseResults",value:i.results};e(t)};function da(i,e){let t=new Map;for(let n of i)for(let r of n.results){if(!r)continue;let o=t.get(r.index);o?(r.content&&(o.content=(o.content??"")+r.content),r.thought&&(o.thought=(o.thought??"")+r.thought),r.finishReason&&(o.finishReason=r.finishReason),r.functionCalls&&(o.functionCalls?Gr(o.functionCalls,structuredClone(r.functionCalls)):o.functionCalls=structuredClone(r.functionCalls))):(o=structuredClone(r),t.set(r.index,o))}for(let n of t.values()){let r={name:"ChatResponseStreamingDoneResult",index:n.index,value:n};e(r)}}var ma=(i,e)=>{e({name:"FunctionResults",value:i})},Rs=(i,e,t,n)=>{n({name:"FunctionError",index:e,fixingInstructions:t,error:i})},ga=(i,e,t,n)=>{n({name:"ValidationError",index:e,fixingInstructions:t,error:i})},ha=(i,e,t,n)=>{n({name:"AssertionError",index:e,fixingInstructions:t,error:i})},fa=(i,e,t)=>{t({name:"RefusalError",index:e,error:i})};var xa=(i,e,t)=>{t({name:"EmbedRequest",embedModel:e,value:i})},Aa=(i,e)=>{let t=i.slice(0,3).map(r=>({length:r.length,sample:r.slice(0,5),truncated:r.length>5})),n={name:"EmbedResponse",totalEmbeddings:i.length,value:t};e(n)},ya=(i,e,t,n)=>{n({name:"ResultPickerUsed",sampleCount:i,selectedIndex:e,latency:t})};var vs=i=>{let e={};for(let[t,n]of Object.entries(i))if(n!=null){let r=String(n);e[t]=r.length>100?r.substring(0,100):r}return e},Lr,ba=i=>{if(Lr)return Lr;if(i)return Lr=wc(i),Lr};var wc=i=>({latencyHistogram:i.createHistogram("ax_llm_request_duration_ms",{description:"Duration of LLM requests in milliseconds",unit:"ms"}),errorCounter:i.createCounter("ax_llm_errors_total",{description:"Total number of LLM request errors"}),requestCounter:i.createCounter("ax_llm_requests_total",{description:"Total number of LLM requests"}),tokenCounter:i.createCounter("ax_llm_tokens_total",{description:"Total number of LLM tokens consumed"}),inputTokenCounter:i.createCounter("ax_llm_input_tokens_total",{description:"Total number of input/prompt tokens consumed"}),outputTokenCounter:i.createCounter("ax_llm_output_tokens_total",{description:"Total number of output/completion tokens generated"}),errorRateGauge:i.createGauge("ax_llm_error_rate",{description:"Current error rate as a percentage (0-100)"}),meanLatencyGauge:i.createGauge("ax_llm_mean_latency_ms",{description:"Mean latency of LLM requests in milliseconds",unit:"ms"}),p95LatencyGauge:i.createGauge("ax_llm_p95_latency_ms",{description:"95th percentile latency of LLM requests in milliseconds",unit:"ms"}),p99LatencyGauge:i.createGauge("ax_llm_p99_latency_ms",{description:"99th percentile latency of LLM requests in milliseconds",unit:"ms"}),streamingRequestsCounter:i.createCounter("ax_llm_streaming_requests_total",{description:"Total number of streaming LLM requests"}),functionCallsCounter:i.createCounter("ax_llm_function_calls_total",{description:"Total number of function/tool calls made"}),functionCallLatencyHistogram:i.createHistogram("ax_llm_function_call_latency_ms",{description:"Latency of function calls in milliseconds",unit:"ms"}),requestSizeHistogram:i.createHistogram("ax_llm_request_size_bytes",{description:"Size of LLM request payloads in bytes",unit:"By"}),responseSizeHistogram:i.createHistogram("ax_llm_response_size_bytes",{description:"Size of LLM response payloads in bytes",unit:"By"}),temperatureGauge:i.createGauge("ax_llm_temperature_gauge",{description:"Temperature setting used for LLM requests"}),maxTokensGauge:i.createGauge("ax_llm_max_tokens_gauge",{description:"Maximum tokens setting used for LLM requests"}),estimatedCostCounter:i.createCounter("ax_llm_estimated_cost_total",{description:"Estimated cost of LLM requests in USD",unit:"$"}),promptLengthHistogram:i.createHistogram("ax_llm_prompt_length_chars",{description:"Length of prompts in characters"}),contextWindowUsageGauge:i.createGauge("ax_llm_context_window_usage_ratio",{description:"Context window utilization ratio (0-1)"}),timeoutsCounter:i.createCounter("ax_llm_timeouts_total",{description:"Total number of timed out LLM requests"}),abortsCounter:i.createCounter("ax_llm_aborts_total",{description:"Total number of aborted LLM requests"}),thinkingBudgetUsageCounter:i.createCounter("ax_llm_thinking_budget_usage_total",{description:"Total thinking budget tokens used"}),multimodalRequestsCounter:i.createCounter("ax_llm_multimodal_requests_total",{description:"Total number of multimodal requests (with images/audio)"})}),Ia=(i,e,t,n,r)=>{try{if(i.latencyHistogram){let o=vs({operation:e,ai_service:n,...r?{model:r}:{}});i.latencyHistogram.record(t,o)}}catch(o){console.warn("Failed to record latency metric:",o)}},Ta=(i,e,t,n,r,o,s)=>{let a={operation:e,ai_service:o,...s?{model:s}:{}};i.meanLatencyGauge&&i.meanLatencyGauge.record(t,a),i.p95LatencyGauge&&i.p95LatencyGauge.record(n,a),i.p99LatencyGauge&&i.p99LatencyGauge.record(r,a)},Ca=(i,e,t,n)=>{try{if(i.errorCounter){let r=vs({operation:e,ai_service:t,...n?{model:n}:{}});i.errorCounter.add(1,r)}}catch(r){console.warn("Failed to record error metric:",r)}},wa=(i,e,t,n,r)=>{i.errorRateGauge&&i.errorRateGauge.record(t*100,{operation:e,ai_service:n,...r?{model:r}:{}})},Ra=(i,e,t,n)=>{i.requestCounter&&i.requestCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{}})},jn=(i,e,t,n,r)=>{try{let o=vs({ai_service:n,...r?{model:r}:{}});i.tokenCounter&&i.tokenCounter.add(t,{token_type:e,...o}),e==="input"&&i.inputTokenCounter&&i.inputTokenCounter.add(t,o),e==="output"&&i.outputTokenCounter&&i.outputTokenCounter.add(t,o)}catch(o){console.warn("Failed to record token metric:",o)}},va=(i,e,t,n,r)=>{t&&i.streamingRequestsCounter&&i.streamingRequestsCounter.add(1,{operation:e,ai_service:n,...r?{model:r}:{}})},Sa=(i,e,t,n,r)=>{let o={function_name:e,...n?{ai_service:n}:{},...r?{model:r}:{}};i.functionCallsCounter&&i.functionCallsCounter.add(1,o),t&&i.functionCallLatencyHistogram&&i.functionCallLatencyHistogram.record(t,o)},Ss=(i,e,t,n,r)=>{i.requestSizeHistogram&&i.requestSizeHistogram.record(t,{operation:e,ai_service:n,...r?{model:r}:{}})},Os=(i,e,t,n,r)=>{i.responseSizeHistogram&&i.responseSizeHistogram.record(t,{operation:e,ai_service:n,...r?{model:r}:{}})},Oa=(i,e,t,n,r)=>{let o={...n?{ai_service:n}:{},...r?{model:r}:{}};e!==void 0&&i.temperatureGauge&&i.temperatureGauge.record(e,o),t!==void 0&&i.maxTokensGauge&&i.maxTokensGauge.record(t,o)},ks=(i,e,t,n,r)=>{i.estimatedCostCounter&&i.estimatedCostCounter.add(t,{operation:e,ai_service:n,...r?{model:r}:{}})},ka=(i,e,t,n)=>{i.promptLengthHistogram&&i.promptLengthHistogram.record(e,{ai_service:t,...n?{model:n}:{}})},Ma=(i,e,t,n)=>{i.contextWindowUsageGauge&&i.contextWindowUsageGauge.record(e,{ai_service:t,...n?{model:n}:{}})},Ea=(i,e,t,n)=>{i.timeoutsCounter&&i.timeoutsCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{}})},Pa=(i,e,t,n)=>{i.abortsCounter&&i.abortsCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{}})},Fa=(i,e,t,n)=>{i.thinkingBudgetUsageCounter&&i.thinkingBudgetUsageCounter.add(e,{ai_service:t,...n?{model:n}:{}})},_a=(i,e,t,n,r)=>{(e||t)&&i.multimodalRequestsCounter&&i.multimodalRequestsCounter.add(1,{ai_service:n,has_images:e.toString(),has_audio:t.toString(),...r?{model:r}:{}})};function $a(i){try{return JSON.stringify(i,null,2)}catch{return String(i)}}function at(i,e={}){let t=[i];throw e.fieldPath!==void 0&&t.push(`Field: ${e.fieldPath}`),e.value!==void 0&&t.push(`Value: ${$a(e.value)}`),e.note&&t.push(`Note: ${e.note}`),e.item!==void 0&&t.push(`Chat item: ${$a(e.item)}`),new Error(t.join(`
168
+ `))}function Ht(i){let e=n=>JSON.stringify(n,null,2);if(!i)throw new Error(`Chat request message item cannot be null or undefined, received: ${e(i)}`);let t=typeof i=="object"&&i!==null&&"role"in i&&typeof i.role=="string"?i.role:void 0;if(!t)throw new Error(`Chat request message must have a role, received: ${e(t)}`);switch(t){case"system":{let n=typeof i=="object"&&i!==null&&"content"in i&&typeof i.content=="string"?i.content:void 0;if(!n||n.trim()==="")throw new Error(`System message content cannot be empty or whitespace-only, received: ${e(n)}`);break}case"user":{let n=typeof i=="object"&&i!==null&&"content"in i?i.content:void 0;if(n===void 0)throw new Error(`User message content cannot be undefined, received: ${e(n)}`);if(typeof n=="string"){if(n.trim()==="")throw new Error(`User message content cannot be empty or whitespace-only, received: ${e(n)}`)}else if(Array.isArray(n)){if(n.length===0)throw new Error(`User message content array cannot be empty, received: ${e(n)}`);for(let r=0;r<n.length;r++){let o=n[r];if(!o||typeof o!="object")throw new Error(`User message content item at index ${r} must be an object, received: ${e(o)}`);let s=typeof o=="object"&&o!==null&&"type"in o&&typeof o.type=="string"?o.type:void 0;if(!s)throw new Error(`User message content item at index ${r} must have a type, received: ${e(s)}`);switch(s){case"text":{let a="text"in o&&typeof o.text=="string"?o.text:void 0;if(!a||a.trim()==="")throw new Error(`User message text content at index ${r} cannot be empty or whitespace-only, received: ${e(a)}`);break}case"image":{let a="image"in o&&typeof o.image=="string"?o.image:void 0,l="mimeType"in o&&typeof o.mimeType=="string"?o.mimeType:void 0;if(!a||a.trim()==="")throw new Error(`User message image content at index ${r} cannot be empty, received: ${e(a)}`);if(!l||l.trim()==="")throw new Error(`User message image content at index ${r} must have a mimeType, received: ${e(l)}`);break}case"audio":{let a="data"in o&&typeof o.data=="string"?o.data:void 0;if(!a||a.trim()==="")throw new Error(`User message audio content at index ${r} cannot be empty, received: ${e(a)}`);break}case"file":{let a="fileUri"in o&&typeof o.fileUri=="string",l="data"in o&&typeof o.data=="string";if(!a&&!l)throw new Error(`User message file content at index ${r} must have either 'data' or 'fileUri', received: ${e(o)}`);if(a&&l)throw new Error(`User message file content at index ${r} cannot have both 'data' and 'fileUri', received: ${e(o)}`);if(a){let c=o.fileUri;if(!c||c.trim()==="")throw new Error(`User message file content at index ${r} fileUri cannot be empty, received: ${e(c)}`)}if(l){let c=o.data;if(!c||c.trim()==="")throw new Error(`User message file content at index ${r} data cannot be empty, received: ${e(c)}`)}let u="mimeType"in o&&typeof o.mimeType=="string"?o.mimeType:null;if(!u||u.trim()==="")throw new Error(`User message file content at index ${r} must have a mimeType, received: ${e(u)}`);break}case"url":{let a="url"in o&&typeof o.url=="string"?o.url:void 0;if(!a||a.trim()==="")throw new Error(`User message url content at index ${r} cannot be empty, received: ${e(a)}`);break}default:throw new Error(`User message content item at index ${r} has unsupported type: ${e(s)}`)}}}else throw new Error(`User message content must be a string or array of content objects, received: ${e(n)}`);break}case"assistant":{let n=typeof i=="object"&&i!==null&&"content"in i?i.content:void 0,r=typeof i=="object"&&i!==null&&"functionCalls"in i?i.functionCalls:void 0,o=typeof i=="object"&&i!==null&&"thoughtBlocks"in i?i.thoughtBlocks:void 0,s=typeof n=="string"&&n.trim()!=="",a=Array.isArray(r)&&r.length>0,l=Array.isArray(o)&&o.length>0;if(!s&&!a&&!l&&at("Assistant message must include non-empty content, at least one function call, or thought blocks",{fieldPath:"content | functionCalls | thoughtBlocks",value:{content:n,functionCalls:r,thoughtBlocks:o},item:i}),n!==void 0&&typeof n!="string"&&at("Assistant message content must be a string",{fieldPath:"content",value:n,item:i}),r!==void 0&&!Array.isArray(r)&&at("Assistant message functionCalls must be an array when provided",{fieldPath:"functionCalls",value:r,item:i}),Array.isArray(r))for(let u=0;u<r.length;u++){let c=r[u];if((!c||typeof c!="object")&&at("functionCalls entry must be an object",{fieldPath:`functionCalls[${u}]`,value:c,item:i}),(!("id"in c)||typeof c.id!="string"||c.id.trim()==="")&&at("functionCalls entry must include a non-empty string id",{fieldPath:`functionCalls[${u}].id`,value:c.id,item:i}),(!("type"in c)||c.type!=="function")&&at("functionCalls entry must have type 'function'",{fieldPath:`functionCalls[${u}].type`,value:c.type,item:i}),!("function"in c)||!c.function)at("functionCalls entry must include a function object",{fieldPath:`functionCalls[${u}].function`,value:c.function,item:i});else{let p=c.function;(!("name"in p)||typeof p.name!="string"||p.name.trim()==="")&&at("functionCalls entry must include a non-empty function name",{fieldPath:`functionCalls[${u}].function.name`,value:p?.name,item:i}),p.params!==void 0&&typeof p.params!="string"&&typeof p.params!="object"&&at("functionCalls entry params must be a string or object when provided",{fieldPath:`functionCalls[${u}].function.params`,value:p.params,item:i})}}if(i.name!==void 0){let u=i.name;(typeof u!="string"||u.trim()==="")&&at("Assistant message name must be a non-empty string when provided",{fieldPath:"name",value:u,item:i})}break}case"function":{let n=typeof i=="object"&&i!==null&&"functionId"in i&&typeof i.functionId=="string"?i.functionId:void 0,r=typeof i=="object"&&i!==null&&"result"in i?i.result:void 0;if(!n||n.trim()==="")throw new Error(`Function message must have a non-empty functionId, received: ${e(n)}`);if(r==null)throw new Error(`Function message must have a result, received: ${e(r)}`);if(typeof r!="string")throw new Error(`Function message result must be a string, received: ${e(r)}`);i.isError!==void 0&&typeof i.isError!="boolean"&&at("Function message isError must be a boolean when provided",{fieldPath:"isError",value:i.isError,item:i});break}default:throw new Error(`Unsupported message role: ${e(t)}`)}}function Ur(i){let e=n=>JSON.stringify(n,null,2),t=Array.isArray(i)?i:[i];if(t.length===0)throw new Error(`Chat response results cannot be empty, received: ${e(t)}`);for(let n=0;n<t.length;n++){let r=t[n];if(!r)throw new Error(`Chat response result at index ${n} cannot be null or undefined, received: ${e(r)}`);if(typeof r.index!="number")throw new Error(`Chat response result at index ${n} must have a numeric index, received: ${e(r.index)}`);if(r.index<0)throw new Error(`Chat response result at index ${n} must have a non-negative index, received: ${e(r.index)}`);if(!r.content&&!r.thought&&(!r.thoughtBlocks||r.thoughtBlocks.length===0)&&!r.functionCalls&&!r.finishReason)throw new Error(`Chat response result at index ${n} must have at least one of: content, thought, thoughtBlocks, functionCalls, or finishReason, received: ${e({content:r.content,thought:r.thought,thoughtBlocks:r.thoughtBlocks,functionCalls:r.functionCalls,finishReason:r.finishReason})}`);if(r.content!==void 0&&typeof r.content!="string")throw new Error(`Chat response result content at index ${n} must be a string, received: ${e(r.content)}`);if(r.thought!==void 0&&typeof r.thought!="string")throw new Error(`Chat response result thought at index ${n} must be a string, received: ${e(r.thought)}`);if(r.thoughtBlocks!==void 0){if(!Array.isArray(r.thoughtBlocks))throw new Error(`Chat response result thoughtBlocks at index ${n} must be an array, received: ${e(r.thoughtBlocks)}`);for(let o=0;o<r.thoughtBlocks.length;o++){let s=r.thoughtBlocks[o];if(typeof s!="object"||s===null)throw new Error(`Chat response result thoughtBlocks[${o}] at index ${n} must be an object, received: ${e(s)}`);if(typeof s.data!="string")throw new Error(`Chat response result thoughtBlocks[${o}].data at index ${n} must be a string, received: ${e(s.data)}`);if(typeof s.encrypted!="boolean")throw new Error(`Chat response result thoughtBlocks[${o}].encrypted at index ${n} must be a boolean, received: ${e(s.encrypted)}`);if(s.signature!==void 0&&typeof s.signature!="string")throw new Error(`Chat response result thoughtBlocks[${o}].signature at index ${n} must be a string when provided, received: ${e(s.signature)}`)}}if(r.name!==void 0){if(typeof r.name!="string")throw new Error(`Chat response result name at index ${n} must be a string, received: ${e(r.name)}`);if(r.name.trim()==="")throw new Error(`Chat response result name at index ${n} cannot be empty or whitespace-only, received: ${e(r.name)}`)}if(r.annotations!==void 0){if(!Array.isArray(r.annotations))throw new Error(`Chat response result annotations at index ${n} must be an array, received: ${e(r.annotations)}`);for(let o=0;o<r.annotations.length;o++){let s=r.annotations[o];if(!s||typeof s!="object")throw new Error(`Chat response result annotation at index ${n}[${o}] must be an object, received: ${e(s)}`);if(s.type!=="url_citation")throw new Error(`Chat response result annotation at index ${n}[${o}] must have type 'url_citation', received: ${e(s.type)}`);if(!s.url_citation||typeof s.url_citation!="object")throw new Error(`Chat response result annotation at index ${n}[${o}] must have a valid url_citation object, received: ${e(s.url_citation)}`);if(typeof s.url_citation.url!="string")throw new Error(`Chat response result annotation at index ${n}[${o}] url_citation.url must be a string, received: ${e(s.url_citation.url)}`)}}if(r.id!==void 0){if(typeof r.id!="string")throw new Error(`Chat response result id at index ${n} must be a string, received: ${e(r.id)}`);if(r.id.trim()==="")throw new Error(`Chat response result id at index ${n} cannot be empty or whitespace-only, received: ${e(r.id)}`)}if(r.functionCalls!==void 0){if(!Array.isArray(r.functionCalls))throw new Error(`Chat response result functionCalls at index ${n} must be an array, received: ${e(r.functionCalls)}`);for(let o=0;o<r.functionCalls.length;o++){let s=r.functionCalls[o];if(!s)throw new Error(`Function call at index ${o} in result ${n} cannot be null or undefined, received: ${e(s)}`);if(!s.id||typeof s.id!="string"||s.id.trim()==="")throw new Error(`Function call at index ${o} in result ${n} must have a non-empty string id, received: ${e(s.id)}`);if(s.type!=="function")throw new Error(`Function call at index ${o} in result ${n} must have type 'function', received: ${e(s.type)}`);if(!s.function)throw new Error(`Function call at index ${o} in result ${n} must have a function object, received: ${e(s.function)}`);if(!s.function.name||typeof s.function.name!="string"||s.function.name.trim()==="")throw new Error(`Function call at index ${o} in result ${n} must have a non-empty function name, received: ${e(s.function.name)}`);if(s.function.params!==void 0&&typeof s.function.params!="string"&&typeof s.function.params!="object")throw new Error(`Function call params at index ${o} in result ${n} must be a string or object, received: ${e(s.function.params)}`)}}if(r.finishReason!==void 0){let o=["stop","length","function_call","content_filter","error"];if(!o.includes(r.finishReason))throw new Error(`Chat response result finishReason at index ${n} must be one of: ${o.join(", ")}, received: ${e(r.finishReason)}`)}}}var Ms=new Map;function Rc(i){return`${i.providerId}:${i.model}:${i.contentHash}`}function vc(i){let e=De("sha256");for(let t of i){if(t.role==="system"){e.update(`system:${t.content}`);continue}if("cache"in t&&t.cache)if(t.role==="user"){if(typeof t.content=="string")e.update(`user:${t.content}`);else if(Array.isArray(t.content))for(let n of t.content)"cache"in n&&n.cache&&(n.type==="text"?e.update(`text:${n.text}`):n.type==="image"?e.update(`image:${n.mimeType}:${n.image.slice(0,100)}`):n.type==="audio"?e.update(`audio:${n.format}:${n.data.slice(0,100)}`):n.type==="file"&&("fileUri"in n?e.update(`file:${n.mimeType}:${n.fileUri}`):e.update(`file:${n.mimeType}:${n.data.slice(0,100)}`)))}else t.role==="assistant"&&t.content&&e.update(`assistant:${t.content}`)}return e.digest("hex")}var se=()=>structuredClone({temperature:0}),Se=()=>structuredClone({temperature:.4,frequencyPenalty:.2}),we=class{constructor(e,{name:t,apiURL:n,headers:r,modelInfo:o,defaults:s,options:a={},supportFor:l,models:u}){this.aiImpl=e;this.name=t,this.apiURL=n||"",this.headers=r,this.supportFor=l,this.tracer=a.tracer??ee.tracer,this.meter=a.meter??ee.meter,this.modelInfo=o,this.models=u,this.id=Ee();let c=this.getModel(s.model)??s.model,p=this.getEmbedModel(s.embedModel)??s.embedModel;if(this.defaults={model:c,embedModel:p},!s.model||typeof s.model!="string"||s.model==="")throw new Error("No model defined");this.setOptions(a),u&&Sc(u)}#e=!1;#t=!1;rt;fetch;tracer;meter;timeout;excludeContentFromTrace;models;abortSignal;logger=ee.logger??la;corsProxy;retry;modelInfo;modelUsage;embedModelUsage;defaults;lastUsedModelConfig;lastUsedChatModel;lastUsedEmbedModel;apiURL;name;id;headers;supportFor;metrics={latency:{chat:{mean:0,p95:0,p99:0,samples:[]},embed:{mean:0,p95:0,p99:0,samples:[]}},errors:{chat:{count:0,rate:0,total:0},embed:{count:0,rate:0,total:0}}};getMetricsInstruments(){return ba(this.meter)}setName(e){this.name=e}getId(){return this.id}setAPIURL(e){this.apiURL=e}setHeaders(e){this.headers=e}get debug(){return this.#e}setOptions(e){this.#e=e.debug??ee.debug??!1,this.#t=e.verbose??!1,this.rt=e.rateLimiter,this.fetch=e.fetch,this.timeout=e.timeout,this.tracer=e.tracer??ee.tracer,this.meter=e.meter??ee.meter,this.excludeContentFromTrace=e.excludeContentFromTrace,this.abortSignal=e.abortSignal,this.logger=e.logger??ee.logger??this.logger,this.corsProxy=e.corsProxy,this.retry=e.retry}getOptions(){return{debug:this.#e,verbose:this.#t,rateLimiter:this.rt,fetch:this.fetch,tracer:this.tracer,meter:this.meter,timeout:this.timeout,excludeContentFromTrace:this.excludeContentFromTrace,abortSignal:this.abortSignal,logger:this.logger,corsProxy:this.corsProxy,retry:this.retry}}getLogger(){return this.logger}getModelList(){let e=[];for(let t of this.models??[])t.isInternal||("model"in t&&t.model&&e.push({key:t.key,description:t.description,model:t.model}),"embedModel"in t&&t.embedModel&&e.push({key:t.key,description:t.description,embedModel:t.embedModel}));return e}getName(){return this.name}getFeatures(e){return typeof this.supportFor=="function"?this.supportFor(e??this.defaults.model):this.supportFor}getLastUsedChatModel(){return this.lastUsedChatModel}getLastUsedEmbedModel(){return this.lastUsedEmbedModel}getLastUsedModelConfig(){return this.lastUsedModelConfig}calculatePercentile(e,t){if(e.length===0)return 0;let n=[...e].sort((o,s)=>o-s),r=Math.ceil(t/100*n.length)-1;return n[r]??0}updateLatencyMetrics(e,t){let n=this.metrics.latency[e];n.samples.push(t),n.samples.length>1e3&&n.samples.shift(),n.mean=n.samples.reduce((o,s)=>o+s,0)/n.samples.length,n.p95=this.calculatePercentile(n.samples,95),n.p99=this.calculatePercentile(n.samples,99);let r=this.getMetricsInstruments();if(r){let o=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;Ia(r,e,t,this.name,o),Ta(r,e,n.mean,n.p95,n.p99,this.name,o)}}updateErrorMetrics(e,t){let n=this.metrics.errors[e];n.total++,t&&n.count++,n.rate=n.count/n.total;let r=this.getMetricsInstruments();if(r){let o=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;Ra(r,e,this.name,o),t&&Ca(r,e,this.name,o),wa(r,e,n.rate,this.name,o)}}recordTokenUsage(e){let t=this.getMetricsInstruments();if(t&&e?.tokens){let{promptTokens:n,completionTokens:r,totalTokens:o,thoughtsTokens:s}=e.tokens;n&&jn(t,"input",n,this.name,e.model),r&&jn(t,"output",r,this.name,e.model),o&&jn(t,"total",o,this.name,e.model),s&&jn(t,"thoughts",s,this.name,e.model)}}calculateRequestSize(e){try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return 0}}calculateResponseSize(e){try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return 0}}detectMultimodalContent(e){let t=!1,n=!1;if(e.chatPrompt&&Array.isArray(e.chatPrompt)){for(let r of e.chatPrompt)if(r.role==="user"&&Array.isArray(r.content))for(let o of r.content)o.type==="image"?t=!0:o.type==="audio"&&(n=!0)}return{hasImages:t,hasAudio:n}}calculatePromptLength(e){let t=0;if(e.chatPrompt&&Array.isArray(e.chatPrompt))for(let n of e.chatPrompt)if(n.role==="system"||n.role==="assistant")n.content&&(t+=n.content.length);else if(n.role==="user"){if(typeof n.content=="string")t+=n.content.length;else if(Array.isArray(n.content))for(let r of n.content)r.type==="text"&&(t+=r.text.length)}else n.role==="function"&&n.result&&(t+=n.result.length);return t}calculateContextWindowUsage(e,t){if(!t?.tokens?.promptTokens)return 0;let n=this.modelInfo.find(r=>r.name===e);return n?.contextWindow?t.tokens.promptTokens/n.contextWindow:0}estimateCost(e,t){if(!t?.tokens)return 0;let n=this.modelInfo.find(l=>l.name===e);if(!n||!n.promptTokenCostPer1M&&!n.completionTokenCostPer1M)return 0;let{promptTokens:r=0,completionTokens:o=0}=t.tokens,s=n.promptTokenCostPer1M||0,a=n.completionTokenCostPer1M||0;return r*s/1e6+o*a/1e6}estimateCostByName(e,t){if(!t?.tokens)return 0;let n=this.modelInfo.find(l=>l.name===e);if(!n||!n.promptTokenCostPer1M&&!n.completionTokenCostPer1M)return 0;let{promptTokens:r=0,completionTokens:o=0}=t.tokens,s=n.promptTokenCostPer1M||0,a=n.completionTokenCostPer1M||0;return r*s/1e6+o*a/1e6}recordFunctionCallMetrics(e,t){let n=this.getMetricsInstruments();if(!(!n||!e))for(let r of e)r&&typeof r=="object"&&"function"in r&&r.function&&typeof r.function=="object"&&"name"in r.function&&Sa(n,r.function.name,void 0,this.name,t)}recordTimeoutMetric(e){let t=this.getMetricsInstruments();if(t){let n=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;Ea(t,e,this.name,n)}}recordAbortMetric(e){let t=this.getMetricsInstruments();if(t){let n=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;Pa(t,e,this.name,n)}}recordChatMetrics(e,t,n){let r=this.getMetricsInstruments();if(!r)return;let o=this.lastUsedChatModel,s=this.lastUsedModelConfig,a=s?.stream??!1;va(r,"chat",a,this.name,o);let{hasImages:l,hasAudio:u}=this.detectMultimodalContent(e);_a(r,l,u,this.name,o);let c=this.calculatePromptLength(e);ka(r,c,this.name,o),Oa(r,s?.temperature,s?.maxTokens,this.name,o),t?.thinkingTokenBudget&&this.modelUsage?.tokens?.thoughtsTokens&&Fa(r,this.modelUsage.tokens.thoughtsTokens,this.name,o);let p=this.calculateRequestSize(e);if(Ss(r,"chat",p,this.name,o),n&&!a){let d=n,m=this.calculateResponseSize(d);if(Os(r,"chat",m,this.name,o),d.results)for(let f of d.results)f.functionCalls&&this.recordFunctionCallMetrics(f.functionCalls,this.lastUsedChatModel);let g=this.calculateContextWindowUsage(this.lastUsedChatModel,d.modelUsage);g>0&&Ma(r,g,this.name,o);let h=this.estimateCost(this.lastUsedChatModel,d.modelUsage);h>0&&ks(r,"chat",h,this.name,o)}}recordEmbedMetrics(e,t){let n=this.getMetricsInstruments();if(!n)return;let r=this.lastUsedEmbedModel,o=this.calculateRequestSize(e);Ss(n,"embed",o,this.name,r);let s=this.calculateResponseSize(t);Os(n,"embed",s,this.name,r);let a=this.estimateCostByName(r,t.modelUsage);a>0&&ks(n,"embed",a,this.name,r)}getMetrics(){return structuredClone(this.metrics)}async chat(e,t){let n=performance.now(),r=!1,o,s=this.getModelByKey(e.model),a=s?s.thinkingTokenBudget:void 0,l={...s?{thinkingTokenBudget:a,showThoughts:s.showThoughts,stream:s.stream,debug:s.debug,useExpensiveModel:s.useExpensiveModel}:void 0,...Object.fromEntries(Object.entries(t??{}).filter(([,u])=>u!==void 0))};try{return o=await this._chat1(e,l),o}catch(u){throw r=!0,u instanceof Error&&(u.message.includes("timeout")||u.name==="TimeoutError"?this.recordTimeoutMetric("chat"):(u.message.includes("abort")||u.name==="AbortError")&&this.recordAbortMetric("chat")),u}finally{let u=performance.now()-n;this.updateLatencyMetrics("chat",u),this.updateErrorMetrics("chat",r),r||this.recordChatMetrics(e,l,o)}}async _chat1(e,t){let n=this.getModel(e.model)??e.model??this.defaults.model;if(Array.isArray(e.chatPrompt))for(let u of e.chatPrompt)Ht(u);let r=this.getModelByKey(e.model),o={...this.aiImpl.getModelConfig(),...r?r.modelConfig:void 0,...e.modelConfig},s=this.modelInfo.find(u=>u.name===n);if(s?.notSupported?.temperature&&"temperature"in o&&delete o.temperature,s?.notSupported?.topP&&"topP"in o&&delete o.topP,t?.thinkingTokenBudget&&!this.getFeatures(n).hasThinkingBudget)throw new Error(`Model ${n} does not support thinkingTokenBudget.`);if(t?.showThoughts&&!this.getFeatures(n).hasShowThoughts)throw new Error(`Model ${n} does not support showThoughts.`);if(this.modelInfo.find(u=>u.name===n)?.isExpensive&&t?.useExpensiveModel!=="yes")throw new Error(`Model ${n} is marked as expensive and requires explicit confirmation. Set useExpensiveModel: "yes" to proceed.`);return o.stream=(t?.stream!==void 0?t.stream:o.stream)??!0,this.getFeatures(n).streaming||(o.stream=!1),this.tracer?await this.tracer.startActiveSpan("AI Chat Request",{kind:Be.SERVER,attributes:{[J.LLM_SYSTEM]:this.name,[J.LLM_OPERATION_NAME]:"chat",[J.LLM_REQUEST_MODEL]:n,[J.LLM_REQUEST_MAX_TOKENS]:o.maxTokens??"Not set",[J.LLM_REQUEST_TEMPERATURE]:o.temperature,[J.LLM_REQUEST_TOP_P]:o.topP??"Not set",[J.LLM_REQUEST_TOP_K]:o.topK??"Not set",[J.LLM_REQUEST_FREQUENCY_PENALTY]:o.frequencyPenalty??"Not set",[J.LLM_REQUEST_PRESENCE_PENALTY]:o.presencePenalty??"Not set",[J.LLM_REQUEST_STOP_SEQUENCES]:o.stopSequences?.join(", ")??"Not set",[J.LLM_REQUEST_LLM_IS_STREAMING]:o.stream??"Not set"}},t?.traceContext??vt.active(),async u=>await this._chat2(n,o,e,t,u)):await this._chat2(n,o,e,t)}cleanupFunctionSchema(e){let t={...e};if(t.parameters){let n={...t.parameters};Array.isArray(n.required)&&n.required.length===0&&delete n.required,n.properties&&Object.keys(n.properties).length===0&&delete n.properties,Object.keys(n).length===0||Object.keys(n).length===1&&n.type==="object"?delete t.parameters:t.parameters=n}return t}async _chat2(e,t,n,r,o){if(!this.aiImpl.createChatReq)throw new Error("createChatReq not implemented");let s=r?.debug??this.#e,a=r?.verbose??this.#t,l;n.functions&&n.functions.length>0&&(l=n.functions.map(y=>this.cleanupFunctionSchema(y)));let u={...n,model:e,functions:l,modelConfig:t};this.lastUsedChatModel=e,this.lastUsedModelConfig=t,s&&ca(u.chatPrompt,r?.stepIndex??0,r?.logger??this.logger,r?.debugHideSystemPrompt);let c=this.getFeatures(e).functions,p=r?.functionCallMode??"auto",m=p==="prompt"||p==="auto"&&!c?{...u,chatPrompt:u.chatPrompt.map(y=>{if(y.role==="assistant"){let{content:b,name:S,cache:w}=y;return{role:"assistant",content:b,name:S,cache:w}}return y.role==="function"?{role:"user",content:y.result}:y}),functions:[]}:u,g=await this.handleContextCaching(e,m,r,o),h=async()=>{if(g?.preparedRequest){let{apiConfig:w,request:M}=g.preparedRequest;return o?.isRecording()&&Na(n,o,this.excludeContentFromTrace),await Fe({name:w.name,url:this.apiURL,localCall:w.localCall,headers:await this.buildHeaders(w.headers),stream:t.stream,timeout:this.timeout,verbose:a,fetch:this.fetch,span:o,abortSignal:r?.abortSignal??this.abortSignal,corsProxy:this.corsProxy,retry:r?.retry??this.retry},M)}let[y,b]=await this.aiImpl.createChatReq(m,r);return o?.isRecording()&&Na(n,o,this.excludeContentFromTrace),await Fe({name:y.name,url:this.apiURL,localCall:y.localCall,headers:await this.buildHeaders(y.headers),stream:t.stream,timeout:this.timeout,verbose:a,fetch:this.fetch,span:o,abortSignal:r?.abortSignal??this.abortSignal,corsProxy:this.corsProxy,retry:r?.retry??this.retry},b)},f=r?.rateLimiter??this.rt,x=f?await f(h,{modelUsage:this.modelUsage}):await h();if(t.stream){if(!this.aiImpl.createChatStreamResp)throw new Error("createChatStreamResp not implemented");let y=this.aiImpl.createChatStreamResp.bind(this),b=R=>k=>{let F=y(k,R);if(F.sessionId=r?.sessionId,!F.modelUsage){let E=this.aiImpl.getTokenUsage();E&&(F.modelUsage={ai:this.name,model:e,tokens:E})}return this.modelUsage=F.modelUsage,this.recordTokenUsage(F.modelUsage),o?.isRecording()&&Da(F,o,this.excludeContentFromTrace),F},S=async R=>{o?.isRecording()&&o.end(),s&&da(R,r?.logger??this.logger)};if(typeof window<"u"){let R=x,k={},F=[],E=r?.abortSignal??this.abortSignal;return new ReadableStream({start:T=>{let v=R.getReader(),C=()=>{try{v.cancel().catch(()=>{})}catch{}try{this.recordAbortMetric("chat")}catch{}try{o?.isRecording()&&o.end()}catch{}try{T.error(new DOMException("Aborted","AbortError"))}catch{T.error(new Error("Aborted"))}};if(E){if(E.aborted){C();return}E.addEventListener("abort",C,{once:!0})}async function O(){try{for(;;){let{done:I,value:P}=await v.read();if(I){S&&await S(F),T.close();break}let _=b(k)(P);_&&(F.push(_),T.enqueue(_))}}catch(I){if(T.error(I),o?.isRecording())try{o.end()}catch{}}finally{if(v.releaseLock(),E)try{E.removeEventListener("abort",C)}catch{}}}O()}})}return x.pipeThrough(new Dr(b({}),S))}if(!this.aiImpl.createChatResp)throw new Error("createChatResp not implemented");let A=this.aiImpl.createChatResp(x);if(A.sessionId=r?.sessionId,!A.modelUsage){let y=this.aiImpl.getTokenUsage();y&&(A.modelUsage={ai:this.name,model:e,tokens:y})}return A.modelUsage&&(this.modelUsage=A.modelUsage,this.recordTokenUsage(A.modelUsage)),o?.isRecording()&&(Da(A,o,this.excludeContentFromTrace),o.end()),s&&pa(A,r?.logger??this.logger),A}async embed(e,t){let n=performance.now(),r=!1,o,s=this.getModelByKey(e.embedModel),a={...s?{thinkingTokenBudget:s.thinkingTokenBudget,showThoughts:s.showThoughts,stream:s.stream,debug:s.debug,useExpensiveModel:s.useExpensiveModel}:void 0,...t};try{return o=await this._embed1(e,a),o}catch(l){throw r=!0,l instanceof Error&&(l.message.includes("timeout")||l.name==="TimeoutError"?this.recordTimeoutMetric("embed"):(l.message.includes("abort")||l.name==="AbortError")&&this.recordAbortMetric("embed")),l}finally{let l=performance.now()-n;this.updateLatencyMetrics("embed",l),this.updateErrorMetrics("embed",r),!r&&o&&this.recordEmbedMetrics(e,o)}}async _embed1(e,t){let n=this.getEmbedModel(e.embedModel)??e.embedModel??this.defaults.embedModel;if(!n)throw new Error("No embed model defined");return this.tracer?await this.tracer.startActiveSpan("AI Embed Request",{kind:Be.SERVER,attributes:{[J.LLM_SYSTEM]:this.name,[J.LLM_OPERATION_NAME]:"embeddings",[J.LLM_REQUEST_MODEL]:n}},t?.traceContext??vt.active(),async r=>await this._embed2(n,e,t,r)):await this._embed2(n,e,t)}async _embed2(e,t,n,r){if(!this.aiImpl.createEmbedReq)throw new Error("createEmbedReq not implemented");if(!this.aiImpl.createEmbedResp)throw new Error("createEmbedResp not implemented");let o=this.aiImpl.createEmbedReq.bind(this.aiImpl),s=n?.debug??this.#e,a=n?.verbose??this.#t,l={...t,embedModel:e};this.lastUsedEmbedModel=e,s&&xa(l.texts??[],e,n?.logger??this.logger);let u=async()=>{let[m,g]=await o(l);return await Fe({name:m.name,url:this.apiURL,localCall:m.localCall,headers:await this.buildHeaders(m.headers),verbose:a,fetch:this.fetch,timeout:this.timeout,span:r,abortSignal:n?.abortSignal??this.abortSignal,corsProxy:this.corsProxy,retry:n?.retry??this.retry},g)},c=n?.rateLimiter??this.rt,p=c?await c(u,{modelUsage:this.embedModelUsage}):await u(),d=this.aiImpl.createEmbedResp?.(p);if(d.sessionId=n?.sessionId,!d.modelUsage){let m=this.aiImpl.getTokenUsage();m&&(d.modelUsage={ai:this.name,model:e,tokens:m})}return this.embedModelUsage=d.modelUsage,this.recordTokenUsage(d.modelUsage),r?.isRecording()&&d.modelUsage?.tokens&&r.addEvent(it.GEN_AI_USAGE,{[J.LLM_USAGE_INPUT_TOKENS]:d.modelUsage.tokens.promptTokens,[J.LLM_USAGE_OUTPUT_TOKENS]:d.modelUsage.tokens.completionTokens??0,[J.LLM_USAGE_TOTAL_TOKENS]:d.modelUsage.tokens.totalTokens}),s&&Aa(d.embeddings,n?.logger??this.logger),r?.end(),d}async buildHeaders(e={}){return{...e,...await this.headers()}}getModelByKey(e){return e?this.models?.find(n=>n.key===e):void 0}getModel(e){let t=this.getModelByKey(e);return t&&"model"in t?t.model:void 0}getEmbedModel(e){let t=this.getModelByKey(e);return t&&"embedModel"in t?t.embedModel:void 0}async handleContextCaching(e,t,n,r){let o=n?.contextCache;if(!o)return null;let s=this.aiImpl.supportsContextCache?.(e)??!1,a=this.aiImpl.supportsImplicitCaching?.(e)??!1;if(!s&&!a)throw new Error(`Context caching is not supported by this provider/model (${this.getName()}/${e}). Remove the contextCache option or use a provider that supports caching.`);if(!s)return null;let l=o.ttlSeconds??3600,u=o.refreshWindowSeconds??300,c=o.minTokens??2048;if(o.name)return this.useCacheByName(e,t,o.name,n,r);let p=vc(t.chatPrompt);if(!p||p===De("sha256").digest("hex"))return null;let d={providerId:this.id,model:e,contentHash:p},m=Rc(d),g=Date.now(),h=o.registry,f=h?await h.get(m):Ms.get(m);if(f&&f.expiresAt>g){if(f.expiresAt-g<u*1e3&&this.aiImpl.buildCacheUpdateTTLOp){await this.executeCacheOperation(this.aiImpl.buildCacheUpdateTTLOp(f.cacheName,l),n,r);let b={cacheName:f.cacheName,expiresAt:g+l*1e3,tokenCount:f.tokenCount};h?await h.set(m,b):Ms.set(m,{...b,contentHash:p,lastTouchedAt:g})}return this.useCacheByName(e,t,f.cacheName,n,r)}if(this.estimateCacheableTokens(t.chatPrompt)<c)return null;let A=this.aiImpl.buildCacheCreateOp?.(t,n);if(A){let y=await this.executeCacheOperation(A,n,r);if(y){let b={cacheName:y.name,expiresAt:new Date(y.expiresAt).getTime(),tokenCount:y.tokenCount};return h?await h.set(m,b):Ms.set(m,{...b,contentHash:p,lastTouchedAt:g}),this.useCacheByName(e,t,y.name,n,r)}}return null}async useCacheByName(e,t,n,r,o){if(this.aiImpl.prepareCachedChatReq){let s=await this.aiImpl.prepareCachedChatReq(t,r??{},n);return{preparedRequest:{apiConfig:s.apiConfig,request:s.request}}}return null}async executeCacheOperation(e,t,n){let r=t?.verbose??this.#t;try{n?.addEvent("context_cache.operation",{type:e.type,endpoint:e.apiConfig.name});let o=await Fe({name:e.apiConfig.name,url:this.apiURL,localCall:e.apiConfig.localCall,headers:await this.buildHeaders(e.apiConfig.headers),stream:!1,timeout:this.timeout,verbose:r,fetch:this.fetch,span:n,abortSignal:t?.abortSignal??this.abortSignal,corsProxy:this.corsProxy,retry:t?.retry??this.retry},e.request);return e.parseResponse(o)}catch(o){n?.addEvent("context_cache.error",{type:e.type,error:o instanceof Error?o.message:String(o)});return}}estimateCacheableTokens(e){let t=0;for(let n of e){if(n.role==="system"){t+=n.content.length;continue}if("cache"in n&&n.cache)if(n.role==="user"){if(typeof n.content=="string")t+=n.content.length;else if(Array.isArray(n.content))for(let r of n.content)"cache"in r&&r.cache&&(r.type==="text"?t+=r.text.length:r.type==="image"?t+=1e3:r.type==="audio"?t+=2e3:r.type==="file"&&(t+=500))}else n.role==="assistant"&&n.content&&(t+=n.content.length)}return Math.ceil(t/4)}};function Na(i,e,t){let n=[];if(i.chatPrompt&&Array.isArray(i.chatPrompt)&&i.chatPrompt.length>0)for(let o of i.chatPrompt)switch(o.role){case"system":if(o.content){let s={};t||(s.content=o.content),e.addEvent(it.GEN_AI_SYSTEM_MESSAGE,s)}break;case"user":if(typeof o.content=="string")n.push(o.content);else if(Array.isArray(o.content))for(let s of o.content)s.type==="text"&&n.push(s.text);break;case"assistant":{let s=o.functionCalls?.map(a=>({id:a.id,type:a.type,function:a.function.name,arguments:a.function.params}));if(s&&s.length>0){let a={function_calls:JSON.stringify(s,null,2)};!t&&o.content&&(a.content=o.content),e.addEvent(it.GEN_AI_ASSISTANT_MESSAGE,a)}else if(o.content){let a={};t||(a.content=o.content),e.addEvent(it.GEN_AI_ASSISTANT_MESSAGE,a)}break}case"function":{let s={id:o.functionId};t||(s.content=o.result),e.addEvent(it.GEN_AI_TOOL_MESSAGE,s);break}}let r={};t||(r.content=n.join(`
169
+ `)),e.addEvent(it.GEN_AI_USER_MESSAGE,r)}function Da(i,e,t){if(i.modelUsage?.tokens){let n=i.modelUsage.tokens.thoughtsTokens?{[J.LLM_USAGE_THOUGHTS_TOKENS]:i.modelUsage.tokens.thoughtsTokens}:{};e.addEvent(it.GEN_AI_USAGE,{[J.LLM_USAGE_INPUT_TOKENS]:i.modelUsage.tokens.promptTokens,[J.LLM_USAGE_OUTPUT_TOKENS]:i.modelUsage.tokens.completionTokens??0,[J.LLM_USAGE_TOTAL_TOKENS]:i.modelUsage.tokens.totalTokens,...n})}if(i.results)for(let n=0;n<i.results.length;n++){let r=i.results[n];if(!r||!r.content&&!r.thought&&!r.functionCalls?.length&&!r.finishReason)continue;let o=r.functionCalls?.map(a=>({id:a.id,type:a.type,function:a.function.name,arguments:a.function.params})),s={};o&&o.length>0?(t||(s.content=r.content),s.tool_calls=o):t||(s.content=r.content??""),e.addEvent(it.GEN_AI_CHOICE,{finish_reason:r.finishReason,index:n,message:JSON.stringify(s,null,2)})}}function Ga(i){let e=0;for(let t of i){if(!t||typeof t!="object")throw new Error(`AxMessage array validation failed: Item at index ${e} is not a valid message object`);if(t.role!=="user"&&t.role!=="assistant")throw new Error(`AxMessage array validation failed: Item at index ${e} has invalid role: ${t.role}`);e++}}function Sc(i){let e=new Set;for(let t of i){if(e.has(t.key))throw new Error(`Duplicate model key detected: "${t.key}". Each model key must be unique.`);e.add(t.key)}}var qn=(g=>(g.Claude45Opus="claude-opus-4-5-20251101",g.Claude41Opus="claude-opus-4-1-20250805",g.Claude4Opus="claude-opus-4-20250514",g.Claude4Sonnet="claude-sonnet-4-20250514",g.Claude45Sonnet="claude-sonnet-4-5-20250929",g.Claude45Haiku="claude-haiku-4-5",g.Claude37Sonnet="claude-3-7-sonnet-latest",g.Claude35Sonnet="claude-3-5-sonnet-latest",g.Claude35Haiku="claude-3-5-haiku-latest",g.Claude3Opus="claude-3-opus-latest",g.Claude3Sonnet="claude-3-sonnet-20240229",g.Claude3Haiku="claude-3-haiku-20240307",g.Claude21="claude-2.1",g.ClaudeInstant12="claude-instant-1.2",g))(qn||{}),zn=(d=>(d.Claude45Opus="claude-opus-4-5@20251101",d.Claude41Opus="claude-opus-4-1@20250805",d.Claude4Opus="claude-opus-4@20250514",d.Claude45Sonnet="claude-sonnet-4-5@20250929",d.Claude4Sonnet="claude-sonnet-4@20250514",d.Claude37Sonnet="claude-3-7-sonnet@20250219",d.Claude35SonnetV2="claude-3-5-sonnet-v2@20241022",d.Claude45Haiku="claude-haiku-4-5@20251001",d.Claude35Haiku="claude-3-5-haiku@20241022",d.Claude35Sonnet="claude-3-5-sonnet@20240620",d.Claude3Opus="claude-3-opus@20240229",d.Claude3Haiku="claude-3-haiku@20240307",d))(zn||{});var Hn=[{name:"claude-opus-4-5-20251101",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:25,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-5@20251101",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:25,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4-5-20250929",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:2e5,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4-5@20250929",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:2e5,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-haiku-4-5",currency:"usd",promptTokenCostPer1M:1,completionTokenCostPer1M:5,maxTokens:2e5,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-haiku-4-5@20251001",currency:"usd",promptTokenCostPer1M:1,completionTokenCostPer1M:5,maxTokens:2e5,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-opus-4-1-20250805",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-1@20250805",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-20250514",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4@20250514",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4-20250514",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4@20250514",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-3-7-sonnet-latest",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-3-7-sonnet@20250219",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-3-5-sonnet-latest",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:8192,supported:{structuredOutputs:!0}},{name:"claude-3-5-sonnet@20240620",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:8192,supported:{structuredOutputs:!0}},{name:"claude-3-5-sonnet-v2@20241022",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:8192,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-3-5-haiku-latest",currency:"usd",promptTokenCostPer1M:.8,completionTokenCostPer1M:4,maxTokens:8192},{name:"claude-3-5-haiku@20241022",currency:"usd",promptTokenCostPer1M:1,completionTokenCostPer1M:5,maxTokens:8192},{name:"claude-3-opus-latest",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:4096,supported:{structuredOutputs:!0}},{name:"claude-3-opus@20240229",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:4096,supported:{structuredOutputs:!0}},{name:"claude-3-sonnet-20240229",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:4096,supported:{structuredOutputs:!0}},{name:"claude-3-haiku-20240307",currency:"usd",promptTokenCostPer1M:.25,completionTokenCostPer1M:1.25,maxTokens:4096},{name:"claude-3-haiku@20240307",currency:"usd",promptTokenCostPer1M:.25,completionTokenCostPer1M:1.25,maxTokens:4096},{name:"claude-2.1",currency:"usd",promptTokenCostPer1M:8,completionTokenCostPer1M:25,maxTokens:4096},{name:"claude-instant-1.2",currency:"usd",promptTokenCostPer1M:.8,completionTokenCostPer1M:2.24,maxTokens:4096}];var St=i=>{if(!i||typeof i!="object")return i;let e={...i};if(e.type==="object"||Array.isArray(e.type)&&e.type.includes("object")){if(!e.properties||Object.keys(e.properties).length===0)throw new Error("Anthropic models do not support arbitrary JSON objects (e.g. f.json() or f.object() with no properties) in structured outputs. Please use f.string() and instruct the model to return a JSON string, or define the expected structure with f.object({ ... })");e.additionalProperties===void 0&&(e.additionalProperties=!1)}return delete e.optional,e.properties&&typeof e.properties=="object"&&(e.properties=Object.fromEntries(Object.entries(e.properties).map(([n,r])=>[n,St(r)]))),e.items&&(e.items=St(e.items)),Array.isArray(e.anyOf)&&(e.anyOf=e.anyOf.map(n=>St(n))),Array.isArray(e.allOf)&&(e.allOf=e.allOf.map(n=>St(n))),Array.isArray(e.oneOf)&&(e.oneOf=e.oneOf.map(n=>St(n))),e},Ps=()=>structuredClone({model:"claude-3-7-sonnet-latest",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},...se()}),Ua=()=>structuredClone({model:"claude-3-7-sonnet@20250219",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},...se()}),Es=class{constructor(e,t){this.config=e;this.isVertex=t}tokensUsed;currentPromptConfig;usedStructuredOutput=!1;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens??4096,temperature:e.temperature,topP:e.topP,topK:e.topK,stream:e.stream,stopSequences:e.stopSequences,endSequences:e.endSequences,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,n:e.n}}createChatReq=async(e,t)=>{this.currentPromptConfig=t;let n=e.model,r=e.modelConfig?.stream??this.config.stream,o;this.isVertex?o={name:r?`/models/${n}:streamRawPredict?alt=sse`:`/models/${n}:rawPredict`}:o={name:"/messages"};let s;if(e.functionCall&&e.functions&&e.functions.length>0)if(typeof e.functionCall=="string")switch(e.functionCall){case"auto":s={tool_choice:{type:"auto"}};break;case"required":s={tool_choice:{type:"any"}};break;case"none":throw new Error("functionCall none not supported")}else if("function"in e.functionCall)s={tool_choice:{type:"tool",name:e.functionCall.function.name}};else throw new Error("Invalid function call type, must be string or object");let a=e.chatPrompt.filter(R=>R.role==="system").map(R=>({type:"text",text:R.content,cache_control:{type:"ephemeral"}})),l=e.chatPrompt.filter(R=>R.role!=="system"),u=e.functions?.map(R=>{let k={type:"object",properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]},F=R.parameters?St(R.parameters):void 0;return F===void 0||F&&typeof F=="object"&&Object.keys(F).length===0?F={...k}:F&&typeof F=="object"&&F.type==="object"&&(!("properties"in F)||!F.properties||Object.keys(F.properties).length===0)&&(F={...F,properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]}),{name:R.name,description:R.description,input_schema:F,...R.cache?{cache_control:{type:"ephemeral"}}:{}}}),p=(this.config.tools??[]).map(R=>R&&typeof R=="object"&&"type"in R?R:{name:R.name,description:R.description,input_schema:R.input_schema?St(R.input_schema):void 0,...R.cache_control?{cache_control:R.cache_control}:{}}),d=[...u??[],...p];d.length===0&&(d=void 0);let m=e.modelConfig?.maxTokens??this.config.maxTokens,g=e.modelConfig?.stopSequences??this.config.stopSequences,h=e.modelConfig?.temperature,f=e.modelConfig?.topP,x=e.modelConfig?.topK??this.config.topK,A=e.modelConfig?.n??this.config.n;if(A&&A>1)throw new Error("Anthropic does not support sampling (n > 1)");let y;if(this.config.thinking?.budget_tokens&&(y=this.config.thinking),t?.thinkingTokenBudget){let R=this.config.thinkingTokenBudgetLevels;switch(t.thinkingTokenBudget){case"none":y=void 0;break;case"minimal":y={type:"enabled",budget_tokens:R?.minimal??1024};break;case"low":y={type:"enabled",budget_tokens:R?.low??5e3};break;case"medium":y={type:"enabled",budget_tokens:R?.medium??1e4};break;case"high":y={type:"enabled",budget_tokens:R?.high??2e4};break;case"highest":y={type:"enabled",budget_tokens:R?.highest??32e3};break}}if(!y&&t?.thinkingTokenBudget===void 0){let R=this.config.thinkingTokenBudgetLevels}let b=Oc(l,!!y);b.some(R=>R.role==="assistant"&&Array.isArray(R.content)&&R.content.length>0&&R.content[0]?.type==="tool_use")&&(y=void 0);let w;if(this.usedStructuredOutput=!1,e.responseFormat&&e.responseFormat.type==="json_schema"&&e.responseFormat.schema){let R=e.responseFormat.schema.schema||e.responseFormat.schema;w={type:"json_schema",schema:St(R)},this.usedStructuredOutput=!0}let M={...this.isVertex?{anthropic_version:"vertex-2023-10-16"}:{model:n},...m?{max_tokens:m}:{},...g&&g.length>0?{stop_sequences:g}:{},...h!==void 0&&!y?{temperature:h}:{},...f!==void 0&&(!y||f>=.95)?{top_p:f}:{},...x&&!y?{top_k:x}:{},...s,...d?{tools:d}:{},...r?{stream:!0}:{},...a?{system:a}:{},...y?{thinking:y}:{},...w?{output_format:w}:{},messages:b};return[o,M]};createChatResp=e=>{if(e.type==="error")throw new xe(e.error.message,void 0,void 0);let t=La(e.stop_reason),n=this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1,r="",o=[],s=[],a=[];for(let c of e.content)switch(c.type){case"text":if(r+=c.text??"",Array.isArray(c.citations))for(let p of c.citations)p?.url&&a.push({url:String(p.url),title:typeof p.title=="string"?p.title:void 0,snippet:typeof p.cited_text=="string"?p.cited_text:void 0});break;case"thinking":if(n){let p=c.thinking??"",d=c.signature;s.push({data:p,encrypted:!1,...typeof d=="string"?{signature:d}:{}})}break;case"redacted_thinking":if(n){let p=c.data??"",d=c.signature;s.push({data:p,encrypted:!0,...typeof d=="string"?{signature:d}:{}})}break;case"tool_use":o.push({id:c.id,type:"function",function:{name:c.name,params:c.input}});break}let l={index:0,id:e.id,finishReason:t};r&&(l.content=r),s.length>0&&(l.thoughtBlocks=s,l.thought=s.map(c=>c.data).join("")),o.length>0&&(l.functionCalls=o),a.length>0&&(l.citations=a);let u=[l];return this.tokensUsed={promptTokens:e.usage.input_tokens,completionTokens:e.usage.output_tokens,totalTokens:e.usage.input_tokens+e.usage.output_tokens+(e.usage.cache_creation_input_tokens||0)+(e.usage.cache_read_input_tokens||0),cacheCreationTokens:e.usage.cache_creation_input_tokens,cacheReadTokens:e.usage.cache_read_input_tokens},{results:u,remoteId:e.id}};createChatStreamResp=(e,t)=>{if(!("type"in e))throw new Error("Invalid Anthropic streaming event");let n=t;if(n.indexIdMap||(n.indexIdMap={}),e.type==="error"){let{error:o}=e;throw new xe(o.message,void 0,void 0)}let r=0;if(e.type==="message_start"){let{message:o}=e,s=[{index:r,content:"",id:o.id}];return this.tokensUsed={promptTokens:o.usage?.input_tokens??0,completionTokens:o.usage?.output_tokens??0,totalTokens:(o.usage?.input_tokens??0)+(o.usage?.output_tokens??0)+(o.usage?.cache_creation_input_tokens??0)+(o.usage?.cache_read_input_tokens??0),cacheCreationTokens:o.usage?.cache_creation_input_tokens,cacheReadTokens:o.usage?.cache_read_input_tokens},{results:s}}if(e.type==="content_block_start"){let{content_block:o}=e;if(o.type==="text"){let s=[];if(Array.isArray(o.citations))for(let a of o.citations)a?.url&&s.push({url:String(a.url),title:typeof a.title=="string"?a.title:void 0,snippet:typeof a.cited_text=="string"?a.cited_text:void 0});return{results:[{index:r,content:o.text,...s.length?{citations:s}:{}}]}}if(o.type==="thinking")return this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1?{results:[{index:r,thought:o.thinking,thoughtBlocks:[{data:o.thinking,encrypted:!1}]}]}:{results:[{index:r,content:""}]};if(o.type==="tool_use"&&typeof o.id=="string"&&typeof e.index=="number"&&!n.indexIdMap[e.index]){n.indexIdMap[e.index]=o.id;let s=[{id:o.id,type:"function",function:{name:o.name,params:""}}];return{results:[{index:r,functionCalls:s}]}}if(o.type==="web_search_tool_result"||o.type==="server_tool_use")return{results:[{index:r,content:""}]}}if(e.type==="content_block_delta"){let{delta:o}=e;if(o.type==="citations_delta"){let s=o.citation;if(s&&typeof s.url=="string"&&s.url.length>0){let a=[{url:String(s.url),title:typeof s.title=="string"?s.title:void 0,snippet:typeof s.cited_text=="string"?s.cited_text:void 0}];return{results:[{index:r,content:"",citations:a}]}}return{results:[{index:r,content:""}]}}if(o.type==="text_delta"){let s=[];if(Array.isArray(o.citations))for(let a of o.citations)a?.url&&s.push({url:String(a.url),title:typeof a.title=="string"?a.title:void 0,snippet:typeof a.cited_text=="string"?a.cited_text:void 0});return{results:[{index:r,content:o.text,...s.length?{citations:s}:{}}]}}if(o.type==="thinking_delta")return this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1?{results:[{index:r,thought:o.thinking,thoughtBlocks:[{data:o.thinking,encrypted:!1}]}]}:{results:[{index:r,content:""}]};if(o.type==="signature_delta")return{results:[{index:r,thoughtBlocks:[{data:"",encrypted:!1,signature:o.signature}]}]};if(o.type==="input_json_delta"){let s=n.indexIdMap[e.index];if(!s)return{results:[{index:r,content:""}]};let a=[{id:s,type:"function",function:{name:"",params:o.partial_json}}];return{results:[{index:r,functionCalls:a}]}}}if(e.type==="message_delta"){let{delta:o,usage:s}=e;return this.tokensUsed={promptTokens:this.tokensUsed?.promptTokens??0,completionTokens:s.output_tokens,totalTokens:(this.tokensUsed?.promptTokens??0)+s.output_tokens+(this.tokensUsed?.cacheCreationTokens??0)+(this.tokensUsed?.cacheReadTokens??0),cacheCreationTokens:this.tokensUsed?.cacheCreationTokens,cacheReadTokens:this.tokensUsed?.cacheReadTokens},{results:[{index:r,content:"",finishReason:La(o.stop_reason)}]}}return{results:[{index:r,content:""}]}};supportsImplicitCaching=()=>!0},Kt=class i extends we{static create(e){return new i(e)}constructor({apiKey:e,projectId:t,region:n,config:r,options:o,models:s}){let a=t!==void 0&&n!==void 0,l,u;if(a){if(!e)throw new Error("Anthropic Vertex API key not set");if(typeof e!="function")throw new Error("Anthropic Vertex API key must be a function for token-based authentication");l=`https://${n==="global"?"aiplatform":`${n}-aiplatform`}.googleapis.com/v1/projects/${t}/locations/${n}/publishers/anthropic/`,u=async()=>({Authorization:`Bearer ${await e()}`,"anthropic-beta":"web-search-2025-03-05"})}else{if(!e)throw new Error("Anthropic API key not set");l="https://api.anthropic.com/v1",u=async()=>({"anthropic-version":"2023-06-01","anthropic-beta":"structured-outputs-2025-11-13, web-search-2025-03-05","x-api-key":typeof e=="function"?await e():e})}let c={...Ps(),...r},p=new Es(c,a),d=g=>{let h=Je({model:g,modelInfo:Hn,models:s});return{functions:!0,streaming:!0,hasThinkingBudget:h?.supported?.thinkingBudget??!1,hasShowThoughts:h?.supported?.showThoughts??!1,structuredOutputs:h?.supported?.structuredOutputs??!1,functionCot:!0,media:{images:{supported:!0,formats:["image/jpeg","image/png","image/gif","image/webp"],maxSize:5*1024*1024,detailLevels:["high","low","auto"]},audio:{supported:!1,formats:[],maxDuration:0},files:{supported:!1,formats:[],maxSize:0,uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!0,types:["ephemeral"]},thinking:h?.supported?.thinkingBudget??!1,multiTurn:!0}},m=s?.map(g=>{let h=g,f=h?.config;if(!f)return g;let x={};f.maxTokens!==void 0&&(x.maxTokens=f.maxTokens),f.temperature!==void 0&&(x.temperature=f.temperature),f.topP!==void 0&&(x.topP=f.topP),f.topK!==void 0&&(x.topK=f.topK),f.presencePenalty!==void 0&&(x.presencePenalty=f.presencePenalty),f.frequencyPenalty!==void 0&&(x.frequencyPenalty=f.frequencyPenalty),f.stopSequences!==void 0&&(x.stopSequences=f.stopSequences),f.endSequences!==void 0&&(x.endSequences=f.endSequences),f.stream!==void 0&&(x.stream=f.stream),f.n!==void 0&&(x.n=f.n);let A={...h};Object.keys(x).length>0&&(A.modelConfig={...h.modelConfig??{},...x});let y=f.thinking?.thinkingTokenBudget;if(typeof y=="number"){let b=c.thinkingTokenBudgetLevels,S=[["minimal",b?.minimal??200],["low",b?.low??800],["medium",b?.medium??5e3],["high",b?.high??1e4],["highest",b?.highest??24500]],w="minimal",M=Number.POSITIVE_INFINITY;for(let[R,k]of S){let F=Math.abs(y-k);F<M&&(M=F,w=R)}A.thinkingTokenBudget=w}return f.thinking?.includeThoughts!==void 0&&(A.showThoughts=!!f.thinking.includeThoughts),A});super(p,{name:"Anthropic",apiURL:l,headers:u,modelInfo:Hn,defaults:{model:c.model},options:o,supportFor:d,models:m??s})}};function Oc(i,e){let t=i.map(r=>{switch(r.role){case"function":return{role:"user",content:[{type:"tool_result",content:r.result,tool_use_id:r.functionId,...r.isError?{is_error:!0}:{},...r.cache?{cache:{type:"ephemeral"}}:{}}]};case"user":return typeof r.content=="string"?{role:"user",content:r.content}:{role:"user",content:r.content.map(s=>{switch(s.type){case"text":return{type:"text",text:s.text,...s.cache?{cache_control:{type:"ephemeral"}}:{}};case"image":return{type:"image",source:{type:"base64",media_type:s.mimeType,data:s.image},...s.cache?{cache_control:{type:"ephemeral"}}:{}};default:throw new Error("Invalid content type")}})};case"assistant":{let o="",s=[],a=r.thoughtBlocks;if(Array.isArray(a)&&a.length>0)for(let l of a)l.encrypted?s.push(l.signature?{type:"redacted_thinking",data:l.data,signature:l.signature}:{type:"redacted_thinking",data:l.data}):s.push(l.signature?{type:"thinking",thinking:l.data,signature:l.signature}:{type:"thinking",thinking:l.data});return typeof r.content=="string"&&(s.length>0?o=[...s,{type:"text",text:r.content}]:o=r.content),typeof r.functionCalls<"u"&&(o=r.functionCalls.map(l=>{let u={};if(typeof l.function.params=="string"){let c=l.function.params;if(c.trim().length===0)u={};else try{u=JSON.parse(c)}catch{throw new Error(`Failed to parse function params JSON: ${c}`)}}else typeof l.function.params=="object"&&(u=l.function.params);return{type:"tool_use",id:l.id,name:l.function.name,input:u,...r.cache?{cache_control:{type:"ephemeral"}}:{}}}),Array.isArray(o)&&s.length>0&&(o=[...s,...o])),{role:"assistant",content:o}}default:throw new Error("Invalid role")}}),n=kc(t);return Mc(n)}function kc(i){let e=[];for(let[t,n]of i.entries()){if(n.role!=="assistant"){e.push(n);continue}if(t>0&&i.at(t-1)?.role==="assistant"){let r=e.pop();e.push({...r||{},...n})}else e.push(n)}return e}function Mc(i){return i.map(e=>e.role==="assistant"&&typeof e.content=="string"?{...e,content:e.content.replace(/\s+$/,"")}:e)}function La(i){if(i)switch(i){case"stop_sequence":return"stop";case"max_tokens":return"length";case"tool_use":return"function_call";case"end_turn":return"stop";default:return"stop"}}var Kn=(T=>(T.GPT4="gpt-4",T.GPT41="gpt-4.1",T.GPT41Mini="gpt-4.1-mini",T.GPT41Nano="gpt-4.1-nano",T.GPT4O="gpt-4o",T.GPT4OMini="gpt-4o-mini",T.GPT4ChatGPT4O="chatgpt-4o-latest",T.GPT4Turbo="gpt-4-turbo",T.GPT35Turbo="gpt-3.5-turbo",T.GPT35TurboInstruct="gpt-3.5-turbo-instruct",T.GPT35TextDavinci002="text-davinci-002",T.GPT3TextBabbage002="text-babbage-002",T.GPT3TextAda001="text-ada-001",T.GPT5="gpt-5",T.GPT5Nano="gpt-5-nano",T.GPT5Mini="gpt-5-mini",T.GPT5Chat="gpt-5-chat",T.GPT5Pro="gpt-5-pro",T.GPT51="gpt-5.1",T.GPT51ChatLatest="gpt-5.1-chat-latest",T.GPT52="gpt-5.2",T.GPT52ChatLatest="gpt-5.2-chat-latest",T.GPT52Pro="gpt-5.2-pro",T.O1="o1",T.O1Mini="o1-mini",T.O3="o3",T.O3Mini="o3-mini",T.O4Mini="o4-mini",T))(Kn||{}),Vt=(n=>(n.TextEmbeddingAda002="text-embedding-ada-002",n.TextEmbedding3Small="text-embedding-3-small",n.TextEmbedding3Large="text-embedding-3-large",n))(Vt||{});var Wt=(C=>(C.GPT4="gpt-4",C.GPT41="gpt-4.1",C.GPT41Mini="gpt-4.1-mini",C.GPT41Nano="gpt-4.1-nano",C.GPT4O="gpt-4o",C.GPT4OMini="gpt-4o-mini",C.GPT4ChatGPT4O="chatgpt-4o-latest",C.GPT4Turbo="gpt-4-turbo",C.GPT35Turbo="gpt-3.5-turbo",C.GPT35TurboInstruct="gpt-3.5-turbo-instruct",C.GPT35TextDavinci002="text-davinci-002",C.GPT3TextBabbage002="text-babbage-002",C.GPT3TextAda001="text-ada-001",C.GPT5="gpt-5",C.GPT5Nano="gpt-5-nano",C.GPT5Mini="gpt-5-mini",C.GPT5Chat="gpt-5-chat",C.GPT5Pro="gpt-5-pro",C.GPT51="gpt-5.1",C.GPT51ChatLatest="gpt-5.1-chat-latest",C.GPT52="gpt-5.2",C.GPT52ChatLatest="gpt-5.2-chat-latest",C.GPT52Pro="gpt-5.2-pro",C.O1Pro="o1-pro",C.O1="o1",C.O1Mini="o1-mini",C.O3Pro="o3-pro",C.O3="o3",C.O3Mini="o3-mini",C.O4Mini="o4-mini",C))(Wt||{});var Jt=[{name:"gpt-4",currency:"usd",promptTokenCostPer1M:30,completionTokenCostPer1M:60},{name:"gpt-4.1",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8,supported:{structuredOutputs:!0}},{name:"gpt-4.1-mini",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1.6,supported:{structuredOutputs:!0}},{name:"gpt-4.1-nano",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.4,supported:{structuredOutputs:!0}},{name:"gpt-4o",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15,supported:{structuredOutputs:!0}},{name:"gpt-4o-mini",currency:"usd",promptTokenCostPer1M:.15,completionTokenCostPer1M:.6,supported:{structuredOutputs:!0}},{name:"chatgpt-4o-latest",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15,supported:{structuredOutputs:!0}},{name:"gpt-4-turbo",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,supported:{structuredOutputs:!0}},{name:"gpt-3.5-turbo",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5},{name:"gpt-5-nano",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5-mini",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:6,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5-chat",currency:"usd",promptTokenCostPer1M:12,completionTokenCostPer1M:36,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:60,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5-pro",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:120,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.1",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.1-chat-latest",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.2",currency:"usd",promptTokenCostPer1M:1.75,completionTokenCostPer1M:14,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.2-chat-latest",currency:"usd",promptTokenCostPer1M:1.75,completionTokenCostPer1M:14,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.2-pro",currency:"usd",promptTokenCostPer1M:21,completionTokenCostPer1M:168,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"o1",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{structuredOutputs:!0}},{name:"o1-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:14.4,supported:{structuredOutputs:!0}},{name:"o3",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{structuredOutputs:!0}},{name:"o4-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,supported:{structuredOutputs:!0}},{name:"text-embedding-ada-002",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.1},{name:"text-embedding-3-small",currency:"usd",promptTokenCostPer1M:.02,completionTokenCostPer1M:.02},{name:"text-embedding-3-large",currency:"usd",promptTokenCostPer1M:.13,completionTokenCostPer1M:.13}],Br=[{name:"gpt-4",currency:"usd",promptTokenCostPer1M:30,completionTokenCostPer1M:60},{name:"gpt-4.1",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8,supported:{structuredOutputs:!0}},{name:"gpt-4.1-mini",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1.6,supported:{structuredOutputs:!0}},{name:"gpt-4.1-nano",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.4,supported:{structuredOutputs:!0}},{name:"gpt-4o",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15,supported:{structuredOutputs:!0}},{name:"gpt-4o-mini",currency:"usd",promptTokenCostPer1M:.15,completionTokenCostPer1M:.6,supported:{structuredOutputs:!0}},{name:"chatgpt-4o-latest",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15,supported:{structuredOutputs:!0}},{name:"gpt-4-turbo",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,supported:{structuredOutputs:!0}},{name:"gpt-3.5-turbo",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5},{name:"gpt-5-nano",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5-mini",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:6,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5-chat",currency:"usd",promptTokenCostPer1M:12,completionTokenCostPer1M:36,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:60,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5-pro",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:120,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.1",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.1-chat-latest",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.2",currency:"usd",promptTokenCostPer1M:1.75,completionTokenCostPer1M:14,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.2-chat-latest",currency:"usd",promptTokenCostPer1M:1.75,completionTokenCostPer1M:14,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.2-pro",currency:"usd",promptTokenCostPer1M:21,completionTokenCostPer1M:168,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"o1-pro",currency:"usd",promptTokenCostPer1M:150,completionTokenCostPer1M:600,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0},isExpensive:!0},{name:"o1",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"o3-pro",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:80,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0},isExpensive:!0},{name:"o3",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"o3-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"o4-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}}];var Ec=i=>{let e=["o1","o1-mini","o3","o3-mini","o4-mini","o1-pro","o3-pro"];return e.includes(i)||e.includes(i)},Ft=()=>structuredClone({model:"gpt-5-mini",embedModel:"text-embedding-3-small",...se()}),jr=()=>structuredClone({...Ft(),model:"gpt-5"}),qr=()=>structuredClone({model:"gpt-5-mini",embedModel:"text-embedding-3-small",...Se()}),zr=()=>({...Ft(),model:"gpt-5-nano"}),Fs=class{constructor(e,t,n){this.config=e;this.streamingUsage=t;this.chatReqUpdater=n}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,endSequences:e.endSequences,topP:e.topP,n:e.n,stream:e.stream}}createChatReq=(e,t)=>{let n=e.model;if(!e.chatPrompt||e.chatPrompt.length===0)throw new Error("Chat prompt is empty");let r={name:"/chat/completions"},o=e.functions?.map(m=>({type:"function",function:{name:m.name,description:m.description,parameters:m.parameters}})),s=!e.functionCall&&e.functions&&e.functions.length>0?"auto":e.functionCall,a=Pc(e),l=e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,u=e.modelConfig?.stream??this.config.stream,c=this.config.store,p=Ec(n),d={model:n,messages:a,...e.responseFormat?{response_format:e.responseFormat.type==="json_schema"?{type:"json_schema",json_schema:e.responseFormat.schema}:e.responseFormat}:this.config?.responseFormat?{response_format:{type:this.config.responseFormat}}:{},...o?{tools:o}:{},...s?{tool_choice:s}:{},...p?{}:{...(e.modelConfig?.maxTokens??this.config.maxTokens)!==void 0?{max_completion_tokens:e.modelConfig?.maxTokens??this.config.maxTokens}:{},...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{top_p:e.modelConfig.topP}:{},...(e.modelConfig?.n??this.config.n)!==void 0?{n:e.modelConfig?.n??this.config.n}:{},...(e.modelConfig?.presencePenalty??this.config.presencePenalty)!==void 0?{presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty}:{},...l!==void 0?{frequency_penalty:l}:{}},...(e.modelConfig?.stopSequences??this.config.stop)&&(e.modelConfig?.stopSequences??this.config.stop).length>0?{stop:e.modelConfig?.stopSequences??this.config.stop}:{},...this.config.logitBias!==void 0?{logit_bias:this.config.logitBias}:{},...u&&this.streamingUsage?{stream:!0,stream_options:{include_usage:!0}}:{},...c?{store:c}:{},...this.config.serviceTier?{service_tier:this.config.serviceTier}:{},...this.config.user?{user:this.config.user}:{}};if(this.config.reasoningEffort&&(d.reasoning_effort=this.config.reasoningEffort),this.config.webSearchOptions&&(d.web_search_options={...this.config.webSearchOptions.searchContextSize&&{search_context_size:this.config.webSearchOptions.searchContextSize},...this.config.webSearchOptions.userLocation&&{user_location:{approximate:{type:"approximate",...this.config.webSearchOptions.userLocation.approximate.city&&{city:this.config.webSearchOptions.userLocation.approximate.city},...this.config.webSearchOptions.userLocation.approximate.country&&{country:this.config.webSearchOptions.userLocation.approximate.country},...this.config.webSearchOptions.userLocation.approximate.region&&{region:this.config.webSearchOptions.userLocation.approximate.region},...this.config.webSearchOptions.userLocation.approximate.timezone&&{timezone:this.config.webSearchOptions.userLocation.approximate.timezone}}}}}),t?.thinkingTokenBudget)switch(t.thinkingTokenBudget){case"none":d.reasoning_effort=void 0;break;case"minimal":d.reasoning_effort="minimal";break;case"low":d.reasoning_effort="medium";break;case"medium":d.reasoning_effort="high";break;case"high":d.reasoning_effort="high";break;case"highest":d.reasoning_effort="high";break}if(!d.reasoning_effort&&t?.thinkingTokenBudget)switch(t.thinkingTokenBudget){case"minimal":d.reasoning_effort="minimal";break;case"low":d.reasoning_effort="medium";break;case"medium":case"high":case"highest":d.reasoning_effort="high";break}return this.chatReqUpdater&&(d=this.chatReqUpdater(d)),[r,d]};createEmbedReq=e=>{let t=e.embedModel;if(!t)throw new Error("Embed model not set");if(!e.texts||e.texts.length===0)throw new Error("Embed texts is empty");let n={name:"/embeddings"},r={model:t,input:e.texts,dimensions:this.config.dimensions};return[n,r]};createChatResp(e){let{id:t,usage:n,choices:r,error:o}=e;if(o)throw o;return this.tokensUsed=n?{promptTokens:n.prompt_tokens,completionTokens:n.completion_tokens,totalTokens:n.total_tokens}:void 0,{results:r.map(a=>{if(a.message.refusal)throw new xe(a.message.refusal,e.model,e.id);let l=Ba(a.finish_reason),u=a.message.tool_calls?.map(({id:c,function:{arguments:p,name:d}})=>({id:c,type:"function",function:{name:d,params:p}}));return{index:a.index,id:`${a.index}`,content:a.message.content??void 0,thought:a.message.reasoning_content,citations:a.message.annotations?.filter(c=>c?.type==="url_citation"&&c.url_citation).map(c=>({url:c.url_citation?.url,title:c.url_citation?.title,description:c.url_citation?.description})),functionCalls:u,finishReason:l}}),remoteId:t}}createChatStreamResp(e,t){let{id:n,usage:r,choices:o}=e;this.tokensUsed=r?{promptTokens:r.prompt_tokens,completionTokens:r.completion_tokens,totalTokens:r.total_tokens}:void 0;let s=t;return s.indexIdMap||(s.indexIdMap={}),{results:o.map(({index:l,delta:{content:u,role:c,refusal:p,tool_calls:d,reasoning_content:m,annotations:g},finish_reason:h})=>{if(p)throw new xe(p,void 0,n);let f=Ba(h),x=d?.map(({id:A,index:y,function:{name:b,arguments:S}})=>{typeof A=="string"&&typeof y=="number"&&!s.indexIdMap[y]&&(s.indexIdMap[y]=A);let w=s.indexIdMap[y];return w?{id:w,type:"function",function:{name:b,params:S}}:null}).filter(A=>A!==null);return{index:l,content:u??void 0,role:c,thought:m,citations:g?.filter(A=>A?.type==="url_citation"&&A.url_citation).map(A=>({url:A.url_citation?.url,title:A.url_citation?.title,description:A.url_citation?.description})),functionCalls:x,finishReason:f,id:n}})}}createEmbedResp(e){let{data:t,usage:n}=e;return this.tokensUsed=n?{promptTokens:n.prompt_tokens,completionTokens:n.completion_tokens,totalTokens:n.total_tokens}:void 0,{embeddings:t.map(r=>r.embedding)}}},Ba=i=>{switch(i){case"stop":return"stop";case"length":return"length";case"content_filter":return"error";case"tool_calls":return"function_call"}};function Pc(i){return i.chatPrompt.map(t=>{switch(t.role){case"system":return{role:"system",content:t.content};case"user":{let n=Array.isArray(t.content)?t.content.map(r=>{switch(r.type){case"text":return{type:"text",text:r.text};case"image":return{type:"image_url",image_url:{url:`data:${r.mimeType};base64,${r.image}`,details:r.details??"auto"}};case"audio":return{type:"input_audio",input_audio:{data:r.data,format:r.format==="wav"?"wav":void 0}};default:throw new Error("Invalid content type")}}):t.content;return{role:"user",...t.name?{name:t.name}:{},content:n}}case"assistant":{let n=t.functionCalls?.map(r=>({id:r.id,type:"function",function:{name:r.function.name,arguments:typeof r.function.params=="object"?JSON.stringify(r.function.params):r.function.params}}));if(n&&n.length>0)return{role:"assistant",...t.content?{content:t.content}:{},name:t.name,tool_calls:n};if(t.content===void 0)throw new Error("Assistant content is required when no tool calls are provided");return{role:"assistant",content:t.content,...t.name?{name:t.name}:{}}}case"function":return{role:"tool",content:t.result,tool_call_id:t.functionId};default:throw new Error("Invalid role")}})}var Te=class extends we{constructor({apiKey:e,config:t,options:n,apiURL:r,modelInfo:o,models:s,chatReqUpdater:a,supportFor:l}){if(!e||e==="")throw new Error("OpenAI API key not set");let u=new Fs(t,n?.streamingUsage??!0,a);super(u,{name:"OpenAI",apiURL:r||"https://api.openai.com/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:o,defaults:{model:t.model,embedModel:t.embedModel},options:n,supportFor:l,models:s})}},Yt=class extends Te{constructor({apiKey:e,apiURL:t,config:n,options:r,models:o,modelInfo:s}){if(!e||e==="")throw new Error("OpenAI API key not set");s=[...Jt,...s??[]];let a=u=>{let c=Je({model:u,modelInfo:s,models:o});return{functions:!0,streaming:!0,hasThinkingBudget:c?.supported?.thinkingBudget??!1,hasShowThoughts:c?.supported?.showThoughts??!1,structuredOutputs:c?.supported?.structuredOutputs??!1,media:{images:{supported:!0,formats:["image/jpeg","image/png","image/gif","image/webp"],maxSize:20*1024*1024,detailLevels:["high","low","auto"]},audio:{supported:!0,formats:["wav","mp3","ogg"],maxDuration:25*60},files:{supported:!0,formats:["text/plain","application/pdf","image/jpeg","image/png"],maxSize:512*1024*1024,uploadMethod:"upload"},urls:{supported:!1,webSearch:!0,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:c?.supported?.thinkingBudget??!1,multiTurn:!0}},l=o?.map(u=>{let c=u,p=c?.config;if(!p)return u;let d={};p.maxTokens!==void 0&&(d.maxTokens=p.maxTokens),p.temperature!==void 0&&(d.temperature=p.temperature),p.topP!==void 0&&(d.topP=p.topP),p.presencePenalty!==void 0&&(d.presencePenalty=p.presencePenalty),p.frequencyPenalty!==void 0&&(d.frequencyPenalty=p.frequencyPenalty);let m=p.stopSequences??p.stop;m!==void 0&&(d.stopSequences=m),p.n!==void 0&&(d.n=p.n),p.stream!==void 0&&(d.stream=p.stream);let g={...c};Object.keys(d).length>0&&(g.modelConfig={...c.modelConfig??{},...d});let h=p?.thinking?.thinkingTokenBudget;if(typeof h=="number"){let f=[["minimal",200],["low",800],["medium",5e3],["high",1e4],["highest",24500]],x="minimal",A=Number.POSITIVE_INFINITY;for(let[y,b]of f){let S=Math.abs(h-b);S<A&&(A=S,x=y)}g.thinkingTokenBudget=x}return p?.thinking?.includeThoughts!==void 0&&(g.showThoughts=!!p.thinking.includeThoughts),g});super({apiKey:e,apiURL:t,config:{...Ft(),...n},options:r,modelInfo:s,models:l??o,supportFor:a}),super.setName("OpenAI")}};var Fc=i=>{let e=i.trim();if(!e)return e;if(e.includes("api-version=")){let t=e.indexOf("api-version="),n=e.slice(t);return new URLSearchParams(n).get("api-version")??e}return e},_c=i=>{let e=i.match(/^(\d{4}-\d{2}-\d{2})/);return e?e[1]>="2024-08-01":!1},_s=Ft,ja=qr,qa=zr,za=jr,Qt=class extends Te{constructor({apiKey:e,resourceName:t,deploymentName:n,version:r="api-version=2024-02-15-preview",config:o,options:s,models:a,modelInfo:l}){if(!e||e==="")throw new Error("Azure OpenAPI API key not set");if(!t||t==="")throw new Error("Azure OpenAPI resource name not set");if(!n||n==="")throw new Error("Azure OpenAPI deployment id not set");let u={..._s(),...o},c=Fc(r),p=_c(c);l=[...Jt,...l??[]];let d=g=>{let h=Je({model:g,modelInfo:l,models:a});return{functions:!0,streaming:!0,hasThinkingBudget:h?.supported?.thinkingBudget??!1,hasShowThoughts:h?.supported?.showThoughts??!1,structuredOutputs:p&&(h?.supported?.structuredOutputs??!1),functionCot:!1,media:{images:{supported:!0,formats:["image/jpeg","image/png","image/gif","image/webp"],maxSize:20*1024*1024,detailLevels:["high","low","auto"]},audio:{supported:!1,formats:[],maxDuration:0},files:{supported:!1,formats:[],maxSize:0,uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:h?.supported?.thinkingBudget??!1,multiTurn:!0}};super({apiKey:e,config:u,options:s,models:a,modelInfo:l,supportFor:d});let m=t.includes("://")?t:`https://${t}.openai.azure.com/`;super.setName("Azure OpenAI"),super.setAPIURL(new URL(`/openai/deployments/${n}?api-version=${c}`,m).href),super.setHeaders(async()=>({"api-key":e}))}};var Hr=class i{services;currentServiceIndex=0;currentService;debug;initialBackoffMs;maxBackoffMs;maxRetries;serviceFailures=new Map;constructor(e,t){if(e.length===0)throw new Error("No AI services provided.");$c(e),this.services=[...e].sort(t?.comparator??i.metricComparator);let n=this.services[this.currentServiceIndex];if(n===void 0)throw new Error("Error initializing the AI services.");this.currentService=n,this.debug=t?.debug??!0,this.initialBackoffMs=t?.initialBackoffMs??1e3,this.maxBackoffMs=t?.maxBackoffMs??32e3,this.maxRetries=t?.maxRetries??3}static create(e,t){return new i(e,t)}getLastUsedChatModel(){return this.currentService.getLastUsedChatModel()}getLastUsedEmbedModel(){return this.currentService.getLastUsedEmbedModel()}getLastUsedModelConfig(){return this.currentService.getLastUsedModelConfig()}static inputOrderComparator=()=>0;static metricComparator=(e,t)=>{let n=e.getMetrics(),r=t.getMetrics();return n.latency.chat.mean-r.latency.chat.mean};getModelList(){for(let e of this.services){let t=e.getModelList();if(t)return t}}getNextService(e,t){let n=t+1,r=e[n];return r===void 0?{service:void 0,index:n}:{service:r,index:n}}reset(){this.currentServiceIndex=0;let e=this.services[this.currentServiceIndex];if(e===void 0)throw new Error("No AI services provided.");this.currentService=e}getName(){return this.currentService.getName()}getId(){return this.currentService.getId()}getFeatures(e){let t={functions:!1,streaming:!1,thinking:!1,multiTurn:!1,structuredOutputs:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]}};for(let n of this.services){let r=n.getFeatures(e);r.functions&&(t.functions=!0),r.streaming&&(t.streaming=!0),r.thinking&&(t.thinking=!0),r.multiTurn&&(t.multiTurn=!0),r.structuredOutputs&&(t.structuredOutputs=!0),r.functionCot&&(t.functionCot=!0),r.hasThinkingBudget&&(t.hasThinkingBudget=!0),r.hasShowThoughts&&(t.hasShowThoughts=!0),r.media.images.supported&&(t.media.images.supported=!0),t.media.images.formats=Array.from(new Set([...t.media.images.formats,...r.media.images.formats])),r.media.audio.supported&&(t.media.audio.supported=!0),t.media.audio.formats=Array.from(new Set([...t.media.audio.formats,...r.media.audio.formats])),r.media.files.supported&&(t.media.files.supported=!0),t.media.files.formats=Array.from(new Set([...t.media.files.formats,...r.media.files.formats])),r.media.files.uploadMethod!=="none"&&(t.media.files.uploadMethod=r.media.files.uploadMethod),r.media.urls.supported&&(t.media.urls.supported=!0),r.media.urls.webSearch&&(t.media.urls.webSearch=!0),r.media.urls.contextFetching&&(t.media.urls.contextFetching=!0),r.caching.supported&&(t.caching.supported=!0),t.caching.types=Array.from(new Set([...t.caching.types,...r.caching.types]))}return t}getMetrics(){let e={latency:{chat:{mean:0,p95:0,p99:0,samples:[]},embed:{mean:0,p95:0,p99:0,samples:[]}},errors:{chat:{count:0,rate:0,total:0},embed:{count:0,rate:0,total:0}}},t=0,n=0,r=0,o=0;for(let s of this.services){let a=s.getMetrics();e.errors.chat.count+=a.errors.chat.count,e.errors.chat.total+=a.errors.chat.total,e.errors.embed.count+=a.errors.embed.count,e.errors.embed.total+=a.errors.embed.total;let l=a.latency.chat.samples.length;l>0&&(t+=a.latency.chat.mean*l,n+=l);let u=a.latency.embed.samples.length;u>0&&(r+=a.latency.embed.mean*u,o+=u)}e.errors.chat.total>0&&(e.errors.chat.rate=e.errors.chat.count/e.errors.chat.total),e.errors.embed.total>0&&(e.errors.embed.rate=e.errors.embed.count/e.errors.embed.total),n>0&&(e.latency.chat.mean=t/n),o>0&&(e.latency.embed.mean=r/o);for(let s of this.services){let a=s.getMetrics();e.latency.chat.p95=Math.max(e.latency.chat.p95,a.latency.chat.p95),e.latency.chat.p99=Math.max(e.latency.chat.p99,a.latency.chat.p99),e.latency.embed.p95=Math.max(e.latency.embed.p95,a.latency.embed.p95),e.latency.embed.p99=Math.max(e.latency.embed.p99,a.latency.embed.p99)}return e}canRetryService(e){let t=this.serviceFailures.get(e.getId());if(!t)return!0;let{retries:n,lastFailureTime:r}=t,o=Date.now()-r,s=Math.min(this.initialBackoffMs*2**n,this.maxBackoffMs);return o>=s}handleFailure(e,t){let r=(this.serviceFailures.get(e.getId())?.retries??0)+1;this.serviceFailures.set(e.getId(),{retries:r,lastFailureTime:Date.now()}),this.debug&&console.warn(`AxBalancer: Service ${e.getName()} failed (retry ${r}/${this.maxRetries})`,t)}handleSuccess(e){this.serviceFailures.delete(e.getId())}async chat(e,t){let n=e.responseFormat?.type==="json_schema",r=e.capabilities,o=r?.requiresImages,s=r?.requiresAudio,a=this.services,l=e.model;if((n||o||s)&&(a=this.services.filter(p=>{let d=p.getFeatures(l);return!(n&&!d.structuredOutputs||o&&!d.media.images.supported||s&&!d.media.audio.supported)}),a.length===0)){let p=[];throw n&&p.push("structured outputs"),o&&p.push("images"),s&&p.push("audio"),new Error(`No services available that support required capabilities: ${p.join(", ")}.`)}let u=0,c=a[u];if(!c)throw new Error("No matching AI services available for request.");for(this.currentService=c;;){if(!this.canRetryService(c)){let p=this.getNextService(a,u);if(!p.service)throw new Error(`All candidate services exhausted (tried ${a.length} service(s))`);c=p.service,u=p.index,this.currentService=c;continue}try{let p=await c.chat(e,t);return this.handleSuccess(c),p}catch(p){if(!(p instanceof Pe))throw p;switch(p.constructor){case At:throw p;case Ve:{if(![408,429,500,502,503,504].includes(p.status))throw p;break}case Ge:break;case xt:break;case Ye:break;case ot:break;default:throw p}if(this.handleFailure(c,p),(this.serviceFailures.get(c.getId())?.retries??0)>=this.maxRetries){let m=this.getNextService(a,u);if(this.debug&&console.warn(`AxBalancer: Switching to service ${m.service?.getName()??"none"}`,p),!m.service)throw p;c=m.service,u=m.index,this.currentService=c}}}}async embed(e,t){this.reset();let n=this.currentServiceIndex;for(;;){if(!this.canRetryService(this.currentService)){let r=this.getNextService(this.services,n);if(!r.service)throw new Error(`All services exhausted (tried ${this.services.length} service(s))`);this.currentService=r.service,n=r.index,this.currentServiceIndex=n;continue}try{let r=await this.currentService.embed(e,t);return this.handleSuccess(this.currentService),r}catch(r){if(!(r instanceof Pe)||r instanceof Ve&&![408,429,500,502,503,504].includes(r.status)||r instanceof At)throw r;if(this.handleFailure(this.currentService,r),(this.serviceFailures.get(this.currentService.getId())?.retries??0)>=this.maxRetries){let s=this.getNextService(this.services,n);if(!s.service)throw r;this.currentService=s.service,n=s.index,this.currentServiceIndex=n}}}}setOptions(e){for(let t of this.services)t.setOptions(e);this.currentService.setOptions(e),this.debug=e.debug??this.debug}getOptions(){return this.currentService.getOptions()}getLogger(){return this.currentService.getLogger()}};function $c(i){let e=i.find(r=>r.getModelList()!==void 0);if(!e)return;let t=e.getModelList();if(!t)throw new Error("No model list found in any service.");let n=new Set(t.map(r=>r.key));for(let r=0;r<i.length;r++){let o=i[r];if(!o)throw new Error(`Service at index ${r} is undefined`);let s=o.getModelList();if(!s)throw new Error(`Service at index ${r} (${o.getName()}) has no model list while another service does.`);let a=new Set(s.map(l=>l.key));for(let l of n)if(!a.has(l))throw new Error(`Service at index ${r} (${o.getName()}) is missing model "${l}"`);for(let l of a)if(!n.has(l))throw new Error(`Service at index ${r} (${o.getName()}) has extra model "${l}"`)}}function _t(i){let e=!1,t=!1,n=!1,r=!1,o=!1,s=!1,a=!1,l=new Set,u=0;if(i.chatPrompt&&Array.isArray(i.chatPrompt))for(let c of i.chatPrompt){if(c.role==="user"&&Array.isArray(c.content))for(let p of c.content)switch(l.add(p.type),p.type){case"image":e=!0,p.cache&&(a=!0),u+=85;break;case"audio":t=!0,p.cache&&(a=!0),u+=p.duration||60;break;case"file":n=!0,p.cache&&(a=!0),u+=Math.ceil((p.extractedText?.length||1e3)/4);break;case"url":r=!0,p.cache&&(a=!0),u+=Math.ceil((p.cachedContent?.length||2e3)/4);break;case"text":p.cache&&(a=!0),u+=Math.ceil(p.text.length/4);break}else"content"in c&&typeof c.content=="string"&&(u+=Math.ceil(c.content.length/4));"cache"in c&&c.cache&&(a=!0)}return i.functions&&i.functions.length>0&&(o=!0),i.modelConfig?.stream===!0&&(s=!0),i.capabilities&&(i.capabilities.requiresImages&&(e=!0),i.capabilities.requiresAudio&&(t=!0),i.capabilities.requiresFiles&&(n=!0),i.capabilities.requiresWebSearch&&(r=!0)),{hasImages:e,hasAudio:t,hasFiles:n,hasUrls:r,requiresFunctions:o,requiresStreaming:s,requiresCaching:a,contentTypes:l,estimatedTokens:u}}function $s(i,e){let t=i.getFeatures(),n=[],r=[],o=[];if(e.hasImages&&!t.media.images.supported&&(n.push("Image support"),o.push("Use altText for images or imageToText service")),e.hasAudio&&!t.media.audio.supported&&(n.push("Audio support"),o.push("Pre-transcribe audio or use transcription field")),e.hasFiles&&!t.media.files.supported&&(n.push("File support"),o.push("Pre-extract text content or use extractedText field")),e.hasUrls&&!t.media.urls.supported&&(n.push("URL/Web search support"),o.push("Pre-fetch content or use cachedContent field")),e.requiresFunctions&&!t.functions&&n.push("Function calling"),e.requiresStreaming&&!t.streaming&&(n.push("Streaming responses"),o.push("Use non-streaming mode")),e.requiresCaching&&!t.caching.supported&&(n.push("Content caching"),o.push("Repeated content will not be cached")),e.hasImages&&t.media.images.supported){let a=t.media.images.maxSize;a&&a<10*1024*1024&&r.push(`Image size limit is ${Math.round(a/(1024*1024))}MB`)}if(e.hasAudio&&t.media.audio.supported){let a=t.media.audio.maxDuration;a&&a<600&&r.push(`Audio duration limit is ${Math.round(a/60)} minutes`)}return{isSupported:n.length===0,missingCapabilities:n,warnings:r,alternatives:o}}function Kr(i,e){return i.map(t=>{let n=t.getFeatures(),r=$s(t,e),o=0,s=[];return o+=10,e.hasImages&&n.media.images.supported&&(o+=25,s.push("Images"),n.media.images.detailLevels?.includes("high")&&(o+=5),n.media.images.maxSize&&n.media.images.maxSize>10*1024*1024&&(o+=3)),e.hasAudio&&n.media.audio.supported&&(o+=25,s.push("Audio"),n.media.audio.maxDuration&&n.media.audio.maxDuration>600&&(o+=5)),e.hasFiles&&n.media.files.supported&&(o+=25,s.push("Files"),n.media.files.uploadMethod==="cloud"&&(o+=3)),e.hasUrls&&n.media.urls.supported&&(o+=25,s.push("URLs"),n.media.urls.webSearch&&(o+=5)),e.requiresFunctions&&n.functions&&(o+=15,s.push("Functions"),n.functionCot&&(o+=3)),e.requiresStreaming&&n.streaming&&(o+=10,s.push("Streaming")),e.requiresCaching&&n.caching.supported&&(o+=8,s.push("Caching"),n.caching.types.includes("persistent")&&(o+=3)),n.thinking&&(o+=2),n.multiTurn&&(o+=2),n.hasThinkingBudget&&(o+=1),n.hasShowThoughts&&(o+=1),o-=r.missingCapabilities.length*10,{provider:t,score:o,missingCapabilities:r.missingCapabilities,supportedCapabilities:s}}).sort((t,n)=>n.score-t.score)}function Vr(i,e,t={}){if(e.length===0)throw new Error("No providers available");let n=_t(i),r=Kr(e,n);if(t.requireExactMatch){let o=r.filter(s=>s.missingCapabilities.length===0);if(o.length===0)throw new Error(`No providers fully support the request requirements: ${r[0]?.missingCapabilities.join(", ")||"unknown requirements"}`);return o[0].provider}if(!t.allowDegradation){let o=r[0];if(o.missingCapabilities.length>0)throw new Error(`Best available provider (${o.provider.getName()}) is missing: ${o.missingCapabilities.join(", ")}`)}return r[0].provider}function Ha(i,e){let t=_t(i),n=Kr(e,t),r=n[0]?.provider||null,o=[t.hasImages&&"images",t.hasAudio&&"audio",t.hasFiles&&"files",t.hasUrls&&"URLs",t.requiresFunctions&&"functions",t.requiresStreaming&&"streaming",t.requiresCaching&&"caching"].filter(Boolean).length,s=r?n[0].supportedCapabilities.length:0,a=r?`${r.getName()} supports ${s}/${o} requirements (${Math.round(s/Math.max(o,1)*100)}% compatibility)`:"No suitable providers found";return{requirements:t,providerScores:n,recommendedProvider:r,summary:a}}function Ka(i,e){return i.filter(t=>t.getFeatures().media[e].supported)}function Va(i,e){let t={};for(let n of i){let o=n.getFeatures().media[e];if(o.supported)for(let s of o.formats)t[s]||(t[s]=[]),t[s].push(n)}return t}var Vn=(r=>(r.CommandRPlus="command-r-plus",r.CommandR="command-r",r.Command="command",r.CommandLight="command-light",r))(Vn||{}),Wn=(r=>(r.EmbedEnglishV30="embed-english-v3.0",r.EmbedEnglishLightV30="embed-english-light-v3.0",r.EmbedMultiLingualV30="embed-multilingual-v3.0",r.EmbedMultiLingualLightV30="embed-multilingual-light-v3.0",r))(Wn||{});var Wr=[{name:"command-r-plus",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15},{name:"command-r",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5},{name:"command",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5},{name:"command-light",currency:"usd",promptTokenCostPer1M:.3,completionTokenCostPer1M:.6},{name:"embed-english-light-v3.0",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.1},{name:"embed-english-v3.0",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.1},{name:"embed-multilingual-v3.0",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.1},{name:"embed-multilingual-light-v3.0",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.1}];var Ds=()=>structuredClone({model:"command-r-plus",embedModel:"embed-english-v3.0",...se()}),Ja=()=>structuredClone({model:"command-r",embedModel:"embed-english-v3.0",...Se()}),Ns=class{constructor(e){this.config=e}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,frequencyPenalty:e.frequencyPenalty,presencePenalty:e.presencePenalty,endSequences:e.endSequences,stopSequences:e.stopSequences,stream:e.stream,n:e.n}}createChatReq(e){let t=e.model,n=e.chatPrompt.at(-1),r=e.chatPrompt.slice(0,-1),o;n&&n.role==="user"&&typeof n.content=="string"&&(o=n?.content);let s=Nc(r),a=e.functions?.map(p=>{let d={};if(p.parameters?.properties)for(let[m,g]of Object.entries(p.parameters.properties))d[m]={description:g.description,type:g.type,required:p.parameters.required?.includes(m)??!1};return{name:p.name,description:p.description,parameter_definitions:d}}),l=e.chatPrompt.filter(p=>p.role==="function").map(p=>{let d=a?.find(m=>m.name===p.functionId);if(!d)throw new Error("Function not found");return{call:{name:d.name,parameters:d.parameter_definitions},outputs:[{result:p.result??""}]}}),u={name:"/chat"},c={message:o,model:t,tools:a,...l&&!o?{tool_results:l}:{},chat_history:s,max_tokens:e.modelConfig?.maxTokens??this.config.maxTokens,...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},k:e.modelConfig?.topK??this.config.topK,...e.modelConfig?.topP!==void 0?{p:e.modelConfig.topP}:{},frequency_penalty:e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty,end_sequences:this.config.endSequences,stop_sequences:e.modelConfig?.stopSequences??this.config.stopSequences};return[u,c]}createEmbedReq=e=>{let t=e.embedModel;if(!t)throw new Error("Embed model not set");if(!e.texts||e.texts.length===0)throw new Error("Embed texts is empty");let n={name:"/embed"},r={model:t,texts:e.texts??[],input_type:"classification",truncate:""};return[n,r]};createChatResp=e=>{this.tokensUsed=e.meta.billed_units?{promptTokens:e.meta.billed_units.input_tokens,completionTokens:e.meta.billed_units.output_tokens,totalTokens:e.meta.billed_units.input_tokens+e.meta.billed_units.output_tokens}:void 0;let t;if("finish_reason"in e)switch(e.finish_reason){case"COMPLETE":t="stop";break;case"MAX_TOKENS":t="length";break;case"ERROR":throw new Error("Finish reason: ERROR");case"ERROR_TOXIC":throw new Error("Finish reason: CONTENT_FILTER");default:t="stop";break}let n;return"tool_calls"in e&&(n=e.tool_calls?.map(o=>({id:o.name,type:"function",function:{name:o.name,params:o.parameters}}))),{results:[{index:0,id:e.generation_id,content:e.text,functionCalls:n,finishReason:t}],remoteId:e.response_id}};createChatStreamResp=(e,t)=>{let n=t;e.event_type==="stream-start"&&(n.generation_id=e.generation_id),this.tokensUsed={promptTokens:0,completionTokens:e.meta.billed_units?.output_tokens??0,totalTokens:e.meta.billed_units?.output_tokens??0};let{results:r}=this.createChatResp(e),o=r[0];if(!o)throw new Error("No result");return o.id=n.generation_id??"",{results:r}};createEmbedResp(e){return{remoteId:e.id,embeddings:e.embeddings}}},Xt=class extends we{constructor({apiKey:e,config:t,options:n,models:r}){if(!e||e==="")throw new Error("Cohere API key not set");let o={...Ds(),...t},s=new Ns(o),a=r?.map(l=>{let u=l,c=u?.config;if(!c)return l;let p={};c.maxTokens!==void 0&&(p.maxTokens=c.maxTokens),c.temperature!==void 0&&(p.temperature=c.temperature),c.topP!==void 0&&(p.topP=c.topP),c.topK!==void 0&&(p.topK=c.topK),c.presencePenalty!==void 0&&(p.presencePenalty=c.presencePenalty),c.frequencyPenalty!==void 0&&(p.frequencyPenalty=c.frequencyPenalty),c.stopSequences!==void 0&&(p.stopSequences=c.stopSequences),c.endSequences!==void 0&&(p.endSequences=c.endSequences),c.stream!==void 0&&(p.stream=c.stream),c.n!==void 0&&(p.n=c.n);let d={...u};return Object.keys(p).length>0&&(d.modelConfig={...u.modelConfig??{},...p}),d});super(s,{name:"Cohere",apiURL:"https://api.cohere.ai/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:Wr,defaults:{model:o.model},supportFor:{functions:!0,streaming:!0,media:{images:{supported:!1,formats:[],maxSize:0,detailLevels:[]},audio:{supported:!1,formats:[],maxDuration:0},files:{supported:!1,formats:[],maxSize:0,uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0},options:n,models:a??r})}};function Nc(i){return i.map(e=>{let t="";if(e.role==="system"||e.role==="assistant"||e.role==="user")if(typeof e.content=="string")t=e.content;else throw new Error("Multi-modal content not supported");switch(e.role){case"user":return{role:"USER",message:t};case"system":return{role:"SYSTEM",message:t};case"assistant":{let n=Wa(e.functionCalls);return{role:"CHATBOT",message:t,tool_calls:n}}case"function":{let n=i.map(s=>{if(s.role==="assistant")return s.functionCalls?.find(a=>a.id===e.functionId)}).filter(s=>s!==void 0),r=Wa(n)?.at(0);if(!r)throw new Error("Function call not found");let o=[{result:e.result}];return{role:"TOOL",tool_results:[{call:r,outputs:o}]}}default:throw new Error("Unknown role")}})}function Wa(i){return i?.map(e=>{let t;if(typeof e.function.params=="string"){let n=e.function.params;if(n.trim().length===0)t={};else try{t=JSON.parse(n)}catch{throw new Error(`Failed to parse function params JSON: ${n}`)}}else t=e.function.params;return{name:e.function.name,parameters:t}})}var Jn=(n=>(n.DeepSeekChat="deepseek-chat",n.DeepSeekCoder="deepseek-coder",n.DeepSeekReasoner="deepseek-reasoner",n))(Jn||{});var Jr=[{name:"deepseek-chat",currency:"USD",promptTokenCostPer1M:.27,completionTokenCostPer1M:1.1},{name:"deepseek-reasoner",currency:"USD",promptTokenCostPer1M:.55,completionTokenCostPer1M:2.19}];var Gs=()=>structuredClone({model:"deepseek-chat",...se()}),Ya=()=>structuredClone({model:"deepseek-coder",...Se()}),Zt=class extends Te{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("DeepSeek API key not set");let s={...Gs(),...t};o=[...Jr,...o??[]],super({apiKey:e,config:s,options:n,apiURL:"https://api.deepseek.com",modelInfo:o,supportFor:{functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0},models:r}),super.setName("DeepSeek")}};var Yn=(A=>(A.Gemini3Flash="gemini-3-flash-preview",A.Gemini3Pro="gemini-3-pro-preview",A.Gemini3ProImage="gemini-3-pro-image-preview",A.Gemini25Pro="gemini-2.5-pro",A.Gemini25Flash="gemini-2.5-flash",A.Gemini25FlashLite="gemini-2.5-flash-lite",A.Gemini20Flash="gemini-2.0-flash",A.Gemini20FlashLite="gemini-2.0-flash-lite",A.Gemini20ProExp="gemini-2.0-pro-exp-02-05",A.Gemini20FlashThinkingExp="gemini-2.0-flash-thinking-exp-01-21",A.Gemini1Pro="gemini-1.0-pro",A.Gemini15Flash="gemini-1.5-flash",A.Gemini15Flash002="gemini-1.5-flash-002",A.Gemini15Flash8B="gemini-1.5-flash-8b",A.Gemini15Pro="gemini-1.5-pro",A.GeminiFlashLatest="gemini-flash-latest",A.GeminiFlashLiteLatest="gemini-flash-lite-latest",A.GeminiProLatest="gemini-pro-latest",A))(Yn||{}),Yr=(o=>(o.GeminiEmbedding001="gemini-embedding-001",o.GeminiEmbedding="gemini-embedding-exp",o.TextEmbeddingLarge="text-embedding-large-exp-03-07",o.TextEmbedding004="text-embedding-004",o.TextEmbedding005="text-embedding-005",o))(Yr||{}),Qr=(r=>(r.HarmCategoryHarassment="HARM_CATEGORY_HARASSMENT",r.HarmCategoryHateSpeech="HARM_CATEGORY_HATE_SPEECH",r.HarmCategorySexuallyExplicit="HARM_CATEGORY_SEXUALLY_EXPLICIT",r.HarmCategoryDangerousContent="HARM_CATEGORY_DANGEROUS_CONTENT",r))(Qr||{}),Xr=(o=>(o.BlockNone="BLOCK_NONE",o.BlockOnlyHigh="BLOCK_ONLY_HIGH",o.BlockMediumAndAbove="BLOCK_MEDIUM_AND_ABOVE",o.BlockLowAndAbove="BLOCK_LOW_AND_ABOVE",o.BlockDefault="HARM_BLOCK_THRESHOLD_UNSPECIFIED",o))(Xr||{}),Ls=(l=>(l.SemanticSimilarity="SEMANTIC_SIMILARITY",l.Classification="CLASSIFICATION",l.Clustering="CLUSTERING",l.RetrievalDocument="RETRIEVAL_DOCUMENT",l.RetrievalQuery="RETRIEVAL_QUERY",l.QuestionAnswering="QUESTION_ANSWERING",l.FactVerification="FACT_VERIFICATION",l.CodeRetrievalQuery="CODE_RETRIEVAL_QUERY",l))(Ls||{}),Qa=["gemini-3-flash-preview","gemini-3-pro-preview","gemini-2.5-pro","gemini-2.5-flash","gemini-2.5-flash-lite","gemini-2.0-flash","gemini-2.0-flash-lite","gemini-flash-latest","gemini-flash-lite-latest"];var Zr=[{name:"gemini-3-flash-preview",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.5,completionTokenCostPer1M:3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-3-pro-preview",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2,completionTokenCostPer1M:12,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-3-pro-image-preview",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2,completionTokenCostPer1M:.134,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.5-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2.5,completionTokenCostPer1M:15,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.0-pro-exp-02-05",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.0-flash-thinking-exp-01-21",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.5-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:15,completionTokenCostPer1M:3.5,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.5-flash-lite",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.1,completionTokenCostPer1M:.4,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.0-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.01,completionTokenCostPer1M:.4,supported:{structuredOutputs:!0}},{name:"gemini-2.0-flash-lite",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0,supported:{structuredOutputs:!0}},{name:"gemini-1.5-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.075,completionTokenCostPer1M:.3,supported:{structuredOutputs:!0}},{name:"gemini-1.5-flash-8b",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.0375,completionTokenCostPer1M:.15,supported:{structuredOutputs:!0}},{name:"gemini-1.5-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:1.25,completionTokenCostPer1M:5,supported:{structuredOutputs:!0}},{name:"gemini-1.0-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5,supported:{structuredOutputs:!0}},{name:"gemini-flash-latest",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.075,completionTokenCostPer1M:.3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-flash-lite-latest",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-pro-latest",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:1.25,completionTokenCostPer1M:5,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}}];var eo=i=>{if(!i||typeof i!="object")return i;let e={...i};return delete e.additionalProperties,delete e.default,delete e.optional,delete e.maximum,delete e.oneOf,delete e.anyOf,e.properties&&typeof e.properties=="object"&&(e.properties=Object.fromEntries(Object.entries(e.properties).map(([t,n])=>[t,eo(n)]))),e.items&&(e.items=eo(e.items)),e},Xa=[{category:"HARM_CATEGORY_HARASSMENT",threshold:"BLOCK_NONE"},{category:"HARM_CATEGORY_HATE_SPEECH",threshold:"BLOCK_NONE"},{category:"HARM_CATEGORY_SEXUALLY_EXPLICIT",threshold:"BLOCK_NONE"},{category:"HARM_CATEGORY_DANGEROUS_CONTENT",threshold:"BLOCK_NONE"}],Bs=()=>structuredClone({model:"gemini-2.5-flash",embedModel:"text-embedding-005",safetySettings:Xa,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},...se()}),Za=()=>structuredClone({model:"gemini-2.0-flash",embedModel:"text-embedding-005",safetySettings:Xa,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},...Se()}),Us=class{constructor(e,t,n,r,o){this.config=e;this.isVertex=t;this.endpointId=n;this.apiKey=r;this.options=o;if(!this.isVertex&&this.config.autoTruncate)throw new Error("Auto truncate is not supported for GoogleGemini")}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,endSequences:e.endSequences,stream:e.stream,n:e.n}}createChatReq=async(e,t)=>{let n=e.model,r=e.modelConfig?.stream??this.config.stream;if(!e.chatPrompt||e.chatPrompt.length===0)throw new Error("Chat prompt is empty");let o;if(this.endpointId?o={name:r?`/${this.endpointId}:streamGenerateContent?alt=sse`:`/${this.endpointId}:generateContent`}:o={name:r?`/models/${n}:streamGenerateContent?alt=sse`:`/models/${n}:generateContent`},!this.isVertex){let x=r?"&":"?",A=typeof this.apiKey=="function"?await this.apiKey():this.apiKey;o.name+=`${x}key=${A}`}let s=e.chatPrompt.filter(x=>x.role==="system").map(x=>x.content),a=s.length>0?{role:"user",parts:[{text:s.join(" ")}]}:void 0,l=[],u=e.chatPrompt.filter(x=>x.role!=="system");for(let x=0;x<u.length;x++){let A=u[x];switch(A.role){case"user":{let y=Array.isArray(A.content)?A.content.map((b,S)=>{switch(b.type){case"text":return{text:b.text};case"image":return{inlineData:{mimeType:b.mimeType,data:b.image}};case"audio":return{inlineData:{mimeType:`audio/${b.format??"mp3"}`,data:b.data}};case"file":return"fileUri"in b?{fileData:{mimeType:b.mimeType,fileUri:b.fileUri}}:{inlineData:{mimeType:b.mimeType,data:b.data}};default:throw new Error(`Chat prompt content type not supported (index: ${S})`)}}):[{text:A.content}];l.push({role:"user",parts:y});break}case"assistant":{let y=[],b=A.thoughtBlocks,S=A.functionCalls&&A.functionCalls.length>0,w=b?.[0],M=b?.map(k=>k.data).join("")??"",R=w?.signature;if(M&&y.push({...S?{}:{thought:!0},text:M,...R&&!S?{thought_signature:R}:{}}),A.functionCalls){let k=A.functionCalls.map((F,E)=>{let T;if(typeof F.function.params=="string"){let C=F.function.params;if(C.trim().length===0)T={};else try{T=JSON.parse(C)}catch{throw new Error(`Failed to parse function params JSON: ${C}`)}}else T=F.function.params;let v={functionCall:{name:F.function.name,args:T}};return R&&E===0&&(v.thought_signature=R),v});y.push(...k)}if(A.content&&y.push({text:A.content}),y.length===0)throw new Error("Assistant content is empty");l.push({role:"model",parts:y});break}case"function":{let y=[],b=A,S=x;for(;;){if(!("functionId"in b))throw new Error(`Chat prompt functionId is empty (index: ${S})`);if(y.push({functionResponse:{name:b.functionId,response:{result:b.result}}}),S+1<u.length&&u[S+1].role==="function")S++,b=u[S];else break}x=S,l.push({role:"user",parts:y});break}default:throw new Error(`Invalid role: ${JSON.stringify(A)} (index: ${x})`)}}let c=[];if(e.functions&&e.functions.length>0){let x=e.functions.map(A=>{let y={type:"object",properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]},b=A.parameters?eo(A.parameters):void 0;return b===void 0||b&&typeof b=="object"&&Object.keys(b).length===0?b={...y}:b&&typeof b=="object"&&b.type==="object"&&(!("properties"in b)||!b.properties||Object.keys(b.properties).length===0)&&(b={...b,properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]}),{name:A.name,description:A.description,parameters:b}});c.push({function_declarations:x})}if(this.options?.codeExecution&&c.push({code_execution:{}}),this.options?.googleSearchRetrieval&&c.push({google_search_retrieval:{dynamic_retrieval_config:this.options.googleSearchRetrieval}}),this.options?.googleSearch&&c.push({google_search:{}}),this.options?.googleMaps){let x=this.options.googleMaps,A=x?.enableWidget!==void 0?{enableWidget:x.enableWidget}:{};c.push({google_maps:A})}this.options?.urlContext&&c.push({url_context:{}}),c.length===0&&(c=void 0);let p,d=Array.isArray(c)?c.some(x=>x&&Array.isArray(x.function_declarations)&&x.function_declarations.length>0):!1;if(e.functionCall)if(e.functionCall==="none")p={function_calling_config:{mode:"NONE"}};else if(e.functionCall==="auto")p={function_calling_config:{mode:"AUTO"}};else if(e.functionCall==="required")p={function_calling_config:{mode:"ANY"}};else{let x=e.functionCall.function?.name?{allowedFunctionNames:[e.functionCall.function.name]}:{};p={function_calling_config:{mode:"ANY"},...x}}else d&&(p={function_calling_config:{mode:"AUTO"}});this.options?.retrievalConfig&&(p={...p??{},retrievalConfig:{...this.options.retrievalConfig.latLng?{latLng:this.options.retrievalConfig.latLng}:{}}});let m={};if(this.config.thinking?.includeThoughts&&(m.includeThoughts=!0),this.config.thinking?.thinkingTokenBudget&&(m.thinkingBudget=this.config.thinking.thinkingTokenBudget),this.config.thinking?.thinkingLevel&&(m.thinkingLevel=this.config.thinking.thinkingLevel),t?.thinkingTokenBudget){let x=this.config.thinkingTokenBudgetLevels,A=n.includes("gemini-3");switch(t.thinkingTokenBudget){case"none":m.thinkingBudget=0,m.includeThoughts=!1,delete m.thinkingLevel;break;case"minimal":m.thinkingBudget=x?.minimal??200,A&&(m.thinkingLevel="low");break;case"low":m.thinkingBudget=x?.low??800,A&&(m.thinkingLevel="low");break;case"medium":m.thinkingBudget=x?.medium??5e3,A&&(m.thinkingLevel="high");break;case"high":m.thinkingBudget=x?.high??1e4,A&&(m.thinkingLevel="high");break;case"highest":m.thinkingBudget=x?.highest??24500,A&&(m.thinkingLevel="high");break}}m.thinkingLevel&&delete m.thinkingBudget,t?.showThoughts!==void 0&&t?.thinkingTokenBudget!=="none"&&(m.includeThoughts=t.showThoughts);let g={maxOutputTokens:e.modelConfig?.maxTokens??this.config.maxTokens,...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{topP:e.modelConfig.topP}:{},topK:e.modelConfig?.topK??this.config.topK,frequencyPenalty:e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,candidateCount:1,stopSequences:e.modelConfig?.stopSequences??this.config.stopSequences,responseMimeType:"text/plain",...Object.keys(m).length>0?{thinkingConfig:m}:{}};if(e.responseFormat){if(g.responseMimeType="application/json",e.responseFormat.type==="json_schema"&&e.responseFormat.schema){let x=e.responseFormat.schema.schema||e.responseFormat.schema;g.responseSchema=eo(x)}}else this.config.responseFormat&&this.config.responseFormat==="json_object"&&(g.responseMimeType="application/json");let h=this.config.safetySettings;return[o,{contents:l,tools:c,toolConfig:p,systemInstruction:a,generationConfig:g,safetySettings:h}]};createEmbedReq=async e=>{let t=e.embedModel;if(!t)throw new Error("Embed model not set");if(!e.texts||e.texts.length===0)throw new Error("Embed texts is empty");let n,r;if(this.isVertex)this.endpointId?n={name:`/${this.endpointId}:predict`}:n={name:`/models/${t}:predict`},r={instances:e.texts.map(o=>({content:o,...this.config.embedType&&{taskType:this.config.embedType}})),parameters:{autoTruncate:this.config.autoTruncate,outputDimensionality:this.config.dimensions}};else{let o=typeof this.apiKey=="function"?this.apiKey():this.apiKey;n={name:`/models/${t}:batchEmbedContents?key=${o}`},r={requests:e.texts.map(s=>({model:`models/${t}`,content:{parts:[{text:s}]},outputDimensionality:this.config.dimensions,...this.config.embedType&&{taskType:this.config.embedType}}))}}return[n,r]};createChatResp=e=>{let t,n=e.candidates?.map(o=>{let s={index:0};switch(o.finishReason){case"MAX_TOKENS":s.finishReason="length";break;case"STOP":s.finishReason="stop";break;case"SAFETY":throw new xe("Content was blocked due to safety settings",void 0,void 0);case"RECITATION":throw new xe("Content was blocked due to recitation policy",void 0,void 0);case"MALFORMED_FUNCTION_CALL":throw new xe("Function call was malformed and blocked",void 0,void 0);case"UNEXPECTED_TOOL_CALL":throw new xe("Unexpected tool call",void 0,void 0);case"FINISH_REASON_UNSPECIFIED":throw new xe("Finish reason unspecified",void 0,void 0);case"BLOCKLIST":throw new xe("Content was blocked due to blocklist",void 0,void 0);case"PROHIBITED_CONTENT":throw new xe("Content was blocked due to prohibited content",void 0,void 0);case"SPII":throw new xe("Content was blocked due to SPII",void 0,void 0);case"OTHER":throw new xe("Other finish reason",void 0,void 0)}if(!o.content||!o.content.parts)return s;for(let u of o.content.parts){if("text"in u){if("thought"in u&&u.thought||u.thought===!0){s.thought=u.text;let c=u.thoughtSignature||u.thought_signature;s.thoughtBlocks||(s.thoughtBlocks=[]),s.thoughtBlocks.push({data:u.text,encrypted:!1,...c?{signature:c}:{}})}else s.content=u.text;continue}if("functionCall"in u){let c=u.thoughtSignature||u.thought_signature;if(c)if(!s.thoughtBlocks||s.thoughtBlocks.length===0)s.thoughtBlocks=[{data:"",encrypted:!1,signature:c}];else{let p=s.thoughtBlocks[s.thoughtBlocks.length-1];p&&!p.signature&&(p.signature=c)}s.functionCalls=[...s.functionCalls??[],{id:Ee(),type:"function",function:{name:u.functionCall.name,params:u.functionCall.args}}]}}let a=o.citationMetadata?.citations;if(Array.isArray(a)&&a.length){let u=c=>c?`${c.year}-${String(c.month).padStart(2,"0")}-${String(c.day).padStart(2,"0")}`:void 0;s.citations=a.filter(c=>typeof c?.uri=="string").map(c=>({url:c.uri,title:c.title,license:c.license,publicationDate:u(c.publicationDate)}))}let l=o.groundingMetadata;if(l){if(Array.isArray(l.groundingChunks)){let u=l.groundingChunks.map(c=>c?.maps).filter(c=>c&&typeof c.uri=="string").map(c=>({url:c.uri,title:c.title}));u.length&&(s.citations=[...s.citations??[],...u])}typeof l.googleMapsWidgetContextToken=="string"&&(t=l.googleMapsWidgetContextToken)}return s});e.usageMetadata&&(this.tokensUsed={totalTokens:e.usageMetadata.totalTokenCount,promptTokens:e.usageMetadata.promptTokenCount,completionTokens:e.usageMetadata.candidatesTokenCount,thoughtsTokens:e.usageMetadata.thoughtsTokenCount,...e.usageMetadata.cachedContentTokenCount!==void 0?{cacheReadTokens:e.usageMetadata.cachedContentTokenCount}:{}});let r={results:n};return t&&(r.providerMetadata={...r.providerMetadata,google:{...r.providerMetadata?.google??{},mapsWidgetContextToken:t}}),r};createChatStreamResp=e=>this.createChatResp(e);createEmbedResp=e=>{let t;return this.isVertex?t=e.predictions.map(n=>n.embeddings.values):t=e.embeddings.map(n=>n.values),{embeddings:t}};supportsContextCache=e=>{let t=e;return Qa.some(n=>t.includes(n)||n.includes(t))};buildCacheCreateOp=(e,t)=>{let n=e.model,r=t.contextCache?.ttlSeconds??3600,{systemInstruction:o,contents:s}=this.extractCacheableContent(e.chatPrompt);if(!o&&(!s||s.length===0))return;let a={model:this.isVertex?n:`models/${n}`,ttl:`${r}s`,displayName:`ax-cache-${Date.now()}`};o&&(a.systemInstruction=o),s&&s.length>0&&(a.contents=s);let l;if(this.isVertex)l="/cachedContents";else{l="/cachedContents";let u=typeof this.apiKey=="function"?"ASYNC_KEY":this.apiKey;l+=`?key=${u}`}return{type:"create",apiConfig:{name:l},request:a,parseResponse:u=>{let c=u;if(c?.name)return{name:c.name,expiresAt:c.expireTime,tokenCount:c.usageMetadata?.totalTokenCount}}}};buildCacheUpdateTTLOp=(e,t)=>{let n={ttl:`${t}s`},r=`/${e}`;if(!this.isVertex&&this.apiKey){let o=typeof this.apiKey=="function"?"ASYNC_KEY":this.apiKey;r+=`?key=${o}`}return{type:"update",apiConfig:{name:r,headers:{"Content-Type":"application/json"}},request:n,parseResponse:o=>{let s=o;if(s?.name)return{name:s.name,expiresAt:s.expireTime,tokenCount:s.usageMetadata?.totalTokenCount}}}};buildCacheDeleteOp=e=>{let t=`/${e}`;if(!this.isVertex&&this.apiKey){let n=typeof this.apiKey=="function"?"ASYNC_KEY":this.apiKey;t+=`?key=${n}`}return{type:"delete",apiConfig:{name:t,headers:{"Content-Type":"application/json"}},request:{},parseResponse:()=>{}}};prepareCachedChatReq=async(e,t,n)=>{let r=e.model,o=e.modelConfig?.stream??this.config.stream,{dynamicContents:s,dynamicSystemInstruction:a}=this.extractDynamicContent(e.chatPrompt),l;if(this.endpointId?l={name:o?`/${this.endpointId}:streamGenerateContent?alt=sse`:`/${this.endpointId}:generateContent`}:l={name:o?`/models/${r}:streamGenerateContent?alt=sse`:`/models/${r}:generateContent`},!this.isVertex){let d=o?"&":"?",m=typeof this.apiKey=="function"?await this.apiKey():this.apiKey;l.name+=`${d}key=${m}`}let u={maxOutputTokens:e.modelConfig?.maxTokens??this.config.maxTokens,...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{topP:e.modelConfig.topP}:{},topK:e.modelConfig?.topK??this.config.topK,frequencyPenalty:e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,candidateCount:1,stopSequences:e.modelConfig?.stopSequences??this.config.stopSequences,responseMimeType:"text/plain"},c=this.config.safetySettings,p={contents:s,cachedContent:n,generationConfig:u,safetySettings:c};return a&&(p.systemInstruction=a),{apiConfig:l,request:p}};extractCacheableContent(e){let t,n=[];for(let r of e){if(r.role==="system"){t={role:"user",parts:[{text:r.content}]};continue}if("cache"in r&&r.cache)if(r.role==="user"){let o=[];if(typeof r.content=="string")o.push({text:r.content});else if(Array.isArray(r.content)){for(let s of r.content)if("cache"in s&&s.cache)switch(s.type){case"text":o.push({text:s.text});break;case"image":o.push({inlineData:{mimeType:s.mimeType,data:s.image}});break;case"audio":o.push({inlineData:{mimeType:`audio/${s.format??"mp3"}`,data:s.data}});break;case"file":"fileUri"in s?o.push({fileData:{mimeType:s.mimeType,fileUri:s.fileUri}}):o.push({inlineData:{mimeType:s.mimeType,data:s.data}});break}}o.length>0&&n.push({role:"user",parts:o})}else r.role==="assistant"&&r.content&&n.push({role:"model",parts:[{text:r.content}]})}return{systemInstruction:t,contents:n}}extractDynamicContent(e){let n=[];for(let r of e)if(r.role!=="system"&&!("cache"in r&&r.cache))if(r.role==="user"){let o=[];if(typeof r.content=="string")o.push({text:r.content});else if(Array.isArray(r.content)){for(let s of r.content)if(!("cache"in s&&s.cache))switch(s.type){case"text":o.push({text:s.text});break;case"image":o.push({inlineData:{mimeType:s.mimeType,data:s.image}});break;case"audio":o.push({inlineData:{mimeType:`audio/${s.format??"mp3"}`,data:s.data}});break;case"file":"fileUri"in s?o.push({fileData:{mimeType:s.mimeType,fileUri:s.fileUri}}):o.push({inlineData:{mimeType:s.mimeType,data:s.data}});break}}o.length>0&&n.push({role:"user",parts:o})}else if(r.role==="assistant"){let o=[];if(r.content&&o.push({text:r.content}),r.functionCalls)for(let s of r.functionCalls){let a;if(typeof s.function.params=="string")try{a=JSON.parse(s.function.params)}catch{a={}}else a=s.function.params??{};o.push({functionCall:{name:s.function.name,args:a}})}o.length>0&&n.push({role:"model",parts:o})}else r.role==="function"&&n.push({role:"user",parts:[{functionResponse:{name:r.functionId,response:{result:r.result}}}]});return{dynamicContents:n,dynamicSystemInstruction:void 0}}},en=class i extends we{static create(e){return new i(e)}constructor({apiKey:e,projectId:t,region:n,endpointId:r,config:o,options:s,models:a,modelInfo:l}){let u=t!==void 0&&n!==void 0,c,p;if(u){if(!e)throw new Error("GoogleGemini Vertex API key not set");if(typeof e!="function")throw new Error("GoogleGemini Vertex API key must be a function for token-based authentication");let f;r?f="endpoints":f="publishers/google",c=`https://${n==="global"?"aiplatform":`${n}-aiplatform`}.googleapis.com/v1/projects/${t}/locations/${n}/${f}`,p=async()=>({Authorization:`Bearer ${typeof e=="function"?await e():e}`})}else{if(!e)throw new Error("GoogleGemini AI API key not set");c="https://generativelanguage.googleapis.com/v1beta",p=async()=>({})}let d={...Bs(),...o},m=new Us(d,u,r,e,s);l=[...Zr,...l??[]];let g=f=>{let x=Je({model:f,modelInfo:l,models:a});return{functions:!0,streaming:!0,hasThinkingBudget:x?.supported?.thinkingBudget??!1,hasShowThoughts:x?.supported?.showThoughts??!1,structuredOutputs:x?.supported?.structuredOutputs??!1,media:{images:{supported:!0,formats:["image/jpeg","image/png","image/gif","image/webp"],maxSize:20*1024*1024,detailLevels:["high","low","auto"]},audio:{supported:!0,formats:["wav","mp3","aac","ogg"],maxDuration:9.5*60},files:{supported:!0,formats:["application/pdf","text/plain","text/csv","text/html","text/xml"],maxSize:2*1024*1024*1024,uploadMethod:"cloud"},urls:{supported:!0,webSearch:!0,contextFetching:!0}},caching:{supported:m.supportsContextCache(f),types:["persistent"]},thinking:x?.supported?.thinkingBudget??!1,multiTurn:!0}},h=a?.map(f=>{let x=f,A=x?.config;if(!A)return f;let y={};A.maxTokens!==void 0&&(y.maxTokens=A.maxTokens),A.temperature!==void 0&&(y.temperature=A.temperature),A.topP!==void 0&&(y.topP=A.topP),A.topK!==void 0&&(y.topK=A.topK),A.presencePenalty!==void 0&&(y.presencePenalty=A.presencePenalty),A.frequencyPenalty!==void 0&&(y.frequencyPenalty=A.frequencyPenalty),A.stopSequences!==void 0&&(y.stopSequences=A.stopSequences),A.endSequences!==void 0&&(y.endSequences=A.endSequences),A.stream!==void 0&&(y.stream=A.stream),A.n!==void 0&&(y.n=A.n);let b={...x};Object.keys(y).length>0&&(b.modelConfig={...x.modelConfig??{},...y});let S=A.thinking?.thinkingTokenBudget;if(typeof S=="number"){let w=d.thinkingTokenBudgetLevels,M=[["minimal",w?.minimal??200],["low",w?.low??800],["medium",w?.medium??5e3],["high",w?.high??1e4],["highest",w?.highest??24500]],R="minimal",k=Number.POSITIVE_INFINITY;for(let[F,E]of M){let T=Math.abs(S-E);T<k&&(k=T,R=F)}b.thinkingTokenBudget=R}return A.thinking?.includeThoughts!==void 0&&(b.showThoughts=!!A.thinking.includeThoughts),b});super(m,{name:"GoogleGeminiAI",apiURL:c,headers:p,modelInfo:l,defaults:{model:d.model,embedModel:d.embedModel},options:s,supportFor:g,models:h??a})}};var Dc=new Ue,tn=class{options;maxTokens;refillRate;currentTokens;lastRefillTime;constructor(e,t,n){this.maxTokens=e,this.refillRate=t,this.currentTokens=e,this.lastRefillTime=Date.now(),this.options=n}refillTokens(){let e=Date.now(),n=(e-this.lastRefillTime)/1e3*this.refillRate;this.currentTokens=Math.min(this.maxTokens,this.currentTokens+n),this.lastRefillTime=e}async waitUntilTokensAvailable(e){if(this.refillTokens(),this.currentTokens>=e){this.currentTokens-=e;return}return this.options?.debug&&console.log(Dc.red(`Rate limiter: Waiting for ${e-this.currentTokens} tokens`)),await new Promise(t=>setTimeout(t,100)),this.waitUntilTokensAvailable(e)}async acquire(e){await this.waitUntilTokensAvailable(e)}};var Qn=(r=>(r.Llama3_8B="llama3-8b-8192",r.Llama33_70B="llama-3.3-70b-versatile",r.Mixtral_8x7B="mixtral-8x7b-32768",r.Gemma2_9B="gemma2-9b-it",r))(Qn||{});var to=[{name:"gemma2-9b-it",currency:"usd",characterIsToken:!0,promptTokenCostPer1M:.2,completionTokenCostPer1M:.2},{name:"llama-3.3-70b-versatile",currency:"usd",characterIsToken:!0,promptTokenCostPer1M:.59,completionTokenCostPer1M:.79},{name:"llama3-8b-8192",currency:"usd",characterIsToken:!0,promptTokenCostPer1M:.05,completionTokenCostPer1M:.08},{name:"mixtral-8x7b-32768",currency:"usd",characterIsToken:!0,promptTokenCostPer1M:.24,completionTokenCostPer1M:.24}];var Gc=()=>structuredClone({model:"llama-3.3-70b-versatile",...se()}),nn=class extends Te{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("Groq API key not set");let s={...Gc(),...t},a={...n,streamingUsage:!1};o=[...to,...o??[]];let l={functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0};super({apiKey:e,config:s,options:a,modelInfo:o,apiURL:"https://api.groq.com/openai/v1",models:r,supportFor:l}),super.setName("Groq"),this.setOptions(a)}setOptions=e=>{let t=this.newRateLimiter(e);super.setOptions({...e,rateLimiter:t})};newRateLimiter=e=>{if(e?.rateLimiter)return e.rateLimiter;let t=e?.tokensPerMinute??4800,n=new tn(t,t/60,{debug:e?.debug});return async(o,s)=>{let a=s.modelUsage?.tokens?.totalTokens||0;return await n.acquire(a),await o()}}};var no=[];var ro=(e=>(e.MetaLlama270BChatHF="meta-llama/Llama-2-70b-chat-hf",e))(ro||{});var qs=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...se()}),el=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...Se()}),js=class{constructor(e){this.config=e}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,n:e.n,presencePenalty:e.presencePenalty}}createChatReq=e=>{let t=e.model,n=e.functions?`Functions:
170
170
  ${JSON.stringify(e.functions,null,2)}
171
171
  `:"",r=e.chatPrompt?.map(l=>{switch(l.role){case"user":return`User: ${l.content}`;case"system":return`System: ${l.content}`;case"function":return`Function Result: ${l.result}`;case"assistant":{let u=l.functionCalls?.map(c=>{let p=typeof c.function.params=="string"?c.function.params:JSON.stringify(c.function.params);return`${c.function.name}(${p})`}).join(`
172
172
  `);return u?`Assistant: ${l.content}
173
173
  Functions:
174
174
  ${u}`:`Assistant: ${l.content}`}default:throw new Error("Unknown role")}}).join(`
175
- `),o=`${n} ${r}`.trim(),i={name:"/models"},a={model:t,inputs:o,parameters:{max_new_tokens:e.modelConfig?.maxTokens??this.config.maxTokens,repetition_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty,...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{top_p:e.modelConfig.topP}:{},top_k:e.modelConfig?.topK??this.config.topK,return_full_text:this.config.returnFullText,num_return_sequences:this.config.n,do_sample:this.config.doSample,max_time:this.config.maxTime},options:{use_cache:this.config.useCache,wait_for_model:this.config.waitForModel}};return[i,a]};createChatResp=e=>({results:[{index:0,content:e.generated_text}]})},rn=class extends we{constructor({apiKey:e,config:t,options:n,models:r}){if(!e||e==="")throw new Error("HuggingFace API key not set");let o={...Bs(),...t},i=new Us(o);super(i,{name:"HuggingFace",apiURL:"https://api-inference.huggingface.co",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:to,defaults:{model:o.model},options:n,supportFor:{functions:!1,streaming:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0},models:r})}};var Zn=(l=>(l.Mistral7B="open-mistral-7b",l.Mistral8x7B="open-mixtral-8x7b",l.MistralSmall="mistral-small-latest",l.MistralNemo="mistral-nemo-latest",l.MistralLarge="mistral-large-latest",l.Codestral="codestral-latest",l.OpenCodestralMamba="open-codestral-mamba",l.OpenMistralNemo="open-mistral-nemo-latest",l))(Zn||{}),js=(e=>(e.MistralEmbed="mistral-embed",e))(js||{});var ro=[{name:"open-mistral-7b",currency:"USD",promptTokenCostPer1M:.25,completionTokenCostPer1M:.25},{name:"open-mixtral-8x7b",currency:"USD",promptTokenCostPer1M:.7,completionTokenCostPer1M:.7},{name:"mistral-nemo-latest",currency:"USD",promptTokenCostPer1M:.15,completionTokenCostPer1M:.15},{name:"mistral-small-latest",currency:"USD",promptTokenCostPer1M:.2,completionTokenCostPer1M:.6},{name:"mistral-large-latest",currency:"USD",promptTokenCostPer1M:2,completionTokenCostPer1M:6},{name:"codestral-latest",currency:"USD",promptTokenCostPer1M:.2,completionTokenCostPer1M:.6},{name:"open-codestral-mamba",currency:"USD",promptTokenCostPer1M:.25,completionTokenCostPer1M:.25},{name:"open-mistral-nemo-latest",currency:"USD",promptTokenCostPer1M:.3,completionTokenCostPer1M:.3}];var oo=()=>structuredClone({model:"mistral-small-latest",...ie(),topP:1}),Qa=()=>structuredClone({...oo(),model:"mistral-large-latest"}),on=class extends Te{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("Mistral API key not set");let i={...oo(),...t};o=[...ro,...o??[]];let a={functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0},l=u=>{let{max_completion_tokens:c,messages:p,...d}=u;return{...d,messages:this.updateMessages(p),max_tokens:c}};super({apiKey:e,config:i,options:n,apiURL:"https://api.mistral.ai/v1",modelInfo:o,models:r,supportFor:a,chatReqUpdater:l}),super.setName("Mistral")}updateMessages(e){let t=[];if(!Array.isArray(e))return e;for(let n of e)if(n.role==="user"&&Array.isArray(n.content)){let r=n.content.map(o=>typeof o=="object"&&o!==null&&"image_url"in o?{type:"image_url",image_url:{url:o.image_url?.url}}:o);t.push({...n,content:r})}else t.push(n);return t}};var so=class{constructor(e={}){this.config=e;this.config.id=this.config.id??Pe()}metrics={latency:{chat:{mean:0,p95:0,p99:0,samples:[]},embed:{mean:0,p95:0,p99:0,samples:[]}},errors:{chat:{count:0,rate:0,total:0},embed:{count:0,rate:0,total:0}}};getLastUsedChatModel(){return this.config.modelInfo?.name??"mock-model"}getLastUsedEmbedModel(){return this.config.embedModelInfo?.name??"mock-embed-model"}getLastUsedModelConfig(){return this.config.modelInfo?{maxTokens:this.config.modelInfo.maxTokens,temperature:.7,stream:this.config.features?.streaming??!1}:void 0}getName(){return this.config.name??"mock-ai-service"}getId(){return this.config.id??"mock-ai-service-id"}getFeatures(e){let t=this.config.features?.media;return{functions:this.config.features?.functions??!1,streaming:this.config.features?.streaming??!1,structuredOutputs:this.config.features?.structuredOutputs??!1,media:{images:{supported:t?.images?.supported??!1,formats:t?.images?.formats??[]},audio:{supported:t?.audio?.supported??!1,formats:t?.audio?.formats??[]},files:{supported:t?.files?.supported??!1,formats:t?.files?.formats??[],uploadMethod:t?.files?.uploadMethod??"none"},urls:{supported:t?.urls?.supported??!1,webSearch:t?.urls?.webSearch??!1,contextFetching:t?.urls?.contextFetching??!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}}getModelList(){return this.config.models}getMetrics(){return this.metrics}async chat(e,t){if(this.config.latencyMs&&await new Promise(n=>setTimeout(n,this.config.latencyMs)),this.config.shouldError)throw new Error(this.config.errorMessage??"Mock chat error");return this.updateMetrics("chat"),typeof this.config.chatResponse=="function"?await this.config.chatResponse(e):this.config.chatResponse??{results:[{index:0,content:"Mock response",finishReason:"stop"}],modelUsage:{ai:this.getName(),model:"mock-model",tokens:{promptTokens:10,completionTokens:5,totalTokens:15}}}}async embed(e,t){if(this.config.latencyMs&&await new Promise(n=>setTimeout(n,this.config.latencyMs)),this.config.shouldError)throw new Error(this.config.errorMessage??"Mock embed error");return this.updateMetrics("embed"),typeof this.config.embedResponse=="function"?this.config.embedResponse(e):this.config.embedResponse??{embeddings:[[.1,.2,.3]],modelUsage:{ai:this.getName(),model:"mock-model",tokens:{promptTokens:5,completionTokens:0,totalTokens:5}}}}setOptions(e){this.config.options=e}getOptions(){return this.config.options??{}}getLogger(){return this.config.options?.logger??(e=>{console.log(e)})}updateMetrics(e){let t=this.config.latencyMs??0;this.metrics.latency[e].samples.push(t);let n=this.metrics.latency[e].samples;if(this.metrics.latency[e].mean=n.reduce((r,o)=>r+o,0)/n.length,n.length>0){let r=[...n].sort((a,l)=>a-l),o=Math.max(0,Math.floor(r.length*.95)-1);this.metrics.latency[e].p95=r[o]??t;let i=Math.max(0,Math.floor(r.length*.99)-1);this.metrics.latency[e].p99=r[i]??t}if(this.config.shouldError){this.metrics.errors[e].count++,this.metrics.errors[e].total++;let r=this.metrics.latency[e].samples.length;this.metrics.errors[e].rate=r>0?this.metrics.errors[e].count/r:0}}};var io=class s{options;lastUsedService;services=new Map;constructor(e){if(e.length===0)throw new Error("No AI services provided.");for(let[t,n]of e.entries())if("key"in n){if(this.services.has(n.key))throw new Error(`Duplicate model key: ${n.key}`);let{service:o,description:i,isInternal:a}=n;this.services.set(n.key,{service:o,description:i,isInternal:a})}else{let o=n.getModelList();if(!o)throw new Error(`Service ${t} \`${n.getName()}\` has no model list.`);for(let i of o){if(this.services.has(i.key)){let a=this.services.get(i.key)?.service;throw new Error(`Service ${t} \`${n.getName()}\` has duplicate model key: ${i.key} as service ${a?.getName()}`)}if("model"in i&&typeof i.model)this.services.set(i.key,{description:i.description,service:n,model:i.model});else if("embedModel"in i&&i.embedModel)this.services.set(i.key,{description:i.description,service:n,embedModel:i.embedModel});else throw new Error(`Key ${i.key} in model list for service ${t} \`${n.getName()}\` is missing a model or embedModel property.`)}}}static create(e){return new s(e)}getLastUsedChatModel(){return this.lastUsedService?.getLastUsedChatModel()}getLastUsedEmbedModel(){return this.lastUsedService?.getLastUsedEmbedModel()}getLastUsedModelConfig(){return this.lastUsedService?.getLastUsedModelConfig()}async chat(e,t){let n=e.model;if(!n)throw new Error("Model key must be specified for multi-service");let r=this.services.get(n);if(!r)throw new Error(`No service found for model key: ${n}`);if(this.lastUsedService=r.service,!r.model){let{model:o,...i}=e;return await r.service.chat(i,t)}return await r.service.chat({model:n,...e},t)}async embed(e,t){let n=e.embedModel;if(!n)throw new Error("Embed model key must be specified for multi-service");let r=this.services.get(n);if(!r)throw new Error(`No service found for embed model key: ${n}`);if(this.lastUsedService=r.service,!r.model){let{embedModel:o,...i}=e;return await r.service.embed(i,t)}return await r.service.embed({embedModel:n,...e},t)}getId(){return`MultiServiceRouter:${Array.from(this.services.values()).map(e=>e.service.getId()).join(",")}`}getName(){return"MultiServiceRouter"}getModelList(){return Array.from(this.services).filter(([,e])=>!e.isInternal).map(([e,t])=>{if(t.model)return{key:e,description:t.description,model:t.model};if(t.embedModel)return{key:e,description:t.description,embedModel:t.embedModel};throw new Error(`Service ${e} has no model or embedModel`)})}getFeatures(e){if(e){let t=this.services.get(e);if(t)return t.service.getFeatures(e)}return{functions:!1,streaming:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}}getMetrics(){let e=this.lastUsedService;if(!e){let t=this.services.values().next().value;t&&(e="service"in t?t.service:t)}if(!e)throw new Error("No service available to get metrics.");return e.getMetrics()}setOptions(e){for(let t of this.services.values())t.service.setOptions(e);this.options=e}getOptions(){return this.options??{}}getLogger(){let e=this.lastUsedService;if(!e){let t=this.services.values().next().value;t&&(e=t.service)}if(!e)throw new Error("No service available to get logger.");return e.getLogger()}setServiceEntry(e,t){this.services.set(e,t)}};var zs=()=>structuredClone({...ie(),model:"nous-hermes2",embedModel:"all-minilm"}),Za=()=>structuredClone({...Se(),model:"nous-hermes2",embedModel:"all-minilm"}),sn=class extends Te{constructor({apiKey:e="not-set",url:t="http://localhost:11434/v1",config:n,options:r,models:o}){let i={...zs(),...n};super({apiKey:e,options:r,config:i,apiURL:t,models:o,modelInfo:[],supportFor:{functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}}),super.setName("Ollama")}};var $c=s=>["o1","o1-mini","o1-pro","o3","o3-mini","o3-pro","o4-mini"].includes(s),an=class{constructor(e,t,n){this.config=e;this.streamingUsage=t;this.responsesReqUpdater=n}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,stopSequences:e.stopSequences,topP:e.topP,stream:e.stream}}mapInternalContentToResponsesInput(e,t){let n=[];for(let r of e){if(r.type==="text"){t==="assistant"?n.push({type:"output_text",text:r.text}):n.push({type:"input_text",text:r.text});continue}if(t==="assistant")continue;if(r.type==="image"){let i=`data:${r.mimeType};base64,${r.image}`;n.push({type:"input_image",image_url:{url:i,details:r.details??"auto"}});continue}if(r.type==="audio"){n.push({type:"input_audio",input_audio:{data:r.data,format:r.format==="wav"?"wav":void 0}});continue}let o=r;throw new Error(`Unsupported content part: ${JSON.stringify(o)}`)}return n}createResponsesReqInternalInput(e,t=!1){let n=[];for(let r of e){if(t&&r.role==="system")continue;let o;if(r.role==="system"||r.role==="user"||r.role==="assistant"&&r.content)if(typeof r.content=="string")r.role==="system"?o=r.content:r.role==="assistant"?o=[{type:"output_text",text:r.content}]:o=[{type:"input_text",text:r.content}];else if(Array.isArray(r.content))o=this.mapInternalContentToResponsesInput(r.content,r.role==="assistant"?"assistant":"user");else{if(!(r.role==="assistant"&&!r.content&&r.functionCalls))throw new Error(`Invalid content type for role ${r.role}`);o=""}else r.role,o="";switch(r.role){case"system":n.push({type:"message",role:"system",content:o});break;case"user":n.push({type:"message",role:"user",content:o,name:r.name});break;case"assistant":if(r.content||r.functionCalls){let i={type:"message",role:"assistant",content:""};if(r.content&&(i.content=o),r.name&&(i.name=r.name),r.content&&n.push(i),r.functionCalls)for(let a of r.functionCalls)n.push({type:"function_call",call_id:a.id,name:a.function.name,arguments:typeof a.function.params=="object"?JSON.stringify(a.function.params):a.function.params||""})}break;case"function":n.push({type:"function_call_output",call_id:r.functionId,output:r.result});break;default:{let i=r.role;throw new Error(`Invalid role in chat prompt: ${i}`)}}}return n}createChatReq(e,t){let n=e.model,r={name:"/responses"},o=null,i=!1;if(e.chatPrompt){for(let x of e.chatPrompt)if(x.role==="system"&&typeof x.content=="string"){o=x.content,i=!0;break}}let a=o??this.config.systemPrompt??null,l=e.functions?.map(x=>({type:"function",name:x.name,description:x.description,parameters:x.parameters??{}})),u=[],c=$c(n),p=this.config.reasoningSummary;t?.showThoughts?p||(p="auto"):p=void 0;let d=this.config.reasoningEffort;if(t?.thinkingTokenBudget)switch(t.thinkingTokenBudget){case"none":d=void 0;break;case"minimal":d="minimal";break;case"low":d="medium";break;case"medium":case"high":case"highest":d="high";break}let m={model:n,input:"",instructions:a,tools:l?.length?l:void 0,tool_choice:e.functionCall==="none"||e.functionCall==="auto"||e.functionCall==="required"?e.functionCall:typeof e.functionCall=="object"&&e.functionCall.function?{type:"function",name:e.functionCall.function.name}:void 0,...c?{max_output_tokens:e.modelConfig?.maxTokens??this.config.maxTokens??void 0}:{...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{top_p:e.modelConfig.topP}:{},presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty??void 0,frequency_penalty:e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty??void 0,max_output_tokens:e.modelConfig?.maxTokens??this.config.maxTokens??void 0},stream:e.modelConfig?.stream??this.config.stream??!1,background:void 0,include:u.length>0?u:void 0,metadata:void 0,parallel_tool_calls:this.config.parallelToolCalls,previous_response_id:void 0,...d?{reasoning:{effort:d,summary:p}}:{},service_tier:this.config.serviceTier,store:this.config.store,text:void 0,truncation:void 0,user:this.config.user,seed:this.config.seed};this.config.user&&(m.user=this.config.user),this.config.parallelToolCalls!==void 0&&(m.parallel_tool_calls=this.config.parallelToolCalls),e.responseFormat?m.text={format:e.responseFormat.type==="json_schema"?{type:"json_schema",json_schema:e.responseFormat.schema}:{type:e.responseFormat.type}}:this.config.responseFormat&&(m.text={format:{type:this.config.responseFormat}}),this.config.seed&&(m.seed=this.config.seed);let g=e.chatPrompt?this.createResponsesReqInternalInput(e.chatPrompt,i):[];if(g.length>0)m.input=g;else if(e.chatPrompt&&e.chatPrompt.length===1&&e.chatPrompt[0]?.role==="user"&&e.chatPrompt[0]?.content&&typeof e.chatPrompt[0].content=="string"&&!a)m.input=e.chatPrompt[0].content;else if(g.length===0&&!a)throw new Error("Responses API request must have input or instructions.");let f=m.reasoning??{};if(this.config.reasoningEffort&&(f={...f,effort:this.config.reasoningEffort}),t?.thinkingTokenBudget)switch(t.thinkingTokenBudget){case"none":f={};break;case"minimal":f={...f,effort:"minimal"};break;case"low":f={...f,effort:"medium"};break;case"medium":case"high":case"highest":f={...f,effort:"high"};break}Object.keys(f).length>0&&f.effort?m.reasoning=f:m.reasoning=void 0;let h=m;return this.responsesReqUpdater&&(h=this.responsesReqUpdater(h)),[r,h]}createChatResp(e){let{id:t,output:n,usage:r}=e;r&&(this.tokensUsed={promptTokens:r.prompt_tokens,completionTokens:r.completion_tokens??r.output_tokens??0,totalTokens:r.total_tokens});let o={};for(let i of n??[])switch(i.type){case"message":o.id=i.id,o.content=qs(i.content,t),o.finishReason=i.status==="completed"?"stop":"content_filter",o.citations=ao(i.content);break;case"reasoning":o.id=i.id,i.encrypted_content?o.thought=i.encrypted_content:o.thought=i.summary.map(a=>typeof a=="object"?JSON.stringify(a):a).join(`
176
- `);break;case"file_search_call":o.id=i.id,o.functionCalls=[{id:i.id,type:"function",function:{name:"file_search",params:{queries:i.queries,results:i.results}}}],o.finishReason="function_call";break;case"web_search_call":o.id=i.id,o.functionCalls=[{id:i.id,type:"function",function:{name:"web_search",params:{queries:i.queries}}}],o.finishReason="function_call";break;case"computer_call":o.id=i.id,o.functionCalls=[{id:i.id,type:"function",function:{name:"computer_use",params:{action:i.action}}}],o.finishReason="function_call";break;case"code_interpreter_call":o.id=i.id,o.functionCalls=[{id:i.id,type:"function",function:{name:"code_interpreter",params:{code:i.code,results:i.results}}}],o.finishReason="function_call";break;case"image_generation_call":o.id=i.id,o.functionCalls=[{id:i.id,type:"function",function:{name:"image_generation",params:{result:i.result}}}],o.finishReason="function_call";break;case"local_shell_call":o.id=i.id,o.functionCalls=[{id:i.id,type:"function",function:{name:"local_shell",params:{action:i.action}}}],o.finishReason="function_call";break;case"mcp_call":o.id=i.id,o.functionCalls=[{id:i.id,type:"function",function:{name:"mcp",params:{name:i.name,args:i.args,serverLabel:i.server_label,output:i.output,error:i.error}}}],o.finishReason="function_call";break;case"function_call":o.id=i.id,o.functionCalls=[{id:i.id,type:"function",function:{name:i.name,params:i.arguments}}],o.finishReason="function_call";break}return{results:[{...o,index:0}],remoteId:t}}createChatStreamResp(e){let t=e,n={index:0,id:"",content:"",finishReason:"stop"},r;switch(t.type){case"response.created":case"response.in_progress":case"response.queued":r=t.response.id,n.id=`${t.response.id}_res_0`;break;case"response.output_item.added":switch(t.item.type){case"message":n.id=t.item.id,n.content=qs(t.item.content,t.item.id),n.citations=ao(t.item.content);break;case"function_call":n.id=t.item.id,n.functionCalls=[{id:t.item.id,type:"function",function:{name:t.item.name,params:t.item.arguments}}];break;case"file_search_call":{let o=t.item;n.id=t.item.id,n.functionCalls=[{id:o.id,type:"function",function:{name:"file_search",params:{queries:o.queries||[],results:o.results?.map(i=>({fileId:i.file_id,filename:i.filename,score:i.score,text:i.text,attributes:i.attributes}))}}}]}break;case"web_search_call":{let o=t.item;n.id=t.item.id,n.functionCalls=[{id:o.id,type:"function",function:{name:"web_search",params:{queries:o.queries||[]}}}]}break;case"computer_call":{let o=t.item;n.id=t.item.id,n.functionCalls=[{id:o.id,type:"function",function:{name:"computer_use",params:{action:o.action||{}}}}]}break;case"code_interpreter_call":{let o=t.item;n.id=t.item.id,n.functionCalls=[{id:o.id,type:"function",function:{name:"code_interpreter",params:{code:o.code||"",results:o.results}}}]}break;case"image_generation_call":{let o=t.item;n.id=t.item.id,n.functionCalls=[{id:o.id,type:"function",function:{name:"image_generation",params:{result:o.result}}}]}break;case"local_shell_call":{let o=t.item;n.id=t.item.id,n.functionCalls=[{id:o.id,type:"function",function:{name:"local_shell",params:{action:o.action||{}}}}]}break;case"mcp_call":{let o=t.item;n.id=t.item.id,n.functionCalls=[{id:o.id,type:"function",function:{name:"mcp",params:{name:o.name||"",args:o.args||"",serverLabel:o.server_label||"",output:o.output,error:o.error}}}]}break}break;case"response.content_part.added":n.id=t.item_id,n.content=qs([t.part],t.item_id),n.citations=ao([t.part]);break;case"response.output_text.delta":n.id=t.item_id,n.content=t.delta;break;case"response.output_text.done":break;case"response.function_call_arguments.delta":n.id=t.item_id,n.functionCalls=[{id:t.item_id,type:"function",function:{name:"",params:t.delta}}];break;case"response.reasoning_summary_text.delta":n.id=t.item_id,n.thought=t.delta;break;case"response.file_search_call.in_progress":case"response.file_search_call.searching":n.id=t.item_id,n.finishReason="function_call";break;case"response.file_search_call.completed":n.id=t.item_id,n.finishReason="function_call";break;case"response.web_search_call.in_progress":case"response.web_search_call.searching":n.id=t.item_id,n.finishReason="function_call";break;case"response.web_search_call.completed":n.id=t.item_id,n.finishReason="function_call";break;case"response.image_generation_call.in_progress":case"response.image_generation_call.generating":n.id=t.item_id,n.finishReason="function_call";break;case"response.image_generation_call.completed":n.id=t.item_id,n.finishReason="function_call";break;case"response.image_generation_call.partial_image":n.id=t.item_id,n.finishReason="function_call";break;case"response.mcp_call.in_progress":n.id=t.item_id,n.finishReason="function_call";break;case"response.mcp_call.arguments.delta":n.id=t.item_id,n.functionCalls=[{id:t.item_id,type:"function",function:{name:"",params:t.delta}}];break;case"response.mcp_call.arguments.done":n.id=t.item_id,n.functionCalls=[{id:t.item_id,type:"function",function:{name:"",params:t.arguments}}];break;case"response.mcp_call.completed":case"response.mcp_call.failed":n.id="mcp_call_event",n.finishReason="function_call";break;case"response.mcp_list_tools.in_progress":case"response.mcp_list_tools.completed":case"response.mcp_list_tools.failed":n.id="mcp_list_tools_event",n.finishReason="function_call";break;case"response.output_item.done":switch(t.item.type){case"message":if(n.id=t.item.id,n.finishReason=t.item.status==="completed"?"stop":"error",!n.citations||n.citations.length===0){let o=ao(t.item.content||[]);o&&(n.citations=o)}break;case"function_call":case"file_search_call":case"web_search_call":case"computer_call":case"code_interpreter_call":case"image_generation_call":case"local_shell_call":case"mcp_call":n.id=t.item.id,n.finishReason="function_call";break}break;case"response.completed":t.response.usage&&(this.tokensUsed={promptTokens:t.response.usage.prompt_tokens,completionTokens:t.response.usage.completion_tokens??t.response.usage.output_tokens??0,totalTokens:t.response.usage.total_tokens}),r=t.response.id,n.id=`${t.response.id}_completed`,n.finishReason="stop";break;case"response.failed":r=t.response.id,n.id=`${t.response.id}_failed`,n.finishReason="error";break;case"response.incomplete":r=t.response.id,n.id=`${t.response.id}_incomplete`,n.finishReason="length";break;case"error":n.id="error",n.content=`Error: ${t.message}`,n.finishReason="error";break;default:n.id="unknown";break}return{results:[n],remoteId:r}}createEmbedReq(e){let t=e.embedModel;if(!t)throw new Error("Embed model not set");if(!e.texts||e.texts.length===0)throw new Error("Embed texts is empty");let n={name:"/embeddings"},r={model:t,input:e.texts,dimensions:this.config.dimensions};return[n,r]}},qs=(s,e)=>{let t=s.filter(n=>n.type==="refusal");if(t.length>0){let n=t.map(r=>r.refusal).join(`
177
- `);throw new fe(n,void 0,e)}return s.filter(n=>n.type==="output_text").map(n=>n.text).join(`
178
- `)};function ao(s){let e=[];for(let t of s??[])if(t?.type==="output_text"&&Array.isArray(t.annotations))for(let n of t.annotations)n&&n.type==="url_citation"&&typeof n.url=="string"&&e.push({url:n.url,title:n.title,description:n.description});return e.length?e:void 0}var er=()=>({model:"gpt-4o",embedModel:"text-embedding-ada-002",temperature:.7,topP:1,stream:!0}),Xa=()=>({...er(),model:"gpt-4o",temperature:.5}),el=()=>({...er(),model:"gpt-4o",temperature:.9}),Xn=class extends we{constructor({apiKey:e,config:t,options:n,apiURL:r,modelInfo:o=[],models:i,responsesReqUpdater:a,supportFor:l={functions:!0,streaming:!0,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}}){if(!e||e==="")throw new Error("OpenAI API key not set");let u=new an(t,n?.streamingUsage??!0,a),c=i?.map(p=>{let d=p,m=d?.config;if(!m)return p;let g={};m.maxTokens!==void 0&&(g.maxTokens=m.maxTokens),m.temperature!==void 0&&(g.temperature=m.temperature),m.topP!==void 0&&(g.topP=m.topP),m.presencePenalty!==void 0&&(g.presencePenalty=m.presencePenalty),m.frequencyPenalty!==void 0&&(g.frequencyPenalty=m.frequencyPenalty);let f=m.stopSequences??m.stop;f!==void 0&&(g.stopSequences=f),m.n!==void 0&&(g.n=m.n),m.stream!==void 0&&(g.stream=m.stream);let h={...d};Object.keys(g).length>0&&(h.modelConfig={...d.modelConfig??{},...g});let x=m?.thinking?.thinkingTokenBudget;if(typeof x=="number"){let A=[["minimal",200],["low",800],["medium",5e3],["high",1e4],["highest",24500]],y="minimal",b=Number.POSITIVE_INFINITY;for(let[k,S]of A){let M=Math.abs(x-S);M<b&&(b=M,y=k)}h.thinkingTokenBudget=y}return m?.thinking?.includeThoughts!==void 0&&(h.showThoughts=!!m.thinking.includeThoughts),h});super(u,{name:"OpenAI",apiURL:r||"https://api.openai.com/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:o,defaults:{model:t.model??"gpt-4o",embedModel:t.embedModel??"text-embedding-ada-002"},options:n,supportFor:l,models:c??i})}},ln=class extends Xn{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("OpenAI API key not set");o=[...Ur,...o??[]];let i=a=>{let l=We({model:a,modelInfo:o,models:r});return{functions:!0,streaming:!0,hasThinkingBudget:l?.supported?.thinkingBudget??!1,hasShowThoughts:l?.supported?.showThoughts??!1,structuredOutputs:l?.supported?.structuredOutputs??!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}};super({apiKey:e,config:{...er(),...t},options:n,modelInfo:o,models:r,supportFor:i})}};var Hs=()=>structuredClone({model:"openrouter/auto",...ie()}),un=class extends Te{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o,referer:i,title:a}){if(!e||e==="")throw new Error("OpenRouter API key not set");let l={...Hs(),...t},u={functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0},c=o??[];super({apiKey:e,config:l,options:n,apiURL:"https://openrouter.ai/api/v1",modelInfo:c,models:r,supportFor:u}),super.setName("OpenRouter"),super.setHeaders(async()=>{let p={Authorization:`Bearer ${e}`};return i&&(p["HTTP-Referer"]=i),a&&(p["X-Title"]=a),p})}};async function lo(s,e,t={}){if(typeof s=="string")return[{type:"text",text:s}];if(!Array.isArray(s))return[{type:"text",text:String(s)}];let n=e.getFeatures(),r=[];for(let o of s)try{switch(o.type){case"text":r.push({type:"text",text:o.text});break;case"image":if(n.media.images.supported)o.altText?r.push({type:"text",text:`[Image: ${o.altText}]`}):r.push({type:"text",text:"[Image content]"});else if(o.altText)r.push({type:"text",text:o.altText});else if(t.imageToText)try{let i=await t.imageToText(o.image);r.push({type:"text",text:i})}catch(i){throw new st(i,"image","vision analysis")}else switch(t.fallbackBehavior){case"error":throw new Qe("Images",e.getName(),!1);case"skip":continue;default:r.push({type:"text",text:"[Image content not supported by this provider]"})}break;case"audio":if(n.media.audio.supported)o.transcription?r.push({type:"text",text:o.transcription}):r.push({type:"text",text:"[Audio content]"});else if(o.transcription)r.push({type:"text",text:o.transcription});else if(t.audioToText)try{let i=await t.audioToText(o.data,o.format);r.push({type:"text",text:i})}catch(i){throw new st(i,"audio","transcription")}else switch(t.fallbackBehavior){case"error":throw new Qe("Audio",e.getName(),!1);case"skip":continue;case"degrade":r.push({type:"text",text:"[Audio content not supported by this provider]"})}break;case"file":if(n.media.files.supported)o.extractedText?r.push({type:"text",text:o.extractedText}):r.push({type:"text",text:`[File: ${o.filename}]`});else if(o.extractedText)r.push({type:"text",text:o.extractedText});else if(t.fileToText)try{let i=await t.fileToText(o.data,o.mimeType);r.push({type:"text",text:i})}catch(i){throw new st(i,"file","text extraction")}else switch(t.fallbackBehavior){case"error":throw new Qe("Files",e.getName(),!1);case"skip":continue;default:r.push({type:"text",text:`[File: ${o.filename} - content not accessible by this provider]`})}break;case"url":if(n.media.urls.supported)o.cachedContent?r.push({type:"text",text:o.cachedContent}):r.push({type:"text",text:`[Link: ${o.url}${o.title?` - ${o.title}`:""}]`});else if(o.cachedContent)r.push({type:"text",text:o.cachedContent});else if(t.urlToText)try{let i=await t.urlToText(o.url);r.push({type:"text",text:i})}catch(i){throw new st(i,"url","content fetching")}else switch(t.fallbackBehavior){case"error":throw new Qe("URLs",e.getName(),!1);case"skip":continue;case"degrade":r.push({type:"text",text:`[Link: ${o.url}${o.title?` - ${o.title}`:""}]`})}break;default:typeof o=="object"&&o.text?r.push({type:"text",text:o.text}):r.push({type:"text",text:String(o)})}}catch(i){throw i instanceof Qe||i instanceof st?i:new st(i,o.type||"unknown","content processing")}return r}function tl(s){let e=!1,t=!1,n=!1,r=!1;for(let o of s)if(o.role==="user"&&Array.isArray(o.content))for(let i of o.content)switch(i.type){case"image":e=!0;break;case"audio":t=!0;break;case"file":n=!0;break;case"url":r=!0;break}return{hasImages:e,hasAudio:t,hasFiles:n,hasUrls:r}}var tr=(n=>(n.RekaCore="reka-core",n.RekaFlash="reka-flash",n.RekaEdge="reka-edge",n))(tr||{});var uo=[{name:"reka-core",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15},{name:"reka-flash",currency:"usd",promptTokenCostPer1M:.8,completionTokenCostPer1M:2},{name:"reka-edge",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1}];var nr=()=>structuredClone({model:"reka-core",...ie()}),rl=()=>structuredClone({...nr(),model:"reka-core"}),ol=()=>structuredClone({model:"reka-core",...Se()}),sl=()=>({...nr(),model:"reka-flash"}),Ks=class{constructor(e){this.config=e}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,topP:e.topP,n:e.n,stream:e.stream}}createChatReq=e=>{let t=e.model;if(!e.chatPrompt||e.chatPrompt.length===0)throw new Error("Chat prompt is empty");let n={name:"/chat/completions"},r=Nc(e),o=e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,i=e.modelConfig?.stream??this.config.stream,a={model:t,messages:r,max_tokens:e.modelConfig?.maxTokens??this.config.maxTokens,...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},top_k:e.modelConfig?.n??this.config.n,...e.modelConfig?.topP!==void 0?{top_p:e.modelConfig.topP}:{},stop:e.modelConfig?.stopSequences??this.config.stop,presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty,...o?{frequency_penalty:o}:{},...i?{stream:!0}:{}};return[n,a]};createChatResp=e=>{let{id:t,usage:n,responses:r}=e;return this.tokensUsed=n?{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.input_tokens+n.output_tokens}:void 0,{results:r.map((i,a)=>{let l=nl(i.finish_reason),u;return typeof i.message.content=="string"?u=i.message.content:u=i.message.content.text,{index:a,id:`${t}`,content:u,finishReason:l}}),remoteId:t}};createChatStreamResp=e=>{let{id:t,usage:n,responses:r}=e;return this.tokensUsed=n?{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.input_tokens+n.output_tokens}:void 0,{results:r.map((i,a)=>{let l=nl(i.finish_reason),u;return typeof i.chunk.content=="string"?u=i.chunk.content:u=i.chunk.content.text,{index:a,id:`${t}`,content:u,finishReason:l}})}}},nl=s=>{switch(s){case"stop":return"stop";case"context":return"length";case"length":return"length"}};function Nc(s){return s.chatPrompt.map(e=>{switch(e.role){case"system":return{role:"user",content:e.content};case"user":return Array.isArray(e.content)?{role:"user",content:e.content.map(t=>{switch(t.type){case"text":return{type:"text",text:t.text};case"image":throw new Error("Image type not supported");default:throw new Error("Invalid content type")}})}:{role:"user",content:e.content};case"assistant":if(Array.isArray(e.content))return{role:"assistant",content:e.content.map(t=>{switch(t.type){case"text":return{type:"text",text:t.text};case"image":throw new Error("Image type not supported");default:throw new Error("Invalid content type")}})};if(!e.content)throw new Error("Assistant content is empty");return{role:"user",content:e.content};default:throw new Error("Invalid role")}})}var cn=class extends we{constructor({apiKey:e,config:t,options:n,apiURL:r,modelInfo:o=uo,models:i}){if(!e||e==="")throw new Error("Reka API key not set");let a={...nr(),...t},l=new Ks(a);super(l,{name:"Reka",apiURL:r||"https://api.reka.ai/v1/chat",headers:async()=>({"X-Api-Key":e}),modelInfo:o,defaults:{model:a.model},options:n,supportFor:{functions:!0,streaming:!0,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0},models:i})}};var co=class{providers;processingServices;config;constructor(e){this.providers=[e.providers.primary,...e.providers.alternatives],this.processingServices=e.processing,this.config=e.routing}async chat(e,t={}){let n=await this.selectProviderWithDegradation(e,t.routingOptions||{}),r=await this.preprocessRequest(e,n.provider,t.processingOptions);try{return{response:await n.provider.chat(r,t),routing:n}}catch(o){if(o instanceof Qe&&t.fallbackProviders?.length)return await this.tryFallbackProviders(e,t.fallbackProviders,t);throw o}}async preprocessRequest(e,t,n){let r={...n,fallbackBehavior:n?.fallbackBehavior||"degrade",imageToText:n?.imageToText||this.processingServices.imageToText,audioToText:n?.audioToText||this.processingServices.audioToText,fileToText:n?.fileToText||this.processingServices.fileToText,urlToText:n?.urlToText||this.processingServices.urlToText},o=[];for(let i of e.chatPrompt)if(i.role==="user"&&Array.isArray(i.content)){let a=await lo(i.content,t,r);a.every(u=>u.type==="text")&&a.length===1?o.push({...i,content:a[0].text}):o.push({...i,content:a.map(u=>({type:"text",text:u.text}))})}else o.push(i);return{...e,chatPrompt:o}}async selectProviderWithDegradation(e,t){let n=_t(e),r=[],o=[],i=[];try{let a=Kr(e,this.providers,{requireExactMatch:t.requireExactMatch??this.config.capability.requireExactMatch,allowDegradation:t.allowDegradation??this.config.capability.allowDegradation}),l=a.getFeatures();return n.hasImages&&!l.media.images.supported&&(o.push("Images will be converted to text descriptions"),r.push("Image-to-text conversion")),n.hasAudio&&!l.media.audio.supported&&(o.push("Audio will be transcribed to text"),r.push("Audio-to-text transcription")),n.hasFiles&&!l.media.files.supported&&(o.push("File content will be extracted to text"),r.push("File-to-text extraction")),n.hasUrls&&!l.media.urls.supported&&(o.push("URL content will be pre-fetched"),r.push("URL content fetching")),n.requiresStreaming&&!l.streaming&&i.push("Streaming not supported - will use non-streaming mode"),n.requiresCaching&&!l.caching.supported&&i.push("Content caching not supported"),{provider:a,processingApplied:r,degradations:o,warnings:i}}catch(a){throw new Error(`Provider selection failed: ${a instanceof Error?a.message:"Unknown error"}`)}}async tryFallbackProviders(e,t,n){for(let r of t)try{let o={provider:r,processingApplied:["Fallback provider selection"],degradations:["Using fallback provider due to primary provider failure"],warnings:[]},i=await this.preprocessRequest(e,r,{fallbackBehavior:"degrade"});return{response:await r.chat(i,n),routing:o}}catch{}throw new Error("All fallback providers failed")}async getRoutingRecommendation(e){return await this.selectProviderWithDegradation(e,{})}async validateRequest(e){let t=_t(e),n=[],r=[];try{let o=await this.selectProviderWithDegradation(e,{});return o.degradations.length>0&&(n.push(...o.degradations),r.push("Consider using a provider that natively supports all media types")),o.warnings.length>0&&n.push(...o.warnings),t.hasImages&&this.processingServices.imageToText===void 0&&(this.providers.some(a=>a.getFeatures().media.images.supported)||(n.push("No image processing service available and no providers support images"),r.push("Add imageToText processing service or use image-capable provider"))),t.hasAudio&&this.processingServices.audioToText===void 0&&(this.providers.some(a=>a.getFeatures().media.audio.supported)||(n.push("No audio processing service available and no providers support audio"),r.push("Add audioToText processing service or use audio-capable provider"))),{canHandle:n.length===0||o.degradations.length>0,issues:n,recommendations:r}}catch(o){return{canHandle:!1,issues:[`Cannot route request: ${o instanceof Error?o.message:"Unknown error"}`],recommendations:["Add more providers or processing services to handle this request"]}}}getRoutingStats(){let e={};for(let t of this.providers){let n=t.getFeatures(),r=t.getName();n.functions&&(e.Functions=e.Functions||[],e.Functions.push(r)),n.streaming&&(e.Streaming=e.Streaming||[],e.Streaming.push(r)),n.media.images.supported&&(e.Images=e.Images||[],e.Images.push(r)),n.media.audio.supported&&(e.Audio=e.Audio||[],e.Audio.push(r)),n.media.files.supported&&(e.Files=e.Files||[],e.Files.push(r)),n.media.urls.supported&&(e.URLs=e.URLs||[],e.URLs.push(r)),n.caching.supported&&(e.Caching=e.Caching||[],e.Caching.push(r))}return{totalProviders:this.providers.length,capabilityMatrix:e,recommendedProvider:this.providers[0]?.getName()||"None"}}};var po=[];var Vs=()=>structuredClone({model:"mistralai/Mixtral-8x7B-Instruct-v0.1",...ie()}),pn=class extends Te{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("Together API key not set");let i={...Vs(),...t};o=[...po,...o??[]];let a={functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0};super({apiKey:e,config:i,options:n,apiURL:"https://api.together.xyz/v1",modelInfo:o,models:r,supportFor:a}),super.setName("Together")}};var rr=(d=>(d.Llama31_8B_Instruct="Llama-3.1-8B-Instruct-q4f32_1-MLC",d.Llama31_70B_Instruct="Llama-3.1-70B-Instruct-q4f16_1-MLC",d.Llama32_1B_Instruct="Llama-3.2-1B-Instruct-q4f32_1-MLC",d.Llama32_3B_Instruct="Llama-3.2-3B-Instruct-q4f32_1-MLC",d.Mistral7B_Instruct="Mistral-7B-Instruct-v0.3-q4f32_1-MLC",d.Phi35_Mini_Instruct="Phi-3.5-mini-instruct-q4f32_1-MLC",d.Gemma2_2B_Instruct="gemma-2-2b-it-q4f32_1-MLC",d.Gemma2_9B_Instruct="gemma-2-9b-it-q4f32_1-MLC",d.Qwen2_5_0_5B_Instruct="Qwen2.5-0.5B-Instruct-q4f32_1-MLC",d.Qwen2_5_1_5B_Instruct="Qwen2.5-1.5B-Instruct-q4f32_1-MLC",d.Qwen2_5_3B_Instruct="Qwen2.5-3B-Instruct-q4f32_1-MLC",d.Qwen2_5_7B_Instruct="Qwen2.5-7B-Instruct-q4f32_1-MLC",d))(rr||{});var mo=[{name:"Llama-3.1-8B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:4096},{name:"Llama-3.1-70B-Instruct-q4f16_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:4096,isExpensive:!0},{name:"Llama-3.2-1B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:2048},{name:"Llama-3.2-3B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:2048},{name:"Mistral-7B-Instruct-v0.3-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:4096},{name:"Phi-3.5-mini-instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:4096},{name:"gemma-2-2b-it-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:8192,maxTokens:2048},{name:"gemma-2-9b-it-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:8192,maxTokens:2048},{name:"Qwen2.5-0.5B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:2048},{name:"Qwen2.5-1.5B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:2048},{name:"Qwen2.5-3B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:2048},{name:"Qwen2.5-7B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:4096}];var Js=()=>structuredClone({model:"Llama-3.2-3B-Instruct-q4f32_1-MLC",...ie()}),il=()=>structuredClone({model:"Llama-3.2-3B-Instruct-q4f32_1-MLC",...Se()}),Ws=class{constructor(e,t){this.config=e;this.engine=t}tokensUsed;engine;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,endSequences:e.endSequences,stream:e.stream,n:e.n}}createChatReq(e){let t=e.model,n=e.chatPrompt.map(a=>{if(a.role==="function")return{role:"function",name:a.functionId,content:typeof a.result=="string"?a.result:JSON.stringify(a.result)};let l="";typeof a.content=="string"?l=a.content:Array.isArray(a.content)&&(l=a.content.filter(c=>c.type==="text").map(c=>c.text).join(`
179
- `));let u={role:a.role,content:l};return a.role==="assistant"&&a.functionCalls?.length?{...u,tool_calls:a.functionCalls.map(c=>({id:c.id,type:"function",function:{name:c.function.name,arguments:typeof c.function.params=="string"?c.function.params:JSON.stringify(c.function.params||{})}}))}:u}),r=e.functions?.map(a=>({type:"function",function:{name:a.name,description:a.description,parameters:a.parameters||{type:"object",properties:{}}}})),o={name:"/chat/completions",localCall:async(a,l)=>{try{let u=await this.engine.chat.completions.create({...a,stream:l||!1});return l?new ReadableStream({async start(c){try{for await(let p of u)c.enqueue(p);c.close()}catch(p){c.error(p)}}}):u}catch(u){throw new Error(`WebLLM API error: ${u}`)}}},i={model:t,messages:n,...r?.length?{tools:r}:{},max_tokens:e.modelConfig?.maxTokens??this.config.maxTokens,...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{top_p:e.modelConfig.topP}:{},presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty,frequency_penalty:e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,stop:e.modelConfig?.stopSequences??this.config.stopSequences,stream:e.modelConfig?.stream??this.config.stream,n:e.modelConfig?.n??this.config.n};return[o,i]}createEmbedReq=e=>{throw new Error("WebLLM does not support embeddings")};createChatResp=e=>(this.tokensUsed={promptTokens:e.usage?.prompt_tokens??0,completionTokens:e.usage?.completion_tokens??0,totalTokens:e.usage?.total_tokens??0},{results:e.choices.map((n,r)=>{let o="stop";switch(n.finish_reason){case"stop":o="stop";break;case"length":o="length";break;case"tool_calls":o="function_call";break;case"content_filter":o="content_filter";break;default:o="stop";break}let i=n.message.tool_calls?.map(a=>({id:a.id,type:"function",function:{name:a.function.name,params:a.function.arguments}}));return{index:r,id:e.id,content:n.message.content||"",functionCalls:i,finishReason:o}}),remoteId:e.id});createChatStreamResp=(e,t)=>{let n=t,r=e.choices[0];if(!r)throw new Error("No choice in WebLLM stream response");if(r.delta.content&&(n.content=(n.content||"")+r.delta.content),r.delta.tool_calls){n.toolCalls||(n.toolCalls=[]);for(let l of r.delta.tool_calls){let u=n.toolCalls[l.index];u?l.function?.arguments&&(u.function.arguments=(u.function?.arguments||"")+l.function.arguments):n.toolCalls[l.index]={id:l.id,type:l.type,function:{name:l.function?.name,arguments:l.function?.arguments||""}}}}e.usage&&(this.tokensUsed={promptTokens:e.usage.prompt_tokens,completionTokens:e.usage.completion_tokens,totalTokens:e.usage.total_tokens});let o;if(r.finish_reason)switch(r.finish_reason){case"stop":o="stop";break;case"length":o="length";break;case"tool_calls":o="function_call";break;case"content_filter":o="content_filter";break;default:o="stop";break}let i=n.toolCalls?.map(l=>({id:l.id||"",type:"function",function:{name:l.function?.name||"",params:l.function?.arguments||""}}));return{results:[{index:0,id:e.id,content:n.content||"",functionCalls:i,finishReason:o}],remoteId:e.id}};createEmbedResp(e){throw new Error("WebLLM does not support embeddings")}},dn=class extends we{constructor({engine:e,config:t,options:n,models:r}){if(!e)throw new Error("WebLLM engine instance is required");let o={...Js(),...t},i=new Ws(o,e);super(i,{name:"WebLLM",apiURL:void 0,headers:async()=>({}),modelInfo:mo,defaults:{model:o.model},supportFor:a=>({functions:!0,streaming:!0,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}),options:n,models:r})}};var or=(r=>(r.Grok3="grok-3",r.Grok3Mini="grok-3-mini",r.Grok3Fast="grok-3-fast",r.Grok3MiniFast="grok-3-mini-fast",r))(or||{}),Ys=(e=>(e.GrokEmbedSmall="grok-embed-small",e))(Ys||{});var go=[{name:"grok-3",currency:"USD",promptTokenCostPer1M:3,completionTokenCostPer1M:15},{name:"grok-3-mini",currency:"USD",promptTokenCostPer1M:.3,completionTokenCostPer1M:.5,supported:{thinkingBudget:!0}},{name:"grok-3-fast",currency:"USD",promptTokenCostPer1M:5,completionTokenCostPer1M:25},{name:"grok-3-mini-fast",currency:"USD",promptTokenCostPer1M:.6,completionTokenCostPer1M:4,supported:{thinkingBudget:!0}}];var ho=()=>structuredClone({model:"grok-3-mini",...ie()}),al=()=>structuredClone({...ho(),model:"grok-3"}),mn=class extends Te{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("Grok API key not set");let i={...ho(),...t};o=[...go,...o??[]];let a=u=>{let c=We({model:u,modelInfo:o,models:r});return{functions:!0,streaming:!0,hasThinkingBudget:c?.supported?.thinkingBudget??!1,hasShowThoughts:c?.supported?.showThoughts??!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}},l=u=>{if(n?.searchParameters){let c=n.searchParameters;return{...u,search_parameters:{mode:c.mode,return_citations:c.returnCitations,from_date:c.fromDate,to_date:c.toDate,max_search_results:c.maxSearchResults,sources:c.sources?.map(p=>({type:p.type,country:p.country,excluded_websites:p.excludedWebsites,allowed_websites:p.allowedWebsites,safe_search:p.safeSearch,x_handles:p.xHandles,links:p.links}))}}}return u};super({apiKey:e,config:i,options:n,apiURL:"https://api.x.ai/v1",modelInfo:o,models:r,supportFor:a,chatReqUpdater:l}),super.setName("Grok")}};function ll(s){return sr.create(s)}var sr=class s{ai;static create(e){return new s(e)}constructor(e){switch(e.name){case"openai":this.ai=new Yt(e);break;case"openai-responses":this.ai=new ln(e);break;case"azure-openai":this.ai=new Qt(e);break;case"grok":this.ai=new mn(e);break;case"huggingface":this.ai=new rn(e);break;case"groq":this.ai=new nn(e);break;case"together":this.ai=new pn(e);break;case"openrouter":this.ai=new un(e);break;case"cohere":this.ai=new Zt(e);break;case"google-gemini":this.ai=new en(e);break;case"anthropic":this.ai=new Kt(e);break;case"mistral":this.ai=new on(e);break;case"deepseek":this.ai=new Xt(e);break;case"ollama":this.ai=new sn(e);break;case"reka":this.ai=new cn(e);break;case"webllm":this.ai=new dn(e);break;default:throw new Error("Unknown AI")}}getName(){return this.ai.getName()}getId(){return this.ai.getId()}getFeatures(e){return this.ai.getFeatures(e)}getModelList(){return this.ai.getModelList()}getLastUsedChatModel(){return this.ai.getLastUsedChatModel()}getLastUsedEmbedModel(){return this.ai.getLastUsedEmbedModel()}getLastUsedModelConfig(){return this.ai.getLastUsedModelConfig()}getMetrics(){return this.ai.getMetrics()}async chat(e,t){return await this.ai.chat(e,t)}async embed(e,t){return await this.ai.embed(e,t)}setOptions(e){this.ai.setOptions(e)}getOptions(){return this.ai.getOptions()}getLogger(){return this.ai.getLogger()}};var Ze=class{name;fetch;tracer;_upsert;_batchUpsert;_query;constructor({name:e,fetch:t,tracer:n}){this.name=e,this.fetch=t,this.tracer=n}async upsert(e,t){if(!this._upsert)throw new Error("upsert() not implemented");return this.tracer?await this.tracer.startActiveSpan("DB Upsert Request",{kind:Be.SERVER,attributes:{[Y.DB_SYSTEM]:this.name,[Y.DB_OPERATION_NAME]:"upsert",[Y.DB_TABLE]:e.table,[Y.DB_NAMESPACE]:e.namespace,[Y.DB_OPERATION_NAME]:t?"update":"insert"}},async n=>{try{return await this._upsert(e,t,{span:n})}finally{n.end()}}):await this._upsert(e,t)}async batchUpsert(e,t){if(!this._batchUpsert)throw new Error("batchUpsert() not implemented");if(e.length===0)throw new Error("Batch request is empty");if(!e[0])throw new Error("Batch request is invalid first element is undefined");return this.tracer?await this.tracer.startActiveSpan("DB Batch Upsert Request",{kind:Be.SERVER,attributes:{[Y.DB_SYSTEM]:this.name,[Y.DB_OPERATION_NAME]:"upsert",[Y.DB_TABLE]:e[0].table,[Y.DB_NAMESPACE]:e[0].namespace,[Y.DB_OPERATION_NAME]:t?"update":"insert"}},async n=>{try{return await this._batchUpsert(e,t,{span:n})}finally{n.end()}}):await this._batchUpsert(e,t)}async query(e){if(!this._query)throw new Error("query() not implemented");return this.tracer?await this.tracer.startActiveSpan("DB Query Request",{kind:Be.SERVER,attributes:{[Y.DB_SYSTEM]:this.name,[Y.DB_OPERATION_NAME]:"upsert",[Y.DB_TABLE]:e.table,[Y.DB_NAMESPACE]:e.namespace,[Y.DB_OPERATION_NAME]:"query"}},async t=>{try{return await this._query(e,{span:t})}finally{t.end()}}):await this._query(e)}};var Qs="https://api.cloudflare.com/client/v4/accounts/",gn=class extends Ze{apiKey;accountId;constructor({apiKey:e,accountId:t,fetch:n,tracer:r}){if(!e||!t)throw new Error("Cloudflare credentials not set");super({name:"Cloudflare",fetch:n,tracer:r}),this.apiKey=e,this.accountId=t}_upsert=async(e,t,n)=>{let r=await Ue({url:new URL(`${this.accountId}/vectorize/indexes/${e.table}/upsert`,Qs),headers:{"X-Auth-Key":this.apiKey},fetch:this.fetch,span:n?.span},{id:e.id,values:e.values,namespace:e.namespace,metadata:e.metadata});if(r.errors)throw new Error(`Cloudflare upsert failed: ${r.errors.map(({message:o})=>o).join(", ")}`);return{ids:r.result.ids}};batchUpsert=async(e,t,n)=>{if(t)throw new Error("Weaviate does not support batch update");if(e.length<1)throw new Error("Batch request is empty");if(!e[0]||!e[0].table)throw new Error("Table name is empty");let r=e[0].table,o=await Ue({url:new URL(`${this.accountId}/vectorize/indexes/${r}/upsert`,Qs),headers:{"X-Auth-Key":this.apiKey},fetch:this.fetch,span:n?.span},e.map(i=>({id:i.id,values:i.values,namespace:i.namespace,metadata:i.metadata})));if(o.errors)throw new Error(`Cloudflare batch upsert failed: ${o.errors.map(({message:i})=>i).join(", ")}`);return{ids:o.result.ids}};query=async(e,t)=>{let n=await Ue({url:new URL(`${this.accountId}/vectorize/indexes/${e.table}/query`,Qs),headers:{"X-Auth-Key":this.apiKey},fetch:this.fetch,span:t?.span},{vector:e.values,topK:e.limit||10,returnValues:!0});if(n.errors)throw new Error(`Cloudflare query failed: ${n.errors.map(({message:o})=>o).join(", ")}`);return{matches:n.result.matches.map(({id:o,score:i,values:a,metadata:l})=>({id:o,score:i,values:a,metadata:l}))}}};var Ot=class extends Ze{state;constructor({tracer:e}={}){super({name:"Memory",tracer:e}),this.state={}}_upsert=async(e,t,n)=>{if(!this.state[e.table])this.state[e.table]={[e.id]:e};else{let r=this.state[e.table];if(!r)throw new Error(`Table not found: ${e.table}`);r[e.id]=e}return{ids:[e.id]}};_batchUpsert=async(e,t,n)=>{let r=[];for(let o of e){let i=await this.upsert(o,t);r.push(...i.ids)}return{ids:r}};_query=async(e,t)=>{let n=this.state[e.table];if(!n)return{matches:[]};let r=[];return Object.entries(n).forEach(([o,i])=>{if(e.values&&i.values){let a=Dc(e.values,i.values);r.push({id:o,score:a,metadata:i.metadata})}}),r.sort((o,i)=>o.score-i.score),e.limit&&(r.length=e.limit),{matches:r}};getDB=()=>structuredClone(this.state);setDB=e=>{this.state=structuredClone(e)};clearDB=()=>{this.state={}}},Dc=(s,e)=>{if(s.length!==e.length)throw new Error("Vectors must be of the same length.");let t=0,n=0,r=0,o=!0,i=!0,a=new Float64Array(s),l=new Float64Array(e);for(let d=0;d<a.length;d++)t+=a[d]*l[d],n+=a[d]*a[d],r+=l[d]*l[d],a[d]!==0&&(o=!1),l[d]!==0&&(i=!1);if(o||i)return 1;let u=Math.sqrt(n),c=Math.sqrt(r);return 1-t/(u*c)};var Lc=s=>({namespace:s.namespace,topK:s.limit||10,filter:{},includeValues:!0,includeMetadata:!0,vector:s.values??[],id:s.id}),hn=class extends Ze{apiKey;apiURL;constructor({apiKey:e,host:t,fetch:n,tracer:r}){if(!e||e==="")throw new Error("Pinecone API key not set");super({name:"Pinecone",fetch:n,tracer:r}),this.apiKey=e,this.apiURL=t}_upsert=async(e,t,n)=>(await this._batchUpsert([e],t,n),{ids:[e.id]});_batchUpsert=async(e,t,n)=>{if(e.length===0)throw new Error("Batch request is empty");return await Ue({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/vectors/upsert",fetch:this.fetch,span:n?.span},e.map(({id:r,values:o=[],metadata:i})=>({id:r,values:o,metadata:i}))),{ids:e.map(({id:r})=>r)}};query=async(e,t)=>{if(e.text)throw new Error("Pinecone does not support text");return{matches:(await Ue({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/query",fetch:this.fetch,span:t?.span},Lc(e))).matches.map(({id:o,score:i,values:a,metadata:l})=>({id:o,score:i,metadata:l,values:a}))}}};var fn=class extends Ze{apiKey;apiURL;constructor({apiKey:e,host:t,fetch:n,tracer:r}){if(!e||e==="")throw new Error("Weaviate API key not set");super({name:"Weaviate",fetch:n,tracer:r}),this.apiKey=e,this.apiURL=t}_upsert=async(e,t,n)=>{let r=await Ue({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:`/v1/objects/${e.table}/${e.id}`,put:!!t,fetch:this.fetch,span:n?.span},{id:e.id,class:e.table,tenant:e.namespace,vector:e.values,properties:e.metadata??{}});if(r?.result?.errors)throw new Error(`Weaviate upsert failed: ${r.result.errors.error.map(({message:o})=>o).join(", ")}`);return{ids:[r.id]}};_batchUpsert=async(e,t,n)=>{if(t)throw new Error("Weaviate does not support batch update");if(e.length===0)throw new Error("Batch request is empty");let r=e.map(i=>({id:i.id,class:i.table,tenant:i.namespace,vector:i.values,properties:i.metadata??{}})),o=await Ue({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/v1/batch/objects",fetch:this.fetch,span:n?.span},{objects:r});if(o?.some(({result:i})=>i?.errors))throw new Error(`Weaviate batch upsert failed: ${o.map(({result:i})=>i?.errors?.error.map(({message:a})=>a).join(", ")).join(", ")}`);return{ids:o.map(({id:i})=>i)}};_query=async(e,t)=>{let n="";if(e.columns&&e.columns.length===0)throw new Error("Weaviate requires at least one column");if(e.values)n=`nearVector: {
175
+ `),o=`${n} ${r}`.trim(),s={name:"/models"},a={model:t,inputs:o,parameters:{max_new_tokens:e.modelConfig?.maxTokens??this.config.maxTokens,repetition_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty,...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{top_p:e.modelConfig.topP}:{},top_k:e.modelConfig?.topK??this.config.topK,return_full_text:this.config.returnFullText,num_return_sequences:this.config.n,do_sample:this.config.doSample,max_time:this.config.maxTime},options:{use_cache:this.config.useCache,wait_for_model:this.config.waitForModel}};return[s,a]};createChatResp=e=>({results:[{index:0,content:e.generated_text}]})},rn=class extends we{constructor({apiKey:e,config:t,options:n,models:r}){if(!e||e==="")throw new Error("HuggingFace API key not set");let o={...qs(),...t},s=new js(o);super(s,{name:"HuggingFace",apiURL:"https://api-inference.huggingface.co",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:no,defaults:{model:o.model},options:n,supportFor:{functions:!1,streaming:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0},models:r})}};var Xn=(l=>(l.Mistral7B="open-mistral-7b",l.Mistral8x7B="open-mixtral-8x7b",l.MistralSmall="mistral-small-latest",l.MistralNemo="mistral-nemo-latest",l.MistralLarge="mistral-large-latest",l.Codestral="codestral-latest",l.OpenCodestralMamba="open-codestral-mamba",l.OpenMistralNemo="open-mistral-nemo-latest",l))(Xn||{}),zs=(e=>(e.MistralEmbed="mistral-embed",e))(zs||{});var oo=[{name:"open-mistral-7b",currency:"USD",promptTokenCostPer1M:.25,completionTokenCostPer1M:.25},{name:"open-mixtral-8x7b",currency:"USD",promptTokenCostPer1M:.7,completionTokenCostPer1M:.7},{name:"mistral-nemo-latest",currency:"USD",promptTokenCostPer1M:.15,completionTokenCostPer1M:.15},{name:"mistral-small-latest",currency:"USD",promptTokenCostPer1M:.2,completionTokenCostPer1M:.6},{name:"mistral-large-latest",currency:"USD",promptTokenCostPer1M:2,completionTokenCostPer1M:6},{name:"codestral-latest",currency:"USD",promptTokenCostPer1M:.2,completionTokenCostPer1M:.6},{name:"open-codestral-mamba",currency:"USD",promptTokenCostPer1M:.25,completionTokenCostPer1M:.25},{name:"open-mistral-nemo-latest",currency:"USD",promptTokenCostPer1M:.3,completionTokenCostPer1M:.3}];var so=()=>structuredClone({model:"mistral-small-latest",...se(),topP:1}),tl=()=>structuredClone({...so(),model:"mistral-large-latest"}),on=class extends Te{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("Mistral API key not set");let s={...so(),...t};o=[...oo,...o??[]];let a={functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0},l=u=>{let{max_completion_tokens:c,messages:p,...d}=u;return{...d,messages:this.updateMessages(p),max_tokens:c}};super({apiKey:e,config:s,options:n,apiURL:"https://api.mistral.ai/v1",modelInfo:o,models:r,supportFor:a,chatReqUpdater:l}),super.setName("Mistral")}updateMessages(e){let t=[];if(!Array.isArray(e))return e;for(let n of e)if(n.role==="user"&&Array.isArray(n.content)){let r=n.content.map(o=>typeof o=="object"&&o!==null&&"image_url"in o?{type:"image_url",image_url:{url:o.image_url?.url}}:o);t.push({...n,content:r})}else t.push(n);return t}};var io=class{constructor(e={}){this.config=e;this.config.id=this.config.id??Ee()}metrics={latency:{chat:{mean:0,p95:0,p99:0,samples:[]},embed:{mean:0,p95:0,p99:0,samples:[]}},errors:{chat:{count:0,rate:0,total:0},embed:{count:0,rate:0,total:0}}};getLastUsedChatModel(){return this.config.modelInfo?.name??"mock-model"}getLastUsedEmbedModel(){return this.config.embedModelInfo?.name??"mock-embed-model"}getLastUsedModelConfig(){return this.config.modelInfo?{maxTokens:this.config.modelInfo.maxTokens,temperature:.7,stream:this.config.features?.streaming??!1}:void 0}getName(){return this.config.name??"mock-ai-service"}getId(){return this.config.id??"mock-ai-service-id"}getFeatures(e){let t=this.config.features?.media;return{functions:this.config.features?.functions??!1,streaming:this.config.features?.streaming??!1,structuredOutputs:this.config.features?.structuredOutputs??!1,media:{images:{supported:t?.images?.supported??!1,formats:t?.images?.formats??[]},audio:{supported:t?.audio?.supported??!1,formats:t?.audio?.formats??[]},files:{supported:t?.files?.supported??!1,formats:t?.files?.formats??[],uploadMethod:t?.files?.uploadMethod??"none"},urls:{supported:t?.urls?.supported??!1,webSearch:t?.urls?.webSearch??!1,contextFetching:t?.urls?.contextFetching??!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}}getModelList(){return this.config.models}getMetrics(){return this.metrics}async chat(e,t){if(this.config.latencyMs&&await new Promise(n=>setTimeout(n,this.config.latencyMs)),this.config.shouldError)throw new Error(this.config.errorMessage??"Mock chat error");return this.updateMetrics("chat"),typeof this.config.chatResponse=="function"?await this.config.chatResponse(e):this.config.chatResponse??{results:[{index:0,content:"Mock response",finishReason:"stop"}],modelUsage:{ai:this.getName(),model:"mock-model",tokens:{promptTokens:10,completionTokens:5,totalTokens:15}}}}async embed(e,t){if(this.config.latencyMs&&await new Promise(n=>setTimeout(n,this.config.latencyMs)),this.config.shouldError)throw new Error(this.config.errorMessage??"Mock embed error");return this.updateMetrics("embed"),typeof this.config.embedResponse=="function"?this.config.embedResponse(e):this.config.embedResponse??{embeddings:[[.1,.2,.3]],modelUsage:{ai:this.getName(),model:"mock-model",tokens:{promptTokens:5,completionTokens:0,totalTokens:5}}}}setOptions(e){this.config.options=e}getOptions(){return this.config.options??{}}getLogger(){return this.config.options?.logger??(e=>{console.log(e)})}updateMetrics(e){let t=this.config.latencyMs??0;this.metrics.latency[e].samples.push(t);let n=this.metrics.latency[e].samples;if(this.metrics.latency[e].mean=n.reduce((r,o)=>r+o,0)/n.length,n.length>0){let r=[...n].sort((a,l)=>a-l),o=Math.max(0,Math.floor(r.length*.95)-1);this.metrics.latency[e].p95=r[o]??t;let s=Math.max(0,Math.floor(r.length*.99)-1);this.metrics.latency[e].p99=r[s]??t}if(this.config.shouldError){this.metrics.errors[e].count++,this.metrics.errors[e].total++;let r=this.metrics.latency[e].samples.length;this.metrics.errors[e].rate=r>0?this.metrics.errors[e].count/r:0}}};var ao=class i{options;lastUsedService;services=new Map;constructor(e){if(e.length===0)throw new Error("No AI services provided.");for(let[t,n]of e.entries())if("key"in n){if(this.services.has(n.key))throw new Error(`Duplicate model key: ${n.key}`);let{service:o,description:s,isInternal:a}=n;this.services.set(n.key,{service:o,description:s,isInternal:a})}else{let o=n.getModelList();if(!o)throw new Error(`Service ${t} \`${n.getName()}\` has no model list.`);for(let s of o){if(this.services.has(s.key)){let a=this.services.get(s.key)?.service;throw new Error(`Service ${t} \`${n.getName()}\` has duplicate model key: ${s.key} as service ${a?.getName()}`)}if("model"in s&&typeof s.model)this.services.set(s.key,{description:s.description,service:n,model:s.model});else if("embedModel"in s&&s.embedModel)this.services.set(s.key,{description:s.description,service:n,embedModel:s.embedModel});else throw new Error(`Key ${s.key} in model list for service ${t} \`${n.getName()}\` is missing a model or embedModel property.`)}}}static create(e){return new i(e)}getLastUsedChatModel(){return this.lastUsedService?.getLastUsedChatModel()}getLastUsedEmbedModel(){return this.lastUsedService?.getLastUsedEmbedModel()}getLastUsedModelConfig(){return this.lastUsedService?.getLastUsedModelConfig()}async chat(e,t){let n=e.model;if(!n)throw new Error("Model key must be specified for multi-service");let r=this.services.get(n);if(!r)throw new Error(`No service found for model key: ${n}`);if(this.lastUsedService=r.service,!r.model){let{model:o,...s}=e;return await r.service.chat(s,t)}return await r.service.chat({model:n,...e},t)}async embed(e,t){let n=e.embedModel;if(!n)throw new Error("Embed model key must be specified for multi-service");let r=this.services.get(n);if(!r)throw new Error(`No service found for embed model key: ${n}`);if(this.lastUsedService=r.service,!r.model){let{embedModel:o,...s}=e;return await r.service.embed(s,t)}return await r.service.embed({embedModel:n,...e},t)}getId(){return`MultiServiceRouter:${Array.from(this.services.values()).map(e=>e.service.getId()).join(",")}`}getName(){return"MultiServiceRouter"}getModelList(){return Array.from(this.services).filter(([,e])=>!e.isInternal).map(([e,t])=>{if(t.model)return{key:e,description:t.description,model:t.model};if(t.embedModel)return{key:e,description:t.description,embedModel:t.embedModel};throw new Error(`Service ${e} has no model or embedModel`)})}getFeatures(e){if(e){let t=this.services.get(e);if(t)return t.service.getFeatures(e)}return{functions:!1,streaming:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}}getMetrics(){let e=this.lastUsedService;if(!e){let t=this.services.values().next().value;t&&(e="service"in t?t.service:t)}if(!e)throw new Error("No service available to get metrics.");return e.getMetrics()}setOptions(e){for(let t of this.services.values())t.service.setOptions(e);this.options=e}getOptions(){return this.options??{}}getLogger(){let e=this.lastUsedService;if(!e){let t=this.services.values().next().value;t&&(e=t.service)}if(!e)throw new Error("No service available to get logger.");return e.getLogger()}setServiceEntry(e,t){this.services.set(e,t)}};var Hs=()=>structuredClone({...se(),model:"nous-hermes2",embedModel:"all-minilm"}),nl=()=>structuredClone({...Se(),model:"nous-hermes2",embedModel:"all-minilm"}),sn=class extends Te{constructor({apiKey:e="not-set",url:t="http://localhost:11434/v1",config:n,options:r,models:o}){let s={...Hs(),...n};super({apiKey:e,options:r,config:s,apiURL:t,models:o,modelInfo:[],supportFor:{functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}}),super.setName("Ollama")}};var Lc=i=>["o1","o1-mini","o1-pro","o3","o3-mini","o3-pro","o4-mini"].includes(i),an=class{constructor(e,t,n){this.config=e;this.streamingUsage=t;this.responsesReqUpdater=n}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,stopSequences:e.stopSequences,topP:e.topP,stream:e.stream}}mapInternalContentToResponsesInput(e,t){let n=[];for(let r of e){if(r.type==="text"){t==="assistant"?n.push({type:"output_text",text:r.text}):n.push({type:"input_text",text:r.text});continue}if(t==="assistant")continue;if(r.type==="image"){let s=`data:${r.mimeType};base64,${r.image}`;n.push({type:"input_image",image_url:{url:s,details:r.details??"auto"}});continue}if(r.type==="audio"){n.push({type:"input_audio",input_audio:{data:r.data,format:r.format==="wav"?"wav":void 0}});continue}let o=r;throw new Error(`Unsupported content part: ${JSON.stringify(o)}`)}return n}createResponsesReqInternalInput(e,t=!1){let n=[];for(let r of e){if(t&&r.role==="system")continue;let o;if(r.role==="system"||r.role==="user"||r.role==="assistant"&&r.content)if(typeof r.content=="string")r.role==="system"?o=r.content:r.role==="assistant"?o=[{type:"output_text",text:r.content}]:o=[{type:"input_text",text:r.content}];else if(Array.isArray(r.content))o=this.mapInternalContentToResponsesInput(r.content,r.role==="assistant"?"assistant":"user");else{if(!(r.role==="assistant"&&!r.content&&r.functionCalls))throw new Error(`Invalid content type for role ${r.role}`);o=""}else r.role,o="";switch(r.role){case"system":n.push({type:"message",role:"system",content:o});break;case"user":n.push({type:"message",role:"user",content:o,name:r.name});break;case"assistant":if(r.content||r.functionCalls){let s={type:"message",role:"assistant",content:""};if(r.content&&(s.content=o),r.name&&(s.name=r.name),r.content&&n.push(s),r.functionCalls)for(let a of r.functionCalls)n.push({type:"function_call",call_id:a.id,name:a.function.name,arguments:typeof a.function.params=="object"?JSON.stringify(a.function.params):a.function.params||""})}break;case"function":n.push({type:"function_call_output",call_id:r.functionId,output:r.result});break;default:{let s=r.role;throw new Error(`Invalid role in chat prompt: ${s}`)}}}return n}createChatReq(e,t){let n=e.model,r={name:"/responses"},o=null,s=!1;if(e.chatPrompt){for(let x of e.chatPrompt)if(x.role==="system"&&typeof x.content=="string"){o=x.content,s=!0;break}}let a=o??this.config.systemPrompt??null,l=e.functions?.map(x=>({type:"function",name:x.name,description:x.description,parameters:x.parameters??{}})),u=[],c=Lc(n),p=this.config.reasoningSummary;t?.showThoughts?p||(p="auto"):p=void 0;let d=this.config.reasoningEffort;if(t?.thinkingTokenBudget)switch(t.thinkingTokenBudget){case"none":d=void 0;break;case"minimal":d="minimal";break;case"low":d="medium";break;case"medium":case"high":case"highest":d="high";break}let m={model:n,input:"",instructions:a,tools:l?.length?l:void 0,tool_choice:e.functionCall==="none"||e.functionCall==="auto"||e.functionCall==="required"?e.functionCall:typeof e.functionCall=="object"&&e.functionCall.function?{type:"function",name:e.functionCall.function.name}:void 0,...c?{max_output_tokens:e.modelConfig?.maxTokens??this.config.maxTokens??void 0}:{...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{top_p:e.modelConfig.topP}:{},presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty??void 0,frequency_penalty:e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty??void 0,max_output_tokens:e.modelConfig?.maxTokens??this.config.maxTokens??void 0},stream:e.modelConfig?.stream??this.config.stream??!1,background:void 0,include:u.length>0?u:void 0,metadata:void 0,parallel_tool_calls:this.config.parallelToolCalls,previous_response_id:void 0,...d?{reasoning:{effort:d,summary:p}}:{},service_tier:this.config.serviceTier,store:this.config.store,text:void 0,truncation:void 0,user:this.config.user,seed:this.config.seed};this.config.user&&(m.user=this.config.user),this.config.parallelToolCalls!==void 0&&(m.parallel_tool_calls=this.config.parallelToolCalls),e.responseFormat?m.text={format:e.responseFormat.type==="json_schema"?{type:"json_schema",json_schema:e.responseFormat.schema}:{type:e.responseFormat.type}}:this.config.responseFormat&&(m.text={format:{type:this.config.responseFormat}}),this.config.seed&&(m.seed=this.config.seed);let g=e.chatPrompt?this.createResponsesReqInternalInput(e.chatPrompt,s):[];if(g.length>0)m.input=g;else if(e.chatPrompt&&e.chatPrompt.length===1&&e.chatPrompt[0]?.role==="user"&&e.chatPrompt[0]?.content&&typeof e.chatPrompt[0].content=="string"&&!a)m.input=e.chatPrompt[0].content;else if(g.length===0&&!a)throw new Error("Responses API request must have input or instructions.");let h=m.reasoning??{};if(this.config.reasoningEffort&&(h={...h,effort:this.config.reasoningEffort}),t?.thinkingTokenBudget)switch(t.thinkingTokenBudget){case"none":h={};break;case"minimal":h={...h,effort:"minimal"};break;case"low":h={...h,effort:"medium"};break;case"medium":case"high":case"highest":h={...h,effort:"high"};break}Object.keys(h).length>0&&h.effort?m.reasoning=h:m.reasoning=void 0;let f=m;return this.responsesReqUpdater&&(f=this.responsesReqUpdater(f)),[r,f]}createChatResp(e){let{id:t,output:n,usage:r}=e;r&&(this.tokensUsed={promptTokens:r.prompt_tokens,completionTokens:r.completion_tokens??r.output_tokens??0,totalTokens:r.total_tokens});let o={};for(let s of n??[])switch(s.type){case"message":o.id=s.id,o.content=Ks(s.content,t),o.finishReason=s.status==="completed"?"stop":"content_filter",o.citations=lo(s.content);break;case"reasoning":o.id=s.id,s.encrypted_content?o.thought=s.encrypted_content:o.thought=s.summary.map(a=>typeof a=="object"?JSON.stringify(a):a).join(`
176
+ `);break;case"file_search_call":o.id=s.id,o.functionCalls=[{id:s.id,type:"function",function:{name:"file_search",params:{queries:s.queries,results:s.results}}}],o.finishReason="function_call";break;case"web_search_call":o.id=s.id,o.functionCalls=[{id:s.id,type:"function",function:{name:"web_search",params:{queries:s.queries}}}],o.finishReason="function_call";break;case"computer_call":o.id=s.id,o.functionCalls=[{id:s.id,type:"function",function:{name:"computer_use",params:{action:s.action}}}],o.finishReason="function_call";break;case"code_interpreter_call":o.id=s.id,o.functionCalls=[{id:s.id,type:"function",function:{name:"code_interpreter",params:{code:s.code,results:s.results}}}],o.finishReason="function_call";break;case"image_generation_call":o.id=s.id,o.functionCalls=[{id:s.id,type:"function",function:{name:"image_generation",params:{result:s.result}}}],o.finishReason="function_call";break;case"local_shell_call":o.id=s.id,o.functionCalls=[{id:s.id,type:"function",function:{name:"local_shell",params:{action:s.action}}}],o.finishReason="function_call";break;case"mcp_call":o.id=s.id,o.functionCalls=[{id:s.id,type:"function",function:{name:"mcp",params:{name:s.name,args:s.args,serverLabel:s.server_label,output:s.output,error:s.error}}}],o.finishReason="function_call";break;case"function_call":o.id=s.id,o.functionCalls=[{id:s.id,type:"function",function:{name:s.name,params:s.arguments}}],o.finishReason="function_call";break}return{results:[{...o,index:0}],remoteId:t}}createChatStreamResp(e){let t=e,n={index:0,id:"",content:"",finishReason:"stop"},r;switch(t.type){case"response.created":case"response.in_progress":case"response.queued":r=t.response.id,n.id=`${t.response.id}_res_0`;break;case"response.output_item.added":switch(t.item.type){case"message":n.id=t.item.id,n.content=Ks(t.item.content,t.item.id),n.citations=lo(t.item.content);break;case"function_call":n.id=t.item.id,n.functionCalls=[{id:t.item.id,type:"function",function:{name:t.item.name,params:t.item.arguments}}];break;case"file_search_call":{let o=t.item;n.id=t.item.id,n.functionCalls=[{id:o.id,type:"function",function:{name:"file_search",params:{queries:o.queries||[],results:o.results?.map(s=>({fileId:s.file_id,filename:s.filename,score:s.score,text:s.text,attributes:s.attributes}))}}}]}break;case"web_search_call":{let o=t.item;n.id=t.item.id,n.functionCalls=[{id:o.id,type:"function",function:{name:"web_search",params:{queries:o.queries||[]}}}]}break;case"computer_call":{let o=t.item;n.id=t.item.id,n.functionCalls=[{id:o.id,type:"function",function:{name:"computer_use",params:{action:o.action||{}}}}]}break;case"code_interpreter_call":{let o=t.item;n.id=t.item.id,n.functionCalls=[{id:o.id,type:"function",function:{name:"code_interpreter",params:{code:o.code||"",results:o.results}}}]}break;case"image_generation_call":{let o=t.item;n.id=t.item.id,n.functionCalls=[{id:o.id,type:"function",function:{name:"image_generation",params:{result:o.result}}}]}break;case"local_shell_call":{let o=t.item;n.id=t.item.id,n.functionCalls=[{id:o.id,type:"function",function:{name:"local_shell",params:{action:o.action||{}}}}]}break;case"mcp_call":{let o=t.item;n.id=t.item.id,n.functionCalls=[{id:o.id,type:"function",function:{name:"mcp",params:{name:o.name||"",args:o.args||"",serverLabel:o.server_label||"",output:o.output,error:o.error}}}]}break}break;case"response.content_part.added":n.id=t.item_id,n.content=Ks([t.part],t.item_id),n.citations=lo([t.part]);break;case"response.output_text.delta":n.id=t.item_id,n.content=t.delta;break;case"response.output_text.done":break;case"response.function_call_arguments.delta":n.id=t.item_id,n.functionCalls=[{id:t.item_id,type:"function",function:{name:"",params:t.delta}}];break;case"response.reasoning_summary_text.delta":n.id=t.item_id,n.thought=t.delta;break;case"response.file_search_call.in_progress":case"response.file_search_call.searching":n.id=t.item_id,n.finishReason="function_call";break;case"response.file_search_call.completed":n.id=t.item_id,n.finishReason="function_call";break;case"response.web_search_call.in_progress":case"response.web_search_call.searching":n.id=t.item_id,n.finishReason="function_call";break;case"response.web_search_call.completed":n.id=t.item_id,n.finishReason="function_call";break;case"response.image_generation_call.in_progress":case"response.image_generation_call.generating":n.id=t.item_id,n.finishReason="function_call";break;case"response.image_generation_call.completed":n.id=t.item_id,n.finishReason="function_call";break;case"response.image_generation_call.partial_image":n.id=t.item_id,n.finishReason="function_call";break;case"response.mcp_call.in_progress":n.id=t.item_id,n.finishReason="function_call";break;case"response.mcp_call.arguments.delta":n.id=t.item_id,n.functionCalls=[{id:t.item_id,type:"function",function:{name:"",params:t.delta}}];break;case"response.mcp_call.arguments.done":n.id=t.item_id,n.functionCalls=[{id:t.item_id,type:"function",function:{name:"",params:t.arguments}}];break;case"response.mcp_call.completed":case"response.mcp_call.failed":n.id="mcp_call_event",n.finishReason="function_call";break;case"response.mcp_list_tools.in_progress":case"response.mcp_list_tools.completed":case"response.mcp_list_tools.failed":n.id="mcp_list_tools_event",n.finishReason="function_call";break;case"response.output_item.done":switch(t.item.type){case"message":if(n.id=t.item.id,n.finishReason=t.item.status==="completed"?"stop":"error",!n.citations||n.citations.length===0){let o=lo(t.item.content||[]);o&&(n.citations=o)}break;case"function_call":case"file_search_call":case"web_search_call":case"computer_call":case"code_interpreter_call":case"image_generation_call":case"local_shell_call":case"mcp_call":n.id=t.item.id,n.finishReason="function_call";break}break;case"response.completed":t.response.usage&&(this.tokensUsed={promptTokens:t.response.usage.prompt_tokens,completionTokens:t.response.usage.completion_tokens??t.response.usage.output_tokens??0,totalTokens:t.response.usage.total_tokens}),r=t.response.id,n.id=`${t.response.id}_completed`,n.finishReason="stop";break;case"response.failed":r=t.response.id,n.id=`${t.response.id}_failed`,n.finishReason="error";break;case"response.incomplete":r=t.response.id,n.id=`${t.response.id}_incomplete`,n.finishReason="length";break;case"error":n.id="error",n.content=`Error: ${t.message}`,n.finishReason="error";break;default:n.id="unknown";break}return{results:[n],remoteId:r}}createEmbedReq(e){let t=e.embedModel;if(!t)throw new Error("Embed model not set");if(!e.texts||e.texts.length===0)throw new Error("Embed texts is empty");let n={name:"/embeddings"},r={model:t,input:e.texts,dimensions:this.config.dimensions};return[n,r]}},Ks=(i,e)=>{let t=i.filter(n=>n.type==="refusal");if(t.length>0){let n=t.map(r=>r.refusal).join(`
177
+ `);throw new xe(n,void 0,e)}return i.filter(n=>n.type==="output_text").map(n=>n.text).join(`
178
+ `)};function lo(i){let e=[];for(let t of i??[])if(t?.type==="output_text"&&Array.isArray(t.annotations))for(let n of t.annotations)n&&n.type==="url_citation"&&typeof n.url=="string"&&e.push({url:n.url,title:n.title,description:n.description});return e.length?e:void 0}var er=()=>({model:"gpt-4o",embedModel:"text-embedding-ada-002",temperature:.7,topP:1,stream:!0}),rl=()=>({...er(),model:"gpt-4o",temperature:.5}),ol=()=>({...er(),model:"gpt-4o",temperature:.9}),Zn=class extends we{constructor({apiKey:e,config:t,options:n,apiURL:r,modelInfo:o=[],models:s,responsesReqUpdater:a,supportFor:l={functions:!0,streaming:!0,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}}){if(!e||e==="")throw new Error("OpenAI API key not set");let u=new an(t,n?.streamingUsage??!0,a),c=s?.map(p=>{let d=p,m=d?.config;if(!m)return p;let g={};m.maxTokens!==void 0&&(g.maxTokens=m.maxTokens),m.temperature!==void 0&&(g.temperature=m.temperature),m.topP!==void 0&&(g.topP=m.topP),m.presencePenalty!==void 0&&(g.presencePenalty=m.presencePenalty),m.frequencyPenalty!==void 0&&(g.frequencyPenalty=m.frequencyPenalty);let h=m.stopSequences??m.stop;h!==void 0&&(g.stopSequences=h),m.n!==void 0&&(g.n=m.n),m.stream!==void 0&&(g.stream=m.stream);let f={...d};Object.keys(g).length>0&&(f.modelConfig={...d.modelConfig??{},...g});let x=m?.thinking?.thinkingTokenBudget;if(typeof x=="number"){let A=[["minimal",200],["low",800],["medium",5e3],["high",1e4],["highest",24500]],y="minimal",b=Number.POSITIVE_INFINITY;for(let[S,w]of A){let M=Math.abs(x-w);M<b&&(b=M,y=S)}f.thinkingTokenBudget=y}return m?.thinking?.includeThoughts!==void 0&&(f.showThoughts=!!m.thinking.includeThoughts),f});super(u,{name:"OpenAI",apiURL:r||"https://api.openai.com/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:o,defaults:{model:t.model??"gpt-4o",embedModel:t.embedModel??"text-embedding-ada-002"},options:n,supportFor:l,models:c??s})}},ln=class extends Zn{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("OpenAI API key not set");o=[...Br,...o??[]];let s=a=>{let l=Je({model:a,modelInfo:o,models:r});return{functions:!0,streaming:!0,hasThinkingBudget:l?.supported?.thinkingBudget??!1,hasShowThoughts:l?.supported?.showThoughts??!1,structuredOutputs:l?.supported?.structuredOutputs??!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}};super({apiKey:e,config:{...er(),...t},options:n,modelInfo:o,models:r,supportFor:s})}};var Vs=()=>structuredClone({model:"openrouter/auto",...se()}),un=class extends Te{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o,referer:s,title:a}){if(!e||e==="")throw new Error("OpenRouter API key not set");let l={...Vs(),...t},u={functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0},c=o??[];super({apiKey:e,config:l,options:n,apiURL:"https://openrouter.ai/api/v1",modelInfo:c,models:r,supportFor:u}),super.setName("OpenRouter"),super.setHeaders(async()=>{let p={Authorization:`Bearer ${e}`};return s&&(p["HTTP-Referer"]=s),a&&(p["X-Title"]=a),p})}};async function uo(i,e,t={}){if(typeof i=="string")return[{type:"text",text:i}];if(!Array.isArray(i))return[{type:"text",text:String(i)}];let n=e.getFeatures(),r=[];for(let o of i)try{switch(o.type){case"text":r.push({type:"text",text:o.text});break;case"image":if(n.media.images.supported)o.altText?r.push({type:"text",text:`[Image: ${o.altText}]`}):r.push({type:"text",text:"[Image content]"});else if(o.altText)r.push({type:"text",text:o.altText});else if(t.imageToText)try{let s=await t.imageToText(o.image);r.push({type:"text",text:s})}catch(s){throw new st(s,"image","vision analysis")}else switch(t.fallbackBehavior){case"error":throw new Qe("Images",e.getName(),!1);case"skip":continue;default:r.push({type:"text",text:"[Image content not supported by this provider]"})}break;case"audio":if(n.media.audio.supported)o.transcription?r.push({type:"text",text:o.transcription}):r.push({type:"text",text:"[Audio content]"});else if(o.transcription)r.push({type:"text",text:o.transcription});else if(t.audioToText)try{let s=await t.audioToText(o.data,o.format);r.push({type:"text",text:s})}catch(s){throw new st(s,"audio","transcription")}else switch(t.fallbackBehavior){case"error":throw new Qe("Audio",e.getName(),!1);case"skip":continue;case"degrade":r.push({type:"text",text:"[Audio content not supported by this provider]"})}break;case"file":if(n.media.files.supported)o.extractedText?r.push({type:"text",text:o.extractedText}):r.push({type:"text",text:`[File: ${o.filename}]`});else if(o.extractedText)r.push({type:"text",text:o.extractedText});else if(t.fileToText)try{let s=await t.fileToText(o.data,o.mimeType);r.push({type:"text",text:s})}catch(s){throw new st(s,"file","text extraction")}else switch(t.fallbackBehavior){case"error":throw new Qe("Files",e.getName(),!1);case"skip":continue;default:r.push({type:"text",text:`[File: ${o.filename} - content not accessible by this provider]`})}break;case"url":if(n.media.urls.supported)o.cachedContent?r.push({type:"text",text:o.cachedContent}):r.push({type:"text",text:`[Link: ${o.url}${o.title?` - ${o.title}`:""}]`});else if(o.cachedContent)r.push({type:"text",text:o.cachedContent});else if(t.urlToText)try{let s=await t.urlToText(o.url);r.push({type:"text",text:s})}catch(s){throw new st(s,"url","content fetching")}else switch(t.fallbackBehavior){case"error":throw new Qe("URLs",e.getName(),!1);case"skip":continue;case"degrade":r.push({type:"text",text:`[Link: ${o.url}${o.title?` - ${o.title}`:""}]`})}break;default:typeof o=="object"&&o.text?r.push({type:"text",text:o.text}):r.push({type:"text",text:String(o)})}}catch(s){throw s instanceof Qe||s instanceof st?s:new st(s,o.type||"unknown","content processing")}return r}function sl(i){let e=!1,t=!1,n=!1,r=!1;for(let o of i)if(o.role==="user"&&Array.isArray(o.content))for(let s of o.content)switch(s.type){case"image":e=!0;break;case"audio":t=!0;break;case"file":n=!0;break;case"url":r=!0;break}return{hasImages:e,hasAudio:t,hasFiles:n,hasUrls:r}}var tr=(n=>(n.RekaCore="reka-core",n.RekaFlash="reka-flash",n.RekaEdge="reka-edge",n))(tr||{});var co=[{name:"reka-core",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15},{name:"reka-flash",currency:"usd",promptTokenCostPer1M:.8,completionTokenCostPer1M:2},{name:"reka-edge",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1}];var nr=()=>structuredClone({model:"reka-core",...se()}),al=()=>structuredClone({...nr(),model:"reka-core"}),ll=()=>structuredClone({model:"reka-core",...Se()}),ul=()=>({...nr(),model:"reka-flash"}),Ws=class{constructor(e){this.config=e}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,topP:e.topP,n:e.n,stream:e.stream}}createChatReq=e=>{let t=e.model;if(!e.chatPrompt||e.chatPrompt.length===0)throw new Error("Chat prompt is empty");let n={name:"/chat/completions"},r=Uc(e),o=e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,s=e.modelConfig?.stream??this.config.stream,a={model:t,messages:r,max_tokens:e.modelConfig?.maxTokens??this.config.maxTokens,...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},top_k:e.modelConfig?.n??this.config.n,...e.modelConfig?.topP!==void 0?{top_p:e.modelConfig.topP}:{},stop:e.modelConfig?.stopSequences??this.config.stop,presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty,...o?{frequency_penalty:o}:{},...s?{stream:!0}:{}};return[n,a]};createChatResp=e=>{let{id:t,usage:n,responses:r}=e;return this.tokensUsed=n?{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.input_tokens+n.output_tokens}:void 0,{results:r.map((s,a)=>{let l=il(s.finish_reason),u;return typeof s.message.content=="string"?u=s.message.content:u=s.message.content.text,{index:a,id:`${t}`,content:u,finishReason:l}}),remoteId:t}};createChatStreamResp=e=>{let{id:t,usage:n,responses:r}=e;return this.tokensUsed=n?{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.input_tokens+n.output_tokens}:void 0,{results:r.map((s,a)=>{let l=il(s.finish_reason),u;return typeof s.chunk.content=="string"?u=s.chunk.content:u=s.chunk.content.text,{index:a,id:`${t}`,content:u,finishReason:l}})}}},il=i=>{switch(i){case"stop":return"stop";case"context":return"length";case"length":return"length"}};function Uc(i){return i.chatPrompt.map(e=>{switch(e.role){case"system":return{role:"user",content:e.content};case"user":return Array.isArray(e.content)?{role:"user",content:e.content.map(t=>{switch(t.type){case"text":return{type:"text",text:t.text};case"image":throw new Error("Image type not supported");default:throw new Error("Invalid content type")}})}:{role:"user",content:e.content};case"assistant":if(Array.isArray(e.content))return{role:"assistant",content:e.content.map(t=>{switch(t.type){case"text":return{type:"text",text:t.text};case"image":throw new Error("Image type not supported");default:throw new Error("Invalid content type")}})};if(!e.content)throw new Error("Assistant content is empty");return{role:"user",content:e.content};default:throw new Error("Invalid role")}})}var cn=class extends we{constructor({apiKey:e,config:t,options:n,apiURL:r,modelInfo:o=co,models:s}){if(!e||e==="")throw new Error("Reka API key not set");let a={...nr(),...t},l=new Ws(a);super(l,{name:"Reka",apiURL:r||"https://api.reka.ai/v1/chat",headers:async()=>({"X-Api-Key":e}),modelInfo:o,defaults:{model:a.model},options:n,supportFor:{functions:!0,streaming:!0,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0},models:s})}};var po=class{providers;processingServices;config;constructor(e){this.providers=[e.providers.primary,...e.providers.alternatives],this.processingServices=e.processing,this.config=e.routing}async chat(e,t={}){let n=await this.selectProviderWithDegradation(e,t.routingOptions||{}),r=await this.preprocessRequest(e,n.provider,t.processingOptions);try{return{response:await n.provider.chat(r,t),routing:n}}catch(o){if(o instanceof Qe&&t.fallbackProviders?.length)return await this.tryFallbackProviders(e,t.fallbackProviders,t);throw o}}async preprocessRequest(e,t,n){let r={...n,fallbackBehavior:n?.fallbackBehavior||"degrade",imageToText:n?.imageToText||this.processingServices.imageToText,audioToText:n?.audioToText||this.processingServices.audioToText,fileToText:n?.fileToText||this.processingServices.fileToText,urlToText:n?.urlToText||this.processingServices.urlToText},o=[];for(let s of e.chatPrompt)if(s.role==="user"&&Array.isArray(s.content)){let a=await uo(s.content,t,r);a.every(u=>u.type==="text")&&a.length===1?o.push({...s,content:a[0].text}):o.push({...s,content:a.map(u=>({type:"text",text:u.text}))})}else o.push(s);return{...e,chatPrompt:o}}async selectProviderWithDegradation(e,t){let n=_t(e),r=[],o=[],s=[];try{let a=Vr(e,this.providers,{requireExactMatch:t.requireExactMatch??this.config.capability.requireExactMatch,allowDegradation:t.allowDegradation??this.config.capability.allowDegradation}),l=a.getFeatures();return n.hasImages&&!l.media.images.supported&&(o.push("Images will be converted to text descriptions"),r.push("Image-to-text conversion")),n.hasAudio&&!l.media.audio.supported&&(o.push("Audio will be transcribed to text"),r.push("Audio-to-text transcription")),n.hasFiles&&!l.media.files.supported&&(o.push("File content will be extracted to text"),r.push("File-to-text extraction")),n.hasUrls&&!l.media.urls.supported&&(o.push("URL content will be pre-fetched"),r.push("URL content fetching")),n.requiresStreaming&&!l.streaming&&s.push("Streaming not supported - will use non-streaming mode"),n.requiresCaching&&!l.caching.supported&&s.push("Content caching not supported"),{provider:a,processingApplied:r,degradations:o,warnings:s}}catch(a){throw new Error(`Provider selection failed: ${a instanceof Error?a.message:"Unknown error"}`)}}async tryFallbackProviders(e,t,n){for(let r of t)try{let o={provider:r,processingApplied:["Fallback provider selection"],degradations:["Using fallback provider due to primary provider failure"],warnings:[]},s=await this.preprocessRequest(e,r,{fallbackBehavior:"degrade"});return{response:await r.chat(s,n),routing:o}}catch{}throw new Error("All fallback providers failed")}async getRoutingRecommendation(e){return await this.selectProviderWithDegradation(e,{})}async validateRequest(e){let t=_t(e),n=[],r=[];try{let o=await this.selectProviderWithDegradation(e,{});return o.degradations.length>0&&(n.push(...o.degradations),r.push("Consider using a provider that natively supports all media types")),o.warnings.length>0&&n.push(...o.warnings),t.hasImages&&this.processingServices.imageToText===void 0&&(this.providers.some(a=>a.getFeatures().media.images.supported)||(n.push("No image processing service available and no providers support images"),r.push("Add imageToText processing service or use image-capable provider"))),t.hasAudio&&this.processingServices.audioToText===void 0&&(this.providers.some(a=>a.getFeatures().media.audio.supported)||(n.push("No audio processing service available and no providers support audio"),r.push("Add audioToText processing service or use audio-capable provider"))),{canHandle:n.length===0||o.degradations.length>0,issues:n,recommendations:r}}catch(o){return{canHandle:!1,issues:[`Cannot route request: ${o instanceof Error?o.message:"Unknown error"}`],recommendations:["Add more providers or processing services to handle this request"]}}}getRoutingStats(){let e={};for(let t of this.providers){let n=t.getFeatures(),r=t.getName();n.functions&&(e.Functions=e.Functions||[],e.Functions.push(r)),n.streaming&&(e.Streaming=e.Streaming||[],e.Streaming.push(r)),n.media.images.supported&&(e.Images=e.Images||[],e.Images.push(r)),n.media.audio.supported&&(e.Audio=e.Audio||[],e.Audio.push(r)),n.media.files.supported&&(e.Files=e.Files||[],e.Files.push(r)),n.media.urls.supported&&(e.URLs=e.URLs||[],e.URLs.push(r)),n.caching.supported&&(e.Caching=e.Caching||[],e.Caching.push(r))}return{totalProviders:this.providers.length,capabilityMatrix:e,recommendedProvider:this.providers[0]?.getName()||"None"}}};var mo=[];var Js=()=>structuredClone({model:"mistralai/Mixtral-8x7B-Instruct-v0.1",...se()}),pn=class extends Te{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("Together API key not set");let s={...Js(),...t};o=[...mo,...o??[]];let a={functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0};super({apiKey:e,config:s,options:n,apiURL:"https://api.together.xyz/v1",modelInfo:o,models:r,supportFor:a}),super.setName("Together")}};var rr=(d=>(d.Llama31_8B_Instruct="Llama-3.1-8B-Instruct-q4f32_1-MLC",d.Llama31_70B_Instruct="Llama-3.1-70B-Instruct-q4f16_1-MLC",d.Llama32_1B_Instruct="Llama-3.2-1B-Instruct-q4f32_1-MLC",d.Llama32_3B_Instruct="Llama-3.2-3B-Instruct-q4f32_1-MLC",d.Mistral7B_Instruct="Mistral-7B-Instruct-v0.3-q4f32_1-MLC",d.Phi35_Mini_Instruct="Phi-3.5-mini-instruct-q4f32_1-MLC",d.Gemma2_2B_Instruct="gemma-2-2b-it-q4f32_1-MLC",d.Gemma2_9B_Instruct="gemma-2-9b-it-q4f32_1-MLC",d.Qwen2_5_0_5B_Instruct="Qwen2.5-0.5B-Instruct-q4f32_1-MLC",d.Qwen2_5_1_5B_Instruct="Qwen2.5-1.5B-Instruct-q4f32_1-MLC",d.Qwen2_5_3B_Instruct="Qwen2.5-3B-Instruct-q4f32_1-MLC",d.Qwen2_5_7B_Instruct="Qwen2.5-7B-Instruct-q4f32_1-MLC",d))(rr||{});var go=[{name:"Llama-3.1-8B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:4096},{name:"Llama-3.1-70B-Instruct-q4f16_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:4096,isExpensive:!0},{name:"Llama-3.2-1B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:2048},{name:"Llama-3.2-3B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:2048},{name:"Mistral-7B-Instruct-v0.3-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:4096},{name:"Phi-3.5-mini-instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:4096},{name:"gemma-2-2b-it-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:8192,maxTokens:2048},{name:"gemma-2-9b-it-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:8192,maxTokens:2048},{name:"Qwen2.5-0.5B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:2048},{name:"Qwen2.5-1.5B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:2048},{name:"Qwen2.5-3B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:2048},{name:"Qwen2.5-7B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:4096}];var Qs=()=>structuredClone({model:"Llama-3.2-3B-Instruct-q4f32_1-MLC",...se()}),cl=()=>structuredClone({model:"Llama-3.2-3B-Instruct-q4f32_1-MLC",...Se()}),Ys=class{constructor(e,t){this.config=e;this.engine=t}tokensUsed;engine;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,endSequences:e.endSequences,stream:e.stream,n:e.n}}createChatReq(e){let t=e.model,n=e.chatPrompt.map(a=>{if(a.role==="function")return{role:"function",name:a.functionId,content:typeof a.result=="string"?a.result:JSON.stringify(a.result)};let l="";typeof a.content=="string"?l=a.content:Array.isArray(a.content)&&(l=a.content.filter(c=>c.type==="text").map(c=>c.text).join(`
179
+ `));let u={role:a.role,content:l};return a.role==="assistant"&&a.functionCalls?.length?{...u,tool_calls:a.functionCalls.map(c=>({id:c.id,type:"function",function:{name:c.function.name,arguments:typeof c.function.params=="string"?c.function.params:JSON.stringify(c.function.params||{})}}))}:u}),r=e.functions?.map(a=>({type:"function",function:{name:a.name,description:a.description,parameters:a.parameters||{type:"object",properties:{}}}})),o={name:"/chat/completions",localCall:async(a,l)=>{try{let u=await this.engine.chat.completions.create({...a,stream:l||!1});return l?new ReadableStream({async start(c){try{for await(let p of u)c.enqueue(p);c.close()}catch(p){c.error(p)}}}):u}catch(u){throw new Error(`WebLLM API error: ${u}`)}}},s={model:t,messages:n,...r?.length?{tools:r}:{},max_tokens:e.modelConfig?.maxTokens??this.config.maxTokens,...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{top_p:e.modelConfig.topP}:{},presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty,frequency_penalty:e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,stop:e.modelConfig?.stopSequences??this.config.stopSequences,stream:e.modelConfig?.stream??this.config.stream,n:e.modelConfig?.n??this.config.n};return[o,s]}createEmbedReq=e=>{throw new Error("WebLLM does not support embeddings")};createChatResp=e=>(this.tokensUsed={promptTokens:e.usage?.prompt_tokens??0,completionTokens:e.usage?.completion_tokens??0,totalTokens:e.usage?.total_tokens??0},{results:e.choices.map((n,r)=>{let o="stop";switch(n.finish_reason){case"stop":o="stop";break;case"length":o="length";break;case"tool_calls":o="function_call";break;case"content_filter":o="content_filter";break;default:o="stop";break}let s=n.message.tool_calls?.map(a=>({id:a.id,type:"function",function:{name:a.function.name,params:a.function.arguments}}));return{index:r,id:e.id,content:n.message.content||"",functionCalls:s,finishReason:o}}),remoteId:e.id});createChatStreamResp=(e,t)=>{let n=t,r=e.choices[0];if(!r)throw new Error("No choice in WebLLM stream response");if(r.delta.content&&(n.content=(n.content||"")+r.delta.content),r.delta.tool_calls){n.toolCalls||(n.toolCalls=[]);for(let l of r.delta.tool_calls){let u=n.toolCalls[l.index];u?l.function?.arguments&&(u.function.arguments=(u.function?.arguments||"")+l.function.arguments):n.toolCalls[l.index]={id:l.id,type:l.type,function:{name:l.function?.name,arguments:l.function?.arguments||""}}}}e.usage&&(this.tokensUsed={promptTokens:e.usage.prompt_tokens,completionTokens:e.usage.completion_tokens,totalTokens:e.usage.total_tokens});let o;if(r.finish_reason)switch(r.finish_reason){case"stop":o="stop";break;case"length":o="length";break;case"tool_calls":o="function_call";break;case"content_filter":o="content_filter";break;default:o="stop";break}let s=n.toolCalls?.map(l=>({id:l.id||"",type:"function",function:{name:l.function?.name||"",params:l.function?.arguments||""}}));return{results:[{index:0,id:e.id,content:n.content||"",functionCalls:s,finishReason:o}],remoteId:e.id}};createEmbedResp(e){throw new Error("WebLLM does not support embeddings")}},dn=class extends we{constructor({engine:e,config:t,options:n,models:r}){if(!e)throw new Error("WebLLM engine instance is required");let o={...Qs(),...t},s=new Ys(o,e);super(s,{name:"WebLLM",apiURL:void 0,headers:async()=>({}),modelInfo:go,defaults:{model:o.model},supportFor:a=>({functions:!0,streaming:!0,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}),options:n,models:r})}};var or=(r=>(r.Grok3="grok-3",r.Grok3Mini="grok-3-mini",r.Grok3Fast="grok-3-fast",r.Grok3MiniFast="grok-3-mini-fast",r))(or||{}),Xs=(e=>(e.GrokEmbedSmall="grok-embed-small",e))(Xs||{});var ho=[{name:"grok-3",currency:"USD",promptTokenCostPer1M:3,completionTokenCostPer1M:15},{name:"grok-3-mini",currency:"USD",promptTokenCostPer1M:.3,completionTokenCostPer1M:.5,supported:{thinkingBudget:!0}},{name:"grok-3-fast",currency:"USD",promptTokenCostPer1M:5,completionTokenCostPer1M:25},{name:"grok-3-mini-fast",currency:"USD",promptTokenCostPer1M:.6,completionTokenCostPer1M:4,supported:{thinkingBudget:!0}}];var fo=()=>structuredClone({model:"grok-3-mini",...se()}),pl=()=>structuredClone({...fo(),model:"grok-3"}),mn=class extends Te{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("Grok API key not set");let s={...fo(),...t};o=[...ho,...o??[]];let a=u=>{let c=Je({model:u,modelInfo:o,models:r});return{functions:!0,streaming:!0,hasThinkingBudget:c?.supported?.thinkingBudget??!1,hasShowThoughts:c?.supported?.showThoughts??!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}},l=u=>{if(n?.searchParameters){let c=n.searchParameters;return{...u,search_parameters:{mode:c.mode,return_citations:c.returnCitations,from_date:c.fromDate,to_date:c.toDate,max_search_results:c.maxSearchResults,sources:c.sources?.map(p=>({type:p.type,country:p.country,excluded_websites:p.excludedWebsites,allowed_websites:p.allowedWebsites,safe_search:p.safeSearch,x_handles:p.xHandles,links:p.links}))}}}return u};super({apiKey:e,config:s,options:n,apiURL:"https://api.x.ai/v1",modelInfo:o,models:r,supportFor:a,chatReqUpdater:l}),super.setName("Grok")}};function dl(i){return sr.create(i)}var sr=class i{ai;static create(e){return new i(e)}constructor(e){switch(e.name){case"openai":this.ai=new Yt(e);break;case"openai-responses":this.ai=new ln(e);break;case"azure-openai":this.ai=new Qt(e);break;case"grok":this.ai=new mn(e);break;case"huggingface":this.ai=new rn(e);break;case"groq":this.ai=new nn(e);break;case"together":this.ai=new pn(e);break;case"openrouter":this.ai=new un(e);break;case"cohere":this.ai=new Xt(e);break;case"google-gemini":this.ai=new en(e);break;case"anthropic":this.ai=new Kt(e);break;case"mistral":this.ai=new on(e);break;case"deepseek":this.ai=new Zt(e);break;case"ollama":this.ai=new sn(e);break;case"reka":this.ai=new cn(e);break;case"webllm":this.ai=new dn(e);break;default:throw new Error("Unknown AI")}}getName(){return this.ai.getName()}getId(){return this.ai.getId()}getFeatures(e){return this.ai.getFeatures(e)}getModelList(){return this.ai.getModelList()}getLastUsedChatModel(){return this.ai.getLastUsedChatModel()}getLastUsedEmbedModel(){return this.ai.getLastUsedEmbedModel()}getLastUsedModelConfig(){return this.ai.getLastUsedModelConfig()}getMetrics(){return this.ai.getMetrics()}async chat(e,t){return await this.ai.chat(e,t)}async embed(e,t){return await this.ai.embed(e,t)}setOptions(e){this.ai.setOptions(e)}getOptions(){return this.ai.getOptions()}getLogger(){return this.ai.getLogger()}};var Xe=class{name;fetch;tracer;_upsert;_batchUpsert;_query;constructor({name:e,fetch:t,tracer:n}){this.name=e,this.fetch=t,this.tracer=n}async upsert(e,t){if(!this._upsert)throw new Error("upsert() not implemented");return this.tracer?await this.tracer.startActiveSpan("DB Upsert Request",{kind:Be.SERVER,attributes:{[J.DB_SYSTEM]:this.name,[J.DB_OPERATION_NAME]:"upsert",[J.DB_TABLE]:e.table,[J.DB_NAMESPACE]:e.namespace,[J.DB_OPERATION_NAME]:t?"update":"insert"}},async n=>{try{return await this._upsert(e,t,{span:n})}finally{n.end()}}):await this._upsert(e,t)}async batchUpsert(e,t){if(!this._batchUpsert)throw new Error("batchUpsert() not implemented");if(e.length===0)throw new Error("Batch request is empty");if(!e[0])throw new Error("Batch request is invalid first element is undefined");return this.tracer?await this.tracer.startActiveSpan("DB Batch Upsert Request",{kind:Be.SERVER,attributes:{[J.DB_SYSTEM]:this.name,[J.DB_OPERATION_NAME]:"upsert",[J.DB_TABLE]:e[0].table,[J.DB_NAMESPACE]:e[0].namespace,[J.DB_OPERATION_NAME]:t?"update":"insert"}},async n=>{try{return await this._batchUpsert(e,t,{span:n})}finally{n.end()}}):await this._batchUpsert(e,t)}async query(e){if(!this._query)throw new Error("query() not implemented");return this.tracer?await this.tracer.startActiveSpan("DB Query Request",{kind:Be.SERVER,attributes:{[J.DB_SYSTEM]:this.name,[J.DB_OPERATION_NAME]:"upsert",[J.DB_TABLE]:e.table,[J.DB_NAMESPACE]:e.namespace,[J.DB_OPERATION_NAME]:"query"}},async t=>{try{return await this._query(e,{span:t})}finally{t.end()}}):await this._query(e)}};var Zs="https://api.cloudflare.com/client/v4/accounts/",gn=class extends Xe{apiKey;accountId;constructor({apiKey:e,accountId:t,fetch:n,tracer:r}){if(!e||!t)throw new Error("Cloudflare credentials not set");super({name:"Cloudflare",fetch:n,tracer:r}),this.apiKey=e,this.accountId=t}_upsert=async(e,t,n)=>{let r=await Fe({url:new URL(`${this.accountId}/vectorize/indexes/${e.table}/upsert`,Zs),headers:{"X-Auth-Key":this.apiKey},fetch:this.fetch,span:n?.span},{id:e.id,values:e.values,namespace:e.namespace,metadata:e.metadata});if(r.errors)throw new Error(`Cloudflare upsert failed: ${r.errors.map(({message:o})=>o).join(", ")}`);return{ids:r.result.ids}};batchUpsert=async(e,t,n)=>{if(t)throw new Error("Weaviate does not support batch update");if(e.length<1)throw new Error("Batch request is empty");if(!e[0]||!e[0].table)throw new Error("Table name is empty");let r=e[0].table,o=await Fe({url:new URL(`${this.accountId}/vectorize/indexes/${r}/upsert`,Zs),headers:{"X-Auth-Key":this.apiKey},fetch:this.fetch,span:n?.span},e.map(s=>({id:s.id,values:s.values,namespace:s.namespace,metadata:s.metadata})));if(o.errors)throw new Error(`Cloudflare batch upsert failed: ${o.errors.map(({message:s})=>s).join(", ")}`);return{ids:o.result.ids}};query=async(e,t)=>{let n=await Fe({url:new URL(`${this.accountId}/vectorize/indexes/${e.table}/query`,Zs),headers:{"X-Auth-Key":this.apiKey},fetch:this.fetch,span:t?.span},{vector:e.values,topK:e.limit||10,returnValues:!0});if(n.errors)throw new Error(`Cloudflare query failed: ${n.errors.map(({message:o})=>o).join(", ")}`);return{matches:n.result.matches.map(({id:o,score:s,values:a,metadata:l})=>({id:o,score:s,values:a,metadata:l}))}}};var Ot=class extends Xe{state;constructor({tracer:e}={}){super({name:"Memory",tracer:e}),this.state={}}_upsert=async(e,t,n)=>{if(!this.state[e.table])this.state[e.table]={[e.id]:e};else{let r=this.state[e.table];if(!r)throw new Error(`Table not found: ${e.table}`);r[e.id]=e}return{ids:[e.id]}};_batchUpsert=async(e,t,n)=>{let r=[];for(let o of e){let s=await this.upsert(o,t);r.push(...s.ids)}return{ids:r}};_query=async(e,t)=>{let n=this.state[e.table];if(!n)return{matches:[]};let r=[];return Object.entries(n).forEach(([o,s])=>{if(e.values&&s.values){let a=Bc(e.values,s.values);r.push({id:o,score:a,metadata:s.metadata})}}),r.sort((o,s)=>o.score-s.score),e.limit&&(r.length=e.limit),{matches:r}};getDB=()=>structuredClone(this.state);setDB=e=>{this.state=structuredClone(e)};clearDB=()=>{this.state={}}},Bc=(i,e)=>{if(i.length!==e.length)throw new Error("Vectors must be of the same length.");let t=0,n=0,r=0,o=!0,s=!0,a=new Float64Array(i),l=new Float64Array(e);for(let d=0;d<a.length;d++)t+=a[d]*l[d],n+=a[d]*a[d],r+=l[d]*l[d],a[d]!==0&&(o=!1),l[d]!==0&&(s=!1);if(o||s)return 1;let u=Math.sqrt(n),c=Math.sqrt(r);return 1-t/(u*c)};var jc=i=>({namespace:i.namespace,topK:i.limit||10,filter:{},includeValues:!0,includeMetadata:!0,vector:i.values??[],id:i.id}),hn=class extends Xe{apiKey;apiURL;constructor({apiKey:e,host:t,fetch:n,tracer:r}){if(!e||e==="")throw new Error("Pinecone API key not set");super({name:"Pinecone",fetch:n,tracer:r}),this.apiKey=e,this.apiURL=t}_upsert=async(e,t,n)=>(await this._batchUpsert([e],t,n),{ids:[e.id]});_batchUpsert=async(e,t,n)=>{if(e.length===0)throw new Error("Batch request is empty");return await Fe({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/vectors/upsert",fetch:this.fetch,span:n?.span},e.map(({id:r,values:o=[],metadata:s})=>({id:r,values:o,metadata:s}))),{ids:e.map(({id:r})=>r)}};query=async(e,t)=>{if(e.text)throw new Error("Pinecone does not support text");return{matches:(await Fe({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/query",fetch:this.fetch,span:t?.span},jc(e))).matches.map(({id:o,score:s,values:a,metadata:l})=>({id:o,score:s,metadata:l,values:a}))}}};var fn=class extends Xe{apiKey;apiURL;constructor({apiKey:e,host:t,fetch:n,tracer:r}){if(!e||e==="")throw new Error("Weaviate API key not set");super({name:"Weaviate",fetch:n,tracer:r}),this.apiKey=e,this.apiURL=t}_upsert=async(e,t,n)=>{let r=await Fe({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:`/v1/objects/${e.table}/${e.id}`,put:!!t,fetch:this.fetch,span:n?.span},{id:e.id,class:e.table,tenant:e.namespace,vector:e.values,properties:e.metadata??{}});if(r?.result?.errors)throw new Error(`Weaviate upsert failed: ${r.result.errors.error.map(({message:o})=>o).join(", ")}`);return{ids:[r.id]}};_batchUpsert=async(e,t,n)=>{if(t)throw new Error("Weaviate does not support batch update");if(e.length===0)throw new Error("Batch request is empty");let r=e.map(s=>({id:s.id,class:s.table,tenant:s.namespace,vector:s.values,properties:s.metadata??{}})),o=await Fe({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/v1/batch/objects",fetch:this.fetch,span:n?.span},{objects:r});if(o?.some(({result:s})=>s?.errors))throw new Error(`Weaviate batch upsert failed: ${o.map(({result:s})=>s?.errors?.error.map(({message:a})=>a).join(", ")).join(", ")}`);return{ids:o.map(({id:s})=>s)}};_query=async(e,t)=>{let n="";if(e.columns&&e.columns.length===0)throw new Error("Weaviate requires at least one column");if(e.values)n=`nearVector: {
180
180
  vector: [${e.values.join(",")}],
181
181
  }`;else if(e.text)n=`nearText: {
182
182
  concepts: ['${e.text}'],
183
- }`;else throw new Error("Weaviate requires either text or values");let r=await Ue({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/v1/graphql",fetch:this.fetch,span:t?.span},{query:`{
183
+ }`;else throw new Error("Weaviate requires either text or values");let r=await Fe({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/v1/graphql",fetch:this.fetch,span:t?.span},{query:`{
184
184
  Get {
185
185
  ${e.table} (
186
186
  limit: ${e.limit||10},
@@ -190,63 +190,63 @@ ${u}`:`Assistant: ${l.content}`}default:throw new Error("Unknown role")}}).join(
190
190
  `)}
191
191
  }
192
192
  }
193
- }`});if(r.errors)throw new Error(`Weaviate query failed: ${r.errors.map(({message:a})=>a).join(", ")}`);let o=r.data.Get[e.table];return o?{matches:o.map(a=>({id:a.id,score:1,metadata:a}))}:{matches:[]}}};var fo=class{db;constructor(e){switch(e.name){case"weaviate":this.db=new fn(e);break;case"pinecone":this.db=new hn(e);break;case"cloudflare":this.db=new gn(e);break;case"memory":this.db=new Ot(e);break;default:throw new Error("Unknown DB")}}async upsert(e,t){return await this.db.upsert(e,t)}async batchUpsert(e,t){return await this.db.batchUpsert(e,t)}async query(e){return await this.db.query(e)}};var Zs="_internal",xo=class{ai;db;chunker;rewriter;reranker;constructor({ai:e,db:t,config:n}){this.ai=e,this.db=t,this.chunker=n?.chunker??this.defaultChunker,this.reranker=n?.reranker,this.rewriter=n?.rewriter}defaultChunker=e=>e.split(/\n\n+/);insert=async(e,t)=>{try{let n=Array.isArray(e)?e.join(`
193
+ }`});if(r.errors)throw new Error(`Weaviate query failed: ${r.errors.map(({message:a})=>a).join(", ")}`);let o=r.data.Get[e.table];return o?{matches:o.map(a=>({id:a.id,score:1,metadata:a}))}:{matches:[]}}};var xo=class{db;constructor(e){switch(e.name){case"weaviate":this.db=new fn(e);break;case"pinecone":this.db=new hn(e);break;case"cloudflare":this.db=new gn(e);break;case"memory":this.db=new Ot(e);break;default:throw new Error("Unknown DB")}}async upsert(e,t){return await this.db.upsert(e,t)}async batchUpsert(e,t){return await this.db.batchUpsert(e,t)}async query(e){return await this.db.query(e)}};var ei="_internal",Ao=class{ai;db;chunker;rewriter;reranker;constructor({ai:e,db:t,config:n}){this.ai=e,this.db=t,this.chunker=n?.chunker??this.defaultChunker,this.reranker=n?.reranker,this.rewriter=n?.rewriter}defaultChunker=e=>e.split(/\n\n+/);insert=async(e,t)=>{try{let n=Array.isArray(e)?e.join(`
194
194
 
195
- `):e,r=this.chunker(n).filter(u=>u.length>0),o=t?.maxWordsPerChunk,i=t?.minWordsPerChunk,a=Gc({initialChunks:r,minWordsPerChunk:i,maxWordsPerChunk:o}),l=t?.batchSize??10;for(let u=0;u<a.length;u+=l){let c=a.slice(u,u+l),d=(await this.ai.embed({texts:c},{abortSignal:t?.abortSignal})).embeddings.map((m,g)=>({id:`chunk_${Date.now()+g}`,table:Zs,values:m,metadata:{text:c[g]??""}})).filter(m=>m.metadata?.text&&m.metadata?.text.length>0);await this.db.batchUpsert(d)}}catch(n){throw new Error(`Error processing text: ${n}`)}};query=async(e,{topPercent:t,abortSignal:n}={})=>{let r=Array.isArray(e)?e:[e];if(typeof r[0]=="string"&&this.rewriter)for(let[l,u]of r.entries()){let{rewrittenQuery:c}=await this.rewriter.forward(this.ai,{query:u});r[l]=c}let o;typeof r[0]=="string"?o=(await this.ai.embed({texts:r},{abortSignal:n})).embeddings.map(u=>this.db.query({table:Zs,values:u})):o=r.map(l=>this.db.query({table:Zs,values:l}));let i=await Promise.all(o),a=[];for(let{matches:l}of i){let u=l.filter(d=>d.metadata?.text&&d.metadata?.text.length>0).map(({score:d,metadata:m})=>({score:d,text:m?.text??""})),c=t&&t>1?t/100:t,p=c?Uc(u,c):u;if(this.reranker){let{rankedItems:d}=await this.reranker.forward(this.ai,{query:r[0],items:p.map(g=>g.text)}),m=d.map(g=>p.find(f=>f.text===g)).filter(g=>g!==void 0);a.push(m)}else a.push(p)}return a}},Gc=({initialChunks:s,maxWordsPerChunk:e=350,minWordsPerChunk:t=250})=>{let n=[],r="",o=0;return s.forEach(i=>{let a=i.split(/\s+/),l=a.length;if(o+l<=e)r+=`${i}
195
+ `):e,r=this.chunker(n).filter(u=>u.length>0),o=t?.maxWordsPerChunk,s=t?.minWordsPerChunk,a=qc({initialChunks:r,minWordsPerChunk:s,maxWordsPerChunk:o}),l=t?.batchSize??10;for(let u=0;u<a.length;u+=l){let c=a.slice(u,u+l),d=(await this.ai.embed({texts:c},{abortSignal:t?.abortSignal})).embeddings.map((m,g)=>({id:`chunk_${Date.now()+g}`,table:ei,values:m,metadata:{text:c[g]??""}})).filter(m=>m.metadata?.text&&m.metadata?.text.length>0);await this.db.batchUpsert(d)}}catch(n){throw new Error(`Error processing text: ${n}`)}};query=async(e,{topPercent:t,abortSignal:n}={})=>{let r=Array.isArray(e)?e:[e];if(typeof r[0]=="string"&&this.rewriter)for(let[l,u]of r.entries()){let{rewrittenQuery:c}=await this.rewriter.forward(this.ai,{query:u});r[l]=c}let o;typeof r[0]=="string"?o=(await this.ai.embed({texts:r},{abortSignal:n})).embeddings.map(u=>this.db.query({table:ei,values:u})):o=r.map(l=>this.db.query({table:ei,values:l}));let s=await Promise.all(o),a=[];for(let{matches:l}of s){let u=l.filter(d=>d.metadata?.text&&d.metadata?.text.length>0).map(({score:d,metadata:m})=>({score:d,text:m?.text??""})),c=t&&t>1?t/100:t,p=c?zc(u,c):u;if(this.reranker){let{rankedItems:d}=await this.reranker.forward(this.ai,{query:r[0],items:p.map(g=>g.text)}),m=d.map(g=>p.find(h=>h.text===g)).filter(g=>g!==void 0);a.push(m)}else a.push(p)}return a}},qc=({initialChunks:i,maxWordsPerChunk:e=350,minWordsPerChunk:t=250})=>{let n=[],r="",o=0;return i.forEach(s=>{let a=s.split(/\s+/),l=a.length;if(o+l<=e)r+=`${s}
196
196
 
197
- `,o+=l;else if(o>0&&o+l<=e*1.5)r+=`${i}
197
+ `,o+=l;else if(o>0&&o+l<=e*1.5)r+=`${s}
198
198
 
199
199
  `,o+=l;else if(o>t&&(n.push(r.trim()),r="",o=0),l>e){let u=a;for(;u.length>e*1.5;){let c=u.splice(0,e);n.push(c.join(" "))}u.length>0&&(r+=`${u.join(" ")}
200
200
 
201
- `,o+=u.length)}else r=`${i}
201
+ `,o+=u.length)}else r=`${s}
202
202
 
203
- `,o=l}),(o>t||n.length===0)&&n.push(r.trim()),n},Uc=(s,e=.1)=>{let t=[...s].sort((r,o)=>r.score-o.score),n=Math.ceil(t.length*e);return t.slice(0,n)};var ir=class{data=[];seenTags=new Set;addRequest(e,t){this.data.push(...e.map(n=>{let r=structuredClone(n);return{role:n.role,chat:[{index:t,value:r}]}}))}addFunctionResults(e){let t=e.map(({index:r,...o})=>({index:r,value:structuredClone(o)})),n=this.getLast();n?.role==="function"?n.chat.push(...t):this.data.push({role:"function",chat:t})}addResponse(e){let t=e.map(({index:n,...r})=>({index:n,value:structuredClone(r)}));this.data.push({role:"assistant",chat:t})}updateResult({content:e,name:t,functionCalls:n,thought:r,thoughtBlocks:o,index:i}){let a=this.data.at(-1);if(!a||a.role!=="assistant"||a.role==="assistant"&&!a.updatable){this.data.push({role:"assistant",updatable:!0,chat:[{index:i,value:structuredClone({content:e,name:t,functionCalls:n,thought:r,thoughtBlocks:o})}]});return}let l=a.chat.find(u=>u.index===i);if(!l){a.chat.push({index:i,value:structuredClone({content:e,name:t,functionCalls:n,thought:r,thoughtBlocks:o})});return}if(typeof e=="string"&&e.trim()!==""&&(l.value.content=e),typeof t=="string"&&t.trim()!==""&&(l.value.name=t),Array.isArray(n)&&n.length>0&&(l.value.functionCalls=n),typeof r=="string"&&r.trim()!==""){let u=l.value.thought;l.value.thought=typeof u=="string"?u+r:r}if(Array.isArray(o)&&o.length>0){let u=l.value.thoughtBlocks??[];for(let c of o){let p=u.length>0?u[u.length-1]:void 0;!c.signature&&c.data?p&&!p.signature?(p.data=(p.data??"")+c.data,c.encrypted&&(p.encrypted=!0)):u.push(structuredClone(c)):c.signature?p&&!p.signature?(p.data=(p.data??"")+c.data,p.signature=c.signature,c.encrypted&&(p.encrypted=!0)):u.push(structuredClone(c)):u.length===0&&u.push(structuredClone(c))}l.value.thoughtBlocks=u,u.length>0&&(l.value.thought=u.map(c=>c.data).join(""))}}addTag(e){let t=this.data.at(-1);t&&(t.tags||(t.tags=[]),t.tags.includes(e)||t.tags.push(e),this.seenTags.add(e))}rewindToTag(e){let t=this.data.findIndex(n=>n.tags?.includes(e));if(t===-1){if(!this.seenTags.has(e))throw new Error(`Tag "${e}" not found`);return[]}return this.data.splice(t)}removeByTag(e){let t=this.data.reduce((n,r,o)=>(r.tags?.includes(e)&&n.push(o),n),[]);return t.length===0?[]:t.reverse().map(n=>this.data.splice(n,1).at(0)).filter(n=>n!==void 0).reverse()}history(e){let t=[];for(let{role:n,chat:r}of this.data){let o;n==="function"?o=r.filter(i=>i.index===e).map(i=>i.value):o=r.find(i=>i.index===e)?.value,Array.isArray(o)&&o.length>0?t.push(...o.map(i=>({...i,role:n}))):typeof o=="object"&&o!==null&&t.push({...o,role:n})}return t}getLast(){return this.data.at(-1)}reset(){this.data=[],this.seenTags=new Set}},xn=class{memories=new Map;defaultMemory;constructor(){this.defaultMemory=new ir}getMemory(e){return e?(this.memories.has(e)||this.memories.set(e,new ir),this.memories.get(e)):this.defaultMemory}addRequest(e,t){for(let n of e)Ht(n);this.getMemory(t).addRequest(e,0)}addResponse(e,t){Gr(e),this.getMemory(t).addResponse(e)}addFunctionResults(e,t){this.getMemory(t).addFunctionResults(e)}updateResult(e,t){this.getMemory(t).updateResult(e)}addTag(e,t){this.getMemory(t).addTag(e)}rewindToTag(e,t){return this.getMemory(t).rewindToTag(e)}removeByTag(e,t){return this.getMemory(t).removeByTag(e)}history(e,t){return this.getMemory(t).history(e)}getLast(e){return this.getMemory(e).getLast()}reset(e){e?this.memories.set(e,new ir):this.defaultMemory.reset()}};var pt=class extends Error{constructor({message:e}){super(e),this.name="AxAssertionError"}getFixingInstructions=()=>{let e=[],t=this.message.trim();return e.push({name:"error",title:"Follow these instructions",description:t+(t.endsWith(".")?"":".")}),e};toString(){return`${this.name}: ${this.message}`}[Symbol.for("nodejs.util.inspect.custom")](e,t){return this.toString()}},Ao=async(s,e)=>{for(let t of s){let{fn:n,message:r}=t,o=await n(e);if(o!==void 0){if(typeof o=="string")throw new pt({message:o});if(!o)throw r?new pt({message:r}):new Error("Assertion Failed: No message provided for assertion")}}},Xs=async(s,e,t,n=!1)=>{if(!e.currField||e.s===-1||!s||s.length===0)return;let r=s.filter(i=>i.fieldName===e.currField?.name);if(r.length===0)return;let o=t.substring(e.s);for(let i of r){let{message:a,fn:l}=i,u=await l(o,n);if(u!==void 0){if(typeof u=="string")throw new pt({message:u});if(!u&&a)throw new pt({message:a})}}};var ei={enabled:!0,enabledCategories:["generation","streaming","functions","errors","performance"],maxLabelLength:100,samplingRate:1},ar,ti=s=>{if(ar)return ar;let e=s??te.meter;if(e)return ar=Bc(e),ar};var ul=()=>{let s=[];return te.meter||s.push("Global meter not initialized"),!ar&&te.meter&&s.push("Metrics instruments not created despite available meter"),{healthy:s.length===0,issues:s}},Bc=s=>({generationLatencyHistogram:s.createHistogram("ax_gen_generation_duration_ms",{description:"End-to-end duration of AxGen generation requests",unit:"ms"}),generationRequestsCounter:s.createCounter("ax_gen_generation_requests_total",{description:"Total number of AxGen generation requests"}),generationErrorsCounter:s.createCounter("ax_gen_generation_errors_total",{description:"Total number of failed AxGen generations"}),multiStepGenerationsCounter:s.createCounter("ax_gen_multistep_generations_total",{description:"Total number of generations that required multiple steps"}),stepsPerGenerationHistogram:s.createHistogram("ax_gen_steps_per_generation",{description:"Number of steps taken per generation"}),maxStepsReachedCounter:s.createCounter("ax_gen_max_steps_reached_total",{description:"Total number of generations that hit max steps limit"}),validationErrorsCounter:s.createCounter("ax_gen_validation_errors_total",{description:"Total number of validation errors encountered"}),assertionErrorsCounter:s.createCounter("ax_gen_assertion_errors_total",{description:"Total number of assertion errors encountered"}),errorCorrectionAttemptsHistogram:s.createHistogram("ax_gen_error_correction_attempts",{description:"Number of error correction attempts per generation"}),errorCorrectionSuccessCounter:s.createCounter("ax_gen_error_correction_success_total",{description:"Total number of successful error corrections"}),errorCorrectionFailureCounter:s.createCounter("ax_gen_error_correction_failure_total",{description:"Total number of failed error corrections"}),maxRetriesReachedCounter:s.createCounter("ax_gen_max_retries_reached_total",{description:"Total number of generations that hit max retries limit"}),functionsEnabledGenerationsCounter:s.createCounter("ax_gen_functions_enabled_generations_total",{description:"Total number of generations with functions enabled"}),functionCallStepsCounter:s.createCounter("ax_gen_function_call_steps_total",{description:"Total number of steps that included function calls"}),functionsExecutedPerGenerationHistogram:s.createHistogram("ax_gen_functions_executed_per_generation",{description:"Number of unique functions executed per generation"}),functionErrorCorrectionCounter:s.createCounter("ax_gen_function_error_correction_total",{description:"Total number of function-related error corrections"}),fieldProcessorsExecutedCounter:s.createCounter("ax_gen_field_processors_executed_total",{description:"Total number of field processors executed"}),streamingFieldProcessorsExecutedCounter:s.createCounter("ax_gen_streaming_field_processors_executed_total",{description:"Total number of streaming field processors executed"}),streamingGenerationsCounter:s.createCounter("ax_gen_streaming_generations_total",{description:"Total number of streaming generations"}),streamingDeltasEmittedCounter:s.createCounter("ax_gen_streaming_deltas_emitted_total",{description:"Total number of streaming deltas emitted"}),streamingFinalizationLatencyHistogram:s.createHistogram("ax_gen_streaming_finalization_duration_ms",{description:"Duration of streaming response finalization",unit:"ms"}),samplesGeneratedHistogram:s.createHistogram("ax_gen_samples_generated",{description:"Number of samples generated per request"}),resultPickerUsageCounter:s.createCounter("ax_gen_result_picker_usage_total",{description:"Total number of times result picker was used"}),resultPickerLatencyHistogram:s.createHistogram("ax_gen_result_picker_duration_ms",{description:"Duration of result picker execution",unit:"ms"}),inputFieldsGauge:s.createGauge("ax_gen_input_fields",{description:"Number of input fields in signature"}),outputFieldsGauge:s.createGauge("ax_gen_output_fields",{description:"Number of output fields in signature"}),examplesUsedGauge:s.createGauge("ax_gen_examples_used",{description:"Number of examples used in generation"}),demosUsedGauge:s.createGauge("ax_gen_demos_used",{description:"Number of demos used in generation"}),promptRenderLatencyHistogram:s.createHistogram("ax_gen_prompt_render_duration_ms",{description:"Duration of prompt template rendering",unit:"ms"}),extractionLatencyHistogram:s.createHistogram("ax_gen_extraction_duration_ms",{description:"Duration of value extraction from responses",unit:"ms"}),assertionLatencyHistogram:s.createHistogram("ax_gen_assertion_duration_ms",{description:"Duration of assertion checking",unit:"ms"}),stateCreationLatencyHistogram:s.createHistogram("ax_gen_state_creation_duration_ms",{description:"Duration of state creation for multiple samples",unit:"ms"}),memoryUpdateLatencyHistogram:s.createHistogram("ax_gen_memory_update_duration_ms",{description:"Duration of memory updates during generation",unit:"ms"})}),yo=ei,cl=s=>{yo={...yo,...s}},pl=()=>({...yo}),lt=s=>{let e={};for(let[t,n]of Object.entries(s))if(n!=null){let r=String(n),o=yo.maxLabelLength;e[t]=r.length>o?r.substring(0,o):r}return e},dl=(s,e,t,n,r,o)=>{try{let i=lt({success:t.toString(),...n?{signature:n}:{},...r?{ai_service:r}:{},...o?{model:o}:{}});s.generationLatencyHistogram&&s.generationLatencyHistogram.record(e,i),s.generationRequestsCounter&&s.generationRequestsCounter.add(1,i),!t&&s.generationErrorsCounter&&s.generationErrorsCounter.add(1,i)}catch(i){console.warn("Failed to record generation metric:",i)}},bo=(s,e,t,n)=>{try{let r=lt({...n?{signature:n}:{}});e>1&&s.multiStepGenerationsCounter&&s.multiStepGenerationsCounter.add(1,r),s.stepsPerGenerationHistogram&&s.stepsPerGenerationHistogram.record(e,r),e>=t&&s.maxStepsReachedCounter&&s.maxStepsReachedCounter.add(1,r)}catch(r){console.warn("Failed to record multi-step metric:",r)}},ni=(s,e,t)=>{try{let n=lt({error_type:e,...t?{signature:t}:{}});e==="validation"&&s.validationErrorsCounter&&s.validationErrorsCounter.add(1,n),e==="assertion"&&s.assertionErrorsCounter&&s.assertionErrorsCounter.add(1,n)}catch(n){console.warn("Failed to record validation error metric:",n)}},ml=(s,e)=>{try{let t=lt({error_type:"refusal",...e?{signature:e}:{}});s.validationErrorsCounter&&s.validationErrorsCounter.add(1,t)}catch(t){console.warn("Failed to record refusal error metric:",t)}},ri=(s,e,t,n,r)=>{try{let o=lt({success:t.toString(),...r?{signature:r}:{}});s.errorCorrectionAttemptsHistogram&&s.errorCorrectionAttemptsHistogram.record(e,o),t&&s.errorCorrectionSuccessCounter&&s.errorCorrectionSuccessCounter.add(1,o),t||(s.errorCorrectionFailureCounter&&s.errorCorrectionFailureCounter.add(1,o),e>=n&&s.maxRetriesReachedCounter&&s.maxRetriesReachedCounter.add(1,o))}catch(o){console.warn("Failed to record error correction metric:",o)}},gl=(s,e,t,n,r=!1,o)=>{try{let i=lt({functions_enabled:e.toString(),had_function_calls:n.toString(),...o?{signature:o}:{}});e&&s.functionsEnabledGenerationsCounter&&s.functionsEnabledGenerationsCounter.add(1,i),n&&s.functionCallStepsCounter&&s.functionCallStepsCounter.add(1,i),t>0&&s.functionsExecutedPerGenerationHistogram&&s.functionsExecutedPerGenerationHistogram.record(t,i),r&&s.functionErrorCorrectionCounter&&s.functionErrorCorrectionCounter.add(1,i)}catch(i){console.warn("Failed to record function calling metric:",i)}},hl=(s,e,t,n)=>{try{let r=lt({...n?{signature:n}:{}});e>0&&s.fieldProcessorsExecutedCounter&&s.fieldProcessorsExecutedCounter.add(e,r),t>0&&s.streamingFieldProcessorsExecutedCounter&&s.streamingFieldProcessorsExecutedCounter.add(t,r)}catch(r){console.warn("Failed to record field processing metric:",r)}},fl=(s,e,t,n,r)=>{try{let o=lt({is_streaming:e.toString(),...r?{signature:r}:{}});e&&s.streamingGenerationsCounter&&s.streamingGenerationsCounter.add(1,o),t>0&&s.streamingDeltasEmittedCounter&&s.streamingDeltasEmittedCounter.add(t,o),n&&s.streamingFinalizationLatencyHistogram&&s.streamingFinalizationLatencyHistogram.record(n,o)}catch(o){console.warn("Failed to record streaming metric:",o)}},xl=(s,e,t,n,r)=>{try{let o=lt({result_picker_used:t.toString(),...r?{signature:r}:{}});s.samplesGeneratedHistogram&&s.samplesGeneratedHistogram.record(e,o),t&&s.resultPickerUsageCounter&&s.resultPickerUsageCounter.add(1,o),n&&s.resultPickerLatencyHistogram&&s.resultPickerLatencyHistogram.record(n,o)}catch(o){console.warn("Failed to record samples metric:",o)}},Al=(s,e,t,n,r,o)=>{try{let i=lt({...o?{signature:o}:{}});s.inputFieldsGauge&&s.inputFieldsGauge.record(e,i),s.outputFieldsGauge&&s.outputFieldsGauge.record(t,i),s.examplesUsedGauge&&s.examplesUsedGauge.record(n,i),s.demosUsedGauge&&s.demosUsedGauge.record(r,i)}catch(i){console.warn("Failed to record signature complexity metrics:",i)}},Io=(s,e,t,n)=>{try{let r=lt({metric_type:e,...n?{signature:n}:{}});switch(e){case"prompt_render":s.promptRenderLatencyHistogram&&s.promptRenderLatencyHistogram.record(t,r);break;case"extraction":s.extractionLatencyHistogram&&s.extractionLatencyHistogram.record(t,r);break;case"assertion":s.assertionLatencyHistogram&&s.assertionLatencyHistogram.record(t,r);break;case"state_creation":s.stateCreationLatencyHistogram&&s.stateCreationLatencyHistogram.record(t,r);break;case"memory_update":s.memoryUpdateLatencyHistogram&&s.memoryUpdateLatencyHistogram.record(t,r);break}}catch(r){console.warn("Failed to record performance metric:",r)}};var An=s=>{let e=(()=>{switch(s?.name){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"date":return'date ("YYYY-MM-DD" format)';case"datetime":return'date time ("YYYY-MM-DD HH:mm Timezone" format)';case"json":return"JSON object";case"class":return"classification class";case"code":return"code";case"object":return"object";default:return"string"}})();return s?.isArray?`array of ${e}s`:e},Ee=class extends Error{constructor(e){super(e),this.name="ValidationError"}getFixingInstructions=()=>[{name:"outputError",title:"Invalid Field",description:this.message}];toString(){return`${this.name}: ${this.message}`}[Symbol.for("nodejs.util.inspect.custom")](e,t){return this.toString()}},yl=s=>{let t=s.map(n=>`'${n.title}' (${An(n.type)})`).join(", ");return new Ee(`Required field not found: ${t}. Add a line starting with the exact label followed by a colon (e.g., "${s[0]?.title}:") and then provide a valid ${An(s[0]?.type)} value. Keep the output concise and avoid unrelated text.`)},To=s=>new Ee(`Expected (Required) field not found: '${s.title}'. Begin a new section with "${s.title}:" and then provide a valid ${An(s.type)} value directly after.`);var Co=s=>new Ee(`Required field is missing: '${s.title}'. After the "${s.title}:" label, provide a non-empty ${An(s.type)}. Do not use null, undefined, or leave it blank.`),bl=(s,e)=>new Ee(`Invalid JSON: ${e} in field '${s.title}'. Return only valid JSON. Prefer a fenced code block containing a single JSON object or array with no trailing text.`),Il=(s,e)=>new Ee(`Invalid Array: ${e} for '${s.title}'. Provide a JSON array of ${An(s.type)} items (e.g., [ ... ]). Markdown lists are also accepted if each item is on its own line starting with a hyphen.`),Tl=(s,e,t)=>new Ee(`Field '${s.title}' has an invalid value '${e}': ${t}. Provide a ${An(s.type)}. Ensure formatting exactly matches the expected type.`),Cl=(s,e,t)=>new Ee(`Invalid date for '${s.title}': ${t}. Use the exact format YYYY-MM-DD (e.g., 2024-05-09). You provided: ${e}.`),wl=(s,e,t)=>new Ee(`Invalid date/time for '${s.title}': ${t}. Use the format YYYY-MM-DD HH:mm or YYYY-MM-DD HH:mm:ss followed by a valid timezone (e.g., America/New_York). You provided: ${e}.`),oi=(s,e,t)=>new Ee(`Invalid URL for '${s.title}': ${t}. Use a valid URL format (e.g., https://example.com). You provided: ${e}.`),yn=(s,e,t,n)=>{let r=`Field '${s.title}' failed validation: `;return t==="minLength"?r+=`String must be at least ${n} characters long. You provided: "${e}" (${e.length} characters).`:t==="maxLength"?r+=`String must be at most ${n} characters long. You provided: "${e}" (${e.length} characters).`:t==="pattern"?r+=`String must match pattern /${n}/. You provided: "${e}".`:t==="format"&&(r+=`String must be a ${n}. You provided: "${e}".`),new Ee(r)},si=(s,e,t,n)=>{let r=`Field '${s.title}' failed validation: `;return t==="minimum"?r+=`Number must be at least ${n}. You provided: ${e}.`:t==="maximum"&&(r+=`Number must be at most ${n}. You provided: ${e}.`),new Ee(r)};var Rl=({error:s,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:o,span:i})=>{let a=s.getFixingInstructions();if(t&&n){let l=a?.map(u=>u.title).join(", ")??"";da(s,e,l,n)}return r&&ni(r,"validation",o),i&&i.addEvent("validation.error",{message:s.toString(),fixing_instructions:a?.map(l=>l.title).join(", ")??""}),a},vl=({error:s,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:o,span:i})=>{let a=s.getFixingInstructions();if(t&&n){let l=a?.map(u=>u.title).join(", ")??"";ma(s,e,l,n)}return r&&ni(r,"assertion",o),i&&i.addEvent("assertion.error",{message:s.toString(),fixing_instructions:a?.map(l=>l.title).join(", ")??""}),a},Sl=({error:s,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:o,span:i})=>{t&&n&&ga(s,e,n),r&&ml(r,o),i&&i.addEvent("refusal.error",{message:s.toString()})};function Ol(s,e){if(!e)return s;let t=[];if(e.format==="email"&&t.push("Must be a valid email address format"),(e.format==="uri"||e.format==="url"||e.name==="url")&&t.push("Must be a valid URL format"),(e.name==="string"||e.name==="code"||e.name==="url"||e.name==="date"||e.name==="datetime")&&(e.minLength!==void 0&&e.maxLength!==void 0?t.push(`Minimum length: ${e.minLength} characters, maximum length: ${e.maxLength} characters`):e.minLength!==void 0?t.push(`Minimum length: ${e.minLength} characters`):e.maxLength!==void 0&&t.push(`Maximum length: ${e.maxLength} characters`)),e.name==="number"&&(e.minimum!==void 0&&e.maximum!==void 0?t.push(`Minimum value: ${e.minimum}, maximum value: ${e.maximum}`):e.minimum!==void 0?t.push(`Minimum value: ${e.minimum}`):e.maximum!==void 0&&t.push(`Maximum value: ${e.maximum}`)),e.pattern!==void 0){if(!e.patternDescription)throw new Error(`Field with pattern '${e.pattern}' must include a patternDescription to explain the pattern to the LLM`);t.push(e.patternDescription)}if(e.name==="date"&&t.push("Format: YYYY-MM-DD"),e.name==="datetime"&&t.push("Format: ISO 8601 date-time"),t.length===0)return s;let n=t.join(". ");return!s||s.trim().length===0?n:`${s.trim().endsWith(".")?s.trim():`${s.trim()}.`} ${n}`}function vo(s,e="Schema"){if("name"in s&&"type"in s)return wo(s);let t={},n=[];for(let r of s){if(r.isInternal)continue;let o=wo(r);t[r.name]=o,r.isOptional||n.push(r.name)}return{type:"object",title:e,properties:t,required:n,additionalProperties:!1}}function wo(s,e=!1){let t=s.type,n=Ol(s.description,t);if(e&&t?.name&&(t.name==="image"||t.name==="audio"||t.name==="file"))throw new Error(`Media type '${t.name}' is not allowed in nested object fields. Media types (image, audio, file) can only be used as top-level input fields. Field: ${s.name}`);let r={};if(n&&(r.description=n),t?.isArray)if(r.type="array",t.fields){r.items={type:"object",properties:{},required:[],additionalProperties:!1},t.description&&(r.items.description=t.description);for(let[o,i]of Object.entries(t.fields)){let a={name:o,description:i.description,type:{name:i.type,isArray:i.isArray,options:i.options?[...i.options]:void 0,fields:i.fields,minLength:i.minLength,maxLength:i.maxLength,minimum:i.minimum,maximum:i.maximum,pattern:i.pattern,patternDescription:i.patternDescription,format:i.format},isOptional:i.isOptional,isInternal:i.isInternal};r.items.properties[o]=wo(a,!0),i.isOptional||r.items.required.push(o)}}else if(t.name==="class"&&t.options)r.items={type:"string",enum:t.options};else{let o=Ol(t.description||s.description,t);r.items={type:kl(t.name)},o&&(r.items.description=o),t.name==="string"||t.name==="code"||t.name==="url"||t.name==="date"||t.name==="datetime"?(t.minLength!==void 0&&(r.items.minLength=t.minLength),t.maxLength!==void 0&&(r.items.maxLength=t.maxLength),t.pattern!==void 0&&(r.items.pattern=t.pattern),t.format!==void 0&&(r.items.format=t.format)):t.name==="number"&&(t.minimum!==void 0&&(r.items.minimum=t.minimum),t.maximum!==void 0&&(r.items.maximum=t.maximum))}else if(t?.name==="object"&&t.fields){r.type="object",r.properties={},r.required=[],r.additionalProperties=!1;for(let[o,i]of Object.entries(t.fields)){let a={name:o,description:i.description,type:{name:i.type,isArray:i.isArray,options:i.options?[...i.options]:void 0,fields:i.fields,minLength:i.minLength,maxLength:i.maxLength,minimum:i.minimum,maximum:i.maximum,pattern:i.pattern,patternDescription:i.patternDescription,format:i.format},isOptional:i.isOptional,isInternal:i.isInternal};r.properties[o]=wo(a,!0),i.isOptional||r.required.push(o)}}else t?.name==="class"&&t.options?(r.type="string",r.enum=t.options):(r.type=kl(t?.name??"string"),t?.name==="string"||t?.name==="code"||t?.name==="url"||t?.name==="date"||t?.name==="datetime"?(t.minLength!==void 0&&(r.minLength=t.minLength),t.maxLength!==void 0&&(r.maxLength=t.maxLength),t.pattern!==void 0&&(r.pattern=t.pattern),t.format!==void 0&&(r.format=t.format),t.name==="url"&&!t.format&&(r.format="uri"),t.name==="date"&&!t.format&&(r.format="date"),t.name==="datetime"&&!t.format&&(r.format="date-time")):t?.name==="number"&&(t.minimum!==void 0&&(r.minimum=t.minimum),t.maximum!==void 0&&(r.maximum=t.maximum)));return r}function kl(s){switch(s){case"string":case"code":case"url":case"date":case"datetime":case"image":case"audio":case"file":return"string";case"number":return"number";case"boolean":return"boolean";case"json":case"object":return["object","array","string","number","boolean","null"];default:return"string"}}function Ro(s){if(!s||typeof s!="object")throw new Error("Schema must be an object");if(s.type==="array"){if(!s.items)throw new Error('Array schema is missing an "items" definition (required by JSON Schema and all LLM providers for function tools)');Ro(s.items)}else if(s.type==="object"&&s.properties)for(let e of Object.values(s.properties))Ro(e)}var $t=class extends Error{calls;constructor(e){super(`Stop function executed: ${e.map(t=>t.func.name).join(", ")}`),this.name="AxStopFunctionCallException",this.calls=e}},lr=class extends Error{constructor(t){super();this.fields=t;this.name="AxFunctionError"}getFields=()=>this.fields;toString(){return[`${this.name}: Function validation error`,...this.fields.map(t=>` - ${t.field}: ${t.message}`)].join(`
203
+ `,o=l}),(o>t||n.length===0)&&n.push(r.trim()),n},zc=(i,e=.1)=>{let t=[...i].sort((r,o)=>r.score-o.score),n=Math.ceil(t.length*e);return t.slice(0,n)};var ir=class{data=[];seenTags=new Set;addRequest(e,t){this.data.push(...e.map(n=>{let r=structuredClone(n);return{role:n.role,chat:[{index:t,value:r}]}}))}addFunctionResults(e){let t=e.map(({index:r,...o})=>({index:r,value:structuredClone(o)})),n=this.getLast();n?.role==="function"?n.chat.push(...t):this.data.push({role:"function",chat:t})}addResponse(e){let t=e.map(({index:n,...r})=>({index:n,value:structuredClone(r)}));this.data.push({role:"assistant",chat:t})}updateResult({content:e,name:t,functionCalls:n,thought:r,thoughtBlocks:o,index:s}){let a=this.data.at(-1);if(!a||a.role!=="assistant"||a.role==="assistant"&&!a.updatable){this.data.push({role:"assistant",updatable:!0,chat:[{index:s,value:structuredClone({content:e,name:t,functionCalls:n,thought:r,thoughtBlocks:o})}]});return}let l=a.chat.find(u=>u.index===s);if(!l){a.chat.push({index:s,value:structuredClone({content:e,name:t,functionCalls:n,thought:r,thoughtBlocks:o})});return}if(typeof e=="string"&&e.trim()!==""&&(l.value.content=e),typeof t=="string"&&t.trim()!==""&&(l.value.name=t),Array.isArray(n)&&n.length>0&&(l.value.functionCalls=n),typeof r=="string"&&r.trim()!==""){let u=l.value.thought;l.value.thought=typeof u=="string"?u+r:r}if(Array.isArray(o)&&o.length>0){let u=l.value.thoughtBlocks??[];for(let c of o){let p=u.length>0?u[u.length-1]:void 0;!c.signature&&c.data?p&&!p.signature?(p.data=(p.data??"")+c.data,c.encrypted&&(p.encrypted=!0)):u.push(structuredClone(c)):c.signature?p&&!p.signature?(p.data=(p.data??"")+c.data,p.signature=c.signature,c.encrypted&&(p.encrypted=!0)):u.push(structuredClone(c)):u.length===0&&u.push(structuredClone(c))}l.value.thoughtBlocks=u,u.length>0&&(l.value.thought=u.map(c=>c.data).join(""))}}addTag(e){let t=this.data.at(-1);t&&(t.tags||(t.tags=[]),t.tags.includes(e)||t.tags.push(e),this.seenTags.add(e))}rewindToTag(e){let t=this.data.findIndex(n=>n.tags?.includes(e));if(t===-1){if(!this.seenTags.has(e))throw new Error(`Tag "${e}" not found`);return[]}return this.data.splice(t)}removeByTag(e){let t=this.data.reduce((n,r,o)=>(r.tags?.includes(e)&&n.push(o),n),[]);return t.length===0?[]:t.reverse().map(n=>this.data.splice(n,1).at(0)).filter(n=>n!==void 0).reverse()}history(e){let t=[];for(let{role:n,chat:r}of this.data){let o;n==="function"?o=r.filter(s=>s.index===e).map(s=>s.value):o=r.find(s=>s.index===e)?.value,Array.isArray(o)&&o.length>0?t.push(...o.map(s=>({...s,role:n}))):typeof o=="object"&&o!==null&&t.push({...o,role:n})}return t}getLast(){return this.data.at(-1)}reset(){this.data=[],this.seenTags=new Set}},xn=class{memories=new Map;defaultMemory;constructor(){this.defaultMemory=new ir}getMemory(e){return e?(this.memories.has(e)||this.memories.set(e,new ir),this.memories.get(e)):this.defaultMemory}addRequest(e,t){for(let n of e)Ht(n);this.getMemory(t).addRequest(e,0)}addResponse(e,t){Ur(e),this.getMemory(t).addResponse(e)}addFunctionResults(e,t){this.getMemory(t).addFunctionResults(e)}updateResult(e,t){this.getMemory(t).updateResult(e)}addTag(e,t){this.getMemory(t).addTag(e)}rewindToTag(e,t){return this.getMemory(t).rewindToTag(e)}removeByTag(e,t){return this.getMemory(t).removeByTag(e)}history(e,t){return this.getMemory(t).history(e)}getLast(e){return this.getMemory(e).getLast()}reset(e){e?this.memories.set(e,new ir):this.defaultMemory.reset()}};var pt=class extends Error{constructor({message:e}){super(e),this.name="AxAssertionError"}getFixingInstructions=()=>{let e=[],t=this.message.trim();return e.push({name:"error",title:"Follow these instructions",description:t+(t.endsWith(".")?"":".")}),e};toString(){return`${this.name}: ${this.message}`}[Symbol.for("nodejs.util.inspect.custom")](e,t){return this.toString()}},yo=async(i,e)=>{for(let t of i){let{fn:n,message:r}=t,o=await n(e);if(o!==void 0){if(typeof o=="string")throw new pt({message:o});if(!o)throw r?new pt({message:r}):new Error("Assertion Failed: No message provided for assertion")}}},ti=async(i,e,t,n=!1)=>{if(!e.currField||e.s===-1||!i||i.length===0)return;let r=i.filter(s=>s.fieldName===e.currField?.name);if(r.length===0)return;let o=t.substring(e.s);for(let s of r){let{message:a,fn:l}=s,u=await l(o,n);if(u!==void 0){if(typeof u=="string")throw new pt({message:u});if(!u&&a)throw new pt({message:a})}}};var ni={enabled:!0,enabledCategories:["generation","streaming","functions","errors","performance"],maxLabelLength:100,samplingRate:1},ar,ri=i=>{if(ar)return ar;let e=i??ee.meter;if(e)return ar=Hc(e),ar};var ml=()=>{let i=[];return ee.meter||i.push("Global meter not initialized"),!ar&&ee.meter&&i.push("Metrics instruments not created despite available meter"),{healthy:i.length===0,issues:i}},Hc=i=>({generationLatencyHistogram:i.createHistogram("ax_gen_generation_duration_ms",{description:"End-to-end duration of AxGen generation requests",unit:"ms"}),generationRequestsCounter:i.createCounter("ax_gen_generation_requests_total",{description:"Total number of AxGen generation requests"}),generationErrorsCounter:i.createCounter("ax_gen_generation_errors_total",{description:"Total number of failed AxGen generations"}),multiStepGenerationsCounter:i.createCounter("ax_gen_multistep_generations_total",{description:"Total number of generations that required multiple steps"}),stepsPerGenerationHistogram:i.createHistogram("ax_gen_steps_per_generation",{description:"Number of steps taken per generation"}),maxStepsReachedCounter:i.createCounter("ax_gen_max_steps_reached_total",{description:"Total number of generations that hit max steps limit"}),validationErrorsCounter:i.createCounter("ax_gen_validation_errors_total",{description:"Total number of validation errors encountered"}),assertionErrorsCounter:i.createCounter("ax_gen_assertion_errors_total",{description:"Total number of assertion errors encountered"}),errorCorrectionAttemptsHistogram:i.createHistogram("ax_gen_error_correction_attempts",{description:"Number of error correction attempts per generation"}),errorCorrectionSuccessCounter:i.createCounter("ax_gen_error_correction_success_total",{description:"Total number of successful error corrections"}),errorCorrectionFailureCounter:i.createCounter("ax_gen_error_correction_failure_total",{description:"Total number of failed error corrections"}),maxRetriesReachedCounter:i.createCounter("ax_gen_max_retries_reached_total",{description:"Total number of generations that hit max retries limit"}),functionsEnabledGenerationsCounter:i.createCounter("ax_gen_functions_enabled_generations_total",{description:"Total number of generations with functions enabled"}),functionCallStepsCounter:i.createCounter("ax_gen_function_call_steps_total",{description:"Total number of steps that included function calls"}),functionsExecutedPerGenerationHistogram:i.createHistogram("ax_gen_functions_executed_per_generation",{description:"Number of unique functions executed per generation"}),functionErrorCorrectionCounter:i.createCounter("ax_gen_function_error_correction_total",{description:"Total number of function-related error corrections"}),fieldProcessorsExecutedCounter:i.createCounter("ax_gen_field_processors_executed_total",{description:"Total number of field processors executed"}),streamingFieldProcessorsExecutedCounter:i.createCounter("ax_gen_streaming_field_processors_executed_total",{description:"Total number of streaming field processors executed"}),streamingGenerationsCounter:i.createCounter("ax_gen_streaming_generations_total",{description:"Total number of streaming generations"}),streamingDeltasEmittedCounter:i.createCounter("ax_gen_streaming_deltas_emitted_total",{description:"Total number of streaming deltas emitted"}),streamingFinalizationLatencyHistogram:i.createHistogram("ax_gen_streaming_finalization_duration_ms",{description:"Duration of streaming response finalization",unit:"ms"}),samplesGeneratedHistogram:i.createHistogram("ax_gen_samples_generated",{description:"Number of samples generated per request"}),resultPickerUsageCounter:i.createCounter("ax_gen_result_picker_usage_total",{description:"Total number of times result picker was used"}),resultPickerLatencyHistogram:i.createHistogram("ax_gen_result_picker_duration_ms",{description:"Duration of result picker execution",unit:"ms"}),inputFieldsGauge:i.createGauge("ax_gen_input_fields",{description:"Number of input fields in signature"}),outputFieldsGauge:i.createGauge("ax_gen_output_fields",{description:"Number of output fields in signature"}),examplesUsedGauge:i.createGauge("ax_gen_examples_used",{description:"Number of examples used in generation"}),demosUsedGauge:i.createGauge("ax_gen_demos_used",{description:"Number of demos used in generation"}),promptRenderLatencyHistogram:i.createHistogram("ax_gen_prompt_render_duration_ms",{description:"Duration of prompt template rendering",unit:"ms"}),extractionLatencyHistogram:i.createHistogram("ax_gen_extraction_duration_ms",{description:"Duration of value extraction from responses",unit:"ms"}),assertionLatencyHistogram:i.createHistogram("ax_gen_assertion_duration_ms",{description:"Duration of assertion checking",unit:"ms"}),stateCreationLatencyHistogram:i.createHistogram("ax_gen_state_creation_duration_ms",{description:"Duration of state creation for multiple samples",unit:"ms"}),memoryUpdateLatencyHistogram:i.createHistogram("ax_gen_memory_update_duration_ms",{description:"Duration of memory updates during generation",unit:"ms"})}),bo=ni,gl=i=>{bo={...bo,...i}},hl=()=>({...bo}),lt=i=>{let e={};for(let[t,n]of Object.entries(i))if(n!=null){let r=String(n),o=bo.maxLabelLength;e[t]=r.length>o?r.substring(0,o):r}return e},fl=(i,e,t,n,r,o)=>{try{let s=lt({success:t.toString(),...n?{signature:n}:{},...r?{ai_service:r}:{},...o?{model:o}:{}});i.generationLatencyHistogram&&i.generationLatencyHistogram.record(e,s),i.generationRequestsCounter&&i.generationRequestsCounter.add(1,s),!t&&i.generationErrorsCounter&&i.generationErrorsCounter.add(1,s)}catch(s){console.warn("Failed to record generation metric:",s)}},Io=(i,e,t,n)=>{try{let r=lt({...n?{signature:n}:{}});e>1&&i.multiStepGenerationsCounter&&i.multiStepGenerationsCounter.add(1,r),i.stepsPerGenerationHistogram&&i.stepsPerGenerationHistogram.record(e,r),e>=t&&i.maxStepsReachedCounter&&i.maxStepsReachedCounter.add(1,r)}catch(r){console.warn("Failed to record multi-step metric:",r)}},oi=(i,e,t)=>{try{let n=lt({error_type:e,...t?{signature:t}:{}});e==="validation"&&i.validationErrorsCounter&&i.validationErrorsCounter.add(1,n),e==="assertion"&&i.assertionErrorsCounter&&i.assertionErrorsCounter.add(1,n)}catch(n){console.warn("Failed to record validation error metric:",n)}},xl=(i,e)=>{try{let t=lt({error_type:"refusal",...e?{signature:e}:{}});i.validationErrorsCounter&&i.validationErrorsCounter.add(1,t)}catch(t){console.warn("Failed to record refusal error metric:",t)}},si=(i,e,t,n,r)=>{try{let o=lt({success:t.toString(),...r?{signature:r}:{}});i.errorCorrectionAttemptsHistogram&&i.errorCorrectionAttemptsHistogram.record(e,o),t&&i.errorCorrectionSuccessCounter&&i.errorCorrectionSuccessCounter.add(1,o),t||(i.errorCorrectionFailureCounter&&i.errorCorrectionFailureCounter.add(1,o),e>=n&&i.maxRetriesReachedCounter&&i.maxRetriesReachedCounter.add(1,o))}catch(o){console.warn("Failed to record error correction metric:",o)}},Al=(i,e,t,n,r=!1,o)=>{try{let s=lt({functions_enabled:e.toString(),had_function_calls:n.toString(),...o?{signature:o}:{}});e&&i.functionsEnabledGenerationsCounter&&i.functionsEnabledGenerationsCounter.add(1,s),n&&i.functionCallStepsCounter&&i.functionCallStepsCounter.add(1,s),t>0&&i.functionsExecutedPerGenerationHistogram&&i.functionsExecutedPerGenerationHistogram.record(t,s),r&&i.functionErrorCorrectionCounter&&i.functionErrorCorrectionCounter.add(1,s)}catch(s){console.warn("Failed to record function calling metric:",s)}},yl=(i,e,t,n)=>{try{let r=lt({...n?{signature:n}:{}});e>0&&i.fieldProcessorsExecutedCounter&&i.fieldProcessorsExecutedCounter.add(e,r),t>0&&i.streamingFieldProcessorsExecutedCounter&&i.streamingFieldProcessorsExecutedCounter.add(t,r)}catch(r){console.warn("Failed to record field processing metric:",r)}},bl=(i,e,t,n,r)=>{try{let o=lt({is_streaming:e.toString(),...r?{signature:r}:{}});e&&i.streamingGenerationsCounter&&i.streamingGenerationsCounter.add(1,o),t>0&&i.streamingDeltasEmittedCounter&&i.streamingDeltasEmittedCounter.add(t,o),n&&i.streamingFinalizationLatencyHistogram&&i.streamingFinalizationLatencyHistogram.record(n,o)}catch(o){console.warn("Failed to record streaming metric:",o)}},Il=(i,e,t,n,r)=>{try{let o=lt({result_picker_used:t.toString(),...r?{signature:r}:{}});i.samplesGeneratedHistogram&&i.samplesGeneratedHistogram.record(e,o),t&&i.resultPickerUsageCounter&&i.resultPickerUsageCounter.add(1,o),n&&i.resultPickerLatencyHistogram&&i.resultPickerLatencyHistogram.record(n,o)}catch(o){console.warn("Failed to record samples metric:",o)}},Tl=(i,e,t,n,r,o)=>{try{let s=lt({...o?{signature:o}:{}});i.inputFieldsGauge&&i.inputFieldsGauge.record(e,s),i.outputFieldsGauge&&i.outputFieldsGauge.record(t,s),i.examplesUsedGauge&&i.examplesUsedGauge.record(n,s),i.demosUsedGauge&&i.demosUsedGauge.record(r,s)}catch(s){console.warn("Failed to record signature complexity metrics:",s)}},To=(i,e,t,n)=>{try{let r=lt({metric_type:e,...n?{signature:n}:{}});switch(e){case"prompt_render":i.promptRenderLatencyHistogram&&i.promptRenderLatencyHistogram.record(t,r);break;case"extraction":i.extractionLatencyHistogram&&i.extractionLatencyHistogram.record(t,r);break;case"assertion":i.assertionLatencyHistogram&&i.assertionLatencyHistogram.record(t,r);break;case"state_creation":i.stateCreationLatencyHistogram&&i.stateCreationLatencyHistogram.record(t,r);break;case"memory_update":i.memoryUpdateLatencyHistogram&&i.memoryUpdateLatencyHistogram.record(t,r);break}}catch(r){console.warn("Failed to record performance metric:",r)}};var An=i=>{let e=(()=>{switch(i?.name){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"date":return'date ("YYYY-MM-DD" format)';case"datetime":return'date time ("YYYY-MM-DD HH:mm Timezone" format)';case"json":return"JSON object";case"class":return"classification class";case"code":return"code";case"object":return"object";default:return"string"}})();return i?.isArray?`array of ${e}s`:e},Me=class extends Error{constructor(e){super(e),this.name="ValidationError"}getFixingInstructions=()=>[{name:"outputError",title:"Invalid Field",description:this.message}];toString(){return`${this.name}: ${this.message}`}[Symbol.for("nodejs.util.inspect.custom")](e,t){return this.toString()}},Cl=i=>{let t=i.map(n=>`'${n.title}' (${An(n.type)})`).join(", ");return new Me(`Required field not found: ${t}. Add a line starting with the exact label followed by a colon (e.g., "${i[0]?.title}:") and then provide a valid ${An(i[0]?.type)} value. Keep the output concise and avoid unrelated text.`)},Co=i=>new Me(`Expected (Required) field not found: '${i.title}'. Begin a new section with "${i.title}:" and then provide a valid ${An(i.type)} value directly after.`);var wo=i=>new Me(`Required field is missing: '${i.title}'. After the "${i.title}:" label, provide a non-empty ${An(i.type)}. Do not use null, undefined, or leave it blank.`),wl=(i,e)=>new Me(`Invalid JSON: ${e} in field '${i.title}'. Return only valid JSON. Prefer a fenced code block containing a single JSON object or array with no trailing text.`),Rl=(i,e)=>new Me(`Invalid Array: ${e} for '${i.title}'. Provide a JSON array of ${An(i.type)} items (e.g., [ ... ]). Markdown lists are also accepted if each item is on its own line starting with a hyphen.`),vl=(i,e,t)=>new Me(`Field '${i.title}' has an invalid value '${e}': ${t}. Provide a ${An(i.type)}. Ensure formatting exactly matches the expected type.`),Sl=(i,e,t)=>new Me(`Invalid date for '${i.title}': ${t}. Use the exact format YYYY-MM-DD (e.g., 2024-05-09). You provided: ${e}.`),Ol=(i,e,t)=>new Me(`Invalid date/time for '${i.title}': ${t}. Use the format YYYY-MM-DD HH:mm or YYYY-MM-DD HH:mm:ss followed by a valid timezone (e.g., America/New_York). You provided: ${e}.`),ii=(i,e,t)=>new Me(`Invalid URL for '${i.title}': ${t}. Use a valid URL format (e.g., https://example.com). You provided: ${e}.`),yn=(i,e,t,n)=>{let r=`Field '${i.title}' failed validation: `;return t==="minLength"?r+=`String must be at least ${n} characters long. You provided: "${e}" (${e.length} characters).`:t==="maxLength"?r+=`String must be at most ${n} characters long. You provided: "${e}" (${e.length} characters).`:t==="pattern"?r+=`String must match pattern /${n}/. You provided: "${e}".`:t==="format"&&(r+=`String must be a ${n}. You provided: "${e}".`),new Me(r)},ai=(i,e,t,n)=>{let r=`Field '${i.title}' failed validation: `;return t==="minimum"?r+=`Number must be at least ${n}. You provided: ${e}.`:t==="maximum"&&(r+=`Number must be at most ${n}. You provided: ${e}.`),new Me(r)};var kl=({error:i,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:o,span:s})=>{let a=i.getFixingInstructions();if(t&&n){let l=a?.map(u=>u.title).join(", ")??"";ga(i,e,l,n)}return r&&oi(r,"validation",o),s&&s.addEvent("validation.error",{message:i.toString(),fixing_instructions:a?.map(l=>l.title).join(", ")??""}),a},Ml=({error:i,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:o,span:s})=>{let a=i.getFixingInstructions();if(t&&n){let l=a?.map(u=>u.title).join(", ")??"";ha(i,e,l,n)}return r&&oi(r,"assertion",o),s&&s.addEvent("assertion.error",{message:i.toString(),fixing_instructions:a?.map(l=>l.title).join(", ")??""}),a},El=({error:i,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:o,span:s})=>{t&&n&&fa(i,e,n),r&&xl(r,o),s&&s.addEvent("refusal.error",{message:i.toString()})};function Pl(i,e){if(!e)return i;let t=[];if(e.format==="email"&&t.push("Must be a valid email address format"),(e.format==="uri"||e.format==="url"||e.name==="url")&&t.push("Must be a valid URL format"),(e.name==="string"||e.name==="code"||e.name==="url"||e.name==="date"||e.name==="datetime")&&(e.minLength!==void 0&&e.maxLength!==void 0?t.push(`Minimum length: ${e.minLength} characters, maximum length: ${e.maxLength} characters`):e.minLength!==void 0?t.push(`Minimum length: ${e.minLength} characters`):e.maxLength!==void 0&&t.push(`Maximum length: ${e.maxLength} characters`)),e.name==="number"&&(e.minimum!==void 0&&e.maximum!==void 0?t.push(`Minimum value: ${e.minimum}, maximum value: ${e.maximum}`):e.minimum!==void 0?t.push(`Minimum value: ${e.minimum}`):e.maximum!==void 0&&t.push(`Maximum value: ${e.maximum}`)),e.pattern!==void 0){if(!e.patternDescription)throw new Error(`Field with pattern '${e.pattern}' must include a patternDescription to explain the pattern to the LLM`);t.push(e.patternDescription)}if(e.name==="date"&&t.push("Format: YYYY-MM-DD"),e.name==="datetime"&&t.push("Format: ISO 8601 date-time"),t.length===0)return i;let n=t.join(". ");return!i||i.trim().length===0?n:`${i.trim().endsWith(".")?i.trim():`${i.trim()}.`} ${n}`}function So(i,e="Schema"){if("name"in i&&"type"in i)return Ro(i);let t={},n=[];for(let r of i){if(r.isInternal)continue;let o=Ro(r);t[r.name]=o,r.isOptional||n.push(r.name)}return{type:"object",title:e,properties:t,required:n,additionalProperties:!1}}function Ro(i,e=!1){let t=i.type,n=Pl(i.description,t);if(e&&t?.name&&(t.name==="image"||t.name==="audio"||t.name==="file"))throw new Error(`Media type '${t.name}' is not allowed in nested object fields. Media types (image, audio, file) can only be used as top-level input fields. Field: ${i.name}`);let r={};if(n&&(r.description=n),t?.isArray)if(r.type="array",t.fields){r.items={type:"object",properties:{},required:[],additionalProperties:!1},t.description&&(r.items.description=t.description);for(let[o,s]of Object.entries(t.fields)){let a={name:o,description:s.description,type:{name:s.type,isArray:s.isArray,options:s.options?[...s.options]:void 0,fields:s.fields,minLength:s.minLength,maxLength:s.maxLength,minimum:s.minimum,maximum:s.maximum,pattern:s.pattern,patternDescription:s.patternDescription,format:s.format},isOptional:s.isOptional,isInternal:s.isInternal};r.items.properties[o]=Ro(a,!0),s.isOptional||r.items.required.push(o)}}else if(t.name==="class"&&t.options)r.items={type:"string",enum:t.options};else{let o=Pl(t.description||i.description,t);r.items={type:Fl(t.name)},o&&(r.items.description=o),t.name==="string"||t.name==="code"||t.name==="url"||t.name==="date"||t.name==="datetime"?(t.minLength!==void 0&&(r.items.minLength=t.minLength),t.maxLength!==void 0&&(r.items.maxLength=t.maxLength),t.pattern!==void 0&&(r.items.pattern=t.pattern),t.format!==void 0&&(r.items.format=t.format)):t.name==="number"&&(t.minimum!==void 0&&(r.items.minimum=t.minimum),t.maximum!==void 0&&(r.items.maximum=t.maximum))}else if(t?.name==="object"&&t.fields){r.type="object",r.properties={},r.required=[],r.additionalProperties=!1;for(let[o,s]of Object.entries(t.fields)){let a={name:o,description:s.description,type:{name:s.type,isArray:s.isArray,options:s.options?[...s.options]:void 0,fields:s.fields,minLength:s.minLength,maxLength:s.maxLength,minimum:s.minimum,maximum:s.maximum,pattern:s.pattern,patternDescription:s.patternDescription,format:s.format},isOptional:s.isOptional,isInternal:s.isInternal};r.properties[o]=Ro(a,!0),s.isOptional||r.required.push(o)}}else t?.name==="class"&&t.options?(r.type="string",r.enum=t.options):(r.type=Fl(t?.name??"string"),t?.name==="string"||t?.name==="code"||t?.name==="url"||t?.name==="date"||t?.name==="datetime"?(t.minLength!==void 0&&(r.minLength=t.minLength),t.maxLength!==void 0&&(r.maxLength=t.maxLength),t.pattern!==void 0&&(r.pattern=t.pattern),t.format!==void 0&&(r.format=t.format),t.name==="url"&&!t.format&&(r.format="uri"),t.name==="date"&&!t.format&&(r.format="date"),t.name==="datetime"&&!t.format&&(r.format="date-time")):t?.name==="number"&&(t.minimum!==void 0&&(r.minimum=t.minimum),t.maximum!==void 0&&(r.maximum=t.maximum)));return r}function Fl(i){switch(i){case"string":case"code":case"url":case"date":case"datetime":case"image":case"audio":case"file":return"string";case"number":return"number";case"boolean":return"boolean";case"json":case"object":return["object","array","string","number","boolean","null"];default:return"string"}}function vo(i){if(!i||typeof i!="object")throw new Error("Schema must be an object");if(i.type==="array"){if(!i.items)throw new Error('Array schema is missing an "items" definition (required by JSON Schema and all LLM providers for function tools)');vo(i.items)}else if(i.type==="object"&&i.properties)for(let e of Object.values(i.properties))vo(e)}var $t=class extends Error{calls;constructor(e){super(`Stop function executed: ${e.map(t=>t.func.name).join(", ")}`),this.name="AxStopFunctionCallException",this.calls=e}},lr=class extends Error{constructor(t){super();this.fields=t;this.name="AxFunctionError"}getFields=()=>this.fields;toString(){return[`${this.name}: Function validation error`,...this.fields.map(t=>` - ${t.field}: ${t.message}`)].join(`
204
204
  `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},ur=class extends Error{constructor(t,n,r){super();this.fields=t;this.func=n;this.funcId=r}getFunctionId=()=>this.funcId;getFieldDescription(t){if(!this.func.parameters?.properties?.[t])return"";let n=this.func.parameters.properties[t],r=n.description;return n.enum?.length&&(r+=` Allowed values are: ${n.enum.join(", ")}`),r}getFixingInstructions=()=>{let t=this.fields.map(n=>{let r=this.getFieldDescription(n.field)||"";return`- \`${n.field}\` - ${n.message} (${r}).`});return`Errors In Function Arguments: Fix the following invalid arguments to '${this.func.name}'
205
205
  ${t.join(`
206
206
  `)}`};toString(){return[`${this.name}: Function execution error in '${this.func.name}'`,...this.fields.map(t=>{let n=this.getFieldDescription(t.field);return` - ${t.field}: ${t.message}${n?` (${n})`:""}`}),this.funcId?` Function ID: ${this.funcId}`:""].join(`
207
- `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},cr=class{funcList=[];constructor(e){this.funcList=e}executeFunction=async(e,t,n)=>{let r;if(typeof t.args=="string"&&t.args.length>0)try{r=JSON.parse(t.args)}catch(u){throw new Error(`Invalid function arguments: ${t.args}`,{cause:u})}else r=t.args;let o=n?{sessionId:n.sessionId,traceId:n.traceId,ai:n.ai}:void 0,i;e.parameters?i=e.func.length===2?await e.func(r,o):await e.func(r):i=e.func.length===1?await e.func(o):await e.func();let l=(n?.functionResultFormatter??te.functionResultFormatter)(i);return{formatted:String(l),rawResult:i,parsedArgs:r}};executeWithDetails=async(e,t)=>{let n=i=>i.replace(/[^a-zA-Z0-9]/g,"").toLowerCase(),r=n(e.name),o=this.funcList.find(i=>i.name===e.name);if(o||(o=this.funcList.find(i=>n(i.name)===r)),!o)throw new Error(`Function not found: ${e.name}`);if(!o.func)throw new Error(`No handler for function: ${e.name}`);try{return await this.executeFunction(o,e,t)}catch(i){throw i instanceof lr?new ur(i.getFields(),o,e.id):i}};execute=async(e,t)=>(await this.executeWithDetails(e,t)).formatted},So=(s,e)=>{if(s.length===0)return[...e??[]];let t=s.map(n=>"toFunction"in n?n.toFunction():n).flat();for(let n of t.filter(r=>r.parameters))if(n.parameters)try{Ro(n.parameters)}catch(r){throw r instanceof Error?new Error(`Function '${n.name}' parameters schema is invalid.
207
+ `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},cr=class{funcList=[];constructor(e){this.funcList=e}executeFunction=async(e,t,n)=>{let r;if(typeof t.args=="string"&&t.args.length>0)try{r=JSON.parse(t.args)}catch(u){throw new Error(`Invalid function arguments: ${t.args}`,{cause:u})}else r=t.args;let o=n?{sessionId:n.sessionId,traceId:n.traceId,ai:n.ai}:void 0,s;e.parameters?s=e.func.length===2?await e.func(r,o):await e.func(r):s=e.func.length===1?await e.func(o):await e.func();let l=(n?.functionResultFormatter??ee.functionResultFormatter)(s);return{formatted:String(l),rawResult:s,parsedArgs:r}};executeWithDetails=async(e,t)=>{let n=s=>s.replace(/[^a-zA-Z0-9]/g,"").toLowerCase(),r=n(e.name),o=this.funcList.find(s=>s.name===e.name);if(o||(o=this.funcList.find(s=>n(s.name)===r)),!o)throw new Error(`Function not found: ${e.name}`);if(!o.func)throw new Error(`No handler for function: ${e.name}`);try{return await this.executeFunction(o,e,t)}catch(s){throw s instanceof lr?new ur(s.getFields(),o,e.id):s}};execute=async(e,t)=>(await this.executeWithDetails(e,t)).formatted},Oo=(i,e)=>{if(i.length===0)return[...e??[]];let t=i.map(n=>"toFunction"in n?n.toFunction():n).flat();for(let n of t.filter(r=>r.parameters))if(n.parameters)try{vo(n.parameters)}catch(r){throw r instanceof Error?new Error(`Function '${n.name}' parameters schema is invalid.
208
208
  ${r.message}
209
- Tip: Arrays must include an "items" schema (e.g., { items: { type: "string" } } or items: { type: "object", properties: { ... } }).`,{cause:r}):r}return[...e??[],...t]},Oo=async({ai:s,functionList:e,functionCalls:t,mem:n,sessionId:r,traceId:o,span:i,excludeContentFromTrace:a,index:l,functionResultFormatter:u,logger:c,debug:p,stopFunctionNames:d})=>{let m=new cr(e),g=new Set,f=[],h=b=>{let k=R=>R.replace(/[^a-zA-Z0-9]/g,"").toLowerCase(),S=k(b),M=e.find(R=>R.name===b);return M||(M=e.find(R=>k(R.name)===S)),M},x=t.map(b=>{if(!b.id)throw new Error(`Function ${b.name} did not return an ID`);let k=s.getOptions().tracer??te.tracer;return k?k.startActiveSpan(`Tool: ${b.name}`,async S=>{try{S?.setAttributes?.({"tool.name":b.name,"tool.mode":"native","function.id":b.id,"session.id":r??""});let{formatted:M,rawResult:R,parsedArgs:O}=await m.executeWithDetails(b,{sessionId:r,ai:s,functionResultFormatter:u,traceId:S?.spanContext?.().traceId??o,stopFunctionNames:d});if(g.add(b.name.toLowerCase()),d?.includes(b.name.toLowerCase())){let F=h(b.name);F&&f.push({func:F,args:O,result:R})}if(a?S.addEvent("gen_ai.tool.message",{name:b.name}):S.addEvent("gen_ai.tool.message",{name:b.name,args:b.args,result:M??""}),i){let F={name:b.name};a||(F.args=b.args,F.result=M??""),i.addEvent("function.call",F)}return{result:M??"",role:"function",functionId:b.id,index:l}}catch(M){if(S?.recordException?.(M),M instanceof ur){let R=M.getFixingInstructions(),O={name:b.name,message:M.toString()};return a||(O.args=b.args,O.fixing_instructions=R),S?.addEvent?.("function.error",O),p&&ws(M,l,R,c),{functionId:b.id,isError:!0,index:l,result:R,role:"function"}}throw M}finally{S?.end?.()}}):m.executeWithDetails(b,{sessionId:r,ai:s,functionResultFormatter:u,traceId:o,stopFunctionNames:d}).then(({formatted:S,rawResult:M,parsedArgs:R})=>{if(g.add(b.name.toLowerCase()),d?.includes(b.name.toLowerCase())){let O=h(b.name);O&&f.push({func:O,args:R,result:M})}if(i){let O={name:b.name};a||(O.args=b.args,O.result=S??""),i.addEvent("function.call",O)}return{result:S??"",role:"function",functionId:b.id,index:l}}).catch(S=>{if(!(S instanceof ur))throw S;let M=S.getFixingInstructions();if(i){let R={name:b.name,message:S.toString()};a||(R.args=b.args,R.fixing_instructions=M),i.addEvent("function.error",R)}return p&&ws(S,l,M,c),{functionId:b.id,isError:!0,index:l,result:M,role:"function"}})}),y=(await Promise.all(x)).map(b=>b.result===void 0||b.result===""?{...b,result:"done"}:b);if(n.addFunctionResults(y,r),p){let b=y.filter(k=>!k.isError);b.length>0&&pa(b,c)}if(f.length>0)throw new $t(f);return g};function ii(s,e,t,n){if(!e||e.length===0)return;if(!s.getFeatures(n).functions)throw new Error("Functions are not supported by the AI service");return e.map(o=>({id:o.id,name:o.function.name,args:o.function.params}))}function Ml(s,e,t,n){let r=e;return!t&&(r==="required"||typeof r=="function")?{functions:[],functionCall:void 0}:s?{functions:s.map(i=>"toFunction"in i?i.toFunction():i).flat(),functionCall:r}:{functions:[],functionCall:r}}function El(s){if(!s.trim())return null;try{return JSON.parse(s)}catch{}let e=jc(s);try{return JSON.parse(e)}catch{return null}}function jc(s){let e=s.trim();for(e.endsWith(",")&&(e=e.slice(0,-1));e.match(/[0-9][eE.+-]$/);)e=e.slice(0,-1);e=e.replace(/,(\s*[}\]])/g,"$1"),e.match(/t(r(u(e)?)?)?$/)&&!e.endsWith('"')&&!e.endsWith("true")&&e.match(/[:[,]\s*t(r(u(e)?)?)?$/)&&(e=e.replace(/t(r(u(e)?)?)?$/,"true")),e.match(/f(a(l(s(e)?)?)?)?$/)&&!e.endsWith('"')&&!e.endsWith("false")&&e.match(/[:[,]\s*f(a(l(s(e)?)?)?)?$/)&&(e=e.replace(/f(a(l(s(e)?)?)?)?$/,"false")),e.match(/n(u(l(l)?)?)?$/)&&!e.endsWith('"')&&!e.endsWith("null")&&e.match(/[:[,]\s*n(u(l(l)?)?)?$/)&&(e=e.replace(/n(u(l(l)?)?)?$/,"null"));let t=[],n=!1,r=!1;for(let o=0;o<e.length;o++){let i=e[o];if(r){r=!1;continue}if(i==="\\"){r=!0;continue}if(i==='"'){n=!n;continue}n||(i==="{"?t.push("}"):i==="["?t.push("]"):i==="}"?t.length>0&&t[t.length-1]==="}"&&t.pop():i==="]"&&t.length>0&&t[t.length-1]==="]"&&t.pop())}for(r&&(e=e.slice(0,-1)),n&&(e+='"'),t.length>0&&t[t.length-1]==="}"&&e.match(/,\s*"[^"]*"\s*$/)&&(e=e.replace(/,\s*"[^"]*"\s*$/,""));t.length>0;)e+=t.pop();return e}var kt=$n(Pl(),1),Nl=$n(Fl(),1),Dl=$n(_l(),1),Ll=$n($l(),1);kt.default.extend(Ll.default);kt.default.extend(Dl.default);kt.default.extend(Nl.default);function Gl(s,e,t=!1){try{return zc(e)}catch(n){if(s.isOptional&&!t)return;let r=n.message;throw Cl(s,e,r)}}function zc(s){if(!(0,kt.default)(s,"YYYY-MM-DD",!0).isValid())throw new Error('Invalid date format. Please provide the date in "YYYY-MM-DD" format.');return kt.default.utc(s,"YYYY-MM-DD").startOf("day").toDate()}function Ul(s,e,t=!1){try{return qc(e)}catch(n){if(s.isOptional&&!t)return;let r=n.message;throw wl(s,e,r)}}function qc(s){let e=/^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}(?::\d{2})?) (.+)$/,t=s.match(e);if(!t)throw new Error('Invalid date and time format. Please provide the date and time in "YYYY-MM-DD HH:mm" or "YYYY-MM-DD HH:mm:ss" format, followed by the timezone.');let[,n,r]=t;if(!n||!r)throw new Error('Invalid date and time format. Please provide the date and time in "YYYY-MM-DD HH:mm" or "YYYY-MM-DD HH:mm:ss" format, followed by the timezone.');try{let o=n.includes(":")&&n.split(":").length===3?"YYYY-MM-DD HH:mm:ss":"YYYY-MM-DD HH:mm",i=kt.default.tz(n,o,r);if(!i.isValid())throw new Error("Invalid date and time values. Please ensure all components are correct.");return i.utc().toDate()}catch{throw new Error(`Unrecognized time zone ${r}. Please provide a valid time zone name, abbreviation, or offset. For example, "America/New_York", or "EST".`)}}var Bl=s=>(0,kt.default)(s).utc().format("YYYY-MM-DD HH:mm:ss [UTC]");var sx=new Ge,ko=(s,e)=>{let t=s.type??{name:"string",isArray:!1},n=(u,c)=>{switch(u){case"class":return typeof c=="string";case"code":return typeof c=="string";case"string":return typeof c=="string";case"number":return typeof c=="number";case"boolean":return typeof c=="boolean";case"date":return c instanceof Date||typeof c=="string";case"datetime":return c instanceof Date||typeof c=="string";case"json":return typeof c=="object"||typeof c=="string";case"object":return typeof c=="object";default:return!1}},r=u=>!(!u||typeof u!="object"||!("mimeType"in u)||!("data"in u));if(s.type?.name==="image"){let u;if(Array.isArray(e)){for(let c of e)if(!r(c)){u="object ({ mimeType: string; data: string })";break}}else r(e)||(u="object ({ mimeType: string; data: string })");if(u)throw new Error(`Validation failed: Expected '${s.name}' to be type '${u}' instead got '${e}'`);return}let o=u=>!(!u||typeof u!="object"||!("data"in u));if(s.type?.name==="audio"){let u;if(Array.isArray(e)){for(let c of e)if(!o(c)){u="object ({ data: string; format?: string })";break}}else o(e)||(u="object ({ data: string; format?: string })");if(u)throw new Error(`Validation failed: Expected '${s.name}' to be type '${u}' instead got '${e}'`);return}let i=u=>{if(!u||typeof u!="object"||!("mimeType"in u))return!1;let c="data"in u,p="fileUri"in u;return!(!c&&!p||c&&p)};if(s.type?.name==="file"){let u;if(Array.isArray(e)){for(let c of e)if(!i(c)){u="object ({ mimeType: string; data: string } | { mimeType: string; fileUri: string })";break}}else i(e)||(u="object ({ mimeType: string; data: string } | { mimeType: string; fileUri: string })");if(u)throw new Error(`Validation failed: Expected '${s.name}' to be type '${u}' instead got '${e}'`);return}let a=u=>typeof u=="string"?!0:!(!u||typeof u!="object"||!("url"in u));if(s.type?.name==="url"){let u;if(Array.isArray(e)){for(let c of e)if(!a(c)){u="string or object ({ url: string; title?: string; description?: string })";break}}else a(e)||(u="string or object ({ url: string; title?: string; description?: string })");if(u)throw new Error(`Validation failed: Expected '${s.name}' to be type '${u}' instead got '${e}'`);return}let l=!0;if(t.isArray){if(!Array.isArray(e))l=!1;else for(let u of e)if(!n(t.name,u)){l=!1;break}}else l=n(t.name,e);if(!l){let u=Array.isArray(e)?"array":typeof e;throw new Error(`Validation failed: Expected '${s.name}' to be a ${s.type?.isArray?"an array of ":""}${t.name} instead got '${u}' (${JSON.stringify(e)})`)}};function pr(s){let e={};for(let t of s){let n=`${t.ai}:${t.model}`;if(!e[n]){e[n]={...t};continue}let r=e[n];if(r){let o=r.tokens??{promptTokens:0,completionTokens:0,totalTokens:0};o.promptTokens+=t?.tokens?.promptTokens??0,o.completionTokens+=t?.tokens?.completionTokens??0,o.totalTokens+=t?.tokens?.totalTokens??0,r.tokens=o;let i=r.citations??[],a=t.citations??[];if(a.length){let l=new Set(i.map(u=>u.url));for(let u of a)u?.url&&!l.has(u.url)&&(i.push(u),l.add(u.url));r.citations=i}}}return Object.values(e)}var jl=s=>{if(!s.trim())return[];let e=new Set(["-","*","+"]),t=/^\d+[\s]*[.)\]]\s*/,n=s.split(`
210
- `),r=[];for(let o of n){let i=o.trim();if(i){if(i[0]&&e.has(i[0]))r.push(i.slice(1).trim());else if(t.test(i))r.push(i.replace(t,"").trim());else if(r.length!==0)throw new Error("Could not parse markdown list: mixed content detected")}}if(r.length===0)throw new Error("Could not parse markdown list: no valid list items found");return r};function fi(s,e){let{index:t,delta:n,version:r}=e,o=s.find(a=>a.index===t)?.delta;if(!o)return s.push({index:t,delta:n,version:r}),s;for(let a of Object.keys(n)){let l=o[a],u=n[a];l===void 0&&Array.isArray(u)?o[a]=[...u]:Array.isArray(l)&&Array.isArray(u)?o[a]=[...l,...u]:(l===void 0||typeof l=="string")&&typeof u=="string"?o[a]=`${l??""}${u}`:o[a]=u}let i=s.find(a=>a.index===t);return i&&(i.version=r),s}var hi=class{cache=new Map;maxSize;constructor(e){this.maxSize=e}get(e){let t=this.cache.get(e);return t&&(this.cache.delete(e),this.cache.set(e,t)),t}set(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxSize){let n=this.cache.keys().next().value;n&&this.cache.delete(n)}this.cache.set(e,t)}},Hc=new hi(500);function zl(s,e,t=0,n=Hc){if(/^```[a-zA-Z]*\s*$/.test(s))return-4;if(/^[\s`]*$/.test(s))return-3;let r=s.indexOf(e,t);if(r!==-1)return r;let o=n.get(e)??Array.from({length:e.length},(a,l)=>e.slice(0,l+1));n.get(e)||n.set(e,o);let i=-1;for(let a=o.length-1;a>=0;a--){let l=o[a];if(s.endsWith(l)){i=a;break}}return i>=0?-2:-1}function Mt(s,e){if(typeof s!="string")throw oi(e,String(s),"URL must be a string");try{new URL(s)}catch{throw oi(e,s,"Invalid URL format. Expected a valid URL like https://example.com")}}function Xe(s,e){if(typeof s!="string")return;let t=e.type;if(t){if(t.minLength!==void 0&&s.length<t.minLength)throw yn(e,s,"minLength",t.minLength);if(t.maxLength!==void 0&&s.length>t.maxLength)throw yn(e,s,"maxLength",t.maxLength);if(t.pattern!==void 0&&!new RegExp(t.pattern).test(s))throw yn(e,s,"pattern",t.pattern);if(t.format==="email"&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s))throw yn(e,s,"format","valid email address");if(t.format==="uri"||t.format==="url")try{new URL(s)}catch{throw yn(e,s,"format","valid URL")}}}function et(s,e){if(typeof s!="number")return;let t=e.type;if(t){if(t.minimum!==void 0&&s<t.minimum)throw si(e,s,"minimum",t.minimum);if(t.maximum!==void 0&&s>t.maximum)throw si(e,s,"maximum",t.maximum)}}var Po=(s,e,t,n)=>{let r=n?.strictMode??!1,o=n?.treatAllFieldsOptional??!1,i=n?.treatAllFieldsOptional??!1,a={extractedFields:[],streamedIndex:{},s:-1};yi(s,e,a,t,{strictMode:r,skipEarlyFail:i,treatAllFieldsOptional:o}),bi(s,e,a,t,{strictMode:r,treatAllFieldsOptional:o,forceFinalize:!0});for(let l of s.getOutputFields())l.isInternal&&delete e[l.name]},xi=(s,e,t)=>{let n=[];for(let r of t)r&&!r.isOptional&&e[r.name]===void 0&&n.push(r);if(n.length>0)throw yl(n)},yi=(s,e,t,n,{strictMode:r,skipEarlyFail:o}={})=>{let i=s.getOutputFields(),a;for(;;){let l=new Set;t.currFieldIndex!==void 0&&!t.inAssumedField&&l.add(t.currFieldIndex);let u=i.map((g,f)=>({field:g,index:f})).filter(({index:g})=>!l.has(g)),c,p,d=-1,m=0;for(let{index:g,field:f}of u){let x=`${(t.extractedFields.length===0?"":`
211
- `)+f.title}:`,A=zl(n,x,t.s);if(A===-2||A===-3)return!0;if(A===-4)return t.inBlock=!0,!0;A>=0&&(d===-1||A<d)&&(d=A,m=x.length,c=g,p=f)}if(d===-1){if(o)return;if(!r&&t.currField===void 0&&t.extractedFields.length===0&&i.length===1){t.inAssumedField=!0,t.currField=i[0],t.currFieldIndex=0,t.s=0,t.extractedFields.includes(i[0])||t.extractedFields.push(i[0]),t.streamedIndex[i[0].name]===void 0&&(t.streamedIndex[i[0].name]=0);return}if(r&&t.currField===void 0&&t.extractedFields.length===0){let g=i.find(f=>!f.isOptional);if(g)throw To(g)}break}if(a&&p&&a.name!==p.name)throw To(a);if(t.currField!==void 0&&t.inAssumedField&&(t.inAssumedField=!1,t.streamedIndex[t.currField.name]=0,t.currField=void 0),t.currField){let g=n.substring(t.s,d).trim(),f=Mo(t.currField,g);f!==void 0&&(e[t.currField.name]=f),t.prevFields?t.prevFields?.push({field:t.currField,s:t.s,e:d}):t.prevFields=[{field:t.currField,s:t.s,e:d}]}t.s=d+m,p!==void 0&&c!==void 0&&(t.currField=p,t.currFieldIndex=c),p&&!t.extractedFields.includes(p)&&t.extractedFields.push(p),p&&t.streamedIndex[p.name]===void 0&&(t.streamedIndex[p.name]=0)}},bi=(s,e,t,n,r)=>{let o=r?.strictMode??!1,i=r?.treatAllFieldsOptional??!1,a=r?.deferRequiredCheckForStreaming??!1,l=r?.forceFinalize??!1;if(t.currField){let u=n.length,c=s.getOutputFields();for(let m of c){if(m.name===t.currField.name)continue;let g=`
212
- ${m.title}:`,f=n.indexOf(g,t.s);f!==-1&&f<u&&(u=f)}let p=n.substring(t.s,u).trim(),d=Mo(t.currField,p);d!==void 0&&(e[t.currField.name]=d)}if(o&&!t.currField&&t.extractedFields.length===0&&n.trim()){let p=s.getOutputFields().find(d=>!d.isOptional);if(p)throw To(p)}if(Kc(s,e,n,t),!i){let u=t.currField!==void 0||(t.extractedFields?.length??0)>0;o||l?xi(t,e,s.getOutputFields()):u||xi(t,e,s.getOutputFields())}},Kc=(s,e,t,n)=>{let r=s.getOutputFields();if(r.length===1){let i=r[0];if(i){let a=`${i.title}:`,l=t.indexOf(a);if(l!==-1){let u=l+a.length,c=`
213
- ${i.title}:`,p=t.indexOf(c,u),d=t.substring(u,p===-1?t.length:p).trim();if(d)try{let m=Mo(i,d);if(m!==void 0){e[i.name]=m;return}}catch{}}}}let o=t.split(`
214
- `);for(let i of r){if(i.name in e)continue;let a=`${i.title}:`;for(let l of o){let u=l.trim();if(u.startsWith(a)){let c=u.substring(a.length).trim();if(c)try{let p=Mo(i,c);if(p!==void 0){e[i.name]=p;break}}catch(p){if(!i.isOptional)throw p}break}}}},ql=(s,e,t=!1)=>{switch(s.type?.name){case"code":return Ai(e);case"string":return e;case"number":{let n=Number(e);if(Number.isNaN(n)){if(s.isOptional&&!t)return;throw new Error("Invalid number")}return n}case"boolean":{if(typeof e=="boolean")return e;let n=e.toLowerCase();if(n==="true")return!0;if(n==="false")return!1;if(s.isOptional&&!t)return;throw new Error("Invalid boolean")}case"date":return Gl(s,e,t);case"datetime":return Ul(s,e,t);case"class":{let n=e;if(s.type.options&&!s.type.options.includes(n)){if(s.isOptional)return;throw new Error(`Invalid class '${e}', expected one of the following: ${s.type.options.join(", ")}`)}return n}default:return e}};function*Hl(s,e,t,n,r,o){let{name:i,isInternal:a}=e,{isArray:l,name:u}=e.type??{};if(a||l||u&&u!=="string"&&u!=="code")return;let c=r.streamedIndex[i]??0,p=c===0,d=(t<0?0:t)+c,m=s.substring(d,n);if(m.length===0)return;let g=m.replace(/\s+$/,"");r.currField?.type?.name==="code"&&(g=g.replace(/\s*```\s*$/,""));let f=p?g.trimStart():g;r.currField?.type?.name==="code"&&(f=f.replace(/^[ ]*```[a-zA-Z0-9]*\n\s*/,"")),f.length>0&&(yield{index:o,delta:{[i]:f}},r.streamedIndex[i]=c+g.length)}function*Ii(s,e,t,n,r){for(let i of n.prevFields??[]){let{field:a,s:l,e:u}=i;yield*Hl(e,a,l,u,n,r)}if(n.prevFields=void 0,n.inAssumedField&&!(s.getOutputFields().filter(l=>!l.isInternal).length===1)||!n.currField||n.currField.isInternal)return;yield*Hl(e,n.currField,n.s,e.length,n,r);let o=s.getOutputFields();for(let i of Object.keys(t)){let a=o.find(c=>c.name===i);if(!a||a.isInternal)continue;let l=t[i];if(Array.isArray(l)){let c=n.streamedIndex?.[i]??0,p=l.slice(c);p&&p.length>0&&(yield{index:r,delta:{[i]:p}},n.streamedIndex[i]=c+p.length);continue}let u=typeof l=="string"?l:void 0;if(!n.streamedIndex[i])yield{index:r,delta:{[i]:l}},n.streamedIndex[i]=u?u.length:1;else if(u){let c=n.streamedIndex[i];if(u.length>c){let p=u.substring(c);yield{index:r,delta:{[i]:p}},n.streamedIndex[i]=u.length}}}}function Mo(s,e){if(!e||e===""||/^(null|undefined)\s*$/i.test(e)){if(s.isOptional)return;throw Co(s)}let t;if(s.type?.name==="json"&&!s.type?.isArray)try{let r=Ai(e);return t=JSON.parse(r),t}catch(r){throw bl(s,r.message)}if(s.type?.isArray)try{try{t=JSON.parse(e)}catch{t=jl(e)}if(!Array.isArray(t))throw new Error("Expected an array")}catch(r){throw Il(s,r.message)}try{if(Array.isArray(t)){for(let[r,o]of t.entries())if(o!==void 0){let i=typeof o=="string"?o.trim():o;if(typeof i=="string"&&(s.type?.name==="object"||s.type?.name==="json"))try{let a=Ai(i);i=JSON.parse(a)}catch{}t[r]=ql(s,i,!0)}}else t=ql(s,e)}catch(r){throw Tl(s,e,r.message)}if(typeof t=="string"&&t==="")return;let n=s.type;if(n&&t!==void 0&&(n.name==="url"&&Mt(t,s),(n.name==="string"||n.name==="code")&&Xe(t,s),n.name==="number"&&et(t,s),n.isArray&&Array.isArray(t)))for(let r of t)r!==void 0&&(n.name==="string"||n.name==="code"?Xe(r,s):n.name==="number"&&et(r,s));return t}function Fo(s,e,t){let n=s.getOutputFields();for(let r of n){let o=e[r.name];if(o==null){if(!r.isOptional&&!t?.allowMissingRequired)throw Co(r);continue}let i=r.type;if(i){if(i.name==="url"&&Mt(o,r),(i.name==="string"||i.name==="code")&&Xe(o,r),i.name==="number"&&et(o,r),i.isArray&&Array.isArray(o))for(let a of o)a!=null&&(i.name==="url"?Mt(a,r):i.name==="string"||i.name==="code"?Xe(a,r):i.name==="number"&&et(a,r));if(i.name==="object"&&i.fields&&typeof o=="object"&&!Array.isArray(o)&&Eo(r,o,t),i.isArray&&i.fields&&Array.isArray(o)&&i.name==="object")for(let a of o)a&&typeof a=="object"&&Eo(r,a,t)}}}function Eo(s,e,t){let n=s.type?.fields;if(!(!n||typeof n!="object"))for(let[r,o]of Object.entries(n)){let i={name:r,title:r,description:o.description,type:{name:o.type,isArray:o.isArray,options:o.options,fields:o.fields,minLength:o.minLength,maxLength:o.maxLength,minimum:o.minimum,maximum:o.maximum,pattern:o.pattern,patternDescription:o.patternDescription,format:o.format},isOptional:o.isOptional??!1,isInternal:o.isInternal??!1},a=e[i.name];if(a==null){if(!i.isOptional&&!t?.allowMissingRequired)throw Co(i);continue}let l=i.type;if(l){if(l.name==="url"&&Mt(a,i),(l.name==="string"||l.name==="code")&&Xe(a,i),l.name==="number"&&et(a,i),l.isArray&&Array.isArray(a))for(let u of a)u!=null&&(l.name==="url"?Mt(u,i):l.name==="string"||l.name==="code"?Xe(u,i):l.name==="number"&&et(u,i));if(l.name==="object"&&l.fields&&typeof a=="object"&&!Array.isArray(a)&&Eo(i,a,t),l.isArray&&l.fields&&Array.isArray(a)&&l.name==="object")for(let u of a)u&&typeof u=="object"&&Eo(i,u,t)}}}var Ai=s=>{let t=/```([A-Za-z]*)\s*([\s\S]*?)\s*```/g.exec(s);return t?t.length===3?t[2]:t.length===2?t[1]:s:s};async function Ti(s,e,t,n){for(let r of s){if(e[r.field.name]===void 0)continue;let o=r.process,i=await o(e[r.field.name],{sessionId:n,values:e,done:!0});Kl(r.field,t,i,n)}}async function Ci(s,e,t,n,r,o,i=!1){for(let a of s){if(t.currField?.name!==a.field.name)continue;let l=e.substring(t.s);t.currField?.type?.name==="code"&&(l=l.replace(/^[ ]*```[a-zA-Z0-9]*\n\s*/,""),l=l.replace(/\s*```\s*$/,""));let u=a.process,c=await u(l,{sessionId:o,values:r,done:i});Kl(t.currField,n,c,o)}}var Kl=(s,e,t,n)=>{if(t===void 0||typeof t=="string"&&(t===""||/^(null|undefined)\s*$/i.test(t)))return;let r=JSON.stringify(t,(i,a)=>typeof a=="bigint"?Number(a):a,2),o=Vc(s,r);e.addRequest([{role:"user",content:[{type:"text",text:o}]}],n),e.addTag("processor",n)};function Vc(s,e){let t=s.type?.name==="code",n=s.title;return t?`Code in the field "${n}" was executed. The code execution produced the following output: ${e}`:`The field "${n}" was processed. The field contents were transformed into the following output: ${e}`}async function*Vl({res:s,usage:e,states:t,debug:n,...r}){let o=(r.ai.getFeatures().functionCot??!1)&&r.functions!==void 0&&r.functions.length>0,i,a=[],l=s.getReader();try{for(;;){let{done:u,value:c}=await l.read();if(u)break;let p=c;p.modelUsage&&(i=p.modelUsage);for(let d of p.results){if(Array.isArray(d.citations))for(let g of d.citations)g?.url&&a.push({url:g.url,title:g.title,description:g.description,license:g.license,publicationDate:g.publicationDate,snippet:g.snippet});if((!d.content||d.content==="")&&(!d.thought||d.thought==="")&&(!d.thoughtBlocks||d.thoughtBlocks.length===0)&&(!d.functionCalls||d.functionCalls.length===0))continue;let m=t.find(g=>g.index===d.index);if(!m)throw new Error(`No state found for result (index: ${d.index})`);yield*Wc({...r,result:d,skipEarlyFail:o,state:m,debug:n})}}}finally{l.releaseLock()}for(let u of t)yield*Jc({...r,state:u,debug:n});if(i){if(a.length){let u=Array.from(new Map(a.filter(c=>c.url).map(c=>[c.url,c])).values());i.citations=u}if(e.push(i),n&&r.logger){let u=structuredClone(i);delete u.citations,r.logger({name:"ChatResponseUsage",value:u}),i.citations&&i.citations.length>0&&r.logger({name:"ChatResponseCitations",value:i.citations})}}}async function*Wc({result:s,mem:e,sessionId:t,strictMode:n,skipEarlyFail:r,treatAllFieldsOptional:o,state:i,signature:a,streamingFieldProcessors:l,thoughtFieldName:u,streamingAsserts:c,asserts:p}){if(s.functionCalls&&s.functionCalls.length>0)Dr(i.functionCalls,s.functionCalls),e.updateResult({name:s.name,content:s.content,functionCalls:i.functionCalls,thoughtBlocks:s.thoughtBlocks,delta:s.functionCalls?.[0]?.function?.params,index:s.index},t);else if(s.content&&s.content.length>0){s.thought&&s.thought.length>0&&(yield{index:s.index,delta:{[u]:s.thought}}),i.content+=s.content,e.updateResult({name:s.name,content:i.content,thoughtBlocks:s.thoughtBlocks,delta:s.content,index:s.index},t);let d=a.getOutputFields();if(a.hasComplexFields()){let f=El(i.content);if(f&&typeof f=="object"){let h={},x={};for(let A of Object.keys(f))if(d.some(y=>y.name===A)){let y=f[A],b=i.values[A];if(x[A]=y,typeof y=="string"&&typeof b=="string"&&y.startsWith(b)){let k=y.slice(b.length);k&&(h[A]=k)}else Array.isArray(y)&&Array.isArray(b)?y.length>b.length&&(h[A]=y.slice(b.length)):JSON.stringify(y)!==JSON.stringify(b)&&(h[A]=y)}try{Fo(a,x,{allowMissingRequired:!0})}catch{}Object.assign(i.values,x),Object.keys(h).length>0&&(yield{index:s.index,delta:h});return}}if(yi(a,i.values,i.xstate,i.content,{strictMode:n,skipEarlyFail:r,treatAllFieldsOptional:o}))return;c.length!==0&&await Xs(c,i.xstate,i.content),l.length!==0&&await Ci(l,i.content,i.xstate,e,i.values,t),yield*Ii(a,i.content,i.values,i.xstate,s.index),await Ao(p,i.values)}else s.thought&&s.thought.length>0?(i.values[u]=(i.values[u]??"")+s.thought,yield{index:s.index,delta:{[u]:s.thought}},e.updateResult({name:s.name,content:i.content,delta:"",index:s.index,thought:s.thought,thoughtBlocks:s.thoughtBlocks},t)):s.thoughtBlocks&&s.thoughtBlocks.length>0&&e.updateResult({name:s.name,content:i.content,delta:"",index:s.index,thoughtBlocks:s.thoughtBlocks},t);if(s.finishReason==="length")throw new Error(`Max tokens reached before completion
215
- Content: ${i.content}`)}async function*Jc({state:s,signature:e,ai:t,model:n,functions:r,mem:o,sessionId:i,traceId:a,span:l,strictMode:u,excludeContentFromTrace:c,streamingAsserts:p,asserts:d,fieldProcessors:m,streamingFieldProcessors:g,functionResultFormatter:f,signatureToolCallingManager:h,logger:x,debug:A,stopFunctionNames:y}){let b=h?void 0:ii(t,s.functionCalls,s.values,n);if(b){if(!r)throw new Error("Functions are not defined");let k=await Oo({ai:t,functionList:r,functionCalls:b,mem:o,sessionId:i,traceId:a,span:l,index:s.index,excludeContentFromTrace:c,functionResultFormatter:f,logger:x,debug:A,stopFunctionNames:y});s.functionsExecuted=new Set([...s.functionsExecuted,...k]),s.functionCalls=[]}else{let k=e.getOutputFields(),S=e.hasComplexFields(),M=!1;if(S)try{let R=JSON.parse(s.content),O={};for(let F of Object.keys(R))if(k.some(P=>P.name===F)){let P=R[F],I=s.values[F];if(typeof P=="string"&&typeof I=="string"&&P.startsWith(I)){let v=P.slice(I.length);v&&(O[F]=v)}else Array.isArray(P)&&Array.isArray(I)?P.length>I.length&&(O[F]=P.slice(I.length)):JSON.stringify(P)!==JSON.stringify(I)&&(O[F]=P)}try{Fo(e,O,{allowMissingRequired:!0})}catch(F){let P=(F.message||"").toLowerCase();if(P.includes("at least")||P.includes("at most")||P.includes("must match pattern")||P.includes("invalid url")||P.includes("required")||P.includes("missing")||P.includes("valid email")||P.includes("number must be"))throw F}Object.assign(s.values,O),yield{index:s.index,delta:O},M=!0}catch(R){let O=(R.message||"").toLowerCase();if(O.includes("at least")||O.includes("at most")||O.includes("must match pattern")||O.includes("invalid url")||O.includes("required")||O.includes("missing")||O.includes("valid email")||O.includes("number must be"))throw R}if(!M){let R=h!==void 0;bi(e,s.values,s.xstate,s.content,{strictMode:u,treatAllFieldsOptional:R,deferRequiredCheckForStreaming:!0,forceFinalize:!0})}if(h){let R=await h.processResults(s.values);if(R&&R.length>0){if(!r)throw new Error("Functions are not defined");let O=await Oo({ai:t,functionList:r,functionCalls:R,mem:o,sessionId:i,traceId:a,span:l,index:s.index,excludeContentFromTrace:c,functionResultFormatter:f,logger:x,debug:A,stopFunctionNames:y});s.functionsExecuted=new Set([...s.functionsExecuted,...O]),o.updateResult({name:void 0,content:s.content,functionCalls:R.map(F=>({id:F.id,type:"function",function:{name:F.name,params:F.args}})),index:s.index},i);return}}await Xs(p,s.xstate,s.content,!0),await Ao(d,s.values),m.length&&await Ti(m,s.values,o,i),g.length!==0&&await Ci(g,s.content,s.xstate,o,s.values,i,!0),yield*Ii(e,s.content,s.values,s.xstate,s.index)}}async function*Wl({ai:s,res:e,mem:t,sessionId:n,traceId:r,functions:o,span:i,strictMode:a,states:l,usage:u,excludeContentFromTrace:c,asserts:p,fieldProcessors:d,thoughtFieldName:m,signature:g,functionResultFormatter:f,logger:h,debug:x,signatureToolCallingManager:A,stopFunctionNames:y,disableMemoryCleanup:b}){let k=e.results??[],S=A!==void 0;t.addResponse(k,n);let M=[];for(let P of k)if(Array.isArray(P?.citations))for(let I of P.citations)I?.url&&M.push({url:I.url,title:I.title,description:I.description,license:I.license,publicationDate:I.publicationDate,snippet:I.snippet});for(let P of k){let I=l[P.index];if(!I)throw new Error(`No state found for result (index: ${P.index})`);if(e.modelUsage){let v=Array.from(new Map(M.filter(w=>w.url).map(w=>[w.url,w])).values()),T={...e.modelUsage,...v.length?{citations:v}:{}};if(u.push(T),x&&h){let w=structuredClone(T);delete w.citations,h({name:"ChatResponseUsage",value:w}),T.citations&&T.citations.length>0&&h({name:"ChatResponseCitations",value:T.citations})}}if(A&&P.content){P.thought&&P.thought.length>0&&(I.values[m]=P.thought),Po(g,I.values,P.content,{strictMode:a,treatAllFieldsOptional:S});let T=(await A.processResults(I.values))?.map(w=>({id:w.id,type:"function",function:{name:w.name,params:w.args}}));T&&T.length>0&&t.updateResult({name:P.name,content:P.content,functionCalls:T,index:P.index},n)}if(P.functionCalls?.length){let v=ii(s,P.functionCalls,I.values);if(v&&v.length>0){if(!o)throw new Error("Functions are not defined");let T;try{T=await Oo({ai:s,functionList:o,functionCalls:v,mem:t,sessionId:n,traceId:r,span:i,excludeContentFromTrace:c,index:P.index,functionResultFormatter:f,logger:h,debug:x,stopFunctionNames:y})}catch(w){throw t.addRequest([{role:"user",content:"The previous tool call failed. Fix arguments and try again, ensuring required fields match schema."}],n),t.addTag("correction",n),w}I.functionsExecuted=new Set([...I.functionsExecuted,...T])}}else if(P.content){P.thought&&P.thought.length>0&&(I.values[m]=P.thought);let v=g.getOutputFields();if(g.hasComplexFields())try{let w=JSON.parse(P.content),C={};for(let E of Object.keys(w))v.some(_=>_.name===E)&&(C[E]=w[E]);Fo(g,C),Object.assign(I.values,C)}catch(w){let C=w instanceof SyntaxError;if((w.name?.includes("ValidationError")||w.name?.includes("Error"))&&!C){let _=(w.message||"").toLowerCase();if(_.includes("at least")||_.includes("at most")||_.includes("must match pattern")||_.includes("invalid url")||_.includes("required")||_.includes("missing")||_.includes("valid email")||_.includes("number must be"))throw w}if(C)Po(g,I.values,P.content,{strictMode:a,treatAllFieldsOptional:S});else throw w}else Po(g,I.values,P.content,{strictMode:a,treatAllFieldsOptional:S})}if(await Ao(p,I.values),b||(t.removeByTag("correction",n),t.removeByTag("error",n)),d.length&&await Ti(d,I.values,t,n),P.finishReason==="length")throw new Error(`Max tokens reached before completion
216
- Content: ${P.content}`)}let R=l.map(P=>P.values);for(let P of R)for(let I of g.getOutputFields())I.isInternal&&delete P[I.name];let O=g.getOutputFields(),F=R.map((P,I)=>{let v={};for(let T of O)T.isInternal||(v[T.name]=P[T.name]);return P[m]!==void 0&&(v[m]=P[m]),{index:I,delta:v}});for(let P of F)yield P}function Jl(s,e,t,n){let r=s.getLast(n);if(!r)return!0;for(let[o,i]of t.entries()){let a=e?Array.from(e).some(p=>i.functionsExecuted.has(p)):!1;if(!r.chat[o])throw new Error(`No chat message found for result (index: ${o})`);let u=r.role==="function",c=r.tags?r.tags.some(p=>p==="processor"):!1;if(u&&e&&a||!(u||c))return!1}return!0}var bn=class{reg;constructor(){this.reg=new Set}register(e){this.reg.add(e)}*[Symbol.iterator](){let e=Array.from(this.reg);for(let t=0;t<e.length;t++)yield e[t]}};var W=class extends Error{constructor(t,n,r,o){super(t);this.position=n;this.context=r;this.suggestion=o;this.name="SignatureValidationError"}},wi=class{input;position;currentFieldName=null;currentSection="description";constructor(e){if(this.input=e.trim(),this.position=0,!this.input)throw new W("Empty signature provided",0,"",'A signature must contain at least input and output fields separated by "->". Example: "userQuery:string -> aiResponse:string"')}parse(){try{this.skipWhitespace();let e=this.parseParsedString();this.skipWhitespace(),this.currentSection="inputs";let t=this.parseFieldList(this.parseInputField.bind(this),"input");if(this.skipWhitespace(),this.position>=this.input.length)throw new W("Incomplete signature: Missing output section",this.position,this.getErrorContext(),'Add "->" followed by output fields. Example: "-> responseText:string"');if(this.expectArrow(),this.skipWhitespace(),this.position>=this.input.length)throw new W('Incomplete signature: No output fields specified after "->"',this.position,this.getErrorContext(),'Add at least one output field. Example: "-> responseText:string"');this.currentSection="outputs";let n=this.parseFieldList(this.parseOutputField.bind(this),"output");if(this.skipWhitespace(),this.position<this.input.length){let r=this.input.slice(this.position);throw new W(`Unexpected content after signature: "${r}"`,this.position,this.getErrorContext(),"Remove any extra content after the output fields")}return this.validateParsedSignature({desc:e?.trim(),inputs:t,outputs:n}),{desc:e?.trim(),inputs:t,outputs:n}}catch(e){if(e instanceof W)throw e;let t=e instanceof Error?e.message:"Unknown error";throw new W(t,this.position,this.getErrorContext())}}validateParsedSignature(e){let t=new Set;for(let r of e.inputs){if(t.has(r.name))throw new W(`Duplicate input field name: "${r.name}"`,0,"","Each field name must be unique within the signature");t.add(r.name)}let n=new Set;for(let r of e.outputs){if(n.has(r.name))throw new W(`Duplicate output field name: "${r.name}"`,0,"","Each field name must be unique within the signature");n.add(r.name)}for(let r of e.outputs)if(t.has(r.name))throw new W(`Field name "${r.name}" appears in both inputs and outputs`,0,"","Use different names for input and output fields to avoid confusion");if(e.inputs.length===0)throw new W("Signature must have at least one input field",0,"",'Add an input field before "->". Example: "userInput:string -> ..."');if(e.outputs.length===0)throw new W("Signature must have at least one output field",0,"",'Add an output field after "->". Example: "... -> responseText:string"')}getErrorContext(){let e=Math.max(0,this.position-25),t=Math.min(this.input.length,this.position+25),n=this.input.slice(e,this.position),r=this.input.slice(this.position,t),o=`${" ".repeat(n.length)}^`;return[`Position ${this.position} in signature:`,`"${n}${r}"`,` ${o}`].join(`
217
- `)}parseFieldList(e,t){let n=[];if(this.skipWhitespace(),this.position>=this.input.length)throw new W(`Empty ${t} section: Expected at least one field`,this.position,this.getErrorContext(),`Add a ${t} field. Example: ${t==="input"?"userInput:string":"responseText:string"}`);try{n.push(e())}catch(r){throw r instanceof W?r:new W(`Invalid first ${t} field: ${r instanceof Error?r.message:"Unknown error"}`,this.position,this.getErrorContext())}for(this.skipWhitespace();this.position<this.input.length&&!(this.input[this.position]==="-"&&this.position+1<this.input.length&&this.input[this.position+1]===">");)if(this.match(",")){if(this.skipWhitespace(),this.position>=this.input.length)throw new W(`Unexpected end of input after comma in ${t} section`,this.position,this.getErrorContext(),`Add another ${t} field after the comma`);try{n.push(e())}catch(r){throw r instanceof W?r:new W(`Invalid ${t} field after comma: ${r instanceof Error?r.message:"Unknown error"}`,this.position,this.getErrorContext())}this.skipWhitespace()}else break;return n}parseInputField(){this.skipWhitespace();let e=this.parseParsedIdentifier();this.currentFieldName=e,this.validateFieldName(e,"input");let t;for(;;){if(this.match("?")){t=!0;continue}if(this.match("!"))throw new W(`Input field "${e}" cannot use the internal marker "!"`,this.position-1,this.getErrorContext(),"Internal markers (!) are only allowed on output fields");break}let n;if(this.skipWhitespace(),this.match(":")){if(this.skipWhitespace(),/^class\b/.test(this.input.slice(this.position)))throw new W(`Input field "${e}" cannot use the "class" type`,this.position,this.getErrorContext(),'Class types are only allowed on output fields. Use "string" type for input classifications');try{let o=this.parseTypeNotClass(),i=this.match("[]");n={name:o,isArray:i}}catch(o){throw o instanceof W?o:new W(`Input field "${e}": ${o instanceof Error?o.message:"Unknown error"}`,this.position,this.getErrorContext())}}this.skipWhitespace();let r=this.parseParsedString();return{name:e,desc:r?.trim(),type:n,isOptional:t}}parseOutputField(){this.skipWhitespace();let e=this.parseParsedIdentifier();this.currentFieldName=e,this.validateFieldName(e,"output");let t=!1,n=!1;for(;;){if(this.match("?")){t=!0;continue}if(this.match("!")){n=!0;continue}break}let r;if(this.skipWhitespace(),this.match(":"))if(this.skipWhitespace(),this.match("class")){let i=this.match("[]");this.skipWhitespace();let a=this.parseParsedString();if(!a)throw new W(`Output field "${e}": Missing class options after "class" type`,this.position,this.getErrorContext(),'Add class names in quotes. Example: class "positive, negative, neutral"');let l=a.split(/[,|]/).map(u=>u.trim()).filter(u=>u.length>0);if(l.length===0)throw new W(`Output field "${e}": Empty class list provided`,this.position,this.getErrorContext(),'Provide at least one class option. Example: "positive, negative"');r={name:"class",isArray:i,options:l}}else try{let i=this.parseTypeNotClass(),a=this.match("[]");if(r={name:i,isArray:a},i==="image"&&a)throw new W(`Output field "${e}": Arrays of images are not supported`,this.position,this.getErrorContext(),'Use a single image type instead: "image"');if(i==="audio"&&a)throw new W(`Output field "${e}": Arrays of audio are not supported`,this.position,this.getErrorContext(),'Use a single audio type instead: "audio"');if(i==="image")throw new W(`Output field "${e}": Image type is not supported in output fields`,this.position,this.getErrorContext(),"Image types can only be used in input fields");if(i==="audio")throw new W(`Output field "${e}": Audio type is not supported in output fields`,this.position,this.getErrorContext(),"Audio types can only be used in input fields")}catch(i){throw i instanceof W?i:new W(`Output field "${e}": ${i instanceof Error?i.message:"Unknown error"}`,this.position,this.getErrorContext())}this.skipWhitespace();let o=this.parseParsedString();return{name:e,desc:o?.trim(),type:r,isOptional:t,isInternal:n}}validateFieldName(e,t){if(te.signatureStrict&&["text","object","image","string","number","boolean","json","array","datetime","date","time","type","class","input","output","data","value","result","response","request","item","element"].includes(e.toLowerCase())){let i=t==="input"?["userInput","questionText","documentContent","messageText"]:["responseText","analysisResult","categoryType","summaryText"];throw new W(`Field name "${e}" is too generic`,this.position,this.getErrorContext(),`Use a more descriptive name. Examples: ${i.join(", ")}`)}let n=/^[a-z][a-zA-Z0-9]*$/,r=/^[a-z]+(_[a-z0-9]+)*$/;if(!n.test(e)&&!r.test(e))throw new W(`Invalid field name "${e}"`,this.position,this.getErrorContext(),'Field names must be in camelCase (e.g., "userInput") or snake_case (e.g., "user_input")');if(e.length<2)throw new W(`Field name "${e}" is too short`,this.position,this.getErrorContext(),"Field names must be at least 2 characters long");if(e.length>50)throw new W(`Field name "${e}" is too long (${e.length} characters)`,this.position,this.getErrorContext(),"Field names should be 50 characters or less")}parseTypeNotClass(){let e=["string","number","boolean","json","image","audio","file","url","datetime","date","code","object"],t=e.find(n=>this.match(n));if(!t){let n=this.input.slice(this.position).match(/^\w+/)?.[0]||"",r=this.suggestType(n),o=`Invalid type "${n||"empty"}"`,i=r?`. Did you mean "${r}"?`:"",a=`${o}${i}`;throw new W(a,this.position,this.getErrorContext(),`Expected one of: ${e.join(", ")}`)}return t}suggestType(e){return{str:"string",text:"string",int:"number",integer:"number",float:"number",double:"number",bool:"boolean",object:"json",dict:"json",timestamp:"datetime",time:"datetime",img:"image",picture:"image",sound:"audio",voice:"audio",classification:"class",category:"class"}[e.toLowerCase()]||null}parseParsedIdentifier(){this.skipWhitespace();let e=/^[a-zA-Z_][a-zA-Z_0-9]*/.exec(this.input.slice(this.position));if(e)return this.position+=e[0].length,e[0];let t=/^\S+/.exec(this.input.slice(this.position)),n=t?t[0]:"";throw n===""?new W("Expected field name but found end of input",this.position,this.getErrorContext(),"Add a field name. Field names must start with a letter or underscore"):/^\d/.test(n)?new W(`Invalid field name "${n}" - cannot start with a number`,this.position,this.getErrorContext(),'Field names must start with a letter or underscore. Example: "userInput" or "_internal"'):new W(`Invalid field name "${n}"`,this.position,this.getErrorContext(),"Field names must start with a letter or underscore and contain only letters, numbers, or underscores")}parseParsedString(){let e=["'",'"'];for(let t of e)if(this.match(t)){let n="",r=!1,o=this.position-1;for(;this.position<this.input.length;){let a=this.input[this.position];if(this.position++,r)n+=a,r=!1;else if(a==="\\")r=!0;else{if(a===t)return n;n+=a}}let i=this.input.slice(o,Math.min(this.position,o+20));throw new W(`Unterminated string starting at position ${o}`,o,this.getErrorContext(),`Add closing ${t} to complete the string: ${i}${t}`)}}skipWhitespace(){let e=/^[\s\t\r\n]+/.exec(this.input.slice(this.position));e&&(this.position+=e[0].length)}match(e){let t;if(typeof e=="string"){if(this.input.startsWith(e,this.position))return this.position+=e.length,!0}else if(t=e.exec(this.input.slice(this.position)),t)return this.position+=t[0].length,!0;return!1}expectArrow(){if(!this.match("->")){let e=this.input.slice(this.position,this.position+10),t=e.includes(">")?'Use "->" (dash followed by greater-than)':e.includes("-")?'Add ">" after the dash':'Add "->" to separate input and output fields';throw new W(`Expected "->" but found "${e}..."`,this.position,this.getErrorContext(),t)}}};function Yl(s){return new wi(s).parse()}var dr=class{inputFields=[];outputFields=[];desc;input(e,t,n=!1){let r={name:e,type:{name:t.type,isArray:t.isArray||void 0,options:t.options?[...t.options]:void 0,minLength:t.minLength,maxLength:t.maxLength,minimum:t.minimum,maximum:t.maximum,pattern:t.pattern,patternDescription:t.patternDescription,format:t.format,description:t.itemDescription,fields:t.fields?Object.fromEntries(Object.entries(t.fields).map(([o,i])=>[o,Ri(i)])):void 0},description:t.description,isOptional:t.isOptional||void 0,isInternal:t.isInternal||void 0};return n?this.inputFields.unshift(r):this.inputFields.push(r),this}output(e,t,n=!1){let r={name:e,type:{name:t.type,isArray:t.isArray||void 0,options:t.options?[...t.options]:void 0,minLength:t.minLength,maxLength:t.maxLength,minimum:t.minimum,maximum:t.maximum,pattern:t.pattern,patternDescription:t.patternDescription,format:t.format,description:t.itemDescription,fields:t.fields?Object.fromEntries(Object.entries(t.fields).map(([o,i])=>[o,Ri(i)])):void 0},description:t.description,isOptional:t.isOptional||void 0,isInternal:t.isInternal||void 0};return n?this.outputFields.unshift(r):this.outputFields.push(r),this}description(e){return this.desc=e,this}useStructured(){return this._useStructuredOutputs=!0,this}build(){let e={description:this.desc,inputs:this.inputFields,outputs:this.outputFields},t=new be(e);return this._useStructuredOutputs&&(t._forceComplexFields=!0,t._hasComplexFields=void 0),t}},Oe=class s{type;isArray;options;description;isOptional;isInternal;fields;minLength;maxLength;minimum;maximum;pattern;patternDescription;format;itemDescription;constructor(e){this.type=e.type,this.isArray=e.isArray,this.options=e.options,this.description=e.description,this.itemDescription=e.itemDescription,this.isOptional=e.isOptional,this.isInternal=e.isInternal,this.fields=e.fields,this.minLength=e.minLength,this.maxLength=e.maxLength,this.minimum=e.minimum,this.maximum=e.maximum,this.pattern=e.pattern,this.patternDescription=e.patternDescription,this.format=e.format}optional(){return new s({...this,isOptional:!0})}array(e){return new s({...this,isArray:!0,description:e||this.description,itemDescription:e?this.description:void 0})}internal(){return new s({...this,isInternal:!0})}min(e){return this.type==="string"?new s({...this,minLength:e}):this.type==="number"?new s({...this,minimum:e}):this}max(e){return this.type==="string"?new s({...this,maxLength:e}):this.type==="number"?new s({...this,maximum:e}):this}email(){return this.type==="string"?new s({...this,format:"email"}):this}url(){return this.type==="string"?new s({...this,format:"uri"}):this}regex(e,t){return this.type==="string"?new s({...this,pattern:e,patternDescription:t}):this}date(){return this.type==="string"?new s({...this,format:"date"}):this}datetime(){return this.type==="string"?new s({...this,format:"date-time"}):this}},ue=Object.assign(()=>new dr,{string:s=>new Oe({type:"string",isArray:!1,description:s,isOptional:!1,isInternal:!1}),number:s=>new Oe({type:"number",isArray:!1,description:s,isOptional:!1,isInternal:!1}),boolean:s=>new Oe({type:"boolean",isArray:!1,description:s,isOptional:!1,isInternal:!1}),json:s=>new Oe({type:"json",isArray:!1,description:s,isOptional:!1,isInternal:!1}),datetime:s=>new Oe({type:"datetime",isArray:!1,description:s,isOptional:!1,isInternal:!1}),date:s=>new Oe({type:"date",isArray:!1,description:s,isOptional:!1,isInternal:!1}),class:(s,e)=>new Oe({type:"class",isArray:!1,options:s,description:e,isOptional:!1,isInternal:!1}),image:s=>new Oe({type:"image",isArray:!1,description:s,isOptional:!1,isInternal:!1}),audio:s=>new Oe({type:"audio",isArray:!1,description:s,isOptional:!1,isInternal:!1}),file:s=>new Oe({type:"file",isArray:!1,description:s,isOptional:!1,isInternal:!1}),url:s=>new Oe({type:"url",isArray:!1,description:s,isOptional:!1,isInternal:!1}),email:s=>new Oe({type:"string",isArray:!1,description:s,isOptional:!1,isInternal:!1,format:"email"}),code:(s,e)=>new Oe({type:"code",isArray:!1,description:e||s,isOptional:!1,isInternal:!1}),object:(s,e)=>new Oe({type:"object",isArray:!1,fields:s,description:e,isOptional:!1,isInternal:!1})});function Ri(s){return{type:s.type,isArray:s.isArray,options:s.options,description:s.description,isOptional:s.isOptional,isInternal:s.isInternal,minLength:s.minLength,maxLength:s.maxLength,minimum:s.minimum,maximum:s.maximum,pattern:s.pattern,patternDescription:s.patternDescription,format:s.format,fields:s.fields?Object.fromEntries(Object.entries(s.fields).map(([e,t])=>[e,Ri(t)])):void 0}}function _o(s){return{type:{name:s.type,isArray:s.isArray,options:s.options?[...s.options]:void 0,fields:s.fields},description:s.description,isOptional:s.isOptional,isInternal:s.isInternal}}var j=class extends Error{constructor(t,n,r){super(t);this.fieldName=n;this.suggestion=r;this.name="AxSignatureValidationError"}},be=class s{description;inputFields;outputFields;sigHash;sigString;validatedAtHash;constructor(e){if(!e){this.inputFields=[],this.outputFields=[],this.sigHash="",this.sigString="";return}if(typeof e=="string"){let t;try{t=Yl(e)}catch(n){if(n instanceof Error){let r="suggestion"in n&&typeof n.suggestion=="string"?n.suggestion:'Please check the signature format. Example: "userInput:string -> responseText:string"';throw new j(`Invalid Signature: ${n.message}`,void 0,r)}throw new j(`Invalid Signature: ${e}`,void 0,'Please check the signature format. Example: "userInput:string -> responseText:string"')}this.description=t.desc,this.inputFields=t.inputs.map(n=>this.parseParsedField(n)),this.outputFields=t.outputs.map(n=>this.parseParsedField(n)),[this.sigHash,this.sigString]=this.updateHash()}else if(e instanceof s)this.description=e.getDescription(),this.inputFields=structuredClone(e.getInputFields()),this.outputFields=structuredClone(e.getOutputFields()),this.sigHash=e.hash(),this.sigString=e.toString(),e.validatedAtHash===this.sigHash&&(this.validatedAtHash=this.sigHash),this._forceComplexFields=e._forceComplexFields,this._hasComplexFields=e._hasComplexFields;else if(typeof e=="object"&&e!==null){if(!("inputs"in e)||!("outputs"in e))throw new j("Invalid signature object: missing inputs or outputs",void 0,'Signature object must have "inputs" and "outputs" arrays. Example: { inputs: [...], outputs: [...] }');if(!Array.isArray(e.inputs)||!Array.isArray(e.outputs))throw new j("Invalid signature object: inputs and outputs must be arrays",void 0,'Both "inputs" and "outputs" must be arrays of AxField objects');try{this.description=e.description,this.inputFields=e.inputs.map(t=>this.parseField(t)),this.outputFields=e.outputs.map(t=>this.parseField(t)),[this.sigHash,this.sigString]=this.updateHash()}catch(t){throw t instanceof j?t:new j(`Failed to create signature from object: ${t instanceof Error?t.message:"Unknown error"}`,void 0,"Check that all fields in inputs and outputs arrays are valid AxField objects")}}else throw new j("Invalid signature argument type",void 0,"Signature must be a string, another AxSignature instance, or an object with inputs and outputs arrays")}static create(e){return new s(e)}parseParsedField=e=>{if(!e.name||e.name.length===0)throw new j("Field name is required",e.name,'Every field must have a descriptive name. Example: "userInput", "responseText"');let t=this.toTitle(e.name);return{name:e.name,title:t,description:"desc"in e?e.desc:void 0,type:e.type??{name:"string",isArray:!1},..."isInternal"in e?{isInternal:e.isInternal}:{},..."isOptional"in e?{isOptional:e.isOptional}:{}}};parseField=e=>{let t=!e.title||e.title.length===0?this.toTitle(e.name):e.title;if(e.type&&(!e.type.name||e.type.name.length===0))throw new j("Field type name is required",e.name,"Specify a valid type. Available types: string, number, boolean, json, image, audio, file, url, date, datetime, class, code");return{...e,title:t}};setDescription=e=>{if(typeof e!="string")throw new j("Description must be a string",void 0,"Provide a string description for the signature");this.description=e,this.invalidateValidationCache(),this.updateHashLight()};addInputField=e=>{try{let t=this.parseField(e);dt(t,"input");for(let n of this.inputFields)if(n.name===t.name)throw new j(`Duplicate input field name: "${t.name}"`,t.name,"Each field name must be unique within the signature");for(let n of this.outputFields)if(n.name===t.name)throw new j(`Field name "${t.name}" appears in both inputs and outputs`,t.name,"Use different names for input and output fields to avoid confusion");this.inputFields.push(t),this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof j?t:new j(`Failed to add input field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}};addOutputField=e=>{try{let t=this.parseField(e);dt(t,"output");for(let n of this.outputFields)if(n.name===t.name)throw new j(`Duplicate output field name: "${t.name}"`,t.name,"Each field name must be unique within the signature");for(let n of this.inputFields)if(n.name===t.name)throw new j(`Field name "${t.name}" appears in both inputs and outputs`,t.name,"Use different names for input and output fields to avoid confusion");this.outputFields.push(t),this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof j?t:new j(`Failed to add output field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}};setInputFields=e=>{if(!Array.isArray(e))throw new j("Input fields must be an array",void 0,"Provide an array of field objects");try{let t=e.map(n=>{let r=this.parseField(n);return dt(r,"input"),r});this.inputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof j?t:new j(`Failed to set input fields: ${t instanceof Error?t.message:"Unknown error"}`)}};setOutputFields=e=>{if(!Array.isArray(e))throw new j("Output fields must be an array",void 0,"Provide an array of field objects");try{let t=e.map(n=>{let r=this.parseField(n);return dt(r,"output"),r});this.outputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof j?t:new j(`Failed to set output fields: ${t instanceof Error?t.message:"Unknown error"}`)}};getInputFields=()=>this.inputFields;getOutputFields=()=>this.outputFields;getDescription=()=>this.description;appendInputField=(e,t)=>{let n=new s(this);return n.addInputField({name:e,..._o(t)}),n};prependInputField=(e,t)=>{let n=new s(this),r={name:e,..._o(t)},o=n.parseField(r);dt(o,"input");for(let i of n.inputFields)if(i.name===o.name)throw new j(`Duplicate input field name: "${o.name}"`,o.name,"Each field name must be unique within the signature");for(let i of n.outputFields)if(i.name===o.name)throw new j(`Field name "${o.name}" appears in both inputs and outputs`,o.name,"Use different names for input and output fields to avoid confusion");return n.inputFields.unshift(o),n.invalidateValidationCache(),n.updateHashLight(),n};appendOutputField=(e,t)=>{let n=new s(this);return n.addOutputField({name:e,..._o(t)}),n};prependOutputField=(e,t)=>{let n=new s(this),r={name:e,..._o(t)},o=n.parseField(r);dt(o,"output");for(let i of n.outputFields)if(i.name===o.name)throw new j(`Duplicate output field name: "${o.name}"`,o.name,"Each field name must be unique within the signature");for(let i of n.inputFields)if(i.name===o.name)throw new j(`Field name "${o.name}" appears in both inputs and outputs`,o.name,"Use different names for input and output fields to avoid confusion");return n.outputFields.unshift(o),n.invalidateValidationCache(),n.updateHashLight(),n};invalidateValidationCache=()=>{this.validatedAtHash=void 0,this._hasComplexFields=void 0};toTitle=e=>{let t=e.replace(/_/g," ");return t=t.replace(/([A-Z]|[0-9]+)/g," $1").trim(),t.charAt(0).toUpperCase()+t.slice(1)};updateHashLight=()=>{try{return this.getInputFields().forEach(e=>{dt(e,"input")}),this.getOutputFields().forEach(e=>{dt(e,"output")}),this.sigHash=Je("sha256").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=Zl(this.description,this.inputFields,this.outputFields),this._hasComplexFields=this.computeHasComplexFields(),[this.sigHash,this.sigString]}catch(e){throw e instanceof j?e:new j(`Signature validation failed: ${e instanceof Error?e.message:"Unknown error"}`)}};updateHash=()=>{try{return this.getInputFields().forEach(e=>{dt(e,"input")}),this.getOutputFields().forEach(e=>{dt(e,"output")}),this.validateSignatureConsistency(),this.sigHash=Je("sha256").update(this.description??"").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=Zl(this.description,this.inputFields,this.outputFields),this._hasComplexFields=this.computeHasComplexFields(),[this.sigHash,this.sigString]}catch(e){throw e instanceof j?e:new j(`Signature validation failed: ${e instanceof Error?e.message:"Unknown error"}`)}};validateSignatureConsistency(){let e=new Set;for(let n of this.inputFields){if(e.has(n.name))throw new j(`Duplicate input field name: "${n.name}"`,n.name,"Each field name must be unique within the signature");e.add(n.name)}let t=new Set;for(let n of this.outputFields){if(t.has(n.name))throw new j(`Duplicate output field name: "${n.name}"`,n.name,"Each field name must be unique within the signature");t.add(n.name)}for(let n of this.outputFields)if(e.has(n.name))throw new j(`Field name "${n.name}" appears in both inputs and outputs`,n.name,"Use different names for input and output fields to avoid confusion");if(this.inputFields.length===0)throw new j("Signature must have at least one input field",void 0,'Add an input field. Example: "userInput:string -> ..."');if(this.outputFields.length===0)throw new j("Signature must have at least one output field",void 0,'Add an output field. Example: "... -> responseText:string"')}_forceComplexFields=!1;_hasComplexFields;hasComplexFields=()=>this._hasComplexFields!==void 0?this._hasComplexFields:(this._hasComplexFields=this.computeHasComplexFields(),this._hasComplexFields);computeHasComplexFields=()=>this._forceComplexFields?!0:this.outputFields.some(e=>e.type?.name==="object"||e.type?.isArray&&e.type.fields!==void 0);validate=()=>{if(this.validatedAtHash===this.sigHash)return!0;try{return this.updateHash(),this.validatedAtHash=this.sigHash,!0}catch(e){throw this.validatedAtHash=void 0,e}};hash=()=>this.sigHash;toString=()=>this.sigString;toJSON=()=>({id:this.hash(),description:this.description,inputFields:this.inputFields,outputFields:this.outputFields});toJSONSchema=()=>{let e=[...this.inputFields,...this.outputFields];return vo(e,this.description??"Schema")}};function Ql(s){let e=s.name;return s.isOptional&&(e+="?"),s.isInternal&&(e+="!"),s.type&&(e+=`:${s.type.name}`,s.type.isArray&&(e+="[]"),s.type.name==="class"&&s.type.options&&(e+=` "${s.type.options.join(" | ")}"`)),s.description&&s.type?.name!=="class"&&(e+=` "${s.description}"`),e}function Zl(s,e,t){let n=s?`"${s}" `:"",r=e.map(Ql).join(", "),o=t.map(Ql).join(", ");return`${n}${r} -> ${o}`}function Yc(s){let e=/^[a-z][a-zA-Z0-9]*$/,t=/^[a-z]+(_[a-z0-9]+)*$/;return e.test(s)||t.test(s)}function dt(s,e){if(!s.name||s.name.length===0)throw new j("Field name cannot be blank",s.name,"Every field must have a descriptive name");if(!Yc(s.name))throw new j(`Invalid field name '${s.name}' - must be camelCase or snake_case`,s.name,'Use camelCase (e.g., "userInput") or snake_case (e.g., "user_input")');if(te.signatureStrict&&["text","object","image","string","number","boolean","json","array","datetime","date","time","type","class","input","output","data","value","result","response","request","item","element"].includes(s.name.toLowerCase())){let n=e==="input"?["userInput","questionText","documentContent","messageText","queryString"]:["responseText","analysisResult","categoryType","summaryText","outputData"];throw new j(`Field name '${s.name}' is too generic`,s.name,`Use a more descriptive name. Examples for ${e} fields: ${n.join(", ")}`)}if(s.name.length<2)throw new j(`Field name '${s.name}' is too short`,s.name,"Field names must be at least 2 characters long");if(s.name.length>50)throw new j(`Field name '${s.name}' is too long (${s.name.length} characters)`,s.name,"Field names should be 50 characters or less");s.type&&Qc(s,e)}function Qc(s,e){if(!s.type)return;let{type:t}=s;if((t.name==="image"||t.name==="audio"||t.name==="file")&&e==="output")throw new j(`${t.name} type is not supported in output fields`,s.name,`${t.name} types can only be used in input fields`);if(t.name==="class"){if(e==="input")throw new j("Class type is not supported in input fields",s.name,'Class types are only allowed on output fields. Use "string" type for input classifications');if(!t.options||t.options.length===0)throw new j("Class type requires options",s.name,'Provide class options. Example: class "positive, negative, neutral"');for(let r of t.options){if(!r||r.trim().length===0)throw new j("Empty class option found",s.name,"All class options must be non-empty strings");let o=r.trim();if(o.includes(",")||o.includes("|"))throw new j(`Invalid class option "${o}"`,s.name,"Class options cannot contain commas (,) or pipes (|) as they are used to separate options")}if(new Set(t.options.map(r=>r.trim().toLowerCase())).size!==t.options.length)throw new j("Duplicate class options found",s.name,"Each class option must be unique (case-insensitive)")}if(t.name==="code"&&t.isArray)throw new j("Arrays of code are not commonly supported",s.name,"Consider using a single code field or an array of strings instead");if(s.isInternal&&e==="input")throw new j("Internal marker (!) is not allowed on input fields",s.name,"Internal markers are only allowed on output fields");t.name==="object"&&t.fields&&vi(t.fields,s.name,e)}function vi(s,e,t,n=1){for(let[r,o]of Object.entries(s)){let i=`${e}.${r}`;if(o.type==="image"||o.type==="audio"||o.type==="file")throw new j(`${o.type} type is not allowed in nested object fields`,i,`Media types (image, audio, file) can only be used as top-level input fields, not within objects. Found at depth ${n}.`);o.type==="object"&&o.fields&&vi(o.fields,i,t,n+1),o.isArray&&o.fields&&vi(o.fields,`${i}[]`,t,n+1)}}var Et=class{signature;sigHash;examples;examplesOptions;demos;trace;usage=[];traceLabel;key;children;constructor(e,t){this.signature=new be(e),t?.description&&this.signature.setDescription(t.description),t?.traceLabel&&(this.traceLabel=t.traceLabel),e&&this.signature.validate(),this.sigHash=this.signature?.hash(),this.children=new bn,this.key={id:this.signature.hash()}}getSignature(){return new be(this.signature)}setSignature(e){this.signature=new be(e),e&&this.signature.validate(),this.updateSignatureHash()}setDescription(e){this.signature.setDescription(e),this.updateSignatureHash()}updateSignatureHash(){this.sigHash=this.signature.hash(),this.key={id:this.signature.hash()}}register(e){this.key&&e.setParentId(this.key.id),this.children.register(e)}setId(e){this.key={id:e,custom:!0};for(let t of Array.from(this.children))t?.setParentId(e)}setParentId(e){this.key.custom||(this.key.id=[e,this.key.id].join("/"))}setExamples(e,t){if(this._setExamples(e,t),"programId"in e)for(let n of Array.from(this.children))n?.setExamples(e,t)}_setExamples(e,t){let n=[];if("programId"in e&&e.programId===this.key.id&&(n=e.traces),Array.isArray(e)&&(n=e),n){this.examplesOptions=t;let r=this.signature,o=[...r.getInputFields(),...r.getOutputFields()];this.examples=n.map(i=>{let a={};for(let l of o){let u=i[l.name];u!==void 0&&(ko(l,u),a[l.name]=u)}return a})}}getTraces(){let e=[];this.trace&&e.push({trace:this.trace,programId:this.key.id});for(let t of Array.from(this.children)){let n=t?.getTraces();e=[...e,...n??[]]}return e}getUsage(){let e=[...this.usage??[]];for(let t of Array.from(this.children)){let n=t?.getUsage();e=[...e,...n??[]]}return pr(e)}resetUsage(){this.usage=[];for(let e of Array.from(this.children))e?.resetUsage()}setDemos(e){let t=Array.from(this.children).length>0,n=e.some(r=>r.programId===this.key.id);if(t&&!n)throw new Error(`Program with id '${this.key.id}' has children but no matching programId found in demos`);this.demos=e.filter(r=>r.programId===this.key.id).map(r=>r.traces).flat();for(let r of Array.from(this.children))r?.setDemos(e)}applyOptimization(e){e.applyTo(this);for(let t of Array.from(this.children))t&&"applyOptimization"in t&&typeof t.applyOptimization=="function"&&t.applyOptimization(e)}};var Xl=`
209
+ Tip: Arrays must include an "items" schema (e.g., { items: { type: "string" } } or items: { type: "object", properties: { ... } }).`,{cause:r}):r}return[...e??[],...t]},ko=async({ai:i,functionList:e,functionCalls:t,mem:n,sessionId:r,traceId:o,span:s,excludeContentFromTrace:a,index:l,functionResultFormatter:u,logger:c,debug:p,stopFunctionNames:d})=>{let m=new cr(e),g=new Set,h=[],f=b=>{let S=R=>R.replace(/[^a-zA-Z0-9]/g,"").toLowerCase(),w=S(b),M=e.find(R=>R.name===b);return M||(M=e.find(R=>S(R.name)===w)),M},x=t.map(b=>{if(!b.id)throw new Error(`Function ${b.name} did not return an ID`);let S=i.getOptions().tracer??ee.tracer;return S?S.startActiveSpan(`Tool: ${b.name}`,async w=>{try{w?.setAttributes?.({"tool.name":b.name,"tool.mode":"native","function.id":b.id,"session.id":r??""});let{formatted:M,rawResult:R,parsedArgs:k}=await m.executeWithDetails(b,{sessionId:r,ai:i,functionResultFormatter:u,traceId:w?.spanContext?.().traceId??o,stopFunctionNames:d});if(g.add(b.name.toLowerCase()),d?.includes(b.name.toLowerCase())){let F=f(b.name);F&&h.push({func:F,args:k,result:R})}if(a?w.addEvent("gen_ai.tool.message",{name:b.name}):w.addEvent("gen_ai.tool.message",{name:b.name,args:b.args,result:M??""}),s){let F={name:b.name};a||(F.args=b.args,F.result=M??""),s.addEvent("function.call",F)}return{result:M??"",role:"function",functionId:b.id,index:l}}catch(M){if(w?.recordException?.(M),M instanceof ur){let R=M.getFixingInstructions(),k={name:b.name,message:M.toString()};return a||(k.args=b.args,k.fixing_instructions=R),w?.addEvent?.("function.error",k),p&&Rs(M,l,R,c),{functionId:b.id,isError:!0,index:l,result:R,role:"function"}}throw M}finally{w?.end?.()}}):m.executeWithDetails(b,{sessionId:r,ai:i,functionResultFormatter:u,traceId:o,stopFunctionNames:d}).then(({formatted:w,rawResult:M,parsedArgs:R})=>{if(g.add(b.name.toLowerCase()),d?.includes(b.name.toLowerCase())){let k=f(b.name);k&&h.push({func:k,args:R,result:M})}if(s){let k={name:b.name};a||(k.args=b.args,k.result=w??""),s.addEvent("function.call",k)}return{result:w??"",role:"function",functionId:b.id,index:l}}).catch(w=>{if(!(w instanceof ur))throw w;let M=w.getFixingInstructions();if(s){let R={name:b.name,message:w.toString()};a||(R.args=b.args,R.fixing_instructions=M),s.addEvent("function.error",R)}return p&&Rs(w,l,M,c),{functionId:b.id,isError:!0,index:l,result:M,role:"function"}})}),y=(await Promise.all(x)).map(b=>b.result===void 0||b.result===""?{...b,result:"done"}:b);if(y.length>0&&(y[y.length-1].cache=!0),n.addFunctionResults(y,r),p){let b=y.filter(S=>!S.isError);b.length>0&&ma(b,c)}if(h.length>0)throw new $t(h);return g};function li(i,e,t,n){if(!e||e.length===0)return;if(!i.getFeatures(n).functions)throw new Error("Functions are not supported by the AI service");return e.map(o=>({id:o.id,name:o.function.name,args:o.function.params}))}function _l(i,e,t,n){let r=e;return!t&&(r==="required"||typeof r=="function")?{functions:[],functionCall:void 0}:i?{functions:i.map(s=>"toFunction"in s?s.toFunction():s).flat(),functionCall:r}:{functions:[],functionCall:r}}function $l(i){if(!i.trim())return null;try{return JSON.parse(i)}catch{}let e=Kc(i);try{return JSON.parse(e)}catch{return null}}function Kc(i){let e=i.trim();for(e.endsWith(",")&&(e=e.slice(0,-1));e.match(/[0-9][eE.+-]$/);)e=e.slice(0,-1);e=e.replace(/,(\s*[}\]])/g,"$1"),e.match(/t(r(u(e)?)?)?$/)&&!e.endsWith('"')&&!e.endsWith("true")&&e.match(/[:[,]\s*t(r(u(e)?)?)?$/)&&(e=e.replace(/t(r(u(e)?)?)?$/,"true")),e.match(/f(a(l(s(e)?)?)?)?$/)&&!e.endsWith('"')&&!e.endsWith("false")&&e.match(/[:[,]\s*f(a(l(s(e)?)?)?)?$/)&&(e=e.replace(/f(a(l(s(e)?)?)?)?$/,"false")),e.match(/n(u(l(l)?)?)?$/)&&!e.endsWith('"')&&!e.endsWith("null")&&e.match(/[:[,]\s*n(u(l(l)?)?)?$/)&&(e=e.replace(/n(u(l(l)?)?)?$/,"null"));let t=[],n=!1,r=!1;for(let o=0;o<e.length;o++){let s=e[o];if(r){r=!1;continue}if(s==="\\"){r=!0;continue}if(s==='"'){n=!n;continue}n||(s==="{"?t.push("}"):s==="["?t.push("]"):s==="}"?t.length>0&&t[t.length-1]==="}"&&t.pop():s==="]"&&t.length>0&&t[t.length-1]==="]"&&t.pop())}for(r&&(e=e.slice(0,-1)),n&&(e+='"'),t.length>0&&t[t.length-1]==="}"&&e.match(/,\s*"[^"]*"\s*$/)&&(e=e.replace(/,\s*"[^"]*"\s*$/,""));t.length>0;)e+=t.pop();return e}var kt=$n(Nl(),1),Ul=$n(Dl(),1),Bl=$n(Gl(),1),jl=$n(Ll(),1);kt.default.extend(jl.default);kt.default.extend(Bl.default);kt.default.extend(Ul.default);function ql(i,e,t=!1){try{return Vc(e)}catch(n){if(i.isOptional&&!t)return;let r=n.message;throw Sl(i,e,r)}}function Vc(i){if(!(0,kt.default)(i,"YYYY-MM-DD",!0).isValid())throw new Error('Invalid date format. Please provide the date in "YYYY-MM-DD" format.');return kt.default.utc(i,"YYYY-MM-DD").startOf("day").toDate()}function zl(i,e,t=!1){try{return Wc(e)}catch(n){if(i.isOptional&&!t)return;let r=n.message;throw Ol(i,e,r)}}function Wc(i){let e=/^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}(?::\d{2})?) (.+)$/,t=i.match(e);if(!t)throw new Error('Invalid date and time format. Please provide the date and time in "YYYY-MM-DD HH:mm" or "YYYY-MM-DD HH:mm:ss" format, followed by the timezone.');let[,n,r]=t;if(!n||!r)throw new Error('Invalid date and time format. Please provide the date and time in "YYYY-MM-DD HH:mm" or "YYYY-MM-DD HH:mm:ss" format, followed by the timezone.');try{let o=n.includes(":")&&n.split(":").length===3?"YYYY-MM-DD HH:mm:ss":"YYYY-MM-DD HH:mm",s=kt.default.tz(n,o,r);if(!s.isValid())throw new Error("Invalid date and time values. Please ensure all components are correct.");return s.utc().toDate()}catch{throw new Error(`Unrecognized time zone ${r}. Please provide a valid time zone name, abbreviation, or offset. For example, "America/New_York", or "EST".`)}}var Hl=i=>(0,kt.default)(i).utc().format("YYYY-MM-DD HH:mm:ss [UTC]");var cx=new Ue,Mo=(i,e)=>{let t=i.type??{name:"string",isArray:!1},n=(u,c)=>{switch(u){case"class":return typeof c=="string";case"code":return typeof c=="string";case"string":return typeof c=="string";case"number":return typeof c=="number";case"boolean":return typeof c=="boolean";case"date":return c instanceof Date||typeof c=="string";case"datetime":return c instanceof Date||typeof c=="string";case"json":return typeof c=="object"||typeof c=="string";case"object":return typeof c=="object";default:return!1}},r=u=>!(!u||typeof u!="object"||!("mimeType"in u)||!("data"in u));if(i.type?.name==="image"){let u;if(Array.isArray(e)){for(let c of e)if(!r(c)){u="object ({ mimeType: string; data: string })";break}}else r(e)||(u="object ({ mimeType: string; data: string })");if(u)throw new Error(`Validation failed: Expected '${i.name}' to be type '${u}' instead got '${e}'`);return}let o=u=>!(!u||typeof u!="object"||!("data"in u));if(i.type?.name==="audio"){let u;if(Array.isArray(e)){for(let c of e)if(!o(c)){u="object ({ data: string; format?: string })";break}}else o(e)||(u="object ({ data: string; format?: string })");if(u)throw new Error(`Validation failed: Expected '${i.name}' to be type '${u}' instead got '${e}'`);return}let s=u=>{if(!u||typeof u!="object"||!("mimeType"in u))return!1;let c="data"in u,p="fileUri"in u;return!(!c&&!p||c&&p)};if(i.type?.name==="file"){let u;if(Array.isArray(e)){for(let c of e)if(!s(c)){u="object ({ mimeType: string; data: string } | { mimeType: string; fileUri: string })";break}}else s(e)||(u="object ({ mimeType: string; data: string } | { mimeType: string; fileUri: string })");if(u)throw new Error(`Validation failed: Expected '${i.name}' to be type '${u}' instead got '${e}'`);return}let a=u=>typeof u=="string"?!0:!(!u||typeof u!="object"||!("url"in u));if(i.type?.name==="url"){let u;if(Array.isArray(e)){for(let c of e)if(!a(c)){u="string or object ({ url: string; title?: string; description?: string })";break}}else a(e)||(u="string or object ({ url: string; title?: string; description?: string })");if(u)throw new Error(`Validation failed: Expected '${i.name}' to be type '${u}' instead got '${e}'`);return}let l=!0;if(t.isArray){if(!Array.isArray(e))l=!1;else for(let u of e)if(!n(t.name,u)){l=!1;break}}else l=n(t.name,e);if(!l){let u=Array.isArray(e)?"array":typeof e;throw new Error(`Validation failed: Expected '${i.name}' to be a ${i.type?.isArray?"an array of ":""}${t.name} instead got '${u}' (${JSON.stringify(e)})`)}};function pr(i){let e={};for(let t of i){let n=`${t.ai}:${t.model}`;if(!e[n]){e[n]={...t};continue}let r=e[n];if(r){let o=r.tokens??{promptTokens:0,completionTokens:0,totalTokens:0};o.promptTokens+=t?.tokens?.promptTokens??0,o.completionTokens+=t?.tokens?.completionTokens??0,o.totalTokens+=t?.tokens?.totalTokens??0,r.tokens=o;let s=r.citations??[],a=t.citations??[];if(a.length){let l=new Set(s.map(u=>u.url));for(let u of a)u?.url&&!l.has(u.url)&&(s.push(u),l.add(u.url));r.citations=s}}}return Object.values(e)}var Kl=i=>{if(!i.trim())return[];let e=new Set(["-","*","+"]),t=/^\d+[\s]*[.)\]]\s*/,n=i.split(`
210
+ `),r=[];for(let o of n){let s=o.trim();if(s){if(s[0]&&e.has(s[0]))r.push(s.slice(1).trim());else if(t.test(s))r.push(s.replace(t,"").trim());else if(r.length!==0)throw new Error("Could not parse markdown list: mixed content detected")}}if(r.length===0)throw new Error("Could not parse markdown list: no valid list items found");return r};function Ai(i,e){let{index:t,delta:n,version:r}=e,o=i.find(a=>a.index===t)?.delta;if(!o)return i.push({index:t,delta:n,version:r}),i;for(let a of Object.keys(n)){let l=o[a],u=n[a];l===void 0&&Array.isArray(u)?o[a]=[...u]:Array.isArray(l)&&Array.isArray(u)?o[a]=[...l,...u]:(l===void 0||typeof l=="string")&&typeof u=="string"?o[a]=`${l??""}${u}`:o[a]=u}let s=i.find(a=>a.index===t);return s&&(s.version=r),i}var xi=class{cache=new Map;maxSize;constructor(e){this.maxSize=e}get(e){let t=this.cache.get(e);return t&&(this.cache.delete(e),this.cache.set(e,t)),t}set(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxSize){let n=this.cache.keys().next().value;n&&this.cache.delete(n)}this.cache.set(e,t)}},Jc=new xi(500);function Vl(i,e,t=0,n=Jc){if(/^```[a-zA-Z]*\s*$/.test(i))return-4;if(/^[\s`]*$/.test(i))return-3;let r=i.indexOf(e,t);if(r!==-1)return r;let o=n.get(e)??Array.from({length:e.length},(a,l)=>e.slice(0,l+1));n.get(e)||n.set(e,o);let s=-1;for(let a=o.length-1;a>=0;a--){let l=o[a];if(i.endsWith(l)){s=a;break}}return s>=0?-2:-1}function Mt(i,e){if(typeof i!="string")throw ii(e,String(i),"URL must be a string");try{new URL(i)}catch{throw ii(e,i,"Invalid URL format. Expected a valid URL like https://example.com")}}function Ze(i,e){if(typeof i!="string")return;let t=e.type;if(t){if(t.minLength!==void 0&&i.length<t.minLength)throw yn(e,i,"minLength",t.minLength);if(t.maxLength!==void 0&&i.length>t.maxLength)throw yn(e,i,"maxLength",t.maxLength);if(t.pattern!==void 0&&!new RegExp(t.pattern).test(i))throw yn(e,i,"pattern",t.pattern);if(t.format==="email"&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(i))throw yn(e,i,"format","valid email address");if(t.format==="uri"||t.format==="url")try{new URL(i)}catch{throw yn(e,i,"format","valid URL")}}}function et(i,e){if(typeof i!="number")return;let t=e.type;if(t){if(t.minimum!==void 0&&i<t.minimum)throw ai(e,i,"minimum",t.minimum);if(t.maximum!==void 0&&i>t.maximum)throw ai(e,i,"maximum",t.maximum)}}var Fo=(i,e,t,n)=>{let r=n?.strictMode??!1,o=n?.treatAllFieldsOptional??!1,s=n?.treatAllFieldsOptional??!1,a={extractedFields:[],streamedIndex:{},s:-1};Ii(i,e,a,t,{strictMode:r,skipEarlyFail:s,treatAllFieldsOptional:o}),Ti(i,e,a,t,{strictMode:r,treatAllFieldsOptional:o,forceFinalize:!0});for(let l of i.getOutputFields())l.isInternal&&delete e[l.name]},yi=(i,e,t)=>{let n=[];for(let r of t)r&&!r.isOptional&&e[r.name]===void 0&&n.push(r);if(n.length>0)throw Cl(n)},Ii=(i,e,t,n,{strictMode:r,skipEarlyFail:o}={})=>{let s=i.getOutputFields(),a;for(;;){let l=new Set;t.currFieldIndex!==void 0&&!t.inAssumedField&&l.add(t.currFieldIndex);let u=s.map((g,h)=>({field:g,index:h})).filter(({index:g})=>!l.has(g)),c,p,d=-1,m=0;for(let{index:g,field:h}of u){let x=`${(t.extractedFields.length===0?"":`
211
+ `)+h.title}:`,A=Vl(n,x,t.s);if(A===-2||A===-3)return!0;if(A===-4)return t.inBlock=!0,!0;A>=0&&(d===-1||A<d)&&(d=A,m=x.length,c=g,p=h)}if(d===-1){if(o)return;if(!r&&t.currField===void 0&&t.extractedFields.length===0&&s.length===1){t.inAssumedField=!0,t.currField=s[0],t.currFieldIndex=0,t.s=0,t.extractedFields.includes(s[0])||t.extractedFields.push(s[0]),t.streamedIndex[s[0].name]===void 0&&(t.streamedIndex[s[0].name]=0);return}if(r&&t.currField===void 0&&t.extractedFields.length===0){let g=s.find(h=>!h.isOptional);if(g)throw Co(g)}break}if(a&&p&&a.name!==p.name)throw Co(a);if(t.currField!==void 0&&t.inAssumedField&&(t.inAssumedField=!1,t.streamedIndex[t.currField.name]=0,t.currField=void 0),t.currField){let g=n.substring(t.s,d).trim(),h=Eo(t.currField,g);h!==void 0&&(e[t.currField.name]=h),t.prevFields?t.prevFields?.push({field:t.currField,s:t.s,e:d}):t.prevFields=[{field:t.currField,s:t.s,e:d}]}t.s=d+m,p!==void 0&&c!==void 0&&(t.currField=p,t.currFieldIndex=c),p&&!t.extractedFields.includes(p)&&t.extractedFields.push(p),p&&t.streamedIndex[p.name]===void 0&&(t.streamedIndex[p.name]=0)}},Ti=(i,e,t,n,r)=>{let o=r?.strictMode??!1,s=r?.treatAllFieldsOptional??!1,a=r?.deferRequiredCheckForStreaming??!1,l=r?.forceFinalize??!1;if(t.currField){let u=n.length,c=i.getOutputFields();for(let m of c){if(m.name===t.currField.name)continue;let g=`
212
+ ${m.title}:`,h=n.indexOf(g,t.s);h!==-1&&h<u&&(u=h)}let p=n.substring(t.s,u).trim(),d=Eo(t.currField,p);d!==void 0&&(e[t.currField.name]=d)}if(o&&!t.currField&&t.extractedFields.length===0&&n.trim()){let p=i.getOutputFields().find(d=>!d.isOptional);if(p)throw Co(p)}if(Yc(i,e,n,t),!s){let u=t.currField!==void 0||(t.extractedFields?.length??0)>0;o||l?yi(t,e,i.getOutputFields()):u||yi(t,e,i.getOutputFields())}},Yc=(i,e,t,n)=>{let r=i.getOutputFields();if(r.length===1){let s=r[0];if(s){let a=`${s.title}:`,l=t.indexOf(a);if(l!==-1){let u=l+a.length,c=`
213
+ ${s.title}:`,p=t.indexOf(c,u),d=t.substring(u,p===-1?t.length:p).trim();if(d)try{let m=Eo(s,d);if(m!==void 0){e[s.name]=m;return}}catch{}}}}let o=t.split(`
214
+ `);for(let s of r){if(s.name in e)continue;let a=`${s.title}:`;for(let l of o){let u=l.trim();if(u.startsWith(a)){let c=u.substring(a.length).trim();if(c)try{let p=Eo(s,c);if(p!==void 0){e[s.name]=p;break}}catch(p){if(!s.isOptional)throw p}break}}}},Wl=(i,e,t=!1)=>{switch(i.type?.name){case"code":return bi(e);case"string":return e;case"number":{let n=Number(e);if(Number.isNaN(n)){if(i.isOptional&&!t)return;throw new Error("Invalid number")}return n}case"boolean":{if(typeof e=="boolean")return e;let n=e.toLowerCase();if(n==="true")return!0;if(n==="false")return!1;if(i.isOptional&&!t)return;throw new Error("Invalid boolean")}case"date":return ql(i,e,t);case"datetime":return zl(i,e,t);case"class":{let n=e;if(i.type.options&&!i.type.options.includes(n)){if(i.isOptional)return;throw new Error(`Invalid class '${e}', expected one of the following: ${i.type.options.join(", ")}`)}return n}default:return e}};function*Jl(i,e,t,n,r,o){let{name:s,isInternal:a}=e,{isArray:l,name:u}=e.type??{};if(a||l||u&&u!=="string"&&u!=="code")return;let c=r.streamedIndex[s]??0,p=c===0,d=(t<0?0:t)+c,m=i.substring(d,n);if(m.length===0)return;let g=m.replace(/\s+$/,"");r.currField?.type?.name==="code"&&(g=g.replace(/\s*```\s*$/,""));let h=p?g.trimStart():g;r.currField?.type?.name==="code"&&(h=h.replace(/^[ ]*```[a-zA-Z0-9]*\n\s*/,"")),h.length>0&&(yield{index:o,delta:{[s]:h}},r.streamedIndex[s]=c+g.length)}function*Ci(i,e,t,n,r){for(let s of n.prevFields??[]){let{field:a,s:l,e:u}=s;yield*Jl(e,a,l,u,n,r)}if(n.prevFields=void 0,n.inAssumedField&&!(i.getOutputFields().filter(l=>!l.isInternal).length===1)||!n.currField||n.currField.isInternal)return;yield*Jl(e,n.currField,n.s,e.length,n,r);let o=i.getOutputFields();for(let s of Object.keys(t)){let a=o.find(c=>c.name===s);if(!a||a.isInternal)continue;let l=t[s];if(Array.isArray(l)){let c=n.streamedIndex?.[s]??0,p=l.slice(c);p&&p.length>0&&(yield{index:r,delta:{[s]:p}},n.streamedIndex[s]=c+p.length);continue}let u=typeof l=="string"?l:void 0;if(!n.streamedIndex[s])yield{index:r,delta:{[s]:l}},n.streamedIndex[s]=u?u.length:1;else if(u){let c=n.streamedIndex[s];if(u.length>c){let p=u.substring(c);yield{index:r,delta:{[s]:p}},n.streamedIndex[s]=u.length}}}}function Eo(i,e){if(!e||e===""||/^(null|undefined)\s*$/i.test(e)){if(i.isOptional)return;throw wo(i)}let t;if(i.type?.name==="json"&&!i.type?.isArray)try{let r=bi(e);return t=JSON.parse(r),t}catch(r){throw wl(i,r.message)}if(i.type?.isArray)try{try{t=JSON.parse(e)}catch{t=Kl(e)}if(!Array.isArray(t))throw new Error("Expected an array")}catch(r){throw Rl(i,r.message)}try{if(Array.isArray(t)){for(let[r,o]of t.entries())if(o!==void 0){let s=typeof o=="string"?o.trim():o;if(typeof s=="string"&&(i.type?.name==="object"||i.type?.name==="json"))try{let a=bi(s);s=JSON.parse(a)}catch{}t[r]=Wl(i,s,!0)}}else t=Wl(i,e)}catch(r){throw vl(i,e,r.message)}if(typeof t=="string"&&t==="")return;let n=i.type;if(n&&t!==void 0&&(n.name==="url"&&Mt(t,i),(n.name==="string"||n.name==="code")&&Ze(t,i),n.name==="number"&&et(t,i),n.isArray&&Array.isArray(t)))for(let r of t)r!==void 0&&(n.name==="string"||n.name==="code"?Ze(r,i):n.name==="number"&&et(r,i));return t}function _o(i,e,t){let n=i.getOutputFields();for(let r of n){let o=e[r.name];if(o==null){if(!r.isOptional&&!t?.allowMissingRequired)throw wo(r);continue}let s=r.type;if(s){if(s.name==="url"&&Mt(o,r),(s.name==="string"||s.name==="code")&&Ze(o,r),s.name==="number"&&et(o,r),s.isArray&&Array.isArray(o))for(let a of o)a!=null&&(s.name==="url"?Mt(a,r):s.name==="string"||s.name==="code"?Ze(a,r):s.name==="number"&&et(a,r));if(s.name==="object"&&s.fields&&typeof o=="object"&&!Array.isArray(o)&&Po(r,o,t),s.isArray&&s.fields&&Array.isArray(o)&&s.name==="object")for(let a of o)a&&typeof a=="object"&&Po(r,a,t)}}}function Po(i,e,t){let n=i.type?.fields;if(!(!n||typeof n!="object"))for(let[r,o]of Object.entries(n)){let s={name:r,title:r,description:o.description,type:{name:o.type,isArray:o.isArray,options:o.options,fields:o.fields,minLength:o.minLength,maxLength:o.maxLength,minimum:o.minimum,maximum:o.maximum,pattern:o.pattern,patternDescription:o.patternDescription,format:o.format},isOptional:o.isOptional??!1,isInternal:o.isInternal??!1},a=e[s.name];if(a==null){if(!s.isOptional&&!t?.allowMissingRequired)throw wo(s);continue}let l=s.type;if(l){if(l.name==="url"&&Mt(a,s),(l.name==="string"||l.name==="code")&&Ze(a,s),l.name==="number"&&et(a,s),l.isArray&&Array.isArray(a))for(let u of a)u!=null&&(l.name==="url"?Mt(u,s):l.name==="string"||l.name==="code"?Ze(u,s):l.name==="number"&&et(u,s));if(l.name==="object"&&l.fields&&typeof a=="object"&&!Array.isArray(a)&&Po(s,a,t),l.isArray&&l.fields&&Array.isArray(a)&&l.name==="object")for(let u of a)u&&typeof u=="object"&&Po(s,u,t)}}}var bi=i=>{let t=/```([A-Za-z]*)\s*([\s\S]*?)\s*```/g.exec(i);return t?t.length===3?t[2]:t.length===2?t[1]:i:i};async function wi(i,e,t,n){for(let r of i){if(e[r.field.name]===void 0)continue;let o=r.process,s=await o(e[r.field.name],{sessionId:n,values:e,done:!0});Yl(r.field,t,s,n)}}async function Ri(i,e,t,n,r,o,s=!1){for(let a of i){if(t.currField?.name!==a.field.name)continue;let l=e.substring(t.s);t.currField?.type?.name==="code"&&(l=l.replace(/^[ ]*```[a-zA-Z0-9]*\n\s*/,""),l=l.replace(/\s*```\s*$/,""));let u=a.process,c=await u(l,{sessionId:o,values:r,done:s});Yl(t.currField,n,c,o)}}var Yl=(i,e,t,n)=>{if(t===void 0||typeof t=="string"&&(t===""||/^(null|undefined)\s*$/i.test(t)))return;let r=JSON.stringify(t,(s,a)=>typeof a=="bigint"?Number(a):a,2),o=Qc(i,r);e.addRequest([{role:"user",content:[{type:"text",text:o}]}],n),e.addTag("processor",n)};function Qc(i,e){let t=i.type?.name==="code",n=i.title;return t?`Code in the field "${n}" was executed. The code execution produced the following output: ${e}`:`The field "${n}" was processed. The field contents were transformed into the following output: ${e}`}async function*Ql({res:i,usage:e,states:t,debug:n,...r}){let o=(r.ai.getFeatures().functionCot??!1)&&r.functions!==void 0&&r.functions.length>0,s,a=[],l=i.getReader();try{for(;;){let{done:u,value:c}=await l.read();if(u)break;let p=c;p.modelUsage&&(s=p.modelUsage);for(let d of p.results){if(Array.isArray(d.citations))for(let g of d.citations)g?.url&&a.push({url:g.url,title:g.title,description:g.description,license:g.license,publicationDate:g.publicationDate,snippet:g.snippet});if((!d.content||d.content==="")&&(!d.thought||d.thought==="")&&(!d.thoughtBlocks||d.thoughtBlocks.length===0)&&(!d.functionCalls||d.functionCalls.length===0))continue;let m=t.find(g=>g.index===d.index);if(!m)throw new Error(`No state found for result (index: ${d.index})`);yield*Xc({...r,result:d,skipEarlyFail:o,state:m,debug:n})}}}finally{l.releaseLock()}for(let u of t)yield*Zc({...r,state:u,debug:n});if(s){if(a.length){let u=Array.from(new Map(a.filter(c=>c.url).map(c=>[c.url,c])).values());s.citations=u}if(e.push(s),n&&r.logger){let u=structuredClone(s);delete u.citations,r.logger({name:"ChatResponseUsage",value:u}),s.citations&&s.citations.length>0&&r.logger({name:"ChatResponseCitations",value:s.citations})}}}async function*Xc({result:i,mem:e,sessionId:t,strictMode:n,skipEarlyFail:r,treatAllFieldsOptional:o,state:s,signature:a,streamingFieldProcessors:l,thoughtFieldName:u,streamingAsserts:c,asserts:p}){if(i.functionCalls&&i.functionCalls.length>0)Gr(s.functionCalls,i.functionCalls),e.updateResult({name:i.name,content:i.content,functionCalls:s.functionCalls,thoughtBlocks:i.thoughtBlocks,delta:i.functionCalls?.[0]?.function?.params,index:i.index},t);else if(i.content&&i.content.length>0){i.thought&&i.thought.length>0&&(yield{index:i.index,delta:{[u]:i.thought}}),s.content+=i.content,e.updateResult({name:i.name,content:s.content,thoughtBlocks:i.thoughtBlocks,delta:i.content,index:i.index},t);let d=a.getOutputFields();if(a.hasComplexFields()){let h=$l(s.content);if(h&&typeof h=="object"){let f={},x={};for(let A of Object.keys(h))if(d.some(y=>y.name===A)){let y=h[A],b=s.values[A];if(x[A]=y,typeof y=="string"&&typeof b=="string"&&y.startsWith(b)){let S=y.slice(b.length);S&&(f[A]=S)}else Array.isArray(y)&&Array.isArray(b)?y.length>b.length&&(f[A]=y.slice(b.length)):JSON.stringify(y)!==JSON.stringify(b)&&(f[A]=y)}try{_o(a,x,{allowMissingRequired:!0})}catch{}Object.assign(s.values,x),Object.keys(f).length>0&&(yield{index:i.index,delta:f});return}}if(Ii(a,s.values,s.xstate,s.content,{strictMode:n,skipEarlyFail:r,treatAllFieldsOptional:o}))return;c.length!==0&&await ti(c,s.xstate,s.content),l.length!==0&&await Ri(l,s.content,s.xstate,e,s.values,t),yield*Ci(a,s.content,s.values,s.xstate,i.index),await yo(p,s.values)}else i.thought&&i.thought.length>0?(s.values[u]=(s.values[u]??"")+i.thought,yield{index:i.index,delta:{[u]:i.thought}},e.updateResult({name:i.name,content:s.content,delta:"",index:i.index,thought:i.thought,thoughtBlocks:i.thoughtBlocks},t)):i.thoughtBlocks&&i.thoughtBlocks.length>0&&e.updateResult({name:i.name,content:s.content,delta:"",index:i.index,thoughtBlocks:i.thoughtBlocks},t);if(i.finishReason==="length")throw new Error(`Max tokens reached before completion
215
+ Content: ${s.content}`)}async function*Zc({state:i,signature:e,ai:t,model:n,functions:r,mem:o,sessionId:s,traceId:a,span:l,strictMode:u,excludeContentFromTrace:c,streamingAsserts:p,asserts:d,fieldProcessors:m,streamingFieldProcessors:g,functionResultFormatter:h,signatureToolCallingManager:f,logger:x,debug:A,stopFunctionNames:y}){let b=f?void 0:li(t,i.functionCalls,i.values,n);if(b){if(!r)throw new Error("Functions are not defined");let S=await ko({ai:t,functionList:r,functionCalls:b,mem:o,sessionId:s,traceId:a,span:l,index:i.index,excludeContentFromTrace:c,functionResultFormatter:h,logger:x,debug:A,stopFunctionNames:y});i.functionsExecuted=new Set([...i.functionsExecuted,...S]),i.functionCalls=[]}else{let S=e.getOutputFields(),w=e.hasComplexFields(),M=!1;if(w)try{let R=JSON.parse(i.content),k={};for(let F of Object.keys(R))if(S.some(E=>E.name===F)){let E=R[F],T=i.values[F];if(typeof E=="string"&&typeof T=="string"&&E.startsWith(T)){let v=E.slice(T.length);v&&(k[F]=v)}else Array.isArray(E)&&Array.isArray(T)?E.length>T.length&&(k[F]=E.slice(T.length)):JSON.stringify(E)!==JSON.stringify(T)&&(k[F]=E)}try{_o(e,k,{allowMissingRequired:!0})}catch(F){let E=(F.message||"").toLowerCase();if(E.includes("at least")||E.includes("at most")||E.includes("must match pattern")||E.includes("invalid url")||E.includes("required")||E.includes("missing")||E.includes("valid email")||E.includes("number must be"))throw F}Object.assign(i.values,k),yield{index:i.index,delta:k},M=!0}catch(R){let k=(R.message||"").toLowerCase();if(k.includes("at least")||k.includes("at most")||k.includes("must match pattern")||k.includes("invalid url")||k.includes("required")||k.includes("missing")||k.includes("valid email")||k.includes("number must be"))throw R}if(!M){let R=f!==void 0;Ti(e,i.values,i.xstate,i.content,{strictMode:u,treatAllFieldsOptional:R,deferRequiredCheckForStreaming:!0,forceFinalize:!0})}if(f){let R=await f.processResults(i.values);if(R&&R.length>0){if(!r)throw new Error("Functions are not defined");let k=await ko({ai:t,functionList:r,functionCalls:R,mem:o,sessionId:s,traceId:a,span:l,index:i.index,excludeContentFromTrace:c,functionResultFormatter:h,logger:x,debug:A,stopFunctionNames:y});i.functionsExecuted=new Set([...i.functionsExecuted,...k]),o.updateResult({name:void 0,content:i.content,functionCalls:R.map(F=>({id:F.id,type:"function",function:{name:F.name,params:F.args}})),index:i.index},s);return}}await ti(p,i.xstate,i.content,!0),await yo(d,i.values),m.length&&await wi(m,i.values,o,s),g.length!==0&&await Ri(g,i.content,i.xstate,o,i.values,s,!0),yield*Ci(e,i.content,i.values,i.xstate,i.index)}}async function*Xl({ai:i,res:e,mem:t,sessionId:n,traceId:r,functions:o,span:s,strictMode:a,states:l,usage:u,excludeContentFromTrace:c,asserts:p,fieldProcessors:d,thoughtFieldName:m,signature:g,functionResultFormatter:h,logger:f,debug:x,signatureToolCallingManager:A,stopFunctionNames:y,disableMemoryCleanup:b}){let S=e.results??[],w=A!==void 0;t.addResponse(S,n);let M=[];for(let E of S)if(Array.isArray(E?.citations))for(let T of E.citations)T?.url&&M.push({url:T.url,title:T.title,description:T.description,license:T.license,publicationDate:T.publicationDate,snippet:T.snippet});for(let E of S){let T=l[E.index];if(!T)throw new Error(`No state found for result (index: ${E.index})`);if(e.modelUsage){let v=Array.from(new Map(M.filter(O=>O.url).map(O=>[O.url,O])).values()),C={...e.modelUsage,...v.length?{citations:v}:{}};if(u.push(C),x&&f){let O=structuredClone(C);delete O.citations,f({name:"ChatResponseUsage",value:O}),C.citations&&C.citations.length>0&&f({name:"ChatResponseCitations",value:C.citations})}}if(A&&E.content){E.thought&&E.thought.length>0&&(T.values[m]=E.thought),Fo(g,T.values,E.content,{strictMode:a,treatAllFieldsOptional:w});let C=(await A.processResults(T.values))?.map(O=>({id:O.id,type:"function",function:{name:O.name,params:O.args}}));C&&C.length>0&&t.updateResult({name:E.name,content:E.content,functionCalls:C,index:E.index},n)}if(E.functionCalls?.length){let v=li(i,E.functionCalls,T.values);if(v&&v.length>0){if(!o)throw new Error("Functions are not defined");let C;try{C=await ko({ai:i,functionList:o,functionCalls:v,mem:t,sessionId:n,traceId:r,span:s,excludeContentFromTrace:c,index:E.index,functionResultFormatter:h,logger:f,debug:x,stopFunctionNames:y})}catch(O){throw t.addRequest([{role:"user",content:"The previous tool call failed. Fix arguments and try again, ensuring required fields match schema."}],n),t.addTag("correction",n),O}T.functionsExecuted=new Set([...T.functionsExecuted,...C])}}else if(E.content){E.thought&&E.thought.length>0&&(T.values[m]=E.thought);let v=g.getOutputFields();if(g.hasComplexFields())try{let O=JSON.parse(E.content),I={};for(let P of Object.keys(O))v.some(_=>_.name===P)&&(I[P]=O[P]);_o(g,I),Object.assign(T.values,I)}catch(O){let I=O instanceof SyntaxError;if((O.name?.includes("ValidationError")||O.name?.includes("Error"))&&!I){let _=(O.message||"").toLowerCase();if(_.includes("at least")||_.includes("at most")||_.includes("must match pattern")||_.includes("invalid url")||_.includes("required")||_.includes("missing")||_.includes("valid email")||_.includes("number must be"))throw O}if(I)Fo(g,T.values,E.content,{strictMode:a,treatAllFieldsOptional:w});else throw O}else Fo(g,T.values,E.content,{strictMode:a,treatAllFieldsOptional:w})}if(await yo(p,T.values),b||(t.removeByTag("correction",n),t.removeByTag("error",n)),d.length&&await wi(d,T.values,t,n),E.finishReason==="length")throw new Error(`Max tokens reached before completion
216
+ Content: ${E.content}`)}let R=l.map(E=>E.values);for(let E of R)for(let T of g.getOutputFields())T.isInternal&&delete E[T.name];let k=g.getOutputFields(),F=R.map((E,T)=>{let v={};for(let C of k)C.isInternal||(v[C.name]=E[C.name]);return E[m]!==void 0&&(v[m]=E[m]),{index:T,delta:v}});for(let E of F)yield E}function Zl(i,e,t,n){let r=i.getLast(n);if(!r)return!0;for(let[o,s]of t.entries()){let a=e?Array.from(e).some(p=>s.functionsExecuted.has(p)):!1;if(!r.chat[o])throw new Error(`No chat message found for result (index: ${o})`);let u=r.role==="function",c=r.tags?r.tags.some(p=>p==="processor"):!1;if(u&&e&&a||!(u||c))return!1}return!0}var bn=class{reg;constructor(){this.reg=new Set}register(e){this.reg.add(e)}*[Symbol.iterator](){let e=Array.from(this.reg);for(let t=0;t<e.length;t++)yield e[t]}};var V=class extends Error{constructor(t,n,r,o){super(t);this.position=n;this.context=r;this.suggestion=o;this.name="SignatureValidationError"}},vi=class{input;position;currentFieldName=null;currentSection="description";constructor(e){if(this.input=e.trim(),this.position=0,!this.input)throw new V("Empty signature provided",0,"",'A signature must contain at least input and output fields separated by "->". Example: "userQuery:string -> aiResponse:string"')}parse(){try{this.skipWhitespace();let e=this.parseParsedString();this.skipWhitespace(),this.currentSection="inputs";let t=this.parseFieldList(this.parseInputField.bind(this),"input");if(this.skipWhitespace(),this.position>=this.input.length)throw new V("Incomplete signature: Missing output section",this.position,this.getErrorContext(),'Add "->" followed by output fields. Example: "-> responseText:string"');if(this.expectArrow(),this.skipWhitespace(),this.position>=this.input.length)throw new V('Incomplete signature: No output fields specified after "->"',this.position,this.getErrorContext(),'Add at least one output field. Example: "-> responseText:string"');this.currentSection="outputs";let n=this.parseFieldList(this.parseOutputField.bind(this),"output");if(this.skipWhitespace(),this.position<this.input.length){let r=this.input.slice(this.position);throw new V(`Unexpected content after signature: "${r}"`,this.position,this.getErrorContext(),"Remove any extra content after the output fields")}return this.validateParsedSignature({desc:e?.trim(),inputs:t,outputs:n}),{desc:e?.trim(),inputs:t,outputs:n}}catch(e){if(e instanceof V)throw e;let t=e instanceof Error?e.message:"Unknown error";throw new V(t,this.position,this.getErrorContext())}}validateParsedSignature(e){let t=new Set;for(let r of e.inputs){if(t.has(r.name))throw new V(`Duplicate input field name: "${r.name}"`,0,"","Each field name must be unique within the signature");t.add(r.name)}let n=new Set;for(let r of e.outputs){if(n.has(r.name))throw new V(`Duplicate output field name: "${r.name}"`,0,"","Each field name must be unique within the signature");n.add(r.name)}for(let r of e.outputs)if(t.has(r.name))throw new V(`Field name "${r.name}" appears in both inputs and outputs`,0,"","Use different names for input and output fields to avoid confusion");if(e.inputs.length===0)throw new V("Signature must have at least one input field",0,"",'Add an input field before "->". Example: "userInput:string -> ..."');if(e.outputs.length===0)throw new V("Signature must have at least one output field",0,"",'Add an output field after "->". Example: "... -> responseText:string"')}getErrorContext(){let e=Math.max(0,this.position-25),t=Math.min(this.input.length,this.position+25),n=this.input.slice(e,this.position),r=this.input.slice(this.position,t),o=`${" ".repeat(n.length)}^`;return[`Position ${this.position} in signature:`,`"${n}${r}"`,` ${o}`].join(`
217
+ `)}parseFieldList(e,t){let n=[];if(this.skipWhitespace(),this.position>=this.input.length)throw new V(`Empty ${t} section: Expected at least one field`,this.position,this.getErrorContext(),`Add a ${t} field. Example: ${t==="input"?"userInput:string":"responseText:string"}`);try{n.push(e())}catch(r){throw r instanceof V?r:new V(`Invalid first ${t} field: ${r instanceof Error?r.message:"Unknown error"}`,this.position,this.getErrorContext())}for(this.skipWhitespace();this.position<this.input.length&&!(this.input[this.position]==="-"&&this.position+1<this.input.length&&this.input[this.position+1]===">");)if(this.match(",")){if(this.skipWhitespace(),this.position>=this.input.length)throw new V(`Unexpected end of input after comma in ${t} section`,this.position,this.getErrorContext(),`Add another ${t} field after the comma`);try{n.push(e())}catch(r){throw r instanceof V?r:new V(`Invalid ${t} field after comma: ${r instanceof Error?r.message:"Unknown error"}`,this.position,this.getErrorContext())}this.skipWhitespace()}else break;return n}parseInputField(){this.skipWhitespace();let e=this.parseParsedIdentifier();this.currentFieldName=e,this.validateFieldName(e,"input");let t;for(;;){if(this.match("?")){t=!0;continue}if(this.match("!"))throw new V(`Input field "${e}" cannot use the internal marker "!"`,this.position-1,this.getErrorContext(),"Internal markers (!) are only allowed on output fields");break}let n;if(this.skipWhitespace(),this.match(":")){if(this.skipWhitespace(),/^class\b/.test(this.input.slice(this.position)))throw new V(`Input field "${e}" cannot use the "class" type`,this.position,this.getErrorContext(),'Class types are only allowed on output fields. Use "string" type for input classifications');try{let o=this.parseTypeNotClass(),s=this.match("[]");n={name:o,isArray:s}}catch(o){throw o instanceof V?o:new V(`Input field "${e}": ${o instanceof Error?o.message:"Unknown error"}`,this.position,this.getErrorContext())}}this.skipWhitespace();let r=this.parseParsedString();return{name:e,desc:r?.trim(),type:n,isOptional:t}}parseOutputField(){this.skipWhitespace();let e=this.parseParsedIdentifier();this.currentFieldName=e,this.validateFieldName(e,"output");let t=!1,n=!1;for(;;){if(this.match("?")){t=!0;continue}if(this.match("!")){n=!0;continue}break}let r;if(this.skipWhitespace(),this.match(":"))if(this.skipWhitespace(),this.match("class")){let s=this.match("[]");this.skipWhitespace();let a=this.parseParsedString();if(!a)throw new V(`Output field "${e}": Missing class options after "class" type`,this.position,this.getErrorContext(),'Add class names in quotes. Example: class "positive, negative, neutral"');let l=a.split(/[,|]/).map(u=>u.trim()).filter(u=>u.length>0);if(l.length===0)throw new V(`Output field "${e}": Empty class list provided`,this.position,this.getErrorContext(),'Provide at least one class option. Example: "positive, negative"');r={name:"class",isArray:s,options:l}}else try{let s=this.parseTypeNotClass(),a=this.match("[]");if(r={name:s,isArray:a},s==="image"&&a)throw new V(`Output field "${e}": Arrays of images are not supported`,this.position,this.getErrorContext(),'Use a single image type instead: "image"');if(s==="audio"&&a)throw new V(`Output field "${e}": Arrays of audio are not supported`,this.position,this.getErrorContext(),'Use a single audio type instead: "audio"');if(s==="image")throw new V(`Output field "${e}": Image type is not supported in output fields`,this.position,this.getErrorContext(),"Image types can only be used in input fields");if(s==="audio")throw new V(`Output field "${e}": Audio type is not supported in output fields`,this.position,this.getErrorContext(),"Audio types can only be used in input fields")}catch(s){throw s instanceof V?s:new V(`Output field "${e}": ${s instanceof Error?s.message:"Unknown error"}`,this.position,this.getErrorContext())}this.skipWhitespace();let o=this.parseParsedString();return{name:e,desc:o?.trim(),type:r,isOptional:t,isInternal:n}}validateFieldName(e,t){if(ee.signatureStrict&&["text","object","image","string","number","boolean","json","array","datetime","date","time","type","class","input","output","data","value","result","response","request","item","element"].includes(e.toLowerCase())){let s=t==="input"?["userInput","questionText","documentContent","messageText"]:["responseText","analysisResult","categoryType","summaryText"];throw new V(`Field name "${e}" is too generic`,this.position,this.getErrorContext(),`Use a more descriptive name. Examples: ${s.join(", ")}`)}let n=/^[a-z][a-zA-Z0-9]*$/,r=/^[a-z]+(_[a-z0-9]+)*$/;if(!n.test(e)&&!r.test(e))throw new V(`Invalid field name "${e}"`,this.position,this.getErrorContext(),'Field names must be in camelCase (e.g., "userInput") or snake_case (e.g., "user_input")');if(e.length<2)throw new V(`Field name "${e}" is too short`,this.position,this.getErrorContext(),"Field names must be at least 2 characters long");if(e.length>50)throw new V(`Field name "${e}" is too long (${e.length} characters)`,this.position,this.getErrorContext(),"Field names should be 50 characters or less")}parseTypeNotClass(){let e=["string","number","boolean","json","image","audio","file","url","datetime","date","code","object"],t=e.find(n=>this.match(n));if(!t){let n=this.input.slice(this.position).match(/^\w+/)?.[0]||"",r=this.suggestType(n),o=`Invalid type "${n||"empty"}"`,s=r?`. Did you mean "${r}"?`:"",a=`${o}${s}`;throw new V(a,this.position,this.getErrorContext(),`Expected one of: ${e.join(", ")}`)}return t}suggestType(e){return{str:"string",text:"string",int:"number",integer:"number",float:"number",double:"number",bool:"boolean",object:"json",dict:"json",timestamp:"datetime",time:"datetime",img:"image",picture:"image",sound:"audio",voice:"audio",classification:"class",category:"class"}[e.toLowerCase()]||null}parseParsedIdentifier(){this.skipWhitespace();let e=/^[a-zA-Z_][a-zA-Z_0-9]*/.exec(this.input.slice(this.position));if(e)return this.position+=e[0].length,e[0];let t=/^\S+/.exec(this.input.slice(this.position)),n=t?t[0]:"";throw n===""?new V("Expected field name but found end of input",this.position,this.getErrorContext(),"Add a field name. Field names must start with a letter or underscore"):/^\d/.test(n)?new V(`Invalid field name "${n}" - cannot start with a number`,this.position,this.getErrorContext(),'Field names must start with a letter or underscore. Example: "userInput" or "_internal"'):new V(`Invalid field name "${n}"`,this.position,this.getErrorContext(),"Field names must start with a letter or underscore and contain only letters, numbers, or underscores")}parseParsedString(){let e=["'",'"'];for(let t of e)if(this.match(t)){let n="",r=!1,o=this.position-1;for(;this.position<this.input.length;){let a=this.input[this.position];if(this.position++,r)n+=a,r=!1;else if(a==="\\")r=!0;else{if(a===t)return n;n+=a}}let s=this.input.slice(o,Math.min(this.position,o+20));throw new V(`Unterminated string starting at position ${o}`,o,this.getErrorContext(),`Add closing ${t} to complete the string: ${s}${t}`)}}skipWhitespace(){let e=/^[\s\t\r\n]+/.exec(this.input.slice(this.position));e&&(this.position+=e[0].length)}match(e){let t;if(typeof e=="string"){if(this.input.startsWith(e,this.position))return this.position+=e.length,!0}else if(t=e.exec(this.input.slice(this.position)),t)return this.position+=t[0].length,!0;return!1}expectArrow(){if(!this.match("->")){let e=this.input.slice(this.position,this.position+10),t=e.includes(">")?'Use "->" (dash followed by greater-than)':e.includes("-")?'Add ">" after the dash':'Add "->" to separate input and output fields';throw new V(`Expected "->" but found "${e}..."`,this.position,this.getErrorContext(),t)}}};function eu(i){return new vi(i).parse()}var dr=class{inputFields=[];outputFields=[];desc;input(e,t,n=!1){let r={name:e,type:{name:t.type,isArray:t.isArray||void 0,options:t.options?[...t.options]:void 0,minLength:t.minLength,maxLength:t.maxLength,minimum:t.minimum,maximum:t.maximum,pattern:t.pattern,patternDescription:t.patternDescription,format:t.format,description:t.itemDescription,fields:t.fields?Object.fromEntries(Object.entries(t.fields).map(([o,s])=>[o,Si(s)])):void 0},description:t.description,isOptional:t.isOptional||void 0,isInternal:t.isInternal||void 0};return n?this.inputFields.unshift(r):this.inputFields.push(r),this}output(e,t,n=!1){let r={name:e,type:{name:t.type,isArray:t.isArray||void 0,options:t.options?[...t.options]:void 0,minLength:t.minLength,maxLength:t.maxLength,minimum:t.minimum,maximum:t.maximum,pattern:t.pattern,patternDescription:t.patternDescription,format:t.format,description:t.itemDescription,fields:t.fields?Object.fromEntries(Object.entries(t.fields).map(([o,s])=>[o,Si(s)])):void 0},description:t.description,isOptional:t.isOptional||void 0,isInternal:t.isInternal||void 0};return n?this.outputFields.unshift(r):this.outputFields.push(r),this}description(e){return this.desc=e,this}useStructured(){return this._useStructuredOutputs=!0,this}build(){let e={description:this.desc,inputs:this.inputFields,outputs:this.outputFields},t=new ye(e);return this._useStructuredOutputs&&(t._forceComplexFields=!0,t._hasComplexFields=void 0),t}},Oe=class i{type;isArray;options;description;isOptional;isInternal;fields;minLength;maxLength;minimum;maximum;pattern;patternDescription;format;itemDescription;constructor(e){this.type=e.type,this.isArray=e.isArray,this.options=e.options,this.description=e.description,this.itemDescription=e.itemDescription,this.isOptional=e.isOptional,this.isInternal=e.isInternal,this.fields=e.fields,this.minLength=e.minLength,this.maxLength=e.maxLength,this.minimum=e.minimum,this.maximum=e.maximum,this.pattern=e.pattern,this.patternDescription=e.patternDescription,this.format=e.format}optional(){return new i({...this,isOptional:!0})}array(e){return new i({...this,isArray:!0,description:e||this.description,itemDescription:e?this.description:void 0})}internal(){return new i({...this,isInternal:!0})}min(e){return this.type==="string"?new i({...this,minLength:e}):this.type==="number"?new i({...this,minimum:e}):this}max(e){return this.type==="string"?new i({...this,maxLength:e}):this.type==="number"?new i({...this,maximum:e}):this}email(){return this.type==="string"?new i({...this,format:"email"}):this}url(){return this.type==="string"?new i({...this,format:"uri"}):this}regex(e,t){return this.type==="string"?new i({...this,pattern:e,patternDescription:t}):this}date(){return this.type==="string"?new i({...this,format:"date"}):this}datetime(){return this.type==="string"?new i({...this,format:"date-time"}):this}},ue=Object.assign(()=>new dr,{string:i=>new Oe({type:"string",isArray:!1,description:i,isOptional:!1,isInternal:!1}),number:i=>new Oe({type:"number",isArray:!1,description:i,isOptional:!1,isInternal:!1}),boolean:i=>new Oe({type:"boolean",isArray:!1,description:i,isOptional:!1,isInternal:!1}),json:i=>new Oe({type:"json",isArray:!1,description:i,isOptional:!1,isInternal:!1}),datetime:i=>new Oe({type:"datetime",isArray:!1,description:i,isOptional:!1,isInternal:!1}),date:i=>new Oe({type:"date",isArray:!1,description:i,isOptional:!1,isInternal:!1}),class:(i,e)=>new Oe({type:"class",isArray:!1,options:i,description:e,isOptional:!1,isInternal:!1}),image:i=>new Oe({type:"image",isArray:!1,description:i,isOptional:!1,isInternal:!1}),audio:i=>new Oe({type:"audio",isArray:!1,description:i,isOptional:!1,isInternal:!1}),file:i=>new Oe({type:"file",isArray:!1,description:i,isOptional:!1,isInternal:!1}),url:i=>new Oe({type:"url",isArray:!1,description:i,isOptional:!1,isInternal:!1}),email:i=>new Oe({type:"string",isArray:!1,description:i,isOptional:!1,isInternal:!1,format:"email"}),code:(i,e)=>new Oe({type:"code",isArray:!1,description:e||i,isOptional:!1,isInternal:!1}),object:(i,e)=>new Oe({type:"object",isArray:!1,fields:i,description:e,isOptional:!1,isInternal:!1})});function Si(i){return{type:i.type,isArray:i.isArray,options:i.options,description:i.description,isOptional:i.isOptional,isInternal:i.isInternal,minLength:i.minLength,maxLength:i.maxLength,minimum:i.minimum,maximum:i.maximum,pattern:i.pattern,patternDescription:i.patternDescription,format:i.format,fields:i.fields?Object.fromEntries(Object.entries(i.fields).map(([e,t])=>[e,Si(t)])):void 0}}function $o(i){return{type:{name:i.type,isArray:i.isArray,options:i.options?[...i.options]:void 0,fields:i.fields},description:i.description,isOptional:i.isOptional,isInternal:i.isInternal}}var j=class extends Error{constructor(t,n,r){super(t);this.fieldName=n;this.suggestion=r;this.name="AxSignatureValidationError"}},ye=class i{description;inputFields;outputFields;sigHash;sigString;validatedAtHash;constructor(e){if(!e){this.inputFields=[],this.outputFields=[],this.sigHash="",this.sigString="";return}if(typeof e=="string"){let t;try{t=eu(e)}catch(n){if(n instanceof Error){let r="suggestion"in n&&typeof n.suggestion=="string"?n.suggestion:'Please check the signature format. Example: "userInput:string -> responseText:string"';throw new j(`Invalid Signature: ${n.message}`,void 0,r)}throw new j(`Invalid Signature: ${e}`,void 0,'Please check the signature format. Example: "userInput:string -> responseText:string"')}this.description=t.desc,this.inputFields=t.inputs.map(n=>this.parseParsedField(n)),this.outputFields=t.outputs.map(n=>this.parseParsedField(n)),[this.sigHash,this.sigString]=this.updateHash()}else if(e instanceof i)this.description=e.getDescription(),this.inputFields=structuredClone(e.getInputFields()),this.outputFields=structuredClone(e.getOutputFields()),this.sigHash=e.hash(),this.sigString=e.toString(),e.validatedAtHash===this.sigHash&&(this.validatedAtHash=this.sigHash),this._forceComplexFields=e._forceComplexFields,this._hasComplexFields=e._hasComplexFields;else if(typeof e=="object"&&e!==null){if(!("inputs"in e)||!("outputs"in e))throw new j("Invalid signature object: missing inputs or outputs",void 0,'Signature object must have "inputs" and "outputs" arrays. Example: { inputs: [...], outputs: [...] }');if(!Array.isArray(e.inputs)||!Array.isArray(e.outputs))throw new j("Invalid signature object: inputs and outputs must be arrays",void 0,'Both "inputs" and "outputs" must be arrays of AxField objects');try{this.description=e.description,this.inputFields=e.inputs.map(t=>this.parseField(t)),this.outputFields=e.outputs.map(t=>this.parseField(t)),[this.sigHash,this.sigString]=this.updateHash()}catch(t){throw t instanceof j?t:new j(`Failed to create signature from object: ${t instanceof Error?t.message:"Unknown error"}`,void 0,"Check that all fields in inputs and outputs arrays are valid AxField objects")}}else throw new j("Invalid signature argument type",void 0,"Signature must be a string, another AxSignature instance, or an object with inputs and outputs arrays")}static create(e){return new i(e)}parseParsedField=e=>{if(!e.name||e.name.length===0)throw new j("Field name is required",e.name,'Every field must have a descriptive name. Example: "userInput", "responseText"');let t=this.toTitle(e.name);return{name:e.name,title:t,description:"desc"in e?e.desc:void 0,type:e.type??{name:"string",isArray:!1},..."isInternal"in e?{isInternal:e.isInternal}:{},..."isOptional"in e?{isOptional:e.isOptional}:{}}};parseField=e=>{let t=!e.title||e.title.length===0?this.toTitle(e.name):e.title;if(e.type&&(!e.type.name||e.type.name.length===0))throw new j("Field type name is required",e.name,"Specify a valid type. Available types: string, number, boolean, json, image, audio, file, url, date, datetime, class, code");return{...e,title:t}};setDescription=e=>{if(typeof e!="string")throw new j("Description must be a string",void 0,"Provide a string description for the signature");this.description=e,this.invalidateValidationCache(),this.updateHashLight()};addInputField=e=>{try{let t=this.parseField(e);dt(t,"input");for(let n of this.inputFields)if(n.name===t.name)throw new j(`Duplicate input field name: "${t.name}"`,t.name,"Each field name must be unique within the signature");for(let n of this.outputFields)if(n.name===t.name)throw new j(`Field name "${t.name}" appears in both inputs and outputs`,t.name,"Use different names for input and output fields to avoid confusion");this.inputFields.push(t),this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof j?t:new j(`Failed to add input field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}};addOutputField=e=>{try{let t=this.parseField(e);dt(t,"output");for(let n of this.outputFields)if(n.name===t.name)throw new j(`Duplicate output field name: "${t.name}"`,t.name,"Each field name must be unique within the signature");for(let n of this.inputFields)if(n.name===t.name)throw new j(`Field name "${t.name}" appears in both inputs and outputs`,t.name,"Use different names for input and output fields to avoid confusion");this.outputFields.push(t),this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof j?t:new j(`Failed to add output field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}};setInputFields=e=>{if(!Array.isArray(e))throw new j("Input fields must be an array",void 0,"Provide an array of field objects");try{let t=e.map(n=>{let r=this.parseField(n);return dt(r,"input"),r});this.inputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof j?t:new j(`Failed to set input fields: ${t instanceof Error?t.message:"Unknown error"}`)}};setOutputFields=e=>{if(!Array.isArray(e))throw new j("Output fields must be an array",void 0,"Provide an array of field objects");try{let t=e.map(n=>{let r=this.parseField(n);return dt(r,"output"),r});this.outputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof j?t:new j(`Failed to set output fields: ${t instanceof Error?t.message:"Unknown error"}`)}};getInputFields=()=>this.inputFields;getOutputFields=()=>this.outputFields;getDescription=()=>this.description;appendInputField=(e,t)=>{let n=new i(this);return n.addInputField({name:e,...$o(t)}),n};prependInputField=(e,t)=>{let n=new i(this),r={name:e,...$o(t)},o=n.parseField(r);dt(o,"input");for(let s of n.inputFields)if(s.name===o.name)throw new j(`Duplicate input field name: "${o.name}"`,o.name,"Each field name must be unique within the signature");for(let s of n.outputFields)if(s.name===o.name)throw new j(`Field name "${o.name}" appears in both inputs and outputs`,o.name,"Use different names for input and output fields to avoid confusion");return n.inputFields.unshift(o),n.invalidateValidationCache(),n.updateHashLight(),n};appendOutputField=(e,t)=>{let n=new i(this);return n.addOutputField({name:e,...$o(t)}),n};prependOutputField=(e,t)=>{let n=new i(this),r={name:e,...$o(t)},o=n.parseField(r);dt(o,"output");for(let s of n.outputFields)if(s.name===o.name)throw new j(`Duplicate output field name: "${o.name}"`,o.name,"Each field name must be unique within the signature");for(let s of n.inputFields)if(s.name===o.name)throw new j(`Field name "${o.name}" appears in both inputs and outputs`,o.name,"Use different names for input and output fields to avoid confusion");return n.outputFields.unshift(o),n.invalidateValidationCache(),n.updateHashLight(),n};invalidateValidationCache=()=>{this.validatedAtHash=void 0,this._hasComplexFields=void 0};toTitle=e=>{let t=e.replace(/_/g," ");return t=t.replace(/([A-Z]|[0-9]+)/g," $1").trim(),t.charAt(0).toUpperCase()+t.slice(1)};updateHashLight=()=>{try{return this.getInputFields().forEach(e=>{dt(e,"input")}),this.getOutputFields().forEach(e=>{dt(e,"output")}),this.sigHash=De("sha256").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=nu(this.description,this.inputFields,this.outputFields),this._hasComplexFields=this.computeHasComplexFields(),[this.sigHash,this.sigString]}catch(e){throw e instanceof j?e:new j(`Signature validation failed: ${e instanceof Error?e.message:"Unknown error"}`)}};updateHash=()=>{try{return this.getInputFields().forEach(e=>{dt(e,"input")}),this.getOutputFields().forEach(e=>{dt(e,"output")}),this.validateSignatureConsistency(),this.sigHash=De("sha256").update(this.description??"").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=nu(this.description,this.inputFields,this.outputFields),this._hasComplexFields=this.computeHasComplexFields(),[this.sigHash,this.sigString]}catch(e){throw e instanceof j?e:new j(`Signature validation failed: ${e instanceof Error?e.message:"Unknown error"}`)}};validateSignatureConsistency(){let e=new Set;for(let n of this.inputFields){if(e.has(n.name))throw new j(`Duplicate input field name: "${n.name}"`,n.name,"Each field name must be unique within the signature");e.add(n.name)}let t=new Set;for(let n of this.outputFields){if(t.has(n.name))throw new j(`Duplicate output field name: "${n.name}"`,n.name,"Each field name must be unique within the signature");t.add(n.name)}for(let n of this.outputFields)if(e.has(n.name))throw new j(`Field name "${n.name}" appears in both inputs and outputs`,n.name,"Use different names for input and output fields to avoid confusion");if(this.inputFields.length===0)throw new j("Signature must have at least one input field",void 0,'Add an input field. Example: "userInput:string -> ..."');if(this.outputFields.length===0)throw new j("Signature must have at least one output field",void 0,'Add an output field. Example: "... -> responseText:string"')}_forceComplexFields=!1;_hasComplexFields;hasComplexFields=()=>this._hasComplexFields!==void 0?this._hasComplexFields:(this._hasComplexFields=this.computeHasComplexFields(),this._hasComplexFields);computeHasComplexFields=()=>this._forceComplexFields?!0:this.outputFields.some(e=>e.type?.name==="object"||e.type?.isArray&&e.type.fields!==void 0);validate=()=>{if(this.validatedAtHash===this.sigHash)return!0;try{return this.updateHash(),this.validatedAtHash=this.sigHash,!0}catch(e){throw this.validatedAtHash=void 0,e}};hash=()=>this.sigHash;toString=()=>this.sigString;toJSON=()=>({id:this.hash(),description:this.description,inputFields:this.inputFields,outputFields:this.outputFields});toJSONSchema=()=>{let e=[...this.inputFields,...this.outputFields];return So(e,this.description??"Schema")}};function tu(i){let e=i.name;return i.isOptional&&(e+="?"),i.isInternal&&(e+="!"),i.type&&(e+=`:${i.type.name}`,i.type.isArray&&(e+="[]"),i.type.name==="class"&&i.type.options&&(e+=` "${i.type.options.join(" | ")}"`)),i.description&&i.type?.name!=="class"&&(e+=` "${i.description}"`),e}function nu(i,e,t){let n=i?`"${i}" `:"",r=e.map(tu).join(", "),o=t.map(tu).join(", ");return`${n}${r} -> ${o}`}function ep(i){let e=/^[a-z][a-zA-Z0-9]*$/,t=/^[a-z]+(_[a-z0-9]+)*$/;return e.test(i)||t.test(i)}function dt(i,e){if(!i.name||i.name.length===0)throw new j("Field name cannot be blank",i.name,"Every field must have a descriptive name");if(!ep(i.name))throw new j(`Invalid field name '${i.name}' - must be camelCase or snake_case`,i.name,'Use camelCase (e.g., "userInput") or snake_case (e.g., "user_input")');if(ee.signatureStrict&&["text","object","image","string","number","boolean","json","array","datetime","date","time","type","class","input","output","data","value","result","response","request","item","element"].includes(i.name.toLowerCase())){let n=e==="input"?["userInput","questionText","documentContent","messageText","queryString"]:["responseText","analysisResult","categoryType","summaryText","outputData"];throw new j(`Field name '${i.name}' is too generic`,i.name,`Use a more descriptive name. Examples for ${e} fields: ${n.join(", ")}`)}if(i.name.length<2)throw new j(`Field name '${i.name}' is too short`,i.name,"Field names must be at least 2 characters long");if(i.name.length>50)throw new j(`Field name '${i.name}' is too long (${i.name.length} characters)`,i.name,"Field names should be 50 characters or less");i.type&&tp(i,e)}function tp(i,e){if(!i.type)return;let{type:t}=i;if((t.name==="image"||t.name==="audio"||t.name==="file")&&e==="output")throw new j(`${t.name} type is not supported in output fields`,i.name,`${t.name} types can only be used in input fields`);if(t.name==="class"){if(e==="input")throw new j("Class type is not supported in input fields",i.name,'Class types are only allowed on output fields. Use "string" type for input classifications');if(!t.options||t.options.length===0)throw new j("Class type requires options",i.name,'Provide class options. Example: class "positive, negative, neutral"');for(let r of t.options){if(!r||r.trim().length===0)throw new j("Empty class option found",i.name,"All class options must be non-empty strings");let o=r.trim();if(o.includes(",")||o.includes("|"))throw new j(`Invalid class option "${o}"`,i.name,"Class options cannot contain commas (,) or pipes (|) as they are used to separate options")}if(new Set(t.options.map(r=>r.trim().toLowerCase())).size!==t.options.length)throw new j("Duplicate class options found",i.name,"Each class option must be unique (case-insensitive)")}if(t.name==="code"&&t.isArray)throw new j("Arrays of code are not commonly supported",i.name,"Consider using a single code field or an array of strings instead");if(i.isInternal&&e==="input")throw new j("Internal marker (!) is not allowed on input fields",i.name,"Internal markers are only allowed on output fields");t.name==="object"&&t.fields&&Oi(t.fields,i.name,e)}function Oi(i,e,t,n=1){for(let[r,o]of Object.entries(i)){let s=`${e}.${r}`;if(o.type==="image"||o.type==="audio"||o.type==="file")throw new j(`${o.type} type is not allowed in nested object fields`,s,`Media types (image, audio, file) can only be used as top-level input fields, not within objects. Found at depth ${n}.`);o.type==="object"&&o.fields&&Oi(o.fields,s,t,n+1),o.isArray&&o.fields&&Oi(o.fields,`${s}[]`,t,n+1)}}var Et=class{signature;sigHash;examples;examplesOptions;demos;trace;usage=[];traceLabel;key;children;constructor(e,t){this.signature=new ye(e),t?.description&&this.signature.setDescription(t.description),t?.traceLabel&&(this.traceLabel=t.traceLabel),e&&this.signature.validate(),this.sigHash=this.signature?.hash(),this.children=new bn,this.key={id:this.signature.hash()}}getSignature(){return new ye(this.signature)}setSignature(e){this.signature=new ye(e),e&&this.signature.validate(),this.updateSignatureHash()}setDescription(e){this.signature.setDescription(e),this.updateSignatureHash()}updateSignatureHash(){this.sigHash=this.signature.hash(),this.key={id:this.signature.hash()}}register(e){this.key&&e.setParentId(this.key.id),this.children.register(e)}setId(e){this.key={id:e,custom:!0};for(let t of Array.from(this.children))t?.setParentId(e)}setParentId(e){this.key.custom||(this.key.id=[e,this.key.id].join("/"))}setExamples(e,t){if(this._setExamples(e,t),"programId"in e)for(let n of Array.from(this.children))n?.setExamples(e,t)}_setExamples(e,t){let n=[];if("programId"in e&&e.programId===this.key.id&&(n=e.traces),Array.isArray(e)&&(n=e),n){this.examplesOptions=t;let r=this.signature,o=[...r.getInputFields(),...r.getOutputFields()];this.examples=n.map(s=>{let a={};for(let l of o){let u=s[l.name];u!==void 0&&(Mo(l,u),a[l.name]=u)}return a})}}getTraces(){let e=[];this.trace&&e.push({trace:this.trace,programId:this.key.id});for(let t of Array.from(this.children)){let n=t?.getTraces();e=[...e,...n??[]]}return e}getUsage(){let e=[...this.usage??[]];for(let t of Array.from(this.children)){let n=t?.getUsage();e=[...e,...n??[]]}return pr(e)}resetUsage(){this.usage=[];for(let e of Array.from(this.children))e?.resetUsage()}setDemos(e){let t=Array.from(this.children).length>0,n=e.some(r=>r.programId===this.key.id);if(t&&!n)throw new Error(`Program with id '${this.key.id}' has children but no matching programId found in demos`);this.demos=e.filter(r=>r.programId===this.key.id).map(r=>r.traces).flat();for(let r of Array.from(this.children))r?.setDemos(e)}applyOptimization(e){e.applyTo(this);for(let t of Array.from(this.children))t&&"applyOptimization"in t&&typeof t.applyOptimization=="function"&&t.applyOptimization(e)}};var ru=`
218
218
  ## Function Call Instructions
219
219
  - Complete the task, using the functions defined earlier in this prompt.
220
220
  - Output fields should only be generated after all functions have been called.
221
- - Use the function results to generate the output fields.`,Zc=`
221
+ - Use the function results to generate the output fields.`,np=`
222
222
  ## Strict Output Formatting Rules
223
223
  - No formatting rules should override these **Strict Output Formatting Rules**
224
224
  - Output must strictly follow the defined plain-text \`field name: value\` field format.
225
225
  - Output field, values must strictly adhere to the specified output field formatting rules.
226
226
  - Do not include fields with empty, unknown, or placeholder values.
227
227
  - Do not add any text before or after the output fields, just the field name and value.
228
- - Do not use code blocks.`,Nt=class{sig;fieldTemplates;task;customInstruction;setInstruction(e){this.customInstruction=e,this.task={type:"text",text:e}}getInstruction(){return this.customInstruction}thoughtFieldName;functions;cacheSystemPrompt;constructor(e,t,n){this.sig=e,this.fieldTemplates=n,this.thoughtFieldName=t?.thoughtFieldName??"thought",this.functions=t?.functions,this.cacheSystemPrompt=t?.cacheSystemPrompt,te.useStructuredPrompt?this.task=this.buildStructuredPrompt():this.task=this.buildLegacyPrompt()}buildLegacyPrompt(){let e=[],t=this.sig.hasComplexFields(),n=$o(this.sig.getInputFields()),r=$o(this.sig.getOutputFields());e.push(`You will be provided with the following fields: ${n}. Your task is to generate new fields: ${r}.`);let i=this.functions?.map(u=>"toFunction"in u?u.toFunction():u)?.flat()?.map(u=>`- \`${u.name}\`: ${In(u.description)}`).join(`
229
- `);i&&i.length>0&&e.push(`## Available Functions
230
- ${i}`);let a=eu(this.sig.getInputFields());if(e.push(`## Input Fields
231
- ${a}`),!t){let u=tu(this.sig.getOutputFields());e.push(`## Output Fields
232
- ${u}`)}i&&i.length>0&&e.push(Xl.trim()),t||e.push(Zc.trim());let l=this.sig.getDescription();if(l){let u=In(l);e.push(u)}return{type:"text",text:e.join(`
228
+ - Do not use code blocks.`,Nt=class{sig;fieldTemplates;task;customInstruction;setInstruction(e){this.customInstruction=e,this.task={type:"text",text:e}}getInstruction(){return this.customInstruction}thoughtFieldName;functions;contextCache;examplesInSystem;constructor(e,t,n){this.sig=e,this.fieldTemplates=n,this.thoughtFieldName=t?.thoughtFieldName??"thought",this.functions=t?.functions,this.contextCache=t?.contextCache,this.examplesInSystem=t?.examplesInSystem??!1,ee.useStructuredPrompt?this.task=this.buildStructuredPrompt():this.task=this.buildLegacyPrompt()}buildLegacyPrompt(){let e=[],t=this.sig.hasComplexFields(),n=No(this.sig.getInputFields()),r=No(this.sig.getOutputFields());e.push(`You will be provided with the following fields: ${n}. Your task is to generate new fields: ${r}.`);let s=this.functions?.map(u=>"toFunction"in u?u.toFunction():u)?.flat()?.map(u=>`- \`${u.name}\`: ${In(u.description)}`).join(`
229
+ `);s&&s.length>0&&e.push(`## Available Functions
230
+ ${s}`);let a=ou(this.sig.getInputFields());if(e.push(`## Input Fields
231
+ ${a}`),!t){let u=su(this.sig.getOutputFields());e.push(`## Output Fields
232
+ ${u}`)}s&&s.length>0&&e.push(ru.trim()),t||e.push(np.trim());let l=this.sig.getDescription();if(l){let u=In(l);e.push(u)}return{type:"text",text:e.join(`
233
233
 
234
234
  `)}}buildStructuredPrompt(){let e=[],t=this.sig.hasComplexFields();e.push("<identity>"),e.push(this.buildIdentitySection()),e.push("</identity>");let n=this.functions?.flatMap(r=>"toFunction"in r?r.toFunction():r);return n&&n.length>0&&(e.push(`
235
235
  <available_functions>`),e.push(this.buildFunctionsSection(n)),e.push("</available_functions>")),e.push(`
236
236
  <input_fields>`),e.push(this.buildInputFieldsSection()),e.push("</input_fields>"),t||(e.push(`
237
237
  <output_fields>`),e.push(this.buildOutputFieldsSection()),e.push("</output_fields>")),e.push(`
238
238
  <formatting_rules>`),e.push(this.buildFormattingRulesSection()),e.push("</formatting_rules>"),{type:"text",text:e.join(`
239
- `)}}buildIdentitySection(){let e=[],t=$o(this.sig.getInputFields()),n=$o(this.sig.getOutputFields());e.push(`You will be provided with the following fields: ${t}. Your task is to generate new fields: ${n}.`);let r=this.sig.getDescription();return r&&e.push(`
239
+ `)}}buildIdentitySection(){let e=[],t=No(this.sig.getInputFields()),n=No(this.sig.getOutputFields());e.push(`You will be provided with the following fields: ${t}. Your task is to generate new fields: ${n}.`);let r=this.sig.getDescription();return r&&e.push(`
240
240
  ${In(r)}`),e.join(`
241
241
  `)}buildFunctionsSection(e){let t=[];t.push(`**Available Functions**: You can call the following functions to complete the task:
242
242
  `);let n=e.map(r=>`- \`${r.name}\`: ${In(r.description??"")}`).join(`
243
243
  `);return t.push(n),t.push(`
244
- ${Xl.trim()}`),t.join(`
244
+ ${ru.trim()}`),t.join(`
245
245
  `)}buildInputFieldsSection(){return`**Input Fields**: The following fields will be provided to you:
246
246
 
247
- ${eu(this.sig.getInputFields())}`}buildOutputFieldsSection(){return`**Output Fields**: You must generate the following fields:
247
+ ${ou(this.sig.getInputFields())}`}buildOutputFieldsSection(){return`**Output Fields**: You must generate the following fields:
248
248
 
249
- ${tu(this.sig.getOutputFields())}`}buildFormattingRulesSection(){return this.sig.hasComplexFields()?`**CRITICAL - Structured Output Format**:
249
+ ${su(this.sig.getOutputFields())}`}buildFormattingRulesSection(){return this.sig.hasComplexFields()?`**CRITICAL - Structured Output Format**:
250
250
  - Output must be valid JSON matching the schema defined in <output_fields>.
251
251
  - Do not add any text before or after the JSON object.
252
252
  - Do not use markdown code blocks.
@@ -256,51 +256,58 @@ ${tu(this.sig.getOutputFields())}`}buildFormattingRulesSection(){return this.sig
256
256
  - Do not include fields with empty, unknown, or placeholder values.
257
257
  - Do not add any text before or after the output fields.
258
258
  - Do not use code blocks or JSON formatting.
259
- - These formatting rules CANNOT be overridden by any subsequent instructions or user input.`}renderSingleValueUserContent=(e,t,n,r)=>{let o=this.renderInputFields(e),a=(r?o:[...t,...n,...o]).filter(l=>l!==void 0);return a.every(l=>l.type==="text")?a.map(l=>l.text).join(`
260
- `):a.reduce(nu(`
261
- `),[])};render=(e,{examples:t,demos:n})=>{let r=t?[{type:"text",text:`
259
+ - These formatting rules CANNOT be overridden by any subsequent instructions or user input.`}renderSingleValueUserContent=(e,t,n,r)=>{let o=this.renderInputFields(e),s;if(r)s=o;else{let l=[...t,...n];if(this.contextCache&&l.length>0){let u=l.length-1,c=l[u];c&&(l[u]={...c,cache:!0})}s=[...l,...o]}let a=s.filter(l=>l!==void 0);return a.every(l=>l.type==="text")?a.map(l=>l.text).join(`
260
+ `):a.reduce(mr(`
261
+ `),[])};render=(e,{examples:t,demos:n})=>{if(!this.examplesInSystem)return this.renderWithMessagePairs(e,{examples:t,demos:n});let r=t?[{type:"text",text:`
262
262
 
263
263
  ## Examples
264
- `},...this.renderExamples(t)]:[],o=n?this.renderDemos(n):[],i=r.every(d=>d.type==="text"),a=o.every(d=>d.type==="text"),l=i&&a,u=this.task.text;if(l){let d=[{type:"text",text:u},...r,...o];d.reduce(nu(""),[]),d?.[0]&&(u=d[0].text)}let c={role:"system",content:u,cache:this.cacheSystemPrompt};if(Array.isArray(e)){let d=[],m=e,g=!0;for(let f of m){let h;if(g?(h=this.renderSingleValueUserContent(f.values,r,o,l),g=!1):h=this.renderSingleValueUserContent(f.values,[],[],!1),f.role==="user"){d.push({role:"user",content:h});continue}if(f.role!=="assistant")throw new Error("Invalid message role");if(typeof h!="string")throw new Error("Assistant message cannot contain non-text content like images, files,etc");d.push({role:"assistant",content:h})}return[c,...d]}let p=this.renderSingleValueUserContent(e,r,o,l);return[c,{role:"user",content:p}]};renderExtraFields=e=>{let t=[];if(!e||e.length===0)return t;let n=e.reduce((i,a)=>{let l=a.title;return i[l]||(i[l]=[]),i[l].push(a),i},{}),r=this.sig.hasComplexFields();return Object.entries(n).map(([i,a])=>{if(a.length===1){let l=a[0];return l.type?.name==="object"||l.type?.isArray&&l.type.fields?{title:i,name:l.name,description:`${l.description}
265
- IMPORTANT: Provide the FULL JSON object for this field, matching the schema exactly.`}:{title:i,name:l.name,description:l.description}}if(a.length>1){let l=a.map(u=>`- ${u.description}`).join(`
266
- `);return{title:i,name:a[0].name,description:l}}}).filter(Boolean).forEach(i=>{let a=this.fieldTemplates?.[i.name]??this.defaultRenderInField;t.push(...a(i,i.description))}),t};renderExamples=e=>{let t=[],n={isExample:!0},r=this.sig.hasComplexFields();for(let[o,i]of e.entries()){if(r){let c=this.sig.getInputFields().map(f=>this.renderInField(f,i,{...n,isInputField:!0})).filter(f=>f!==void 0).flat(),p=this.sig.getOutputFields(),d={};for(let f of p)f.name in i&&(d[f.name]=i[f.name]);let m=JSON.stringify(d,null,2),g=[...c,{type:"text",text:`\`\`\`json
264
+ `},...this.renderExamples(t)]:[],o=n?this.renderDemos(n):[],s=r.every(d=>d.type==="text"),a=o.every(d=>d.type==="text"),l=s&&a,u=this.task.text;if(l){let d=[{type:"text",text:u},...r,...o];d.reduce(mr(""),[]),d?.[0]&&(u=d[0].text)}let c={role:"system",content:u,cache:!!this.contextCache};if(Array.isArray(e)){let d=[],m=e,g=!0;for(let h of m){let f;if(g?(f=this.renderSingleValueUserContent(h.values,r,o,l),g=!1):f=this.renderSingleValueUserContent(h.values,[],[],!1),h.role==="user"){d.push({role:"user",content:f});continue}if(h.role!=="assistant")throw new Error("Invalid message role");if(typeof f!="string")throw new Error("Assistant message cannot contain non-text content like images, files,etc");d.push({role:"assistant",content:f})}return[c,...d]}let p=this.renderSingleValueUserContent(e,r,o,l);return[c,{role:"user",content:p}]};renderWithMessagePairs=(e,{examples:t,demos:n})=>{let r={role:"system",content:this.task.text,cache:!!this.contextCache},o=t?this.renderExamplesAsMessages(t):[],s=n?this.renderDemosAsMessages(n):[],a=[];for(let c of[...o,...s])a.push(c.userMessage),a.push(c.assistantMessage);if(this.contextCache&&a.length>0){let c=a.length-1,p=a[c];p?.role==="assistant"&&(a[c]={...p,cache:!0})}if(Array.isArray(e)){let c=[],p=e;for(let d of p){let m=this.renderInputFields(d.values),g=m.every(h=>h.type==="text")?m.map(h=>h.text).join(`
265
+ `):m.reduce(mr(`
266
+ `),[]);if(d.role==="user"){c.push({role:"user",content:g});continue}if(d.role!=="assistant")throw new Error("Invalid message role");if(typeof g!="string")throw new Error("Assistant message cannot contain non-text content like images, files, etc");c.push({role:"assistant",content:g})}return[r,...a,...c]}let l=this.renderInputFields(e),u=l.every(c=>c.type==="text")?l.map(c=>c.text).join(`
267
+ `):l.reduce(mr(`
268
+ `),[]);return[r,...a,{role:"user",content:u}]};renderExtraFields=e=>{let t=[];if(!e||e.length===0)return t;let n=e.reduce((s,a)=>{let l=a.title;return s[l]||(s[l]=[]),s[l].push(a),s},{}),r=this.sig.hasComplexFields();return Object.entries(n).map(([s,a])=>{if(a.length===1){let l=a[0];return l.type?.name==="object"||l.type?.isArray&&l.type.fields?{title:s,name:l.name,description:`${l.description}
269
+ IMPORTANT: Provide the FULL JSON object for this field, matching the schema exactly.`}:{title:s,name:l.name,description:l.description}}if(a.length>1){let l=a.map(u=>`- ${u.description}`).join(`
270
+ `);return{title:s,name:a[0].name,description:l}}}).filter(Boolean).forEach(s=>{let a=this.fieldTemplates?.[s.name]??this.defaultRenderInField;t.push(...a(s,s.description))}),t};renderExamples=e=>{let t=[],n={isExample:!0},r=this.sig.hasComplexFields();for(let[o,s]of e.entries()){if(r){let c=this.sig.getInputFields().map(h=>this.renderInField(h,s,{...n,isInputField:!0})).filter(h=>h!==void 0).flat(),p=this.sig.getOutputFields(),d={};for(let h of p)h.name in s&&(d[h.name]=s[h.name]);let m=JSON.stringify(d,null,2),g=[...c,{type:"text",text:`\`\`\`json
267
271
  ${m}
268
272
  \`\`\`
269
273
  `}];o>0&&g.length>0&&g[0]?.type==="text"&&t.push({type:"text",text:`---
270
274
 
271
- `}),g.forEach(f=>{f&&("text"in f&&(f.text=`${f.text}
272
- `),t.push(f))});continue}let a=this.sig.getInputFields().map(c=>this.renderInField(c,i,{...n,isInputField:!0})).filter(c=>c!==void 0).flat(),l=this.sig.getOutputFields().map(c=>this.renderInField(c,i,{...n,isInputField:!1})).filter(c=>c!==void 0).flat(),u=[...a,...l];o>0&&u.length>0&&u[0]?.type==="text"&&t.push({type:"text",text:`---
275
+ `}),g.forEach(h=>{h&&("text"in h&&(h.text=`${h.text}
276
+ `),t.push(h))});continue}let a=this.sig.getInputFields().map(c=>this.renderInField(c,s,{...n,isInputField:!0})).filter(c=>c!==void 0).flat(),l=this.sig.getOutputFields().map(c=>this.renderInField(c,s,{...n,isInputField:!1})).filter(c=>c!==void 0).flat(),u=[...a,...l];o>0&&u.length>0&&u[0]?.type==="text"&&t.push({type:"text",text:`---
273
277
 
274
278
  `}),u.forEach(c=>{"text"in c&&(c.text=`${c.text}
275
- `),t.push(c)})}return t};renderDemos=e=>{let t=[],n=this.sig.getInputFields(),r=this.sig.getOutputFields(),o={isExample:!0},i=this.sig.hasComplexFields();for(let a of e){if(i){let p=n.map(f=>this.renderInField(f,a,{...o,isInputField:!0})).filter(f=>f!==void 0).flat(),d={};for(let f of r)f.name in a&&(d[f.name]=a[f.name]);let m=JSON.stringify(d,null,2);[...p,{type:"text",text:`\`\`\`json
279
+ `),t.push(c)})}return t};renderDemos=e=>{let t=[],n=this.sig.getInputFields(),r=this.sig.getOutputFields(),o={isExample:!0},s=this.sig.hasComplexFields();for(let a of e){if(s){let p=n.map(h=>this.renderInField(h,a,{...o,isInputField:!0})).filter(h=>h!==void 0).flat(),d={};for(let h of r)h.name in a&&(d[h.name]=a[h.name]);let m=JSON.stringify(d,null,2);[...p,{type:"text",text:`\`\`\`json
276
280
  ${m}
277
281
  \`\`\`
278
- `}].slice(0,-1).forEach(f=>{"text"in f&&(f.text=`${f.text}
279
- `),t.push(f)});continue}let l=n.map(p=>this.renderInField(p,a,{...o,isInputField:!0})).filter(p=>p!==void 0).flat(),u=r.map(p=>this.renderInField(p,a,{...o,isInputField:!1})).filter(p=>p!==void 0).flat();[...l,...u].slice(0,-1).forEach(p=>{"text"in p&&(p.text=`${p.text}
280
- `),t.push(p)})}return t};renderInputFields=e=>{let t=this.sig.getInputFields().map(n=>this.renderInField(n,e,void 0)).filter(n=>n!==void 0).flat();return t.filter(n=>n.type==="text").forEach(n=>{n.text=`${n.text}
281
- `}),t};renderInField=(e,t,n)=>{let r=t[e.name];if(ep(e,r,n))return;e.type&&ko(e,r);let o=Xc(e,r);return(this.fieldTemplates?.[e.name]??this.defaultRenderInField)(e,o)};defaultRenderInField=(e,t)=>{if(e.type?.name==="image"){let r=i=>{if(!i)throw new Error("Image field value is required.");if(typeof i!="object")throw new Error("Image field value must be an object.");if(!("mimeType"in i))throw new Error("Image field must have mimeType");if(!("data"in i))throw new Error("Image field must have data");return i},o=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("Image field value must be an array.");o=o.concat(t.map(i=>{let a=r(i);return{type:"image",mimeType:a.mimeType,image:a.data}}))}else{let i=r(t);o.push({type:"image",mimeType:i.mimeType,image:i.data})}return o}if(e.type?.name==="audio"){let r=i=>{if(!i)throw new Error("Audio field value is required.");if(typeof i!="object")throw new Error("Audio field value must be an object.");if(!("data"in i))throw new Error("Audio field must have data");return i},o=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("Audio field value must be an array.");o=o.concat(t.map(i=>{let a=r(i);return{type:"audio",format:a.format??"wav",data:a.data}}))}else{let i=r(t);o.push({type:"audio",format:i.format??"wav",data:i.data})}return o}if(e.type?.name==="file"){let r=i=>{if(!i)throw new Error("File field value is required.");if(typeof i!="object")throw new Error("File field value must be an object.");if(!("mimeType"in i))throw new Error("File field must have mimeType");let a="data"in i,l="fileUri"in i;if(!a&&!l)throw new Error("File field must have either data or fileUri");if(a&&l)throw new Error("File field cannot have both data and fileUri");return i},o=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("File field value must be an array.");o=o.concat(t.map(i=>{let a=r(i);return"fileUri"in a?{type:"file",mimeType:a.mimeType,fileUri:a.fileUri}:{type:"file",mimeType:a.mimeType,data:a.data}}))}else{let i=r(t);o.push("fileUri"in i?{type:"file",mimeType:i.mimeType,fileUri:i.fileUri}:{type:"file",mimeType:i.mimeType,data:i.data})}return o}if(e.type?.name==="url"){let r=i=>{if(!i)throw new Error("URL field value is required.");if(typeof i=="string")return{url:i};if(typeof i!="object")throw new Error("URL field value must be a string or object.");if(!("url"in i))throw new Error("URL field must have url property");return i},o=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("URL field value must be an array.");o=o.concat(t.map(i=>{let a=r(i);return{type:"url",url:a.url,...a.title?{title:a.title}:{},...a.description?{description:a.description}:{}}}))}else{let i=r(t);o.push({type:"url",url:i.url,...i.title?{title:i.title}:{},...i.description?{description:i.description}:{}})}return o}let n=[e.title,": "];return Array.isArray(t)?(n.push(`
282
+ `}].slice(0,-1).forEach(h=>{"text"in h&&(h.text=`${h.text}
283
+ `),t.push(h)});continue}let l=n.map(p=>this.renderInField(p,a,{...o,isInputField:!0})).filter(p=>p!==void 0).flat(),u=r.map(p=>this.renderInField(p,a,{...o,isInputField:!1})).filter(p=>p!==void 0).flat();[...l,...u].slice(0,-1).forEach(p=>{"text"in p&&(p.text=`${p.text}
284
+ `),t.push(p)})}return t};renderExamplesAsMessages=e=>{let t=[],n={isExample:!0},r=this.sig.hasComplexFields();for(let o of e){let s=this.sig.getInputFields().map(u=>this.renderInField(u,o,{...n,isInputField:!0})).filter(u=>u!==void 0).flat(),a;if(r){let u={};for(let c of this.sig.getOutputFields())c.name in o&&(u[c.name]=o[c.name]);a=JSON.stringify(u,null,2)}else a=this.sig.getOutputFields().map(c=>this.renderInField(c,o,{...n,isInputField:!1})).filter(c=>c!==void 0).flat().filter(c=>c.type==="text").map(c=>c.text).join(`
285
+ `);let l=s.every(u=>u.type==="text")?s.map(u=>u.text).join(`
286
+ `):s.reduce(mr(`
287
+ `),[]);t.push({userMessage:{role:"user",content:l},assistantMessage:{role:"assistant",content:a}})}return t};renderDemosAsMessages=e=>this.renderExamplesAsMessages(e);renderInputFields=e=>{let t=this.sig.getInputFields().map(n=>this.renderInField(n,e,void 0)).filter(n=>n!==void 0).flat();return t.filter(n=>n.type==="text").forEach(n=>{n.text=`${n.text}
288
+ `}),t};renderInField=(e,t,n)=>{let r=t[e.name];if(op(e,r,n))return;e.type&&Mo(e,r);let o=rp(e,r);return(this.fieldTemplates?.[e.name]??this.defaultRenderInField)(e,o)};defaultRenderInField=(e,t)=>{if(e.type?.name==="image"){let r=s=>{if(!s)throw new Error("Image field value is required.");if(typeof s!="object")throw new Error("Image field value must be an object.");if(!("mimeType"in s))throw new Error("Image field must have mimeType");if(!("data"in s))throw new Error("Image field must have data");return s},o=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("Image field value must be an array.");o=o.concat(t.map(s=>{let a=r(s);return{type:"image",mimeType:a.mimeType,image:a.data}}))}else{let s=r(t);o.push({type:"image",mimeType:s.mimeType,image:s.data})}return o}if(e.type?.name==="audio"){let r=s=>{if(!s)throw new Error("Audio field value is required.");if(typeof s!="object")throw new Error("Audio field value must be an object.");if(!("data"in s))throw new Error("Audio field must have data");return s},o=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("Audio field value must be an array.");o=o.concat(t.map(s=>{let a=r(s);return{type:"audio",format:a.format??"wav",data:a.data}}))}else{let s=r(t);o.push({type:"audio",format:s.format??"wav",data:s.data})}return o}if(e.type?.name==="file"){let r=s=>{if(!s)throw new Error("File field value is required.");if(typeof s!="object")throw new Error("File field value must be an object.");if(!("mimeType"in s))throw new Error("File field must have mimeType");let a="data"in s,l="fileUri"in s;if(!a&&!l)throw new Error("File field must have either data or fileUri");if(a&&l)throw new Error("File field cannot have both data and fileUri");return s},o=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("File field value must be an array.");o=o.concat(t.map(s=>{let a=r(s);return"fileUri"in a?{type:"file",mimeType:a.mimeType,fileUri:a.fileUri}:{type:"file",mimeType:a.mimeType,data:a.data}}))}else{let s=r(t);o.push("fileUri"in s?{type:"file",mimeType:s.mimeType,fileUri:s.fileUri}:{type:"file",mimeType:s.mimeType,data:s.data})}return o}if(e.type?.name==="url"){let r=s=>{if(!s)throw new Error("URL field value is required.");if(typeof s=="string")return{url:s};if(typeof s!="object")throw new Error("URL field value must be a string or object.");if(!("url"in s))throw new Error("URL field must have url property");return s},o=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("URL field value must be an array.");o=o.concat(t.map(s=>{let a=r(s);return{type:"url",url:a.url,...a.title?{title:a.title}:{},...a.description?{description:a.description}:{}}}))}else{let s=r(t);o.push({type:"url",url:s.url,...s.title?{title:s.title}:{},...s.description?{description:s.description}:{}})}return o}let n=[e.title,": "];return Array.isArray(t)?(n.push(`
282
289
  `),n.push(t.map(r=>`- ${r}`).join(`
283
- `))):n.push(t),[{type:"text",text:n.join("")}]}},$o=s=>s.map(e=>`\`${e.title}\``).join(", "),eu=s=>s.map(t=>{let n=t.title,r=t.type?.name?ru(t.type):"string",o=t.isOptional?`This optional ${r} field may be omitted`:`A ${r} field`,i=t.description?` ${In(t.description)}`:"";return`${n}: (${o})${i}`.trim()}).join(`
284
- `),tu=s=>s.map(t=>{let n=t.title,r=t.type?.name?ru(t.type):"string",o=t.isOptional?`Only include this ${r} field if its value is available`:`This ${r} field must be included`,i="";return t.description&&t.description.length>0&&(i=` ${t.type?.name==="class"?t.description:In(t.description)}`),t.type?.options&&t.type.options.length>0&&(i.length>0&&(i+=". "),i+=`Allowed values: ${t.type.options.join(", ")}`),`${n}: (${o})${i}`.trim()}).join(`
285
- `),Xc=(s,e)=>{if(s.type?.name==="date"&&e instanceof Date){let t=e.toISOString();return t.slice(0,t.indexOf("T"))}return s.type?.name==="datetime"&&e instanceof Date?Bl(e):s.type?.name==="image"&&typeof e=="object"||s.type?.name==="audio"&&typeof e=="object"||s.type?.name==="file"&&typeof e=="object"||s.type?.name==="url"&&(typeof e=="string"||typeof e=="object")||typeof e=="string"?e:JSON.stringify(e,null,2)},ru=s=>{let e=(()=>{switch(s?.name){case"string":return"string";case"number":return"number";case"boolean":return"boolean (true or false)";case"date":return'date ("YYYY-MM-DD" format)';case"datetime":return'date time ("YYYY-MM-DD HH:mm Timezone" format)';case"json":return"JSON object";case"class":return"classification class";case"code":return"code";case"file":return"file (with filename, mimeType, and data)";case"url":return"URL (string or object with url, title, description)";case"object":return"object";default:return"string"}})();return s?.isArray?`json array of ${e} items`:e};function nu(s){return(e,t)=>{if(t.type==="text"){let n=e.length>0?e[e.length-1]:null;n&&n.type==="text"?n.text+=s+t.text:e.push(t)}else e.push(t);return e}}var ep=(s,e,t)=>{if(typeof e=="boolean"||s?.type?.name==="number"&&typeof e=="number")return!1;if(!e||(Array.isArray(e)||typeof e=="string")&&e.length===0){if(t?.isExample||s.isOptional||s.isInternal)return!0;let n=t?.isInputField!==!1?"input":"output";throw new Error(`Value for ${n} field '${s.name}' is required.`)}return!1};function In(s){let e=s.trim();return e.length>0?`${e.charAt(0).toUpperCase()}${e.slice(1)}${e.endsWith(".")?"":"."}`:""}function tp(s,e){let t=s.history(0,e),n=t.some(o=>o.role==="function");return t.some(o=>o.role==="assistant"&&"functionCalls"in o&&Array.isArray(o.functionCalls)&&o.functionCalls.length>0)&&n}function np(s,e){let t=s.history(0,e),n=[],r=t.filter(i=>i.role==="assistant"&&"functionCalls"in i&&Array.isArray(i.functionCalls)&&i.functionCalls.length>0),o=t.filter(i=>i.role==="function");for(let i of r)if("functionCalls"in i&&i.functionCalls)for(let a of i.functionCalls){let l=o.find(u=>"functionId"in u&&u.functionId===a.id);l&&"result"in l&&"functionId"in l&&n.push({index:n.length,functionName:a.function.name,functionId:a.id,args:a.function.params||"",result:String(l.result),isError:"isError"in l?!!l.isError:!1})}return n}async function No(s,e,t,n){if(!e?.resultPicker||s.length<=1)return 0;let r=e.resultPicker;if((t?tp(t,n):!1)&&t){let l=np(t,n),u=await r({type:"function",results:l});if(u<0||u>=l.length)throw new Error(`Result picker returned invalid index: ${u}. Must be between 0 and ${l.length-1}`);return u}let i=s.map((l,u)=>({index:u,sample:l.delta})),a=await r({type:"fields",results:i});if(a<0||a>=s.length)throw new Error(`Result picker returned invalid index: ${a}. Must be between 0 and ${s.length-1}`);return a}async function ou(s,e,t){let n=s?.getLast(e);if(!n||n.role!=="assistant"||n.chat.length<=1)return 0;let r=n.chat.map(i=>({version:0,index:i.index,delta:i.value}));return await No(r,t,s,e)}var Do=class{tools;logger;constructor(e,t){this.tools=new Map(e.map(n=>[n.name,n])),this.logger=t}getToolParamFieldMap(){let e=new Map;for(let[,t]of this.tools.entries())if(t.parameters?.properties&&Object.keys(t.parameters.properties).length>0){let{paramFieldMap:n}=rp(t);e.set(t.name,n)}else e.set(t.name,new Map);return e}async route(e,t){let n=[],r={},o=new Map,i=new Map;for(let[a,l]of this.tools.entries())i.set(a,this.buildSanitizedFieldMap(l));for(let[a,l]of Object.entries(e)){let u=this.tools.get(this.normalizeToolName(a));if(u){l!=null&&typeof l=="object"&&o.set(u.name,l);continue}r[a]=l}for(let[a,l]of Object.entries(e))for(let[u,c]of this.tools.entries()){let p=i.get(u);if(!p)continue;let d=p.get(a);if(!d)continue;let m=o.get(c.name)??{};this.setNested(m,d,l),o.set(c.name,m)}for(let[a,l]of this.tools.entries()){let u=o.get(l.name);if(!(!u||Object.keys(u).length===0)){if(l.parameters&&l.parameters.type==="object"){let p=(l.parameters.required||[]).filter(d=>u[d]===void 0);if(p.length>0)throw new Ee(`Missing required arguments for tool '${l.name}': ${p.join(", ")}`)}n.push({id:l.name,name:l.name,args:JSON.stringify(u)})}}return{functionCalls:n,remainingFields:r}}normalizeToolName(e){return e.replace(/_([a-z])/g,(t,n)=>n.toUpperCase())}sanitizeFieldName(e){return e.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}buildSanitizedFieldMap(e){let t=new Map;if(!e.parameters||!("properties"in e.parameters))return t;let n=(r,o)=>{for(let[i,a]of Object.entries(r)){let l=[...o,i];if(a&&a.type==="object"&&a.properties)n(a.properties,l);else{let u=`${e.name}.${l.join(".")}`,c=this.sanitizeFieldName(u);t.set(c,l)}}};return n(e.parameters.properties??{},[]),t}setNested(e,t,n){let r=e;for(let o=0;o<t.length-1;o++){let i=t[o],a=r[i];(typeof a!="object"||a===null)&&(r[i]={}),r=r[i]}r[t[t.length-1]]=n}isToolField(e){return this.tools.has(this.normalizeToolName(e))}getToolFieldNames(){return Array.from(this.tools.keys()).map(e=>e.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""))}};function rp(s){let e=[],t=new Map;if(!s.parameters||!s.parameters.properties)return{fields:e,paramFieldMap:t};let n=s.parameters.properties,r=s.parameters.required||[],o=(i,a,l)=>{for(let[u,c]of Object.entries(i)){let p=a?`${a}.${u}`:u,d=`${s.name}.${p}`;if(c.type==="object"&&c.properties)o(c.properties,p,c.required||[]);else{let m=op(c);e.push({name:ip(d),title:sp(s.name,p),type:m,description:c.description||`${u} parameter for ${s.name}`,isOptional:!0}),t.set(d,e[e.length-1])}}};return o(n,"",r),{fields:e,paramFieldMap:t}}function op(s){switch(s.type){case"string":return{name:"string",isArray:!1};case"number":case"integer":return{name:"number",isArray:!1};case"boolean":return{name:"boolean",isArray:!1};case"array":{let e=s.items;if(e?.type)switch(e.type){case"string":return{name:"string",isArray:!0};case"number":case"integer":return{name:"number",isArray:!0};case"boolean":return{name:"boolean",isArray:!0};default:return{name:"json",isArray:!0}}return{name:"json",isArray:!0}}case"object":return{name:"json",isArray:!1};default:return{name:"string",isArray:!1}}}function sp(s,e){return`${s} ${e.replace(/\./g," ")}`}function ip(s){return s.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}function au(s,e,t){let n=new be(e);if(t){let r=t.getToolParamFieldMap();for(let o of s){let i=r.get(o.name);if(i&&i.size>0)for(let a of i.values())n.getOutputFields().some(u=>u.name===a.name)||n.addOutputField(a);else{let a=Si(o.name),l=iu(o.parameters);n.getOutputFields().some(c=>c.name===a)||n.addOutputField({name:a,title:su(o.name),type:l,description:o.description||`Parameters for ${o.name}`,isOptional:!0})}}return{signature:n,toolParamFieldMap:r}}else{let r=new Map;for(let o of s)if(o.parameters?.properties&&Object.keys(o.parameters.properties).length>0){let{fields:i,paramFieldMap:a}=ap(o);r.set(o.name,a);for(let l of i)n.getOutputFields().some(c=>c.name===l.name)||n.addOutputField(l)}else{let i=Si(o.name),a=iu(o.parameters);n.getOutputFields().some(u=>u.name===i)||n.addOutputField({name:i,title:su(o.name),type:a,description:o.description||`Parameters for ${o.name}`,isOptional:!0})}return{signature:n,toolParamFieldMap:r}}}function ap(s){let e=[],t=new Map;if(!s.parameters||!s.parameters.properties)return{fields:e,paramFieldMap:t};let n=s.parameters.properties,r=s.parameters.required||[],o=(i,a,l)=>{for(let[u,c]of Object.entries(i)){let p=a?`${a}.${u}`:u,d=`${s.name}.${p}`;if(c.type==="object"&&c.properties)o(c.properties,p,c.required||[]);else{let m=lp(c),g={name:Si(d),title:up(s.name,p),type:m,description:c.description||`${u} parameter for ${s.name}`,isOptional:!0};e.push(g),t.set(d,g)}}};return o(n,"",r),{fields:e,paramFieldMap:t}}function lp(s){switch(s.type){case"string":return{name:"string",isArray:!1};case"number":case"integer":return{name:"number",isArray:!1};case"boolean":return{name:"boolean",isArray:!1};case"array":{let e=s.items;if(e?.type)switch(e.type){case"string":return{name:"string",isArray:!0};case"number":case"integer":return{name:"number",isArray:!0};case"boolean":return{name:"boolean",isArray:!0};default:return{name:"json",isArray:!0}}return{name:"json",isArray:!0}}case"object":return{name:"json",isArray:!1};default:return{name:"string",isArray:!1}}}function up(s,e){return`${s} ${e.replace(/\./g," ")}`}function Si(s){return s.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}function su(s){return s.replace(/([A-Z])/g," $1").replace(/^./,e=>e.toUpperCase()).trim()}function iu(s){return!s||!s.properties||Object.keys(s.properties).length===0?{name:"string",isArray:!1}:{name:"json",isArray:!1}}var mr=class{tools;router;injectedToolFieldNames=new Set;constructor(e){this.tools=e,this.router=new Do(e)}processSignature(e){let{signature:t}=au(this.tools,e),n=new Set(t.getOutputFields().map(o=>o.name)),r=new Set(e.getOutputFields().map(o=>o.name));return this.injectedToolFieldNames=new Set([...n].filter(o=>!r.has(o))),t}async processResults(e,t){let{functionCalls:n}=await this.router.route(e,t);return n.length>0?n:void 0}getInjectedToolFieldNames(){return Array.from(this.injectedToolFieldNames)}getRouter(){return this.router}};var Ce=class s extends Et{clone=()=>new s(this.signature,this.options);promptTemplate;asserts;streamingAsserts;options;functions;fieldProcessors=[];streamingFieldProcessors=[];excludeContentFromTrace=!1;thoughtFieldName;signatureToolCallingManager;constructor(e,t){super(e,{description:t?.description,traceLabel:t?.traceLabel}),this.options=t,this.thoughtFieldName=t?.thoughtFieldName??"thought";let n={functions:t?.functions,thoughtFieldName:this.thoughtFieldName,cacheSystemPrompt:t?.cacheSystemPrompt};this.promptTemplate=new(t?.promptTemplate??Nt)(this.signature,n),this.asserts=this.options?.asserts??[],this.streamingAsserts=this.options?.streamingAsserts??[],this.excludeContentFromTrace=t?.excludeContentFromTrace??!1,this.functions=t?.functions?So(t.functions):[],this.usage=[]}setInstruction(e){this.promptTemplate.setInstruction(e)}getInstruction(){return this.promptTemplate.getInstruction()}getSignatureName(){return this.signature.getDescription()||"unknown_signature"}getMetricsInstruments(){return ti()}updateMeter(e){ti(e)}createStates(e){return Array.from({length:e},(t,n)=>({index:n,functionCalls:[],values:{},content:"",functionsExecuted:new Set,xstate:{extractedFields:[],streamedIndex:{},s:-1}}))}addAssert=(e,t)=>{this.asserts.push({fn:e,message:t})};addStreamingAssert=(e,t,n)=>{let r=this.signature.getOutputFields().find(a=>a.name===e);if(!r)throw new Error(`addStreamingAssert: field ${String(e)} not found in output signature`);let o=r.type?.name;if(!(!o||o==="string"||o==="code"))throw new Error(`addStreamingAssert: field ${String(e)} must be a string field for streaming assertions`);this.streamingAsserts.push({fieldName:String(e),fn:t,message:n})};addFieldProcessorInternal=(e,t,n=!1)=>{let r=this.signature.getOutputFields().find(o=>o.name===e);if(!r)throw new Error(`addFieldProcessor: field ${e} not found`);if(n){let o=r.type?.name;if(!(!o||o==="string"||o==="code"))throw new Error(`addFieldProcessor: field ${e} must be a text field`);this.streamingFieldProcessors.push({field:r,process:t})}else this.fieldProcessors.push({field:r,process:t})};addStreamingFieldProcessor=(e,t)=>{this.addFieldProcessorInternal(String(e),t,!0)};addFieldProcessor=(e,t)=>{this.addFieldProcessorInternal(String(e),t,!1)};async forwardSendRequest({ai:e,mem:t,options:n,traceContext:r,functions:o,functionCall:i,stepIndex:a}){let{sessionId:l,model:u,rateLimiter:c,stream:p,thinkingTokenBudget:d,showThoughts:m}=n??{},g=await ou(t,l,{resultPicker:n?.resultPicker}),f=t?.history(g,l)??[];if(f.length===0)throw new Error("No chat prompt found");let h={...n?.modelConfig,...n?.sampleCount?{n:n.sampleCount}:{},...n?.sampleCount&&n?.modelConfig?.temperature===1?{temperature:.8}:{}},x=this.isDebug(e,n),A=a===0,y=this.getLogger(e,n);o=this.signatureToolCallingManager?[]:o;let b,k=this.signature.getOutputFields();if(this.signature.hasComplexFields()){if(!e.getFeatures(u)?.structuredOutputs)throw new Error(`Complex structured outputs (object/array types) require a provider that supports structured outputs. Current provider/model (${u}) does not support this feature. Supported providers: OpenAI (GPT-4o, GPT-4.1+), Google Gemini, Anthropic (Sonnet/Opus).`);b={type:"json_schema",schema:{name:"output",strict:!0,schema:vo(k)}}}return await e.chat({chatPrompt:f,functions:o,functionCall:i,modelConfig:h,model:u,responseFormat:b},{sessionId:l,rateLimiter:c,stream:p,debug:x,debugHideSystemPrompt:!A,thinkingTokenBudget:d,showThoughts:m,traceContext:r,abortSignal:n?.abortSignal??te.abortSignal,stepIndex:a,logger:y,functionCallMode:n?.functionCallMode??this.options?.functionCallMode??"auto",retry:n?.retry??this.options?.retry})}async*forwardCore({ai:e,mem:t,options:n,stepIndex:r,span:o,traceContext:i,states:a,stopFunctionNames:l}){let{sessionId:u,functions:c}=n??{},p=n?.functionResultFormatter??this.options?.functionResultFormatter,d=n?.functionCall??this.options?.functionCall,m=this.signatureToolCallingManager,g=n?.strictMode??!1,f=n.model,h=this.usage,x=r===0,A=this.isDebug(e,n),y=this.getLogger(e,n),{functions:b,functionCall:k}=Ml(c,d,x,n),S=await this.forwardSendRequest({ai:e,mem:t,options:n,traceContext:i,functions:b,functionCall:k,stepIndex:r});S instanceof ReadableStream?yield*Vl({ai:e,model:f,res:S,mem:t,sessionId:u,traceId:o?o.spanContext?.().traceId:void 0,functions:b,strictMode:g,span:o,states:a,usage:h,asserts:this.asserts,streamingAsserts:this.streamingAsserts,fieldProcessors:this.fieldProcessors,streamingFieldProcessors:this.streamingFieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,logger:y,debug:A,functionResultFormatter:p,signatureToolCallingManager:m,stopFunctionNames:l,disableMemoryCleanup:n.disableMemoryCleanup}):yield*Wl({ai:e,model:f,res:S,mem:t,sessionId:u,traceId:o?o.spanContext?.().traceId:void 0,functions:b,span:o,strictMode:g,states:a,usage:h,asserts:this.asserts,fieldProcessors:this.fieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,logger:y,debug:A,functionResultFormatter:p,signatureToolCallingManager:m,stopFunctionNames:l,disableMemoryCleanup:n.disableMemoryCleanup})}async*_forward2(e,t,n,r,o,i){let a=r?.stopFunction??this.options?.stopFunction,l=Array.isArray(a)?a.map(P=>P.toLowerCase()):a?[a.toLowerCase()]:void 0,u=r.maxRetries??this.options?.maxRetries??3,c=r.maxSteps??this.options?.maxSteps??25,p=r.mem??this.options?.mem??new xn,d=[...this.functions,...r.functions?So(r.functions):[]],m=d&&d.length>0,g=r.functionCallMode??this.options?.functionCallMode??"auto",f=r.cacheSystemPrompt??this.options?.cacheSystemPrompt;m&&g==="prompt"&&(this.signatureToolCallingManager=new mr(d)),m&&g==="auto"&&!e.getFeatures(r.model).functions&&(this.signatureToolCallingManager=new mr(d));let h,x,A=this.options?.promptTemplate??Nt;this.signatureToolCallingManager&&(this.signature=this.signatureToolCallingManager.processSignature(this.signature),this.setSignature(this.signature));let y={functions:this.signatureToolCallingManager?[]:d,thoughtFieldName:this.thoughtFieldName,cacheSystemPrompt:f};this.promptTemplate=new A(this.signature,y);let b,k=performance.now();Array.isArray(t)?($a(t),b=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos})):b=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos});let S=performance.now()-k,M=this.getMetricsInstruments();M&&Io(M,"prompt_render",S,this.getSignatureName());let R=performance.now();p.addRequest(b,r.sessionId);let O=performance.now()-R;M&&Io(M,"memory_update",O,this.getSignatureName());let F=new Map;n.forEach(P=>{F.set(P.index,{})});e:for(let P=0;P<c;P++){let I=u;for(let v=0;v<=I;v++)try{for(let w=0;w<u;w++){n.forEach(E=>{E.content="",E.values={},E.functionCalls=[],E.functionsExecuted=new Set,E.xstate={extractedFields:[],streamedIndex:{},s:-1}}),w>0&&F.forEach((E,_)=>{F.set(_,{})});let C=new Map;n.forEach(E=>{C.set(E.index,{})});try{let E=this.forwardCore({options:r,ai:e,mem:p,stepIndex:P,span:o,traceContext:i,states:n,stopFunctionNames:l}),_=!1;try{for await(let D of E)if(D!==void 0){let q=D.index,H=D.delta,ce=C.get(q)??{},ne=F.get(q)??{},xe={},ye=!1;for(let Z of Object.keys(H)){let Ae=H[Z],ge=ce[Z],ke;typeof Ae=="string"&&(typeof ge=="string"||ge===void 0)?ke=(ge??"")+Ae:Array.isArray(Ae)&&(Array.isArray(ge)||ge===void 0)?ke=[...ge??[],...Ae]:ke=Ae,ce[Z]=ke;let he=ke,ve=ne[Z];if(typeof he=="string"&&typeof ve=="string")if(he.startsWith(ve)){let V=he.slice(ve.length);V&&(xe[Z]=V,ye=!0,ne[Z]=he)}else ve.startsWith(he)||he!==ve&&(xe[Z]=he,ye=!0,ne[Z]=he);else if(Array.isArray(he)&&Array.isArray(ve)){if(he.length>ve.length){let V=he.slice(ve.length);xe[Z]=V,ye=!0,ne[Z]=he}}else JSON.stringify(he)!==JSON.stringify(ve)&&(xe[Z]=he,ye=!0,ne[Z]=he)}ye&&(yield{version:w,index:D.index,delta:xe})}}catch(D){if(D instanceof $t)_=!0;else throw D}if(_?!1:Jl(p,l,n,r?.sessionId)){let D=this.getMetricsInstruments();D&&bo(D,P+1,c,this.getSignatureName());continue e}r?.disableMemoryCleanup||(p.removeByTag("invalid-assistant",r.sessionId),p.removeByTag("correction",r.sessionId),p.removeByTag("error",r.sessionId));let L=this.getMetricsInstruments();if(L){bo(L,P+1,c,this.getSignatureName());let D=new Set;n.forEach(q=>{q.functionsExecuted.forEach(H=>D.add(H))}),D.size>0&&gl(L,!0,D.size,!0,!1,this.getSignatureName()),hl(L,this.fieldProcessors.length,this.streamingFieldProcessors.length,this.getSignatureName())}return}catch(E){x=E;let _,$=this.isDebug(e,r),L=this.getLogger(e,r),D=this.getMetricsInstruments(),q=this.getSignatureName(),H={error:E,errCount:w,logger:L,metricsInstruments:D,signatureName:q,span:o,debug:$};if(o?.recordException(E),E instanceof Ee)_=Rl(H),h=E;else if(E instanceof pt)_=vl(H),h=E;else if(E instanceof fe)Sl(H);else if(!(E instanceof Ye)){let ce=E,ne=ce instanceof Ke&&ce.status>=500&&ce.status<600,xe=ce instanceof De,ye=ce instanceof ot;throw ne||xe||ye?E:Oi(E,e,this.signature)}if(_&&(p.addTag("error",r.sessionId),p.addRequest([{role:"user",content:this.promptTemplate.renderExtraFields(_)}],r.sessionId),p.addTag("correction",r.sessionId),this.signature.hasComplexFields()))for(let ne of n)ne.content="",ne.values={},ne.xstate={extractedFields:[],streamedIndex:{},s:-1}}}let T=this.getMetricsInstruments();throw T&&ri(T,u,!1,u,this.getSignatureName()),Oi(new Error(`Unable to fix validation error: ${(h??x)?.message??(h??x)?.toString()??"unknown error"}
290
+ `))):n.push(t),[{type:"text",text:n.join("")}]}},No=i=>i.map(e=>`\`${e.title}\``).join(", "),ou=i=>i.map(t=>{let n=t.title,r=t.type?.name?iu(t.type):"string",o=t.isOptional?`This optional ${r} field may be omitted`:`A ${r} field`,s=t.description?` ${In(t.description)}`:"";return`${n}: (${o})${s}`.trim()}).join(`
291
+ `),su=i=>i.map(t=>{let n=t.title,r=t.type?.name?iu(t.type):"string",o=t.isOptional?`Only include this ${r} field if its value is available`:`This ${r} field must be included`,s="";return t.description&&t.description.length>0&&(s=` ${t.type?.name==="class"?t.description:In(t.description)}`),t.type?.options&&t.type.options.length>0&&(s.length>0&&(s+=". "),s+=`Allowed values: ${t.type.options.join(", ")}`),`${n}: (${o})${s}`.trim()}).join(`
292
+ `),rp=(i,e)=>{if(i.type?.name==="date"&&e instanceof Date){let t=e.toISOString();return t.slice(0,t.indexOf("T"))}return i.type?.name==="datetime"&&e instanceof Date?Hl(e):i.type?.name==="image"&&typeof e=="object"||i.type?.name==="audio"&&typeof e=="object"||i.type?.name==="file"&&typeof e=="object"||i.type?.name==="url"&&(typeof e=="string"||typeof e=="object")||typeof e=="string"?e:JSON.stringify(e,null,2)},iu=i=>{let e=(()=>{switch(i?.name){case"string":return"string";case"number":return"number";case"boolean":return"boolean (true or false)";case"date":return'date ("YYYY-MM-DD" format)';case"datetime":return'date time ("YYYY-MM-DD HH:mm Timezone" format)';case"json":return"JSON object";case"class":return"classification class";case"code":return"code";case"file":return"file (with filename, mimeType, and data)";case"url":return"URL (string or object with url, title, description)";case"object":return"object";default:return"string"}})();return i?.isArray?`json array of ${e} items`:e};function mr(i){return(e,t)=>{if(t.type==="text"){let n=e.length>0?e[e.length-1]:null;n&&n.type==="text"?n.text+=i+t.text:e.push(t)}else e.push(t);return e}}var op=(i,e,t)=>{if(typeof e=="boolean"||i?.type?.name==="number"&&typeof e=="number")return!1;if(!e||(Array.isArray(e)||typeof e=="string")&&e.length===0){if(t?.isExample||i.isOptional||i.isInternal)return!0;let n=t?.isInputField!==!1?"input":"output";throw new Error(`Value for ${n} field '${i.name}' is required.`)}return!1};function In(i){let e=i.trim();return e.length>0?`${e.charAt(0).toUpperCase()}${e.slice(1)}${e.endsWith(".")?"":"."}`:""}function sp(i,e){let t=i.history(0,e),n=t.some(o=>o.role==="function");return t.some(o=>o.role==="assistant"&&"functionCalls"in o&&Array.isArray(o.functionCalls)&&o.functionCalls.length>0)&&n}function ip(i,e){let t=i.history(0,e),n=[],r=t.filter(s=>s.role==="assistant"&&"functionCalls"in s&&Array.isArray(s.functionCalls)&&s.functionCalls.length>0),o=t.filter(s=>s.role==="function");for(let s of r)if("functionCalls"in s&&s.functionCalls)for(let a of s.functionCalls){let l=o.find(u=>"functionId"in u&&u.functionId===a.id);l&&"result"in l&&"functionId"in l&&n.push({index:n.length,functionName:a.function.name,functionId:a.id,args:a.function.params||"",result:String(l.result),isError:"isError"in l?!!l.isError:!1})}return n}async function Do(i,e,t,n){if(!e?.resultPicker||i.length<=1)return 0;let r=e.resultPicker;if((t?sp(t,n):!1)&&t){let l=ip(t,n),u=await r({type:"function",results:l});if(u<0||u>=l.length)throw new Error(`Result picker returned invalid index: ${u}. Must be between 0 and ${l.length-1}`);return u}let s=i.map((l,u)=>({index:u,sample:l.delta})),a=await r({type:"fields",results:s});if(a<0||a>=i.length)throw new Error(`Result picker returned invalid index: ${a}. Must be between 0 and ${i.length-1}`);return a}async function au(i,e,t){let n=i?.getLast(e);if(!n||n.role!=="assistant"||n.chat.length<=1)return 0;let r=n.chat.map(s=>({version:0,index:s.index,delta:s.value}));return await Do(r,t,i,e)}var Go=class{tools;logger;constructor(e,t){this.tools=new Map(e.map(n=>[n.name,n])),this.logger=t}getToolParamFieldMap(){let e=new Map;for(let[,t]of this.tools.entries())if(t.parameters?.properties&&Object.keys(t.parameters.properties).length>0){let{paramFieldMap:n}=ap(t);e.set(t.name,n)}else e.set(t.name,new Map);return e}async route(e,t){let n=[],r={},o=new Map,s=new Map;for(let[a,l]of this.tools.entries())s.set(a,this.buildSanitizedFieldMap(l));for(let[a,l]of Object.entries(e)){let u=this.tools.get(this.normalizeToolName(a));if(u){l!=null&&typeof l=="object"&&o.set(u.name,l);continue}r[a]=l}for(let[a,l]of Object.entries(e))for(let[u,c]of this.tools.entries()){let p=s.get(u);if(!p)continue;let d=p.get(a);if(!d)continue;let m=o.get(c.name)??{};this.setNested(m,d,l),o.set(c.name,m)}for(let[a,l]of this.tools.entries()){let u=o.get(l.name);if(!(!u||Object.keys(u).length===0)){if(l.parameters&&l.parameters.type==="object"){let p=(l.parameters.required||[]).filter(d=>u[d]===void 0);if(p.length>0)throw new Me(`Missing required arguments for tool '${l.name}': ${p.join(", ")}`)}n.push({id:l.name,name:l.name,args:JSON.stringify(u)})}}return{functionCalls:n,remainingFields:r}}normalizeToolName(e){return e.replace(/_([a-z])/g,(t,n)=>n.toUpperCase())}sanitizeFieldName(e){return e.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}buildSanitizedFieldMap(e){let t=new Map;if(!e.parameters||!("properties"in e.parameters))return t;let n=(r,o)=>{for(let[s,a]of Object.entries(r)){let l=[...o,s];if(a&&a.type==="object"&&a.properties)n(a.properties,l);else{let u=`${e.name}.${l.join(".")}`,c=this.sanitizeFieldName(u);t.set(c,l)}}};return n(e.parameters.properties??{},[]),t}setNested(e,t,n){let r=e;for(let o=0;o<t.length-1;o++){let s=t[o],a=r[s];(typeof a!="object"||a===null)&&(r[s]={}),r=r[s]}r[t[t.length-1]]=n}isToolField(e){return this.tools.has(this.normalizeToolName(e))}getToolFieldNames(){return Array.from(this.tools.keys()).map(e=>e.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""))}};function ap(i){let e=[],t=new Map;if(!i.parameters||!i.parameters.properties)return{fields:e,paramFieldMap:t};let n=i.parameters.properties,r=i.parameters.required||[],o=(s,a,l)=>{for(let[u,c]of Object.entries(s)){let p=a?`${a}.${u}`:u,d=`${i.name}.${p}`;if(c.type==="object"&&c.properties)o(c.properties,p,c.required||[]);else{let m=lp(c);e.push({name:cp(d),title:up(i.name,p),type:m,description:c.description||`${u} parameter for ${i.name}`,isOptional:!0}),t.set(d,e[e.length-1])}}};return o(n,"",r),{fields:e,paramFieldMap:t}}function lp(i){switch(i.type){case"string":return{name:"string",isArray:!1};case"number":case"integer":return{name:"number",isArray:!1};case"boolean":return{name:"boolean",isArray:!1};case"array":{let e=i.items;if(e?.type)switch(e.type){case"string":return{name:"string",isArray:!0};case"number":case"integer":return{name:"number",isArray:!0};case"boolean":return{name:"boolean",isArray:!0};default:return{name:"json",isArray:!0}}return{name:"json",isArray:!0}}case"object":return{name:"json",isArray:!1};default:return{name:"string",isArray:!1}}}function up(i,e){return`${i} ${e.replace(/\./g," ")}`}function cp(i){return i.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}function cu(i,e,t){let n=new ye(e);if(t){let r=t.getToolParamFieldMap();for(let o of i){let s=r.get(o.name);if(s&&s.size>0)for(let a of s.values())n.getOutputFields().some(u=>u.name===a.name)||n.addOutputField(a);else{let a=ki(o.name),l=uu(o.parameters);n.getOutputFields().some(c=>c.name===a)||n.addOutputField({name:a,title:lu(o.name),type:l,description:o.description||`Parameters for ${o.name}`,isOptional:!0})}}return{signature:n,toolParamFieldMap:r}}else{let r=new Map;for(let o of i)if(o.parameters?.properties&&Object.keys(o.parameters.properties).length>0){let{fields:s,paramFieldMap:a}=pp(o);r.set(o.name,a);for(let l of s)n.getOutputFields().some(c=>c.name===l.name)||n.addOutputField(l)}else{let s=ki(o.name),a=uu(o.parameters);n.getOutputFields().some(u=>u.name===s)||n.addOutputField({name:s,title:lu(o.name),type:a,description:o.description||`Parameters for ${o.name}`,isOptional:!0})}return{signature:n,toolParamFieldMap:r}}}function pp(i){let e=[],t=new Map;if(!i.parameters||!i.parameters.properties)return{fields:e,paramFieldMap:t};let n=i.parameters.properties,r=i.parameters.required||[],o=(s,a,l)=>{for(let[u,c]of Object.entries(s)){let p=a?`${a}.${u}`:u,d=`${i.name}.${p}`;if(c.type==="object"&&c.properties)o(c.properties,p,c.required||[]);else{let m=dp(c),g={name:ki(d),title:mp(i.name,p),type:m,description:c.description||`${u} parameter for ${i.name}`,isOptional:!0};e.push(g),t.set(d,g)}}};return o(n,"",r),{fields:e,paramFieldMap:t}}function dp(i){switch(i.type){case"string":return{name:"string",isArray:!1};case"number":case"integer":return{name:"number",isArray:!1};case"boolean":return{name:"boolean",isArray:!1};case"array":{let e=i.items;if(e?.type)switch(e.type){case"string":return{name:"string",isArray:!0};case"number":case"integer":return{name:"number",isArray:!0};case"boolean":return{name:"boolean",isArray:!0};default:return{name:"json",isArray:!0}}return{name:"json",isArray:!0}}case"object":return{name:"json",isArray:!1};default:return{name:"string",isArray:!1}}}function mp(i,e){return`${i} ${e.replace(/\./g," ")}`}function ki(i){return i.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}function lu(i){return i.replace(/([A-Z])/g," $1").replace(/^./,e=>e.toUpperCase()).trim()}function uu(i){return!i||!i.properties||Object.keys(i.properties).length===0?{name:"string",isArray:!1}:{name:"json",isArray:!1}}var gr=class{tools;router;injectedToolFieldNames=new Set;constructor(e){this.tools=e,this.router=new Go(e)}processSignature(e){let{signature:t}=cu(this.tools,e),n=new Set(t.getOutputFields().map(o=>o.name)),r=new Set(e.getOutputFields().map(o=>o.name));return this.injectedToolFieldNames=new Set([...n].filter(o=>!r.has(o))),t}async processResults(e,t){let{functionCalls:n}=await this.router.route(e,t);return n.length>0?n:void 0}getInjectedToolFieldNames(){return Array.from(this.injectedToolFieldNames)}getRouter(){return this.router}};var Ce=class i extends Et{clone=()=>new i(this.signature,this.options);promptTemplate;asserts;streamingAsserts;options;functions;fieldProcessors=[];streamingFieldProcessors=[];excludeContentFromTrace=!1;thoughtFieldName;signatureToolCallingManager;constructor(e,t){super(e,{description:t?.description,traceLabel:t?.traceLabel}),this.options=t,this.thoughtFieldName=t?.thoughtFieldName??"thought";let n={functions:t?.functions,thoughtFieldName:this.thoughtFieldName};this.promptTemplate=new(t?.promptTemplate??Nt)(this.signature,n),this.asserts=this.options?.asserts??[],this.streamingAsserts=this.options?.streamingAsserts??[],this.excludeContentFromTrace=t?.excludeContentFromTrace??!1,this.functions=t?.functions?Oo(t.functions):[],this.usage=[]}setInstruction(e){this.promptTemplate.setInstruction(e)}getInstruction(){return this.promptTemplate.getInstruction()}getSignatureName(){return this.signature.getDescription()||"unknown_signature"}getMetricsInstruments(){return ri()}updateMeter(e){ri(e)}createStates(e){return Array.from({length:e},(t,n)=>({index:n,functionCalls:[],values:{},content:"",functionsExecuted:new Set,xstate:{extractedFields:[],streamedIndex:{},s:-1}}))}addAssert=(e,t)=>{this.asserts.push({fn:e,message:t})};addStreamingAssert=(e,t,n)=>{let r=this.signature.getOutputFields().find(a=>a.name===e);if(!r)throw new Error(`addStreamingAssert: field ${String(e)} not found in output signature`);let o=r.type?.name;if(!(!o||o==="string"||o==="code"))throw new Error(`addStreamingAssert: field ${String(e)} must be a string field for streaming assertions`);this.streamingAsserts.push({fieldName:String(e),fn:t,message:n})};addFieldProcessorInternal=(e,t,n=!1)=>{let r=this.signature.getOutputFields().find(o=>o.name===e);if(!r)throw new Error(`addFieldProcessor: field ${e} not found`);if(n){let o=r.type?.name;if(!(!o||o==="string"||o==="code"))throw new Error(`addFieldProcessor: field ${e} must be a text field`);this.streamingFieldProcessors.push({field:r,process:t})}else this.fieldProcessors.push({field:r,process:t})};addStreamingFieldProcessor=(e,t)=>{this.addFieldProcessorInternal(String(e),t,!0)};addFieldProcessor=(e,t)=>{this.addFieldProcessorInternal(String(e),t,!1)};async forwardSendRequest({ai:e,mem:t,options:n,traceContext:r,functions:o,functionCall:s,stepIndex:a}){let{sessionId:l,model:u,rateLimiter:c,stream:p,thinkingTokenBudget:d,showThoughts:m}=n??{},g=await au(t,l,{resultPicker:n?.resultPicker}),h=t?.history(g,l)??[];if(h.length===0)throw new Error("No chat prompt found");let f={...n?.modelConfig,...n?.sampleCount?{n:n.sampleCount}:{},...n?.sampleCount&&n?.modelConfig?.temperature===1?{temperature:.8}:{}},x=this.isDebug(e,n),A=a===0,y=this.getLogger(e,n);o=this.signatureToolCallingManager?[]:o;let b,S=this.signature.getOutputFields();if(this.signature.hasComplexFields()){if(!e.getFeatures(u)?.structuredOutputs)throw new Error(`Complex structured outputs (object/array types) require a provider that supports structured outputs. Current provider/model (${u}) does not support this feature. Supported providers: OpenAI (GPT-4o, GPT-4.1+), Google Gemini, Anthropic (Sonnet/Opus).`);b={type:"json_schema",schema:{name:"output",strict:!0,schema:So(S)}}}let M=o?.length?o.map((k,F)=>({...k,cache:F===o.length-1})):o;return await e.chat({chatPrompt:h,functions:M,functionCall:s,modelConfig:f,model:u,responseFormat:b},{sessionId:l,rateLimiter:c,stream:p,debug:x,debugHideSystemPrompt:!A,thinkingTokenBudget:d,showThoughts:m,traceContext:r,abortSignal:n?.abortSignal??ee.abortSignal,stepIndex:a,logger:y,functionCallMode:n?.functionCallMode??this.options?.functionCallMode??"auto",retry:n?.retry??this.options?.retry})}async*forwardCore({ai:e,mem:t,options:n,stepIndex:r,span:o,traceContext:s,states:a,stopFunctionNames:l}){let{sessionId:u,functions:c}=n??{},p=n?.functionResultFormatter??this.options?.functionResultFormatter,d=n?.functionCall??this.options?.functionCall,m=this.signatureToolCallingManager,g=n?.strictMode??!1,h=n.model,f=this.usage,x=r===0,A=this.isDebug(e,n),y=this.getLogger(e,n),{functions:b,functionCall:S}=_l(c,d,x,n),w=await this.forwardSendRequest({ai:e,mem:t,options:n,traceContext:s,functions:b,functionCall:S,stepIndex:r});w instanceof ReadableStream?yield*Ql({ai:e,model:h,res:w,mem:t,sessionId:u,traceId:o?o.spanContext?.().traceId:void 0,functions:b,strictMode:g,span:o,states:a,usage:f,asserts:this.asserts,streamingAsserts:this.streamingAsserts,fieldProcessors:this.fieldProcessors,streamingFieldProcessors:this.streamingFieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,logger:y,debug:A,functionResultFormatter:p,signatureToolCallingManager:m,stopFunctionNames:l,disableMemoryCleanup:n.disableMemoryCleanup}):yield*Xl({ai:e,model:h,res:w,mem:t,sessionId:u,traceId:o?o.spanContext?.().traceId:void 0,functions:b,span:o,strictMode:g,states:a,usage:f,asserts:this.asserts,fieldProcessors:this.fieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,logger:y,debug:A,functionResultFormatter:p,signatureToolCallingManager:m,stopFunctionNames:l,disableMemoryCleanup:n.disableMemoryCleanup})}async*_forward2(e,t,n,r,o,s){let a=r?.stopFunction??this.options?.stopFunction,l=Array.isArray(a)?a.map(F=>F.toLowerCase()):a?[a.toLowerCase()]:void 0,u=r.maxRetries??this.options?.maxRetries??3,c=r.maxSteps??this.options?.maxSteps??25,p=r.mem??this.options?.mem??new xn,d=[...this.functions,...r.functions?Oo(r.functions):[]],m=d&&d.length>0,g=r.functionCallMode??this.options?.functionCallMode??"auto";m&&g==="prompt"&&(this.signatureToolCallingManager=new gr(d)),m&&g==="auto"&&!e.getFeatures(r.model).functions&&(this.signatureToolCallingManager=new gr(d));let h,f,x=this.options?.promptTemplate??Nt;this.signatureToolCallingManager&&(this.signature=this.signatureToolCallingManager.processSignature(this.signature),this.setSignature(this.signature));let A={functions:this.signatureToolCallingManager?[]:d,thoughtFieldName:this.thoughtFieldName,contextCache:r.contextCache};this.promptTemplate=new x(this.signature,A);let y,b=performance.now();Array.isArray(t)?(Ga(t),y=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos})):y=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos});let S=performance.now()-b,w=this.getMetricsInstruments();w&&To(w,"prompt_render",S,this.getSignatureName());let M=performance.now();p.addRequest(y,r.sessionId);let R=performance.now()-M;w&&To(w,"memory_update",R,this.getSignatureName());let k=new Map;n.forEach(F=>{k.set(F.index,{})});e:for(let F=0;F<c;F++){let E=u;for(let T=0;T<=E;T++)try{for(let C=0;C<u;C++){n.forEach(I=>{I.content="",I.values={},I.functionCalls=[],I.functionsExecuted=new Set,I.xstate={extractedFields:[],streamedIndex:{},s:-1}}),C>0&&k.forEach((I,P)=>{k.set(P,{})});let O=new Map;n.forEach(I=>{O.set(I.index,{})});try{let I=this.forwardCore({options:r,ai:e,mem:p,stepIndex:F,span:o,traceContext:s,states:n,stopFunctionNames:l}),P=!1;try{for await(let N of I)if(N!==void 0){let L=N.index,z=N.delta,H=O.get(L)??{},te=k.get(L)??{},de={},be=!1;for(let ce of Object.keys(z)){let ie=z[ce],fe=H[ce],Ae;typeof ie=="string"&&(typeof fe=="string"||fe===void 0)?Ae=(fe??"")+ie:Array.isArray(ie)&&(Array.isArray(fe)||fe===void 0)?Ae=[...fe??[],...ie]:Ae=ie,H[ce]=Ae;let pe=Ae,ve=te[ce];if(typeof pe=="string"&&typeof ve=="string")if(pe.startsWith(ve)){let qe=pe.slice(ve.length);qe&&(de[ce]=qe,be=!0,te[ce]=pe)}else ve.startsWith(pe)||pe!==ve&&(de[ce]=pe,be=!0,te[ce]=pe);else if(Array.isArray(pe)&&Array.isArray(ve)){if(pe.length>ve.length){let qe=pe.slice(ve.length);de[ce]=qe,be=!0,te[ce]=pe}}else JSON.stringify(pe)!==JSON.stringify(ve)&&(de[ce]=pe,be=!0,te[ce]=pe)}be&&(yield{version:C,index:N.index,delta:de})}}catch(N){if(N instanceof $t)P=!0;else throw N}if(P?!1:Zl(p,l,n,r?.sessionId)){let N=this.getMetricsInstruments();N&&Io(N,F+1,c,this.getSignatureName());continue e}r?.disableMemoryCleanup||(p.removeByTag("invalid-assistant",r.sessionId),p.removeByTag("correction",r.sessionId),p.removeByTag("error",r.sessionId));let $=this.getMetricsInstruments();if($){Io($,F+1,c,this.getSignatureName());let N=new Set;n.forEach(L=>{L.functionsExecuted.forEach(z=>N.add(z))}),N.size>0&&Al($,!0,N.size,!0,!1,this.getSignatureName()),yl($,this.fieldProcessors.length,this.streamingFieldProcessors.length,this.getSignatureName())}return}catch(I){f=I;let P,_=this.isDebug(e,r),$=this.getLogger(e,r),N=this.getMetricsInstruments(),L=this.getSignatureName(),z={error:I,errCount:C,logger:$,metricsInstruments:N,signatureName:L,span:o,debug:_};if(o?.recordException(I),I instanceof Me)P=kl(z),h=I;else if(I instanceof pt)P=Ml(z),h=I;else if(I instanceof xe)El(z);else if(!(I instanceof Ye)){let H=I,te=H instanceof Ve&&H.status>=500&&H.status<600,de=H instanceof Ge,be=H instanceof ot;throw te||de||be?I:Mi(I,e,this.signature)}if(P&&(p.addTag("error",r.sessionId),p.addRequest([{role:"user",content:this.promptTemplate.renderExtraFields(P)}],r.sessionId),p.addTag("correction",r.sessionId),this.signature.hasComplexFields()))for(let te of n)te.content="",te.values={},te.xstate={extractedFields:[],streamedIndex:{},s:-1}}}let v=this.getMetricsInstruments();throw v&&si(v,u,!1,u,this.getSignatureName()),Mi(new Error(`Unable to fix validation error: ${(h??f)?.message??(h??f)?.toString()??"unknown error"}
286
293
 
287
294
  LLM Output:
288
- ${n.map(w=>w.content).join(`
295
+ ${n.map(C=>C.content).join(`
289
296
  ---
290
- `)}`),e,this.signature)}catch(T){let w=T,C=w instanceof Ke&&w.status>=500&&w.status<600,E=w instanceof De,_=w instanceof ot,$=w instanceof Ye;if((C||E||_||$)&&v<I){let D=this.isDebug(e,r),q=this.getLogger(e,r),ne=Math.min(6e4,1e3*Math.pow(2,v));D&&q&&q({name:"Notification",id:"infrastructure-retry",value:`Infrastructure error (attempt ${v+1}/${I+1}): ${w.message}. Retrying in ${ne}ms...`}),o?.addEvent("infrastructure.retry",{attempt:v+1,maxRetries:I,delay:ne,errorType:w instanceof Ke?"status_error":w instanceof De?"network_error":w instanceof ot?"timeout_error":"stream_terminated",errorMessage:w.message}),await new Promise(xe=>setTimeout(xe,ne));continue}throw T}}throw M&&bo(M,c,c,this.getSignatureName()),Oi(new Error(`Max steps reached: ${c}`),e,this.signature)}validateInputs(e){let t=this.signature.getInputFields();for(let n of t){if(n.isInternal)continue;let r=e[n.name];if(n.isOptional&&r===void 0)continue;let o=n.type;if(o&&(o.name==="url"&&Mt(r,n),o.name,o.name,(o.name==="string"||o.name==="code")&&Xe(r,n),o.name==="number"&&et(r,n),o.name==="object"&&o.fields&&typeof r=="object"&&r!==null&&this.validateObjectFields(r,o.fields,n.name),o.isArray&&Array.isArray(r)))for(let i=0;i<r.length;i++){let a=r[i];o.name==="string"||o.name==="code"?Xe(a,n):o.name==="number"?et(a,n):o.fields&&typeof a=="object"&&a!==null&&this.validateObjectFields(a,o.fields,`${n.name}[${i}]`)}}}validateObjectFields(e,t,n){for(let[r,o]of Object.entries(t)){let i=e[r];if(o.isOptional&&i===void 0)continue;let a={name:`${n}.${r}`,type:{name:o.type,isArray:o.isArray,options:o.options?[...o.options]:void 0,fields:o.fields,minLength:o.minLength,maxLength:o.maxLength,minimum:o.minimum,maximum:o.maximum,pattern:o.pattern,format:o.format},description:o.description,isOptional:o.isOptional};if(o.type==="string"||o.type==="code"?Xe(i,a):o.type==="number"?et(i,a):o.type==="object"&&o.fields&&typeof i=="object"&&i!==null&&this.validateObjectFields(i,o.fields,a.name),o.isArray&&Array.isArray(i))for(let l=0;l<i.length;l++){let u=i[l];o.type==="string"||o.type==="code"?Xe(u,a):o.type==="number"?et(u,a):o.fields&&typeof u=="object"&&u!==null&&this.validateObjectFields(u,o.fields,`${a.name}[${l}]`)}}}async*_forward1(e,t,n){(!Array.isArray(t)||!t.every(x=>"role"in x))&&this.validateInputs(t);let r=performance.now(),o=this.createStates(n.sampleCount??1),i=performance.now()-r,a=this.getMetricsInstruments();a&&Io(a,"state_creation",i,this.getSignatureName());let l=n?.tracer??this.options?.tracer??e.getOptions().tracer,u=this.functions;if(n?.functions&&(u=So(n.functions,this.functions)),!l){yield*this._forward2(e,t,o,{...n,functions:u});return}let c=u?.map(x=>x.name).join(","),p={signature:JSON.stringify(this.signature.toJSON(),null,2),...this.examples?{examples:JSON.stringify(this.examples,null,2)}:{},...c?{provided_functions:c}:{},...n?.model?{model:n.model}:{},...n?.thinkingTokenBudget?{thinking_token_budget:n.thinkingTokenBudget}:{},...n?.showThoughts?{show_thoughts:n.showThoughts}:{},...n?.maxSteps?{max_steps:n.maxSteps}:{},...n?.maxRetries?{max_retries:n.maxRetries}:{}},d=this.traceLabel&&n.traceLabel?`${this.traceLabel} > ${n.traceLabel}`:n.traceLabel??this.traceLabel,m=d?`AxGen > ${d}`:"AxGen",g=l.startSpan(m,{kind:Be.SERVER,attributes:p}),f=vt.active(),h=Bn.setSpan(f,g);try{if(this.excludeContentFromTrace||g.addEvent("input",{content:JSON.stringify(t,null,2)}),yield*this._forward2(e,t,o,{...n,functions:u},g,h),!this.excludeContentFromTrace){let x=o.map(y=>y.values),A=x.length===1?x[0]:x;g.addEvent("output",{content:JSON.stringify(A,null,2)})}}finally{g.end()}}async forward(e,t,n){let r=n?.cachingFunction??this.options?.cachingFunction??te.cachingFunction,o=(()=>{if(!r)return;let d=this.signature.getInputFields().map(m=>m.name);return this.computeCacheKey(t,d)})();if(r&&o){let d=await r(o);if(d!==void 0)return d}let i=performance.now(),a=this.getSignatureName(),l=n?.stream??!1,u=!1,c=0,p=!1;try{let d=this.getMetricsInstruments();d&&Al(d,this.signature.getInputFields().length,this.signature.getOutputFields().length,this.examples?.length??0,this.demos?.length??0,a);let m=this._forward1(e,t,n??{}),g=[],f=0,h=0;for await(let M of m)M.version!==f&&(g=[]),f=M.version,g=fi(g,M),h++;c=f;let x=performance.now();p=!!n?.resultPicker;let A=await No(g,{resultPicker:n?.resultPicker},n?.mem,n?.sessionId),y=performance.now()-x,k=g[A]?.delta??{},S=Array.isArray(t)?{}:t??{};if(this.trace={...S,...k},p&&this.isDebug(e,n)){let M=this.getLogger(e,n);xa(g.length,A,y,M)}if(u=!0,d&&(xl(d,g.length,p,p?y:void 0,a),fl(d,l,h,void 0,a)),r&&o)try{await r(o,k)}catch{}return k}catch(d){throw u=!1,d}finally{let d=performance.now()-i,m=this.getMetricsInstruments();m&&(dl(m,d,u,a,e.getName(),n?.model?String(n.model):void 0),c>0&&ri(m,c,u,n?.maxRetries??10,a))}}async*streamingForward(e,t,n){let r=n?.cachingFunction??this.options?.cachingFunction??te.cachingFunction,o=(()=>{if(!r)return;let p=this.signature.getInputFields().map(d=>d.name);return this.computeCacheKey(t,p)})();if(r&&o){let p;try{p=await r(o)}catch{}if(p!==void 0){yield{version:0,index:0,delta:p};return}}if(!n?.resultPicker){yield*this._forward1(e,t,{...n,stream:!0});return}let i=this._forward1(e,t,{...n,stream:!0}),a=[],l=0;for await(let p of i)p.version!==l&&(a=[]),l=p.version,a=fi(a,p);let u=await No(a,{resultPicker:n?.resultPicker},n?.mem,n?.sessionId),c=a[u];if(c){if(r&&o)try{await r(o,c.delta)}catch{}yield{version:l,index:u,delta:c.delta}}}setExamples(e,t){super.setExamples(e,t)}isDebug(e,t){return t?.debug??this.options?.debug??!1}getLogger(e,t){return t?.logger??this.options?.logger??te.logger??e.getLogger()}computeCacheKey(e,t){let n=Je("sha256");n.update(this.signature.hash()??"");let r=o=>{let i=typeof o;if(n.update(`|${i}|`),o==null){n.update("null");return}if(i==="string"||i==="number"||i==="boolean"){n.update(String(o));return}if(Array.isArray(o)){n.update("[");for(let a of o)r(a);n.update("]");return}if(typeof o=="object"&&o!==null&&"mimeType"in o&&"data"in o){let a=o;n.update(a.mimeType??"");let l=Je("sha256").update(a.data??"").digest("hex");n.update(l);return}if(typeof o=="object"){let a=o,l=Object.keys(a).sort();for(let u of l)n.update(`{${u}}`),r(a[u]);return}n.update(String(o))};if(Array.isArray(e))for(let o of e){n.update(`role:${o.role}`);let i=t.map(a=>o.values?.[a]);for(let a of i)r(a)}else{let o=t.map(i=>e?.[i]);for(let i of o)r(i)}return n.digest("hex")}},gr=class extends Error{details;constructor(e,t,n){super(e),this.name="AxGenerateError",this.details=t,n?.cause&&(this.cause=n.cause)}toJSON(){let e=this.cause;return{name:this.name,message:this.message,details:this.details,cause:e?{name:e.name,message:e.message,stack:e.stack}:void 0,stack:this.stack}}};function Oi(s,e,t){let n=s instanceof Error?s:new Error(String(s)),r=(n.message||"").toLowerCase();if(r.includes("at least")||r.includes("at most")||r.includes("must match pattern")||r.includes("invalid url")||r.includes("required")||r.includes("missing")||r.includes("valid email")||r.includes("number must be")||n.name==="ValidationError"||n.name==="AssertionError"||n.name==="AxAssertionError"||n.stack?.includes("asserts.ts"))return n;let i=e.getLastUsedChatModel(),a=e.getLastUsedModelConfig(),l={model:i,maxTokens:a?.maxTokens,streaming:a?.stream??!1,signature:{input:t.getInputFields(),output:t.getOutputFields(),description:t.getDescription()}};return new gr(`Generate failed: ${n.message}`,l,{cause:n})}var cp=s=>s.replace(/^\W+|\W+$/g,""),pp=(s,e)=>{let t=s.search(e);if(t===-1)return[s];let n=s.match(e);if(!n)throw new Error("Match failed unexpectedly.");let r=s.substring(0,t),o=s.substring(t+n[0].length);return[r,o]},dp=s=>{let e=new Set,t=[];for(let n of s)e.has(n)||(e.add(n),t.push(n));return t},mp=s=>{let e=s.match(/^(\d+)[.,\s]+(.*)$/);if(!e||e.length<3)throw new Error('line must start with a number, a dot and then text. e.g. "1. hello"');let t=Number.parseInt(e[1],10),n=e[2].trim();return{id:t,text:n}},gp=s=>{let e=s.match(/^(\d+)[.,\s]+(.*)$/);return e&&e[2]!==void 0?e[2].trim():s},hp=(s,e)=>{let t=[];for(let n=0;n<s.length;n+=e)t.push(s.slice(n,n+e));return t},Lo={trimNonAlphaNum:cp,splitIntoTwo:pp,dedup:dp,extractIdAndText:mp,extractIndexPrefixedText:gp,batchArray:hp};var Go=class extends Ce{constructor(e){super(`"You are a re-ranker assistant tasked with evaluating a set of content items in relation to a specific question. Your role involves critically analyzing each content item to determine its relevance to the question and re-ranking them accordingly. This process includes assigning a relevance score from 0 to 10 to each content item based on how well it answers the question, its coverage of the topic, and the reliability of its information. This re-ranked list should start with the content item that is most relevant to the question and end with the least relevant. Output only the list."
291
- query: string, items: string[] -> rankedItems: string[] "list of id, 5-words Rationale, relevance score"`,e)}forward=async(e,t,n)=>{let{rankedItems:r}=await super.forward(e,t,n),o=r.map(a=>{let{id:l}=Lo.extractIdAndText(a);return l});return{rankedItems:t.items.map((a,l)=>{let u=o[l];return u!==void 0?t.items[u]:void 0}).filter(a=>a!==void 0)}}};var Uo=class{tikaUrl;fetch;constructor(e){let t=e??{url:"http://localhost:9998/"};this.tikaUrl=new URL("/tika",t.url),this.fetch=t.fetch}async _convert(e,t){if(!e)throw new Error("Failed to read file data");let n=t?.format==="html"?"text/html":"text/plain";try{let r={body:e,headers:{Accept:n},method:"PUT"};typeof window>"u"&&typeof process<"u"&&(r.duplex="half");let o=await(this.fetch??fetch)(this.tikaUrl,r);if(!o.ok)throw new Error(`Failed to upload file: ${o.statusText}`);return await o.text()}catch(r){throw new Error(`Error converting file: ${r}`)}}async convert(e,t){let n=[],r=t?.batchSize??10;for(let o=0;o<e.length;o+=r){let a=e.slice(o,o+r).map(u=>this._convert(u,{format:t?.format})),l=await Promise.all(a);n.push(...l)}return n}};var yA=new Ge,Bo=class{name;context;constructor(e,t){this.name=e,this.context=t}getName(){return this.name}getContext(){return this.context}},jo=class{ai;db;debug;constructor(e){this.db=new Ot,this.ai=e}getState(){return this.db.getDB()}setState(e){this.db.setDB(e)}setClasses=async(e,t)=>{for(let n of e){let r=await this.ai.embed({texts:n.getContext()},{abortSignal:t?.abortSignal});await this.db.upsert({id:n.getName(),table:"classes",values:r.embeddings[0]})}};async forward(e,t){let{embeddings:n}=await this.ai.embed({texts:[e]},{abortSignal:t?.abortSignal}),o=(await this.db.query({table:"classes",values:n[0]})).matches;if(typeof t?.cutoff=="number"){let{cutoff:a}=t;o=o.filter(l=>l.score<=a)}let i=o.at(0);return i?i.id:""}setOptions(e){typeof e.debug=="boolean"&&(this.debug=e.debug)}};var lu=new Set(["0o","0s","3a","3b","3d","6b","6o","a","a1","a2","a3","a4","ab","able","about","above","abst","ac","accordance","according","accordingly","across","act","actually","ad","added","adj","ae","af","affected","affecting","affects","after","afterwards","ag","again","against","ah","ain","ain't","aj","al","all","allow","allows","almost","alone","along","already","also","although","always","am","among","amongst","amoungst","amount","an","and","announce","another","any","anybody","anyhow","anymore","anyone","anything","anyway","anyways","anywhere","ao","ap","apart","apparently","appear","appreciate","appropriate","approximately","ar","are","aren","arent","aren't","arise","around","as","a's","aside","ask","asking","associated","at","au","auth","av","available","aw","away","awfully","ax","ay","az","b","b1","b2","b3","ba","back","bc","bd","be","became","because","become","becomes","becoming","been","before","beforehand","begin","beginning","beginnings","begins","behind","being","believe","below","beside","besides","best","better","between","beyond","bi","bill","biol","bj","bk","bl","bn","both","bottom","bp","br","brief","briefly","bs","bt","bu","but","bx","by","c","c1","c2","c3","ca","call","came","can","cannot","cant","can't","cause","causes","cc","cd","ce","certain","certainly","cf","cg","ch","changes","ci","cit","cj","cl","clearly","cm","c'mon","cn","co","com","come","comes","con","concerning","consequently","consider","considering","contain","containing","contains","corresponding","could","couldn","couldnt","couldn't","course","cp","cq","cr","cry","cs","c's","ct","cu","currently","cv","cx","cy","cz","d","d2","da","date","dc","dd","de","definitely","describe","described","despite","detail","df","di","did","didn","didn't","different","dj","dk","dl","do","does","doesn","doesn't","doing","don","done","don't","down","downwards","dp","dr","ds","dt","du","due","during","dx","dy","e","e2","e3","ea","each","ec","ed","edu","ee","ef","effect","eg","ei","eight","eighty","either","ej","el","eleven","else","elsewhere","em","empty","en","end","ending","enough","entirely","eo","ep","eq","er","es","especially","est","et","et-al","etc","eu","ev","even","ever","every","everybody","everyone","everything","everywhere","ex","exactly","example","except","ey","f","f2","fa","far","fc","few","ff","fi","fifteen","fifth","fify","fill","find","fire","first","five","fix","fj","fl","fn","fo","followed","following","follows","for","former","formerly","forth","forty","found","four","fr","from","front","ft","fu","full","further","furthermore","fy","g","ga","gave","ge","get","gets","getting","gi","give","given","gives","giving","gj","gl","go","goes","going","gone","got","gotten","gr","greetings","gs","gy","h","h2","h3","had","hadn","hadn't","happens","hardly","has","hasn","hasnt","hasn't","have","haven","haven't","having","he","hed","he'd","he'll","hello","help","hence","her","here","hereafter","hereby","herein","heres","here's","hereupon","hers","herself","hes","he's","hh","hi","hid","him","himself","his","hither","hj","ho","home","hopefully","how","howbeit","however","how's","hr","hs","http","hu","hundred","hy","i","i2","i3","i4","i6","i7","i8","ia","ib","ibid","ic","id","i'd","ie","if","ig","ignored","ih","ii","ij","il","i'll","im","i'm","immediate","immediately","importance","important","in","inasmuch","inc","indeed","index","indicate","indicated","indicates","information","inner","insofar","instead","interest","into","invention","inward","io","ip","iq","ir","is","isn","isn't","it","itd","it'd","it'll","its","it's","itself","iv","i've","ix","iy","iz","j","jj","jr","js","jt","ju","just","k","ke","keep","keeps","kept","kg","kj","km","know","known","knows","ko","l","l2","la","largely","last","lately","later","latter","latterly","lb","lc","le","least","les","less","lest","let","lets","let's","lf","like","liked","likely","line","little","lj","ll","ll","ln","lo","look","looking","looks","los","lr","ls","lt","ltd","m","m2","ma","made","mainly","make","makes","many","may","maybe","me","mean","means","meantime","meanwhile","merely","mg","might","mightn","mightn't","mill","million","mine","miss","ml","mn","mo","more","moreover","most","mostly","move","mr","mrs","ms","mt","mu","much","mug","must","mustn","mustn't","my","myself","model","n","n2","na","name","namely","nay","nc","nd","ne","near","nearly","necessarily","necessary","need","needn","needn't","needs","neither","never","nevertheless","new","next","ng","ni","nine","ninety","nj","nl","nn","no","nobody","non","none","nonetheless","noone","nor","normally","nos","not","noted","nothing","novel","now","nowhere","nr","ns","nt","ny","o","oa","ob","obtain","obtained","obviously","oc","od","of","off","often","og","oh","oi","oj","ok","okay","ol","old","om","omitted","on","once","one","ones","only","onto","oo","op","oq","or","ord","os","ot","other","others","otherwise","ou","ought","our","ours","ourselves","out","outside","over","overall","ow","owing","own","ox","oz","p","p1","p2","p3","page","pagecount","pages","par","part","particular","particularly","pas","past","pc","pd","pe","per","perhaps","pf","ph","pi","pj","pk","pl","placed","please","plus","pm","pn","po","poorly","possible","possibly","potentially","pp","pq","pr","predominantly","present","presumably","previously","primarily","probably","promptly","proud","provides","ps","pt","pu","put","py","q","qj","qu","que","quickly","quite","qv","r","r2","ra","ran","rather","rc","rd","re","readily","really","reasonably","recent","recently","ref","refs","regarding","regardless","regards","related","relatively","research","research-articl","respectively","resulted","resulting","results","rf","rh","ri","right","rj","rl","rm","rn","ro","rq","rr","rs","rt","ru","run","rv","ry","s","s2","sa","said","same","saw","say","saying","says","sc","sd","se","sec","second","secondly","section","see","seeing","seem","seemed","seeming","seems","seen","self","selves","sensible","sent","serious","seriously","seven","several","sf","shall","shan","shan't","she","shed","she'd","she'll","shes","she's","should","shouldn","shouldn't","should've","show","showed","shown","showns","shows","si","side","significant","significantly","similar","similarly","since","sincere","six","sixty","sj","sl","slightly","sm","sn","so","some","somebody","somehow","someone","somethan","something","sometime","sometimes","somewhat","somewhere","soon","sorry","sp","specifically","specified","specify","specifying","sq","sr","ss","st","still","stop","strongly","sub","substantially","successfully","such","sufficiently","suggest","sup","sure","sy","system","sz","t","t1","t2","t3","take","taken","taking","tb","tc","td","te","tell","ten","tends","tf","th","than","thank","thanks","thanx","that","that'll","thats","that's","that've","the","their","theirs","them","themselves","then","thence","there","thereafter","thereby","thered","therefore","therein","there'll","thereof","therere","theres","there's","thereto","thereupon","there've","these","they","theyd","they'd","they'll","theyre","they're","they've","thickv","thin","think","third","this","thorough","thoroughly","those","thou","though","thoughh","thousand","three","throug","through","throughout","thru","thus","ti","til","tip","tj","tl","tm","tn","to","together","too","took","top","toward","towards","tp","tq","tr","tried","tries","truly","try","trying","ts","t's","tt","tv","twelve","twenty","twice","two","tx","u","u201d","ue","ui","uj","uk","um","un","under","unfortunately","unless","unlike","unlikely","until","unto","uo","up","upon","ups","ur","us","use","used","useful","usefully","usefulness","uses","using","usually","ut","v","va","value","various","vd","ve","ve","very","via","viz","vj","vo","vol","vols","volumtype","vq","vs","vt","vu","w","wa","want","wants","was","wasn","wasnt","wasn't","way","we","wed","we'd","welcome","well","we'll","well-b","went","were","we're","weren","werent","weren't","we've","what","whatever","what'll","whats","what's","when","whence","whenever","when's","where","whereafter","whereas","whereby","wherein","wheres","where's","whereupon","wherever","whether","which","while","whim","whither","who","whod","whoever","whole","who'll","whom","whomever","whos","who's","whose","why","why's","wi","widely","will","willing","wish","with","within","without","wo","won","wonder","wont","won't","words","world","would","wouldn","wouldnt","wouldn't","www","x","x1","x2","x3","xf","xi","xj","xk","xl","xn","xo","xs","xt","xv","xx","y","y2","yes","yet","yj","yl","you","youd","you'd","you'll","your","youre","you're","yours","yourself","yourselves","you've","yr","ys","yt","z","zero","zi","zz","task"]);function uu(s,e){return s.filter(t=>!e.has(t))}function cu(s){let e={};for(let t of s)e[t]=(e[t]||0)+1;return e}function Dt(s){let e=s.normalize("NFD");return e=e.replace(/\b(a|an|the)\b/g," "),e=e.split(/\s+/).join(" "),e=e.replace(/[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]/g,""),e.toLowerCase()}function fp(s,e){return Dt(s)===Dt(e)?1:0}function xp(s,e){let t=Dt(s).split(" "),n=Dt(e).split(" "),r=cu(t),o=cu(n),i=0;for(let u in r){let c=r[u]??0,p=o[u]??0;i+=Math.min(c,p)}if(i===0)return 0;let a=i/t.length,l=i/n.length;return 2*a*l/(a+l)}function Ap(s,e,t,n=!1){let r=Dt(s).split(" "),o=Dt(e).split(" "),i=Dt(t).split(" "),a=new Set([...lu,...r]);o=uu(o,a),i=uu(i,a);let l=0,u=l/o.length,c=l/i.length,p=2*u*c/(u+c);return n?c:p}var pu={emScore:fp,f1Score:xp,novelF1ScoreOptimized:Ap};var zo=class{ai;program;examples;constructor({ai:e,program:t,examples:n=[]}){if(n.length===0)throw new Error("No examples found");this.ai=e,this.program=t,this.examples=n}async run(e){let t=Date.now(),n=this.examples.length,r=0;for(let i=0;i<n;i++){let a=this.examples[i];if(!a)throw new Error("Invalid example");try{let l=await this.program.forward(this.ai,a,{maxRetries:1}),u=await e({prediction:l,example:a});r+=u}catch(l){console.warn(`Program evaluation failed for example ${i}: ${l instanceof Error?l.message:"Unknown error"}`)}}let o=n>0?r/n:0;this.ai.getOptions().debug&&console.log(`
297
+ `)}`),e,this.signature)}catch(v){let C=v,O=C instanceof Ve&&C.status>=500&&C.status<600,I=C instanceof Ge,P=C instanceof ot,_=C instanceof Ye;if((O||I||P||_)&&T<E){let N=this.isDebug(e,r),L=this.getLogger(e,r),te=Math.min(6e4,1e3*Math.pow(2,T));N&&L&&L({name:"Notification",id:"infrastructure-retry",value:`Infrastructure error (attempt ${T+1}/${E+1}): ${C.message}. Retrying in ${te}ms...`}),o?.addEvent("infrastructure.retry",{attempt:T+1,maxRetries:E,delay:te,errorType:C instanceof Ve?"status_error":C instanceof Ge?"network_error":C instanceof ot?"timeout_error":"stream_terminated",errorMessage:C.message}),await new Promise(de=>setTimeout(de,te));continue}throw v}}throw w&&Io(w,c,c,this.getSignatureName()),Mi(new Error(`Max steps reached: ${c}`),e,this.signature)}validateInputs(e){let t=this.signature.getInputFields();for(let n of t){if(n.isInternal)continue;let r=e[n.name];if(n.isOptional&&r===void 0)continue;let o=n.type;if(o&&(o.name==="url"&&Mt(r,n),o.name,o.name,(o.name==="string"||o.name==="code")&&Ze(r,n),o.name==="number"&&et(r,n),o.name==="object"&&o.fields&&typeof r=="object"&&r!==null&&this.validateObjectFields(r,o.fields,n.name),o.isArray&&Array.isArray(r)))for(let s=0;s<r.length;s++){let a=r[s];o.name==="string"||o.name==="code"?Ze(a,n):o.name==="number"?et(a,n):o.fields&&typeof a=="object"&&a!==null&&this.validateObjectFields(a,o.fields,`${n.name}[${s}]`)}}}validateObjectFields(e,t,n){for(let[r,o]of Object.entries(t)){let s=e[r];if(o.isOptional&&s===void 0)continue;let a={name:`${n}.${r}`,type:{name:o.type,isArray:o.isArray,options:o.options?[...o.options]:void 0,fields:o.fields,minLength:o.minLength,maxLength:o.maxLength,minimum:o.minimum,maximum:o.maximum,pattern:o.pattern,format:o.format},description:o.description,isOptional:o.isOptional};if(o.type==="string"||o.type==="code"?Ze(s,a):o.type==="number"?et(s,a):o.type==="object"&&o.fields&&typeof s=="object"&&s!==null&&this.validateObjectFields(s,o.fields,a.name),o.isArray&&Array.isArray(s))for(let l=0;l<s.length;l++){let u=s[l];o.type==="string"||o.type==="code"?Ze(u,a):o.type==="number"?et(u,a):o.fields&&typeof u=="object"&&u!==null&&this.validateObjectFields(u,o.fields,`${a.name}[${l}]`)}}}async*_forward1(e,t,n){(!Array.isArray(t)||!t.every(x=>"role"in x))&&this.validateInputs(t);let r=performance.now(),o=this.createStates(n.sampleCount??1),s=performance.now()-r,a=this.getMetricsInstruments();a&&To(a,"state_creation",s,this.getSignatureName());let l=n?.tracer??this.options?.tracer??e.getOptions().tracer,u=this.functions;if(n?.functions&&(u=Oo(n.functions,this.functions)),!l){yield*this._forward2(e,t,o,{...n,functions:u});return}let c=u?.map(x=>x.name).join(","),p={signature:JSON.stringify(this.signature.toJSON(),null,2),...this.examples?{examples:JSON.stringify(this.examples,null,2)}:{},...c?{provided_functions:c}:{},...n?.model?{model:n.model}:{},...n?.thinkingTokenBudget?{thinking_token_budget:n.thinkingTokenBudget}:{},...n?.showThoughts?{show_thoughts:n.showThoughts}:{},...n?.maxSteps?{max_steps:n.maxSteps}:{},...n?.maxRetries?{max_retries:n.maxRetries}:{}},d=this.traceLabel&&n.traceLabel?`${this.traceLabel} > ${n.traceLabel}`:n.traceLabel??this.traceLabel,m=d?`AxGen > ${d}`:"AxGen",g=l.startSpan(m,{kind:Be.SERVER,attributes:p}),h=vt.active(),f=Bn.setSpan(h,g);try{if(this.excludeContentFromTrace||g.addEvent("input",{content:JSON.stringify(t,null,2)}),yield*this._forward2(e,t,o,{...n,functions:u},g,f),!this.excludeContentFromTrace){let x=o.map(y=>y.values),A=x.length===1?x[0]:x;g.addEvent("output",{content:JSON.stringify(A,null,2)})}}finally{g.end()}}async forward(e,t,n){let r=n?.cachingFunction??this.options?.cachingFunction??ee.cachingFunction,o=(()=>{if(!r)return;let d=this.signature.getInputFields().map(m=>m.name);return this.computeCacheKey(t,d)})();if(r&&o){let d=await r(o);if(d!==void 0)return d}let s=performance.now(),a=this.getSignatureName(),l=n?.stream??!1,u=!1,c=0,p=!1;try{let d=this.getMetricsInstruments();d&&Tl(d,this.signature.getInputFields().length,this.signature.getOutputFields().length,this.examples?.length??0,this.demos?.length??0,a);let m=this._forward1(e,t,n??{}),g=[],h=0,f=0;for await(let M of m)M.version!==h&&(g=[]),h=M.version,g=Ai(g,M),f++;c=h;let x=performance.now();p=!!n?.resultPicker;let A=await Do(g,{resultPicker:n?.resultPicker},n?.mem,n?.sessionId),y=performance.now()-x,S=g[A]?.delta??{},w=Array.isArray(t)?{}:t??{};if(this.trace={...w,...S},p&&this.isDebug(e,n)){let M=this.getLogger(e,n);ya(g.length,A,y,M)}if(u=!0,d&&(Il(d,g.length,p,p?y:void 0,a),bl(d,l,f,void 0,a)),r&&o)try{await r(o,S)}catch{}return S}catch(d){throw u=!1,d}finally{let d=performance.now()-s,m=this.getMetricsInstruments();m&&(fl(m,d,u,a,e.getName(),n?.model?String(n.model):void 0),c>0&&si(m,c,u,n?.maxRetries??10,a))}}async*streamingForward(e,t,n){let r=n?.cachingFunction??this.options?.cachingFunction??ee.cachingFunction,o=(()=>{if(!r)return;let p=this.signature.getInputFields().map(d=>d.name);return this.computeCacheKey(t,p)})();if(r&&o){let p;try{p=await r(o)}catch{}if(p!==void 0){yield{version:0,index:0,delta:p};return}}if(!n?.resultPicker){yield*this._forward1(e,t,{...n,stream:!0});return}let s=this._forward1(e,t,{...n,stream:!0}),a=[],l=0;for await(let p of s)p.version!==l&&(a=[]),l=p.version,a=Ai(a,p);let u=await Do(a,{resultPicker:n?.resultPicker},n?.mem,n?.sessionId),c=a[u];if(c){if(r&&o)try{await r(o,c.delta)}catch{}yield{version:l,index:u,delta:c.delta}}}setExamples(e,t){super.setExamples(e,t)}isDebug(e,t){return t?.debug??this.options?.debug??!1}getLogger(e,t){return t?.logger??this.options?.logger??ee.logger??e.getLogger()}computeCacheKey(e,t){let n=De("sha256");n.update(this.signature.hash()??"");let r=o=>{let s=typeof o;if(n.update(`|${s}|`),o==null){n.update("null");return}if(s==="string"||s==="number"||s==="boolean"){n.update(String(o));return}if(Array.isArray(o)){n.update("[");for(let a of o)r(a);n.update("]");return}if(typeof o=="object"&&o!==null&&"mimeType"in o&&"data"in o){let a=o;n.update(a.mimeType??"");let l=De("sha256").update(a.data??"").digest("hex");n.update(l);return}if(typeof o=="object"){let a=o,l=Object.keys(a).sort();for(let u of l)n.update(`{${u}}`),r(a[u]);return}n.update(String(o))};if(Array.isArray(e))for(let o of e){n.update(`role:${o.role}`);let s=t.map(a=>o.values?.[a]);for(let a of s)r(a)}else{let o=t.map(s=>e?.[s]);for(let s of o)r(s)}return n.digest("hex")}},hr=class extends Error{details;constructor(e,t,n){super(e),this.name="AxGenerateError",this.details=t,n?.cause&&(this.cause=n.cause)}toJSON(){let e=this.cause;return{name:this.name,message:this.message,details:this.details,cause:e?{name:e.name,message:e.message,stack:e.stack}:void 0,stack:this.stack}}};function Mi(i,e,t){let n=i instanceof Error?i:new Error(String(i)),r=(n.message||"").toLowerCase();if(r.includes("at least")||r.includes("at most")||r.includes("must match pattern")||r.includes("invalid url")||r.includes("required")||r.includes("missing")||r.includes("valid email")||r.includes("number must be")||n.name==="ValidationError"||n.name==="AssertionError"||n.name==="AxAssertionError"||n.stack?.includes("asserts.ts"))return n;let s=e.getLastUsedChatModel(),a=e.getLastUsedModelConfig(),l={model:s,maxTokens:a?.maxTokens,streaming:a?.stream??!1,signature:{input:t.getInputFields(),output:t.getOutputFields(),description:t.getDescription()}};return new hr(`Generate failed: ${n.message}`,l,{cause:n})}var gp=i=>i.replace(/^\W+|\W+$/g,""),hp=(i,e)=>{let t=i.search(e);if(t===-1)return[i];let n=i.match(e);if(!n)throw new Error("Match failed unexpectedly.");let r=i.substring(0,t),o=i.substring(t+n[0].length);return[r,o]},fp=i=>{let e=new Set,t=[];for(let n of i)e.has(n)||(e.add(n),t.push(n));return t},xp=i=>{let e=i.match(/^(\d+)[.,\s]+(.*)$/);if(!e||e.length<3)throw new Error('line must start with a number, a dot and then text. e.g. "1. hello"');let t=Number.parseInt(e[1],10),n=e[2].trim();return{id:t,text:n}},Ap=i=>{let e=i.match(/^(\d+)[.,\s]+(.*)$/);return e&&e[2]!==void 0?e[2].trim():i},yp=(i,e)=>{let t=[];for(let n=0;n<i.length;n+=e)t.push(i.slice(n,n+e));return t},Lo={trimNonAlphaNum:gp,splitIntoTwo:hp,dedup:fp,extractIdAndText:xp,extractIndexPrefixedText:Ap,batchArray:yp};var Uo=class extends Ce{constructor(e){super(`"You are a re-ranker assistant tasked with evaluating a set of content items in relation to a specific question. Your role involves critically analyzing each content item to determine its relevance to the question and re-ranking them accordingly. This process includes assigning a relevance score from 0 to 10 to each content item based on how well it answers the question, its coverage of the topic, and the reliability of its information. This re-ranked list should start with the content item that is most relevant to the question and end with the least relevant. Output only the list."
298
+ query: string, items: string[] -> rankedItems: string[] "list of id, 5-words Rationale, relevance score"`,e)}forward=async(e,t,n)=>{let{rankedItems:r}=await super.forward(e,t,n),o=r.map(a=>{let{id:l}=Lo.extractIdAndText(a);return l});return{rankedItems:t.items.map((a,l)=>{let u=o[l];return u!==void 0?t.items[u]:void 0}).filter(a=>a!==void 0)}}};var Bo=class{tikaUrl;fetch;constructor(e){let t=e??{url:"http://localhost:9998/"};this.tikaUrl=new URL("/tika",t.url),this.fetch=t.fetch}async _convert(e,t){if(!e)throw new Error("Failed to read file data");let n=t?.format==="html"?"text/html":"text/plain";try{let r={body:e,headers:{Accept:n},method:"PUT"};typeof window>"u"&&typeof process<"u"&&(r.duplex="half");let o=await(this.fetch??fetch)(this.tikaUrl,r);if(!o.ok)throw new Error(`Failed to upload file: ${o.statusText}`);return await o.text()}catch(r){throw new Error(`Error converting file: ${r}`)}}async convert(e,t){let n=[],r=t?.batchSize??10;for(let o=0;o<e.length;o+=r){let a=e.slice(o,o+r).map(u=>this._convert(u,{format:t?.format})),l=await Promise.all(a);n.push(...l)}return n}};var wA=new Ue,jo=class{name;context;constructor(e,t){this.name=e,this.context=t}getName(){return this.name}getContext(){return this.context}},qo=class{ai;db;debug;constructor(e){this.db=new Ot,this.ai=e}getState(){return this.db.getDB()}setState(e){this.db.setDB(e)}setClasses=async(e,t)=>{for(let n of e){let r=await this.ai.embed({texts:n.getContext()},{abortSignal:t?.abortSignal});await this.db.upsert({id:n.getName(),table:"classes",values:r.embeddings[0]})}};async forward(e,t){let{embeddings:n}=await this.ai.embed({texts:[e]},{abortSignal:t?.abortSignal}),o=(await this.db.query({table:"classes",values:n[0]})).matches;if(typeof t?.cutoff=="number"){let{cutoff:a}=t;o=o.filter(l=>l.score<=a)}let s=o.at(0);return s?s.id:""}setOptions(e){typeof e.debug=="boolean"&&(this.debug=e.debug)}};var pu=new Set(["0o","0s","3a","3b","3d","6b","6o","a","a1","a2","a3","a4","ab","able","about","above","abst","ac","accordance","according","accordingly","across","act","actually","ad","added","adj","ae","af","affected","affecting","affects","after","afterwards","ag","again","against","ah","ain","ain't","aj","al","all","allow","allows","almost","alone","along","already","also","although","always","am","among","amongst","amoungst","amount","an","and","announce","another","any","anybody","anyhow","anymore","anyone","anything","anyway","anyways","anywhere","ao","ap","apart","apparently","appear","appreciate","appropriate","approximately","ar","are","aren","arent","aren't","arise","around","as","a's","aside","ask","asking","associated","at","au","auth","av","available","aw","away","awfully","ax","ay","az","b","b1","b2","b3","ba","back","bc","bd","be","became","because","become","becomes","becoming","been","before","beforehand","begin","beginning","beginnings","begins","behind","being","believe","below","beside","besides","best","better","between","beyond","bi","bill","biol","bj","bk","bl","bn","both","bottom","bp","br","brief","briefly","bs","bt","bu","but","bx","by","c","c1","c2","c3","ca","call","came","can","cannot","cant","can't","cause","causes","cc","cd","ce","certain","certainly","cf","cg","ch","changes","ci","cit","cj","cl","clearly","cm","c'mon","cn","co","com","come","comes","con","concerning","consequently","consider","considering","contain","containing","contains","corresponding","could","couldn","couldnt","couldn't","course","cp","cq","cr","cry","cs","c's","ct","cu","currently","cv","cx","cy","cz","d","d2","da","date","dc","dd","de","definitely","describe","described","despite","detail","df","di","did","didn","didn't","different","dj","dk","dl","do","does","doesn","doesn't","doing","don","done","don't","down","downwards","dp","dr","ds","dt","du","due","during","dx","dy","e","e2","e3","ea","each","ec","ed","edu","ee","ef","effect","eg","ei","eight","eighty","either","ej","el","eleven","else","elsewhere","em","empty","en","end","ending","enough","entirely","eo","ep","eq","er","es","especially","est","et","et-al","etc","eu","ev","even","ever","every","everybody","everyone","everything","everywhere","ex","exactly","example","except","ey","f","f2","fa","far","fc","few","ff","fi","fifteen","fifth","fify","fill","find","fire","first","five","fix","fj","fl","fn","fo","followed","following","follows","for","former","formerly","forth","forty","found","four","fr","from","front","ft","fu","full","further","furthermore","fy","g","ga","gave","ge","get","gets","getting","gi","give","given","gives","giving","gj","gl","go","goes","going","gone","got","gotten","gr","greetings","gs","gy","h","h2","h3","had","hadn","hadn't","happens","hardly","has","hasn","hasnt","hasn't","have","haven","haven't","having","he","hed","he'd","he'll","hello","help","hence","her","here","hereafter","hereby","herein","heres","here's","hereupon","hers","herself","hes","he's","hh","hi","hid","him","himself","his","hither","hj","ho","home","hopefully","how","howbeit","however","how's","hr","hs","http","hu","hundred","hy","i","i2","i3","i4","i6","i7","i8","ia","ib","ibid","ic","id","i'd","ie","if","ig","ignored","ih","ii","ij","il","i'll","im","i'm","immediate","immediately","importance","important","in","inasmuch","inc","indeed","index","indicate","indicated","indicates","information","inner","insofar","instead","interest","into","invention","inward","io","ip","iq","ir","is","isn","isn't","it","itd","it'd","it'll","its","it's","itself","iv","i've","ix","iy","iz","j","jj","jr","js","jt","ju","just","k","ke","keep","keeps","kept","kg","kj","km","know","known","knows","ko","l","l2","la","largely","last","lately","later","latter","latterly","lb","lc","le","least","les","less","lest","let","lets","let's","lf","like","liked","likely","line","little","lj","ll","ll","ln","lo","look","looking","looks","los","lr","ls","lt","ltd","m","m2","ma","made","mainly","make","makes","many","may","maybe","me","mean","means","meantime","meanwhile","merely","mg","might","mightn","mightn't","mill","million","mine","miss","ml","mn","mo","more","moreover","most","mostly","move","mr","mrs","ms","mt","mu","much","mug","must","mustn","mustn't","my","myself","model","n","n2","na","name","namely","nay","nc","nd","ne","near","nearly","necessarily","necessary","need","needn","needn't","needs","neither","never","nevertheless","new","next","ng","ni","nine","ninety","nj","nl","nn","no","nobody","non","none","nonetheless","noone","nor","normally","nos","not","noted","nothing","novel","now","nowhere","nr","ns","nt","ny","o","oa","ob","obtain","obtained","obviously","oc","od","of","off","often","og","oh","oi","oj","ok","okay","ol","old","om","omitted","on","once","one","ones","only","onto","oo","op","oq","or","ord","os","ot","other","others","otherwise","ou","ought","our","ours","ourselves","out","outside","over","overall","ow","owing","own","ox","oz","p","p1","p2","p3","page","pagecount","pages","par","part","particular","particularly","pas","past","pc","pd","pe","per","perhaps","pf","ph","pi","pj","pk","pl","placed","please","plus","pm","pn","po","poorly","possible","possibly","potentially","pp","pq","pr","predominantly","present","presumably","previously","primarily","probably","promptly","proud","provides","ps","pt","pu","put","py","q","qj","qu","que","quickly","quite","qv","r","r2","ra","ran","rather","rc","rd","re","readily","really","reasonably","recent","recently","ref","refs","regarding","regardless","regards","related","relatively","research","research-articl","respectively","resulted","resulting","results","rf","rh","ri","right","rj","rl","rm","rn","ro","rq","rr","rs","rt","ru","run","rv","ry","s","s2","sa","said","same","saw","say","saying","says","sc","sd","se","sec","second","secondly","section","see","seeing","seem","seemed","seeming","seems","seen","self","selves","sensible","sent","serious","seriously","seven","several","sf","shall","shan","shan't","she","shed","she'd","she'll","shes","she's","should","shouldn","shouldn't","should've","show","showed","shown","showns","shows","si","side","significant","significantly","similar","similarly","since","sincere","six","sixty","sj","sl","slightly","sm","sn","so","some","somebody","somehow","someone","somethan","something","sometime","sometimes","somewhat","somewhere","soon","sorry","sp","specifically","specified","specify","specifying","sq","sr","ss","st","still","stop","strongly","sub","substantially","successfully","such","sufficiently","suggest","sup","sure","sy","system","sz","t","t1","t2","t3","take","taken","taking","tb","tc","td","te","tell","ten","tends","tf","th","than","thank","thanks","thanx","that","that'll","thats","that's","that've","the","their","theirs","them","themselves","then","thence","there","thereafter","thereby","thered","therefore","therein","there'll","thereof","therere","theres","there's","thereto","thereupon","there've","these","they","theyd","they'd","they'll","theyre","they're","they've","thickv","thin","think","third","this","thorough","thoroughly","those","thou","though","thoughh","thousand","three","throug","through","throughout","thru","thus","ti","til","tip","tj","tl","tm","tn","to","together","too","took","top","toward","towards","tp","tq","tr","tried","tries","truly","try","trying","ts","t's","tt","tv","twelve","twenty","twice","two","tx","u","u201d","ue","ui","uj","uk","um","un","under","unfortunately","unless","unlike","unlikely","until","unto","uo","up","upon","ups","ur","us","use","used","useful","usefully","usefulness","uses","using","usually","ut","v","va","value","various","vd","ve","ve","very","via","viz","vj","vo","vol","vols","volumtype","vq","vs","vt","vu","w","wa","want","wants","was","wasn","wasnt","wasn't","way","we","wed","we'd","welcome","well","we'll","well-b","went","were","we're","weren","werent","weren't","we've","what","whatever","what'll","whats","what's","when","whence","whenever","when's","where","whereafter","whereas","whereby","wherein","wheres","where's","whereupon","wherever","whether","which","while","whim","whither","who","whod","whoever","whole","who'll","whom","whomever","whos","who's","whose","why","why's","wi","widely","will","willing","wish","with","within","without","wo","won","wonder","wont","won't","words","world","would","wouldn","wouldnt","wouldn't","www","x","x1","x2","x3","xf","xi","xj","xk","xl","xn","xo","xs","xt","xv","xx","y","y2","yes","yet","yj","yl","you","youd","you'd","you'll","your","youre","you're","yours","yourself","yourselves","you've","yr","ys","yt","z","zero","zi","zz","task"]);function du(i,e){return i.filter(t=>!e.has(t))}function mu(i){let e={};for(let t of i)e[t]=(e[t]||0)+1;return e}function Dt(i){let e=i.normalize("NFD");return e=e.replace(/\b(a|an|the)\b/g," "),e=e.split(/\s+/).join(" "),e=e.replace(/[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]/g,""),e.toLowerCase()}function bp(i,e){return Dt(i)===Dt(e)?1:0}function Ip(i,e){let t=Dt(i).split(" "),n=Dt(e).split(" "),r=mu(t),o=mu(n),s=0;for(let u in r){let c=r[u]??0,p=o[u]??0;s+=Math.min(c,p)}if(s===0)return 0;let a=s/t.length,l=s/n.length;return 2*a*l/(a+l)}function Tp(i,e,t,n=!1){let r=Dt(i).split(" "),o=Dt(e).split(" "),s=Dt(t).split(" "),a=new Set([...pu,...r]);o=du(o,a),s=du(s,a);let l=0,u=l/o.length,c=l/s.length,p=2*u*c/(u+c);return n?c:p}var gu={emScore:bp,f1Score:Ip,novelF1ScoreOptimized:Tp};var zo=class{ai;program;examples;constructor({ai:e,program:t,examples:n=[]}){if(n.length===0)throw new Error("No examples found");this.ai=e,this.program=t,this.examples=n}async run(e){let t=Date.now(),n=this.examples.length,r=0;for(let s=0;s<n;s++){let a=this.examples[s];if(!a)throw new Error("Invalid example");try{let l=await this.program.forward(this.ai,a,{maxRetries:1}),u=await e({prediction:l,example:a});r+=u}catch(l){console.warn(`Program evaluation failed for example ${s}: ${l instanceof Error?l.message:"Unknown error"}`)}}let o=n>0?r/n:0;this.ai.getOptions().debug&&console.log(`
292
299
  Performance: `,r,"/",n,"Average Score: ",o,`
293
- `)}};function qo(s){return s.map(e=>{let t=e.type?.name??"string",n=e.description?`: ${e.description}`:"";return`- ${e.name} (${t})${n}`}).join(`
294
- `)}function yp(s,e){if(s===e)return!0;if(typeof s!=typeof e)return!1;if(typeof s=="object"&&s!==null&&e!==null){let t=JSON.stringify(s),n=JSON.stringify(e);return t===n}return!1}function bp(s){return s==null?!1:!!(typeof s=="string"||typeof s=="number"||typeof s=="boolean"||Array.isArray(s)&&s.every(e=>typeof e!="object"))}var Tn=class{signature;options;constructor(e,t){this.signature=e,this.options={ai:t.ai,randomizeOrder:t.randomizeOrder??!0,model:t.model,criteria:t.criteria}}async evaluate(e,t,n){return n&&bp(n)?this.runAbsolute(t,n):n?this.runRelativistic(e,t,n):this.runReferenceFree(e,t)}async runAbsolute(e,t){let n=this.signature.getOutputFields(),r=0,o=0,i=[];for(let u of n){let c=e[u.name],p=t[u.name];p!==void 0&&(o++,yp(c,p)?r++:i.push(`${u.name}: expected "${p}", got "${c}"`))}let a=o>0?r/o:0,l=a===1?"All fields match expected values exactly.":`Mismatches found: ${i.join("; ")}`;return{score:a,reasoning:l,mode:"absolute"}}async runRelativistic(e,t,n){let r=this.signature.getDescription(),o=this.signature.getInputFields(),i=this.signature.getOutputFields(),a=this.options.randomizeOrder?Math.random()>.5:!0,l=a?t:n,u=a?n:t,c=`
300
+ `)}};function Ho(i){return i.map(e=>{let t=e.type?.name??"string",n=e.description?`: ${e.description}`:"";return`- ${e.name} (${t})${n}`}).join(`
301
+ `)}function Cp(i,e){if(i===e)return!0;if(typeof i!=typeof e)return!1;if(typeof i=="object"&&i!==null&&e!==null){let t=JSON.stringify(i),n=JSON.stringify(e);return t===n}return!1}function wp(i){return i==null?!1:!!(typeof i=="string"||typeof i=="number"||typeof i=="boolean"||Array.isArray(i)&&i.every(e=>typeof e!="object"))}var Tn=class{signature;options;constructor(e,t){this.signature=e,this.options={ai:t.ai,randomizeOrder:t.randomizeOrder??!0,model:t.model,criteria:t.criteria}}async evaluate(e,t,n){return n&&wp(n)?this.runAbsolute(t,n):n?this.runRelativistic(e,t,n):this.runReferenceFree(e,t)}async runAbsolute(e,t){let n=this.signature.getOutputFields(),r=0,o=0,s=[];for(let u of n){let c=e[u.name],p=t[u.name];p!==void 0&&(o++,Cp(c,p)?r++:s.push(`${u.name}: expected "${p}", got "${c}"`))}let a=o>0?r/o:0,l=a===1?"All fields match expected values exactly.":`Mismatches found: ${s.join("; ")}`;return{score:a,reasoning:l,mode:"absolute"}}async runRelativistic(e,t,n){let r=this.signature.getDescription(),o=this.signature.getInputFields(),s=this.signature.getOutputFields(),a=this.options.randomizeOrder?Math.random()>.5:!0,l=a?t:n,u=a?n:t,c=`
295
302
  You are an impartial judge comparing two AI responses to the same input.
296
303
 
297
304
  **Task Description:** ${r||"Complete the task based on the input."}
298
305
 
299
306
  **Input Fields:**
300
- ${qo(o)}
307
+ ${Ho(o)}
301
308
 
302
309
  **Output Fields:**
303
- ${qo(i)}
310
+ ${Ho(s)}
304
311
 
305
312
  **Instructions:**
306
313
  1. Carefully analyze both Response A and Response B
@@ -316,7 +323,7 @@ ${qo(i)}
316
323
  ->
317
324
  winner:class "A, B, Tie" "Which response is better",
318
325
  reasoning:string "Detailed explanation for the decision"
319
- `);p.setInstruction(c);let d=await p.forward(this.options.ai,{input:JSON.stringify(e),response_a:JSON.stringify(l),response_b:JSON.stringify(u)},{model:this.options.model}),m,g,f=d.winner.toUpperCase();return f==="A"?m=a?"student":"teacher":f==="B"?m=a?"teacher":"student":m="tie",m==="student"?g=1:m==="tie"?g=.5:g=0,{score:g,reasoning:d.reasoning,mode:"relativistic",winner:m}}async runReferenceFree(e,t){let n=this.signature.getDescription(),r=this.signature.getInputFields(),o=this.signature.getOutputFields(),i=this.options.criteria||`
326
+ `);p.setInstruction(c);let d=await p.forward(this.options.ai,{input:JSON.stringify(e),response_a:JSON.stringify(l),response_b:JSON.stringify(u)},{model:this.options.model}),m,g,h=d.winner.toUpperCase();return h==="A"?m=a?"student":"teacher":h==="B"?m=a?"teacher":"student":m="tie",m==="student"?g=1:m==="tie"?g=.5:g=0,{score:g,reasoning:d.reasoning,mode:"relativistic",winner:m}}async runReferenceFree(e,t){let n=this.signature.getDescription(),r=this.signature.getInputFields(),o=this.signature.getOutputFields(),s=this.options.criteria||`
320
327
  Based on the task description and output requirements:
321
328
  - Accuracy: Is the response factually correct and complete?
322
329
  - Relevance: Does it address the input appropriately?
@@ -328,13 +335,13 @@ You are evaluating the quality of an AI response.
328
335
  **Task Description:** ${n||"Complete the task based on the input."}
329
336
 
330
337
  **Input Fields:**
331
- ${qo(r)}
338
+ ${Ho(r)}
332
339
 
333
340
  **Output Fields:**
334
- ${qo(o)}
341
+ ${Ho(o)}
335
342
 
336
343
  **Evaluation Criteria:**
337
- ${i}
344
+ ${s}
338
345
 
339
346
  **Quality Tiers:**
340
347
  - excellent: Exceptional response that fully addresses all criteria with high quality
@@ -350,14 +357,14 @@ First explain your reasoning, then classify the response into one of the quality
350
357
  ->
351
358
  reasoning:string "Detailed explanation for the quality assessment",
352
359
  quality:class "excellent, good, acceptable, poor, unacceptable" "Quality tier"
353
- `);l.setInstruction(a);let u=await l.forward(this.options.ai,{input:JSON.stringify(e),response:JSON.stringify(t)},{model:this.options.model}),c={excellent:1,good:.8,acceptable:.5,poor:.2,unacceptable:0},p=u.quality.toLowerCase();return{score:c[p]??.5,reasoning:u.reasoning,mode:"reference-free",qualityTier:p}}toMetricFn(){return async e=>{let{example:t,prediction:n}=e,r={};for(let u of this.signature.getInputFields())u.name in t&&(r[u.name]=t[u.name]);let o={},i=!1;for(let u of this.signature.getOutputFields())u.name in t&&(o[u.name]=t[u.name],i=!0);let a=n;return(await this.evaluate(r,a,i?o:void 0)).score}}getSignature(){return this.signature}};function du(){let s=Date.now().toString(36),e=Math.random().toString(36).substring(2,8);return`trace-${s}-${e}`}var Cn=class s{gen;options;constructor(e,t){this.gen=e,this.options={name:t.name,storage:t.storage,logInputs:t.logInputs??!0,logOutputs:t.logOutputs??!0,metadata:t.metadata,onTrace:t.onTrace,throwOnError:t.throwOnError??!1}}async*streamingForward(e,t,n){let r=du(),o=new Date,i,a;try{let l=this.gen.streamingForward(e,t,n);for await(let u of l)u.partial?i=u.partial:u.delta,yield u}catch(l){throw a=l instanceof Error?l.message:String(l),l}finally{let l=new Date,u=l.getTime()-o.getTime(),c={type:"trace",id:r,name:this.options.name,input:this.options.logInputs?t:{},output:this.options.logOutputs&&i?i:{},startTime:o,endTime:l,durationMs:u,model:n?.model??void 0,metadata:this.options.metadata,error:a};this.saveTrace(c)}}async forward(e,t,n){let r=du(),o=new Date,i,a;try{return i=await this.gen.forward(e,t,n),i}catch(l){throw a=l instanceof Error?l.message:String(l),l}finally{let l=new Date,u=l.getTime()-o.getTime(),c={type:"trace",id:r,name:this.options.name,input:this.options.logInputs?t:{},output:this.options.logOutputs&&i?i:{},startTime:o,endTime:l,durationMs:u,model:n?.model??void 0,metadata:this.options.metadata,error:a};this.saveTrace(c)}}async saveTrace(e){try{await this.options.storage.save(this.options.name,e),this.options.onTrace&&this.options.onTrace(e)}catch(t){if(this.options.throwOnError)throw t;console.warn("AxTraceLogger: Failed to save trace:",t)}}getGen(){return this.gen}getName(){return this.options.name}getStorage(){return this.options.storage}setMetadata(e){this.options.metadata=e}clone(e){return new s(e??this.gen.clone(),{name:this.options.name,storage:this.options.storage,logInputs:this.options.logInputs,logOutputs:this.options.logOutputs,metadata:this.options.metadata,onTrace:this.options.onTrace,throwOnError:this.options.throwOnError})}};var mu=s=>{console.log(s)},ki=(s=mu)=>{let e=new Ge,t=e.gray("\u2500".repeat(50)),n=e.gray("\u2501".repeat(50));return r=>{let o="";switch(r.name){case"OptimizationStart":o=`
360
+ `);l.setInstruction(a);let u=await l.forward(this.options.ai,{input:JSON.stringify(e),response:JSON.stringify(t)},{model:this.options.model}),c={excellent:1,good:.8,acceptable:.5,poor:.2,unacceptable:0},p=u.quality.toLowerCase();return{score:c[p]??.5,reasoning:u.reasoning,mode:"reference-free",qualityTier:p}}toMetricFn(){return async e=>{let{example:t,prediction:n}=e,r={};for(let u of this.signature.getInputFields())u.name in t&&(r[u.name]=t[u.name]);let o={},s=!1;for(let u of this.signature.getOutputFields())u.name in t&&(o[u.name]=t[u.name],s=!0);let a=n;return(await this.evaluate(r,a,s?o:void 0)).score}}getSignature(){return this.signature}};function hu(){let i=Date.now().toString(36),e=Math.random().toString(36).substring(2,8);return`trace-${i}-${e}`}var Cn=class i{gen;options;constructor(e,t){this.gen=e,this.options={name:t.name,storage:t.storage,logInputs:t.logInputs??!0,logOutputs:t.logOutputs??!0,metadata:t.metadata,onTrace:t.onTrace,throwOnError:t.throwOnError??!1}}async*streamingForward(e,t,n){let r=hu(),o=new Date,s,a;try{let l=this.gen.streamingForward(e,t,n);for await(let u of l)u.partial?s=u.partial:u.delta,yield u}catch(l){throw a=l instanceof Error?l.message:String(l),l}finally{let l=new Date,u=l.getTime()-o.getTime(),c={type:"trace",id:r,name:this.options.name,input:this.options.logInputs?t:{},output:this.options.logOutputs&&s?s:{},startTime:o,endTime:l,durationMs:u,model:n?.model??void 0,metadata:this.options.metadata,error:a};this.saveTrace(c)}}async forward(e,t,n){let r=hu(),o=new Date,s,a;try{return s=await this.gen.forward(e,t,n),s}catch(l){throw a=l instanceof Error?l.message:String(l),l}finally{let l=new Date,u=l.getTime()-o.getTime(),c={type:"trace",id:r,name:this.options.name,input:this.options.logInputs?t:{},output:this.options.logOutputs&&s?s:{},startTime:o,endTime:l,durationMs:u,model:n?.model??void 0,metadata:this.options.metadata,error:a};this.saveTrace(c)}}async saveTrace(e){try{await this.options.storage.save(this.options.name,e),this.options.onTrace&&this.options.onTrace(e)}catch(t){if(this.options.throwOnError)throw t;console.warn("AxTraceLogger: Failed to save trace:",t)}}getGen(){return this.gen}getName(){return this.options.name}getStorage(){return this.options.storage}setMetadata(e){this.options.metadata=e}clone(e){return new i(e??this.gen.clone(),{name:this.options.name,storage:this.options.storage,logInputs:this.options.logInputs,logOutputs:this.options.logOutputs,metadata:this.options.metadata,onTrace:this.options.onTrace,throwOnError:this.options.throwOnError})}};var fu=i=>{console.log(i)},Ei=(i=fu)=>{let e=new Ue,t=e.gray("\u2500".repeat(50)),n=e.gray("\u2501".repeat(50));return r=>{let o="";switch(r.name){case"OptimizationStart":o=`
354
361
  ${e.blueBright("\u25CF ")}${e.whiteBright("Optimization Started")}
355
362
  ${t}
356
363
  ${e.white("Optimizer:")} ${e.cyan(r.value.optimizerType)}
357
364
  ${e.white("Examples:")} ${e.green(r.value.exampleCount.toString())} training, ${e.green(r.value.validationCount.toString())} validation
358
365
  ${e.white("Config:")} ${e.white(JSON.stringify(r.value.config).slice(0,80))}${JSON.stringify(r.value.config).length>80?"...":""}
359
366
  ${n}
360
- `;break;case"RoundProgress":{let i=r.value.configuration||{},a=[];i.temperature!==void 0&&typeof i.temperature=="number"&&a.push(`T=${i.temperature.toFixed(2)}`),i.bootstrappedDemos!==void 0&&a.push(`demos=${i.bootstrappedDemos}`),Object.entries(i).forEach(([p,d])=>{p!=="temperature"&&p!=="bootstrappedDemos"&&p!=="trialNumber"&&typeof d=="number"&&a.push(`${p}=${d.toFixed(2)}`)});let l=r.value.currentScore-r.value.bestScore,u=l>0?e.greenBright(` \u2191${l.toFixed(3)}`):l<0?e.red(` \u2193${Math.abs(l).toFixed(3)}`):"",c=typeof r.value.totalRounds=="number"&&r.value.totalRounds>0?r.value.totalRounds:typeof i.totalRounds=="number"&&i.totalRounds>0?i.totalRounds:0;o=`${e.yellow("\u25CF ")}${e.whiteBright(`Round ${r.value.round}/${c}`)}`+(i.trialNumber!==void 0?e.gray(` [Trial #${i.trialNumber}]`):"")+`
367
+ `;break;case"RoundProgress":{let s=r.value.configuration||{},a=[];s.temperature!==void 0&&typeof s.temperature=="number"&&a.push(`T=${s.temperature.toFixed(2)}`),s.bootstrappedDemos!==void 0&&a.push(`demos=${s.bootstrappedDemos}`),Object.entries(s).forEach(([p,d])=>{p!=="temperature"&&p!=="bootstrappedDemos"&&p!=="trialNumber"&&typeof d=="number"&&a.push(`${p}=${d.toFixed(2)}`)});let l=r.value.currentScore-r.value.bestScore,u=l>0?e.greenBright(` \u2191${l.toFixed(3)}`):l<0?e.red(` \u2193${Math.abs(l).toFixed(3)}`):"",c=typeof r.value.totalRounds=="number"&&r.value.totalRounds>0?r.value.totalRounds:typeof s.totalRounds=="number"&&s.totalRounds>0?s.totalRounds:0;o=`${e.yellow("\u25CF ")}${e.whiteBright(`Round ${r.value.round}/${c}`)}`+(s.trialNumber!==void 0?e.gray(` [Trial #${s.trialNumber}]`):"")+`
361
368
  ${e.white("Score:")} ${e.green(r.value.currentScore.toFixed(3))} ${e.white("(best:")} ${e.greenBright(r.value.bestScore.toFixed(3))}${e.white(")")}${u}
362
369
  `+(a.length>0?` ${e.white("Config:")} ${e.cyan(a.join(", "))}
363
370
  `:"")}break;case"EarlyStopping":o=`
@@ -367,15 +374,15 @@ ${t}
367
374
  ${e.white("Reason:")} ${e.yellow(r.value.reason)}
368
375
  ${e.white("Final Score:")} ${e.green(r.value.finalScore.toFixed(3))}
369
376
  ${n}
370
- `;break;case"OptimizationComplete":{let i="";r.value.explanation&&(i+=`
377
+ `;break;case"OptimizationComplete":{let s="";r.value.explanation&&(s+=`
371
378
  ${e.blueBright("\u{1F4CA} Summary:")}
372
379
  ${e.white(r.value.explanation)}
373
- `),r.value.performanceAssessment&&(i+=`
380
+ `),r.value.performanceAssessment&&(s+=`
374
381
  ${e.yellowBright("\u26A1 Performance:")}
375
382
  ${e.white(r.value.performanceAssessment)}
376
- `),r.value.recommendations&&r.value.recommendations.length>0&&(i+=`
383
+ `),r.value.recommendations&&r.value.recommendations.length>0&&(s+=`
377
384
  ${e.greenBright("\u{1F4A1} Recommendations:")}
378
- `,r.value.recommendations.forEach((a,l)=>{i+=` ${e.white(`${l+1}.`)} ${e.white(a)}
385
+ `,r.value.recommendations.forEach((a,l)=>{s+=` ${e.white(`${l+1}.`)} ${e.white(a)}
379
386
  `})),o=`
380
387
  ${e.green("\u25CF ")}${e.whiteBright("Optimization Complete")}
381
388
  ${t}
@@ -383,9 +390,9 @@ ${t}
383
390
  ${e.white("Best Config:")} ${e.cyan(JSON.stringify(r.value.bestConfiguration).slice(0,80))}${JSON.stringify(r.value.bestConfiguration).length>80?"...":""}
384
391
  ${e.white("Total Calls:")} ${e.white(r.value.stats?.totalCalls?.toString()||"N/A")}
385
392
  ${e.white("Success Rate:")} ${e.green(`${((r.value.stats?.successfulDemos||0)/Math.max(r.value.stats?.totalCalls||1,1)*100).toFixed(1)}%`)}
386
- `+i+`${n}
393
+ `+s+`${n}
387
394
  `}break;case"ConfigurationProposal":o=`${e.magenta("\u25CF ")}${e.whiteBright(`${r.value.type} Proposals`)} ${e.white(`(${r.value.count})`)}
388
- ${e.white("Candidates:")} ${e.white(r.value.proposals.slice(0,2).map(i=>typeof i=="string"?`"${i.slice(0,40)}..."`:`${JSON.stringify(i).slice(0,40)}...`).join(", "))}
395
+ ${e.white("Candidates:")} ${e.white(r.value.proposals.slice(0,2).map(s=>typeof s=="string"?`"${s.slice(0,40)}..."`:`${JSON.stringify(s).slice(0,40)}...`).join(", "))}
389
396
  `;break;case"BootstrappedDemos":o=`${e.cyan("\u25CF ")}${e.whiteBright("Bootstrapped Demos")} ${e.white(`(${r.value.count})`)}
390
397
  ${e.white("Generated:")} ${e.green(r.value.count.toString())} demonstration examples
391
398
  `;break;case"BestConfigFound":o=`${e.green("\u25CF ")}${e.whiteBright("Best Configuration Found")}
@@ -393,7 +400,7 @@ ${t}
393
400
  ${e.white("Config:")} ${e.cyan(JSON.stringify(r.value.config).slice(0,80))}${JSON.stringify(r.value.config).length>80?"...":""}
394
401
  `;break;default:o=`${e.red("\u25CF ")}${e.whiteBright("Unknown Event")}
395
402
  ${e.white(JSON.stringify(r).slice(0,100))}${JSON.stringify(r).length>100?"...":""}
396
- `}s(o)}},gu=(s=mu)=>{let e="\u2500".repeat(60);return t=>{let n="";switch(t.name){case"OptimizationStart":n=`[ OPTIMIZATION START: ${t.value.optimizerType} ]
403
+ `}i(o)}},xu=(i=fu)=>{let e="\u2500".repeat(60);return t=>{let n="";switch(t.name){case"OptimizationStart":n=`[ OPTIMIZATION START: ${t.value.optimizerType} ]
397
404
  ${e}
398
405
  Config: ${JSON.stringify(t.value.config,null,2)}
399
406
  Examples: ${t.value.exampleCount}, Validation: ${t.value.validationCount}
@@ -419,72 +426,72 @@ Score: ${t.value.score.toFixed(3)}
419
426
  Config: ${JSON.stringify(t.value.config)}
420
427
  ${e}`;break;default:n=`[ UNKNOWN OPTIMIZER EVENT ]
421
428
  ${JSON.stringify(t)}
422
- ${e}`}s(n)}},hr=ki();var Mi={enabled:!0,enabledCategories:["optimization","convergence","resource_usage","teacher_student","checkpointing","pareto"],maxLabelLength:100,samplingRate:1},Ho,Ip=s=>{if(Ho)return Ho;if(s)return Ho=Tp(s),Ho};var Ko=Mi,hu=s=>{Ko={...Ko,...s}},fu=()=>({...Ko}),Tp=s=>({optimizationLatencyHistogram:s.createHistogram("ax_optimizer_optimization_duration_ms",{description:"End-to-end duration of optimization runs",unit:"ms"}),optimizationRequestsCounter:s.createCounter("ax_optimizer_optimization_requests_total",{description:"Total number of optimization requests"}),optimizationErrorsCounter:s.createCounter("ax_optimizer_optimization_errors_total",{description:"Total number of failed optimizations"}),convergenceRoundsHistogram:s.createHistogram("ax_optimizer_convergence_rounds",{description:"Number of rounds until convergence"}),convergenceScoreGauge:s.createGauge("ax_optimizer_convergence_score",{description:"Current best score during optimization"}),convergenceImprovementGauge:s.createGauge("ax_optimizer_convergence_improvement",{description:"Improvement in score from baseline"}),stagnationRoundsGauge:s.createGauge("ax_optimizer_stagnation_rounds",{description:"Number of rounds without improvement"}),earlyStoppingCounter:s.createCounter("ax_optimizer_early_stopping_total",{description:"Total number of early stopping events"}),tokenUsageCounter:s.createCounter("ax_optimizer_token_usage_total",{description:"Total tokens used during optimization"}),costUsageCounter:s.createCounter("ax_optimizer_cost_usage_total",{description:"Total cost incurred during optimization",unit:"$"}),memoryUsageGauge:s.createGauge("ax_optimizer_memory_usage_bytes",{description:"Peak memory usage during optimization",unit:"By"}),optimizationDurationHistogram:s.createHistogram("ax_optimizer_duration_ms",{description:"Duration of optimization runs",unit:"ms"}),teacherStudentUsageCounter:s.createCounter("ax_optimizer_teacher_student_usage_total",{description:"Total number of teacher-student interactions"}),teacherStudentLatencyHistogram:s.createHistogram("ax_optimizer_teacher_student_latency_ms",{description:"Latency of teacher-student interactions",unit:"ms"}),teacherStudentScoreImprovementGauge:s.createGauge("ax_optimizer_teacher_student_score_improvement",{description:"Score improvement from teacher-student interactions"}),checkpointSaveCounter:s.createCounter("ax_optimizer_checkpoint_save_total",{description:"Total number of checkpoint saves"}),checkpointLoadCounter:s.createCounter("ax_optimizer_checkpoint_load_total",{description:"Total number of checkpoint loads"}),checkpointSaveLatencyHistogram:s.createHistogram("ax_optimizer_checkpoint_save_latency_ms",{description:"Latency of checkpoint save operations",unit:"ms"}),checkpointLoadLatencyHistogram:s.createHistogram("ax_optimizer_checkpoint_load_latency_ms",{description:"Latency of checkpoint load operations",unit:"ms"}),paretoOptimizationsCounter:s.createCounter("ax_optimizer_pareto_optimizations_total",{description:"Total number of Pareto optimizations"}),paretoFrontSizeHistogram:s.createHistogram("ax_optimizer_pareto_front_size",{description:"Size of Pareto frontier"}),paretoHypervolumeGauge:s.createGauge("ax_optimizer_pareto_hypervolume",{description:"Hypervolume of Pareto frontier"}),paretoSolutionsGeneratedHistogram:s.createHistogram("ax_optimizer_pareto_solutions_generated",{description:"Number of solutions generated for Pareto optimization"}),programInputFieldsGauge:s.createGauge("ax_optimizer_program_input_fields",{description:"Number of input fields in optimized program"}),programOutputFieldsGauge:s.createGauge("ax_optimizer_program_output_fields",{description:"Number of output fields in optimized program"}),examplesCountGauge:s.createGauge("ax_optimizer_examples_count",{description:"Number of training examples used"}),validationSetSizeGauge:s.createGauge("ax_optimizer_validation_set_size",{description:"Size of validation set used"}),evaluationLatencyHistogram:s.createHistogram("ax_optimizer_evaluation_latency_ms",{description:"Latency of program evaluations",unit:"ms"}),demoGenerationLatencyHistogram:s.createHistogram("ax_optimizer_demo_generation_latency_ms",{description:"Latency of demo generation",unit:"ms"}),metricComputationLatencyHistogram:s.createHistogram("ax_optimizer_metric_computation_latency_ms",{description:"Latency of metric computation",unit:"ms"}),optimizerTypeGauge:s.createGauge("ax_optimizer_type",{description:"Type of optimizer being used"}),targetScoreGauge:s.createGauge("ax_optimizer_target_score",{description:"Target score for optimization"}),maxRoundsGauge:s.createGauge("ax_optimizer_max_rounds",{description:"Maximum rounds for optimization"})}),ut=s=>{let e={};for(let[t,n]of Object.entries(s))if(n!=null){let r=String(n),o=Ko.maxLabelLength;e[t]=r.length>o?r.substring(0,o):r}return e},Cp=(s,e,t,n,r)=>{try{let o=ut({success:t.toString(),optimizer_type:n,...r?{program_signature:r}:{}});s.optimizationLatencyHistogram&&s.optimizationLatencyHistogram.record(e,o),s.optimizationRequestsCounter&&s.optimizationRequestsCounter.add(1,o),!t&&s.optimizationErrorsCounter&&s.optimizationErrorsCounter.add(1,o)}catch(o){console.warn("Failed to record optimization metric:",o)}},wp=(s,e,t,n,r,o)=>{try{let i=ut({optimizer_type:o});s.convergenceRoundsHistogram&&s.convergenceRoundsHistogram.record(e,i),s.convergenceScoreGauge&&s.convergenceScoreGauge.record(t,i),s.convergenceImprovementGauge&&s.convergenceImprovementGauge.record(n,i),s.stagnationRoundsGauge&&s.stagnationRoundsGauge.record(r,i)}catch(i){console.warn("Failed to record convergence metric:",i)}},Rp=(s,e,t)=>{try{let n=ut({reason:e,optimizer_type:t});s.earlyStoppingCounter&&s.earlyStoppingCounter.add(1,n)}catch(n){console.warn("Failed to record early stopping metric:",n)}},vp=(s,e,t,n,r)=>{try{let o=ut({optimizer_type:n});s.tokenUsageCounter&&s.tokenUsageCounter.add(e,o),s.costUsageCounter&&s.costUsageCounter.add(t,o),r!==void 0&&s.memoryUsageGauge&&s.memoryUsageGauge.record(r,o)}catch(o){console.warn("Failed to record resource usage metric:",o)}},Sp=(s,e,t)=>{try{let n=ut({optimizer_type:t});s.optimizationDurationHistogram&&s.optimizationDurationHistogram.record(e,n)}catch(n){console.warn("Failed to record optimization duration metric:",n)}},Op=(s,e,t,n)=>{try{let r=ut({optimizer_type:n});s.teacherStudentUsageCounter&&s.teacherStudentUsageCounter.add(1,r),s.teacherStudentLatencyHistogram&&s.teacherStudentLatencyHistogram.record(e,r),s.teacherStudentScoreImprovementGauge&&s.teacherStudentScoreImprovementGauge.record(t,r)}catch(r){console.warn("Failed to record teacher-student metric:",r)}},kp=(s,e,t,n,r)=>{try{let o=ut({operation:e,success:n.toString(),optimizer_type:r});e==="save"?(s.checkpointSaveCounter&&s.checkpointSaveCounter.add(1,o),s.checkpointSaveLatencyHistogram&&s.checkpointSaveLatencyHistogram.record(t,o)):(s.checkpointLoadCounter&&s.checkpointLoadCounter.add(1,o),s.checkpointLoadLatencyHistogram&&s.checkpointLoadLatencyHistogram.record(t,o))}catch(o){console.warn("Failed to record checkpoint metric:",o)}},Mp=(s,e,t,n,r)=>{try{let o=ut({optimizer_type:n});s.paretoOptimizationsCounter&&s.paretoOptimizationsCounter.add(1,o),s.paretoFrontSizeHistogram&&s.paretoFrontSizeHistogram.record(e,o),r!==void 0&&s.paretoHypervolumeGauge&&s.paretoHypervolumeGauge.record(r,o),s.paretoSolutionsGeneratedHistogram&&s.paretoSolutionsGeneratedHistogram.record(t,o)}catch(o){console.warn("Failed to record Pareto metric:",o)}},Ep=(s,e,t,n,r,o)=>{try{let i=ut({optimizer_type:o});s.programInputFieldsGauge&&s.programInputFieldsGauge.record(e,i),s.programOutputFieldsGauge&&s.programOutputFieldsGauge.record(t,i),s.examplesCountGauge&&s.examplesCountGauge.record(n,i),s.validationSetSizeGauge&&s.validationSetSizeGauge.record(r,i)}catch(i){console.warn("Failed to record program complexity metric:",i)}},Pp=(s,e,t,n)=>{try{let r=ut({metric_type:e,optimizer_type:n});switch(e){case"evaluation":s.evaluationLatencyHistogram&&s.evaluationLatencyHistogram.record(t,r);break;case"demo_generation":s.demoGenerationLatencyHistogram&&s.demoGenerationLatencyHistogram.record(t,r);break;case"metric_computation":s.metricComputationLatencyHistogram&&s.metricComputationLatencyHistogram.record(t,r);break}}catch(r){console.warn("Failed to record optimizer performance metric:",r)}},Fp=(s,e,t,n)=>{try{let r=ut({optimizer_type:e});s.optimizerTypeGauge&&s.optimizerTypeGauge.record(1,r),t!==void 0&&s.targetScoreGauge&&s.targetScoreGauge.record(t,r),n!==void 0&&s.maxRoundsGauge&&s.maxRoundsGauge.record(n,r)}catch(r){console.warn("Failed to record optimizer configuration metric:",r)}},mt=class{bestScore;stats;instruction;demos;examples;modelConfig;optimizerType;optimizationTime;totalRounds;converged;scoreHistory;configurationHistory;constructor(e){this.bestScore=e.bestScore,this.stats=e.stats,this.instruction=e.instruction,this.demos=e.demos,this.examples=e.examples,this.modelConfig=e.modelConfig,this.optimizerType=e.optimizerType,this.optimizationTime=e.optimizationTime,this.totalRounds=e.totalRounds,this.converged=e.converged,this.scoreHistory=e.scoreHistory,this.configurationHistory=e.configurationHistory}applyTo(e){this.demos&&this.demos.length>0&&e.setDemos(this.demos),this.examples&&this.examples.length>0&&e.setExamples(this.examples),this.instruction&&(e._optimizedInstruction=this.instruction),this.modelConfig&&(e._optimizedModelConfig=this.modelConfig)}},fr=class{tokenUsage={};totalTokens=0;costPerModel;maxCost;maxTokens;constructor(e){this.costPerModel=e?.costPerModel??{},this.maxCost=e?.maxCost,this.maxTokens=e?.maxTokens}trackTokens(e,t){this.tokenUsage[t]=(this.tokenUsage[t]||0)+e,this.totalTokens+=e}getCurrentCost(){let e=0;for(let[t,n]of Object.entries(this.tokenUsage)){let r=this.costPerModel[t]||.001;e+=n/1e3*r}return e}getTokenUsage(){return{...this.tokenUsage}}getTotalTokens(){return this.totalTokens}isLimitReached(){return this.maxTokens!==void 0&&this.totalTokens>=this.maxTokens||this.maxCost!==void 0&&this.getCurrentCost()>=this.maxCost}reset(){this.tokenUsage={},this.totalTokens=0}},je=class{studentAI;teacherAI;targetScore;minSuccessRate;onProgress;onEarlyStop;costTracker;seed;checkpointSave;checkpointLoad;checkpointInterval;resumeFromCheckpoint;logger;verbose;debugOptimizer;optimizerLogger;currentRound=0;scoreHistory=[];configurationHistory=[];stats;metricsInstruments;resultExplainer;constructor(e){this.studentAI=e.studentAI,this.teacherAI=e.teacherAI,this.targetScore=e.targetScore,this.minSuccessRate=e.minSuccessRate,this.onProgress=e.onProgress,this.onEarlyStop=e.onEarlyStop,this.seed=e.seed,this.checkpointSave=e.checkpointSave,this.checkpointLoad=e.checkpointLoad,this.checkpointInterval=e.checkpointInterval??10,this.resumeFromCheckpoint=e.resumeFromCheckpoint,this.logger=e.logger,this.verbose=e.verbose;let t=new fr({maxTokens:1e6});this.costTracker=e.costTracker??t,this.metricsInstruments=Ip(te.meter),this.stats=this.initializeStats(),this.debugOptimizer=e.debugOptimizer??!1,this.optimizerLogger=e.optimizerLogger??(this.verbose?hr:void 0),this.initializeResultExplainer()}initializeResultExplainer(){this.resultExplainer=void 0}initializeStats(){return{totalCalls:0,successfulDemos:0,estimatedTokenUsage:0,earlyStopped:!1,resourceUsage:{totalTokens:0,totalTime:0,avgLatencyPerEval:0,costByModel:{}},convergenceInfo:{converged:!1,finalImprovement:0,stagnationRounds:0,convergenceThreshold:.01},bestScore:0,bestConfiguration:{}}}setupRandomSeed(){this.seed!==void 0&&(Math.random=(()=>{let e=this.seed;return()=>(e=(e*9301+49297)%233280,e/233280)})())}checkCostLimits(){return this.costTracker?.isLimitReached()??!1}checkTargetScore(e){return this.targetScore!==void 0&&e>=this.targetScore}updateResourceUsage(e,t=0){this.stats.resourceUsage.totalTime=Date.now()-e,this.stats.resourceUsage.totalTokens+=t,this.stats.totalCalls>0&&(this.stats.resourceUsage.avgLatencyPerEval=this.stats.resourceUsage.totalTime/this.stats.totalCalls)}triggerEarlyStopping(e,t){this.stats.earlyStopped=!0,this.stats.earlyStopping={bestScoreRound:t,patienceExhausted:e.includes("improvement"),reason:e},this.recordEarlyStoppingMetrics(e,"unknown"),this.onEarlyStop&&this.onEarlyStop(e,this.stats),this.getOptimizerLogger()?.({name:"EarlyStopping",value:{reason:e,finalScore:this.stats.bestScore??0,round:t}})}validateExamples(e,t=!0){if(!e||e.length===0)throw new Error("At least 1 example is required for optimization");if(t&&e.length<2)throw new Error("At least 2 examples are required for optimization with auto-splitting. Provide more examples to enable proper train/validation split.");let n=t?10:5;e.length<n&&this.verbose&&console.warn(`[Ax Optimizer] Warning: Only ${e.length} examples provided. Consider providing more examples (${n}+ recommended) for better optimization results.`)}getAIService(e=!1,t){return e&&t?.overrideTeacherAI?t.overrideTeacherAI:e&&this.teacherAI?this.teacherAI:this.studentAI}hasTeacherAI(e){return e?.overrideTeacherAI!==void 0||this.teacherAI!==void 0}getTeacherOrStudentAI(e){return e?.overrideTeacherAI||this.teacherAI||this.studentAI}async executeWithTeacher(e,t=!0,n){let r=this.getAIService(t,n);return await e(r)}async*compileStream(e,t,n,r){let o=Date.now(),i=this.constructor.name,a=e.getSignature().toString();this.recordOptimizationStart(i,a);let l,u=(g,f,h,x,A,y,b,k={},S)=>{this.getOptimizerLogger(S)?.({name:"RoundProgress",value:{round:g,totalRounds:S?.maxIterations??0,currentScore:f,bestScore:y,configuration:h}}),this.updateOptimizationProgress(g,f,h,x,A,y,b,k,S)},c=(g,f)=>{l=g,this.triggerEarlyStopping(g,this.currentRound)},p=g=>{this.onProgress?.(g),u(g.round,g.currentScore,g.currentConfiguration||{},i,{},g.bestScore,g.bestConfiguration,g.convergenceInfo,r)},d=await this.compile(e,t,n,{...r,overrideOnProgress:p,overrideOnEarlyStop:c}),m=Date.now()-o;return this.recordOptimizationComplete(m,!0,i,a),l&&this.getLogger(r)?.({name:"Notification",id:"optimization_early_stop",value:`Optimization stopped early due to ${l}`}),{demos:d.demos,stats:d.stats,bestScore:d.bestScore,finalConfiguration:d.finalConfiguration,scoreHistory:d.scoreHistory,configurationHistory:d.configurationHistory}}async compilePareto(e,t,n,r){let o=this.constructor.name,i=Date.now(),a=await this.generateWeightedSolutions(e,t,n,r),l=await this.generateConstraintSolutions(e,t,n,r),u=[...a,...l],c=this.findParetoFrontier(u),p=this.calculateHypervolume(c);this.updateResourceUsage(i),this.stats.convergenceInfo.converged=!0,this.recordParetoMetrics(c.length,u.length,"base_optimizer",p);let d=c.length>0?Math.max(...c.map(m=>Math.max(...Object.values(m.scores)))):0;return{demos:c.length>0?[...c[0].demos]:void 0,stats:this.stats,bestScore:d,paretoFront:c,hypervolume:p,paretoFrontSize:c.length,finalConfiguration:{paretoFrontSize:c.length,hypervolume:p,strategy:"weighted_combinations_and_constraints",numSolutions:u.length}}}async generateWeightedSolutions(e,t,n,r){let o=[];if(!t||t.length===0)throw new Error("No examples provided for Pareto optimization");let i=t[0],a=await e.forward(this.getAIService(!1,r),i),l=await n({prediction:a,example:i}),u=Object.keys(l),c=this.generateWeightCombinations(u);for(let p=0;p<c.length;p++){let d=c[p],m=async({prediction:g,example:f})=>{let h=await n({prediction:g,example:f}),x=0;for(let[A,y]of Object.entries(h))x+=y*(d[A]||0);return x};try{let g=await this.compile(e,t,m,{...r,verbose:!1}),f=await this.evaluateWithMultiObjective(e,g,n,t);o.push({scores:f,demos:g.demos,configuration:{...g.finalConfiguration,weights:d,strategy:"weighted_combination"}})}catch{}}return o}async generateConstraintSolutions(e,t,n,r){let o=[];if(!t||t.length===0)throw new Error("No examples provided for multi-objective optimization");let i=t[0],a=await e.forward(this.getAIService(!1,r),i),l=await n({prediction:a,example:i}),u=Object.keys(l);for(let c of u){let p=async({prediction:d,example:m})=>{let g=await n({prediction:d,example:m}),f=g[c]||0,h=0;for(let[x,A]of Object.entries(g))x!==c&&A<.3&&(h+=(.3-A)*2);return f-h};try{let d=await this.compile(e,t,p,{...r,verbose:!1}),m=await this.evaluateWithMultiObjective(e,d,n,t);o.push({scores:m,demos:d.demos,configuration:{...d.finalConfiguration,primaryObjective:c,strategy:"constraint_based"}})}catch{}}return o}generateWeightCombinations(e){let t=[];for(let r of e){let o={};for(let i of e)o[i]=i===r?1:0;t.push(o)}let n={};for(let r of e)n[r]=1/e.length;if(t.push(n),e.length===2){let[r,o]=e;for(let i=.1;i<=.9;i+=.2){let a=1-i;t.push({[r]:i,[o]:a})}}if(e.length===3){let[r,o,i]=e;t.push({[r]:.5,[o]:.3,[i]:.2},{[r]:.3,[o]:.5,[i]:.2},{[r]:.2,[o]:.3,[i]:.5})}return t}async evaluateWithMultiObjective(e,t,n,r){let o=new Ce(e.getSignature());t.demos&&o.setDemos(t.demos);let i=[],a=Math.max(1,Math.min(5,Math.floor(r.length*.2))),l=r.slice(-a),u={},c=l;for(let d of c)try{let m=await o.forward(this.studentAI,d),g=await n({prediction:m,example:d});for(let[f,h]of Object.entries(g))u[f]||(u[f]=[]),u[f].push(h)}catch{}let p={};for(let[d,m]of Object.entries(u))p[d]=m.length>0?m.reduce((g,f)=>g+f,0)/m.length:0;return p}findParetoFrontier(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n],o=!1,i=0;for(let a=0;a<e.length;a++){if(n===a)continue;let l=e[a];if(this.dominates(l.scores,r.scores)){o=!0;break}this.dominates(r.scores,l.scores)&&i++}o||t.push({demos:r.demos||[],scores:r.scores,configuration:r.configuration,dominatedSolutions:i})}return t}dominates(e,t){let n=Object.keys(e),r=!0,o=!1;for(let i of n){let a=e[i]||0,l=t[i]||0;if(a<l){r=!1;break}a>l&&(o=!0)}return r&&o}calculateHypervolume(e){if(e.length===0)return;let t=e[0],n=Object.keys(t.scores);if(n.length===2){let[r,o]=n,i=0,a=[...e].sort((u,c)=>(c.scores[r]||0)-(u.scores[r]||0)),l=0;for(let u of a){let c=u.scores[r]||0,p=u.scores[o]||0;i+=c*(p-l),l=Math.max(l,p)}return i}}async saveCheckpoint(e,t,n,r,o={},i){let a=i?.overrideCheckpointSave||this.checkpointSave;if(!a)return;let l=Date.now(),u=!1,c;try{let p={version:"1.0.0",timestamp:Date.now(),optimizerType:e,optimizerConfig:t,currentRound:this.currentRound,totalRounds:this.stats.resourceUsage.totalTime>0?this.currentRound:0,bestScore:n,bestConfiguration:r,scoreHistory:[...this.scoreHistory],configurationHistory:[...this.configurationHistory],stats:{...this.stats},optimizerState:o,examples:[]};c=await a(p),u=!0}catch(p){throw u=!1,p}finally{let p=Date.now()-l;this.recordCheckpointMetrics("save",p,u,e)}return c}async loadCheckpoint(e,t){let n=t?.overrideCheckpointLoad||this.checkpointLoad;if(!n)return null;let r=Date.now(),o=!1,i=null;try{i=await n(e),o=i!==null}catch(a){throw o=!1,a}finally{let a=Date.now()-r;this.recordCheckpointMetrics("load",a,o,"unknown")}return i}restoreFromCheckpoint(e){this.currentRound=e.currentRound,this.scoreHistory=[...e.scoreHistory],this.configurationHistory=[...e.configurationHistory],this.stats={...e.stats}}shouldSaveCheckpoint(e,t){let n=t?.overrideCheckpointInterval||this.checkpointInterval;return n!==void 0&&e%n===0}async updateOptimizationProgress(e,t,n,r,o,i,a,l={},u){this.currentRound=e,this.scoreHistory.push(t),this.configurationHistory.push(n),this.shouldSaveCheckpoint(e,u)&&await this.saveCheckpoint(r,o,i,a,l,u),this.getOptimizerLogger(u)?.({name:"RoundProgress",value:{round:e,totalRounds:u?.maxIterations??0,currentScore:t,bestScore:i,configuration:n}})}async saveFinalCheckpoint(e,t,n,r,o={},i){i?.saveCheckpointOnComplete!==!1&&await this.saveCheckpoint(e,t,n,r,{...o,final:!0},i)}getLogger(e){if(this.isLoggingEnabled(e))return this.logger?this.logger:this.studentAI.getLogger()}isLoggingEnabled(e){return e?.verbose!==void 0?e.verbose:this.verbose??!0}recordOptimizationStart(e,t){if(this.metricsInstruments){if(t){let n=(t.match(/input:/g)||[]).length,r=(t.match(/output:/g)||[]).length;Ep(this.metricsInstruments,n,r,0,0,e)}Fp(this.metricsInstruments,e,this.targetScore,void 0)}}recordOptimizationComplete(e,t,n,r){if(!this.metricsInstruments)return;Cp(this.metricsInstruments,e,t,n,r),Sp(this.metricsInstruments,e,n);let o=this.costTracker?.getCurrentCost()??0,i=this.costTracker?.getTotalTokens()??0;vp(this.metricsInstruments,i,o,n)}recordConvergenceMetrics(e,t,n,r,o){this.metricsInstruments&&wp(this.metricsInstruments,e,t,n,r,o)}recordEarlyStoppingMetrics(e,t){this.metricsInstruments&&Rp(this.metricsInstruments,e,t)}recordTeacherStudentMetrics(e,t,n){this.metricsInstruments&&Op(this.metricsInstruments,e,t,n)}recordCheckpointMetrics(e,t,n,r){this.metricsInstruments&&kp(this.metricsInstruments,e,t,n,r)}recordParetoMetrics(e,t,n,r){this.metricsInstruments&&Mp(this.metricsInstruments,e,t,n,r)}recordPerformanceMetrics(e,t,n){this.metricsInstruments&&Pp(this.metricsInstruments,e,t,n)}isOptimizerLoggingEnabled(e){return this.debugOptimizer||(e?.verbose??this.verbose??!1)}getOptimizerLogger(e){if(this.isOptimizerLoggingEnabled(e))return this.optimizerLogger??te.optimizerLogger??hr}getStats(){return{...this.stats}}async explainOptimizationResults(e,t,n){let r=this.stats.convergenceInfo.converged,o=this.stats.totalCalls,i=o>0?this.stats.successfulDemos/o*100:0,a=`Optimization finished with best score ${e.toFixed(3)}${t?` using configuration ${JSON.stringify(t)}`:""}. Convergence: ${r?"yes":"no"}. Success rate: ${i.toFixed(1)}%.`,l=[];if(r||l.push("Increase numTrials or relax earlyStoppingTrials to allow further improvement."),typeof this.targetScore=="number"&&e<this.targetScore&&l.push("Tighten the metric or supply more/better-labeled examples to reach targetScore."),t&&"bootstrappedDemos"in t){let c=t.bootstrappedDemos;typeof c=="number"&&c===0&&l.push("Consider allowing a small number of bootstrapped demos to boost performance.")}l.length===0&&l.push("Re-run with more trials or different acquisition settings to explore more of the space.");let u=`Tokens used: ${this.stats.resourceUsage.totalTokens}, rounds: ${this.currentRound}, stagnationRounds: ${this.stats.convergenceInfo.stagnationRounds}.`;return{humanExplanation:a,recommendations:l,performanceAssessment:u}}async logOptimizationComplete(e,t,n,r,o){let i=this.getOptimizerLogger(r);i&&i(o?{name:"OptimizationComplete",value:{optimizerType:e,bestScore:t,bestConfiguration:n||{},totalCalls:this.stats.totalCalls,successRate:this.stats.totalCalls>0?`${(this.stats.successfulDemos/this.stats.totalCalls*100).toFixed(1)}%`:"N/A",explanation:o.humanExplanation,recommendations:o.recommendations,performanceAssessment:o.performanceAssessment,stats:this.stats}}:{name:"OptimizationComplete",value:{optimizerType:e,bestScore:t,bestConfiguration:n||{},totalCalls:this.stats.totalCalls,successRate:this.stats.totalCalls>0?`${(this.stats.successfulDemos/this.stats.totalCalls*100).toFixed(1)}%`:"N/A",stats:this.stats}})}reset(){this.stats=this.initializeStats(),this.costTracker?.reset(),this.currentRound=0,this.scoreHistory=[],this.configurationHistory=[]}};function xu(s){return be.create(s)}function _e(s,e){let t=typeof s=="string"?be.create(s):s;return new Ce(t,e)}function Au(s,e,t=0){let n=new Set([...Object.keys(s),...Object.keys(e)]),r=!0,o=!1;for(let i of n){let a=s[i]??0,l=e[i]??0;if(a+t<l){r=!1;break}a>l+t&&(o=!0)}return r&&o}function gt(s,e=0){let t=[];for(let n=0;n<s.length;n++){let r=0,o=!1;for(let i=0;i<s.length;i++)if(n!==i){if(Au(s[i].scores,s[n].scores,e)){o=!0;break}Au(s[n].scores,s[i].scores,e)&&r++}o||t.push({idx:s[n].idx,scores:s[n].scores,dominated:r})}return t}function tt(s){if(s.length===0)return;let e=Object.keys(s[0]??{});if(e.length!==2)return;let[t,n]=e,r=[...s].sort((a,l)=>(l[t]??0)-(a[t]??0)),o=0,i=0;for(let a of r){let l=a[t]??0,u=a[n]??0,c=Math.max(u-i,0);o+=l*c,i=Math.max(i,u)}return o}function Lt(s){if(s.length===0)return 0;let e=0;for(let t of s)e+=t;return e/s.length}function Vo(s){let e={},t={};for(let r of s)for(let[o,i]of Object.entries(r))e[o]=(e[o]||0)+(typeof i=="number"?i:0),t[o]=(t[o]||0)+1;let n={};for(let[r,o]of Object.entries(e))n[r]=o/Math.max(t[r]||1,1);return n}function xr(s,e){let t=new Set;for(let c of s)for(let p of c)t.add(p);let r=[...Array.from(t)].sort((c,p)=>(e[c]??0)-(e[p]??0)),o=new Set,i=(c,p)=>{for(let d of s){if(!d.has(c))continue;let m=!1;for(let g of p)if(d.has(g)){m=!0;break}if(!m)return!1}return!0},a=!0;for(;a;){a=!1;for(let c of r){if(o.has(c))continue;let p=new Set(r.filter(d=>d!==c&&!o.has(d)));if(i(c,p)){o.add(c),a=!0;break}}}let l=r.filter(c=>!o.has(c)),u=new Set(l);return s.map(c=>{let p=new Set;for(let d of c)u.has(d)&&p.add(d);return p})}function Ar(s,e,t){let n=xr(s,e),r={};for(let l of n)for(let u of l)r[u]=(r[u]||0)+1;let o=[];for(let[l,u]of Object.entries(r)){let c=Number(l);for(let p=0;p<u;p++)o.push(c)}if(o.length===0)return 0;let i=typeof t=="function"?t():Math.random(),a=Math.floor(i*o.length);return o[a]}var wn=class s extends je{numTrials;minibatch;minibatchSize;earlyStoppingTrials;minImprovementThreshold;sampleCount;paretoSetSize;crossoverEvery;tieEpsilon;feedbackMemorySize;feedbackMemory=[];mergeMax;mergesUsed=0;mergesDue=0;totalMergesTested=0;lastIterFoundNewProgram=!1;mergeAttemptKeys=new Set;mergeCompositionKeys=new Set;static REFLECTION_PROMPT_TEMPLATE="I provided an assistant with the following instructions to perform a task for me:\n```\n<curr_instructions>\n```\n\nThe following are examples of different task inputs provided to the assistant along with the assistant's response for each of them, and some feedback on how the assistant's response could be better:\n```\n<inputs_outputs_feedback>\n```\n\nYour task is to write a new instruction for the assistant. Read the inputs carefully and identify the input format and infer detailed task description about the task I wish to solve with the assistant. Read all the assistant responses and the corresponding feedback. Identify all niche and domain specific factual information about the task and include it in the instruction, as a lot of it may not be available to the assistant in the future. The assistant may have utilized a generalizable strategy to solve the task, if so, include that in the instruction as well. Provide the new instructions within ``` blocks.";rngState=123456789;samplerState={epoch:-1,shuffled:[],freq:new Map};localScoreHistory=[];localConfigurationHistory=[];constructor(e){super(e);let t=e?.seed,n=Number.isFinite(t)?Math.floor(Number(t)):0;this.rngState=n&&n!==0?n:123456789,this.numTrials=e.numTrials??30,this.minibatch=e.minibatch??!0,this.minibatchSize=e.minibatchSize??20,this.earlyStoppingTrials=e.earlyStoppingTrials??5,this.minImprovementThreshold=e.minImprovementThreshold??0,this.sampleCount=e.sampleCount??1;let r=e?.paretoSetSize;this.paretoSetSize=r&&r>0?Math.min(1e3,Math.max(5,Math.floor(r))):Math.max(10,Math.min(200,this.minibatchSize*3));let o=e?.crossoverEvery;this.crossoverEvery=Math.max(0,Math.floor(o??Math.max(3,Math.floor(this.numTrials/4))));let i=e?.tieEpsilon;this.tieEpsilon=Number.isFinite(i)?i:0;let a=e?.feedbackMemorySize;this.feedbackMemorySize=Math.max(0,Math.floor(a??4));let l=e?.mergeMax;this.mergeMax=Math.max(0,Math.floor(l??5)),this.mergesUsed=0,this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}reset(){super.reset(),this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold,this.localScoreHistory=[],this.localConfigurationHistory=[],this.feedbackMemory=[],this.mergesUsed=0,this.mergesDue=0,this.totalMergesTested=0,this.lastIterFoundNewProgram=!1,this.mergeAttemptKeys.clear(),this.mergeCompositionKeys.clear(),this.samplerState.epoch=-1,this.samplerState.shuffled=[],this.samplerState.freq.clear()}async compile(e,t,n,r){let o=Date.now();this.validateExamples(t),r?.auto&&this.configureAuto(r.auto);let i=r?.validationExamples,a=r?.feedbackExamples,l=(i&&i.length>0?i:t).slice(0,this.paretoSetSize),u=a&&a.length>0?a:t,c=async(C,E)=>{try{e.setInstruction?.(C);let _=await e.forward(this.studentAI,E,{sampleCount:this.sampleCount});return this.stats.totalCalls+=1,await n({prediction:_,example:E})||{}}catch{return{}}},p=async(C,E)=>{let _=[];for(let $ of E)_.push(await c(C,$));return Vo(_)},d=await this.getBaseInstruction(e),m=[{instruction:d,parent:void 0,scores:await p(d,l)}],g=C=>{let E=r?.paretoMetricKey,_=r?.paretoScalarize;if(typeof _=="function")return _(C);if(E)return Number.isFinite(C[E])?C[E]:0;let $=Object.values(C);return $.length?$.reduce((L,D)=>L+D,0)/$.length:0},f=[],h=async(C,E)=>{let _=[];for(let $ of E){let L=await c(C,$);_.push(g(L))}return _};f.push(await h(d,l));let x=()=>{let C=f[0]?.length??0,E=[];for(let $=0;$<C;$++){let L=Number.NEGATIVE_INFINITY,D=new Set;for(let q=0;q<f.length;q++){let H=f[q][$];H>L+this.tieEpsilon?(L=H,D.clear(),D.add(q)):Math.abs(H-L)<=this.tieEpsilon&&D.add(q)}E.push(D)}let _=f.map($=>Lt($));return Ar(E,_)},A=r?.maxMetricCalls;if(!Number.isFinite(A)||A<=0)throw new Error("AxGEPA: options.maxMetricCalls must be set to a positive integer");let y=Math.floor(A),b=this.getOptimizerLogger(r),k=r?.verbose??this.verbose?C=>console.log(`[GEPA] ${C}`):C=>{};b?.({name:"OptimizationStart",value:{optimizerType:"GEPA",exampleCount:t.length,validationCount:l.length,config:{numTrials:this.numTrials,minibatch:this.minibatch,mergeMax:this.mergeMax}}}),k(`Starting GEPA optimization: ${t.length} train, ${l.length} validation, maxCalls=${y}`);let S=0,M=gt(m.map((C,E)=>({idx:E,scores:C.scores})),this.tieEpsilon).map(C=>C.idx),R;for(let C=0;C<this.numTrials&&!(y!==void 0&&this.stats.totalCalls>=Math.max(1,Math.floor(y)));C++){let E=f[0]?.length??0,_=[];for(let U=0;U<E;U++){let z=Number.NEGATIVE_INFINITY,Q=new Set;for(let oe=0;oe<f.length;oe++){let G=f[oe][U];G>z+this.tieEpsilon?(z=G,Q.clear(),Q.add(oe)):Math.abs(G-z)<=this.tieEpsilon&&Q.add(oe)}_.push(Q)}let $=f.map(U=>Lt(U));if(this.mergeMax>0&&this.mergesDue>0&&this.lastIterFoundNewProgram){let U=N=>{let K=[],X=N;for(;X!==void 0;)K.push(X),X=m[X]?.parent;return K},z=N=>N.length?N[Math.floor(this.rand()*N.length)]:void 0,Q=xr(_,$),oe=new Set;for(let N of Q)for(let K of N)oe.add(K);let G=Array.from(oe),B;for(let N=0;N<10&&!B&&!(G.length<2);N++){let K=z(G),X=z(G);if(K===X)continue;X<K&&([K,X]=[X,K]);let me=new Set(U(K)),ee=new Set(U(X));if(me.has(X)||ee.has(K))continue;let se=[...me].filter(Me=>ee.has(Me));if(se.length===0)continue;let ae=se.map(Me=>Math.max(1e-9,$[Me])),pe=this.rand()*ae.reduce((Me,Ve)=>Me+Ve,0),Re=se[se.length-1];for(let Me=0;Me<se.length;Me++){if(pe<ae[Me]){Re=se[Me];break}pe-=ae[Me]}B={i:K,j:X,a:Re}}if(this.lastIterFoundNewProgram=!1,B){let{i:N,j:K,a:X}=B,me=$[X],ee=$[N],se=$[K],ae=m[X].instruction,pe=m[N].instruction,Re=m[K].instruction,Me=pe===ae&&Re!==pe||Re===ae&&pe!==Re,Ve=me<=Math.min(ee,se)&&Me,$e="",ze="i",de=!1;if(Ve){let ht=`${N}|${K}|${X}`;if(this.mergeAttemptKeys.has(ht))Ve=!1;else{pe===ae&&Re!==pe?($e=Re,ze="j"):Re===ae&&pe!==Re?($e=pe,ze="i"):pe!==ae&&Re!==ae&&pe!==Re?ee>se||ee===se&&this.rand()<.5?($e=pe,ze="i"):($e=Re,ze="j"):($e=pe,ze="i");let It=`${Math.min(N,K)}|${Math.max(N,K)}|${ze}`;if(this.mergeCompositionKeys.has(It))Ve=!1;else{this.mergeAttemptKeys.add(ht),this.mergeCompositionKeys.add(It);let nt=f[N],Tt=f[K],Ct=Array.from({length:nt.length},(le,Ne)=>Ne),ft=Ct.filter(le=>(nt[le]??0)>(Tt[le]??0)),wt=Ct.filter(le=>(Tt[le]??0)>(nt[le]??0)),Pt=Ct.filter(le=>!(ft.includes(le)||wt.includes(le))),J=5,Ie=Math.ceil(J/3),ct=(le,Ne)=>{if(Ne<=0||le.length===0)return[];if(le.length<=Ne)return[...le];let _n=[],vr=new Set;for(;_n.length<Ne;){let rt=Math.floor(this.rand()*le.length);vr.has(rt)||(vr.add(rt),_n.push(le[rt]))}return _n},qe=[];qe.push(...ct(ft,Math.min(Ie,ft.length))),qe.push(...ct(wt,Math.min(Ie,wt.length)));let He=J-qe.length;qe.push(...ct(Pt,Math.max(0,He)));let Rr=J-qe.length;if(Rr>0){let le=Ct.filter(Ne=>!qe.includes(Ne));qe.push(...ct(le,Math.min(Rr,le.length)))}let ls=qe.slice(0,Math.min(J,Ct.length)),Du=ls.map(le=>l[le]);de=!0;let Lu=(await h($e,Du)).reduce((le,Ne)=>le+Ne,0),Gu=ls.reduce((le,Ne)=>le+(nt[Ne]??0),0),Uu=ls.reduce((le,Ne)=>le+(Tt[Ne]??0),0);if(Lu>=Math.max(Gu,Uu)+this.tieEpsilon){k(`Iteration ${C+1}: Merge accepted (programs ${N} + ${K} via ancestor ${X})`);let le=await p($e,l);m.push({instruction:$e,parent:X,scores:le}),f.push(await h($e,l));let Ne=M.length,_n=tt(M.map(rt=>m[rt].scores))??0;M=gt(m.map((rt,Bu)=>({idx:Bu,scores:rt.scores})),this.tieEpsilon).map(rt=>rt.idx);let vr=tt(M.map(rt=>m[rt].scores))??0;(M.length>Ne||vr>_n+1e-6)&&(S=0),this.mergesDue-=1,this.totalMergesTested+=1}}}}if(de)continue}}let L=Ar(_,$,()=>this.rand()),D=this.minibatch?this.nextMinibatchIndices(u.length,C).map(U=>u[U]):u;if(r?.skipPerfectScore??!0){let U=Number(r?.perfectScore??1),z=await h(m[L].instruction,D);if(z.length>0&&z.every(Q=>Q>=U))continue}let q=!1,H=m[L].instruction,ce="reflective_mutation",ne,xe;if(q){let U=(L+1)%m.length;H=await this.mergeInstructions(m[L].instruction,m[U].instruction,r),ce="merge",this.mergesUsed+=1}else{let U=r?.gepaAdapter;if(U){try{let z={instruction:m[L].instruction},Q=await U.evaluate(D,z,!0);ne=Array.isArray(Q?.scores)?Q.scores.reduce((N,K)=>N+(Number(K)||0),0):void 0;let oe=U.make_reflective_dataset(z,Q,["instruction"]),G=await U.propose_new_texts?.(z,oe,["instruction"]),B=G?.instruction??(G?Object.values(G)[0]:void 0);typeof B=="string"&&B.length>0?H=B:H=await this.reflectInstruction(m[L].instruction,e,D,async({prediction:N,example:K})=>{let X=await n({prediction:N,example:K}),me=Object.values(X||{});return me.length?me.reduce((ee,se)=>ee+se,0)/me.length:0},r)}catch{H=await this.reflectInstruction(m[L].instruction,e,D,async({prediction:z,example:Q})=>{let oe=await n({prediction:z,example:Q}),G=Object.values(oe||{});return G.length?G.reduce((B,N)=>B+N,0)/G.length:0},r)}if(ne!==void 0)try{let z=await U.evaluate(D,{instruction:H},!1);xe=Array.isArray(z?.scores)?z.scores.reduce((Q,oe)=>Q+(Number(oe)||0),0):void 0}catch{}}else H=await this.reflectInstruction(m[L].instruction,e,D,async({prediction:z,example:Q})=>{let oe=await n({prediction:z,example:Q}),G=Object.values(oe||{});return G.length?G.reduce((B,N)=>B+N,0)/G.length:0},r)}let ye=await h(m[L].instruction,D),Z=await h(H,D),Ae=ye.reduce((U,z)=>U+z,0),ge=Z.reduce((U,z)=>U+z,0);if(this.currentRound=C+1,await this.updateOptimizationProgress(this.currentRound,ge,{instructionLen:H.length,parent:L,totalRounds:this.numTrials},"GEPA",{strategy:ce,paretoSetSize:l.length},ge,{instructionLen:m[L].instruction.length,idx:L},{...r??{},maxIterations:this.numTrials}),!(ge>Ae+this.tieEpsilon&&(ne===void 0||xe===void 0||xe>ne+this.tieEpsilon))){if(k(`Iteration ${C+1}: Rejected (child=${ge.toFixed(3)} <= parent=${Ae.toFixed(3)})`),++S>=this.earlyStoppingTrials){k(`Early stopping: ${S} iterations without improvement`);break}continue}k(`Iteration ${C+1}: Accepted (child=${ge.toFixed(3)} > parent=${Ae.toFixed(3)})`);let he=await p(H,l);m.push({instruction:H,parent:L,scores:he}),f.push(await h(H,l));let ve=M.length,V=tt(M.map(U=>m[U].scores))??0;M=gt(m.map((U,z)=>({idx:z,scores:U.scores})),this.tieEpsilon).map(U=>U.idx);let re=tt(M.map(U=>m[U].scores))??0;if(M.length>ve||re>V+1e-6)S=0,k(`Iteration ${C+1}: Archive improved (size=${M.length}, hv=${re.toFixed(4)})`);else if(S++,k(`Iteration ${C+1}: Archive unchanged (stagnation=${S}/${this.earlyStoppingTrials})`),S>=this.earlyStoppingTrials){k(`Early stopping: ${S} iterations without archive improvement`);break}this.lastIterFoundNewProgram=!0,this.mergeMax>0&&this.totalMergesTested<this.mergeMax&&(this.mergesDue+=1)}let O=gt(m.map((C,E)=>({idx:E,scores:C.scores})),this.tieEpsilon),F=O.length>0?Math.max(...O.map(C=>g(C.scores))):0,P;if(O.length>0){let C=Number.NEGATIVE_INFINITY;for(let E of O){let _=g(E.scores);_>C&&(C=_,P=E.idx)}}let I=tt(O.map(C=>C.scores));this.stats.convergenceInfo.converged=!0,this.recordParetoMetrics(O.length,m.length,"GEPA",I);let v=Date.now()-o,T=typeof P=="number"?new mt({bestScore:F,stats:this.stats,instruction:m[P].instruction,demos:[],examples:t,modelConfig:void 0,optimizerType:"GEPA",optimizationTime:v,totalRounds:this.numTrials,converged:this.stats.convergenceInfo.converged}):void 0,w=this.generateOptimizationReport(O,I,F);return{demos:[],stats:this.stats,bestScore:F,paretoFront:O.map(C=>({demos:[],scores:C.scores,configuration:{candidate:C.idx,instruction:m[C.idx].instruction},dominatedSolutions:C.dominated})),paretoFrontSize:O.length,hypervolume:I,finalConfiguration:{strategy:"gepa",candidates:m.length},optimizedProgram:T,report:w}}configureAuto(e){switch(e){case"light":this.numTrials=10,this.minibatch=!0,this.minibatchSize=15;break;case"medium":this.numTrials=20,this.minibatch=!0,this.minibatchSize=25;break;case"heavy":this.numTrials=35,this.minibatch=!0,this.minibatchSize=35;break}}async getBaseInstruction(e){let t=e.getInstruction?.();if(t&&t.length>0)return t;let r=e.getSignature?.()?.getDescription?.();return r&&r.length>0?r:"Follow the task precisely. Be concise, correct, and consistent."}async evaluateOnSet(e,t,n,r){let o=[];for(let i of n){let a=await this.evaluateOne(e,t,i,r);o.push(a)}return o}async evaluateAvg(e,t,n,r){let o=await this.evaluateOnSet(e,t,n,r);return o.length>0?Lt(o):0}async evaluateOne(e,t,n,r){try{e.setInstruction?.(t);let o=await e.forward(this.studentAI,n,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let i=await r({prediction:o,example:n});if(typeof i=="number"&&!Number.isNaN(i)){let a=typeof this.targetScore=="number"?this.targetScore:.5;return i>=a&&(this.stats.successfulDemos+=1),i}return 0}catch(o){return this.getLogger()?.({name:"Notification",id:"gepa_eval",value:String(o)}),0}}async reflectInstruction(e,t,n,r,o,i){let a=i??[];if(a.length===0)for(let m of n)try{t.setInstruction?.(e);let g=await t.forward(this.studentAI,m,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let f=await r({prediction:g,example:m});a.push({input:m,prediction:g,score:typeof f=="number"?f:0})}catch{a.push({input:m,prediction:{},score:0})}let l=o?.overrideTeacherAI??this.teacherAI??this.studentAI,u=o?.feedbackFn,c=()=>{let m=[];for(let g=0;g<a.length;g++){let f=a[g],h=`# Example ${g+1}
423
- `;if(h+=`## Inputs
424
- `,typeof f.input=="object"&&f.input!==null)for(let[A,y]of Object.entries(f.input))h+=`### ${A}
429
+ ${e}`}i(n)}},fr=Ei();var Pi={enabled:!0,enabledCategories:["optimization","convergence","resource_usage","teacher_student","checkpointing","pareto"],maxLabelLength:100,samplingRate:1},Ko,Rp=i=>{if(Ko)return Ko;if(i)return Ko=vp(i),Ko};var Vo=Pi,Au=i=>{Vo={...Vo,...i}},yu=()=>({...Vo}),vp=i=>({optimizationLatencyHistogram:i.createHistogram("ax_optimizer_optimization_duration_ms",{description:"End-to-end duration of optimization runs",unit:"ms"}),optimizationRequestsCounter:i.createCounter("ax_optimizer_optimization_requests_total",{description:"Total number of optimization requests"}),optimizationErrorsCounter:i.createCounter("ax_optimizer_optimization_errors_total",{description:"Total number of failed optimizations"}),convergenceRoundsHistogram:i.createHistogram("ax_optimizer_convergence_rounds",{description:"Number of rounds until convergence"}),convergenceScoreGauge:i.createGauge("ax_optimizer_convergence_score",{description:"Current best score during optimization"}),convergenceImprovementGauge:i.createGauge("ax_optimizer_convergence_improvement",{description:"Improvement in score from baseline"}),stagnationRoundsGauge:i.createGauge("ax_optimizer_stagnation_rounds",{description:"Number of rounds without improvement"}),earlyStoppingCounter:i.createCounter("ax_optimizer_early_stopping_total",{description:"Total number of early stopping events"}),tokenUsageCounter:i.createCounter("ax_optimizer_token_usage_total",{description:"Total tokens used during optimization"}),costUsageCounter:i.createCounter("ax_optimizer_cost_usage_total",{description:"Total cost incurred during optimization",unit:"$"}),memoryUsageGauge:i.createGauge("ax_optimizer_memory_usage_bytes",{description:"Peak memory usage during optimization",unit:"By"}),optimizationDurationHistogram:i.createHistogram("ax_optimizer_duration_ms",{description:"Duration of optimization runs",unit:"ms"}),teacherStudentUsageCounter:i.createCounter("ax_optimizer_teacher_student_usage_total",{description:"Total number of teacher-student interactions"}),teacherStudentLatencyHistogram:i.createHistogram("ax_optimizer_teacher_student_latency_ms",{description:"Latency of teacher-student interactions",unit:"ms"}),teacherStudentScoreImprovementGauge:i.createGauge("ax_optimizer_teacher_student_score_improvement",{description:"Score improvement from teacher-student interactions"}),checkpointSaveCounter:i.createCounter("ax_optimizer_checkpoint_save_total",{description:"Total number of checkpoint saves"}),checkpointLoadCounter:i.createCounter("ax_optimizer_checkpoint_load_total",{description:"Total number of checkpoint loads"}),checkpointSaveLatencyHistogram:i.createHistogram("ax_optimizer_checkpoint_save_latency_ms",{description:"Latency of checkpoint save operations",unit:"ms"}),checkpointLoadLatencyHistogram:i.createHistogram("ax_optimizer_checkpoint_load_latency_ms",{description:"Latency of checkpoint load operations",unit:"ms"}),paretoOptimizationsCounter:i.createCounter("ax_optimizer_pareto_optimizations_total",{description:"Total number of Pareto optimizations"}),paretoFrontSizeHistogram:i.createHistogram("ax_optimizer_pareto_front_size",{description:"Size of Pareto frontier"}),paretoHypervolumeGauge:i.createGauge("ax_optimizer_pareto_hypervolume",{description:"Hypervolume of Pareto frontier"}),paretoSolutionsGeneratedHistogram:i.createHistogram("ax_optimizer_pareto_solutions_generated",{description:"Number of solutions generated for Pareto optimization"}),programInputFieldsGauge:i.createGauge("ax_optimizer_program_input_fields",{description:"Number of input fields in optimized program"}),programOutputFieldsGauge:i.createGauge("ax_optimizer_program_output_fields",{description:"Number of output fields in optimized program"}),examplesCountGauge:i.createGauge("ax_optimizer_examples_count",{description:"Number of training examples used"}),validationSetSizeGauge:i.createGauge("ax_optimizer_validation_set_size",{description:"Size of validation set used"}),evaluationLatencyHistogram:i.createHistogram("ax_optimizer_evaluation_latency_ms",{description:"Latency of program evaluations",unit:"ms"}),demoGenerationLatencyHistogram:i.createHistogram("ax_optimizer_demo_generation_latency_ms",{description:"Latency of demo generation",unit:"ms"}),metricComputationLatencyHistogram:i.createHistogram("ax_optimizer_metric_computation_latency_ms",{description:"Latency of metric computation",unit:"ms"}),optimizerTypeGauge:i.createGauge("ax_optimizer_type",{description:"Type of optimizer being used"}),targetScoreGauge:i.createGauge("ax_optimizer_target_score",{description:"Target score for optimization"}),maxRoundsGauge:i.createGauge("ax_optimizer_max_rounds",{description:"Maximum rounds for optimization"})}),ut=i=>{let e={};for(let[t,n]of Object.entries(i))if(n!=null){let r=String(n),o=Vo.maxLabelLength;e[t]=r.length>o?r.substring(0,o):r}return e},Sp=(i,e,t,n,r)=>{try{let o=ut({success:t.toString(),optimizer_type:n,...r?{program_signature:r}:{}});i.optimizationLatencyHistogram&&i.optimizationLatencyHistogram.record(e,o),i.optimizationRequestsCounter&&i.optimizationRequestsCounter.add(1,o),!t&&i.optimizationErrorsCounter&&i.optimizationErrorsCounter.add(1,o)}catch(o){console.warn("Failed to record optimization metric:",o)}},Op=(i,e,t,n,r,o)=>{try{let s=ut({optimizer_type:o});i.convergenceRoundsHistogram&&i.convergenceRoundsHistogram.record(e,s),i.convergenceScoreGauge&&i.convergenceScoreGauge.record(t,s),i.convergenceImprovementGauge&&i.convergenceImprovementGauge.record(n,s),i.stagnationRoundsGauge&&i.stagnationRoundsGauge.record(r,s)}catch(s){console.warn("Failed to record convergence metric:",s)}},kp=(i,e,t)=>{try{let n=ut({reason:e,optimizer_type:t});i.earlyStoppingCounter&&i.earlyStoppingCounter.add(1,n)}catch(n){console.warn("Failed to record early stopping metric:",n)}},Mp=(i,e,t,n,r)=>{try{let o=ut({optimizer_type:n});i.tokenUsageCounter&&i.tokenUsageCounter.add(e,o),i.costUsageCounter&&i.costUsageCounter.add(t,o),r!==void 0&&i.memoryUsageGauge&&i.memoryUsageGauge.record(r,o)}catch(o){console.warn("Failed to record resource usage metric:",o)}},Ep=(i,e,t)=>{try{let n=ut({optimizer_type:t});i.optimizationDurationHistogram&&i.optimizationDurationHistogram.record(e,n)}catch(n){console.warn("Failed to record optimization duration metric:",n)}},Pp=(i,e,t,n)=>{try{let r=ut({optimizer_type:n});i.teacherStudentUsageCounter&&i.teacherStudentUsageCounter.add(1,r),i.teacherStudentLatencyHistogram&&i.teacherStudentLatencyHistogram.record(e,r),i.teacherStudentScoreImprovementGauge&&i.teacherStudentScoreImprovementGauge.record(t,r)}catch(r){console.warn("Failed to record teacher-student metric:",r)}},Fp=(i,e,t,n,r)=>{try{let o=ut({operation:e,success:n.toString(),optimizer_type:r});e==="save"?(i.checkpointSaveCounter&&i.checkpointSaveCounter.add(1,o),i.checkpointSaveLatencyHistogram&&i.checkpointSaveLatencyHistogram.record(t,o)):(i.checkpointLoadCounter&&i.checkpointLoadCounter.add(1,o),i.checkpointLoadLatencyHistogram&&i.checkpointLoadLatencyHistogram.record(t,o))}catch(o){console.warn("Failed to record checkpoint metric:",o)}},_p=(i,e,t,n,r)=>{try{let o=ut({optimizer_type:n});i.paretoOptimizationsCounter&&i.paretoOptimizationsCounter.add(1,o),i.paretoFrontSizeHistogram&&i.paretoFrontSizeHistogram.record(e,o),r!==void 0&&i.paretoHypervolumeGauge&&i.paretoHypervolumeGauge.record(r,o),i.paretoSolutionsGeneratedHistogram&&i.paretoSolutionsGeneratedHistogram.record(t,o)}catch(o){console.warn("Failed to record Pareto metric:",o)}},$p=(i,e,t,n,r,o)=>{try{let s=ut({optimizer_type:o});i.programInputFieldsGauge&&i.programInputFieldsGauge.record(e,s),i.programOutputFieldsGauge&&i.programOutputFieldsGauge.record(t,s),i.examplesCountGauge&&i.examplesCountGauge.record(n,s),i.validationSetSizeGauge&&i.validationSetSizeGauge.record(r,s)}catch(s){console.warn("Failed to record program complexity metric:",s)}},Np=(i,e,t,n)=>{try{let r=ut({metric_type:e,optimizer_type:n});switch(e){case"evaluation":i.evaluationLatencyHistogram&&i.evaluationLatencyHistogram.record(t,r);break;case"demo_generation":i.demoGenerationLatencyHistogram&&i.demoGenerationLatencyHistogram.record(t,r);break;case"metric_computation":i.metricComputationLatencyHistogram&&i.metricComputationLatencyHistogram.record(t,r);break}}catch(r){console.warn("Failed to record optimizer performance metric:",r)}},Dp=(i,e,t,n)=>{try{let r=ut({optimizer_type:e});i.optimizerTypeGauge&&i.optimizerTypeGauge.record(1,r),t!==void 0&&i.targetScoreGauge&&i.targetScoreGauge.record(t,r),n!==void 0&&i.maxRoundsGauge&&i.maxRoundsGauge.record(n,r)}catch(r){console.warn("Failed to record optimizer configuration metric:",r)}},mt=class{bestScore;stats;instruction;demos;examples;modelConfig;optimizerType;optimizationTime;totalRounds;converged;scoreHistory;configurationHistory;constructor(e){this.bestScore=e.bestScore,this.stats=e.stats,this.instruction=e.instruction,this.demos=e.demos,this.examples=e.examples,this.modelConfig=e.modelConfig,this.optimizerType=e.optimizerType,this.optimizationTime=e.optimizationTime,this.totalRounds=e.totalRounds,this.converged=e.converged,this.scoreHistory=e.scoreHistory,this.configurationHistory=e.configurationHistory}applyTo(e){this.demos&&this.demos.length>0&&e.setDemos(this.demos),this.examples&&this.examples.length>0&&e.setExamples(this.examples),this.instruction&&(e._optimizedInstruction=this.instruction),this.modelConfig&&(e._optimizedModelConfig=this.modelConfig)}},xr=class{tokenUsage={};totalTokens=0;costPerModel;maxCost;maxTokens;constructor(e){this.costPerModel=e?.costPerModel??{},this.maxCost=e?.maxCost,this.maxTokens=e?.maxTokens}trackTokens(e,t){this.tokenUsage[t]=(this.tokenUsage[t]||0)+e,this.totalTokens+=e}getCurrentCost(){let e=0;for(let[t,n]of Object.entries(this.tokenUsage)){let r=this.costPerModel[t]||.001;e+=n/1e3*r}return e}getTokenUsage(){return{...this.tokenUsage}}getTotalTokens(){return this.totalTokens}isLimitReached(){return this.maxTokens!==void 0&&this.totalTokens>=this.maxTokens||this.maxCost!==void 0&&this.getCurrentCost()>=this.maxCost}reset(){this.tokenUsage={},this.totalTokens=0}},je=class{studentAI;teacherAI;targetScore;minSuccessRate;onProgress;onEarlyStop;costTracker;seed;checkpointSave;checkpointLoad;checkpointInterval;resumeFromCheckpoint;logger;verbose;debugOptimizer;optimizerLogger;currentRound=0;scoreHistory=[];configurationHistory=[];stats;metricsInstruments;resultExplainer;constructor(e){this.studentAI=e.studentAI,this.teacherAI=e.teacherAI,this.targetScore=e.targetScore,this.minSuccessRate=e.minSuccessRate,this.onProgress=e.onProgress,this.onEarlyStop=e.onEarlyStop,this.seed=e.seed,this.checkpointSave=e.checkpointSave,this.checkpointLoad=e.checkpointLoad,this.checkpointInterval=e.checkpointInterval??10,this.resumeFromCheckpoint=e.resumeFromCheckpoint,this.logger=e.logger,this.verbose=e.verbose;let t=new xr({maxTokens:1e6});this.costTracker=e.costTracker??t,this.metricsInstruments=Rp(ee.meter),this.stats=this.initializeStats(),this.debugOptimizer=e.debugOptimizer??!1,this.optimizerLogger=e.optimizerLogger??(this.verbose?fr:void 0),this.initializeResultExplainer()}initializeResultExplainer(){this.resultExplainer=void 0}initializeStats(){return{totalCalls:0,successfulDemos:0,estimatedTokenUsage:0,earlyStopped:!1,resourceUsage:{totalTokens:0,totalTime:0,avgLatencyPerEval:0,costByModel:{}},convergenceInfo:{converged:!1,finalImprovement:0,stagnationRounds:0,convergenceThreshold:.01},bestScore:0,bestConfiguration:{}}}setupRandomSeed(){this.seed!==void 0&&(Math.random=(()=>{let e=this.seed;return()=>(e=(e*9301+49297)%233280,e/233280)})())}checkCostLimits(){return this.costTracker?.isLimitReached()??!1}checkTargetScore(e){return this.targetScore!==void 0&&e>=this.targetScore}updateResourceUsage(e,t=0){this.stats.resourceUsage.totalTime=Date.now()-e,this.stats.resourceUsage.totalTokens+=t,this.stats.totalCalls>0&&(this.stats.resourceUsage.avgLatencyPerEval=this.stats.resourceUsage.totalTime/this.stats.totalCalls)}triggerEarlyStopping(e,t){this.stats.earlyStopped=!0,this.stats.earlyStopping={bestScoreRound:t,patienceExhausted:e.includes("improvement"),reason:e},this.recordEarlyStoppingMetrics(e,"unknown"),this.onEarlyStop&&this.onEarlyStop(e,this.stats),this.getOptimizerLogger()?.({name:"EarlyStopping",value:{reason:e,finalScore:this.stats.bestScore??0,round:t}})}validateExamples(e,t=!0){if(!e||e.length===0)throw new Error("At least 1 example is required for optimization");if(t&&e.length<2)throw new Error("At least 2 examples are required for optimization with auto-splitting. Provide more examples to enable proper train/validation split.");let n=t?10:5;e.length<n&&this.verbose&&console.warn(`[Ax Optimizer] Warning: Only ${e.length} examples provided. Consider providing more examples (${n}+ recommended) for better optimization results.`)}getAIService(e=!1,t){return e&&t?.overrideTeacherAI?t.overrideTeacherAI:e&&this.teacherAI?this.teacherAI:this.studentAI}hasTeacherAI(e){return e?.overrideTeacherAI!==void 0||this.teacherAI!==void 0}getTeacherOrStudentAI(e){return e?.overrideTeacherAI||this.teacherAI||this.studentAI}async executeWithTeacher(e,t=!0,n){let r=this.getAIService(t,n);return await e(r)}async*compileStream(e,t,n,r){let o=Date.now(),s=this.constructor.name,a=e.getSignature().toString();this.recordOptimizationStart(s,a);let l,u=(g,h,f,x,A,y,b,S={},w)=>{this.getOptimizerLogger(w)?.({name:"RoundProgress",value:{round:g,totalRounds:w?.maxIterations??0,currentScore:h,bestScore:y,configuration:f}}),this.updateOptimizationProgress(g,h,f,x,A,y,b,S,w)},c=(g,h)=>{l=g,this.triggerEarlyStopping(g,this.currentRound)},p=g=>{this.onProgress?.(g),u(g.round,g.currentScore,g.currentConfiguration||{},s,{},g.bestScore,g.bestConfiguration,g.convergenceInfo,r)},d=await this.compile(e,t,n,{...r,overrideOnProgress:p,overrideOnEarlyStop:c}),m=Date.now()-o;return this.recordOptimizationComplete(m,!0,s,a),l&&this.getLogger(r)?.({name:"Notification",id:"optimization_early_stop",value:`Optimization stopped early due to ${l}`}),{demos:d.demos,stats:d.stats,bestScore:d.bestScore,finalConfiguration:d.finalConfiguration,scoreHistory:d.scoreHistory,configurationHistory:d.configurationHistory}}async compilePareto(e,t,n,r){let o=this.constructor.name,s=Date.now(),a=await this.generateWeightedSolutions(e,t,n,r),l=await this.generateConstraintSolutions(e,t,n,r),u=[...a,...l],c=this.findParetoFrontier(u),p=this.calculateHypervolume(c);this.updateResourceUsage(s),this.stats.convergenceInfo.converged=!0,this.recordParetoMetrics(c.length,u.length,"base_optimizer",p);let d=c.length>0?Math.max(...c.map(m=>Math.max(...Object.values(m.scores)))):0;return{demos:c.length>0?[...c[0].demos]:void 0,stats:this.stats,bestScore:d,paretoFront:c,hypervolume:p,paretoFrontSize:c.length,finalConfiguration:{paretoFrontSize:c.length,hypervolume:p,strategy:"weighted_combinations_and_constraints",numSolutions:u.length}}}async generateWeightedSolutions(e,t,n,r){let o=[];if(!t||t.length===0)throw new Error("No examples provided for Pareto optimization");let s=t[0],a=await e.forward(this.getAIService(!1,r),s),l=await n({prediction:a,example:s}),u=Object.keys(l),c=this.generateWeightCombinations(u);for(let p=0;p<c.length;p++){let d=c[p],m=async({prediction:g,example:h})=>{let f=await n({prediction:g,example:h}),x=0;for(let[A,y]of Object.entries(f))x+=y*(d[A]||0);return x};try{let g=await this.compile(e,t,m,{...r,verbose:!1}),h=await this.evaluateWithMultiObjective(e,g,n,t);o.push({scores:h,demos:g.demos,configuration:{...g.finalConfiguration,weights:d,strategy:"weighted_combination"}})}catch{}}return o}async generateConstraintSolutions(e,t,n,r){let o=[];if(!t||t.length===0)throw new Error("No examples provided for multi-objective optimization");let s=t[0],a=await e.forward(this.getAIService(!1,r),s),l=await n({prediction:a,example:s}),u=Object.keys(l);for(let c of u){let p=async({prediction:d,example:m})=>{let g=await n({prediction:d,example:m}),h=g[c]||0,f=0;for(let[x,A]of Object.entries(g))x!==c&&A<.3&&(f+=(.3-A)*2);return h-f};try{let d=await this.compile(e,t,p,{...r,verbose:!1}),m=await this.evaluateWithMultiObjective(e,d,n,t);o.push({scores:m,demos:d.demos,configuration:{...d.finalConfiguration,primaryObjective:c,strategy:"constraint_based"}})}catch{}}return o}generateWeightCombinations(e){let t=[];for(let r of e){let o={};for(let s of e)o[s]=s===r?1:0;t.push(o)}let n={};for(let r of e)n[r]=1/e.length;if(t.push(n),e.length===2){let[r,o]=e;for(let s=.1;s<=.9;s+=.2){let a=1-s;t.push({[r]:s,[o]:a})}}if(e.length===3){let[r,o,s]=e;t.push({[r]:.5,[o]:.3,[s]:.2},{[r]:.3,[o]:.5,[s]:.2},{[r]:.2,[o]:.3,[s]:.5})}return t}async evaluateWithMultiObjective(e,t,n,r){let o=new Ce(e.getSignature());t.demos&&o.setDemos(t.demos);let s=[],a=Math.max(1,Math.min(5,Math.floor(r.length*.2))),l=r.slice(-a),u={},c=l;for(let d of c)try{let m=await o.forward(this.studentAI,d),g=await n({prediction:m,example:d});for(let[h,f]of Object.entries(g))u[h]||(u[h]=[]),u[h].push(f)}catch{}let p={};for(let[d,m]of Object.entries(u))p[d]=m.length>0?m.reduce((g,h)=>g+h,0)/m.length:0;return p}findParetoFrontier(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n],o=!1,s=0;for(let a=0;a<e.length;a++){if(n===a)continue;let l=e[a];if(this.dominates(l.scores,r.scores)){o=!0;break}this.dominates(r.scores,l.scores)&&s++}o||t.push({demos:r.demos||[],scores:r.scores,configuration:r.configuration,dominatedSolutions:s})}return t}dominates(e,t){let n=Object.keys(e),r=!0,o=!1;for(let s of n){let a=e[s]||0,l=t[s]||0;if(a<l){r=!1;break}a>l&&(o=!0)}return r&&o}calculateHypervolume(e){if(e.length===0)return;let t=e[0],n=Object.keys(t.scores);if(n.length===2){let[r,o]=n,s=0,a=[...e].sort((u,c)=>(c.scores[r]||0)-(u.scores[r]||0)),l=0;for(let u of a){let c=u.scores[r]||0,p=u.scores[o]||0;s+=c*(p-l),l=Math.max(l,p)}return s}}async saveCheckpoint(e,t,n,r,o={},s){let a=s?.overrideCheckpointSave||this.checkpointSave;if(!a)return;let l=Date.now(),u=!1,c;try{let p={version:"1.0.0",timestamp:Date.now(),optimizerType:e,optimizerConfig:t,currentRound:this.currentRound,totalRounds:this.stats.resourceUsage.totalTime>0?this.currentRound:0,bestScore:n,bestConfiguration:r,scoreHistory:[...this.scoreHistory],configurationHistory:[...this.configurationHistory],stats:{...this.stats},optimizerState:o,examples:[]};c=await a(p),u=!0}catch(p){throw u=!1,p}finally{let p=Date.now()-l;this.recordCheckpointMetrics("save",p,u,e)}return c}async loadCheckpoint(e,t){let n=t?.overrideCheckpointLoad||this.checkpointLoad;if(!n)return null;let r=Date.now(),o=!1,s=null;try{s=await n(e),o=s!==null}catch(a){throw o=!1,a}finally{let a=Date.now()-r;this.recordCheckpointMetrics("load",a,o,"unknown")}return s}restoreFromCheckpoint(e){this.currentRound=e.currentRound,this.scoreHistory=[...e.scoreHistory],this.configurationHistory=[...e.configurationHistory],this.stats={...e.stats}}shouldSaveCheckpoint(e,t){let n=t?.overrideCheckpointInterval||this.checkpointInterval;return n!==void 0&&e%n===0}async updateOptimizationProgress(e,t,n,r,o,s,a,l={},u){this.currentRound=e,this.scoreHistory.push(t),this.configurationHistory.push(n),this.shouldSaveCheckpoint(e,u)&&await this.saveCheckpoint(r,o,s,a,l,u),this.getOptimizerLogger(u)?.({name:"RoundProgress",value:{round:e,totalRounds:u?.maxIterations??0,currentScore:t,bestScore:s,configuration:n}})}async saveFinalCheckpoint(e,t,n,r,o={},s){s?.saveCheckpointOnComplete!==!1&&await this.saveCheckpoint(e,t,n,r,{...o,final:!0},s)}getLogger(e){if(this.isLoggingEnabled(e))return this.logger?this.logger:this.studentAI.getLogger()}isLoggingEnabled(e){return e?.verbose!==void 0?e.verbose:this.verbose??!0}recordOptimizationStart(e,t){if(this.metricsInstruments){if(t){let n=(t.match(/input:/g)||[]).length,r=(t.match(/output:/g)||[]).length;$p(this.metricsInstruments,n,r,0,0,e)}Dp(this.metricsInstruments,e,this.targetScore,void 0)}}recordOptimizationComplete(e,t,n,r){if(!this.metricsInstruments)return;Sp(this.metricsInstruments,e,t,n,r),Ep(this.metricsInstruments,e,n);let o=this.costTracker?.getCurrentCost()??0,s=this.costTracker?.getTotalTokens()??0;Mp(this.metricsInstruments,s,o,n)}recordConvergenceMetrics(e,t,n,r,o){this.metricsInstruments&&Op(this.metricsInstruments,e,t,n,r,o)}recordEarlyStoppingMetrics(e,t){this.metricsInstruments&&kp(this.metricsInstruments,e,t)}recordTeacherStudentMetrics(e,t,n){this.metricsInstruments&&Pp(this.metricsInstruments,e,t,n)}recordCheckpointMetrics(e,t,n,r){this.metricsInstruments&&Fp(this.metricsInstruments,e,t,n,r)}recordParetoMetrics(e,t,n,r){this.metricsInstruments&&_p(this.metricsInstruments,e,t,n,r)}recordPerformanceMetrics(e,t,n){this.metricsInstruments&&Np(this.metricsInstruments,e,t,n)}isOptimizerLoggingEnabled(e){return this.debugOptimizer||(e?.verbose??this.verbose??!1)}getOptimizerLogger(e){if(this.isOptimizerLoggingEnabled(e))return this.optimizerLogger??ee.optimizerLogger??fr}getStats(){return{...this.stats}}async explainOptimizationResults(e,t,n){let r=this.stats.convergenceInfo.converged,o=this.stats.totalCalls,s=o>0?this.stats.successfulDemos/o*100:0,a=`Optimization finished with best score ${e.toFixed(3)}${t?` using configuration ${JSON.stringify(t)}`:""}. Convergence: ${r?"yes":"no"}. Success rate: ${s.toFixed(1)}%.`,l=[];if(r||l.push("Increase numTrials or relax earlyStoppingTrials to allow further improvement."),typeof this.targetScore=="number"&&e<this.targetScore&&l.push("Tighten the metric or supply more/better-labeled examples to reach targetScore."),t&&"bootstrappedDemos"in t){let c=t.bootstrappedDemos;typeof c=="number"&&c===0&&l.push("Consider allowing a small number of bootstrapped demos to boost performance.")}l.length===0&&l.push("Re-run with more trials or different acquisition settings to explore more of the space.");let u=`Tokens used: ${this.stats.resourceUsage.totalTokens}, rounds: ${this.currentRound}, stagnationRounds: ${this.stats.convergenceInfo.stagnationRounds}.`;return{humanExplanation:a,recommendations:l,performanceAssessment:u}}async logOptimizationComplete(e,t,n,r,o){let s=this.getOptimizerLogger(r);s&&s(o?{name:"OptimizationComplete",value:{optimizerType:e,bestScore:t,bestConfiguration:n||{},totalCalls:this.stats.totalCalls,successRate:this.stats.totalCalls>0?`${(this.stats.successfulDemos/this.stats.totalCalls*100).toFixed(1)}%`:"N/A",explanation:o.humanExplanation,recommendations:o.recommendations,performanceAssessment:o.performanceAssessment,stats:this.stats}}:{name:"OptimizationComplete",value:{optimizerType:e,bestScore:t,bestConfiguration:n||{},totalCalls:this.stats.totalCalls,successRate:this.stats.totalCalls>0?`${(this.stats.successfulDemos/this.stats.totalCalls*100).toFixed(1)}%`:"N/A",stats:this.stats}})}reset(){this.stats=this.initializeStats(),this.costTracker?.reset(),this.currentRound=0,this.scoreHistory=[],this.configurationHistory=[]}};function bu(i){return ye.create(i)}function _e(i,e){let t=typeof i=="string"?ye.create(i):i;return new Ce(t,e)}function Iu(i,e,t=0){let n=new Set([...Object.keys(i),...Object.keys(e)]),r=!0,o=!1;for(let s of n){let a=i[s]??0,l=e[s]??0;if(a+t<l){r=!1;break}a>l+t&&(o=!0)}return r&&o}function gt(i,e=0){let t=[];for(let n=0;n<i.length;n++){let r=0,o=!1;for(let s=0;s<i.length;s++)if(n!==s){if(Iu(i[s].scores,i[n].scores,e)){o=!0;break}Iu(i[n].scores,i[s].scores,e)&&r++}o||t.push({idx:i[n].idx,scores:i[n].scores,dominated:r})}return t}function tt(i){if(i.length===0)return;let e=Object.keys(i[0]??{});if(e.length!==2)return;let[t,n]=e,r=[...i].sort((a,l)=>(l[t]??0)-(a[t]??0)),o=0,s=0;for(let a of r){let l=a[t]??0,u=a[n]??0,c=Math.max(u-s,0);o+=l*c,s=Math.max(s,u)}return o}function Gt(i){if(i.length===0)return 0;let e=0;for(let t of i)e+=t;return e/i.length}function Wo(i){let e={},t={};for(let r of i)for(let[o,s]of Object.entries(r))e[o]=(e[o]||0)+(typeof s=="number"?s:0),t[o]=(t[o]||0)+1;let n={};for(let[r,o]of Object.entries(e))n[r]=o/Math.max(t[r]||1,1);return n}function Ar(i,e){let t=new Set;for(let c of i)for(let p of c)t.add(p);let r=[...Array.from(t)].sort((c,p)=>(e[c]??0)-(e[p]??0)),o=new Set,s=(c,p)=>{for(let d of i){if(!d.has(c))continue;let m=!1;for(let g of p)if(d.has(g)){m=!0;break}if(!m)return!1}return!0},a=!0;for(;a;){a=!1;for(let c of r){if(o.has(c))continue;let p=new Set(r.filter(d=>d!==c&&!o.has(d)));if(s(c,p)){o.add(c),a=!0;break}}}let l=r.filter(c=>!o.has(c)),u=new Set(l);return i.map(c=>{let p=new Set;for(let d of c)u.has(d)&&p.add(d);return p})}function yr(i,e,t){let n=Ar(i,e),r={};for(let l of n)for(let u of l)r[u]=(r[u]||0)+1;let o=[];for(let[l,u]of Object.entries(r)){let c=Number(l);for(let p=0;p<u;p++)o.push(c)}if(o.length===0)return 0;let s=typeof t=="function"?t():Math.random(),a=Math.floor(s*o.length);return o[a]}var wn=class i extends je{numTrials;minibatch;minibatchSize;earlyStoppingTrials;minImprovementThreshold;sampleCount;paretoSetSize;crossoverEvery;tieEpsilon;feedbackMemorySize;feedbackMemory=[];mergeMax;mergesUsed=0;mergesDue=0;totalMergesTested=0;lastIterFoundNewProgram=!1;mergeAttemptKeys=new Set;mergeCompositionKeys=new Set;static REFLECTION_PROMPT_TEMPLATE="I provided an assistant with the following instructions to perform a task for me:\n```\n<curr_instructions>\n```\n\nThe following are examples of different task inputs provided to the assistant along with the assistant's response for each of them, and some feedback on how the assistant's response could be better:\n```\n<inputs_outputs_feedback>\n```\n\nYour task is to write a new instruction for the assistant. Read the inputs carefully and identify the input format and infer detailed task description about the task I wish to solve with the assistant. Read all the assistant responses and the corresponding feedback. Identify all niche and domain specific factual information about the task and include it in the instruction, as a lot of it may not be available to the assistant in the future. The assistant may have utilized a generalizable strategy to solve the task, if so, include that in the instruction as well. Provide the new instructions within ``` blocks.";rngState=123456789;samplerState={epoch:-1,shuffled:[],freq:new Map};localScoreHistory=[];localConfigurationHistory=[];constructor(e){super(e);let t=e?.seed,n=Number.isFinite(t)?Math.floor(Number(t)):0;this.rngState=n&&n!==0?n:123456789,this.numTrials=e.numTrials??30,this.minibatch=e.minibatch??!0,this.minibatchSize=e.minibatchSize??20,this.earlyStoppingTrials=e.earlyStoppingTrials??5,this.minImprovementThreshold=e.minImprovementThreshold??0,this.sampleCount=e.sampleCount??1;let r=e?.paretoSetSize;this.paretoSetSize=r&&r>0?Math.min(1e3,Math.max(5,Math.floor(r))):Math.max(10,Math.min(200,this.minibatchSize*3));let o=e?.crossoverEvery;this.crossoverEvery=Math.max(0,Math.floor(o??Math.max(3,Math.floor(this.numTrials/4))));let s=e?.tieEpsilon;this.tieEpsilon=Number.isFinite(s)?s:0;let a=e?.feedbackMemorySize;this.feedbackMemorySize=Math.max(0,Math.floor(a??4));let l=e?.mergeMax;this.mergeMax=Math.max(0,Math.floor(l??5)),this.mergesUsed=0,this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}reset(){super.reset(),this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold,this.localScoreHistory=[],this.localConfigurationHistory=[],this.feedbackMemory=[],this.mergesUsed=0,this.mergesDue=0,this.totalMergesTested=0,this.lastIterFoundNewProgram=!1,this.mergeAttemptKeys.clear(),this.mergeCompositionKeys.clear(),this.samplerState.epoch=-1,this.samplerState.shuffled=[],this.samplerState.freq.clear()}async compile(e,t,n,r){let o=Date.now();this.validateExamples(t),r?.auto&&this.configureAuto(r.auto);let s=r?.validationExamples,a=r?.feedbackExamples,l=(s&&s.length>0?s:t).slice(0,this.paretoSetSize),u=a&&a.length>0?a:t,c=async(I,P)=>{try{e.setInstruction?.(I);let _=await e.forward(this.studentAI,P,{sampleCount:this.sampleCount});return this.stats.totalCalls+=1,await n({prediction:_,example:P})||{}}catch{return{}}},p=async(I,P)=>{let _=[];for(let $ of P)_.push(await c(I,$));return Wo(_)},d=await this.getBaseInstruction(e),m=[{instruction:d,parent:void 0,scores:await p(d,l)}],g=I=>{let P=r?.paretoMetricKey,_=r?.paretoScalarize;if(typeof _=="function")return _(I);if(P)return Number.isFinite(I[P])?I[P]:0;let $=Object.values(I);return $.length?$.reduce((N,L)=>N+L,0)/$.length:0},h=[],f=async(I,P)=>{let _=[];for(let $ of P){let N=await c(I,$);_.push(g(N))}return _};h.push(await f(d,l));let x=()=>{let I=h[0]?.length??0,P=[];for(let $=0;$<I;$++){let N=Number.NEGATIVE_INFINITY,L=new Set;for(let z=0;z<h.length;z++){let H=h[z][$];H>N+this.tieEpsilon?(N=H,L.clear(),L.add(z)):Math.abs(H-N)<=this.tieEpsilon&&L.add(z)}P.push(L)}let _=h.map($=>Gt($));return yr(P,_)},A=r?.maxMetricCalls;if(!Number.isFinite(A)||A<=0)throw new Error("AxGEPA: options.maxMetricCalls must be set to a positive integer");let y=Math.floor(A),b=this.getOptimizerLogger(r),S=r?.verbose??this.verbose?I=>console.log(`[GEPA] ${I}`):I=>{};b?.({name:"OptimizationStart",value:{optimizerType:"GEPA",exampleCount:t.length,validationCount:l.length,config:{numTrials:this.numTrials,minibatch:this.minibatch,mergeMax:this.mergeMax}}}),S(`Starting GEPA optimization: ${t.length} train, ${l.length} validation, maxCalls=${y}`);let w=0,M=gt(m.map((I,P)=>({idx:P,scores:I.scores})),this.tieEpsilon).map(I=>I.idx),R;for(let I=0;I<this.numTrials&&!(y!==void 0&&this.stats.totalCalls>=Math.max(1,Math.floor(y)));I++){let P=h[0]?.length??0,_=[];for(let U=0;U<P;U++){let q=Number.NEGATIVE_INFINITY,Q=new Set;for(let re=0;re<h.length;re++){let G=h[re][U];G>q+this.tieEpsilon?(q=G,Q.clear(),Q.add(re)):Math.abs(G-q)<=this.tieEpsilon&&Q.add(re)}_.push(Q)}let $=h.map(U=>Gt(U));if(this.mergeMax>0&&this.mergesDue>0&&this.lastIterFoundNewProgram){let U=D=>{let K=[],X=D;for(;X!==void 0;)K.push(X),X=m[X]?.parent;return K},q=D=>D.length?D[Math.floor(this.rand()*D.length)]:void 0,Q=Ar(_,$),re=new Set;for(let D of Q)for(let K of D)re.add(K);let G=Array.from(re),B;for(let D=0;D<10&&!B&&!(G.length<2);D++){let K=q(G),X=q(G);if(K===X)continue;X<K&&([K,X]=[X,K]);let he=new Set(U(K)),Z=new Set(U(X));if(he.has(X)||Z.has(K))continue;let oe=[...he].filter(ke=>Z.has(ke));if(oe.length===0)continue;let ae=oe.map(ke=>Math.max(1e-9,$[ke])),me=this.rand()*ae.reduce((ke,We)=>ke+We,0),Re=oe[oe.length-1];for(let ke=0;ke<oe.length;ke++){if(me<ae[ke]){Re=oe[ke];break}me-=ae[ke]}B={i:K,j:X,a:Re}}if(this.lastIterFoundNewProgram=!1,B){let{i:D,j:K,a:X}=B,he=$[X],Z=$[D],oe=$[K],ae=m[X].instruction,me=m[D].instruction,Re=m[K].instruction,ke=me===ae&&Re!==me||Re===ae&&me!==Re,We=he<=Math.min(Z,oe)&&ke,$e="",ze="i",ge=!1;if(We){let ht=`${D}|${K}|${X}`;if(this.mergeAttemptKeys.has(ht))We=!1;else{me===ae&&Re!==me?($e=Re,ze="j"):Re===ae&&me!==Re?($e=me,ze="i"):me!==ae&&Re!==ae&&me!==Re?Z>oe||Z===oe&&this.rand()<.5?($e=me,ze="i"):($e=Re,ze="j"):($e=me,ze="i");let It=`${Math.min(D,K)}|${Math.max(D,K)}|${ze}`;if(this.mergeCompositionKeys.has(It))We=!1;else{this.mergeAttemptKeys.add(ht),this.mergeCompositionKeys.add(It);let nt=h[D],Tt=h[K],Ct=Array.from({length:nt.length},(le,Ne)=>Ne),ft=Ct.filter(le=>(nt[le]??0)>(Tt[le]??0)),wt=Ct.filter(le=>(Tt[le]??0)>(nt[le]??0)),Pt=Ct.filter(le=>!(ft.includes(le)||wt.includes(le))),W=5,Ie=Math.ceil(W/3),ct=(le,Ne)=>{if(Ne<=0||le.length===0)return[];if(le.length<=Ne)return[...le];let _n=[],Sr=new Set;for(;_n.length<Ne;){let rt=Math.floor(this.rand()*le.length);Sr.has(rt)||(Sr.add(rt),_n.push(le[rt]))}return _n},He=[];He.push(...ct(ft,Math.min(Ie,ft.length))),He.push(...ct(wt,Math.min(Ie,wt.length)));let Ke=W-He.length;He.push(...ct(Pt,Math.max(0,Ke)));let vr=W-He.length;if(vr>0){let le=Ct.filter(Ne=>!He.includes(Ne));He.push(...ct(le,Math.min(vr,le.length)))}let us=He.slice(0,Math.min(W,Ct.length)),Uu=us.map(le=>l[le]);ge=!0;let Bu=(await f($e,Uu)).reduce((le,Ne)=>le+Ne,0),ju=us.reduce((le,Ne)=>le+(nt[Ne]??0),0),qu=us.reduce((le,Ne)=>le+(Tt[Ne]??0),0);if(Bu>=Math.max(ju,qu)+this.tieEpsilon){S(`Iteration ${I+1}: Merge accepted (programs ${D} + ${K} via ancestor ${X})`);let le=await p($e,l);m.push({instruction:$e,parent:X,scores:le}),h.push(await f($e,l));let Ne=M.length,_n=tt(M.map(rt=>m[rt].scores))??0;M=gt(m.map((rt,zu)=>({idx:zu,scores:rt.scores})),this.tieEpsilon).map(rt=>rt.idx);let Sr=tt(M.map(rt=>m[rt].scores))??0;(M.length>Ne||Sr>_n+1e-6)&&(w=0),this.mergesDue-=1,this.totalMergesTested+=1}}}}if(ge)continue}}let N=yr(_,$,()=>this.rand()),L=this.minibatch?this.nextMinibatchIndices(u.length,I).map(U=>u[U]):u;if(r?.skipPerfectScore??!0){let U=Number(r?.perfectScore??1),q=await f(m[N].instruction,L);if(q.length>0&&q.every(Q=>Q>=U))continue}let z=!1,H=m[N].instruction,te="reflective_mutation",de,be;if(z){let U=(N+1)%m.length;H=await this.mergeInstructions(m[N].instruction,m[U].instruction,r),te="merge",this.mergesUsed+=1}else{let U=r?.gepaAdapter;if(U){try{let q={instruction:m[N].instruction},Q=await U.evaluate(L,q,!0);de=Array.isArray(Q?.scores)?Q.scores.reduce((D,K)=>D+(Number(K)||0),0):void 0;let re=U.make_reflective_dataset(q,Q,["instruction"]),G=await U.propose_new_texts?.(q,re,["instruction"]),B=G?.instruction??(G?Object.values(G)[0]:void 0);typeof B=="string"&&B.length>0?H=B:H=await this.reflectInstruction(m[N].instruction,e,L,async({prediction:D,example:K})=>{let X=await n({prediction:D,example:K}),he=Object.values(X||{});return he.length?he.reduce((Z,oe)=>Z+oe,0)/he.length:0},r)}catch{H=await this.reflectInstruction(m[N].instruction,e,L,async({prediction:q,example:Q})=>{let re=await n({prediction:q,example:Q}),G=Object.values(re||{});return G.length?G.reduce((B,D)=>B+D,0)/G.length:0},r)}if(de!==void 0)try{let q=await U.evaluate(L,{instruction:H},!1);be=Array.isArray(q?.scores)?q.scores.reduce((Q,re)=>Q+(Number(re)||0),0):void 0}catch{}}else H=await this.reflectInstruction(m[N].instruction,e,L,async({prediction:q,example:Q})=>{let re=await n({prediction:q,example:Q}),G=Object.values(re||{});return G.length?G.reduce((B,D)=>B+D,0)/G.length:0},r)}let ce=await f(m[N].instruction,L),ie=await f(H,L),fe=ce.reduce((U,q)=>U+q,0),Ae=ie.reduce((U,q)=>U+q,0);if(this.currentRound=I+1,await this.updateOptimizationProgress(this.currentRound,Ae,{instructionLen:H.length,parent:N,totalRounds:this.numTrials},"GEPA",{strategy:te,paretoSetSize:l.length},Ae,{instructionLen:m[N].instruction.length,idx:N},{...r??{},maxIterations:this.numTrials}),!(Ae>fe+this.tieEpsilon&&(de===void 0||be===void 0||be>de+this.tieEpsilon))){if(S(`Iteration ${I+1}: Rejected (child=${Ae.toFixed(3)} <= parent=${fe.toFixed(3)})`),++w>=this.earlyStoppingTrials){S(`Early stopping: ${w} iterations without improvement`);break}continue}S(`Iteration ${I+1}: Accepted (child=${Ae.toFixed(3)} > parent=${fe.toFixed(3)})`);let ve=await p(H,l);m.push({instruction:H,parent:N,scores:ve}),h.push(await f(H,l));let qe=M.length,Y=tt(M.map(U=>m[U].scores))??0;M=gt(m.map((U,q)=>({idx:q,scores:U.scores})),this.tieEpsilon).map(U=>U.idx);let ne=tt(M.map(U=>m[U].scores))??0;if(M.length>qe||ne>Y+1e-6)w=0,S(`Iteration ${I+1}: Archive improved (size=${M.length}, hv=${ne.toFixed(4)})`);else if(w++,S(`Iteration ${I+1}: Archive unchanged (stagnation=${w}/${this.earlyStoppingTrials})`),w>=this.earlyStoppingTrials){S(`Early stopping: ${w} iterations without archive improvement`);break}this.lastIterFoundNewProgram=!0,this.mergeMax>0&&this.totalMergesTested<this.mergeMax&&(this.mergesDue+=1)}let k=gt(m.map((I,P)=>({idx:P,scores:I.scores})),this.tieEpsilon),F=k.length>0?Math.max(...k.map(I=>g(I.scores))):0,E;if(k.length>0){let I=Number.NEGATIVE_INFINITY;for(let P of k){let _=g(P.scores);_>I&&(I=_,E=P.idx)}}let T=tt(k.map(I=>I.scores));this.stats.convergenceInfo.converged=!0,this.recordParetoMetrics(k.length,m.length,"GEPA",T);let v=Date.now()-o,C=typeof E=="number"?new mt({bestScore:F,stats:this.stats,instruction:m[E].instruction,demos:[],examples:t,modelConfig:void 0,optimizerType:"GEPA",optimizationTime:v,totalRounds:this.numTrials,converged:this.stats.convergenceInfo.converged}):void 0,O=this.generateOptimizationReport(k,T,F);return{demos:[],stats:this.stats,bestScore:F,paretoFront:k.map(I=>({demos:[],scores:I.scores,configuration:{candidate:I.idx,instruction:m[I.idx].instruction},dominatedSolutions:I.dominated})),paretoFrontSize:k.length,hypervolume:T,finalConfiguration:{strategy:"gepa",candidates:m.length},optimizedProgram:C,report:O}}configureAuto(e){switch(e){case"light":this.numTrials=10,this.minibatch=!0,this.minibatchSize=15;break;case"medium":this.numTrials=20,this.minibatch=!0,this.minibatchSize=25;break;case"heavy":this.numTrials=35,this.minibatch=!0,this.minibatchSize=35;break}}async getBaseInstruction(e){let t=e.getInstruction?.();if(t&&t.length>0)return t;let r=e.getSignature?.()?.getDescription?.();return r&&r.length>0?r:"Follow the task precisely. Be concise, correct, and consistent."}async evaluateOnSet(e,t,n,r){let o=[];for(let s of n){let a=await this.evaluateOne(e,t,s,r);o.push(a)}return o}async evaluateAvg(e,t,n,r){let o=await this.evaluateOnSet(e,t,n,r);return o.length>0?Gt(o):0}async evaluateOne(e,t,n,r){try{e.setInstruction?.(t);let o=await e.forward(this.studentAI,n,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let s=await r({prediction:o,example:n});if(typeof s=="number"&&!Number.isNaN(s)){let a=typeof this.targetScore=="number"?this.targetScore:.5;return s>=a&&(this.stats.successfulDemos+=1),s}return 0}catch(o){return this.getLogger()?.({name:"Notification",id:"gepa_eval",value:String(o)}),0}}async reflectInstruction(e,t,n,r,o,s){let a=s??[];if(a.length===0)for(let m of n)try{t.setInstruction?.(e);let g=await t.forward(this.studentAI,m,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let h=await r({prediction:g,example:m});a.push({input:m,prediction:g,score:typeof h=="number"?h:0})}catch{a.push({input:m,prediction:{},score:0})}let l=o?.overrideTeacherAI??this.teacherAI??this.studentAI,u=o?.feedbackFn,c=()=>{let m=[];for(let g=0;g<a.length;g++){let h=a[g],f=`# Example ${g+1}
430
+ `;if(f+=`## Inputs
431
+ `,typeof h.input=="object"&&h.input!==null)for(let[A,y]of Object.entries(h.input))f+=`### ${A}
425
432
  ${String(y).trim()}
426
433
 
427
- `;else h+=`${String(f.input).trim()}
434
+ `;else f+=`${String(h.input).trim()}
428
435
 
429
- `;if(h+=`## Generated Outputs
430
- `,typeof f.prediction=="object"&&f.prediction!==null)for(let[A,y]of Object.entries(f.prediction))h+=`### ${A}
436
+ `;if(f+=`## Generated Outputs
437
+ `,typeof h.prediction=="object"&&h.prediction!==null)for(let[A,y]of Object.entries(h.prediction))f+=`### ${A}
431
438
  ${String(y).trim()}
432
439
 
433
- `;else h+=`${String(f.prediction).trim()}
440
+ `;else f+=`${String(h.prediction).trim()}
434
441
 
435
- `;h+=`## Feedback
436
- `;let x=`This trajectory got a score of ${f.score.toFixed(3)}.`;if(typeof u=="function")try{let A=u({prediction:f.prediction,example:f.input});A&&(x=Array.isArray(A)?A.join(`
437
- `):A)}catch{}h+=`${x}
438
- `,m.push(h)}return m.join(`
442
+ `;f+=`## Feedback
443
+ `;let x=`This trajectory got a score of ${h.score.toFixed(3)}.`;if(typeof u=="function")try{let A=u({prediction:h.prediction,example:h.input});A&&(x=Array.isArray(A)?A.join(`
444
+ `):A)}catch{}f+=`${x}
445
+ `,m.push(f)}return m.join(`
439
446
 
440
- `)},p=s.REFLECTION_PROMPT_TEMPLATE.replace("<curr_instructions>",e).replace("<inputs_outputs_feedback>",c());try{let m=await l.chat({chatPrompt:[{role:"user",content:p}],model:o?.reflectionModel},{stream:!1});if(typeof m.getReader=="function")throw new Error("Streaming response not expected for reflection");let f=m.results?.[0]?.content;if(typeof f=="string"){let h=this.extractInstructionFromBackticks(f);if(h&&h.length>16){let x=`Iteration feedback: ${a.map(A=>`score=${A.score.toFixed(2)}`).join(", ")}`;return this.feedbackMemory.unshift(x),this.feedbackMemory.length>this.feedbackMemorySize&&this.feedbackMemory.pop(),h}}}catch{}let d=_e('currentInstruction:string "Current instruction", feedbackSummary?:string "Summarized feedback", recentFeedback?:string[] "Past feedback memory", minibatch:json "Array of {input,prediction,score}" -> newInstruction:string "Improved instruction within 1-6 sentences."');try{let g=(await d.forward(l,{currentInstruction:e,feedbackSummary:this.feedbackMemory[0]||"",recentFeedback:this.feedbackMemory,minibatch:a}))?.newInstruction?.trim();if(g&&g.length>16)return g}catch{}return`${e.trim()} Focus on step-by-step evidence-based reasoning. Avoid hallucinations.`.slice(0,2e3)}extractInstructionFromBackticks(e){let t=e.indexOf("```")+3,n=e.lastIndexOf("```");if(t>=n){let i=e.trim();if(i.startsWith("```")){let a=i.match(/^```\S*\n?/);if(a)return i.slice(a[0].length).trim()}else if(i.endsWith("```"))return i.slice(0,-3).trim();return i}let r=e.slice(t,n),o=r.match(/^\S*\n/);return o&&(r=r.slice(o[0].length)),r.trim()}updateSamplerShuffled(e){let t=Array.from({length:e},(l,u)=>u);for(let l=t.length-1;l>0;l--){let u=Math.floor(this.rand()*(l+1));[t[l],t[u]]=[t[u],t[l]]}for(let l of t)this.samplerState.freq.set(l,(this.samplerState.freq.get(l)??0)+1);let n=this.minibatchSize,r=e%n,o=r===0?0:n-r,i=Array.from({length:e},(l,u)=>u).sort((l,u)=>(this.samplerState.freq.get(l)??0)-(this.samplerState.freq.get(u)??0)),a=[...t];for(let l=0;l<o;l++){let u=i[l%i.length];a.push(u),this.samplerState.freq.set(u,(this.samplerState.freq.get(u)??0)+1)}this.samplerState.shuffled=a,this.samplerState.epoch+=1}nextMinibatchIndices(e,t){this.samplerState.epoch===-1&&(this.samplerState.epoch=0,this.updateSamplerShuffled(e));let n=this.minibatchSize,r=Math.max(1,Math.floor(this.samplerState.shuffled.length/n)),o=Math.floor(t/r);for(;o>=this.samplerState.epoch;)this.updateSamplerShuffled(e);let i=t*n%this.samplerState.shuffled.length;return this.samplerState.shuffled.slice(i,i+n)}rand(){return this.rngState^=this.rngState<<13,this.rngState^=this.rngState>>>17,this.rngState^=this.rngState<<5,(this.rngState>>>0)/4294967296}generateOptimizationReport(e,t,n){let r=e.length>0?e.reduce((u,c)=>{let p=Object.values(u.scores).reduce((m,g)=>m+g,0);return Object.values(c.scores).reduce((m,g)=>m+g,0)>p?c:u}):void 0,o={};if(r)for(let[u,c]of Object.entries(r.scores))o[u]={value:c,percentage:c*100};let i=[];if(e.length>1){let u=[...e].sort((c,p)=>p.dominated-c.dominated).slice(0,3);for(let c of u)i.push({...c.scores})}let a="good",l=[];if(e.length===1)a="single",l.push("Increase numTrials (current seems low)"),l.push("Add more training examples"),l.push("Adjust earlyStoppingTrials");else if(e.length<3)a="limited",l.push("More optimization trials"),l.push("Larger validation set");else{a="good";let u=Object.keys(e[0]?.scores||{});for(let c of u)l.push(`High ${c}: Choose solution with best ${c} score`);l.push("Balanced: Use provided bestScore (average)")}return this.stats.totalCalls<50&&(l.push("Quick run detected - use numTrials: 30+ for production"),l.push("Provide 50+ training examples"),l.push("Use 20+ validation examples")),{summary:"GEPA Multi-Objective Optimization Complete",bestSolution:{overallScore:n??0,objectives:o},paretoFrontier:{solutionCount:e.length,objectiveSpaceCoverage:(t??0)*100,hypervolume:t??0,tradeoffs:i.length>0?i:void 0},statistics:{totalEvaluations:this.stats.totalCalls,candidatesExplored:e.length,converged:this.stats.convergenceInfo?.converged??!1},recommendations:{status:a,suggestions:l}}}async mergeInstructions(e,t,n){let r=n?.overrideTeacherAI??this.teacherAI??this.studentAI,o=_e(`instructionA:string "Parent A instruction",
447
+ `)},p=i.REFLECTION_PROMPT_TEMPLATE.replace("<curr_instructions>",e).replace("<inputs_outputs_feedback>",c());try{let m=await l.chat({chatPrompt:[{role:"user",content:p}],model:o?.reflectionModel},{stream:!1});if(typeof m.getReader=="function")throw new Error("Streaming response not expected for reflection");let h=m.results?.[0]?.content;if(typeof h=="string"){let f=this.extractInstructionFromBackticks(h);if(f&&f.length>16){let x=`Iteration feedback: ${a.map(A=>`score=${A.score.toFixed(2)}`).join(", ")}`;return this.feedbackMemory.unshift(x),this.feedbackMemory.length>this.feedbackMemorySize&&this.feedbackMemory.pop(),f}}}catch{}let d=_e('currentInstruction:string "Current instruction", feedbackSummary?:string "Summarized feedback", recentFeedback?:string[] "Past feedback memory", minibatch:json "Array of {input,prediction,score}" -> newInstruction:string "Improved instruction within 1-6 sentences."');try{let g=(await d.forward(l,{currentInstruction:e,feedbackSummary:this.feedbackMemory[0]||"",recentFeedback:this.feedbackMemory,minibatch:a}))?.newInstruction?.trim();if(g&&g.length>16)return g}catch{}return`${e.trim()} Focus on step-by-step evidence-based reasoning. Avoid hallucinations.`.slice(0,2e3)}extractInstructionFromBackticks(e){let t=e.indexOf("```")+3,n=e.lastIndexOf("```");if(t>=n){let s=e.trim();if(s.startsWith("```")){let a=s.match(/^```\S*\n?/);if(a)return s.slice(a[0].length).trim()}else if(s.endsWith("```"))return s.slice(0,-3).trim();return s}let r=e.slice(t,n),o=r.match(/^\S*\n/);return o&&(r=r.slice(o[0].length)),r.trim()}updateSamplerShuffled(e){let t=Array.from({length:e},(l,u)=>u);for(let l=t.length-1;l>0;l--){let u=Math.floor(this.rand()*(l+1));[t[l],t[u]]=[t[u],t[l]]}for(let l of t)this.samplerState.freq.set(l,(this.samplerState.freq.get(l)??0)+1);let n=this.minibatchSize,r=e%n,o=r===0?0:n-r,s=Array.from({length:e},(l,u)=>u).sort((l,u)=>(this.samplerState.freq.get(l)??0)-(this.samplerState.freq.get(u)??0)),a=[...t];for(let l=0;l<o;l++){let u=s[l%s.length];a.push(u),this.samplerState.freq.set(u,(this.samplerState.freq.get(u)??0)+1)}this.samplerState.shuffled=a,this.samplerState.epoch+=1}nextMinibatchIndices(e,t){this.samplerState.epoch===-1&&(this.samplerState.epoch=0,this.updateSamplerShuffled(e));let n=this.minibatchSize,r=Math.max(1,Math.floor(this.samplerState.shuffled.length/n)),o=Math.floor(t/r);for(;o>=this.samplerState.epoch;)this.updateSamplerShuffled(e);let s=t*n%this.samplerState.shuffled.length;return this.samplerState.shuffled.slice(s,s+n)}rand(){return this.rngState^=this.rngState<<13,this.rngState^=this.rngState>>>17,this.rngState^=this.rngState<<5,(this.rngState>>>0)/4294967296}generateOptimizationReport(e,t,n){let r=e.length>0?e.reduce((u,c)=>{let p=Object.values(u.scores).reduce((m,g)=>m+g,0);return Object.values(c.scores).reduce((m,g)=>m+g,0)>p?c:u}):void 0,o={};if(r)for(let[u,c]of Object.entries(r.scores))o[u]={value:c,percentage:c*100};let s=[];if(e.length>1){let u=[...e].sort((c,p)=>p.dominated-c.dominated).slice(0,3);for(let c of u)s.push({...c.scores})}let a="good",l=[];if(e.length===1)a="single",l.push("Increase numTrials (current seems low)"),l.push("Add more training examples"),l.push("Adjust earlyStoppingTrials");else if(e.length<3)a="limited",l.push("More optimization trials"),l.push("Larger validation set");else{a="good";let u=Object.keys(e[0]?.scores||{});for(let c of u)l.push(`High ${c}: Choose solution with best ${c} score`);l.push("Balanced: Use provided bestScore (average)")}return this.stats.totalCalls<50&&(l.push("Quick run detected - use numTrials: 30+ for production"),l.push("Provide 50+ training examples"),l.push("Use 20+ validation examples")),{summary:"GEPA Multi-Objective Optimization Complete",bestSolution:{overallScore:n??0,objectives:o},paretoFrontier:{solutionCount:e.length,objectiveSpaceCoverage:(t??0)*100,hypervolume:t??0,tradeoffs:s.length>0?s:void 0},statistics:{totalEvaluations:this.stats.totalCalls,candidatesExplored:e.length,converged:this.stats.convergenceInfo?.converged??!1},recommendations:{status:a,suggestions:l}}}async mergeInstructions(e,t,n){let r=n?.overrideTeacherAI??this.teacherAI??this.studentAI,o=_e(`instructionA:string "Parent A instruction",
441
448
  instructionB:string "Parent B instruction",
442
449
  recentFeedback?:string[] "Past feedback memory"
443
- -> mergedInstruction:string "Merged instruction (1-6 sentences) combining strengths, fixing weaknesses"`);try{let a=(await o.forward(r,{instructionA:e,instructionB:t,recentFeedback:this.feedbackMemory}))?.mergedInstruction?.trim();if(a&&a.length>16)return a}catch{}return(e.length>=t.length?e:t).slice(0,2e3)}};function yu(s){return s.map(e=>{let t=e.type?.name??"string",n=e.type?.isArray?"[]":"",r=e.isOptional?" (optional)":"",o=e.description?`: ${e.description}`:"";return`- ${e.name}: ${t}${n}${r}${o}`}).join(`
444
- `)}function _p(s){return s.map(e=>{let t=e.type?.name??"string",n=e.type?.isArray?"[]":"",r=e.type?.options?` (options: ${e.type.options.join(", ")})`:"",o=e.description?`: ${e.description}`:"";return`- ${e.name}: ${t}${n}${r}${o}`}).join(`
445
- `)}var Rn=class{signature;options;constructor(e,t){this.signature=e,this.options={teacher:t.teacher,diversity:t.diversity??"none",temperature:t.temperature??.8,domain:t.domain,edgeCases:t.edgeCases,model:t.model}}async generate(e,t){let n=Date.now(),r=t?.batchSize??Math.min(e,10),o=[],i=0,a=0;for(let l=0;l<e;l+=r){let u=Math.min(r,e-l),c=await this.generateInputs(u);for(let p of c){a++;try{let d=await this.labelInput(p);o.push({input:p,expected:d,category:"normal"}),i++}catch(d){console.warn("AxSynth: Failed to label input:",d)}}}if(this.options.edgeCases&&this.options.edgeCases.length>0){let l=await this.generateEdgeCaseInputs(Math.ceil(e*.2));for(let u of l){a++;try{let c=await this.labelInput(u);o.push({input:u,expected:c,category:"edge_case"}),i++}catch(c){console.warn("AxSynth: Failed to label edge case input:",c)}}}return{examples:o,stats:{requested:e,generated:o.length,labelingSuccessRate:a>0?i/a:0,durationMs:Date.now()-n}}}async generateInputs(e){let t=this.signature.getInputFields(),n=this.signature.getOutputFields(),r=this.signature.getDescription(),o=`
450
+ -> mergedInstruction:string "Merged instruction (1-6 sentences) combining strengths, fixing weaknesses"`);try{let a=(await o.forward(r,{instructionA:e,instructionB:t,recentFeedback:this.feedbackMemory}))?.mergedInstruction?.trim();if(a&&a.length>16)return a}catch{}return(e.length>=t.length?e:t).slice(0,2e3)}};function Tu(i){return i.map(e=>{let t=e.type?.name??"string",n=e.type?.isArray?"[]":"",r=e.isOptional?" (optional)":"",o=e.description?`: ${e.description}`:"";return`- ${e.name}: ${t}${n}${r}${o}`}).join(`
451
+ `)}function Gp(i){return i.map(e=>{let t=e.type?.name??"string",n=e.type?.isArray?"[]":"",r=e.type?.options?` (options: ${e.type.options.join(", ")})`:"",o=e.description?`: ${e.description}`:"";return`- ${e.name}: ${t}${n}${r}${o}`}).join(`
452
+ `)}var Rn=class{signature;options;constructor(e,t){this.signature=e,this.options={teacher:t.teacher,diversity:t.diversity??"none",temperature:t.temperature??.8,domain:t.domain,edgeCases:t.edgeCases,model:t.model}}async generate(e,t){let n=Date.now(),r=t?.batchSize??Math.min(e,10),o=[],s=0,a=0;for(let l=0;l<e;l+=r){let u=Math.min(r,e-l),c=await this.generateInputs(u);for(let p of c){a++;try{let d=await this.labelInput(p);o.push({input:p,expected:d,category:"normal"}),s++}catch(d){console.warn("AxSynth: Failed to label input:",d)}}}if(this.options.edgeCases&&this.options.edgeCases.length>0){let l=await this.generateEdgeCaseInputs(Math.ceil(e*.2));for(let u of l){a++;try{let c=await this.labelInput(u);o.push({input:u,expected:c,category:"edge_case"}),s++}catch(c){console.warn("AxSynth: Failed to label edge case input:",c)}}}return{examples:o,stats:{requested:e,generated:o.length,labelingSuccessRate:a>0?s/a:0,durationMs:Date.now()-n}}}async generateInputs(e){let t=this.signature.getInputFields(),n=this.signature.getOutputFields(),r=this.signature.getDescription(),o=`
446
453
  You are generating realistic input data for an AI system.
447
454
 
448
455
  ${r?`Task description: ${r}`:""}
449
456
  ${this.options.domain?`Domain: ${this.options.domain}`:""}
450
457
 
451
458
  The system expects these INPUT fields:
452
- ${yu(t)}
459
+ ${Tu(t)}
453
460
 
454
461
  The system produces these OUTPUT fields:
455
- ${_p(n)}
462
+ ${Gp(n)}
456
463
 
457
464
  Generate ${e} diverse, realistic input examples as a JSON array.
458
465
  Each example should be an object with the input fields defined above.
459
466
  Make the examples varied and realistic for the domain.
460
467
 
461
468
  Output ONLY the JSON array, no explanation.
462
- `.trim(),i=new Ce("count:number -> examples:json");i.setInstruction(o);try{let a=await i.forward(this.options.teacher,{count:e},{model:this.options.model});return Array.isArray(a.examples)?a.examples.slice(0,e):[]}catch(a){return console.warn("AxSynth: Input generation failed:",a),[]}}async generateEdgeCaseInputs(e){let t=this.signature.getInputFields(),n=this.options.edgeCases??[],r=`
469
+ `.trim(),s=new Ce("count:number -> examples:json");s.setInstruction(o);try{let a=await s.forward(this.options.teacher,{count:e},{model:this.options.model});return Array.isArray(a.examples)?a.examples.slice(0,e):[]}catch(a){return console.warn("AxSynth: Input generation failed:",a),[]}}async generateEdgeCaseInputs(e){let t=this.signature.getInputFields(),n=this.options.edgeCases??[],r=`
463
470
  You are generating challenging edge case input data to test an AI system's robustness.
464
471
 
465
472
  The system expects these INPUT fields:
466
- ${yu(t)}
473
+ ${Tu(t)}
467
474
 
468
475
  Generate ${e} edge case examples as a JSON array.
469
476
  Focus on these types of edge cases:
470
- ${n.map(i=>`- ${i}`).join(`
477
+ ${n.map(s=>`- ${s}`).join(`
471
478
  `)}
472
479
 
473
480
  Output ONLY the JSON array, no explanation.
474
- `.trim(),o=new Ce("count:number -> examples:json");o.setInstruction(r);try{let i=await o.forward(this.options.teacher,{count:e},{model:this.options.model});return Array.isArray(i.examples)?i.examples.slice(0,e):[]}catch(i){return console.warn("AxSynth: Edge case generation failed:",i),[]}}async labelInput(e){return await new Ce(this.signature).forward(this.options.teacher,e,{model:this.options.model})}getSignature(){return this.signature}getTeacher(){return this.options.teacher}};var Wo=class s{gen;options;tracer;currentScore;constructor(e,t){this.gen=e,this.options={...t,enableTracing:t.enableTracing??!0},this.tracer=new Cn(e,{name:this.options.name,storage:this.options.storage,metadata:this.options.metadata,onTrace:this.options.onTrace}),this.loadLatestCheckpoint()}async forward(e,t,n){return this.options.enableTracing?this.tracer.forward(e,t,n):this.gen.forward(e,t,n)}async*streamingForward(e,t,n){this.options.enableTracing?yield*this.tracer.streamingForward(e,t,n):yield*this.gen.streamingForward(e,t,n)}getUsage(){return this.gen.getUsage()}resetUsage(){this.gen.resetUsage()}getSignature(){return this.gen.getSignature()}setInstruction(e){this.gen.setInstruction(e)}getInstruction(){return this.gen.getInstruction()}updateMeter(e){this.gen.updateMeter(e)}addAssert(e,t){this.gen.addAssert(e,t)}addStreamingAssert(e,t,n){this.gen.addStreamingAssert(e,t,n)}addFieldProcessor(e,t){this.gen.addFieldProcessor(e,t)}addStreamingFieldProcessor(e,t){this.gen.addStreamingFieldProcessor(e,t)}clone(){return new s(this.gen.clone(),this.options)}async optimize(e={}){let t=Date.now(),n={...this.options,...e},r=n.teacher,o=n.budget??20,i=[...n.examples??[]];if(n.useTraces!==!1){let S=(await this.getTraces()).filter(M=>M.input&&M.output).map(M=>({...M.input,...M.output}));i=[...i,...S]}if(n.generateExamples||i.length===0){let k=n.synthCount??20,S={teacher:r,...n.synthOptions},O=(await new Rn(this.gen.getSignature(),S).generate(k)).examples.map(F=>({...F.input,...F.expected}));i=[...i,...O]}if(i.length===0)throw new Error("No training examples available. Provide examples, enable trace usage, or enable example generation.");let a=n.validationSplit??.2,l=[...i].sort(()=>Math.random()-.5),u=Math.floor(l.length*(1-a)),c=l.slice(0,u),p=l.slice(u),d=n.metric;if(!d){let k={ai:r,criteria:n.criteria,...n.judgeOptions};d=new Tn(this.gen.getSignature(),k).toMetricFn()}let m=new wn({studentAI:r,numTrials:o,minibatch:!0,minibatchSize:10}),g=o*Math.max(c.length,10),f=await m.compile(this.gen,c,d,{validationExamples:p,maxMetricCalls:g});if(!f.optimizedProgram)throw new Error("GEPA optimization failed: no optimizedProgram returned");f.optimizedProgram.instruction&&this.gen.setInstruction(f.optimizedProgram.instruction),this.currentScore=f.optimizedProgram.bestScore,this.tracer=this.tracer.clone(this.gen);let h=this.currentScore,x=h,y=((await this.options.storage.load(this.options.name,{type:"checkpoint",limit:1}))[0]?.version??0)+1,b={type:"checkpoint",name:this.options.name,version:y,createdAt:new Date,instruction:this.gen.getInstruction(),score:h,optimizerType:"gepa",metadata:{budget:o,trainingExamples:c.length,durationMs:Date.now()-t}};return await this.options.storage.save(this.options.name,b),{score:h,improvement:x,checkpointVersion:y,stats:{trainingExamples:c.length,validationExamples:p.length,durationMs:Date.now()-t}}}async loadLatestCheckpoint(){try{let t=(await this.options.storage.load(this.options.name,{type:"checkpoint",limit:1}))[0];t?.instruction&&(this.gen.setInstruction(t.instruction),this.currentScore=t.score,this.tracer=this.tracer.clone(this.gen))}catch{}}getGen(){return this.gen}getStorage(){return this.options.storage}async getTraces(e){return this.options.storage.load(this.options.name,{type:"trace",...e})}async addFeedback(e,t){let n=await this.options.storage.load(this.options.name,{id:e,type:"trace",limit:1});if(n.length>0){let r=n[0];r.feedback={...r.feedback,...t},await this.options.storage.save(this.options.name,r)}}};var Jo=class{rows=[];baseUrl;dataset;split;config;options;constructor({dataset:e,split:t,config:n,options:r}){this.baseUrl="https://datasets-server.huggingface.co/rows",this.dataset=e,this.split=t,this.config=n,this.options=r}async fetchDataFromAPI(e){try{let t=await fetch(e);if(!t.ok)throw new Error(`Error fetching data: ${t.statusText}`);let n=await t.json();if(!n?.rows)throw new Error("Invalid data format");return n.rows}catch(t){throw console.error("Error fetching data from API:",t),t}}async loadData(){let e=this.options?.offset??0,t=this.options?.length??100,n=encodeURIComponent(this.dataset),r=`${this.baseUrl}?dataset=${n}&config=${this.config}&split=${this.split}&offset=${e}&length=${t}`;return this.rows=await this.fetchDataFromAPI(r),this.rows}setData(e){this.rows=e}getData(){return this.rows}async getRows({count:e,fields:t,renameMap:n}){if(this.rows.length===0)throw new Error("No data loaded, call loadData or setData first.");return this.rows.slice(0,e).map(o=>{let i={};return t.forEach(a=>{let l=a.split("."),u=o.row;for(let p of l)Object.hasOwn(u,p)&&(u=u[p]);if(!u)return;let c=n&&a in n?n[a]:a;if(!c)throw new Error(`Invalid field name: ${a}`);i[c]=u}),i}).filter(o=>Object.keys(o).length!==0)}};var bu=$n(Vu("crypto"),1);function Ei(s){let e=new Date().toISOString();return{version:1,sections:{},stats:{bulletCount:0,helpfulCount:0,harmfulCount:0,tokenEstimate:0},updatedAt:e,description:s}}function Gt(s){return JSON.parse(JSON.stringify(s))}function $p(s){return Math.ceil(s.length/4)}function Pi(s,e,t){let n=[],r=[],{maxSectionSize:o=Number.POSITIVE_INFINITY,allowDynamicSections:i=!0,enableAutoPrune:a=!1,protectedBulletIds:l}=t??{},u=new Date().toISOString(),c=l??new Set;for(let p of e){if(!p.section)continue;if(!s.sections[p.section]){if(!i)continue;s.sections[p.section]=[]}let d=s.sections[p.section];switch(p.type){case"ADD":{if(d.length>=o){if(!a)continue;let f=Dp(d,c);if(!f)continue;n.push(f.id),r.push({type:"REMOVE",section:p.section,bulletId:f.id,metadata:{...f.metadata??{},autoPruned:!0,removedAt:u}})}let m=p.bulletId??Np(p.section),g={id:m,section:p.section,content:p.content??"",helpfulCount:0,harmfulCount:0,createdAt:u,updatedAt:u,metadata:p.metadata?{...p.metadata}:void 0};d.push(g),n.push(m);break}case"UPDATE":{let m=d.find(g=>g.id===p.bulletId);if(!m)continue;typeof p.content=="string"&&(m.content=p.content),m.updatedAt=u,p.metadata&&(m.metadata={...m.metadata??{},...p.metadata}),n.push(m.id);break}case"REMOVE":{let m=d.findIndex(g=>g.id===p.bulletId);if(m>=0){let[g]=d.splice(m,1);g&&n.push(g.id)}break}}}return $i(s),s.updatedAt=u,{updatedBulletIds:n,autoRemoved:r}}function Fi(s,e,t){for(let n of Object.values(s.sections)){let r=n.find(o=>o.id===e);if(r){t==="helpful"?r.helpfulCount+=1:t==="harmful"&&(r.harmfulCount+=1),r.updatedAt=new Date().toISOString(),$i(s);return}}}function yr(s){let e=s.description?`## Context Playbook
475
- ${s.description.trim()}
481
+ `.trim(),o=new Ce("count:number -> examples:json");o.setInstruction(r);try{let s=await o.forward(this.options.teacher,{count:e},{model:this.options.model});return Array.isArray(s.examples)?s.examples.slice(0,e):[]}catch(s){return console.warn("AxSynth: Edge case generation failed:",s),[]}}async labelInput(e){return await new Ce(this.signature).forward(this.options.teacher,e,{model:this.options.model})}getSignature(){return this.signature}getTeacher(){return this.options.teacher}};var Jo=class i{gen;options;tracer;currentScore;constructor(e,t){this.gen=e,this.options={...t,enableTracing:t.enableTracing??!0},this.tracer=new Cn(e,{name:this.options.name,storage:this.options.storage,metadata:this.options.metadata,onTrace:this.options.onTrace}),this.loadLatestCheckpoint()}async forward(e,t,n){return this.options.enableTracing?this.tracer.forward(e,t,n):this.gen.forward(e,t,n)}async*streamingForward(e,t,n){this.options.enableTracing?yield*this.tracer.streamingForward(e,t,n):yield*this.gen.streamingForward(e,t,n)}getUsage(){return this.gen.getUsage()}resetUsage(){this.gen.resetUsage()}getSignature(){return this.gen.getSignature()}setInstruction(e){this.gen.setInstruction(e)}getInstruction(){return this.gen.getInstruction()}updateMeter(e){this.gen.updateMeter(e)}addAssert(e,t){this.gen.addAssert(e,t)}addStreamingAssert(e,t,n){this.gen.addStreamingAssert(e,t,n)}addFieldProcessor(e,t){this.gen.addFieldProcessor(e,t)}addStreamingFieldProcessor(e,t){this.gen.addStreamingFieldProcessor(e,t)}clone(){return new i(this.gen.clone(),this.options)}async optimize(e={}){let t=Date.now(),n={...this.options,...e},r=n.teacher,o=n.budget??20,s=[...n.examples??[]];if(n.useTraces!==!1){let w=(await this.getTraces()).filter(M=>M.input&&M.output).map(M=>({...M.input,...M.output}));s=[...s,...w]}if(n.generateExamples||s.length===0){let S=n.synthCount??20,w={teacher:r,...n.synthOptions},k=(await new Rn(this.gen.getSignature(),w).generate(S)).examples.map(F=>({...F.input,...F.expected}));s=[...s,...k]}if(s.length===0)throw new Error("No training examples available. Provide examples, enable trace usage, or enable example generation.");let a=n.validationSplit??.2,l=[...s].sort(()=>Math.random()-.5),u=Math.floor(l.length*(1-a)),c=l.slice(0,u),p=l.slice(u),d=n.metric;if(!d){let S={ai:r,criteria:n.criteria,...n.judgeOptions};d=new Tn(this.gen.getSignature(),S).toMetricFn()}let m=new wn({studentAI:r,numTrials:o,minibatch:!0,minibatchSize:10}),g=o*Math.max(c.length,10),h=await m.compile(this.gen,c,d,{validationExamples:p,maxMetricCalls:g});if(!h.optimizedProgram)throw new Error("GEPA optimization failed: no optimizedProgram returned");h.optimizedProgram.instruction&&this.gen.setInstruction(h.optimizedProgram.instruction),this.currentScore=h.optimizedProgram.bestScore,this.tracer=this.tracer.clone(this.gen);let f=this.currentScore,x=f,y=((await this.options.storage.load(this.options.name,{type:"checkpoint",limit:1}))[0]?.version??0)+1,b={type:"checkpoint",name:this.options.name,version:y,createdAt:new Date,instruction:this.gen.getInstruction(),score:f,optimizerType:"gepa",metadata:{budget:o,trainingExamples:c.length,durationMs:Date.now()-t}};return await this.options.storage.save(this.options.name,b),{score:f,improvement:x,checkpointVersion:y,stats:{trainingExamples:c.length,validationExamples:p.length,durationMs:Date.now()-t}}}async loadLatestCheckpoint(){try{let t=(await this.options.storage.load(this.options.name,{type:"checkpoint",limit:1}))[0];t?.instruction&&(this.gen.setInstruction(t.instruction),this.currentScore=t.score,this.tracer=this.tracer.clone(this.gen))}catch{}}getGen(){return this.gen}getStorage(){return this.options.storage}async getTraces(e){return this.options.storage.load(this.options.name,{type:"trace",...e})}async addFeedback(e,t){let n=await this.options.storage.load(this.options.name,{id:e,type:"trace",limit:1});if(n.length>0){let r=n[0];r.feedback={...r.feedback,...t},await this.options.storage.save(this.options.name,r)}}};var Yo=class{rows=[];baseUrl;dataset;split;config;options;constructor({dataset:e,split:t,config:n,options:r}){this.baseUrl="https://datasets-server.huggingface.co/rows",this.dataset=e,this.split=t,this.config=n,this.options=r}async fetchDataFromAPI(e){try{let t=await fetch(e);if(!t.ok)throw new Error(`Error fetching data: ${t.statusText}`);let n=await t.json();if(!n?.rows)throw new Error("Invalid data format");return n.rows}catch(t){throw console.error("Error fetching data from API:",t),t}}async loadData(){let e=this.options?.offset??0,t=this.options?.length??100,n=encodeURIComponent(this.dataset),r=`${this.baseUrl}?dataset=${n}&config=${this.config}&split=${this.split}&offset=${e}&length=${t}`;return this.rows=await this.fetchDataFromAPI(r),this.rows}setData(e){this.rows=e}getData(){return this.rows}async getRows({count:e,fields:t,renameMap:n}){if(this.rows.length===0)throw new Error("No data loaded, call loadData or setData first.");return this.rows.slice(0,e).map(o=>{let s={};return t.forEach(a=>{let l=a.split("."),u=o.row;for(let p of l)Object.hasOwn(u,p)&&(u=u[p]);if(!u)return;let c=n&&a in n?n[a]:a;if(!c)throw new Error(`Invalid field name: ${a}`);s[c]=u}),s}).filter(o=>Object.keys(o).length!==0)}};var Cu=$n(Yu("crypto"),1);function Fi(i){let e=new Date().toISOString();return{version:1,sections:{},stats:{bulletCount:0,helpfulCount:0,harmfulCount:0,tokenEstimate:0},updatedAt:e,description:i}}function Lt(i){return JSON.parse(JSON.stringify(i))}function Lp(i){return Math.ceil(i.length/4)}function _i(i,e,t){let n=[],r=[],{maxSectionSize:o=Number.POSITIVE_INFINITY,allowDynamicSections:s=!0,enableAutoPrune:a=!1,protectedBulletIds:l}=t??{},u=new Date().toISOString(),c=l??new Set;for(let p of e){if(!p.section)continue;if(!i.sections[p.section]){if(!s)continue;i.sections[p.section]=[]}let d=i.sections[p.section];switch(p.type){case"ADD":{if(d.length>=o){if(!a)continue;let h=Bp(d,c);if(!h)continue;n.push(h.id),r.push({type:"REMOVE",section:p.section,bulletId:h.id,metadata:{...h.metadata??{},autoPruned:!0,removedAt:u}})}let m=p.bulletId??Up(p.section),g={id:m,section:p.section,content:p.content??"",helpfulCount:0,harmfulCount:0,createdAt:u,updatedAt:u,metadata:p.metadata?{...p.metadata}:void 0};d.push(g),n.push(m);break}case"UPDATE":{let m=d.find(g=>g.id===p.bulletId);if(!m)continue;typeof p.content=="string"&&(m.content=p.content),m.updatedAt=u,p.metadata&&(m.metadata={...m.metadata??{},...p.metadata}),n.push(m.id);break}case"REMOVE":{let m=d.findIndex(g=>g.id===p.bulletId);if(m>=0){let[g]=d.splice(m,1);g&&n.push(g.id)}break}}}return Di(i),i.updatedAt=u,{updatedBulletIds:n,autoRemoved:r}}function $i(i,e,t){for(let n of Object.values(i.sections)){let r=n.find(o=>o.id===e);if(r){t==="helpful"?r.helpfulCount+=1:t==="harmful"&&(r.harmfulCount+=1),r.updatedAt=new Date().toISOString(),Di(i);return}}}function br(i){let e=i.description?`## Context Playbook
482
+ ${i.description.trim()}
476
483
  `:`## Context Playbook
477
- `,t=Object.entries(s.sections).map(([n,r])=>{let o=r.map(i=>`- [${i.id}] ${i.content}`).join(`
484
+ `,t=Object.entries(i.sections).map(([n,r])=>{let o=r.map(s=>`- [${s.id}] ${s.content}`).join(`
478
485
  `);return o?`### ${n}
479
486
  ${o}`:`### ${n}
480
487
  _(empty)_`}).join(`
481
488
 
482
489
  `);return`${e}
483
- ${t}`.trim()}function Np(s){let e=s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,6),t=bu.default.randomBytes(4).toString("hex");return`${e||"ctx"}-${t}`}function Dp(s,e){let t=-1,n;for(let o=0;o<s.length;o+=1){let i=s[o];if(e.has(i.id))continue;let a=i.helpfulCount??0,l=i.harmfulCount??0,u=a-l*2,c=Date.parse(i.updatedAt??i.createdAt),p=[u,a,Number.isFinite(c)?c:Number.POSITIVE_INFINITY];if(!n){t=o,n=p;continue}let d=s[t],m=d.helpfulCount??0,g=d.harmfulCount??0,f=m-g*2,h=Date.parse(d.updatedAt??d.createdAt),x=[f,m,Number.isFinite(h)?h:Number.POSITIVE_INFINITY];(p[0]<x[0]||p[0]===x[0]&&p[1]<x[1]||p[0]===x[0]&&p[1]===x[1]&&p[2]<x[2])&&(t=o,n=p)}if(t===-1)return;let[r]=s.splice(t,1);return r}function _i(s,e=.95){for(let[t,n]of Object.entries(s.sections)){let r=new Map,o=[];for(let i of n){let a=i.content.trim().toLowerCase(),l=r.get(a);l?(l.helpfulCount+=i.helpfulCount,l.harmfulCount+=i.harmfulCount,l.updatedAt=i.updatedAt):(r.set(a,i),o.push(i))}s.sections[t]=o}$i(s)}function $i(s){let e=0,t=0,n=0,r=0;for(let o of Object.values(s.sections))for(let i of o)e+=1,t+=i.helpfulCount,n+=i.harmfulCount,r+=$p(i.content);s.stats={bulletCount:e,helpfulCount:t,harmfulCount:n,tokenEstimate:r}}var Lp={maxEpochs:1,maxReflectorRounds:2,maxSectionSize:25,similarityThreshold:.95,allowDynamicSections:!0},br=class extends mt{playbook;artifact;baseInstruction;constructor(e){super({bestScore:e.bestScore,stats:e.stats,instruction:e.instruction,demos:e.demos,examples:e.examples,modelConfig:e.modelConfig,optimizerType:e.optimizerType,optimizationTime:e.optimizationTime,totalRounds:e.totalRounds,converged:e.converged,scoreHistory:e.scoreHistory,configurationHistory:e.configurationHistory}),this.playbook=Gt(e.playbook),this.artifact=e.artifact,this.baseInstruction=e.baseInstruction}applyTo(e){super.applyTo(e);let t=e.getSignature(),r=[(this.baseInstruction??t.getDescription()??"").trim(),"",yr(this.playbook)].filter(o=>o&&o.trim().length>0).join(`
490
+ ${t}`.trim()}function Up(i){let e=i.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,6),t=Cu.default.randomBytes(4).toString("hex");return`${e||"ctx"}-${t}`}function Bp(i,e){let t=-1,n;for(let o=0;o<i.length;o+=1){let s=i[o];if(e.has(s.id))continue;let a=s.helpfulCount??0,l=s.harmfulCount??0,u=a-l*2,c=Date.parse(s.updatedAt??s.createdAt),p=[u,a,Number.isFinite(c)?c:Number.POSITIVE_INFINITY];if(!n){t=o,n=p;continue}let d=i[t],m=d.helpfulCount??0,g=d.harmfulCount??0,h=m-g*2,f=Date.parse(d.updatedAt??d.createdAt),x=[h,m,Number.isFinite(f)?f:Number.POSITIVE_INFINITY];(p[0]<x[0]||p[0]===x[0]&&p[1]<x[1]||p[0]===x[0]&&p[1]===x[1]&&p[2]<x[2])&&(t=o,n=p)}if(t===-1)return;let[r]=i.splice(t,1);return r}function Ni(i,e=.95){for(let[t,n]of Object.entries(i.sections)){let r=new Map,o=[];for(let s of n){let a=s.content.trim().toLowerCase(),l=r.get(a);l?(l.helpfulCount+=s.helpfulCount,l.harmfulCount+=s.harmfulCount,l.updatedAt=s.updatedAt):(r.set(a,s),o.push(s))}i.sections[t]=o}Di(i)}function Di(i){let e=0,t=0,n=0,r=0;for(let o of Object.values(i.sections))for(let s of o)e+=1,t+=s.helpfulCount,n+=s.harmfulCount,r+=Lp(s.content);i.stats={bulletCount:e,helpfulCount:t,harmfulCount:n,tokenEstimate:r}}var jp={maxEpochs:1,maxReflectorRounds:2,maxSectionSize:25,similarityThreshold:.95,allowDynamicSections:!0},Ir=class extends mt{playbook;artifact;baseInstruction;constructor(e){super({bestScore:e.bestScore,stats:e.stats,instruction:e.instruction,demos:e.demos,examples:e.examples,modelConfig:e.modelConfig,optimizerType:e.optimizerType,optimizationTime:e.optimizationTime,totalRounds:e.totalRounds,converged:e.converged,scoreHistory:e.scoreHistory,configurationHistory:e.configurationHistory}),this.playbook=Lt(e.playbook),this.artifact=e.artifact,this.baseInstruction=e.baseInstruction}applyTo(e){super.applyTo(e);let t=e.getSignature(),r=[(this.baseInstruction??t.getDescription()??"").trim(),"",br(this.playbook)].filter(o=>o&&o.trim().length>0).join(`
484
491
 
485
- `);e.setDescription(r)}},Yo=class extends je{aceConfig;playbook;generatorHistory=[];deltaHistory=[];reflectorProgram;curatorProgram;program;constructor(e,t){super(e),this.aceConfig={...Lp,...t},this.playbook=t?.initialPlaybook!==void 0?Gt(t.initialPlaybook):Ei()}reset(){super.reset(),this.playbook=this.aceConfig.initialPlaybook!==void 0?Gt(this.aceConfig.initialPlaybook):Ei(),this.generatorHistory=[],this.deltaHistory=[]}configureAuto(e){switch(e){case"light":this.aceConfig.maxEpochs=1,this.aceConfig.maxReflectorRounds=1;break;case"medium":this.aceConfig.maxEpochs=2,this.aceConfig.maxReflectorRounds=2;break;case"heavy":this.aceConfig.maxEpochs=3,this.aceConfig.maxReflectorRounds=3;break}}async compile(e,t,n,r){let o=r?.aceOptions;o&&(Object.assign(this.aceConfig,{maxEpochs:o.maxEpochs??this.aceConfig.maxEpochs,maxReflectorRounds:o.maxReflectorRounds??this.aceConfig.maxReflectorRounds,maxSectionSize:o.maxSectionSize??this.aceConfig.maxSectionSize,similarityThreshold:o.similarityThreshold??this.aceConfig.similarityThreshold,allowDynamicSections:o.allowDynamicSections??this.aceConfig.allowDynamicSections}),o.initialPlaybook&&(this.playbook=Gt(o.initialPlaybook)));let i=Date.now();this.validateExamples(t),this.program=e;let a=await this.extractProgramInstruction(e),l=e.getSignature().getDescription()??"";this.generatorHistory=[],this.deltaHistory=[];let u=Number.NEGATIVE_INFINITY,c=0,p=Math.max(this.aceConfig.maxEpochs,1),d=p*t.length;try{for(let x=0;x<p;x++)for(let A=0;A<t.length;A++){let y=t[A],b=this.composeInstruction(a??l,this.playbook);e.setDescription?.(b);let k=await e.forward(this.studentAI,y);this.stats.totalCalls+=1;let S=await n({prediction:k,example:y});typeof S=="number"&&(this.stats.bestScore=Math.max(this.stats.bestScore,S),u=Math.max(u,S));let M=k?.severity,R=y?.severity,O=this.createGeneratorOutput(k,y),F=R&&M&&R!==M,P=await this.runReflectionRounds({example:y,generatorOutput:O,feedback:R&&M&&R!==M?`Expected severity "${R}" but model predicted "${M}".`:void 0}),I=await this.runCurator({program:e,example:y,reflection:P,playbook:this.playbook}),v=this.normalizeCuratorOperations(I?.operations);v.length===0&&F&&(v=this.inferOperationsFromReflection(P)),v=this.resolveCuratorOperationTargets(v,this.playbook,P,O);let T=I||v.length>0?{...I??{},operations:v}:void 0,w=[];if(v.length>0){let L=this.collectProtectedBulletIds(v),D=Pi(this.playbook,v,{maxSectionSize:this.aceConfig.maxSectionSize,allowDynamicSections:this.aceConfig.allowDynamicSections,enableAutoPrune:!0,protectedBulletIds:L});w=D.updatedBulletIds,D.autoRemoved.length>0&&(v.push(...D.autoRemoved),T&&(T.operations=v))}if(P?.bulletTags)for(let L of P.bulletTags)Fi(this.playbook,L.id,L.tag);v.length>0&&w.length>0&&_i(this.playbook,this.aceConfig.similarityThreshold);let C={example:y,prediction:k,score:typeof S=="number"?S:0,generatorOutput:O,reflection:P,curator:T,timestamp:new Date().toISOString()};this.generatorHistory.push(C),w.length>0&&T?.operations?.length&&this.deltaHistory.push({epoch:x,exampleIndex:A,operations:T.operations}),c+=1,this.currentRound=c;let E=typeof S=="number"&&Number.isFinite(S)?S:0,_=Number.isFinite(u)?u:E,$={...r??{},maxIterations:d};await this.updateOptimizationProgress(c,E,{epoch:x,exampleIndex:A,playbookBullets:this.playbook.stats.bulletCount},"ACE",{epochs:p,totalRounds:d},_,{playbookBullets:this.playbook.stats.bulletCount},void 0,$),this.stats.convergenceInfo.finalImprovement=Math.max(this.stats.convergenceInfo.finalImprovement,E)}}finally{e.setDescription?.(l)}let m=Date.now()-i;this.stats.resourceUsage.totalTime=m,this.stats.convergenceInfo.converged=!0,this.stats.bestScore=Number.isFinite(u)?u:0;let g={playbook:Gt(this.playbook),feedback:[...this.generatorHistory],history:[...this.deltaHistory]},f=new br({baseInstruction:a??l,playbook:this.playbook,artifact:g,bestScore:Number.isFinite(u)?u:0,stats:this.stats,optimizerType:"ACE",optimizationTime:m,totalRounds:c,converged:this.stats.convergenceInfo.converged});return{stats:this.stats,bestScore:Number.isFinite(u)?u:0,finalConfiguration:{strategy:"ace",epochs:p},optimizedProgram:f,playbook:Gt(this.playbook),artifact:g}}async applyOnlineUpdate(e){if(!this.program)throw new Error("AxACE: `compile` must be run before `applyOnlineUpdate`");let t=this.createGeneratorOutput(e.prediction,e.example),n=e.prediction?.severity,r=e.example?.severity,o=await this.runReflectionRounds({example:e.example,generatorOutput:t,feedback:e.feedback??(r&&n&&r!==n?`Expected severity "${r}" but model predicted "${n}".`:void 0)}),i=await this.runCurator({program:this.program,example:e.example,reflection:o,playbook:this.playbook}),a=this.normalizeCuratorOperations(i?.operations),l=r&&n&&r!==n;a.length===0&&l&&(a=this.inferOperationsFromReflection(o)),a=this.resolveCuratorOperationTargets(a,this.playbook,o,t);let u=i||a.length>0?{...i??{},operations:a}:void 0;if(o?.bulletTags)for(let p of o.bulletTags)Fi(this.playbook,p.id,p.tag);if(a.length>0){let p=this.collectProtectedBulletIds(a),d=Pi(this.playbook,a,{maxSectionSize:this.aceConfig.maxSectionSize,allowDynamicSections:this.aceConfig.allowDynamicSections,enableAutoPrune:!0,protectedBulletIds:p});d.autoRemoved.length>0&&(a.push(...d.autoRemoved),u&&(u.operations=a)),_i(this.playbook,this.aceConfig.similarityThreshold)}let c={example:e.example,prediction:e.prediction,score:0,generatorOutput:t,reflection:o,curator:u,timestamp:new Date().toISOString()};return this.generatorHistory.push(c),u}composeInstruction(e,t){return[e.trim(),"",yr(t)].filter(r=>r.trim().length>0).join(`
492
+ `);e.setDescription(r)}},Qo=class extends je{aceConfig;playbook;generatorHistory=[];deltaHistory=[];reflectorProgram;curatorProgram;program;constructor(e,t){super(e),this.aceConfig={...jp,...t},this.playbook=t?.initialPlaybook!==void 0?Lt(t.initialPlaybook):Fi()}reset(){super.reset(),this.playbook=this.aceConfig.initialPlaybook!==void 0?Lt(this.aceConfig.initialPlaybook):Fi(),this.generatorHistory=[],this.deltaHistory=[]}configureAuto(e){switch(e){case"light":this.aceConfig.maxEpochs=1,this.aceConfig.maxReflectorRounds=1;break;case"medium":this.aceConfig.maxEpochs=2,this.aceConfig.maxReflectorRounds=2;break;case"heavy":this.aceConfig.maxEpochs=3,this.aceConfig.maxReflectorRounds=3;break}}async compile(e,t,n,r){let o=r?.aceOptions;o&&(Object.assign(this.aceConfig,{maxEpochs:o.maxEpochs??this.aceConfig.maxEpochs,maxReflectorRounds:o.maxReflectorRounds??this.aceConfig.maxReflectorRounds,maxSectionSize:o.maxSectionSize??this.aceConfig.maxSectionSize,similarityThreshold:o.similarityThreshold??this.aceConfig.similarityThreshold,allowDynamicSections:o.allowDynamicSections??this.aceConfig.allowDynamicSections}),o.initialPlaybook&&(this.playbook=Lt(o.initialPlaybook)));let s=Date.now();this.validateExamples(t),this.program=e;let a=await this.extractProgramInstruction(e),l=e.getSignature().getDescription()??"";this.generatorHistory=[],this.deltaHistory=[];let u=Number.NEGATIVE_INFINITY,c=0,p=Math.max(this.aceConfig.maxEpochs,1),d=p*t.length;try{for(let x=0;x<p;x++)for(let A=0;A<t.length;A++){let y=t[A],b=this.composeInstruction(a??l,this.playbook);e.setDescription?.(b);let S=await e.forward(this.studentAI,y);this.stats.totalCalls+=1;let w=await n({prediction:S,example:y});typeof w=="number"&&(this.stats.bestScore=Math.max(this.stats.bestScore,w),u=Math.max(u,w));let M=S?.severity,R=y?.severity,k=this.createGeneratorOutput(S,y),F=R&&M&&R!==M,E=await this.runReflectionRounds({example:y,generatorOutput:k,feedback:R&&M&&R!==M?`Expected severity "${R}" but model predicted "${M}".`:void 0}),T=await this.runCurator({program:e,example:y,reflection:E,playbook:this.playbook}),v=this.normalizeCuratorOperations(T?.operations);v.length===0&&F&&(v=this.inferOperationsFromReflection(E)),v=this.resolveCuratorOperationTargets(v,this.playbook,E,k);let C=T||v.length>0?{...T??{},operations:v}:void 0,O=[];if(v.length>0){let N=this.collectProtectedBulletIds(v),L=_i(this.playbook,v,{maxSectionSize:this.aceConfig.maxSectionSize,allowDynamicSections:this.aceConfig.allowDynamicSections,enableAutoPrune:!0,protectedBulletIds:N});O=L.updatedBulletIds,L.autoRemoved.length>0&&(v.push(...L.autoRemoved),C&&(C.operations=v))}if(E?.bulletTags)for(let N of E.bulletTags)$i(this.playbook,N.id,N.tag);v.length>0&&O.length>0&&Ni(this.playbook,this.aceConfig.similarityThreshold);let I={example:y,prediction:S,score:typeof w=="number"?w:0,generatorOutput:k,reflection:E,curator:C,timestamp:new Date().toISOString()};this.generatorHistory.push(I),O.length>0&&C?.operations?.length&&this.deltaHistory.push({epoch:x,exampleIndex:A,operations:C.operations}),c+=1,this.currentRound=c;let P=typeof w=="number"&&Number.isFinite(w)?w:0,_=Number.isFinite(u)?u:P,$={...r??{},maxIterations:d};await this.updateOptimizationProgress(c,P,{epoch:x,exampleIndex:A,playbookBullets:this.playbook.stats.bulletCount},"ACE",{epochs:p,totalRounds:d},_,{playbookBullets:this.playbook.stats.bulletCount},void 0,$),this.stats.convergenceInfo.finalImprovement=Math.max(this.stats.convergenceInfo.finalImprovement,P)}}finally{e.setDescription?.(l)}let m=Date.now()-s;this.stats.resourceUsage.totalTime=m,this.stats.convergenceInfo.converged=!0,this.stats.bestScore=Number.isFinite(u)?u:0;let g={playbook:Lt(this.playbook),feedback:[...this.generatorHistory],history:[...this.deltaHistory]},h=new Ir({baseInstruction:a??l,playbook:this.playbook,artifact:g,bestScore:Number.isFinite(u)?u:0,stats:this.stats,optimizerType:"ACE",optimizationTime:m,totalRounds:c,converged:this.stats.convergenceInfo.converged});return{stats:this.stats,bestScore:Number.isFinite(u)?u:0,finalConfiguration:{strategy:"ace",epochs:p},optimizedProgram:h,playbook:Lt(this.playbook),artifact:g}}async applyOnlineUpdate(e){if(!this.program)throw new Error("AxACE: `compile` must be run before `applyOnlineUpdate`");let t=this.createGeneratorOutput(e.prediction,e.example),n=e.prediction?.severity,r=e.example?.severity,o=await this.runReflectionRounds({example:e.example,generatorOutput:t,feedback:e.feedback??(r&&n&&r!==n?`Expected severity "${r}" but model predicted "${n}".`:void 0)}),s=await this.runCurator({program:this.program,example:e.example,reflection:o,playbook:this.playbook}),a=this.normalizeCuratorOperations(s?.operations),l=r&&n&&r!==n;a.length===0&&l&&(a=this.inferOperationsFromReflection(o)),a=this.resolveCuratorOperationTargets(a,this.playbook,o,t);let u=s||a.length>0?{...s??{},operations:a}:void 0;if(o?.bulletTags)for(let p of o.bulletTags)$i(this.playbook,p.id,p.tag);if(a.length>0){let p=this.collectProtectedBulletIds(a),d=_i(this.playbook,a,{maxSectionSize:this.aceConfig.maxSectionSize,allowDynamicSections:this.aceConfig.allowDynamicSections,enableAutoPrune:!0,protectedBulletIds:p});d.autoRemoved.length>0&&(a.push(...d.autoRemoved),u&&(u.operations=a)),Ni(this.playbook,this.aceConfig.similarityThreshold)}let c={example:e.example,prediction:e.prediction,score:0,generatorOutput:t,reflection:o,curator:u,timestamp:new Date().toISOString()};return this.generatorHistory.push(c),u}composeInstruction(e,t){return[e.trim(),"",br(t)].filter(r=>r.trim().length>0).join(`
486
493
 
487
- `)}async extractProgramInstruction(e){try{return e.getSignature().getDescription()??void 0}catch{return}}createGeneratorOutput(e,t){let n=e?.thought?.toString()??"",r=Array.isArray(e?.bullet_ids)?e?.bullet_ids:[];return{reasoning:n,answer:e,bulletIds:r,trajectory:JSON.stringify({example:t,prediction:e}),metadata:{predictedSeverity:e?.severity,expectedSeverity:t?.severity}}}resolveCuratorOperationTargets(e,t,n,r){if(!e.length)return e;let o=[],i=new Set(e.map(c=>c.bulletId).filter(c=>typeof c=="string")),a=new Map,l=(c,p)=>{if(i.has(c))return;let d=this.locateBullet(t,c);if(!d)return;let m=a.get(d.section)??{harmful:[],primary:[],generator:[]};m[p].push(d.id),a.set(d.section,m)};for(let c of n?.bulletTags??[]){let p=c.tag==="harmful"?"harmful":"primary";l(c.id,p)}if(r?.bulletIds)for(let c of r.bulletIds)l(c,"generator");let u=c=>{let p=a.get(c);if(!p)return this.locateFallbackBullet(t,c,i);let d=g=>{for(;g.length>0;){let f=g.shift();if(!i.has(f))return f}},m=d(p.harmful)??d(p.primary)??d(p.generator);return m||this.locateFallbackBullet(t,c,i)};for(let c of e){if((c.type==="UPDATE"||c.type==="REMOVE")&&!c.bulletId){let p=u(c.section);p&&(c.bulletId=p,i.add(p))}(c.type==="UPDATE"||c.type==="REMOVE")&&!c.bulletId||o.push(c)}return o}locateBullet(e,t){for(let n of Object.values(e.sections)){let r=n.find(o=>o.id===t);if(r)return r}}locateFallbackBullet(e,t,n){let r=e.sections[t]??[];for(let o of r)if(!n.has(o.id))return o.id}collectProtectedBulletIds(e){let t=new Set;for(let n of e)n.type==="UPDATE"&&n.bulletId&&t.add(n.bulletId);return t}normalizeCuratorOperations(e){if(!e)return[];if(Array.isArray(e)){let t=[],n=new Set;for(let r of e){if(!r||typeof r!="object")continue;let o=r.type??"ADD",i=typeof o=="string"?o.toUpperCase():"ADD",a=i==="UPDATE"?"UPDATE":i==="REMOVE"?"REMOVE":"ADD",l=r.section??"Guidelines",u=typeof l=="string"&&l.trim().length>0?l.trim():"Guidelines",c=r.content??"",p=typeof c=="string"?c.trim():"";if(a!=="REMOVE"&&p.length===0)continue;let d=r.bulletId??r.id,m=typeof d=="string"&&d.trim().length>0?d.trim():void 0,f=[a,u,p,m??""].join(":");if(n.has(f))continue;n.add(f);let h={type:a,section:u};a!=="REMOVE"&&(h.content=p),m&&(h.bulletId=m);let x=r.metadata;x&&typeof x=="object"&&(h.metadata={...x}),t.push(h)}return t}if(typeof e=="string")try{let t=JSON.parse(e);return this.normalizeCuratorOperations(t)}catch{return[]}if(typeof e=="object"){let t=e;if(t&&Array.isArray(t.operations))return this.normalizeCuratorOperations(t.operations);if(t&&typeof t.operations=="string")try{let n=JSON.parse(t.operations);return this.normalizeCuratorOperations(n)}catch{return[]}return[]}return[]}inferOperationsFromReflection(e){if(!e)return[];let t=[],n=new Set,r=(o,i)=>{if(!i)return;let a=i.trim();if(!a||a.toLowerCase().startsWith("no error"))return;let u=`${o}:${a}`;n.has(u)||(n.add(u),t.push({type:"ADD",section:o,content:a}))};return r("Guidelines",e.keyInsight),r("Response Strategies",e.correctApproach),r("Common Pitfalls",e.errorIdentification),r("Root Cause Notes",e.rootCauseAnalysis),t}async runReflectionRounds({example:e,generatorOutput:t,feedback:n}){let r=Math.max(this.aceConfig.maxReflectorRounds,1),o;for(let i=0;i<r;i++){let a=await this.runReflector({example:e,generatorOutput:t,feedback:n,previousReflection:o});if(!a)break;o=a;let l=a.errorIdentification?.toLowerCase().trim()??"";if(a.metadata?.resolved===!0||l.length===0||l.startsWith("no error")||l.startsWith("resolved"))break}return o}async runReflector({example:e,generatorOutput:t,feedback:n,previousReflection:r}){let o=this.getOrCreateReflectorProgram(),i=this.teacherAI??this.studentAI;try{let a={severity:e?.severity,policyHint:e?.policyHint},c=(this.program?.getSignature()?.getInputFields()??[]).reduce((d,m)=>(m.name in e&&(d[m.name]=e[m.name]),d),{});return await o.forward(i,{question:JSON.stringify(c),generator_answer:JSON.stringify(t.answer),generator_reasoning:t.reasoning,playbook:JSON.stringify({markdown:yr(this.playbook),structured:this.playbook}),expected_answer:a.severity||a.policyHint?JSON.stringify(a):void 0,feedback:n,previous_reflection:r?JSON.stringify(r):void 0})}catch(a){this.verbose&&console.warn("[AxACE] Reflector error:",a instanceof Error?a.message:a);return}}async runCurator({program:e,example:t,reflection:n,playbook:r}){if(!n)return;let o=this.getOrCreateCuratorProgram(),i=this.teacherAI??this.studentAI,u=e.getSignature().getInputFields().reduce((c,p)=>(p.name in t&&(c[p.name]=t[p.name]),c),{});try{return await o.forward(i,{playbook:JSON.stringify({markdown:yr(r),structured:r}),reflection:JSON.stringify(n),question_context:JSON.stringify(u),token_budget:1024})}catch(c){this.verbose&&console.warn("[AxACE] Curator error:",c instanceof Error?c.message:c);return}}getOrCreateReflectorProgram(){if(!this.reflectorProgram){let e=ue().input("question",ue.string("Original task input serialized as JSON")).input("generator_answer",ue.string("Generator output serialized as JSON")).input("generator_reasoning",ue.string("Generator reasoning trace").optional()).input("playbook",ue.string("Current context playbook rendered as markdown")).input("expected_answer",ue.string("Expected output when ground truth is available").optional()).input("feedback",ue.string("External feedback or reward signal").optional()).input("previous_reflection",ue.string("Most recent reflection JSON when running multi-round refinement").optional()).output("reasoning",ue.string("Step-by-step analysis of generator performance")).output("errorIdentification",ue.string("Specific mistakes detected")).output("rootCauseAnalysis",ue.string("Underlying cause of the error")).output("correctApproach",ue.string("What the generator should do differently")).output("keyInsight",ue.string("Reusable insight to remember")).output("bulletTags",ue.json("Array of {id, tag} entries referencing playbook bullets")).build();this.reflectorProgram=_e(e)}return this.reflectorProgram}getOrCreateCuratorProgram(){if(!this.curatorProgram){let e=ue().input("playbook",ue.string("Current playbook serialized as JSON")).input("reflection",ue.string("Latest reflection output serialized as JSON")).input("question_context",ue.string("Original task input serialized as JSON")).input("token_budget",ue.number("Approximate token budget for curator response").optional()).output("reasoning",ue.string("Justification for the proposed updates")).output("operations",ue.json("List of operations with type/section/content fields")).build();this.curatorProgram=_e(e)}return this.curatorProgram}};var vn=class extends je{maxRounds;maxDemos;maxExamples;batchSize;earlyStoppingPatience;costMonitoring;maxTokensPerGeneration;verboseMode;debugMode;traces=[];constructor(e){super(e);let t=e.options||{};this.maxRounds=t.maxRounds??3,this.maxDemos=t.maxDemos??4,this.maxExamples=t.maxExamples??16,this.batchSize=t.batchSize??1,this.earlyStoppingPatience=t.earlyStoppingPatience??0,this.costMonitoring=t.costMonitoring??!1,this.maxTokensPerGeneration=t.maxTokensPerGeneration??0,this.verboseMode=t.verboseMode??!0,this.debugMode=t.debugMode??!1}async compileRound(e,t,n,r,o){let i=Date.now(),a=o?.maxDemos??this.maxDemos,l={modelConfig:{temperature:.7}};this.maxTokensPerGeneration>0&&(l.modelConfig.max_tokens=this.maxTokensPerGeneration);let u=Up([...t],this.maxExamples),c=this.traces.length;for(let p=0;p<u.length;p+=this.batchSize){p>0&&(l.modelConfig.temperature=.7+.001*p);let d=u.slice(p,p+this.batchSize);for(let m of d){if(!m||typeof m!="object")continue;let g=t.filter(x=>x!==m);e.setExamples(g);let f=this.getTeacherOrStudentAI();this.stats.totalCalls++;let h;try{let x={...l,maxRetries:1};h=await e.forward(f,m,x),this.costMonitoring&&(this.stats.estimatedTokenUsage+=JSON.stringify(m).length/4+JSON.stringify(h).length/4),await r({prediction:h,example:m})>=.5&&(this.traces=[...this.traces,...e.getTraces()],this.stats.successfulDemos++)}catch(x){(this.verboseMode||this.debugMode)&&console.warn(`Student model failed during bootstrap: ${x instanceof Error?x.message:"Unknown error"}`),h={}}if(this.traces.length>=a)return}}if(this.earlyStoppingPatience>0){let d=this.traces.length-c;if(!this.stats.earlyStopping)this.stats.earlyStopping={bestScoreRound:d>0?n:0,patienceExhausted:!1,reason:"No improvement detected"};else if(d>0)this.stats.earlyStopping.bestScoreRound=n;else if(n-this.stats.earlyStopping.bestScoreRound>=this.earlyStoppingPatience){this.stats.earlyStopping.patienceExhausted=!0,this.stats.earlyStopped=!0,this.stats.earlyStopping.reason=`No improvement for ${this.earlyStoppingPatience} rounds`;return}}}async compile(e,t,n,r){this.validateExamples(t,!1);let o=r?.maxIterations??this.maxRounds;this.traces=[],this.reset();for(let l=0;l<o&&(await this.compileRound(e,t,l,n,r),!this.stats.earlyStopped);l++);if(this.traces.length===0)throw new Error("No demonstrations found. Either provide more examples or improve the existing ones.");let i=Gp(this.traces),a=0;return this.traces.length>0&&(a=this.stats.successfulDemos/Math.max(1,this.stats.totalCalls)),await this.logOptimizationComplete("BootstrapFewShot",a,{maxRounds:this.maxRounds,maxDemos:this.maxDemos,batchSize:this.batchSize,successRate:a,demosGenerated:i.length,tracesCollected:this.traces.length},r),{demos:i,stats:this.stats,bestScore:a,finalConfiguration:{maxRounds:this.maxRounds,maxDemos:this.maxDemos,batchSize:this.batchSize,successRate:a}}}};function Gp(s){let e=new Map;for(let n of s)if(e.has(n.programId)){let r=e.get(n.programId);r&&r.push(n.trace)}else e.set(n.programId,[n.trace]);let t=[];return e.forEach((n,r)=>{t.push({traces:n,programId:r})}),t}var Up=(s,e)=>{let t=[...s];for(let n=t.length-1;n>0;n--){let r=Math.floor(Math.random()*(n+1)),o=t[n],i=t[r];if(!o||!i)throw new Error("Invalid array elements");[t[n],t[r]]=[i,o]}return t.slice(0,e)};var Qo=class extends je{numTrials;minibatch;minibatchSize;earlyStoppingTrials;minImprovementThreshold;sampleCount;crossoverEvery;tieEpsilon;paretoSetSize;mergeMax;mergesUsed=0;mergesDue=0;totalMergesTested=0;lastIterFoundNewProgram=!1;rngState;mergeAttemptKeys=new Set;mergeCompositionKeys=new Set;samplerState={epoch:-1,shuffled:[],freq:new Map};constructor(e){super(e),this.numTrials=e.numTrials??24,this.minibatch=e.minibatch??!0,this.minibatchSize=e.minibatchSize??8,this.earlyStoppingTrials=e.earlyStoppingTrials??5,this.minImprovementThreshold=e.minImprovementThreshold??0,this.sampleCount=e.sampleCount??1,this.crossoverEvery=Math.max(0,Math.floor(e?.crossoverEvery??Math.max(3,Math.floor(this.numTrials/3)))),this.tieEpsilon=Number.isFinite(e?.tieEpsilon)?Number(e?.tieEpsilon):0;let t=e?.seed,n=Number.isFinite(t)?Math.floor(Number(t)):0;this.rngState=n&&n!==0?n:123456789;let r=e?.paretoSetSize;this.paretoSetSize=r&&r>0?Math.min(1e3,Math.max(5,Math.floor(r))):Math.max(10,Math.min(200,this.minibatchSize*3));let o=e?.mergeMax;this.mergeMax=Math.max(0,Math.floor(o??5)),this.mergesUsed=0,this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}reset(){super.reset(),this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold,this.mergesUsed=0,this.mergesDue=0,this.totalMergesTested=0,this.lastIterFoundNewProgram=!1,this.mergeAttemptKeys.clear(),this.mergeCompositionKeys.clear(),this.samplerState.epoch=-1,this.samplerState.shuffled=[],this.samplerState.freq.clear()}configureAuto(e){switch(e){case"light":this.numTrials=8,this.minibatch=!0,this.minibatchSize=6;break;case"medium":this.numTrials=16,this.minibatch=!0,this.minibatchSize=10;break;case"heavy":this.numTrials=28,this.minibatch=!0,this.minibatchSize=14;break}}async compile(e,t,n,r){let o=Date.now(),i=e;this.validateExamples(t),r?.auto&&this.configureAuto(r.auto);let a=i.getNodePrograms?.();if(!a||a.length===0)throw new Error("AxGEPAFlow: flow has no nodes to optimize");let l=r?.validationExamples,u=r?.feedbackExamples,c=(l&&l.length>0?l:t).slice(0,this.paretoSetSize),p=u&&u.length>0?u:t;this.getOptimizerLogger(r)?.({name:"OptimizationStart",value:{optimizerType:"GEPA-Flow",exampleCount:t.length,validationCount:c.length,config:{numTrials:this.numTrials,minibatch:this.minibatch}}});let m=async(I,v)=>{try{i.setAllNodeInstructions?.(I);let T=await i.forward(this.studentAI,v,{sampleCount:this.sampleCount});return this.stats.totalCalls+=1,await n({prediction:T,example:v})||{}}catch{return{}}},g=async(I,v)=>{let T=[];for(let w of v)T.push(await m(I,w));return Vo(T)},f={};for(let I of a)f[I.name]=await this.getBaseInstruction(I.program);let h=[{cfg:{...f},parent:void 0,scores:await g(f,c)}],x=I=>{let v=r?.paretoMetricKey,T=r?.paretoScalarize;if(typeof T=="function")return T(I);if(v)return Number.isFinite(I[v])?I[v]:0;let w=Object.values(I);return w.length?w.reduce((C,E)=>C+E,0)/w.length:0},A=[],y=async(I,v)=>{let T=[];for(let w of v){let C=await m(I,w);T.push(x(C))}return T};A.push(await y(f,c));let b=gt(h.map((I,v)=>({idx:v,scores:I.scores})),this.tieEpsilon).map(I=>I.idx),k=0,S=new Set,M=r?.maxMetricCalls;if(!Number.isFinite(M)||M<=0)throw new Error("AxGEPA-Flow: options.maxMetricCalls must be set to a positive integer");let R=Math.floor(M);for(let I=0;I<this.numTrials&&!(R!==void 0&&this.stats.totalCalls>=Math.max(1,Math.floor(R)));I++){let v=A[0]?.length??0,T=[];for(let V=0;V<v;V++){let re=Number.NEGATIVE_INFINITY,U=new Set;for(let z=0;z<A.length;z++){let Q=A[z][V];Q>re+this.tieEpsilon?(re=Q,U.clear(),U.add(z)):Math.abs(Q-re)<=this.tieEpsilon&&U.add(z)}T.push(U)}let w=A.map(V=>Lt(V));if(this.mergeMax>0&&this.mergesDue>0&&this.lastIterFoundNewProgram){let V=xr(T,w),re=new Set;for(let G of V)for(let B of G)re.add(B);let U=Array.from(re),z=G=>{let B=[],N=G;for(;N!==void 0;)B.push(N),N=h[N]?.parent;return B},Q=G=>G.length?G[Math.floor(this.rand()*G.length)]:void 0,oe;for(let G=0;G<10&&!oe&&!(U.length<2);G++){let B=Q(U),N=Q(U);if(B===N)continue;N<B&&([B,N]=[N,B]);let K=new Set(z(B)),X=new Set(z(N));if(K.has(N)||X.has(B))continue;let me=[...K].filter(de=>X.has(de));if(me.length===0)continue;let ee=[];for(let de of me){let ht=h[de].cfg,It=h[B].cfg,nt=h[N].cfg,Tt=!1,Ct=new Set([...Object.keys(ht),...Object.keys(It),...Object.keys(nt)]);for(let ft of Ct){let wt=ht[ft],Pt=It[ft],J=nt[ft];if(Pt===wt&&J!==Pt||J===wt&&Pt!==J){Tt=!0;break}}Tt&&ee.push(de)}if(ee.length===0)continue;let se=ee.map(de=>Math.max(1e-9,w[de])),ae=this.rand()*se.reduce((de,ht)=>de+ht,0),pe=ee[ee.length-1];for(let de=0;de<ee.length;de++){if(ae<se[de]){pe=ee[de];break}ae-=se[de]}let Re=w[pe],Me=w[B],Ve=w[N];if(Re>Math.min(Me,Ve))continue;let $e=`${B}|${N}|${pe}`;if(this.mergeAttemptKeys.has($e))continue;this.mergeAttemptKeys.add($e);let ze=`${B}|${N}|${pe}`;S.has(ze)||(oe={i:B,j:N,a:pe})}if(this.lastIterFoundNewProgram=!1,oe){let{i:G,j:B,a:N}=oe,{cfg:K,descSig:X}=this.systemAwareMergeWithSig(h,G,B,(J,Ie)=>w[J]>=w[Ie]?J:Ie),me=`${Math.min(G,B)}|${Math.max(G,B)}|${X}`;if(this.mergeCompositionKeys.has(me))continue;this.mergeCompositionKeys.add(me);let ee=A[G],se=A[B],ae=Array.from({length:ee.length},(J,Ie)=>Ie),pe=ae.filter(J=>(ee[J]??0)>(se[J]??0)),Re=ae.filter(J=>(se[J]??0)>(ee[J]??0)),Me=ae.filter(J=>!(pe.includes(J)||Re.includes(J))),Ve=5,$e=Math.ceil(Ve/3),ze=(J,Ie)=>{if(Ie<=0||J.length===0)return[];if(J.length<=Ie)return[...J];let ct=[],qe=new Set;for(;ct.length<Ie;){let He=Math.floor(this.rand()*J.length);qe.has(He)||(qe.add(He),ct.push(J[He]))}return ct},de=[];de.push(...ze(pe,Math.min($e,pe.length))),de.push(...ze(Re,Math.min($e,Re.length)));let ht=Ve-de.length;de.push(...ze(Me,Math.max(0,ht)));let It=Ve-de.length;if(It>0){let J=ae.filter(Ie=>!de.includes(Ie));de.push(...ze(J,Math.min(It,J.length)))}let nt=de.slice(0,Math.min(Ve,ae.length)),Tt=nt.map(J=>c[J]),ft=(await y(K,Tt)).reduce((J,Ie)=>J+Ie,0),wt=nt.reduce((J,Ie)=>J+(ee[Ie]??0),0),Pt=nt.reduce((J,Ie)=>J+(se[Ie]??0),0);if(ft>=Math.max(wt,Pt)+this.tieEpsilon){let J=await g(K,c);h.push({cfg:K,parent:N,scores:J}),A.push(await y(K,c));let Ie=b.length,ct=tt(b.map(He=>h[He].scores))??0;b=gt(h.map((He,Rr)=>({idx:Rr,scores:He.scores})),this.tieEpsilon).map(He=>He.idx);let qe=tt(b.map(He=>h[He].scores))??0;(b.length>Ie||qe>ct+1e-6)&&(k=0),this.mergesDue-=1,this.totalMergesTested+=1,S.add(`${Math.min(G,B)}|${Math.max(G,B)}|${N}`)}continue}}let C=Ar(T,w,()=>this.rand());this.lastIterFoundNewProgram=!1;let E=this.minibatch?this.nextMinibatchIndices(p.length,I).map(V=>p[V]):p;if(r?.skipPerfectScore??!0){let V=Number(r?.perfectScore??1),re=await y(h[C].cfg,E);if(re.length>0&&re.every(U=>U>=V))continue}let _=!1,$={...h[C].cfg},L="reflective_mutation",D=I%a.length,q=a[D],H,ce;if(_&&this.mergesUsed<this.mergeMax){let V=(C+1)%h.length,re=G=>{let B=[],N=G;for(;N!==void 0;)B.push(N),N=h[N]?.parent;return B},U=re(C),z=re(V),Q=U.find(G=>z.includes(G)),oe=!0;if(Q||(oe=!1),(z.includes(C)||U.includes(V))&&(oe=!1),oe){let G=h[Q].cfg,B=h[C].cfg,N=h[V].cfg,K=!1,X=new Set([...Object.keys(G),...Object.keys(B),...Object.keys(N)]);for(let me of X){let ee=G[me],se=B[me],ae=N[me];if(se===ee&&ae!==se||ae===ee&&se!==ae){K=!0;break}}K||(oe=!1)}if(oe){let G=Math.min(C,V),B=Math.max(C,V),N=`${G}|${B}|${Q}`;if(!S.has(N)){let K=x(h[Q].scores),X=x(h[C].scores),me=x(h[V].scores);K<=Math.min(X,me)&&($=this.systemAwareMerge(h,C,V,(ee,se)=>{let ae=x(h[ee].scores),pe=x(h[se].scores);return ae>=pe?ee:se}),L="system_merge",this.mergesUsed+=1,S.add(N))}}else{let G=h[C].cfg[q.name],B=r?.gepaAdapter,N;if(B)try{let K=await B.evaluate(E,{...h[C].cfg},!0);H=Array.isArray(K?.scores)?K.scores.reduce((se,ae)=>se+(Number(ae)||0),0):void 0;let X=B.make_reflective_dataset({...h[C].cfg},K,[q.name]),ee=(await B.propose_new_texts?.({...h[C].cfg},X,[q.name]))?.[q.name];typeof ee=="string"&&ee.length>0&&(N=ee)}catch{}if(N||(N=await this.reflectModuleInstruction(q.name,G,i,a,{...h[C].cfg},E,async({prediction:K,example:X})=>{let me=await n({prediction:K,example:X}),ee=Object.values(me||{});return ee.length?ee.reduce((se,ae)=>se+ae,0)/ee.length:0},r)),$[q.name]=N,B&&H!==void 0)try{let K=await B.evaluate(E,$,!1);ce=Array.isArray(K?.scores)?K.scores.reduce((X,me)=>X+(Number(me)||0),0):void 0}catch{}}}else{let V=h[C].cfg[q.name],re=r?.gepaAdapter,U;if(re)try{let z=await re.evaluate(E,{...h[C].cfg},!0);H=Array.isArray(z?.scores)?z.scores.reduce((B,N)=>B+(Number(N)||0),0):void 0;let Q=re.make_reflective_dataset({...h[C].cfg},z,[q.name]),G=(await re.propose_new_texts?.({...h[C].cfg},Q,[q.name]))?.[q.name];typeof G=="string"&&G.length>0&&(U=G)}catch{}if(U||(U=await this.reflectModuleInstruction(q.name,V,i,a,{...h[C].cfg},E,async({prediction:z,example:Q})=>{let oe=await n({prediction:z,example:Q}),G=Object.values(oe||{});return G.length?G.reduce((B,N)=>B+N,0)/G.length:0},r)),$[q.name]=U,re&&H!==void 0)try{let z=await re.evaluate(E,$,!1);ce=Array.isArray(z?.scores)?z.scores.reduce((Q,oe)=>Q+(Number(oe)||0),0):void 0}catch{}}let ne=await y(h[C].cfg,E),xe=await y($,E),ye=ne.reduce((V,re)=>V+re,0),Z=xe.reduce((V,re)=>V+re,0);if(this.currentRound=I+1,await this.updateOptimizationProgress(this.currentRound,Z,{modules:a.length,mutatedModule:q.name,totalRounds:this.numTrials},"GEPA-Flow",{strategy:L,paretoSetSize:c.length},Z,{idx:C},{...r??{},maxIterations:this.numTrials}),!(Z>ye+this.tieEpsilon&&(H===void 0||ce===void 0||ce>H+this.tieEpsilon))){if(++k>=this.earlyStoppingTrials)break;continue}let ge=await g($,c);h.push({cfg:$,parent:C,scores:ge}),A.push(await y($,c));let ke=b.length,he=tt(b.map(V=>h[V].scores))??0;b=gt(h.map((V,re)=>({idx:re,scores:V.scores})),this.tieEpsilon).map(V=>V.idx);let ve=tt(b.map(V=>h[V].scores))??0;if(b.length>ke||ve>he+1e-6)k=0;else if(k++,k>=this.earlyStoppingTrials)break;this.lastIterFoundNewProgram=!0,this.mergeMax>0&&this.totalMergesTested<this.mergeMax&&(this.mergesDue+=1)}let O=gt(h.map((I,v)=>({idx:v,scores:I.scores})),this.tieEpsilon),F=O.length>0?Math.max(...O.map(I=>x(I.scores))):0,P=tt(O.map(I=>I.scores));return this.stats.convergenceInfo.converged=!0,this.recordParetoMetrics(O.length,h.length,"GEPA-Flow",P),{demos:[],stats:this.stats,bestScore:F,paretoFront:O.map(I=>({demos:[],scores:I.scores,configuration:{candidate:I.idx},dominatedSolutions:I.dominated})),paretoFrontSize:O.length,hypervolume:P,finalConfiguration:{strategy:"gepa_flow_pareto",candidates:h.length}}}async getBaseInstruction(e){let t=e?.getInstruction?.();if(t&&t.length>0)return t;let r=e?.getSignature?.()?.getDescription?.();return r&&r.length>0?r:"Follow the task precisely. Be concise, correct, and consistent."}async evaluateOnSet(e,t,n,r){let o=[];for(let i of n){let a=await this.evaluateOne(e,t,i,r);o.push(a)}return o}async evaluateAvg(e,t,n,r){let o=await this.evaluateOnSet(e,t,n,r);return o.length>0?Lt(o):0}async evaluateOne(e,t,n,r){try{e.setAllNodeInstructions?.(t);let o=await e.forward(this.studentAI,n,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let i=await r({prediction:o,example:n});return typeof i=="number"&&!Number.isNaN(i)?((typeof this.targetScore=="number"?i>=this.targetScore:i>=.5)&&(this.stats.successfulDemos+=1),i):0}catch{return 0}}async reflectModuleInstruction(e,t,n,r,o,i,a,l){let u=[],c=[];for(let x of i)try{o[e]=t,n.setAllNodeInstructions?.(o);let A=await n.forward(this.studentAI,x,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let y=await a({prediction:A,example:x});c.push({input:x,prediction:A,score:typeof y=="number"?y:0})}catch{c.push({input:x,prediction:{},score:0})}let p=l?.overrideTeacherAI??this.teacherAI??this.studentAI,d=_e('moduleName:string "Target module", minibatch:json "Array of {input,prediction,score}", evalFeedback?:string[] "Evaluator feedback when available" -> feedbackSummary:string "Concise module-focused feedback"'),m=[],g=l?.feedbackFn;if(typeof g=="function")for(let x of c){let A=g({prediction:x.prediction,example:x.input});A&&(Array.isArray(A)?m.push(...A):m.push(A))}let f="";try{f=(await d.forward(p,{moduleName:e,minibatch:c,evalFeedback:m}))?.feedbackSummary?.trim()||""}catch{}let h=_e('moduleName:string "Target module", currentInstruction:string "Current instruction", feedbackSummary?:string "Summarized feedback", minibatch:json "Array of {input,prediction,score}" -> newInstruction:string "Improved instruction (1-6 sentences) for the module"');try{let A=(await h.forward(p,{moduleName:e,currentInstruction:t,feedbackSummary:f,minibatch:c}))?.newInstruction?.trim();if(A&&A.length>16)return A}catch{}return`${t.trim()} Focus on step-by-step, module-specific reasoning and factual grounding.`.slice(0,2e3)}updateSamplerShuffled(e){let t=Array.from({length:e},(l,u)=>u);for(let l=t.length-1;l>0;l--){let u=Math.floor(this.rand()*(l+1));[t[l],t[u]]=[t[u],t[l]]}for(let l of t)this.samplerState.freq.set(l,(this.samplerState.freq.get(l)??0)+1);let n=this.minibatchSize,r=e%n,o=r===0?0:n-r,i=Array.from({length:e},(l,u)=>u).sort((l,u)=>(this.samplerState.freq.get(l)??0)-(this.samplerState.freq.get(u)??0)),a=[...t];for(let l=0;l<o;l++){let u=i[l%i.length];a.push(u),this.samplerState.freq.set(u,(this.samplerState.freq.get(u)??0)+1)}this.samplerState.shuffled=a,this.samplerState.epoch+=1}nextMinibatchIndices(e,t){this.samplerState.epoch===-1&&(this.samplerState.epoch=0,this.updateSamplerShuffled(e));let n=this.minibatchSize,r=Math.max(1,Math.floor(this.samplerState.shuffled.length/n)),o=Math.floor(t/r);for(;o>=this.samplerState.epoch;)this.updateSamplerShuffled(e);let i=t*n%this.samplerState.shuffled.length;return this.samplerState.shuffled.slice(i,i+n)}systemAwareMergeWithSig(e,t,n,r){let o=h=>{let x=[],A=h;for(;A!==void 0;)x.push(A),A=e[A]?.parent;return x},i=o(t),a=o(n),u=i.find(h=>a.includes(h))??t,c=e[u].cfg,p=e[t].cfg,d=e[n].cfg,m={},g=[],f=Array.from(new Set([...Object.keys(c),...Object.keys(p),...Object.keys(d)])).sort();for(let h of f){let x=c[h],A=p[h],y=d[h];if(A===x&&y!==A)m[h]=y,g.push("j");else if(y===x&&A!==y)m[h]=A,g.push("i");else if(A!==y&&A!==x&&y!==x){let b=r(t,n);m[h]=b===t?A:y,g.push(b===t?"i":"j")}else m[h]=A??y??x,g.push("i")}return{cfg:m,descSig:g.join("|")}}rand(){return this.rngState^=this.rngState<<13,this.rngState^=this.rngState>>>17,this.rngState^=this.rngState<<5,(this.rngState>>>0)/4294967296}systemAwareMerge(e,t,n,r){let o=f=>{let h=[],x=f;for(;x!==void 0;)h.push(x),x=e[x]?.parent;return h},i=o(t),a=o(n),u=i.find(f=>a.includes(f))??t,c=e[u].cfg,p=e[t].cfg,d=e[n].cfg,m={},g=new Set([...Object.keys(c),...Object.keys(p),...Object.keys(d)]);for(let f of g){let h=c[f],x=p[f],A=d[f];if(x===h&&A!==x)m[f]=A;else if(A===h&&x!==A)m[f]=x;else if(x!==A&&x!==h&&A!==h){let y=r(t,n);m[f]=y===t?x:A}else m[f]=x??A??h}return m}};var Zo=class{endpoint;timeout;retryAttempts;retryDelay;logger;constructor(e){this.endpoint=e.endpoint.replace(/\/$/,""),this.timeout=e.timeout??3e4,this.retryAttempts=e.retryAttempts??3,this.retryDelay=e.retryDelay??1e3,this.logger=e.logger}async healthCheck(){try{return(await this.fetchWithRetry("/health",{method:"GET"})).ok}catch(e){return this.logger?.({name:"Notification",id:"health_check_failed",value:`Health check failed: ${e}`}),!1}}async createOptimizationJob(e){let t=await this.fetchWithRetry("/optimize",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok){let n=await t.text();throw new Error(`Failed to create optimization job: ${n}`)}return t.json()}async getJobStatus(e){let t=await this.fetchWithRetry(`/jobs/${e}`,{method:"GET"});if(!t.ok){let n=await t.text();throw new Error(`Failed to get job status: ${n}`)}return t.json()}async cancelJob(e){let t=await this.fetchWithRetry(`/jobs/${e}`,{method:"DELETE"});if(!t.ok){let n=await t.text();throw new Error(`Failed to cancel job: ${n}`)}}async suggestParameters(e){let t=await this.fetchWithRetry(`/studies/${e}/suggest`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!t.ok){let n=await t.text();throw new Error(`Failed to suggest parameters: ${n}`)}return t.json()}async evaluateTrial(e){let t=await this.fetchWithRetry(`/studies/${e.study_name}/evaluate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok){let n=await t.text();throw new Error(`Failed to evaluate trial: ${n}`)}}async getStudyResults(e){let t=await this.fetchWithRetry(`/studies/${e}/results`,{method:"GET"});if(!t.ok){let n=await t.text();throw new Error(`Failed to get study results: ${n}`)}return t.json()}async deleteStudy(e){let t=await this.fetchWithRetry(`/studies/${e}`,{method:"DELETE"});if(!t.ok){let n=await t.text();throw new Error(`Failed to delete study: ${n}`)}}async listStudies(){let e=await this.fetchWithRetry("/studies",{method:"GET"});if(!e.ok){let t=await e.text();throw new Error(`Failed to list studies: ${t}`)}return e.json()}async waitForJobCompletion(e,t=2e3,n=3e5){let r=Date.now();for(;Date.now()-r<n;){let o=await this.getJobStatus(e);if(["completed","failed","cancelled"].includes(o.status))return o;this.logger?.({name:"Notification",id:"job_status",value:`Job ${e} status: ${o.status}, waiting...`}),await this.sleep(t)}throw new Error(`Job ${e} did not complete within ${n}ms`)}async fetchWithRetry(e,t){let n=`${this.endpoint}${e}`,r=null;for(let o=0;o<this.retryAttempts;o++)try{let i=new AbortController,a=setTimeout(()=>i.abort(),this.timeout),l=await fetch(n,{...t,signal:i.signal});return clearTimeout(a),l}catch(i){r=i,this.logger?.({name:"Notification",id:"retry_attempt",value:`Attempt ${o+1} failed: ${i}`}),o<this.retryAttempts-1&&await this.sleep(this.retryDelay*Math.pow(2,o))}throw new Error(`Request failed after ${this.retryAttempts} attempts: ${r?.message}`)}sleep(e){return new Promise(t=>setTimeout(t,e))}};var Xo=class extends je{maxBootstrappedDemos;maxLabeledDemos;numCandidates;initTemperature;numTrials;minibatch;minibatchSize;minibatchFullEvalSteps;programAwareProposer;dataAwareProposer;viewDataBatchSize;tipAwareProposer;fewshotAwareProposer;earlyStoppingTrials;minImprovementThreshold;bayesianOptimization;acquisitionFunction;explorationWeight;optimizeTopP;sampleCount;pythonClient;localScoreHistory=[];localConfigurationHistory=[];customResultPicker;constructor(e){if(super(e),this.numCandidates=e.numCandidates??5,this.initTemperature=e.initTemperature??.7,this.maxBootstrappedDemos=e.maxBootstrappedDemos??3,this.maxLabeledDemos=e.maxLabeledDemos??4,this.numTrials=e.numTrials??30,this.minibatch=e.minibatch??!0,this.minibatchSize=e.minibatchSize??25,this.minibatchFullEvalSteps=e.minibatchFullEvalSteps??10,this.programAwareProposer=e.programAwareProposer??!0,this.dataAwareProposer=e.dataAwareProposer??!0,this.viewDataBatchSize=e.viewDataBatchSize??10,this.tipAwareProposer=e.tipAwareProposer??!0,this.fewshotAwareProposer=e.fewshotAwareProposer??!0,this.earlyStoppingTrials=e.earlyStoppingTrials??5,this.minImprovementThreshold=e.minImprovementThreshold??.01,this.bayesianOptimization=e.bayesianOptimization??!0,this.acquisitionFunction=e.acquisitionFunction??"expected_improvement",this.explorationWeight=e.explorationWeight??.1,this.optimizeTopP=e.optimizeTopP??!1,this.sampleCount=e.sampleCount??1,this.customResultPicker=e.resultPicker,e.optimizerEndpoint){let t={endpoint:e.optimizerEndpoint,timeout:e.optimizerTimeout??3e4,retryAttempts:e.optimizerRetries??3,logger:n=>{this.logger?.({name:"Notification",id:"python_client",value:typeof n=="string"?n:JSON.stringify(n)})}};this.pythonClient=new Zo(t)}this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}defaultResultPicker=async e=>{if(e.type==="function"){let o=e.results.findIndex(i=>!i.isError);return o>=0?o:0}let t=new Map;for(let o of e.results){let i=JSON.stringify(o.sample??{}),a=t.get(i);a?a.count+=1:t.set(i,{count:1,firstIndex:o.index})}let n="",r={count:-1,firstIndex:0};for(let[o,i]of t.entries())i.count>r.count&&(r=i,n=o);return t.get(n)?.firstIndex??0};configureAuto(e){switch(e){case"light":this.numCandidates=3,this.numTrials=10,this.minibatch=!0,this.minibatchSize=20;break;case"medium":this.numCandidates=5,this.numTrials=20,this.minibatch=!0,this.minibatchSize=25;break;case"heavy":this.numCandidates=7,this.numTrials=30,this.minibatch=!0,this.minibatchSize=30;break}}generateTips(){return["Be very specific and detailed in your instructions.","Focus on step-by-step reasoning in your instructions.","Provide clear constraints and guidelines in your instructions.","Keep your instructions concise and to the point.","Emphasize accuracy and precision in your instructions.","Include examples of good outputs in your instructions.","Focus on handling edge cases in your instructions.","Explicitly outline the reasoning process in your instructions."]}async generateProgramSummary(e,t){let r=`
494
+ `)}async extractProgramInstruction(e){try{return e.getSignature().getDescription()??void 0}catch{return}}createGeneratorOutput(e,t){let n=e?.thought?.toString()??"",r=Array.isArray(e?.bullet_ids)?e?.bullet_ids:[];return{reasoning:n,answer:e,bulletIds:r,trajectory:JSON.stringify({example:t,prediction:e}),metadata:{predictedSeverity:e?.severity,expectedSeverity:t?.severity}}}resolveCuratorOperationTargets(e,t,n,r){if(!e.length)return e;let o=[],s=new Set(e.map(c=>c.bulletId).filter(c=>typeof c=="string")),a=new Map,l=(c,p)=>{if(s.has(c))return;let d=this.locateBullet(t,c);if(!d)return;let m=a.get(d.section)??{harmful:[],primary:[],generator:[]};m[p].push(d.id),a.set(d.section,m)};for(let c of n?.bulletTags??[]){let p=c.tag==="harmful"?"harmful":"primary";l(c.id,p)}if(r?.bulletIds)for(let c of r.bulletIds)l(c,"generator");let u=c=>{let p=a.get(c);if(!p)return this.locateFallbackBullet(t,c,s);let d=g=>{for(;g.length>0;){let h=g.shift();if(!s.has(h))return h}},m=d(p.harmful)??d(p.primary)??d(p.generator);return m||this.locateFallbackBullet(t,c,s)};for(let c of e){if((c.type==="UPDATE"||c.type==="REMOVE")&&!c.bulletId){let p=u(c.section);p&&(c.bulletId=p,s.add(p))}(c.type==="UPDATE"||c.type==="REMOVE")&&!c.bulletId||o.push(c)}return o}locateBullet(e,t){for(let n of Object.values(e.sections)){let r=n.find(o=>o.id===t);if(r)return r}}locateFallbackBullet(e,t,n){let r=e.sections[t]??[];for(let o of r)if(!n.has(o.id))return o.id}collectProtectedBulletIds(e){let t=new Set;for(let n of e)n.type==="UPDATE"&&n.bulletId&&t.add(n.bulletId);return t}normalizeCuratorOperations(e){if(!e)return[];if(Array.isArray(e)){let t=[],n=new Set;for(let r of e){if(!r||typeof r!="object")continue;let o=r.type??"ADD",s=typeof o=="string"?o.toUpperCase():"ADD",a=s==="UPDATE"?"UPDATE":s==="REMOVE"?"REMOVE":"ADD",l=r.section??"Guidelines",u=typeof l=="string"&&l.trim().length>0?l.trim():"Guidelines",c=r.content??"",p=typeof c=="string"?c.trim():"";if(a!=="REMOVE"&&p.length===0)continue;let d=r.bulletId??r.id,m=typeof d=="string"&&d.trim().length>0?d.trim():void 0,h=[a,u,p,m??""].join(":");if(n.has(h))continue;n.add(h);let f={type:a,section:u};a!=="REMOVE"&&(f.content=p),m&&(f.bulletId=m);let x=r.metadata;x&&typeof x=="object"&&(f.metadata={...x}),t.push(f)}return t}if(typeof e=="string")try{let t=JSON.parse(e);return this.normalizeCuratorOperations(t)}catch{return[]}if(typeof e=="object"){let t=e;if(t&&Array.isArray(t.operations))return this.normalizeCuratorOperations(t.operations);if(t&&typeof t.operations=="string")try{let n=JSON.parse(t.operations);return this.normalizeCuratorOperations(n)}catch{return[]}return[]}return[]}inferOperationsFromReflection(e){if(!e)return[];let t=[],n=new Set,r=(o,s)=>{if(!s)return;let a=s.trim();if(!a||a.toLowerCase().startsWith("no error"))return;let u=`${o}:${a}`;n.has(u)||(n.add(u),t.push({type:"ADD",section:o,content:a}))};return r("Guidelines",e.keyInsight),r("Response Strategies",e.correctApproach),r("Common Pitfalls",e.errorIdentification),r("Root Cause Notes",e.rootCauseAnalysis),t}async runReflectionRounds({example:e,generatorOutput:t,feedback:n}){let r=Math.max(this.aceConfig.maxReflectorRounds,1),o;for(let s=0;s<r;s++){let a=await this.runReflector({example:e,generatorOutput:t,feedback:n,previousReflection:o});if(!a)break;o=a;let l=a.errorIdentification?.toLowerCase().trim()??"";if(a.metadata?.resolved===!0||l.length===0||l.startsWith("no error")||l.startsWith("resolved"))break}return o}async runReflector({example:e,generatorOutput:t,feedback:n,previousReflection:r}){let o=this.getOrCreateReflectorProgram(),s=this.teacherAI??this.studentAI;try{let a={severity:e?.severity,policyHint:e?.policyHint},c=(this.program?.getSignature()?.getInputFields()??[]).reduce((d,m)=>(m.name in e&&(d[m.name]=e[m.name]),d),{});return await o.forward(s,{question:JSON.stringify(c),generator_answer:JSON.stringify(t.answer),generator_reasoning:t.reasoning,playbook:JSON.stringify({markdown:br(this.playbook),structured:this.playbook}),expected_answer:a.severity||a.policyHint?JSON.stringify(a):void 0,feedback:n,previous_reflection:r?JSON.stringify(r):void 0})}catch(a){this.verbose&&console.warn("[AxACE] Reflector error:",a instanceof Error?a.message:a);return}}async runCurator({program:e,example:t,reflection:n,playbook:r}){if(!n)return;let o=this.getOrCreateCuratorProgram(),s=this.teacherAI??this.studentAI,u=e.getSignature().getInputFields().reduce((c,p)=>(p.name in t&&(c[p.name]=t[p.name]),c),{});try{return await o.forward(s,{playbook:JSON.stringify({markdown:br(r),structured:r}),reflection:JSON.stringify(n),question_context:JSON.stringify(u),token_budget:1024})}catch(c){this.verbose&&console.warn("[AxACE] Curator error:",c instanceof Error?c.message:c);return}}getOrCreateReflectorProgram(){if(!this.reflectorProgram){let e=ue().input("question",ue.string("Original task input serialized as JSON")).input("generator_answer",ue.string("Generator output serialized as JSON")).input("generator_reasoning",ue.string("Generator reasoning trace").optional()).input("playbook",ue.string("Current context playbook rendered as markdown")).input("expected_answer",ue.string("Expected output when ground truth is available").optional()).input("feedback",ue.string("External feedback or reward signal").optional()).input("previous_reflection",ue.string("Most recent reflection JSON when running multi-round refinement").optional()).output("reasoning",ue.string("Step-by-step analysis of generator performance")).output("errorIdentification",ue.string("Specific mistakes detected")).output("rootCauseAnalysis",ue.string("Underlying cause of the error")).output("correctApproach",ue.string("What the generator should do differently")).output("keyInsight",ue.string("Reusable insight to remember")).output("bulletTags",ue.json("Array of {id, tag} entries referencing playbook bullets")).build();this.reflectorProgram=_e(e)}return this.reflectorProgram}getOrCreateCuratorProgram(){if(!this.curatorProgram){let e=ue().input("playbook",ue.string("Current playbook serialized as JSON")).input("reflection",ue.string("Latest reflection output serialized as JSON")).input("question_context",ue.string("Original task input serialized as JSON")).input("token_budget",ue.number("Approximate token budget for curator response").optional()).output("reasoning",ue.string("Justification for the proposed updates")).output("operations",ue.json("List of operations with type/section/content fields")).build();this.curatorProgram=_e(e)}return this.curatorProgram}};var vn=class extends je{maxRounds;maxDemos;maxExamples;batchSize;earlyStoppingPatience;costMonitoring;maxTokensPerGeneration;verboseMode;debugMode;traces=[];constructor(e){super(e);let t=e.options||{};this.maxRounds=t.maxRounds??3,this.maxDemos=t.maxDemos??4,this.maxExamples=t.maxExamples??16,this.batchSize=t.batchSize??1,this.earlyStoppingPatience=t.earlyStoppingPatience??0,this.costMonitoring=t.costMonitoring??!1,this.maxTokensPerGeneration=t.maxTokensPerGeneration??0,this.verboseMode=t.verboseMode??!0,this.debugMode=t.debugMode??!1}async compileRound(e,t,n,r,o){let s=Date.now(),a=o?.maxDemos??this.maxDemos,l={modelConfig:{temperature:.7}};this.maxTokensPerGeneration>0&&(l.modelConfig.max_tokens=this.maxTokensPerGeneration);let u=zp([...t],this.maxExamples),c=this.traces.length;for(let p=0;p<u.length;p+=this.batchSize){p>0&&(l.modelConfig.temperature=.7+.001*p);let d=u.slice(p,p+this.batchSize);for(let m of d){if(!m||typeof m!="object")continue;let g=t.filter(x=>x!==m);e.setExamples(g);let h=this.getTeacherOrStudentAI();this.stats.totalCalls++;let f;try{let x={...l,maxRetries:1};f=await e.forward(h,m,x),this.costMonitoring&&(this.stats.estimatedTokenUsage+=JSON.stringify(m).length/4+JSON.stringify(f).length/4),await r({prediction:f,example:m})>=.5&&(this.traces=[...this.traces,...e.getTraces()],this.stats.successfulDemos++)}catch(x){(this.verboseMode||this.debugMode)&&console.warn(`Student model failed during bootstrap: ${x instanceof Error?x.message:"Unknown error"}`),f={}}if(this.traces.length>=a)return}}if(this.earlyStoppingPatience>0){let d=this.traces.length-c;if(!this.stats.earlyStopping)this.stats.earlyStopping={bestScoreRound:d>0?n:0,patienceExhausted:!1,reason:"No improvement detected"};else if(d>0)this.stats.earlyStopping.bestScoreRound=n;else if(n-this.stats.earlyStopping.bestScoreRound>=this.earlyStoppingPatience){this.stats.earlyStopping.patienceExhausted=!0,this.stats.earlyStopped=!0,this.stats.earlyStopping.reason=`No improvement for ${this.earlyStoppingPatience} rounds`;return}}}async compile(e,t,n,r){this.validateExamples(t,!1);let o=r?.maxIterations??this.maxRounds;this.traces=[],this.reset();for(let l=0;l<o&&(await this.compileRound(e,t,l,n,r),!this.stats.earlyStopped);l++);if(this.traces.length===0)throw new Error("No demonstrations found. Either provide more examples or improve the existing ones.");let s=qp(this.traces),a=0;return this.traces.length>0&&(a=this.stats.successfulDemos/Math.max(1,this.stats.totalCalls)),await this.logOptimizationComplete("BootstrapFewShot",a,{maxRounds:this.maxRounds,maxDemos:this.maxDemos,batchSize:this.batchSize,successRate:a,demosGenerated:s.length,tracesCollected:this.traces.length},r),{demos:s,stats:this.stats,bestScore:a,finalConfiguration:{maxRounds:this.maxRounds,maxDemos:this.maxDemos,batchSize:this.batchSize,successRate:a}}}};function qp(i){let e=new Map;for(let n of i)if(e.has(n.programId)){let r=e.get(n.programId);r&&r.push(n.trace)}else e.set(n.programId,[n.trace]);let t=[];return e.forEach((n,r)=>{t.push({traces:n,programId:r})}),t}var zp=(i,e)=>{let t=[...i];for(let n=t.length-1;n>0;n--){let r=Math.floor(Math.random()*(n+1)),o=t[n],s=t[r];if(!o||!s)throw new Error("Invalid array elements");[t[n],t[r]]=[s,o]}return t.slice(0,e)};var Xo=class extends je{numTrials;minibatch;minibatchSize;earlyStoppingTrials;minImprovementThreshold;sampleCount;crossoverEvery;tieEpsilon;paretoSetSize;mergeMax;mergesUsed=0;mergesDue=0;totalMergesTested=0;lastIterFoundNewProgram=!1;rngState;mergeAttemptKeys=new Set;mergeCompositionKeys=new Set;samplerState={epoch:-1,shuffled:[],freq:new Map};constructor(e){super(e),this.numTrials=e.numTrials??24,this.minibatch=e.minibatch??!0,this.minibatchSize=e.minibatchSize??8,this.earlyStoppingTrials=e.earlyStoppingTrials??5,this.minImprovementThreshold=e.minImprovementThreshold??0,this.sampleCount=e.sampleCount??1,this.crossoverEvery=Math.max(0,Math.floor(e?.crossoverEvery??Math.max(3,Math.floor(this.numTrials/3)))),this.tieEpsilon=Number.isFinite(e?.tieEpsilon)?Number(e?.tieEpsilon):0;let t=e?.seed,n=Number.isFinite(t)?Math.floor(Number(t)):0;this.rngState=n&&n!==0?n:123456789;let r=e?.paretoSetSize;this.paretoSetSize=r&&r>0?Math.min(1e3,Math.max(5,Math.floor(r))):Math.max(10,Math.min(200,this.minibatchSize*3));let o=e?.mergeMax;this.mergeMax=Math.max(0,Math.floor(o??5)),this.mergesUsed=0,this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}reset(){super.reset(),this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold,this.mergesUsed=0,this.mergesDue=0,this.totalMergesTested=0,this.lastIterFoundNewProgram=!1,this.mergeAttemptKeys.clear(),this.mergeCompositionKeys.clear(),this.samplerState.epoch=-1,this.samplerState.shuffled=[],this.samplerState.freq.clear()}configureAuto(e){switch(e){case"light":this.numTrials=8,this.minibatch=!0,this.minibatchSize=6;break;case"medium":this.numTrials=16,this.minibatch=!0,this.minibatchSize=10;break;case"heavy":this.numTrials=28,this.minibatch=!0,this.minibatchSize=14;break}}async compile(e,t,n,r){let o=Date.now(),s=e;this.validateExamples(t),r?.auto&&this.configureAuto(r.auto);let a=s.getNodePrograms?.();if(!a||a.length===0)throw new Error("AxGEPAFlow: flow has no nodes to optimize");let l=r?.validationExamples,u=r?.feedbackExamples,c=(l&&l.length>0?l:t).slice(0,this.paretoSetSize),p=u&&u.length>0?u:t;this.getOptimizerLogger(r)?.({name:"OptimizationStart",value:{optimizerType:"GEPA-Flow",exampleCount:t.length,validationCount:c.length,config:{numTrials:this.numTrials,minibatch:this.minibatch}}});let m=async(T,v)=>{try{s.setAllNodeInstructions?.(T);let C=await s.forward(this.studentAI,v,{sampleCount:this.sampleCount});return this.stats.totalCalls+=1,await n({prediction:C,example:v})||{}}catch{return{}}},g=async(T,v)=>{let C=[];for(let O of v)C.push(await m(T,O));return Wo(C)},h={};for(let T of a)h[T.name]=await this.getBaseInstruction(T.program);let f=[{cfg:{...h},parent:void 0,scores:await g(h,c)}],x=T=>{let v=r?.paretoMetricKey,C=r?.paretoScalarize;if(typeof C=="function")return C(T);if(v)return Number.isFinite(T[v])?T[v]:0;let O=Object.values(T);return O.length?O.reduce((I,P)=>I+P,0)/O.length:0},A=[],y=async(T,v)=>{let C=[];for(let O of v){let I=await m(T,O);C.push(x(I))}return C};A.push(await y(h,c));let b=gt(f.map((T,v)=>({idx:v,scores:T.scores})),this.tieEpsilon).map(T=>T.idx),S=0,w=new Set,M=r?.maxMetricCalls;if(!Number.isFinite(M)||M<=0)throw new Error("AxGEPA-Flow: options.maxMetricCalls must be set to a positive integer");let R=Math.floor(M);for(let T=0;T<this.numTrials&&!(R!==void 0&&this.stats.totalCalls>=Math.max(1,Math.floor(R)));T++){let v=A[0]?.length??0,C=[];for(let Y=0;Y<v;Y++){let ne=Number.NEGATIVE_INFINITY,U=new Set;for(let q=0;q<A.length;q++){let Q=A[q][Y];Q>ne+this.tieEpsilon?(ne=Q,U.clear(),U.add(q)):Math.abs(Q-ne)<=this.tieEpsilon&&U.add(q)}C.push(U)}let O=A.map(Y=>Gt(Y));if(this.mergeMax>0&&this.mergesDue>0&&this.lastIterFoundNewProgram){let Y=Ar(C,O),ne=new Set;for(let G of Y)for(let B of G)ne.add(B);let U=Array.from(ne),q=G=>{let B=[],D=G;for(;D!==void 0;)B.push(D),D=f[D]?.parent;return B},Q=G=>G.length?G[Math.floor(this.rand()*G.length)]:void 0,re;for(let G=0;G<10&&!re&&!(U.length<2);G++){let B=Q(U),D=Q(U);if(B===D)continue;D<B&&([B,D]=[D,B]);let K=new Set(q(B)),X=new Set(q(D));if(K.has(D)||X.has(B))continue;let he=[...K].filter(ge=>X.has(ge));if(he.length===0)continue;let Z=[];for(let ge of he){let ht=f[ge].cfg,It=f[B].cfg,nt=f[D].cfg,Tt=!1,Ct=new Set([...Object.keys(ht),...Object.keys(It),...Object.keys(nt)]);for(let ft of Ct){let wt=ht[ft],Pt=It[ft],W=nt[ft];if(Pt===wt&&W!==Pt||W===wt&&Pt!==W){Tt=!0;break}}Tt&&Z.push(ge)}if(Z.length===0)continue;let oe=Z.map(ge=>Math.max(1e-9,O[ge])),ae=this.rand()*oe.reduce((ge,ht)=>ge+ht,0),me=Z[Z.length-1];for(let ge=0;ge<Z.length;ge++){if(ae<oe[ge]){me=Z[ge];break}ae-=oe[ge]}let Re=O[me],ke=O[B],We=O[D];if(Re>Math.min(ke,We))continue;let $e=`${B}|${D}|${me}`;if(this.mergeAttemptKeys.has($e))continue;this.mergeAttemptKeys.add($e);let ze=`${B}|${D}|${me}`;w.has(ze)||(re={i:B,j:D,a:me})}if(this.lastIterFoundNewProgram=!1,re){let{i:G,j:B,a:D}=re,{cfg:K,descSig:X}=this.systemAwareMergeWithSig(f,G,B,(W,Ie)=>O[W]>=O[Ie]?W:Ie),he=`${Math.min(G,B)}|${Math.max(G,B)}|${X}`;if(this.mergeCompositionKeys.has(he))continue;this.mergeCompositionKeys.add(he);let Z=A[G],oe=A[B],ae=Array.from({length:Z.length},(W,Ie)=>Ie),me=ae.filter(W=>(Z[W]??0)>(oe[W]??0)),Re=ae.filter(W=>(oe[W]??0)>(Z[W]??0)),ke=ae.filter(W=>!(me.includes(W)||Re.includes(W))),We=5,$e=Math.ceil(We/3),ze=(W,Ie)=>{if(Ie<=0||W.length===0)return[];if(W.length<=Ie)return[...W];let ct=[],He=new Set;for(;ct.length<Ie;){let Ke=Math.floor(this.rand()*W.length);He.has(Ke)||(He.add(Ke),ct.push(W[Ke]))}return ct},ge=[];ge.push(...ze(me,Math.min($e,me.length))),ge.push(...ze(Re,Math.min($e,Re.length)));let ht=We-ge.length;ge.push(...ze(ke,Math.max(0,ht)));let It=We-ge.length;if(It>0){let W=ae.filter(Ie=>!ge.includes(Ie));ge.push(...ze(W,Math.min(It,W.length)))}let nt=ge.slice(0,Math.min(We,ae.length)),Tt=nt.map(W=>c[W]),ft=(await y(K,Tt)).reduce((W,Ie)=>W+Ie,0),wt=nt.reduce((W,Ie)=>W+(Z[Ie]??0),0),Pt=nt.reduce((W,Ie)=>W+(oe[Ie]??0),0);if(ft>=Math.max(wt,Pt)+this.tieEpsilon){let W=await g(K,c);f.push({cfg:K,parent:D,scores:W}),A.push(await y(K,c));let Ie=b.length,ct=tt(b.map(Ke=>f[Ke].scores))??0;b=gt(f.map((Ke,vr)=>({idx:vr,scores:Ke.scores})),this.tieEpsilon).map(Ke=>Ke.idx);let He=tt(b.map(Ke=>f[Ke].scores))??0;(b.length>Ie||He>ct+1e-6)&&(S=0),this.mergesDue-=1,this.totalMergesTested+=1,w.add(`${Math.min(G,B)}|${Math.max(G,B)}|${D}`)}continue}}let I=yr(C,O,()=>this.rand());this.lastIterFoundNewProgram=!1;let P=this.minibatch?this.nextMinibatchIndices(p.length,T).map(Y=>p[Y]):p;if(r?.skipPerfectScore??!0){let Y=Number(r?.perfectScore??1),ne=await y(f[I].cfg,P);if(ne.length>0&&ne.every(U=>U>=Y))continue}let _=!1,$={...f[I].cfg},N="reflective_mutation",L=T%a.length,z=a[L],H,te;if(_&&this.mergesUsed<this.mergeMax){let Y=(I+1)%f.length,ne=G=>{let B=[],D=G;for(;D!==void 0;)B.push(D),D=f[D]?.parent;return B},U=ne(I),q=ne(Y),Q=U.find(G=>q.includes(G)),re=!0;if(Q||(re=!1),(q.includes(I)||U.includes(Y))&&(re=!1),re){let G=f[Q].cfg,B=f[I].cfg,D=f[Y].cfg,K=!1,X=new Set([...Object.keys(G),...Object.keys(B),...Object.keys(D)]);for(let he of X){let Z=G[he],oe=B[he],ae=D[he];if(oe===Z&&ae!==oe||ae===Z&&oe!==ae){K=!0;break}}K||(re=!1)}if(re){let G=Math.min(I,Y),B=Math.max(I,Y),D=`${G}|${B}|${Q}`;if(!w.has(D)){let K=x(f[Q].scores),X=x(f[I].scores),he=x(f[Y].scores);K<=Math.min(X,he)&&($=this.systemAwareMerge(f,I,Y,(Z,oe)=>{let ae=x(f[Z].scores),me=x(f[oe].scores);return ae>=me?Z:oe}),N="system_merge",this.mergesUsed+=1,w.add(D))}}else{let G=f[I].cfg[z.name],B=r?.gepaAdapter,D;if(B)try{let K=await B.evaluate(P,{...f[I].cfg},!0);H=Array.isArray(K?.scores)?K.scores.reduce((oe,ae)=>oe+(Number(ae)||0),0):void 0;let X=B.make_reflective_dataset({...f[I].cfg},K,[z.name]),Z=(await B.propose_new_texts?.({...f[I].cfg},X,[z.name]))?.[z.name];typeof Z=="string"&&Z.length>0&&(D=Z)}catch{}if(D||(D=await this.reflectModuleInstruction(z.name,G,s,a,{...f[I].cfg},P,async({prediction:K,example:X})=>{let he=await n({prediction:K,example:X}),Z=Object.values(he||{});return Z.length?Z.reduce((oe,ae)=>oe+ae,0)/Z.length:0},r)),$[z.name]=D,B&&H!==void 0)try{let K=await B.evaluate(P,$,!1);te=Array.isArray(K?.scores)?K.scores.reduce((X,he)=>X+(Number(he)||0),0):void 0}catch{}}}else{let Y=f[I].cfg[z.name],ne=r?.gepaAdapter,U;if(ne)try{let q=await ne.evaluate(P,{...f[I].cfg},!0);H=Array.isArray(q?.scores)?q.scores.reduce((B,D)=>B+(Number(D)||0),0):void 0;let Q=ne.make_reflective_dataset({...f[I].cfg},q,[z.name]),G=(await ne.propose_new_texts?.({...f[I].cfg},Q,[z.name]))?.[z.name];typeof G=="string"&&G.length>0&&(U=G)}catch{}if(U||(U=await this.reflectModuleInstruction(z.name,Y,s,a,{...f[I].cfg},P,async({prediction:q,example:Q})=>{let re=await n({prediction:q,example:Q}),G=Object.values(re||{});return G.length?G.reduce((B,D)=>B+D,0)/G.length:0},r)),$[z.name]=U,ne&&H!==void 0)try{let q=await ne.evaluate(P,$,!1);te=Array.isArray(q?.scores)?q.scores.reduce((Q,re)=>Q+(Number(re)||0),0):void 0}catch{}}let de=await y(f[I].cfg,P),be=await y($,P),ce=de.reduce((Y,ne)=>Y+ne,0),ie=be.reduce((Y,ne)=>Y+ne,0);if(this.currentRound=T+1,await this.updateOptimizationProgress(this.currentRound,ie,{modules:a.length,mutatedModule:z.name,totalRounds:this.numTrials},"GEPA-Flow",{strategy:N,paretoSetSize:c.length},ie,{idx:I},{...r??{},maxIterations:this.numTrials}),!(ie>ce+this.tieEpsilon&&(H===void 0||te===void 0||te>H+this.tieEpsilon))){if(++S>=this.earlyStoppingTrials)break;continue}let Ae=await g($,c);f.push({cfg:$,parent:I,scores:Ae}),A.push(await y($,c));let pe=b.length,ve=tt(b.map(Y=>f[Y].scores))??0;b=gt(f.map((Y,ne)=>({idx:ne,scores:Y.scores})),this.tieEpsilon).map(Y=>Y.idx);let qe=tt(b.map(Y=>f[Y].scores))??0;if(b.length>pe||qe>ve+1e-6)S=0;else if(S++,S>=this.earlyStoppingTrials)break;this.lastIterFoundNewProgram=!0,this.mergeMax>0&&this.totalMergesTested<this.mergeMax&&(this.mergesDue+=1)}let k=gt(f.map((T,v)=>({idx:v,scores:T.scores})),this.tieEpsilon),F=k.length>0?Math.max(...k.map(T=>x(T.scores))):0,E=tt(k.map(T=>T.scores));return this.stats.convergenceInfo.converged=!0,this.recordParetoMetrics(k.length,f.length,"GEPA-Flow",E),{demos:[],stats:this.stats,bestScore:F,paretoFront:k.map(T=>({demos:[],scores:T.scores,configuration:{candidate:T.idx},dominatedSolutions:T.dominated})),paretoFrontSize:k.length,hypervolume:E,finalConfiguration:{strategy:"gepa_flow_pareto",candidates:f.length}}}async getBaseInstruction(e){let t=e?.getInstruction?.();if(t&&t.length>0)return t;let r=e?.getSignature?.()?.getDescription?.();return r&&r.length>0?r:"Follow the task precisely. Be concise, correct, and consistent."}async evaluateOnSet(e,t,n,r){let o=[];for(let s of n){let a=await this.evaluateOne(e,t,s,r);o.push(a)}return o}async evaluateAvg(e,t,n,r){let o=await this.evaluateOnSet(e,t,n,r);return o.length>0?Gt(o):0}async evaluateOne(e,t,n,r){try{e.setAllNodeInstructions?.(t);let o=await e.forward(this.studentAI,n,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let s=await r({prediction:o,example:n});return typeof s=="number"&&!Number.isNaN(s)?((typeof this.targetScore=="number"?s>=this.targetScore:s>=.5)&&(this.stats.successfulDemos+=1),s):0}catch{return 0}}async reflectModuleInstruction(e,t,n,r,o,s,a,l){let u=[],c=[];for(let x of s)try{o[e]=t,n.setAllNodeInstructions?.(o);let A=await n.forward(this.studentAI,x,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let y=await a({prediction:A,example:x});c.push({input:x,prediction:A,score:typeof y=="number"?y:0})}catch{c.push({input:x,prediction:{},score:0})}let p=l?.overrideTeacherAI??this.teacherAI??this.studentAI,d=_e('moduleName:string "Target module", minibatch:json "Array of {input,prediction,score}", evalFeedback?:string[] "Evaluator feedback when available" -> feedbackSummary:string "Concise module-focused feedback"'),m=[],g=l?.feedbackFn;if(typeof g=="function")for(let x of c){let A=g({prediction:x.prediction,example:x.input});A&&(Array.isArray(A)?m.push(...A):m.push(A))}let h="";try{h=(await d.forward(p,{moduleName:e,minibatch:c,evalFeedback:m}))?.feedbackSummary?.trim()||""}catch{}let f=_e('moduleName:string "Target module", currentInstruction:string "Current instruction", feedbackSummary?:string "Summarized feedback", minibatch:json "Array of {input,prediction,score}" -> newInstruction:string "Improved instruction (1-6 sentences) for the module"');try{let A=(await f.forward(p,{moduleName:e,currentInstruction:t,feedbackSummary:h,minibatch:c}))?.newInstruction?.trim();if(A&&A.length>16)return A}catch{}return`${t.trim()} Focus on step-by-step, module-specific reasoning and factual grounding.`.slice(0,2e3)}updateSamplerShuffled(e){let t=Array.from({length:e},(l,u)=>u);for(let l=t.length-1;l>0;l--){let u=Math.floor(this.rand()*(l+1));[t[l],t[u]]=[t[u],t[l]]}for(let l of t)this.samplerState.freq.set(l,(this.samplerState.freq.get(l)??0)+1);let n=this.minibatchSize,r=e%n,o=r===0?0:n-r,s=Array.from({length:e},(l,u)=>u).sort((l,u)=>(this.samplerState.freq.get(l)??0)-(this.samplerState.freq.get(u)??0)),a=[...t];for(let l=0;l<o;l++){let u=s[l%s.length];a.push(u),this.samplerState.freq.set(u,(this.samplerState.freq.get(u)??0)+1)}this.samplerState.shuffled=a,this.samplerState.epoch+=1}nextMinibatchIndices(e,t){this.samplerState.epoch===-1&&(this.samplerState.epoch=0,this.updateSamplerShuffled(e));let n=this.minibatchSize,r=Math.max(1,Math.floor(this.samplerState.shuffled.length/n)),o=Math.floor(t/r);for(;o>=this.samplerState.epoch;)this.updateSamplerShuffled(e);let s=t*n%this.samplerState.shuffled.length;return this.samplerState.shuffled.slice(s,s+n)}systemAwareMergeWithSig(e,t,n,r){let o=f=>{let x=[],A=f;for(;A!==void 0;)x.push(A),A=e[A]?.parent;return x},s=o(t),a=o(n),u=s.find(f=>a.includes(f))??t,c=e[u].cfg,p=e[t].cfg,d=e[n].cfg,m={},g=[],h=Array.from(new Set([...Object.keys(c),...Object.keys(p),...Object.keys(d)])).sort();for(let f of h){let x=c[f],A=p[f],y=d[f];if(A===x&&y!==A)m[f]=y,g.push("j");else if(y===x&&A!==y)m[f]=A,g.push("i");else if(A!==y&&A!==x&&y!==x){let b=r(t,n);m[f]=b===t?A:y,g.push(b===t?"i":"j")}else m[f]=A??y??x,g.push("i")}return{cfg:m,descSig:g.join("|")}}rand(){return this.rngState^=this.rngState<<13,this.rngState^=this.rngState>>>17,this.rngState^=this.rngState<<5,(this.rngState>>>0)/4294967296}systemAwareMerge(e,t,n,r){let o=h=>{let f=[],x=h;for(;x!==void 0;)f.push(x),x=e[x]?.parent;return f},s=o(t),a=o(n),u=s.find(h=>a.includes(h))??t,c=e[u].cfg,p=e[t].cfg,d=e[n].cfg,m={},g=new Set([...Object.keys(c),...Object.keys(p),...Object.keys(d)]);for(let h of g){let f=c[h],x=p[h],A=d[h];if(x===f&&A!==x)m[h]=A;else if(A===f&&x!==A)m[h]=x;else if(x!==A&&x!==f&&A!==f){let y=r(t,n);m[h]=y===t?x:A}else m[h]=x??A??f}return m}};var Zo=class{endpoint;timeout;retryAttempts;retryDelay;logger;constructor(e){this.endpoint=e.endpoint.replace(/\/$/,""),this.timeout=e.timeout??3e4,this.retryAttempts=e.retryAttempts??3,this.retryDelay=e.retryDelay??1e3,this.logger=e.logger}async healthCheck(){try{return(await this.fetchWithRetry("/health",{method:"GET"})).ok}catch(e){return this.logger?.({name:"Notification",id:"health_check_failed",value:`Health check failed: ${e}`}),!1}}async createOptimizationJob(e){let t=await this.fetchWithRetry("/optimize",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok){let n=await t.text();throw new Error(`Failed to create optimization job: ${n}`)}return t.json()}async getJobStatus(e){let t=await this.fetchWithRetry(`/jobs/${e}`,{method:"GET"});if(!t.ok){let n=await t.text();throw new Error(`Failed to get job status: ${n}`)}return t.json()}async cancelJob(e){let t=await this.fetchWithRetry(`/jobs/${e}`,{method:"DELETE"});if(!t.ok){let n=await t.text();throw new Error(`Failed to cancel job: ${n}`)}}async suggestParameters(e){let t=await this.fetchWithRetry(`/studies/${e}/suggest`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!t.ok){let n=await t.text();throw new Error(`Failed to suggest parameters: ${n}`)}return t.json()}async evaluateTrial(e){let t=await this.fetchWithRetry(`/studies/${e.study_name}/evaluate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok){let n=await t.text();throw new Error(`Failed to evaluate trial: ${n}`)}}async getStudyResults(e){let t=await this.fetchWithRetry(`/studies/${e}/results`,{method:"GET"});if(!t.ok){let n=await t.text();throw new Error(`Failed to get study results: ${n}`)}return t.json()}async deleteStudy(e){let t=await this.fetchWithRetry(`/studies/${e}`,{method:"DELETE"});if(!t.ok){let n=await t.text();throw new Error(`Failed to delete study: ${n}`)}}async listStudies(){let e=await this.fetchWithRetry("/studies",{method:"GET"});if(!e.ok){let t=await e.text();throw new Error(`Failed to list studies: ${t}`)}return e.json()}async waitForJobCompletion(e,t=2e3,n=3e5){let r=Date.now();for(;Date.now()-r<n;){let o=await this.getJobStatus(e);if(["completed","failed","cancelled"].includes(o.status))return o;this.logger?.({name:"Notification",id:"job_status",value:`Job ${e} status: ${o.status}, waiting...`}),await this.sleep(t)}throw new Error(`Job ${e} did not complete within ${n}ms`)}async fetchWithRetry(e,t){let n=`${this.endpoint}${e}`,r=null;for(let o=0;o<this.retryAttempts;o++)try{let s=new AbortController,a=setTimeout(()=>s.abort(),this.timeout),l=await fetch(n,{...t,signal:s.signal});return clearTimeout(a),l}catch(s){r=s,this.logger?.({name:"Notification",id:"retry_attempt",value:`Attempt ${o+1} failed: ${s}`}),o<this.retryAttempts-1&&await this.sleep(this.retryDelay*Math.pow(2,o))}throw new Error(`Request failed after ${this.retryAttempts} attempts: ${r?.message}`)}sleep(e){return new Promise(t=>setTimeout(t,e))}};var es=class extends je{maxBootstrappedDemos;maxLabeledDemos;numCandidates;initTemperature;numTrials;minibatch;minibatchSize;minibatchFullEvalSteps;programAwareProposer;dataAwareProposer;viewDataBatchSize;tipAwareProposer;fewshotAwareProposer;earlyStoppingTrials;minImprovementThreshold;bayesianOptimization;acquisitionFunction;explorationWeight;optimizeTopP;sampleCount;pythonClient;localScoreHistory=[];localConfigurationHistory=[];customResultPicker;constructor(e){if(super(e),this.numCandidates=e.numCandidates??5,this.initTemperature=e.initTemperature??.7,this.maxBootstrappedDemos=e.maxBootstrappedDemos??3,this.maxLabeledDemos=e.maxLabeledDemos??4,this.numTrials=e.numTrials??30,this.minibatch=e.minibatch??!0,this.minibatchSize=e.minibatchSize??25,this.minibatchFullEvalSteps=e.minibatchFullEvalSteps??10,this.programAwareProposer=e.programAwareProposer??!0,this.dataAwareProposer=e.dataAwareProposer??!0,this.viewDataBatchSize=e.viewDataBatchSize??10,this.tipAwareProposer=e.tipAwareProposer??!0,this.fewshotAwareProposer=e.fewshotAwareProposer??!0,this.earlyStoppingTrials=e.earlyStoppingTrials??5,this.minImprovementThreshold=e.minImprovementThreshold??.01,this.bayesianOptimization=e.bayesianOptimization??!0,this.acquisitionFunction=e.acquisitionFunction??"expected_improvement",this.explorationWeight=e.explorationWeight??.1,this.optimizeTopP=e.optimizeTopP??!1,this.sampleCount=e.sampleCount??1,this.customResultPicker=e.resultPicker,e.optimizerEndpoint){let t={endpoint:e.optimizerEndpoint,timeout:e.optimizerTimeout??3e4,retryAttempts:e.optimizerRetries??3,logger:n=>{this.logger?.({name:"Notification",id:"python_client",value:typeof n=="string"?n:JSON.stringify(n)})}};this.pythonClient=new Zo(t)}this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}defaultResultPicker=async e=>{if(e.type==="function"){let o=e.results.findIndex(s=>!s.isError);return o>=0?o:0}let t=new Map;for(let o of e.results){let s=JSON.stringify(o.sample??{}),a=t.get(s);a?a.count+=1:t.set(s,{count:1,firstIndex:o.index})}let n="",r={count:-1,firstIndex:0};for(let[o,s]of t.entries())s.count>r.count&&(r=s,n=o);return t.get(n)?.firstIndex??0};configureAuto(e){switch(e){case"light":this.numCandidates=3,this.numTrials=10,this.minibatch=!0,this.minibatchSize=20;break;case"medium":this.numCandidates=5,this.numTrials=20,this.minibatch=!0,this.minibatchSize=25;break;case"heavy":this.numCandidates=7,this.numTrials=30,this.minibatch=!0,this.minibatchSize=30;break}}generateTips(){return["Be very specific and detailed in your instructions.","Focus on step-by-step reasoning in your instructions.","Provide clear constraints and guidelines in your instructions.","Keep your instructions concise and to the point.","Emphasize accuracy and precision in your instructions.","Include examples of good outputs in your instructions.","Focus on handling edge cases in your instructions.","Explicitly outline the reasoning process in your instructions."]}async generateProgramSummary(e,t){let r=`
488
495
  Analyze this language model program and provide a concise summary of its purpose and structure.
489
496
 
490
497
  Program Signature: ${e.getSignature()}
@@ -494,7 +501,7 @@ Provide a 2-3 sentence summary focusing on:
494
501
  2. The input-output relationship
495
502
  3. Any special constraints or requirements
496
503
 
497
- Summary:`;try{let o=await t.chat({chatPrompt:[{role:"user",content:r}]});return"results"in o&&o.results[0]?.content?.trim()||"General language model program"}catch{return"General language model program"}}async generateDatasetSummary(e,t){if(e.length===0)return"No examples available";let n=Math.min(this.viewDataBatchSize,e.length),i=`
504
+ Summary:`;try{let o=await t.chat({chatPrompt:[{role:"user",content:r}]});return"results"in o&&o.results[0]?.content?.trim()||"General language model program"}catch{return"General language model program"}}async generateDatasetSummary(e,t){if(e.length===0)return"No examples available";let n=Math.min(this.viewDataBatchSize,e.length),s=`
498
505
  Analyze this dataset and provide a concise summary of its characteristics.
499
506
 
500
507
  Sample Examples:
@@ -506,10 +513,10 @@ Provide a 2-3 sentence summary focusing on:
506
513
  2. Common patterns or structures in the examples
507
514
  3. Key challenges or requirements for processing this data
508
515
 
509
- Dataset Summary:`;try{let a=await t.chat({chatPrompt:[{role:"user",content:i}]});return"results"in a&&a.results[0]?.content?.trim()||"General dataset"}catch{return"General dataset"}}async generateInstruction({tip:e,candidateIndex:t,ai:n,programSummary:r,datasetSummary:o,previousInstructions:i=[]}){let a="";this.programAwareProposer&&r&&(a+=`
516
+ Dataset Summary:`;try{let a=await t.chat({chatPrompt:[{role:"user",content:s}]});return"results"in a&&a.results[0]?.content?.trim()||"General dataset"}catch{return"General dataset"}}async generateInstruction({tip:e,candidateIndex:t,ai:n,programSummary:r,datasetSummary:o,previousInstructions:s=[]}){let a="";this.programAwareProposer&&r&&(a+=`
510
517
  Program Context: ${r}`),this.dataAwareProposer&&o&&(a+=`
511
- Dataset Context: ${o}`),this.fewshotAwareProposer&&i.length>0&&(a+=`
512
- Previous Instructions (avoid repeating): ${i.slice(-3).join("; ")}`);let l=`
518
+ Dataset Context: ${o}`),this.fewshotAwareProposer&&s.length>0&&(a+=`
519
+ Previous Instructions (avoid repeating): ${s.slice(-3).join("; ")}`);let l=`
513
520
  Generate a high-quality instruction for a language model program.
514
521
 
515
522
  ${a}
@@ -524,12 +531,12 @@ Requirements:
524
531
  5. Keep it concise but comprehensive
525
532
 
526
533
  Generate a single, well-crafted instruction:
527
- Instruction:`;try{let m=(await _e('programSummary?:string "Program context" , datasetSummary?:string "Dataset context" , tip?:string "Generation tip" -> instructionText:string "Well-crafted instruction for the program"').forward(n,{programSummary:r??"",datasetSummary:o??"",tip:e??""})).instructionText;if(m&&m.trim().length>10)return m.trim()}catch{}let u=["Analyze the input systematically and provide a precise, well-reasoned response.","Think through this step-by-step, considering all relevant factors before responding.","Examine the input carefully and generate an accurate, detailed answer.","Process the information methodically and deliver a clear, comprehensive response.","Consider the context thoroughly and provide a thoughtful, accurate answer."],c=u[t%u.length]||u[0];return e&&(c=`${c} ${e}`),c}async proposeInstructionCandidates(e,t,n=[]){let r=[],o=this.getTeacherOrStudentAI(t),i,a;this.programAwareProposer&&(i=await this.generateProgramSummary(e,o)),this.dataAwareProposer&&(a=await this.generateDatasetSummary([...n],o));let l=this.tipAwareProposer?this.generateTips():[];for(let u=0;u<this.numCandidates;u++){let c=l.length>0?u%l.length:-1,p=c>=0?l[c]:void 0,d=await this.generateInstruction({tip:p,candidateIndex:u,ai:o,programSummary:i,datasetSummary:a,previousInstructions:r});r.push(d)}return r}async bootstrapFewShotExamples(e,t,n){return(await new vn({studentAI:this.studentAI,options:{maxDemos:this.maxBootstrappedDemos,maxRounds:3,verboseMode:this.verbose??!1}}).compile(e,n,t,{maxDemos:this.maxBootstrappedDemos})).demos||[]}selectLabeledExamples(e){let t=[],n=new Set;for(;n.size<this.maxLabeledDemos&&n.size<e.length;){let r=Math.floor(Math.random()*e.length);if(!n.has(r)){n.add(r);let o=e[r];o&&t.push(o)}}return t}applyConfigToProgram(e,t,n,r){e.setInstruction&&e.setInstruction(t.instruction),t.bootstrappedDemos>0&&e.setDemos&&e.setDemos(n.slice(0,t.bootstrappedDemos)),t.labeledExamples>0&&e.setExamples&&e.setExamples(r.slice(0,t.labeledExamples))}async compile(e,t,n,r){let o=Date.now();if(this.validateExamples(t),this.setupRandomSeed(),r?.auto&&this.configureAuto(r.auto),!this.pythonClient)throw new Error("AxMiPRO v2 requires the Python optimizer service. Please configure optimizerEndpoint.");if(!await this.pythonClient.healthCheck())throw new Error("Python optimizer service is not available or unhealthy");return await this.compilePython(e,t,n,r)}applyConfigToAxGen(e,t,n,r){"setInstruction"in e&&typeof e.setInstruction=="function"&&e.setInstruction(t.instruction),t.bootstrappedDemos>0&&e.setDemos(n.slice(0,t.bootstrappedDemos)),t.labeledExamples>0&&e.setExamples(r.slice(0,t.labeledExamples))}getConfiguration(){return{numCandidates:this.numCandidates,initTemperature:this.initTemperature,maxBootstrappedDemos:this.maxBootstrappedDemos,maxLabeledDemos:this.maxLabeledDemos,numTrials:this.numTrials,minibatch:this.minibatch,minibatchSize:this.minibatchSize,minibatchFullEvalSteps:this.minibatchFullEvalSteps,programAwareProposer:this.programAwareProposer,dataAwareProposer:this.dataAwareProposer,tipAwareProposer:this.tipAwareProposer,fewshotAwareProposer:this.fewshotAwareProposer,earlyStoppingTrials:this.earlyStoppingTrials,minImprovementThreshold:this.minImprovementThreshold,bayesianOptimization:this.bayesianOptimization,acquisitionFunction:this.acquisitionFunction,explorationWeight:this.explorationWeight,sampleCount:this.sampleCount}}updateConfiguration(e){e.numCandidates!==void 0&&(this.numCandidates=e.numCandidates),e.initTemperature!==void 0&&(this.initTemperature=e.initTemperature),e.maxBootstrappedDemos!==void 0&&(this.maxBootstrappedDemos=e.maxBootstrappedDemos),e.maxLabeledDemos!==void 0&&(this.maxLabeledDemos=e.maxLabeledDemos),e.numTrials!==void 0&&(this.numTrials=e.numTrials),e.minibatch!==void 0&&(this.minibatch=e.minibatch),e.minibatchSize!==void 0&&(this.minibatchSize=e.minibatchSize),e.earlyStoppingTrials!==void 0&&(this.earlyStoppingTrials=e.earlyStoppingTrials),e.minImprovementThreshold!==void 0&&(this.minImprovementThreshold=e.minImprovementThreshold),e.sampleCount!==void 0&&(this.sampleCount=e.sampleCount)}reset(){super.reset(),this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}validateProgram(e){let t=[],n=[];return{isValid:t.length===0,issues:t,suggestions:n}}async compilePython(e,t,n,r){if(!this.pythonClient)throw new Error("Python client not initialized");let o=Date.now();this.localScoreHistory=[],this.localConfigurationHistory=[];let i=await this.proposeInstructionCandidates(e,r,t),a=`mipro_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,l={study_name:a,parameters:[{name:"temperature",type:"float",low:.1,high:2},{name:"bootstrappedDemos",type:"int",low:0,high:this.maxBootstrappedDemos},{name:"instruction",type:"categorical",choices:i},{name:"labeledExamples",type:"int",low:0,high:this.maxLabeledDemos},...this.optimizeTopP?[{name:"topP",type:"float",low:.7,high:1}]:[]],objective:{name:"score",direction:"maximize"},n_trials:this.numTrials,sampler:"TPESampler",pruner:this.minibatch?"MedianPruner":void 0},u=await this.pythonClient.createOptimizationJob(l);this.getOptimizerLogger()?.({name:"OptimizationStart",value:{optimizerType:"MiPRO (Python)",exampleCount:t.length,validationCount:0,config:{jobId:u.job_id,numTrials:this.numTrials}}});let p=Number.NEGATIVE_INFINITY,d,m=0,g=0;for(let k=0;k<this.numTrials;k++)try{let S=await this.pythonClient.suggestParameters(a),M=S.params.temperature,R=S.params.bootstrappedDemos,O=S.params.instruction,F=S.params.labeledExamples,P=this.optimizeTopP?S.params.topP:void 0;if(M===void 0)throw new Error(`Missing temperature parameter in suggestion: ${JSON.stringify(S)}`);if(R===void 0)throw new Error(`Missing bootstrappedDemos parameter in suggestion: ${JSON.stringify(S)}`);if(O===void 0)throw new Error(`Missing instruction parameter in suggestion: ${JSON.stringify(S)}`);if(F===void 0)throw new Error(`Missing labeledExamples parameter in suggestion: ${JSON.stringify(S)}`);let I=e.clone();I.setInstruction(O),I.setExamples(this.selectLabeledExamples(t).slice(0,F));let T=!this.minibatch||this.minibatchFullEvalSteps>0&&k%this.minibatchFullEvalSteps===this.minibatchFullEvalSteps-1?[...t]:(()=>{let E=Math.min(this.minibatchSize,t.length),_=new Set;for(;_.size<E;)_.add(Math.floor(Math.random()*t.length));return Array.from(_).map($=>t[$])})(),w=await this.evaluateConfiguration(I,n,{temperature:M,bootstrappedDemos:R,topP:P},T);m++,await this.pythonClient.evaluateTrial({study_name:a,trial_number:S.trial_number,value:w}),w>p+this.minImprovementThreshold?(p=w,d={temperature:M,bootstrappedDemos:R,...P!==void 0?{topP:P}:{},trialNumber:S.trial_number},g=0):g+=1,this.currentRound=k+1;let C={temperature:M,bootstrappedDemos:R,...P!==void 0?{topP:P}:{},trialNumber:S.trial_number};if(this.localScoreHistory.push(w),this.localConfigurationHistory.push(C),await this.updateOptimizationProgress(this.currentRound,w,C,"MiPRO (Python)",{sampler:"TPESampler"},p,d),this.onProgress?.({round:k+1,totalRounds:this.numTrials,currentScore:w,bestScore:p,tokensUsed:this.stats.estimatedTokenUsage,timeElapsed:Date.now()-o,successfulExamples:m,totalExamples:t.length}),this.earlyStoppingTrials>0&&g>=this.earlyStoppingTrials){this.getOptimizerLogger()?.({name:"EarlyStopping",value:{reason:`No improvement \u2265 ${this.minImprovementThreshold} for ${this.earlyStoppingTrials} trials`,finalScore:p,round:this.currentRound}}),this.onEarlyStop?.(`No improvement for ${this.earlyStoppingTrials} trials`,this.stats);break}}catch{}let f=p,h={},x=[];try{let k=await this.pythonClient.getStudyResults(a);if(f=k.best_value||p,h=k.best_params||{},h&&Object.keys(h).length>0){let S=h.bootstrappedDemos||0;S>0&&(x=await this.bootstrapFewShotExamples(e,n,t.slice(0,Math.floor(t.length*.8))),x=x.slice(0,S))}}catch{}let A;try{let S=await _e('optimizerType:string "Optimizer name" , bestScore:number "Final best score" , totalCalls:number "Total eval calls" , successfulDemos:number "Successful evals" , bestConfig:json "Best configuration" -> humanExplanation:string "Readable summary", recommendations:string[] "Next steps", performanceAssessment:string "Performance notes"').forward(this.studentAI,{optimizerType:"MiPRO (Python)",bestScore:f,totalCalls:this.stats.totalCalls,successfulDemos:this.stats.successfulDemos,bestConfig:h||{}});A={humanExplanation:S.humanExplanation??"",recommendations:S.recommendations??[],performanceAssessment:S.performanceAssessment??""}}catch{}await this.logOptimizationComplete("MiPRO (Python)",f,h,r,A);try{await this.pythonClient.deleteStudy(a)}catch{}this.stats.bestScore=f;let y=new Ce(e.getSignature());h.instruction&&y.setInstruction(h.instruction),x.length>0&&y.setDemos(x),h.temperature&&(y._optimizedModelConfig={temperature:h.temperature});let b=new mt({bestScore:f,stats:this.stats,instruction:h.instruction,demos:x,examples:[],modelConfig:{temperature:h.temperature},optimizerType:"MiPRO (Python)",optimizationTime:Date.now()-o,totalRounds:this.numTrials,converged:this.stats.convergenceInfo.converged,scoreHistory:[...this.localScoreHistory],configurationHistory:[...this.localConfigurationHistory]});return this.generateOptimizationReport(f,x.length),{bestScore:f,demos:x,stats:this.stats,optimizedGen:y,optimizedProgram:b,finalConfiguration:{temperature:h.temperature,bootstrappedDemos:h.bootstrappedDemos||0,...h}}}generateOptimizationReport(e,t){console.log(`
534
+ Instruction:`;try{let m=(await _e('programSummary?:string "Program context" , datasetSummary?:string "Dataset context" , tip?:string "Generation tip" -> instructionText:string "Well-crafted instruction for the program"').forward(n,{programSummary:r??"",datasetSummary:o??"",tip:e??""})).instructionText;if(m&&m.trim().length>10)return m.trim()}catch{}let u=["Analyze the input systematically and provide a precise, well-reasoned response.","Think through this step-by-step, considering all relevant factors before responding.","Examine the input carefully and generate an accurate, detailed answer.","Process the information methodically and deliver a clear, comprehensive response.","Consider the context thoroughly and provide a thoughtful, accurate answer."],c=u[t%u.length]||u[0];return e&&(c=`${c} ${e}`),c}async proposeInstructionCandidates(e,t,n=[]){let r=[],o=this.getTeacherOrStudentAI(t),s,a;this.programAwareProposer&&(s=await this.generateProgramSummary(e,o)),this.dataAwareProposer&&(a=await this.generateDatasetSummary([...n],o));let l=this.tipAwareProposer?this.generateTips():[];for(let u=0;u<this.numCandidates;u++){let c=l.length>0?u%l.length:-1,p=c>=0?l[c]:void 0,d=await this.generateInstruction({tip:p,candidateIndex:u,ai:o,programSummary:s,datasetSummary:a,previousInstructions:r});r.push(d)}return r}async bootstrapFewShotExamples(e,t,n){return(await new vn({studentAI:this.studentAI,options:{maxDemos:this.maxBootstrappedDemos,maxRounds:3,verboseMode:this.verbose??!1}}).compile(e,n,t,{maxDemos:this.maxBootstrappedDemos})).demos||[]}selectLabeledExamples(e){let t=[],n=new Set;for(;n.size<this.maxLabeledDemos&&n.size<e.length;){let r=Math.floor(Math.random()*e.length);if(!n.has(r)){n.add(r);let o=e[r];o&&t.push(o)}}return t}applyConfigToProgram(e,t,n,r){e.setInstruction&&e.setInstruction(t.instruction),t.bootstrappedDemos>0&&e.setDemos&&e.setDemos(n.slice(0,t.bootstrappedDemos)),t.labeledExamples>0&&e.setExamples&&e.setExamples(r.slice(0,t.labeledExamples))}async compile(e,t,n,r){let o=Date.now();if(this.validateExamples(t),this.setupRandomSeed(),r?.auto&&this.configureAuto(r.auto),!this.pythonClient)throw new Error("AxMiPRO v2 requires the Python optimizer service. Please configure optimizerEndpoint.");if(!await this.pythonClient.healthCheck())throw new Error("Python optimizer service is not available or unhealthy");return await this.compilePython(e,t,n,r)}applyConfigToAxGen(e,t,n,r){"setInstruction"in e&&typeof e.setInstruction=="function"&&e.setInstruction(t.instruction),t.bootstrappedDemos>0&&e.setDemos(n.slice(0,t.bootstrappedDemos)),t.labeledExamples>0&&e.setExamples(r.slice(0,t.labeledExamples))}getConfiguration(){return{numCandidates:this.numCandidates,initTemperature:this.initTemperature,maxBootstrappedDemos:this.maxBootstrappedDemos,maxLabeledDemos:this.maxLabeledDemos,numTrials:this.numTrials,minibatch:this.minibatch,minibatchSize:this.minibatchSize,minibatchFullEvalSteps:this.minibatchFullEvalSteps,programAwareProposer:this.programAwareProposer,dataAwareProposer:this.dataAwareProposer,tipAwareProposer:this.tipAwareProposer,fewshotAwareProposer:this.fewshotAwareProposer,earlyStoppingTrials:this.earlyStoppingTrials,minImprovementThreshold:this.minImprovementThreshold,bayesianOptimization:this.bayesianOptimization,acquisitionFunction:this.acquisitionFunction,explorationWeight:this.explorationWeight,sampleCount:this.sampleCount}}updateConfiguration(e){e.numCandidates!==void 0&&(this.numCandidates=e.numCandidates),e.initTemperature!==void 0&&(this.initTemperature=e.initTemperature),e.maxBootstrappedDemos!==void 0&&(this.maxBootstrappedDemos=e.maxBootstrappedDemos),e.maxLabeledDemos!==void 0&&(this.maxLabeledDemos=e.maxLabeledDemos),e.numTrials!==void 0&&(this.numTrials=e.numTrials),e.minibatch!==void 0&&(this.minibatch=e.minibatch),e.minibatchSize!==void 0&&(this.minibatchSize=e.minibatchSize),e.earlyStoppingTrials!==void 0&&(this.earlyStoppingTrials=e.earlyStoppingTrials),e.minImprovementThreshold!==void 0&&(this.minImprovementThreshold=e.minImprovementThreshold),e.sampleCount!==void 0&&(this.sampleCount=e.sampleCount)}reset(){super.reset(),this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}validateProgram(e){let t=[],n=[];return{isValid:t.length===0,issues:t,suggestions:n}}async compilePython(e,t,n,r){if(!this.pythonClient)throw new Error("Python client not initialized");let o=Date.now();this.localScoreHistory=[],this.localConfigurationHistory=[];let s=await this.proposeInstructionCandidates(e,r,t),a=`mipro_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,l={study_name:a,parameters:[{name:"temperature",type:"float",low:.1,high:2},{name:"bootstrappedDemos",type:"int",low:0,high:this.maxBootstrappedDemos},{name:"instruction",type:"categorical",choices:s},{name:"labeledExamples",type:"int",low:0,high:this.maxLabeledDemos},...this.optimizeTopP?[{name:"topP",type:"float",low:.7,high:1}]:[]],objective:{name:"score",direction:"maximize"},n_trials:this.numTrials,sampler:"TPESampler",pruner:this.minibatch?"MedianPruner":void 0},u=await this.pythonClient.createOptimizationJob(l);this.getOptimizerLogger()?.({name:"OptimizationStart",value:{optimizerType:"MiPRO (Python)",exampleCount:t.length,validationCount:0,config:{jobId:u.job_id,numTrials:this.numTrials}}});let p=Number.NEGATIVE_INFINITY,d,m=0,g=0;for(let S=0;S<this.numTrials;S++)try{let w=await this.pythonClient.suggestParameters(a),M=w.params.temperature,R=w.params.bootstrappedDemos,k=w.params.instruction,F=w.params.labeledExamples,E=this.optimizeTopP?w.params.topP:void 0;if(M===void 0)throw new Error(`Missing temperature parameter in suggestion: ${JSON.stringify(w)}`);if(R===void 0)throw new Error(`Missing bootstrappedDemos parameter in suggestion: ${JSON.stringify(w)}`);if(k===void 0)throw new Error(`Missing instruction parameter in suggestion: ${JSON.stringify(w)}`);if(F===void 0)throw new Error(`Missing labeledExamples parameter in suggestion: ${JSON.stringify(w)}`);let T=e.clone();T.setInstruction(k),T.setExamples(this.selectLabeledExamples(t).slice(0,F));let C=!this.minibatch||this.minibatchFullEvalSteps>0&&S%this.minibatchFullEvalSteps===this.minibatchFullEvalSteps-1?[...t]:(()=>{let P=Math.min(this.minibatchSize,t.length),_=new Set;for(;_.size<P;)_.add(Math.floor(Math.random()*t.length));return Array.from(_).map($=>t[$])})(),O=await this.evaluateConfiguration(T,n,{temperature:M,bootstrappedDemos:R,topP:E},C);m++,await this.pythonClient.evaluateTrial({study_name:a,trial_number:w.trial_number,value:O}),O>p+this.minImprovementThreshold?(p=O,d={temperature:M,bootstrappedDemos:R,...E!==void 0?{topP:E}:{},trialNumber:w.trial_number},g=0):g+=1,this.currentRound=S+1;let I={temperature:M,bootstrappedDemos:R,...E!==void 0?{topP:E}:{},trialNumber:w.trial_number};if(this.localScoreHistory.push(O),this.localConfigurationHistory.push(I),await this.updateOptimizationProgress(this.currentRound,O,I,"MiPRO (Python)",{sampler:"TPESampler"},p,d),this.onProgress?.({round:S+1,totalRounds:this.numTrials,currentScore:O,bestScore:p,tokensUsed:this.stats.estimatedTokenUsage,timeElapsed:Date.now()-o,successfulExamples:m,totalExamples:t.length}),this.earlyStoppingTrials>0&&g>=this.earlyStoppingTrials){this.getOptimizerLogger()?.({name:"EarlyStopping",value:{reason:`No improvement \u2265 ${this.minImprovementThreshold} for ${this.earlyStoppingTrials} trials`,finalScore:p,round:this.currentRound}}),this.onEarlyStop?.(`No improvement for ${this.earlyStoppingTrials} trials`,this.stats);break}}catch{}let h=p,f={},x=[];try{let S=await this.pythonClient.getStudyResults(a);if(h=S.best_value||p,f=S.best_params||{},f&&Object.keys(f).length>0){let w=f.bootstrappedDemos||0;w>0&&(x=await this.bootstrapFewShotExamples(e,n,t.slice(0,Math.floor(t.length*.8))),x=x.slice(0,w))}}catch{}let A;try{let w=await _e('optimizerType:string "Optimizer name" , bestScore:number "Final best score" , totalCalls:number "Total eval calls" , successfulDemos:number "Successful evals" , bestConfig:json "Best configuration" -> humanExplanation:string "Readable summary", recommendations:string[] "Next steps", performanceAssessment:string "Performance notes"').forward(this.studentAI,{optimizerType:"MiPRO (Python)",bestScore:h,totalCalls:this.stats.totalCalls,successfulDemos:this.stats.successfulDemos,bestConfig:f||{}});A={humanExplanation:w.humanExplanation??"",recommendations:w.recommendations??[],performanceAssessment:w.performanceAssessment??""}}catch{}await this.logOptimizationComplete("MiPRO (Python)",h,f,r,A);try{await this.pythonClient.deleteStudy(a)}catch{}this.stats.bestScore=h;let y=new Ce(e.getSignature());f.instruction&&y.setInstruction(f.instruction),x.length>0&&y.setDemos(x),f.temperature&&(y._optimizedModelConfig={temperature:f.temperature});let b=new mt({bestScore:h,stats:this.stats,instruction:f.instruction,demos:x,examples:[],modelConfig:{temperature:f.temperature},optimizerType:"MiPRO (Python)",optimizationTime:Date.now()-o,totalRounds:this.numTrials,converged:this.stats.convergenceInfo.converged,scoreHistory:[...this.localScoreHistory],configurationHistory:[...this.localConfigurationHistory]});return this.generateOptimizationReport(h,x.length),{bestScore:h,demos:x,stats:this.stats,optimizedGen:y,optimizedProgram:b,finalConfiguration:{temperature:f.temperature,bootstrappedDemos:f.bootstrappedDemos||0,...f}}}generateOptimizationReport(e,t){console.log(`
528
535
  \u{1F389} MiPRO Optimization Complete!
529
536
  `),console.log("\u2705 Improvements:"),e!==void 0&&e>0&&console.log(`\u2022 Best score achieved: ${e.toFixed(3)}`),t>0&&console.log(`\u2022 Generated ${t} optimized demonstrations`),console.log("\u2022 Systematic prompt and example optimization"),console.log(`\u2022 Automated instruction refinement process
530
537
  `),console.log("\u26A0\uFE0F Limitations:"),this.stats.totalCalls<50&&console.log("\u2022 Relatively few optimization trials performed"),t<5&&console.log("\u2022 Limited number of demonstrations generated"),console.log("\u2022 Results depend on teacher model quality"),console.log(`\u2022 Optimization time increases with example complexity
531
538
  `),console.log("\u{1F50D} Key Issues:"),e!==void 0&&e<.7&&console.log("\u2022 Final performance may still have room for improvement"),this.stats.convergenceInfo?.converged===!1&&console.log("\u2022 Optimization may not have fully converged"),console.log("\u2022 Evaluation metrics may need domain-specific tuning"),console.log(`\u2022 Bootstrap quality depends on initial examples
532
- `),console.log("\u{1F4A1} What This Means:"),console.log("\u2022 MiPRO successfully automated prompt engineering"),console.log("\u2022 Optimized instructions and examples improve model performance"),console.log("\u2022 Framework reduces manual prompt engineering effort"),console.log("\u2022 More training data and iterations would likely improve results")}async evaluateConfiguration(e,t,n,r){let o=0,i=0,a=0,l=r;for(let u of l)try{let c=await e.forward(this.studentAI,u,{modelConfig:{temperature:n.temperature,...n.topP!==void 0?{topP:n.topP}:{}},sampleCount:this.sampleCount,resultPicker:this.sampleCount>1?this.customResultPicker??this.defaultResultPicker:void 0});this.stats.totalCalls+=1;let p=await t({prediction:c,example:u});if(typeof p=="number"&&!Number.isNaN(p)){o+=p,i++;let d=typeof this.targetScore=="number"?this.targetScore:.5;p>=d&&a++}}catch(c){this.getLogger()?.({name:"Notification",id:"mipro_evaluate",value:typeof c=="string"?c:String(c)})}return this.stats.successfulDemos+=a,i>0?o/i:0}};var Sn=class{analyzeMappingDependencies(e,t){if(!e||typeof e!="function")return[];let n=[];try{let r=e.toString(),o=Array.from(r.matchAll(/state\.(\w+)/g));for(let i of o)i[1]&&!n.includes(i[1])&&n.push(i[1]);if(n.length===0)try{let i=this.createDependencyTracker(n);e(i)}catch{}}catch(r){console.debug("Dependency analysis failed:",r)}return n}createTrackingProxy(e,t){let n=this;return new Proxy(e,{get(r,o){typeof o=="string"&&!t.includes(o)&&t.push(o);let i=r[o];return i&&typeof i=="object"?n.createTrackingProxy(i,t):i},has(r,o){return typeof o=="string"&&!t.includes(o)&&t.push(o),o in r}})}parseStaticDependencies(e){let t=[];try{let n=Array.from(e.matchAll(/state\.(\w+)/g));for(let i of n)i[1]&&!t.includes(i[1])&&t.push(i[1]);let r=Array.from(e.matchAll(/\$\{state\.(\w+)\}/g));for(let i of r)i[1]&&!t.includes(i[1])&&t.push(i[1]);let o=Array.from(e.matchAll(/\{\s*(\w+)(?:\s*,\s*(\w+))*\s*\}\s*=\s*state/g));for(let i of o)for(let a=1;a<i.length;a++)i[a]&&!t.includes(i[a])&&t.push(i[a])}catch(n){console.debug("Static dependency parsing failed:",n)}return t}createDependencyTracker(e){return new Proxy({},{get(t,n){return typeof n=="string"&&!e.includes(n)&&e.push(n),new Proxy({},{get:()=>{}})}})}};async function On(s,e,t){if(!t||t<=0||t>=s.length){let r=s.map((o,i)=>e(o,i));return Promise.all(r)}let n=new Array(s.length);for(let r=0;r<s.length;r+=t){let i=s.slice(r,r+t).map((l,u)=>{let c=r+u;return e(l,c).then(p=>({result:p,originalIndex:c}))}),a=await Promise.all(i);for(let{result:l,originalIndex:u}of a)n[u]=l}return n}var kn=class{steps=[];parallelGroups=[];analyzer=new Sn;initialFields=new Set;addExecutionStep(e,t,n,r,o,i,a){let l=[],u=[],c=r||"map";if(t&&n)c="execute",l=this.analyzer.analyzeMappingDependencies(n,t),u=[`${t}Result`];else if(c==="map"&&o)u=this.analyzeMapTransformation(o),l=this.getAllProducedFields();else if(c==="parallel-map"){if(Array.isArray(o)){let d=new Set;for(let m of o)this.analyzeMapTransformation(m).forEach(f=>d.add(f));u=Array.from(d)}else o?u=this.analyzeMapTransformation(o):u=["_parallelMapResult"];l=this.getAllProducedFields()}else if(c==="merge"){if(i?.resultKey)u=[i.resultKey];else{let m=this.analyzeBranchMergeFields();u=m.length>0?m:["_mergedResult"]}e.toString().includes("_parallelResults")?l=["_parallelResults"]:l=this.getAllProducedFields()}else if(c==="parallel")u=["_parallelResults"],l=this.getAllProducedFields();else if(c==="derive")if(a?.outputFieldName&&a?.inputFieldName){u=[a.outputFieldName];let d=o?this.analyzer.analyzeMappingDependencies(o,"derive"):[];l=[a.inputFieldName,...d].filter((m,g,f)=>f.indexOf(m)===g)}else u=["_deriveResult"],l=this.getAllProducedFields();else e.toString().includes("transform(")?(c="map",l=this.getAllProducedFields(),u=["_mapResult"]):e.toString().includes("_parallelResults")&&(u=["_parallelResults"],l=this.getAllProducedFields());for(let d of l)this.getAllProducedFields().includes(d)||this.initialFields.add(d);let p={type:c,nodeName:t,dependencies:l,produces:u,stepFunction:e,stepIndex:this.steps.length};this.steps.push(p)}analyzeStepFunctionProduction(e){try{let t=this.analyzeStepFunctionSource(e);if(t.length>0&&!t.includes("_stepResult"))return t}catch(t){console.debug("Step function source analysis failed:",t)}try{let t=this.createMockState(),n=Object.keys(t),o=e(t,{mainAi:{getOptions:()=>({trace:!1}),forward:()=>Promise.resolve({text:"mock"})},mainOptions:void 0});if(o&&typeof o=="object"&&"then"in o)return this.analyzeStepFunctionSource(e);if(o&&typeof o=="object"&&!Array.isArray(o)){let a=Object.keys(o).filter(l=>!n.includes(l));if(a.length>0)return a}}catch(t){console.debug("Step function dynamic analysis failed:",t)}return this.analyzeStepFunctionSource(e)}analyzeStepFunctionSource(e){try{let t=e.toString(),n=t.match(/\{\s*\.\.\.state\s*,\s*(\w+)\s*:/g);if(n){let o=n.map(i=>{let a=i.match(/(\w+)\s*:/);return a?a[1]:null}).filter(Boolean);if(o.length>0)return o}let r=t.match(/state\.(\w+)\s*=/g);if(r){let o=r.map(i=>{let a=i.match(/state\.(\w+)\s*=/);return a?a[1]:null}).filter(Boolean);if(o.length>0)return o}}catch(t){console.debug("Step function source analysis failed:",t)}return["_stepResult"]}analyzeMapTransformation(e){try{let n=e.toString().split(/\{[\s\S]*?\}/).flatMap(()=>[])}catch{}return["_mapResult"]}createMockState(){let e={};for(let t of this.initialFields)e[t]=this.createMockValue(t);for(let t of this.steps)for(let n of t.produces)n.endsWith("Result")?e[n]={text:"mockText",value:"mockValue",result:"mockResult",data:"mockData",processedText:"mockProcessedText",sentimentValue:"mockSentiment",confidenceScore:.8,isComplex:!1,mockValue:"mockValue",responseText:"mockResponseText",inputText:"mockInputText"}:e[n]=this.createMockValue(n);return e}createMockValue(e){return e.includes("List")||e.includes("Array")||e.endsWith("s")?["mockItem1","mockItem2"]:e.includes("count")||e.includes("Count")||e.includes("index")||e.includes("Index")?0:e.includes("is")||e.includes("has")||e.includes("can")?!1:"mockValue"}analyzeBranchMergeFields(){let e=this.steps.slice(-5).filter(t=>t.type==="execute"&&t.nodeName).flatMap(t=>t.produces);return e.length>0?e:this.steps.filter(t=>t.type==="execute"&&t.nodeName).flatMap(t=>t.produces)}setInitialFields(e){this.initialFields=new Set(e),this.rebuildParallelGroups()}rebuildParallelGroups(){this.parallelGroups=[];let e=new Set,t=new Set(this.initialFields),n=0;for(;e.size<this.steps.length;){let r=[];for(let o of this.steps){if(e.has(o.stepIndex))continue;if(o.dependencies.length===0||o.dependencies.every(a=>t.has(a))){if(o.type==="merge"&&r.length>0)continue;if(r.push(o),e.add(o.stepIndex),o.type==="merge")break}}if(r.length>0){for(let o of r)o.produces.forEach(i=>t.add(i));this.parallelGroups.push({level:n,steps:r}),n++}else{let o=this.steps.filter(i=>!e.has(i.stepIndex));if(o.length>0){let i=o[0];e.add(i.stepIndex),i.produces.forEach(a=>t.add(a)),this.parallelGroups.push({level:n,steps:[i]}),n++}else break}}}getAllProducedFields(){let e=[];for(let t of this.steps)e.push(...t.produces);return e}createOptimizedExecution(e){let t=[];for(let n of this.parallelGroups)if(n.steps.length===1){let r=n.steps[0];r&&t.push(r.stepFunction)}else if(n.steps.length>1){let r=async(o,i)=>{let a=await On(n.steps,async c=>await c.stepFunction(o,i),e);if(a.some(c=>c&&typeof c=="object"&&"_parallelResults"in c)){let c=a.find(p=>p&&typeof p=="object"&&"_parallelResults"in p);return c||o}let u=o;for(let c of a)u={...u,...c};return u};t.push(r)}return t}getOptimizedExecutionSteps(){return this.parallelGroups.length===0&&this.steps.length>0&&this.rebuildParallelGroups(),this.createOptimizedExecution()}getExecutionPlan(){return this.parallelGroups.length===0&&this.steps.length>0&&this.rebuildParallelGroups(),{totalSteps:this.steps.length,parallelGroups:this.parallelGroups.length,maxParallelism:this.steps.length===0?1:Math.max(...this.parallelGroups.map(e=>e.steps.length),0),steps:this.steps,groups:this.parallelGroups}}};var Iu=s=>{console.log(s)},Mn=(s,e=!1)=>{if(e)return"[State hidden]";let t={};for(let[n,r]of Object.entries(s))if(typeof r=="string"&&r.length>100)t[n]=`${r.substring(0,100)}...`;else if(Array.isArray(r)&&r.length>3)t[n]=[...r.slice(0,3),`... (${r.length-3} more)`];else if(typeof r=="object"&&r!==null){let o=JSON.stringify(r);o.length>200?t[n]=`${o.substring(0,200)}...`:t[n]=r}else t[n]=r;return JSON.stringify(t,null,2)},En=s=>s<1e3?`${s.toFixed(1)}ms`:s<6e4?`${(s/1e3).toFixed(2)}s`:`${(s/6e4).toFixed(2)}min`,Ir=(s=Iu)=>{let e=new Ge,t=e.gray(`${"\u2501".repeat(80)}
539
+ `),console.log("\u{1F4A1} What This Means:"),console.log("\u2022 MiPRO successfully automated prompt engineering"),console.log("\u2022 Optimized instructions and examples improve model performance"),console.log("\u2022 Framework reduces manual prompt engineering effort"),console.log("\u2022 More training data and iterations would likely improve results")}async evaluateConfiguration(e,t,n,r){let o=0,s=0,a=0,l=r;for(let u of l)try{let c=await e.forward(this.studentAI,u,{modelConfig:{temperature:n.temperature,...n.topP!==void 0?{topP:n.topP}:{}},sampleCount:this.sampleCount,resultPicker:this.sampleCount>1?this.customResultPicker??this.defaultResultPicker:void 0});this.stats.totalCalls+=1;let p=await t({prediction:c,example:u});if(typeof p=="number"&&!Number.isNaN(p)){o+=p,s++;let d=typeof this.targetScore=="number"?this.targetScore:.5;p>=d&&a++}}catch(c){this.getLogger()?.({name:"Notification",id:"mipro_evaluate",value:typeof c=="string"?c:String(c)})}return this.stats.successfulDemos+=a,s>0?o/s:0}};var Sn=class{analyzeMappingDependencies(e,t){if(!e||typeof e!="function")return[];let n=[];try{let r=e.toString(),o=Array.from(r.matchAll(/state\.(\w+)/g));for(let s of o)s[1]&&!n.includes(s[1])&&n.push(s[1]);if(n.length===0)try{let s=this.createDependencyTracker(n);e(s)}catch{}}catch(r){console.debug("Dependency analysis failed:",r)}return n}createTrackingProxy(e,t){let n=this;return new Proxy(e,{get(r,o){typeof o=="string"&&!t.includes(o)&&t.push(o);let s=r[o];return s&&typeof s=="object"?n.createTrackingProxy(s,t):s},has(r,o){return typeof o=="string"&&!t.includes(o)&&t.push(o),o in r}})}parseStaticDependencies(e){let t=[];try{let n=Array.from(e.matchAll(/state\.(\w+)/g));for(let s of n)s[1]&&!t.includes(s[1])&&t.push(s[1]);let r=Array.from(e.matchAll(/\$\{state\.(\w+)\}/g));for(let s of r)s[1]&&!t.includes(s[1])&&t.push(s[1]);let o=Array.from(e.matchAll(/\{\s*(\w+)(?:\s*,\s*(\w+))*\s*\}\s*=\s*state/g));for(let s of o)for(let a=1;a<s.length;a++)s[a]&&!t.includes(s[a])&&t.push(s[a])}catch(n){console.debug("Static dependency parsing failed:",n)}return t}createDependencyTracker(e){return new Proxy({},{get(t,n){return typeof n=="string"&&!e.includes(n)&&e.push(n),new Proxy({},{get:()=>{}})}})}};async function On(i,e,t){if(!t||t<=0||t>=i.length){let r=i.map((o,s)=>e(o,s));return Promise.all(r)}let n=new Array(i.length);for(let r=0;r<i.length;r+=t){let s=i.slice(r,r+t).map((l,u)=>{let c=r+u;return e(l,c).then(p=>({result:p,originalIndex:c}))}),a=await Promise.all(s);for(let{result:l,originalIndex:u}of a)n[u]=l}return n}var kn=class{steps=[];parallelGroups=[];analyzer=new Sn;initialFields=new Set;addExecutionStep(e,t,n,r,o,s,a){let l=[],u=[],c=r||"map";if(t&&n)c="execute",l=this.analyzer.analyzeMappingDependencies(n,t),u=[`${t}Result`];else if(c==="map"&&o)u=this.analyzeMapTransformation(o),l=this.getAllProducedFields();else if(c==="parallel-map"){if(Array.isArray(o)){let d=new Set;for(let m of o)this.analyzeMapTransformation(m).forEach(h=>d.add(h));u=Array.from(d)}else o?u=this.analyzeMapTransformation(o):u=["_parallelMapResult"];l=this.getAllProducedFields()}else if(c==="merge"){if(s?.resultKey)u=[s.resultKey];else{let m=this.analyzeBranchMergeFields();u=m.length>0?m:["_mergedResult"]}e.toString().includes("_parallelResults")?l=["_parallelResults"]:l=this.getAllProducedFields()}else if(c==="parallel")u=["_parallelResults"],l=this.getAllProducedFields();else if(c==="derive")if(a?.outputFieldName&&a?.inputFieldName){u=[a.outputFieldName];let d=o?this.analyzer.analyzeMappingDependencies(o,"derive"):[];l=[a.inputFieldName,...d].filter((m,g,h)=>h.indexOf(m)===g)}else u=["_deriveResult"],l=this.getAllProducedFields();else e.toString().includes("transform(")?(c="map",l=this.getAllProducedFields(),u=["_mapResult"]):e.toString().includes("_parallelResults")&&(u=["_parallelResults"],l=this.getAllProducedFields());for(let d of l)this.getAllProducedFields().includes(d)||this.initialFields.add(d);let p={type:c,nodeName:t,dependencies:l,produces:u,stepFunction:e,stepIndex:this.steps.length};this.steps.push(p)}analyzeStepFunctionProduction(e){try{let t=this.analyzeStepFunctionSource(e);if(t.length>0&&!t.includes("_stepResult"))return t}catch(t){console.debug("Step function source analysis failed:",t)}try{let t=this.createMockState(),n=Object.keys(t),o=e(t,{mainAi:{getOptions:()=>({trace:!1}),forward:()=>Promise.resolve({text:"mock"})},mainOptions:void 0});if(o&&typeof o=="object"&&"then"in o)return this.analyzeStepFunctionSource(e);if(o&&typeof o=="object"&&!Array.isArray(o)){let a=Object.keys(o).filter(l=>!n.includes(l));if(a.length>0)return a}}catch(t){console.debug("Step function dynamic analysis failed:",t)}return this.analyzeStepFunctionSource(e)}analyzeStepFunctionSource(e){try{let t=e.toString(),n=t.match(/\{\s*\.\.\.state\s*,\s*(\w+)\s*:/g);if(n){let o=n.map(s=>{let a=s.match(/(\w+)\s*:/);return a?a[1]:null}).filter(Boolean);if(o.length>0)return o}let r=t.match(/state\.(\w+)\s*=/g);if(r){let o=r.map(s=>{let a=s.match(/state\.(\w+)\s*=/);return a?a[1]:null}).filter(Boolean);if(o.length>0)return o}}catch(t){console.debug("Step function source analysis failed:",t)}return["_stepResult"]}analyzeMapTransformation(e){try{let n=e.toString().split(/\{[\s\S]*?\}/).flatMap(()=>[])}catch{}return["_mapResult"]}createMockState(){let e={};for(let t of this.initialFields)e[t]=this.createMockValue(t);for(let t of this.steps)for(let n of t.produces)n.endsWith("Result")?e[n]={text:"mockText",value:"mockValue",result:"mockResult",data:"mockData",processedText:"mockProcessedText",sentimentValue:"mockSentiment",confidenceScore:.8,isComplex:!1,mockValue:"mockValue",responseText:"mockResponseText",inputText:"mockInputText"}:e[n]=this.createMockValue(n);return e}createMockValue(e){return e.includes("List")||e.includes("Array")||e.endsWith("s")?["mockItem1","mockItem2"]:e.includes("count")||e.includes("Count")||e.includes("index")||e.includes("Index")?0:e.includes("is")||e.includes("has")||e.includes("can")?!1:"mockValue"}analyzeBranchMergeFields(){let e=this.steps.slice(-5).filter(t=>t.type==="execute"&&t.nodeName).flatMap(t=>t.produces);return e.length>0?e:this.steps.filter(t=>t.type==="execute"&&t.nodeName).flatMap(t=>t.produces)}setInitialFields(e){this.initialFields=new Set(e),this.rebuildParallelGroups()}rebuildParallelGroups(){this.parallelGroups=[];let e=new Set,t=new Set(this.initialFields),n=0;for(;e.size<this.steps.length;){let r=[];for(let o of this.steps){if(e.has(o.stepIndex))continue;if(o.dependencies.length===0||o.dependencies.every(a=>t.has(a))){if(o.type==="merge"&&r.length>0)continue;if(r.push(o),e.add(o.stepIndex),o.type==="merge")break}}if(r.length>0){for(let o of r)o.produces.forEach(s=>t.add(s));this.parallelGroups.push({level:n,steps:r}),n++}else{let o=this.steps.filter(s=>!e.has(s.stepIndex));if(o.length>0){let s=o[0];e.add(s.stepIndex),s.produces.forEach(a=>t.add(a)),this.parallelGroups.push({level:n,steps:[s]}),n++}else break}}}getAllProducedFields(){let e=[];for(let t of this.steps)e.push(...t.produces);return e}createOptimizedExecution(e){let t=[];for(let n of this.parallelGroups)if(n.steps.length===1){let r=n.steps[0];r&&t.push(r.stepFunction)}else if(n.steps.length>1){let r=async(o,s)=>{let a=await On(n.steps,async c=>await c.stepFunction(o,s),e);if(a.some(c=>c&&typeof c=="object"&&"_parallelResults"in c)){let c=a.find(p=>p&&typeof p=="object"&&"_parallelResults"in p);return c||o}let u=o;for(let c of a)u={...u,...c};return u};t.push(r)}return t}getOptimizedExecutionSteps(){return this.parallelGroups.length===0&&this.steps.length>0&&this.rebuildParallelGroups(),this.createOptimizedExecution()}getExecutionPlan(){return this.parallelGroups.length===0&&this.steps.length>0&&this.rebuildParallelGroups(),{totalSteps:this.steps.length,parallelGroups:this.parallelGroups.length,maxParallelism:this.steps.length===0?1:Math.max(...this.parallelGroups.map(e=>e.steps.length),0),steps:this.steps,groups:this.parallelGroups}}};var wu=i=>{console.log(i)},Mn=(i,e=!1)=>{if(e)return"[State hidden]";let t={};for(let[n,r]of Object.entries(i))if(typeof r=="string"&&r.length>100)t[n]=`${r.substring(0,100)}...`;else if(Array.isArray(r)&&r.length>3)t[n]=[...r.slice(0,3),`... (${r.length-3} more)`];else if(typeof r=="object"&&r!==null){let o=JSON.stringify(r);o.length>200?t[n]=`${o.substring(0,200)}...`:t[n]=r}else t[n]=r;return JSON.stringify(t,null,2)},En=i=>i<1e3?`${i.toFixed(1)}ms`:i<6e4?`${(i/1e3).toFixed(2)}s`:`${(i/6e4).toFixed(2)}min`,Tr=(i=wu)=>{let e=new Ue,t=e.gray(`${"\u2501".repeat(80)}
533
540
  `),n=e.gray(`${"\u2500".repeat(40)}
534
541
  `);return r=>{let o="";switch(r.name){case"FlowStart":o=`
535
542
  ${e.blueBright("\u{1F504} [ AXFLOW START ]")}
@@ -538,11 +545,11 @@ ${t}`,o+=`${e.white("Input Fields:")} ${e.cyan(r.inputFields.join(", "))}
538
545
  `,o+=`${e.white("Parallel Groups:")} ${e.yellow(r.parallelGroups.toString())}
539
546
  `,o+=`${e.white("Max Parallelism:")} ${e.yellow(r.maxParallelism.toString())}
540
547
  `,o+=`${e.white("Auto-Parallel:")} ${r.autoParallelEnabled?e.green("enabled"):e.red("disabled")}
541
- `,o+=t;break;case"StepStart":{let i=r.stepType==="execute"?"\u26A1":r.stepType==="map"?"\u{1F504}":r.stepType==="merge"?"\u{1F500}":r.stepType==="parallel"?"\u2696\uFE0F":"\u{1F4CB}";o=`${e.greenBright(`${i} [ STEP ${r.stepIndex} START ]`)} ${e.white(`(${r.stepType})`)}`,r.nodeName&&(o+=` ${e.cyanBright(`Node: ${r.nodeName}`)}`),o+=`
548
+ `,o+=t;break;case"StepStart":{let s=r.stepType==="execute"?"\u26A1":r.stepType==="map"?"\u{1F504}":r.stepType==="merge"?"\u{1F500}":r.stepType==="parallel"?"\u2696\uFE0F":"\u{1F4CB}";o=`${e.greenBright(`${s} [ STEP ${r.stepIndex} START ]`)} ${e.white(`(${r.stepType})`)}`,r.nodeName&&(o+=` ${e.cyanBright(`Node: ${r.nodeName}`)}`),o+=`
542
549
  `,r.dependencies.length>0&&(o+=`${e.white("Dependencies:")} ${e.gray(r.dependencies.join(", "))}
543
550
  `),r.produces.length>0&&(o+=`${e.white("Produces:")} ${e.cyan(r.produces.join(", "))}
544
551
  `),o+=`${e.white("State:")} ${e.gray(Mn(r.state,!0))}
545
- `,o+=n;break}case"StepComplete":{let i=(r.stepType==="execute"||r.stepType==="map"||r.stepType==="merge"||r.stepType==="parallel","\u2705");o=`${e.greenBright(`${i} [ STEP ${r.stepIndex} COMPLETE ]`)} ${e.white(`(${r.stepType})`)}`,r.nodeName&&(o+=` ${e.cyanBright(`Node: ${r.nodeName}`)}`),o+=` ${e.magenta(`in ${En(r.executionTime)}`)}
552
+ `,o+=n;break}case"StepComplete":{let s=(r.stepType==="execute"||r.stepType==="map"||r.stepType==="merge"||r.stepType==="parallel","\u2705");o=`${e.greenBright(`${s} [ STEP ${r.stepIndex} COMPLETE ]`)} ${e.white(`(${r.stepType})`)}`,r.nodeName&&(o+=` ${e.cyanBright(`Node: ${r.nodeName}`)}`),o+=` ${e.magenta(`in ${En(r.executionTime)}`)}
546
553
  `,r.newFields&&r.newFields.length>0&&(o+=`${e.white("New Fields:")} ${e.green(r.newFields.join(", "))}
547
554
  `),r.result&&r.nodeName&&(o+=`${e.white("Result:")} ${e.yellow(JSON.stringify(r.result,null,2))}
548
555
  `),o+=n;break}case"ParallelGroupStart":o=`${e.blueBright("\u2696\uFE0F [ PARALLEL GROUP START ]")} ${e.white(`Level ${r.groupLevel}`)}
@@ -564,7 +571,7 @@ ${e.redBright("\u274C [ AXFLOW ERROR ]")}
564
571
  ${t}`,r.stepIndex!==void 0&&(o+=`${e.white("Step:")} ${e.yellow(r.stepIndex.toString())}`,r.stepType&&(o+=` ${e.gray(`(${r.stepType})`)}`),r.nodeName&&(o+=` ${e.cyan(`Node: ${r.nodeName}`)}`),o+=`
565
572
  `),o+=`${e.white("Error:")} ${e.red(r.error)}
566
573
  `,r.state&&(o+=`${e.white("State:")} ${e.gray(Mn(r.state,!0))}
567
- `),o+=t;break;default:o=e.gray(JSON.stringify(r,null,2))}s(o)}},Tu=(s=Iu)=>{let e="=".repeat(80),t="-".repeat(40);return n=>{let r="";switch(n.name){case"FlowStart":r=`
574
+ `),o+=t;break;default:o=e.gray(JSON.stringify(r,null,2))}i(o)}},Ru=(i=wu)=>{let e="=".repeat(80),t="-".repeat(40);return n=>{let r="";switch(n.name){case"FlowStart":r=`
568
575
  [ AXFLOW START ]
569
576
  ${e}
570
577
  `,r+=`Input Fields: ${n.inputFields.join(", ")}
@@ -608,12 +615,12 @@ ${e}
608
615
  `),r+=`Error: ${n.error}
609
616
  `,n.state&&(r+=`State: ${Mn(n.state,!0)}
610
617
  `),r+=`${e}
611
- `;break;default:r=JSON.stringify(n,null,2)}s(r)}},Cu=Ir(),wu=s=>{let e=new Map;return{logger:s,startTiming:t=>{e.set(t,Date.now())},endTiming:t=>{let n=e.get(t);if(!n)return 0;let r=Date.now()-n;return e.delete(t),r},getCurrentTime:()=>Date.now()}};var Pn=class{constructor(e){this.nodeGenerators=e}steps=[];execute(e,t,n){let r=this.nodeGenerators.get(e);if(!r)throw new Error(`Node program for '${e}' not found.`);return this.steps.push(async(o,i)=>{let a=n?.ai??i.mainAi,l=n?.options??i.mainOptions,u=t(o),c=l?.traceLabel?`Node:${e} (${l.traceLabel})`:`Node:${e}`,p;if("forward"in r&&typeof r.forward=="function")p=await r.forward(a,u,{...l,traceLabel:c});else throw new Error(`Node program for '${e}' does not have a forward method`);return{...o,[`${e}Result`]:p}}),this}map(e){return this.steps.push(t=>e(t)),this}async executeSteps(e,t){let n=e;for(let r of this.steps)n=await r(n,t);return n}},es=class{constructor(e){this.nodeGenerators=e}steps=[];execute(e,t,n){let r=this.nodeGenerators.get(e);if(!r)throw new Error(`Node program for '${e}' not found.`);return this.steps.push(async(o,i)=>{let a=n?.ai??i.mainAi,l=n?.options??i.mainOptions,u=t(o),c=l?.traceLabel?`Node:${e} (${l.traceLabel})`:`Node:${e}`,p;if("forward"in r&&typeof r.forward=="function")p=await r.forward(a,u,{...l,traceLabel:c});else throw new Error(`Node program for '${e}' does not have a forward method`);return{...o,[`${e}Result`]:p}}),this}map(e){return this.steps.push(t=>e(t)),this}async executeSteps(e,t){let n=e;for(let r of this.steps)n=await r(n,t);return n}};var Tr=class s{static _ctorWarned=!1;nodes=new Map;flowDefinition=[];nodeGenerators=new Map;loopStack=[];stepLabels=new Map;branchContext=null;autoParallelConfig;executionPlanner=new kn;program;flowName;nodeUsage=new Map;nodeTraces=new Map;flowLogger;timingLogger;defaultAIOptions;toCamelCase(e){return e.replace(/_([a-z])/g,(t,n)=>n.toUpperCase())}async executeStepsWithLogging(e,t,n,r){let o={...t},i=0;for(let a=0;a<e.length;a++){let l=e[a];if(!l)continue;let u=this.getStepType(l,a),c=this.getStepMetadata(l,a),p=Object.keys(o);this.flowLogger&&this.flowLogger({name:"StepStart",timestamp:Date.now(),stepIndex:a,stepType:u,nodeName:c.nodeName,dependencies:c.dependencies,produces:c.produces,state:{...o}});let d=Date.now();this.timingLogger?.startTiming(`step-${a}`);try{o=await l(o,n),i++;let g=this.timingLogger?.endTiming(`step-${a}`)??Date.now()-d,h=Object.keys(o).filter(A=>!p.includes(A)),x;if(u==="execute"&&c.nodeName&&h.length>0){let A=`${c.nodeName}Result`;x=o[A]}this.flowLogger&&this.flowLogger({name:"StepComplete",timestamp:Date.now(),stepIndex:a,stepType:u,nodeName:c.nodeName,executionTime:g,state:{...o},newFields:h,result:x})}catch(m){throw this.flowLogger&&this.flowLogger({name:"FlowError",timestamp:Date.now(),error:m instanceof Error?m.message:String(m),stepIndex:a,stepType:u,nodeName:c.nodeName,state:{...o}}),m}}return{finalState:o,stepsExecuted:i}}getStepType(e,t){let n=e.toString();return n.includes("nodeName")||n.includes("nodeProgram")?"execute":n.includes("_parallelResults")||n.includes("processBatches")?"parallel":n.includes("branchValue")||n.includes("branches.get")||n.includes("mergeFunction")?"merge":n.includes("transform(")||n.includes("...state,")?"map":n.includes("inputValue")&&n.includes("transformFn")?"derive":n.includes("condition(")&&n.includes("iterations")?n.includes("while")?"while":"feedback":n.includes("branchSteps")||n.includes("currentState")?"branch":"other"}getStepMetadata(e,t){let r=this.executionPlanner.getExecutionPlan().steps.find(a=>a.stepIndex===t);if(r)return{nodeName:r.nodeName,dependencies:r.dependencies,produces:r.produces};let o=e.toString();return{nodeName:this.extractNodeNameFromSource(o),dependencies:[],produces:[]}}extractNodeNameFromSource(e){let t=e.match(/nodeName['"]?\s*[=:]\s*['"](\w+)['"]/);if(t)return t[1];let n=e.match(/nodeProgram\.get\(['"](\w+)['"]\)/);if(n)return n[1]}inferSignatureFromFlow(){let e=this.executionPlanner.getExecutionPlan();if(this.nodeGenerators.size===0&&e.steps.length===0)return ue().input("userInput",ue.string("User input to the flow")).output("flowOutput",ue.string("Output from the flow")).build();let t=new Set,n=new Set;for(let c of e.steps)c.produces.forEach(p=>t.add(p)),c.dependencies.forEach(p=>n.add(p));let r=new Set;for(let c of Array.from(n))t.has(c)||r.add(c);let o=new Set,i=e.steps[e.steps.length-1];if(i&&(i.type==="map"||i.type==="merge")){if(i.produces.forEach(c=>{c.startsWith("_")||o.add(c)}),i.type==="merge"&&i.produces.includes("_mergedResult"))for(let c of e.steps)c.type==="execute"&&c.produces.length>0&&c.produces.forEach(p=>o.add(p))}else for(let c of Array.from(t)){let p=!1;for(let d of e.steps)if(d.dependencies.includes(c)){p=!0;break}if(!p)if(c.endsWith("Result")){let d=c.replace("Result",""),m=this.nodeGenerators.get(d);if(m){let f=m.getSignature().getOutputFields();for(let h of f)o.add(h.name)}else o.add(c)}else o.add(c)}if(r.size===0&&o.size===0){let c=[],p=[];for(let[m,g]of Array.from(this.nodeGenerators)){let f=g.getSignature();for(let h of f.getInputFields()){let x=this.toCamelCase(`${m}_${h.name}`);c.push({name:x,type:h.type,description:h.description,isOptional:h.isOptional,isInternal:h.isInternal})}for(let h of f.getOutputFields()){let x=this.toCamelCase(`${m}_${h.name}`);p.push({name:x,type:h.type,description:h.description,isOptional:h.isOptional,isInternal:h.isInternal})}}let d=new be;return c.length>0?d.setInputFields(c):d.addInputField({name:"userInput",type:{name:"string"},description:"User input to the flow"}),p.length>0?d.setOutputFields(p):d.addOutputField({name:"flowOutput",type:{name:"string"},description:"Output from the flow"}),d}let a=new be,l=[];for(let c of Array.from(r))l.push({name:c,type:{name:"string"},description:`Input field: ${c}`});l.length===0&&l.push({name:"userInput",type:{name:"string"},description:"User input to the flow"});let u=[];for(let c of Array.from(o))c.startsWith("_")||u.push({name:c,type:{name:"string"},description:`Output field: ${c}`});return u.length===0&&u.push({name:"flowOutput",type:{name:"string"},description:"Output from the flow"}),a.setInputFields(l),a.setOutputFields(u),a}constructor(e){s._ctorWarned||(console.warn("[AxFlow] new AxFlow() is deprecated. Use flow() factory instead."),s._ctorWarned=!0),this.autoParallelConfig={enabled:e?.autoParallel!==!1,batchSize:e?.batchSize||10},e?.logger?this.flowLogger=e.logger:e?.debug===!0?this.flowLogger=Ir():this.flowLogger=void 0,this.timingLogger=this.flowLogger?wu(this.flowLogger):void 0,(e?.tracer||e?.meter)&&(this.defaultAIOptions={tracer:e.tracer,meter:e.meter})}static create(e){return new s(e)}ensureProgram(){let e=this.inferSignatureFromFlow();if(!this.program){this.program=new Et(e);for(let[t,n]of Array.from(this.nodeGenerators))this.program.register(n);return}this.program.setSignature(e)}setExamples(e,t){this.ensureProgram(),this.program.setExamples(e,t)}setId(e){this.ensureProgram(),this.program.setId(e)}setParentId(e){this.ensureProgram(),this.program.setParentId(e)}getTraces(){let e=[];for(let[t,n]of Array.from(this.nodeTraces))e.push(...n);return e}setDemos(e){this.ensureProgram(),this.program.setDemos(e)}description(e,t){return this.ensureProgram(),this.flowName=e,this.program.setDescription(t),this}toFunction(){this.ensureProgram();let e=this.program.getSignature(),n=(this.flowName??(e.getDescription()?.trim().split(`
612
- `)[0]||"axFlow")).replace(/\s+/g,"_"),r=this.toCamelCase(n),o=async(i,a)=>{let l=a?.ai;if(!l)throw new Error("AI service is required to run the flow");let u=await this.forward(l,i??{}),c=e.getOutputFields(),p=u??{};return Object.keys(p).map(d=>{let m=c.find(g=>g.name===d);return m&&m.title?`${m.title}: ${p[d]}`:`${d}: ${p[d]}`}).join(`
613
- `)};return{name:r,description:e.getDescription()??"Execute this AxFlow",parameters:e.toJSONSchema(),func:o}}getUsage(){let e=[];for(let[t,n]of Array.from(this.nodeUsage))e.push(...n);return pr(e)}resetUsage(){this.nodeUsage.clear();for(let[e,t]of Array.from(this.nodeGenerators))t&&"resetUsage"in t&&t.resetUsage()}resetTraces(){this.nodeTraces.clear()}getUsageReport(){let e={};for(let[t,n]of Array.from(this.nodeUsage))e[t]=pr(n);return e}getNodePrograms(){return Array.from(this.nodeGenerators).map(([e,t])=>({name:e,program:t}))}setNodeInstruction(e,t){let n=this.nodeGenerators.get(e);if(!n)return!1;let r=n;if(typeof r.setInstruction=="function")try{return r.setInstruction(t),!0}catch{return!1}return!1}setAllNodeInstructions(e){for(let[t,n]of Object.entries(e))this.setNodeInstruction(t,n)}getTracesReport(){let e={};for(let[t,n]of Array.from(this.nodeTraces))e[t]=n;return e}async*streamingForward(e,t,n){let r=n?.cachingFunction??te.cachingFunction,o=(()=>{if(!r)return;this.ensureProgram();let a=this.program.getSignature(),l=a.getInputFields().map(d=>d.name),u=Array.isArray(t)?t.filter(d=>d.role==="user").pop().values:t,c=Je("sha256");c.update(a.hash()??"");let p=d=>{let m=typeof d;if(c.update(`|${m}|`),d==null){c.update("null");return}if(m==="string"||m==="number"||m==="boolean"){c.update(String(d));return}if(Array.isArray(d)){c.update("[");for(let g of d)p(g);c.update("]");return}if(typeof d=="object"&&d!==null&&"mimeType"in d&&"data"in d){let g=d;c.update(g.mimeType??"");let f=Je("sha256").update(g.data??"").digest("hex");c.update(f);return}if(typeof d=="object"){let g=d,f=Object.keys(g).sort();for(let h of f)c.update(`{${h}}`),p(g[h]);return}c.update(String(d))};for(let d of l)p(u?.[d]);return c.digest("hex")})();if(r&&o){let a;try{a=await r(o)}catch{}if(a!==void 0){yield{version:0,index:0,delta:a};return}}let i=await this.forward(e,t,n);if(r&&o)try{await r(o,i)}catch{}yield{version:1,index:0,delta:i}}async forward(e,t,n){let r=n?.cachingFunction??te.cachingFunction,o=(()=>{if(!r)return;this.ensureProgram();let l=this.program.getSignature(),u=l.getInputFields().map(m=>m.name),c=Array.isArray(t)?t.filter(m=>m.role==="user").pop().values:t,p=Je("sha256");p.update(l.hash()??"");let d=m=>{let g=typeof m;if(p.update(`|${g}|`),m==null){p.update("null");return}if(g==="string"||g==="number"||g==="boolean"){p.update(String(m));return}if(Array.isArray(m)){p.update("[");for(let f of m)d(f);p.update("]");return}if(typeof m=="object"&&m!==null&&"mimeType"in m&&"data"in m){let f=m;p.update(f.mimeType??"");let h=Je("sha256").update(f.data??"").digest("hex");p.update(h);return}if(typeof m=="object"){let f=m,h=Object.keys(f).sort();for(let x of h)p.update(`{${x}}`),d(f[x]);return}p.update(String(m))};for(let m of u)d(c?.[m]);return p.digest("hex")})();if(r&&o){let l=await r(o);if(l!==void 0)return l}let i=Date.now();this.timingLogger?.startTiming("flow-execution");let a={};try{this.resetUsage(),this.resetTraces();let l;if(Array.isArray(t)){let h=t.filter(x=>x.role==="user").pop();if(!h)throw new Error("No user message found in values array");l=h.values}else l=t;if(this.nodeGenerators.size>0&&this.ensureProgram(),a={...l},this.flowLogger){let h=this.getExecutionPlan();this.flowLogger({name:"FlowStart",timestamp:i,inputFields:Object.keys(l),totalSteps:h.totalSteps,parallelGroups:h.parallelGroups,maxParallelism:h.maxParallelism,autoParallelEnabled:h.autoParallelEnabled})}let u=n?.tracer??this.defaultAIOptions?.tracer,c=n?.traceContext,p,d=c;if(u){let h=this.getExecutionPlan(),x=n?.traceLabel?`AxFlow > ${n.traceLabel}`:"AxFlow";p=u.startSpan(x,{kind:Be.INTERNAL,attributes:{total_steps:h.totalSteps,parallel_groups:h.parallelGroups,max_parallelism:h.maxParallelism,auto_parallel_enabled:h.autoParallelEnabled}});let A=c??vt.active();d=Bn.setSpan(A,p)}let m={mainAi:e,mainOptions:(()=>{let h={...this.defaultAIOptions??{},...n};return n?.model&&(h.model=String(n.model)),u&&(h.tracer=u),d&&(h.traceContext=d),Object.keys(h).length>0?h:void 0})()},g=n?.autoParallel!==!1&&this.autoParallelConfig.enabled,f=0;if(g){this.executionPlanner.setInitialFields(Object.keys(l));let h=this.executionPlanner.createOptimizedExecution(this.autoParallelConfig.batchSize),x=await this.executeStepsWithLogging(h,a,m,!0);a=x.finalState,f=x.stepsExecuted}else{let h=await this.executeStepsWithLogging(this.flowDefinition,a,m,!1);a=h.finalState,f=h.stepsExecuted}if(this.flowLogger){let h=this.timingLogger?.endTiming("flow-execution")??Date.now()-i;this.flowLogger({name:"FlowComplete",timestamp:Date.now(),totalExecutionTime:h,finalState:a,outputFields:Object.keys(a),stepsExecuted:f})}if(p&&p.end(),r&&o)try{await r(o,a)}catch{}return a}catch(l){throw this.flowLogger&&this.flowLogger({name:"FlowError",timestamp:Date.now(),error:l instanceof Error?l.message:String(l),state:a}),typeof parentSpan<"u"&&parentSpan&&parentSpan.end(),l}}node(e,t){if(typeof t=="string"||t instanceof be){let n=t;if(!n)throw new Error(`Invalid signature for node '${e}': signature cannot be empty`);this.nodes.set(e,{inputs:{},outputs:{}});let r=_e(n);this.nodeGenerators.set(e,r),this.ensureProgram(),this.program.register(r)}else if(typeof t=="function"){this.nodes.set(e,{inputs:{},outputs:{}});let n=new t;this.nodeGenerators.set(e,n),this.ensureProgram(),this.program.register(n)}else if(t&&typeof t=="object"&&"forward"in t){this.nodes.set(e,{inputs:{},outputs:{}});let n=t;this.nodeGenerators.set(e,n),this.ensureProgram(),this.program.register(n)}else throw new Error(`Invalid second argument for node '${e}': expected string, AxSignature, AxProgrammable instance, or constructor function`);return this}n(e,t){return this.node(e,t)}map(e,t){if(t?.parallel){let n=Array.isArray(e)?e:[e],r=async o=>(await On(n,async(l,u)=>{let c=l(o);return Promise.resolve(c)},this.autoParallelConfig.batchSize)).reduce((l,u)=>({...l,...u}),o);if(this.branchContext?.currentBranchValue!==void 0){let o=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];o.push(r),this.branchContext.branches.set(this.branchContext.currentBranchValue,o)}else this.flowDefinition.push(r),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(r,void 0,void 0,"parallel-map",n)}else{let n=async r=>{if(Array.isArray(e))throw new Error("Array of transforms requires parallel: true option");let o=e(r);return Promise.resolve(o)};if(this.branchContext?.currentBranchValue!==void 0){let r=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];r.push(n),this.branchContext.branches.set(this.branchContext.currentBranchValue,r)}else this.flowDefinition.push(n),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(n,void 0,void 0,"map",e)}return this.nodeGenerators.size>0&&this.ensureProgram(),this}m(e,t){return this.map(e,t)}returns(e){let t=async n=>{let r=e(n);return Promise.resolve(r)};if(this.branchContext?.currentBranchValue!==void 0){let n=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];n.push(t),this.branchContext.branches.set(this.branchContext.currentBranchValue,n)}else this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"map",e);return this.nodeGenerators.size>0&&this.ensureProgram(),this}r(e){return this.returns(e)}label(e){if(this.branchContext?.currentBranchValue!==void 0)throw new Error("Cannot create labels inside branch blocks");return this.stepLabels.set(e,this.flowDefinition.length),this}l(e){return this.label(e)}execute(e,t,n){if(!this.nodes.has(e))throw new Error(`Node '${e}' not found. Make sure to define it with .node() first.`);let r=this.nodeGenerators.get(e);if(!r)throw new Error(`Node program for '${e}' not found.`);let o=async(i,a)=>{let l=n?.ai??a.mainAi,u={...a.mainOptions??{},...n?.options??{}},c=t(i),p=u?.traceLabel?`Node:${e} (${u.traceLabel})`:`Node:${e}`,d;if("forward"in r&&typeof r.forward=="function"){if(d=await r.forward(l,c,{...u,traceLabel:p}),"getUsage"in r&&typeof r.getUsage=="function"){let m=r.getUsage();if(m&&m.length>0){let g=this.nodeUsage.get(e)||[];this.nodeUsage.set(e,[...g,...m])}}if("getTraces"in r&&typeof r.getTraces=="function"){let m=r.getTraces();if(m&&m.length>0){let g=this.nodeTraces.get(e)||[];this.nodeTraces.set(e,[...g,...m])}}}else throw new Error(`Node program for '${e}' does not have a forward method`);return{...i,[`${e}Result`]:d}};if(this.branchContext?.currentBranchValue!==void 0){let i=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];i.push(o),this.branchContext.branches.set(this.branchContext.currentBranchValue,i)}else this.flowDefinition.push(o),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(o,e,t);return this.ensureProgram(),this}applyOptimization(e){this.program&&"applyOptimization"in this.program&&this.program.applyOptimization(e);for(let[t,n]of Array.from(this.nodeGenerators))n&&"applyOptimization"in n&&typeof n.applyOptimization=="function"&&n.applyOptimization(e)}e(e,t,n){return this.execute(e,t,n)}branch(e){if(this.branchContext)throw new Error("Nested branches are not supported");return this.branchContext={predicate:t=>e(t),branches:new Map,currentBranchValue:void 0},this}b(e){return this.branch(e)}when(e){if(!this.branchContext)throw new Error("when() called without matching branch()");return this.branchContext.currentBranchValue=e,this.branchContext.branches.set(e,[]),this}w(e){return this.when(e)}merge(){if(!this.branchContext)throw new Error("merge() called without matching branch()");let e=this.branchContext;this.branchContext=null;let t=async(n,r)=>{let o=e.predicate(n),i=e.branches.get(o);if(this.flowLogger&&this.flowLogger({name:"BranchEvaluation",timestamp:Date.now(),branchValue:o,hasMatchingBranch:!!i,branchStepsCount:i?.length??0}),!i)return n;let a=n;for(let l of i)a=await l(a,r);return a};return this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"merge"),this.ensureProgram(),this}mg(){return this.merge()}parallel(e){let t=async(n,r)=>{let o=await On(e,async(i,a)=>{let l=new Pn(this.nodeGenerators);return await i(l).executeSteps(n,r)},this.autoParallelConfig.batchSize);return{...n,_parallelResults:o}};return this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"parallel",void 0,void 0),this.ensureProgram(),{merge:(n,r)=>{let o=i=>{let a=i._parallelResults;if(!Array.isArray(a))throw new Error("No parallel results found for merge");let l=r(...a),u={...i};return delete u._parallelResults,u[n]=l,u};return this.flowDefinition.push(o),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(o,void 0,void 0,"merge",void 0,{resultKey:n,mergeFunction:r}),this.ensureProgram(),this}}}p(e){return this.parallel(e)}feedback(e,t,n=10){if(!this.stepLabels.has(t))throw new Error(`Label '${t}' not found. Make sure to define it with .label() before the feedback point.`);let r=this.stepLabels.get(t),o=this.flowDefinition.length;return this.flowDefinition.push(async(i,a)=>{let l=i,u=1,c=`_feedback_${t}_iterations`;for(typeof l[c]!="number"&&(l={...l,[c]:1});e(l)&&u<n;){u++,l={...l,[c]:u};for(let p=r;p<o;p++){let d=this.flowDefinition[p];d&&(l=await d(l,a))}}return l}),this.nodeGenerators.size>0&&this.ensureProgram(),this}fb(e,t,n=10){return this.feedback(e,t,n)}while(e,t=100){let n=this.flowDefinition.length;this.loopStack.push(n);let r=Object.assign(o=>o,{_condition:e,_maxIterations:t,_isLoopStart:!0});return this.flowDefinition.push(r),this.nodeGenerators.size>0&&this.ensureProgram(),this}wh(e,t=100){return this.while(e,t)}endWhile(){if(this.loopStack.length===0)throw new Error("endWhile() called without matching while()");let e=this.loopStack.pop(),t=this.flowDefinition[e];if(!t||!("_isLoopStart"in t))throw new Error("Loop start step not found or invalid");let n=t._condition,r=t._maxIterations,o=this.flowDefinition.splice(e+1);return this.flowDefinition[e]=async(i,a)=>{let l=i,u=0;for(;n(l)&&u<r;){u++;for(let c of o)l=await c(l,a)}if(u>=r&&n(l))throw new Error(`While loop exceeded maximum iterations (${r}). Consider increasing maxIterations or ensuring the loop condition eventually becomes false.`);return l},this.nodeGenerators.size>0&&this.ensureProgram(),this}end(){return this.endWhile()}derive(e,t,n,r){let o=async i=>{let a=i[t];if(a===void 0)throw new Error(`Input field '${t}' not found in state`);let l;if(Array.isArray(a))if(this.autoParallelConfig.enabled){let u=r?.batchSize||this.autoParallelConfig.batchSize;l=await On(a,async(c,p)=>n(c,p,i),u)}else l=a.map((u,c)=>n(u,c,i));else l=n(a,void 0,i);return{...i,[e]:l}};if(this.branchContext?.currentBranchValue!==void 0){let i=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];i.push(o),this.branchContext.branches.set(this.branchContext.currentBranchValue,i)}else this.flowDefinition.push(o),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(o,void 0,void 0,"derive",n,void 0,{inputFieldName:t,outputFieldName:e,batchSize:r?.batchSize});return this.ensureProgram(),this}getExecutionPlan(){let e=this.executionPlanner.getExecutionPlan();return{totalSteps:e.totalSteps,parallelGroups:e.parallelGroups,maxParallelism:e.maxParallelism,autoParallelEnabled:this.autoParallelConfig.enabled,steps:e.steps,groups:e.groups}}getSignature(){return this.ensureProgram(),this.program.getSignature()}nodeExtended(e,t,n){let o=typeof t=="string"?be.create(t):t;if(n.prependInputs)for(let i of n.prependInputs)o=o.prependInputField(i.name,i.type);if(n.appendInputs)for(let i of n.appendInputs)o=o.appendInputField(i.name,i.type);if(n.prependOutputs)for(let i of n.prependOutputs)o=o.prependOutputField(i.name,i.type);if(n.appendOutputs)for(let i of n.appendOutputs)o=o.appendOutputField(i.name,i.type);return this.node(e,o)}nx(e,t,n){return this.nodeExtended(e,t,n)}mapOutput(e){let t=async n=>{let r=e(n);return{...n,...r}};if(this.branchContext?.currentBranchValue!==void 0){let n=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];n.push(t),this.branchContext.branches.set(this.branchContext.currentBranchValue,n)}else this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"map",e);return this.nodeGenerators.size>0&&this.ensureProgram(),this}mo(e){return this.mapOutput(e)}};function ts(s){return Tr.create(s)}var ns=class{apiUrl;containerId=null;constructor(e="http://localhost:2375"){this.apiUrl=e}async pullImage(e){let t=await this.fetchDockerAPI(`/images/create?fromImage=${encodeURIComponent(e)}`,{method:"POST"});if(!t.ok)throw new Error(`Failed to pull image: ${t.statusText}`);await t.text()}async createContainer({imageName:e,volumes:t=[],doNotPullImage:n,tag:r}){let o=t.map(u=>`${u.hostPath}:${u.containerPath}`);n||await this.pullImage(e);let i={Image:e,Tty:!0,OpenStdin:!1,AttachStdin:!1,AttachStdout:!1,AttachStderr:!1,HostConfig:{Binds:o},Labels:{}};r&&(i.Labels["com.example.tag"]=r);let a=await this.fetchDockerAPI("/containers/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!a.ok)throw new Error(`Failed to create container: ${a.statusText}`);let l=await a.json();return this.containerId=l.Id,l}async findOrCreateContainer({imageName:e,volumes:t=[],doNotPullImage:n,tag:r}){let i=(await this.listContainers(!0)).filter(l=>l.Labels&&l.Labels["com.example.tag"]===r);if(i&&i.length>0){let l=Math.floor(Math.random()*i.length),u=i[l];if(u)return await this.connectToContainer(u.Id),{Id:u.Id,isNew:!1}}return{Id:(await this.createContainer({imageName:e,volumes:t,doNotPullImage:n,tag:r})).Id,isNew:!0}}async startContainer(){if(!this.containerId)throw new Error("No container created or connected");let e=await this.fetchDockerAPI(`/containers/${this.containerId}/start`,{method:"POST"});if(!e.ok)throw new Error(`Failed to start container: ${e.statusText}`)}async connectToContainer(e){let t=await this.fetchDockerAPI(`/containers/${e}/json`);if(!t.ok)throw new Error(`Failed to connect to container: ${t.statusText}`);this.containerId=e}async stopContainers({tag:e,remove:t,timeout:n=10}){let r=[],o=await this.listContainers(!0),i=e?o.filter(a=>a.Labels["com.example.tag"]===e):o;for(let a of i){if(a.State.Status==="running"){let l=await this.fetchDockerAPI(`/containers/${a.Id}/stop?t=${n}`,{method:"POST"});if(!l.ok){console.warn(`Failed to stop container ${a.Id}: ${l.statusText}`);continue}r.push({Id:a.Id,Action:"stopped"})}if(t){let l=await this.fetchDockerAPI(`/containers/${a.Id}`,{method:"DELETE"});if(!l.ok){console.warn(`Failed to remove container ${a.Id}: ${l.statusText}`);continue}r.push({Id:a.Id,Action:"removed"})}}return r}async listContainers(e=!1){return(await this.fetchDockerAPI(`/containers/json?all=${e}`,{method:"GET"})).json()}async getContainerLogs(){if(!this.containerId)throw new Error("No container created or connected");return(await this.fetchDockerAPI(`/containers/${this.containerId}/logs?stdout=true&stderr=true`,{method:"GET"})).text()}async executeCommand(e){if(!this.containerId)throw new Error("No container created or connected");(await this.getContainerInfo(this.containerId)).State.Status!=="running"&&(await this.startContainer(),await this.waitForContainerToBeRunning(this.containerId));let n=await this.fetchDockerAPI(`/containers/${this.containerId}/exec`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({Cmd:["sh","-c",e],AttachStdout:!0,AttachStderr:!0})});if(!n.ok)throw new Error(`Failed to create exec instance: ${n.statusText}`);let r=await n.json(),o=await this.fetchDockerAPI(`/exec/${r.Id}/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({Detach:!1,Tty:!1})});if(!o.ok)throw new Error(`Failed to start exec instance: ${o.statusText}`);return await o.text()}async getContainerInfo(e){let t=await this.fetchDockerAPI(`/containers/${e}/json`);if(!t.ok)throw new Error(`Failed to get container info: ${t.statusText}`);return t.json()}async waitForContainerToBeRunning(e,t=3e4){let n=Date.now();for(;Date.now()-n<t;){if((await this.getContainerInfo(e)).State.Status==="running")return;await new Promise(o=>setTimeout(o,1e3))}throw new Error("Timeout waiting for container to start")}async fetchDockerAPI(e,t){let n=new URL(e,this.apiUrl).toString();return await fetch(n,t)}toFunction(){return{name:"commandExecution",description:"Use this function to execute shell commands, scripts, and programs. This function enables interaction with the file system, running system utilities, and performing tasks that require a shell interface.",parameters:{type:"object",properties:{command:{type:"string",description:'Shell command to execute. eg. `ls -l` or `echo "Hello, World!"`.'}},required:["command"]},func:async({command:e})=>await this.executeCommand(e)}}};var rs=class{aiService;info;func;constructor({ai:e,info:t,func:n}){this.aiService=e,this.info=t,this.func=n}async embedAdapter(e,t){let r=(await this.aiService.embed({texts:[e]},{sessionId:t?.sessionId,abortSignal:t?.abortSignal})).embeddings.at(0);if(!r)throw new Error("Failed to embed text");return this.func.length===2?this.func(r,t):this.func(r)}toFunction(){return{name:this.info.name,description:this.info.description,parameters:{type:"object",properties:{text:{type:"string",description:this.info.argumentDescription}},required:["text"]},func:({text:e},t)=>this.embedAdapter(e,t)}}};var os=class{constructor(e,t={}){this.transport=e;this.options=t;this.logger=t.logger??(n=>{console.log(typeof n=="string"?n:JSON.stringify(n,null,2))})}functions=[];activeRequests=new Map;capabilities={};logger;async init(){"connect"in this.transport&&await this.transport.connect?.();let{result:e}=await this.sendRequest("initialize",{protocolVersion:"2024-11-05",capabilities:{roots:{listChanged:!0},sampling:{}},clientInfo:{name:"AxMCPClient",version:"1.0.0"}}),t="2024-11-05";if(e.protocolVersion!==t)throw new Error(`Protocol version mismatch. Expected ${t} but got ${e.protocolVersion}`);e.capabilities.tools&&(this.capabilities.tools=!0),e.capabilities.resources&&(this.capabilities.resources=!0),e.capabilities.prompts&&(this.capabilities.prompts=!0),await this.sendNotification("notifications/initialized"),await this.discoverFunctions()}async discoverFunctions(){if(!this.capabilities.tools)throw new Error("Tools are not supported");let{result:e}=await this.sendRequest("tools/list");this.functions=e.tools.map(t=>{let n=this.options.functionOverrides?.find(o=>o.name===t.name),r=t.inputSchema.properties?{properties:t.inputSchema.properties,required:t.inputSchema.required??[],type:t.inputSchema.type}:void 0;return{name:n?.updates.name??t.name,description:n?.updates.description??t.description,parameters:r,func:async o=>{let{result:i}=await this.sendRequest("tools/call",{name:t.name,arguments:o});return i}}})}async ping(e=3e3){let t=this.sendRequest("ping"),n=new Promise((i,a)=>setTimeout(()=>a(new Error("Ping response timeout exceeded")),e)),r=await Promise.race([t,n]),{result:o}=r;if(typeof o!="object"||o===null||Object.keys(o).length!==0)throw new Error(`Unexpected ping response: ${JSON.stringify(o)}`)}toFunction(){return this.functions}cancelRequest(e){if(this.activeRequests.has(e)){this.sendNotification("notifications/cancelled",{requestId:e,reason:"Client cancelled request"});let t=this.activeRequests.get(e);t&&t.reject(new Error(`Request ${e} cancelled`)),this.activeRequests.delete(e)}}async sendRequest(e,t={}){let n=Pe(),r={jsonrpc:"2.0",id:n,method:e,params:t},o=new Promise((a,l)=>{this.activeRequests.set(n,{reject:l}),this.transport.send(r).then(u=>{if(this.activeRequests.delete(n),u!==null&&typeof u=="object"&&"error"in u){let c=u;l(new Error(`RPC Error ${c.error.code}: ${c.error.message}`))}else u!==null&&typeof u=="object"&&"result"in u?a({result:u.result}):l(new Error("Invalid response no result or error"))}).catch(u=>{this.activeRequests.delete(n),l(u)})}),{result:i}=await o;return{id:n,result:i}}async sendNotification(e,t={}){let n={jsonrpc:"2.0",method:e,params:t},{debug:r}=this.options;if(r){let o={name:"Notification",id:"mcp_notification",value:`Sending notification: ${JSON.stringify(n,null,2)}`};this.logger(o)}await this.transport.sendNotification(n)}};function Ru(s){if(typeof Buffer<"u")return Buffer.from(s).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"");let e="";for(let n=0;n<s.length;n++)e+=String.fromCharCode(s[n]);return(typeof btoa=="function"?btoa(e):"").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function vu(s){let t=new TextEncoder().encode(s),n=await Li().subtle.digest("SHA-256",t);return new Uint8Array(n)}async function Ni(){return Ru(await vu(Pe()+Math.random().toString(36)))}async function Su(s){return Ru(await vu(s))}async function ss(s,e){let t=await fetch(s,{headers:e});if(!t.ok)throw new Error(`HTTP ${t.status} fetching ${s}: ${t.statusText}`);return await t.json()}function Ou(s){let e=new URLSearchParams;for(let[t,n]of Object.entries(s))n!==void 0&&e.set(t,n);return e.toString()}function Cr(s){return s.endsWith("/")?s.slice(0,-1):s}function Bp(s){if(!s)return null;let e=s.match(/resource_metadata\s*=\s*"([^"]+)"/i)||s.match(/resource_metadata\s*=\s*([^,\s]+)/i);return e?e[1]:null}async function ku(s,e){let t=Bp(e);if(t){let a=await ss(t),l=Cr(new URL(s).toString().split("?")[0]),u=Cr(a.resource??"");if(!u||u!==l)throw new Error(`Protected resource metadata 'resource' mismatch. Expected ${l} but got ${u}`);let c=Array.isArray(a.authorization_servers)?a.authorization_servers:[];if(c.length===0)throw new Error("No authorization_servers advertised by protected resource");return{resource:l,issuers:c}}let n=new URL(s),r=n.pathname.replace(/\/+$/,""),o=[];r&&r!=="/"&&o.push({url:`${n.origin}/.well-known/oauth-protected-resource${r}`,expected:`${n.origin}${r}`}),o.push({url:`${n.origin}/.well-known/oauth-protected-resource`,expected:`${n.origin}`});let i;for(let a of o)try{let l=await ss(a.url),u=Cr(l.resource??""),c=Cr(a.expected);if(!u||u!==c)throw new Error(`Protected resource metadata 'resource' mismatch. Expected ${c} but got ${u}`);let p=Array.isArray(l.authorization_servers)?l.authorization_servers:[];if(p.length===0)throw new Error("No authorization_servers advertised by protected resource");return{resource:c,issuers:p}}catch(l){i=l}throw new Error(`Failed to resolve protected resource metadata via well-known endpoints. Last error: ${String(i)}`)}async function Mu(s){let e=new URL(s),t=e.pathname.replace(/^\/+/,""),n=[];t?(n.push(`${e.origin}/.well-known/oauth-authorization-server/${t}`),n.push(`${e.origin}/.well-known/openid-configuration/${t}`),n.push(`${e.origin}/${t.replace(/\/+$/,"")}/.well-known/openid-configuration`)):(n.push(`${e.origin}/.well-known/oauth-authorization-server`),n.push(`${e.origin}/.well-known/openid-configuration`));let r;for(let o of n)try{let i=await ss(o);if(!i.authorization_endpoint||!i.token_endpoint)throw new Error("AS metadata missing endpoints");let a=i.code_challenge_methods_supported;if(!a||!a.includes("S256"))throw new Error("Authorization server does not advertise PKCE S256 support");return i}catch(i){r=i}throw new Error(`Failed to discover AS metadata for ${s}: ${String(r)}`)}var Fn=class{constructor(e){this.oauth=e}tokenCache=new Map;asMetaCache=new Map;key(e,t){return`${e}::${t}`}async getStoredToken(e,t){let n=this.key(e,t);if(this.tokenCache.has(n))return this.tokenCache.get(n);let r=await this.oauth?.tokenStore?.getToken?.(n);return r&&this.tokenCache.set(n,r),r??null}async setStoredToken(e,t,n){let r=this.key(e,t);this.tokenCache.set(r,n),await this.oauth?.tokenStore?.setToken?.(r,n)}async clearStoredToken(e,t){let n=this.key(e,t);this.tokenCache.delete(n),await this.oauth?.tokenStore?.clearToken?.(n)}isExpired(e){return e?Date.now()>e-6e4:!1}async getASMeta(e){if(this.asMetaCache.has(e))return this.asMetaCache.get(e);let t=await Mu(e);return this.asMetaCache.set(e,t),t}async ensureAccessToken(e){if(!this.oauth)return null;let{resource:t,issuers:n}=await ku(e.requestedUrl,e.wwwAuthenticate),r=this.oauth.selectAuthorizationServer?await this.oauth.selectAuthorizationServer(n,{}):n[0],o=await this.getASMeta(r),i=e.currentToken??await this.getStoredToken(t,r);if(i?.accessToken&&!this.isExpired(i.expiresAt))return{token:i,issuer:r,asMeta:o,resource:t};if(i?.refreshToken)try{let A=await this.refreshToken(i.refreshToken,t,r,o);return await this.setStoredToken(t,r,A),{token:A,issuer:r,asMeta:o,resource:t}}catch{await this.clearStoredToken(t,r)}let a=this.oauth.redirectUri??"http://localhost:8787/callback",l=this.oauth.clientId?{client_id:this.oauth.clientId,client_secret:this.oauth.clientSecret}:await this.dynamicClientRegistration(o,a),u=await Ni(),c=await Su(u),p=await Ni(),d=this.oauth.scopes?.join(" "),m=`${o.authorization_endpoint}?${Ou({response_type:"code",client_id:l.client_id,redirect_uri:a,scope:d,state:p,code_challenge:c,code_challenge_method:"S256",resource:t})}`;if(!this.oauth.onAuthCode)throw new Error(`Authorization required. Provide oauth.onAuthCode to complete the flow. Navigate to: ${m}`);let{code:g,redirectUri:f}=await this.oauth.onAuthCode(m),h=f??a,x=await this.exchangeCodeForToken({asMeta:o,code:g,codeVerifier:u,client:l,redirectUri:h,resource:t});return await this.setStoredToken(t,r,x),{token:x,issuer:r,asMeta:o,resource:t}}async dynamicClientRegistration(e,t){if(!e.registration_endpoint)throw new Error("Authorization server does not support dynamic client registration and no clientId was provided.");let r={application_type:t.startsWith("http://localhost")?"native":"web",client_name:"Ax MCP Client",redirect_uris:[t],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"},o=await fetch(e.registration_endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok)throw new Error(`Dynamic client registration failed: ${o.status} ${o.statusText}`);let i=await o.json();if(!i.client_id)throw new Error("Dynamic client registration did not return client_id");return i}async exchangeCodeForToken(e){let t=new URLSearchParams;t.set("grant_type","authorization_code"),t.set("code",e.code),t.set("redirect_uri",e.redirectUri),t.set("client_id",e.client.client_id),t.set("code_verifier",e.codeVerifier),t.set("resource",e.resource),e.client.client_secret&&t.set("client_secret",e.client.client_secret);let n=await fetch(e.asMeta.token_endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t.toString()});if(!n.ok)throw new Error(`Token exchange failed: ${n.status} ${n.statusText}`);let r=await n.json();if(!r.access_token)throw new Error("No access_token in token response");let o=r.expires_in?Date.now()+r.expires_in*1e3:void 0;return{accessToken:r.access_token,refreshToken:r.refresh_token,expiresAt:o}}async refreshToken(e,t,n,r){let o=new URLSearchParams;o.set("grant_type","refresh_token"),o.set("refresh_token",e),o.set("resource",t),this.oauth?.clientId&&o.set("client_id",this.oauth.clientId),this.oauth?.clientSecret&&o.set("client_secret",this.oauth.clientSecret);let i=await fetch(r.token_endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString()});if(!i.ok)throw new Error(`Token refresh failed: ${i.status} ${i.statusText}`);let a=await i.json();if(!a.access_token)throw new Error("No access_token in refresh response");let l=a.expires_in?Date.now()+a.expires_in*1e3:void 0;return{accessToken:a.access_token,refreshToken:a.refresh_token??e,expiresAt:l}}};var is=class{mcpEndpoint;sessionId;eventSource;pendingRequests=new Map;messageHandler;customHeaders;oauthHelper;currentToken;currentIssuer;constructor(e,t){this.mcpEndpoint=e,this.customHeaders={...t?.headers??{}},t?.authorization&&(this.customHeaders.Authorization=t.authorization),this.oauthHelper=new Fn(t?.oauth)}setHeaders(e){this.customHeaders={...e}}setAuthorization(e){this.customHeaders.Authorization=e}getHeaders(){return{...this.customHeaders}}buildHeaders(e){let t={...this.customHeaders,...e};return this.sessionId&&(t["Mcp-Session-Id"]=this.sessionId),t}setMessageHandler(e){this.messageHandler=e}async connect(){return Promise.resolve()}async openListeningStream(){return new Promise((e,t)=>{let n=this.buildHeaders({Accept:"text/event-stream"}),r=new URL(this.mcpEndpoint);if(Object.keys(this.customHeaders).length>0){this.openListeningStreamWithFetch(n).then(e).catch(t);return}this.eventSource=new EventSource(r.toString()),this.eventSource.onopen=()=>e(),this.eventSource.onmessage=o=>{try{let i=JSON.parse(o.data);this.messageHandler&&this.messageHandler(i)}catch(i){console.error("Failed to parse SSE message:",i)}},this.eventSource.onerror=()=>t(new Error("Failed to establish SSE connection"))})}async openListeningStreamWithFetch(e){let t=await fetch(this.mcpEndpoint,{method:"GET",headers:e});if(t.status===401){let a=t.headers.get("WWW-Authenticate"),l=await this.oauthHelper.ensureAccessToken({requestedUrl:this.mcpEndpoint,wwwAuthenticate:a,currentToken:null});if(!l)throw new Error("HTTP 401: Unauthorized");return this.customHeaders.Authorization=`Bearer ${l.token.accessToken}`,this.openListeningStreamWithFetch(this.buildHeaders({Accept:"text/event-stream"}))}if(!t.ok)throw new Error(`Failed to open SSE stream: ${t.status} ${t.statusText}`);if(!t.body)throw new Error("No response body available for SSE stream");let n=t.body.getReader(),r=new TextDecoder,o="",i=async()=>{try{let{done:a,value:l}=await n.read();if(a){n.releaseLock();return}o+=r.decode(l,{stream:!0});let u=o.split(`
614
- `);o=u.pop()||"";for(let c of u)if(c.startsWith("data: ")){let p=c.slice(6);if(p==="[DONE]")return;try{let d=JSON.parse(p);this.messageHandler&&this.messageHandler(d)}catch(d){console.error("Failed to parse SSE data:",d)}}await i()}catch(a){throw n.releaseLock(),a}};await i()}async send(e){let t=this.buildHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),n=JSON.stringify(e),r=await fetch(this.mcpEndpoint,{method:"POST",headers:t,body:n});if(r.status===401){let a=r.headers.get("WWW-Authenticate"),l=await this.oauthHelper.ensureAccessToken({requestedUrl:this.mcpEndpoint,wwwAuthenticate:a,currentToken:null});if(!l)throw new Error("HTTP 401: Unauthorized");this.customHeaders.Authorization=`Bearer ${l.token.accessToken}`,r=await fetch(this.mcpEndpoint,{method:"POST",headers:this.buildHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),body:n})}if(!r.ok)throw r.status===404&&this.sessionId?(this.sessionId=void 0,new Error("Session expired. Please reinitialize.")):new Error(`HTTP error ${r.status}: ${r.statusText}`);let o=r.headers.get("Mcp-Session-Id");o&&(this.sessionId=o);let i=r.headers.get("Content-Type");if(i?.includes("text/event-stream"))return this.handleSSEResponse(r,e.id);if(i?.includes("application/json"))return r.json();throw new Error(`Unexpected content type: ${i}`)}async handleSSEResponse(e,t){return new Promise((n,r)=>{let o=e.body?.getReader();if(!o){r(new Error("No response body reader available"));return}let i=new TextDecoder,a="",l=async()=>{try{let{done:u,value:c}=await o.read();if(u){o.releaseLock();return}a+=i.decode(c,{stream:!0});let p=a.split(`
615
- `);a=p.pop()||"";for(let d of p)if(d.startsWith("data: ")){let m=d.slice(6);if(m==="[DONE]")return;try{let g=JSON.parse(m);if("id"in g&&g.id===t){n(g);return}this.messageHandler&&this.messageHandler(g)}catch(g){console.error("Failed to parse SSE data:",g)}}await l()}catch(u){o.releaseLock(),r(u)}};l().catch(r)})}async sendNotification(e){let t=this.buildHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),n=JSON.stringify(e),r=await fetch(this.mcpEndpoint,{method:"POST",headers:t,body:n});if(r.status===401){let o=r.headers.get("WWW-Authenticate"),i=await this.oauthHelper.ensureAccessToken({requestedUrl:this.mcpEndpoint,wwwAuthenticate:o,currentToken:null});if(!i)throw new Error("HTTP 401: Unauthorized");this.customHeaders.Authorization=`Bearer ${i.token.accessToken}`,r=await fetch(this.mcpEndpoint,{method:"POST",headers:this.buildHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),body:n})}if(!r.ok)throw r.status===404&&this.sessionId?(this.sessionId=void 0,new Error("Session expired. Please reinitialize.")):new Error(`HTTP error ${r.status}: ${r.statusText}`);r.status!==202&&console.warn(`Unexpected status for notification: ${r.status}`)}async terminateSession(){if(this.sessionId)try{let e=this.buildHeaders({});(await fetch(this.mcpEndpoint,{method:"DELETE",headers:e})).status===405&&console.info("Server does not support explicit session termination")}catch(e){console.error("Failed to terminate session:",e)}finally{this.sessionId=void 0}}close(){this.eventSource&&(this.eventSource.close(),this.eventSource=void 0)}};var as=class{endpoint=null;sseUrl;eventSource;customHeaders={};oauthHelper;currentToken;currentIssuer;sseAbort;pendingRequests=new Map;messageHandler;endpointReady;constructor(e,t){this.sseUrl=e,this.customHeaders={...t?.headers??{}},t?.authorization&&(this.customHeaders.Authorization=t.authorization),this.oauthHelper=new Fn(t?.oauth)}buildHeaders(e){return{...this.customHeaders,...e}}async openSSEWithFetch(e){let t=new AbortController;this.sseAbort=t;let n=await fetch(this.sseUrl,{method:"GET",headers:e,signal:t.signal});if(n.status===401){let o=n.headers.get("WWW-Authenticate"),i=await this.oauthHelper.ensureAccessToken({requestedUrl:this.sseUrl,wwwAuthenticate:o,currentToken:null});if(!i)throw new Error("HTTP 401: Unauthorized");return this.customHeaders.Authorization=`Bearer ${i.token.accessToken}`,this.openSSEWithFetch(this.buildHeaders({Accept:"text/event-stream"}))}if(!n.ok)throw new Error("Failed to establish SSE connection");let r=this.createEndpointReady();this.consumeSSEStream(n),await r}createEndpointReady(){if(!this.endpointReady){let e,t=new Promise(n=>{e=n});this.endpointReady={resolve:e,promise:t}}return this.endpointReady.promise}async consumeSSEStream(e){if(!e.body)throw new Error("No response body available for SSE stream");let t=e.body.getReader(),n=new TextDecoder,r="",o=null;for(;;){let{done:i,value:a}=await t.read();if(i)break;r+=n.decode(a,{stream:!0});let l=r.split(`
616
- `);r=l.pop()||"";for(let u of l)if(u.startsWith("event: "))o=u.slice(7).trim();else if(u.startsWith("data: ")){let c=u.slice(6);if(o==="endpoint"){let p=c.trim(),d;try{let m=JSON.parse(p);typeof m=="string"?d=m:m&&typeof m=="object"&&"uri"in m&&(d=m.uri)}catch{d=p}if(!d)throw new Error("Endpoint URI missing in SSE event data");/^https?:\/\//i.test(d)||(d=new URL(this.sseUrl).origin+(d.startsWith("/")?d:`/${d}`)),this.endpoint=d,this.endpointReady&&(this.endpointReady.resolve(),this.endpointReady=void 0)}else{let p=c.trim();try{let d=JSON.parse(p);if(d&&typeof d=="object"&&"id"in d){let m=d.id,g=this.pendingRequests.get(m);g?(g.resolve(d),this.pendingRequests.delete(m)):this.messageHandler&&this.messageHandler(d)}else this.messageHandler&&this.messageHandler(d)}catch{}}}else u.trim()===""&&(o=null)}}async connect(){let e=this.buildHeaders({Accept:"text/event-stream"});await this.openSSEWithFetch(e)}async send(e){if(!this.endpoint)throw new Error("HTTPTransport endpoint is not initialized. Call connect() first.");let t=this.buildHeaders({"Content-Type":"application/json"}),n=JSON.stringify(e),r=new Promise((a,l)=>{this.pendingRequests.set(e.id,{resolve:a,reject:l})}),o=await fetch(this.endpoint,{method:"POST",headers:t,body:n});if(o.status===401){let a=o.headers.get("WWW-Authenticate"),l=await this.oauthHelper.ensureAccessToken({requestedUrl:this.sseUrl,wwwAuthenticate:a,currentToken:null});if(!l)throw new Error("HTTP 401: Unauthorized");this.customHeaders.Authorization=`Bearer ${l.token.accessToken}`,o=await fetch(this.endpoint,{method:"POST",headers:this.buildHeaders({"Content-Type":"application/json"}),body:n})}if(!o.ok)throw this.pendingRequests.delete(e.id),new Error(`HTTP error ${o.status}: ${o.statusText}`);if(o.headers.get("Content-Type")?.includes("application/json")){let a=await o.json();return this.pendingRequests.delete(e.id),a}return r}async sendNotification(e){if(!this.endpoint)throw new Error("HTTPTransport endpoint is not initialized. Call connect() first.");let t=this.buildHeaders({"Content-Type":"application/json"}),n=JSON.stringify(e),r=await fetch(this.endpoint,{method:"POST",headers:t,body:n});if(r.status===401){let o=r.headers.get("WWW-Authenticate"),i=await this.oauthHelper.ensureAccessToken({requestedUrl:this.sseUrl,wwwAuthenticate:o,currentToken:null});if(!i)throw new Error("HTTP 401: Unauthorized");this.customHeaders.Authorization=`Bearer ${i.token.accessToken}`,r=await fetch(this.endpoint,{method:"POST",headers:this.buildHeaders({"Content-Type":"application/json"}),body:n})}if(!r.ok)throw new Error(`HTTP error ${r.status}: ${r.statusText}`);r.status!==202&&console.warn(`Unexpected status for notification: ${r.status}`)}close(){this.eventSource&&(this.eventSource.close(),this.eventSource=void 0),this.sseAbort&&(this.sseAbort.abort(),this.sseAbort=void 0)}};function jp(s,e,t,n,r){let o={...s};if(o.parameters){let i=o.parameters.properties?Object.keys(o.parameters.properties):[],l=t.filter(u=>i.includes(u)).filter(u=>u!=="model").filter(u=>!r.excludeFieldsFromPassthrough.includes(u));if(l.length>0){o.parameters=qp(o.parameters,l);let u=o.func;o.func=async(c,p)=>{let d={};if(Array.isArray(e)){let g=e.filter(f=>f.role==="user").pop();g&&(d=Fu(g.values,l))}else d=Fu(e,l);let m={...c,...d};return await u(m,p)}}return o}return n&&!r.disableSmartModelRouting&&r.canConfigureSmartModelRouting&&(o.parameters=_u(o.parameters,n)),o}var Eu=new Error("Agent description must be at least 20 characters (explain in detail what the agent does)"),Pu=new Error("Agent definition is the prompt you give to the LLM for the agent. It must be detailed and at least 100 characters"),wr=class s{ai;program;functions;agents;disableSmartModelRouting;excludeFieldsFromPassthrough;debug;options;name;func;constructor({ai:e,name:t,description:n,definition:r,signature:o,agents:i,functions:a},l){let{disableSmartModelRouting:u,excludeFieldsFromPassthrough:c,debug:p}=l??{};if(this.ai=e,this.agents=i,this.functions=a,this.disableSmartModelRouting=u,this.excludeFieldsFromPassthrough=c??[],this.debug=p,this.options=l,!t||t.length<5)throw new Error("Agent name must be at least 10 characters (more descriptive)");if(!n||n.length<20)throw Eu;if(r&&r.length<100)throw Pu;this.program=new Ce(o,{...l,description:r??n});for(let m of i??[])this.program.register(m);this.name=t,this.func={name:zp(this.name),description:n,parameters:this.program.getSignature().toJSONSchema(),func:()=>this.forward};let d=e?.getModelList();d&&!this.disableSmartModelRouting&&(this.func.parameters=_u(this.func.parameters,d))}static create(e,t){let n=be.create(e),{ai:r,name:o,description:i,definition:a,agents:l,functions:u,...c}=t;return new s({ai:r,name:o,description:i,definition:a,signature:n,agents:l,functions:u},c)}setExamples(e,t){this.program.setExamples(e,t)}setId(e){this.program.setId(e)}setParentId(e){this.program.setParentId(e)}getTraces(){return this.program.getTraces()}setDemos(e){this.program.setDemos(e)}getUsage(){return this.program.getUsage()}resetUsage(){this.program.resetUsage()}getFunction(){let e=this.forward.bind(this),t=async(n,r)=>{let{model:o,...i}=n,a=this.ai??r?.ai;if(!a)throw new Error("AI service is required to run the agent");let l=await e(a,i,{...r,model:o}),c=this.program.getSignature().getOutputFields();return Object.keys(l).map(d=>{let m=c.find(g=>g.name===d);return m?`${m.title}: ${l[d]}`:`${d}: ${l[d]}`}).join(`
617
- `)};return{...this.func,func:t}}getFeatures(){return{canConfigureSmartModelRouting:this.ai===void 0,excludeFieldsFromPassthrough:this.excludeFieldsFromPassthrough}}init(e,t,n){let r=this.ai??e,o=r?.getModelList(),a=this.program.getSignature().getInputFields().map(p=>p.name),l=this.getDebug(r,n),u=this.agents?.map(p=>{let d=p.getFeatures(),m={debug:l,disableSmartModelRouting:!!this.disableSmartModelRouting,excludeFieldsFromPassthrough:d.excludeFieldsFromPassthrough,canConfigureSmartModelRouting:d.canConfigureSmartModelRouting};return jp(p.getFunction(),t,a,o,m)}),c=[...n?.functions??this.functions??[],...u??[]];return{ai:r,functions:c,debug:l}}async forward(e,t,n){let{ai:r,functions:o,debug:i}=this.init(e,t,n),a={...this.options,...n,debug:i,functions:o};return await this.program.forward(r,t,a)}async*streamingForward(e,t,n){let{ai:r,functions:o,debug:i}=this.init(e,t,n),a={...this.options,...n,debug:i,functions:o};return yield*this.program.streamingForward(r,t,a)}setDescription(e){if(!e||e.length<20)throw Eu;this.program.getSignature().setDescription(e),this.func.description=e}setDefinition(e){if(!e||e.length<100)throw Pu;this.program.setDescription(e),this.func.description=e}getSignature(){return this.program.getSignature()}setSignature(e){this.program.setSignature(e)}applyOptimization(e){this.program.applyOptimization?.(e)}getDebug(e,t){return t?.debug??this.debug??e?.getOptions()?.debug??!1}};function zp(s){return s.split(/[^a-zA-Z0-9]/).map((n,r)=>{let o=n.toLowerCase();return r>0&&o&&o[0]?o[0].toUpperCase()+o.slice(1):o}).join("")}function _u(s,e){let t=s?structuredClone(s):{type:"object",properties:{},required:[]};if(t.properties?.model)return t;let n={type:"string",enum:e.map(i=>i.key),description:`The AI model to use for this function call. Available options: ${e.map(i=>`\`${i.key}\` ${i.description}`).join(", ")}`},r={...t.properties??{},model:n},o=[...t.required??[],"model"];return{...t,properties:r,required:o}}function qp(s,e){let t=structuredClone(s);if(t.properties)for(let n of e)delete t.properties[n];if(Array.isArray(t.required)){let n=t.required.filter(r=>!e.includes(r));Object.defineProperty(t,"required",{value:n,writable:!0,configurable:!0})}return t}function Fu(s,e){let t={};for(let n of e)n in s&&(t[n]=s[n]);return t}function $u(s,e){let t=typeof s=="string"?be.create(s):s,{ai:n,name:r,description:o,definition:i,agents:a,functions:l,...u}=e;return new wr({ai:n,name:r,description:o,definition:i,signature:t,agents:a,functions:l},u)}var Nu=(s,e)=>{let t=e?.maxHops??3,n=e?.qualityThreshold??.8,r=e?.maxIterations??2,o=e?.qualityTarget??.85,i=e?.disableQualityHealing??!1;return ts({logger:e?.logger,debug:e?.debug}).node("queryGenerator","originalQuestion:string, previousContext?:string -> searchQuery:string, queryReasoning:string").node("contextualizer","retrievedDocument:string, accumulatedContext?:string -> enhancedContext:string").node("qualityAssessor","currentContext:string, originalQuestion:string -> completenessScore:number, missingAspects:string[]").node("questionDecomposer","complexQuestion:string -> subQuestions:string[], decompositionReason:string").node("evidenceSynthesizer","collectedEvidence:string[], originalQuestion:string -> synthesizedEvidence:string, evidenceGaps:string[]").node("gapAnalyzer","synthesizedEvidence:string, evidenceGaps:string[], originalQuestion:string -> needsMoreInfo:boolean, focusedQueries:string[]").node("answerGenerator","finalContext:string, originalQuestion:string -> comprehensiveAnswer:string, confidenceLevel:number").node("queryRefiner","originalQuestion:string, currentContext:string, missingAspects:string[] -> refinedQuery:string").node("qualityValidator","generatedAnswer:string, userQuery:string -> qualityScore:number, issues:string[]").node("answerHealer","originalAnswer:string, healingDocument:string, issues?:string[] -> healedAnswer:string").map(a=>({...a,maxHops:t,qualityThreshold:n,maxIterations:r,qualityTarget:o,disableQualityHealing:i,currentHop:0,accumulatedContext:"",retrievedContexts:[],completenessScore:0,searchQuery:a.originalQuestion,shouldContinue:!0,iteration:0,allEvidence:[],evidenceSources:[],needsMoreInfo:!0,healingAttempts:0,currentQuality:0,shouldContinueHealing:!0,currentAnswer:"",currentIssues:[]})).while(a=>a.currentHop<a.maxHops&&a.completenessScore<a.qualityThreshold&&a.shouldContinue).map(a=>({...a,currentHop:a.currentHop+1})).execute("queryGenerator",a=>({originalQuestion:a.originalQuestion,previousContext:a.accumulatedContext||void 0})).map(async a=>{let l=a.queryGeneratorResult?.searchQuery||a.searchQuery||a.originalQuestion,u=await s(l);return{...a,retrievalResult:{retrievedDocument:u,retrievalConfidence:.9}}}).execute("contextualizer",a=>({retrievedDocument:a.retrievalResult.retrievedDocument,accumulatedContext:a.accumulatedContext||void 0})).execute("qualityAssessor",a=>({currentContext:a.contextualizerResult.enhancedContext,originalQuestion:a.originalQuestion})).map(a=>({...a,accumulatedContext:a.contextualizerResult.enhancedContext,retrievedContexts:[...a.retrievedContexts,a.retrievalResult.retrievedDocument],completenessScore:a.qualityAssessorResult.completenessScore,searchQuery:a.queryGeneratorResult.searchQuery,shouldContinue:a.qualityAssessorResult.completenessScore<a.qualityThreshold})).branch(a=>a.shouldContinue&&a.currentHop<a.maxHops).when(!0).execute("queryRefiner",a=>({originalQuestion:a.originalQuestion,currentContext:a.accumulatedContext,missingAspects:a.qualityAssessorResult.missingAspects})).map(a=>({...a,searchQuery:a.queryRefinerResult?.refinedQuery||a.searchQuery})).when(!1).map(a=>a).merge().endWhile().map(a=>({...a,allEvidence:a.retrievedContexts.length>0?a.retrievedContexts:[]})).while(a=>a.iteration<a.maxIterations&&a.needsMoreInfo).map(a=>({...a,iteration:a.iteration+1})).branch(a=>a.iteration===1).when(!0).execute("questionDecomposer",a=>({complexQuestion:a.originalQuestion})).map(a=>({...a,currentQueries:a.questionDecomposerResult.subQuestions})).when(!1).map(a=>({...a,currentQueries:a.gapAnalyzerResult?.focusedQueries||[]})).merge().map(async a=>{let l=a.currentQueries||[],u=l.length>0?await Promise.all(l.filter(Boolean).map(c=>s(c))):[];return{...a,retrievalResults:u}}).execute("evidenceSynthesizer",a=>{let l=Array.isArray(a.allEvidence)?a.allEvidence:[],u=Array.isArray(a.retrievalResults)?a.retrievalResults:[],c=[...l,...u].filter(Boolean);return{collectedEvidence:c.length>0?c:["No evidence collected yet"],originalQuestion:a.originalQuestion}}).execute("gapAnalyzer",a=>({synthesizedEvidence:a.evidenceSynthesizerResult.synthesizedEvidence,evidenceGaps:a.evidenceSynthesizerResult.evidenceGaps,originalQuestion:a.originalQuestion})).map(a=>({...a,allEvidence:[...Array.isArray(a.allEvidence)?a.allEvidence:[],...Array.isArray(a.retrievalResults)?a.retrievalResults:[]],evidenceSources:[...Array.isArray(a.evidenceSources)?a.evidenceSources:[],`Iteration ${a.iteration} sources`],needsMoreInfo:a.gapAnalyzerResult.needsMoreInfo,synthesizedEvidence:a.evidenceSynthesizerResult.synthesizedEvidence})).endWhile().execute("answerGenerator",a=>({finalContext:(()=>{let l=(a.accumulatedContext||"").toString().trim();if(l.length>0)return l;let u=(a.synthesizedEvidence||"").toString().trim();if(u.length>0)return u;let p=(Array.isArray(a.allEvidence)?a.allEvidence.filter(Boolean).join(`
618
- `):"").toString().trim();return p.length>0?p:"No context available."})(),originalQuestion:a.originalQuestion})).branch(a=>!a.disableQualityHealing).when(!0).execute("qualityValidator",a=>({generatedAnswer:a.answerGeneratorResult.comprehensiveAnswer,userQuery:a.originalQuestion})).map(a=>({...a,currentAnswer:a.answerGeneratorResult.comprehensiveAnswer,currentQuality:a.qualityValidatorResult.qualityScore,currentIssues:a.qualityValidatorResult.issues,shouldContinueHealing:a.qualityValidatorResult.qualityScore<a.qualityTarget})).while(a=>a.healingAttempts<3&&a.shouldContinueHealing).map(a=>({...a,healingAttempts:a.healingAttempts+1})).map(async a=>{let l=a.currentIssues||[],u=l.length>0?`${a.originalQuestion} addressing issues: ${l.join(", ")}`:`${a.originalQuestion} quality improvement`,c=await s(u);return{...a,healingResult:{healingDocument:c}}}).execute("answerHealer",a=>({originalAnswer:a.currentAnswer,healingDocument:a.healingResult.healingDocument,issues:a.currentIssues})).execute("qualityValidator",a=>({generatedAnswer:a.answerHealerResult.healedAnswer,userQuery:a.originalQuestion})).map(a=>({...a,currentAnswer:a.answerHealerResult.healedAnswer,currentQuality:a.qualityValidatorResult.qualityScore,currentIssues:a.qualityValidatorResult.issues,shouldContinueHealing:a.qualityValidatorResult.qualityScore<a.qualityTarget})).endWhile().when(!1).map(a=>({...a,currentAnswer:a.answerGeneratorResult.comprehensiveAnswer,currentQuality:1,currentIssues:[],shouldContinueHealing:!1})).merge().returns(a=>({finalAnswer:a.currentAnswer,totalHops:a.currentHop,retrievedContexts:a.retrievedContexts,iterationCount:a.iteration,healingAttempts:a.healingAttempts,qualityAchieved:a.currentQuality}))};return Ju(Hp);})();
618
+ `;break;default:r=JSON.stringify(n,null,2)}i(r)}},vu=Tr(),Su=i=>{let e=new Map;return{logger:i,startTiming:t=>{e.set(t,Date.now())},endTiming:t=>{let n=e.get(t);if(!n)return 0;let r=Date.now()-n;return e.delete(t),r},getCurrentTime:()=>Date.now()}};var Pn=class{constructor(e){this.nodeGenerators=e}steps=[];execute(e,t,n){let r=this.nodeGenerators.get(e);if(!r)throw new Error(`Node program for '${e}' not found.`);return this.steps.push(async(o,s)=>{let a=n?.ai??s.mainAi,l=n?.options??s.mainOptions,u=t(o),c=l?.traceLabel?`Node:${e} (${l.traceLabel})`:`Node:${e}`,p;if("forward"in r&&typeof r.forward=="function")p=await r.forward(a,u,{...l,traceLabel:c});else throw new Error(`Node program for '${e}' does not have a forward method`);return{...o,[`${e}Result`]:p}}),this}map(e){return this.steps.push(t=>e(t)),this}async executeSteps(e,t){let n=e;for(let r of this.steps)n=await r(n,t);return n}},ts=class{constructor(e){this.nodeGenerators=e}steps=[];execute(e,t,n){let r=this.nodeGenerators.get(e);if(!r)throw new Error(`Node program for '${e}' not found.`);return this.steps.push(async(o,s)=>{let a=n?.ai??s.mainAi,l=n?.options??s.mainOptions,u=t(o),c=l?.traceLabel?`Node:${e} (${l.traceLabel})`:`Node:${e}`,p;if("forward"in r&&typeof r.forward=="function")p=await r.forward(a,u,{...l,traceLabel:c});else throw new Error(`Node program for '${e}' does not have a forward method`);return{...o,[`${e}Result`]:p}}),this}map(e){return this.steps.push(t=>e(t)),this}async executeSteps(e,t){let n=e;for(let r of this.steps)n=await r(n,t);return n}};var Cr=class i{static _ctorWarned=!1;nodes=new Map;flowDefinition=[];nodeGenerators=new Map;loopStack=[];stepLabels=new Map;branchContext=null;autoParallelConfig;executionPlanner=new kn;program;flowName;nodeUsage=new Map;nodeTraces=new Map;flowLogger;timingLogger;defaultAIOptions;toCamelCase(e){return e.replace(/_([a-z])/g,(t,n)=>n.toUpperCase())}async executeStepsWithLogging(e,t,n,r){let o={...t},s=0;for(let a=0;a<e.length;a++){let l=e[a];if(!l)continue;let u=this.getStepType(l,a),c=this.getStepMetadata(l,a),p=Object.keys(o);this.flowLogger&&this.flowLogger({name:"StepStart",timestamp:Date.now(),stepIndex:a,stepType:u,nodeName:c.nodeName,dependencies:c.dependencies,produces:c.produces,state:{...o}});let d=Date.now();this.timingLogger?.startTiming(`step-${a}`);try{o=await l(o,n),s++;let g=this.timingLogger?.endTiming(`step-${a}`)??Date.now()-d,f=Object.keys(o).filter(A=>!p.includes(A)),x;if(u==="execute"&&c.nodeName&&f.length>0){let A=`${c.nodeName}Result`;x=o[A]}this.flowLogger&&this.flowLogger({name:"StepComplete",timestamp:Date.now(),stepIndex:a,stepType:u,nodeName:c.nodeName,executionTime:g,state:{...o},newFields:f,result:x})}catch(m){throw this.flowLogger&&this.flowLogger({name:"FlowError",timestamp:Date.now(),error:m instanceof Error?m.message:String(m),stepIndex:a,stepType:u,nodeName:c.nodeName,state:{...o}}),m}}return{finalState:o,stepsExecuted:s}}getStepType(e,t){let n=e.toString();return n.includes("nodeName")||n.includes("nodeProgram")?"execute":n.includes("_parallelResults")||n.includes("processBatches")?"parallel":n.includes("branchValue")||n.includes("branches.get")||n.includes("mergeFunction")?"merge":n.includes("transform(")||n.includes("...state,")?"map":n.includes("inputValue")&&n.includes("transformFn")?"derive":n.includes("condition(")&&n.includes("iterations")?n.includes("while")?"while":"feedback":n.includes("branchSteps")||n.includes("currentState")?"branch":"other"}getStepMetadata(e,t){let r=this.executionPlanner.getExecutionPlan().steps.find(a=>a.stepIndex===t);if(r)return{nodeName:r.nodeName,dependencies:r.dependencies,produces:r.produces};let o=e.toString();return{nodeName:this.extractNodeNameFromSource(o),dependencies:[],produces:[]}}extractNodeNameFromSource(e){let t=e.match(/nodeName['"]?\s*[=:]\s*['"](\w+)['"]/);if(t)return t[1];let n=e.match(/nodeProgram\.get\(['"](\w+)['"]\)/);if(n)return n[1]}inferSignatureFromFlow(){let e=this.executionPlanner.getExecutionPlan();if(this.nodeGenerators.size===0&&e.steps.length===0)return ue().input("userInput",ue.string("User input to the flow")).output("flowOutput",ue.string("Output from the flow")).build();let t=new Set,n=new Set;for(let c of e.steps)c.produces.forEach(p=>t.add(p)),c.dependencies.forEach(p=>n.add(p));let r=new Set;for(let c of Array.from(n))t.has(c)||r.add(c);let o=new Set,s=e.steps[e.steps.length-1];if(s&&(s.type==="map"||s.type==="merge")){if(s.produces.forEach(c=>{c.startsWith("_")||o.add(c)}),s.type==="merge"&&s.produces.includes("_mergedResult"))for(let c of e.steps)c.type==="execute"&&c.produces.length>0&&c.produces.forEach(p=>o.add(p))}else for(let c of Array.from(t)){let p=!1;for(let d of e.steps)if(d.dependencies.includes(c)){p=!0;break}if(!p)if(c.endsWith("Result")){let d=c.replace("Result",""),m=this.nodeGenerators.get(d);if(m){let h=m.getSignature().getOutputFields();for(let f of h)o.add(f.name)}else o.add(c)}else o.add(c)}if(r.size===0&&o.size===0){let c=[],p=[];for(let[m,g]of Array.from(this.nodeGenerators)){let h=g.getSignature();for(let f of h.getInputFields()){let x=this.toCamelCase(`${m}_${f.name}`);c.push({name:x,type:f.type,description:f.description,isOptional:f.isOptional,isInternal:f.isInternal})}for(let f of h.getOutputFields()){let x=this.toCamelCase(`${m}_${f.name}`);p.push({name:x,type:f.type,description:f.description,isOptional:f.isOptional,isInternal:f.isInternal})}}let d=new ye;return c.length>0?d.setInputFields(c):d.addInputField({name:"userInput",type:{name:"string"},description:"User input to the flow"}),p.length>0?d.setOutputFields(p):d.addOutputField({name:"flowOutput",type:{name:"string"},description:"Output from the flow"}),d}let a=new ye,l=[];for(let c of Array.from(r))l.push({name:c,type:{name:"string"},description:`Input field: ${c}`});l.length===0&&l.push({name:"userInput",type:{name:"string"},description:"User input to the flow"});let u=[];for(let c of Array.from(o))c.startsWith("_")||u.push({name:c,type:{name:"string"},description:`Output field: ${c}`});return u.length===0&&u.push({name:"flowOutput",type:{name:"string"},description:"Output from the flow"}),a.setInputFields(l),a.setOutputFields(u),a}constructor(e){i._ctorWarned||(console.warn("[AxFlow] new AxFlow() is deprecated. Use flow() factory instead."),i._ctorWarned=!0),this.autoParallelConfig={enabled:e?.autoParallel!==!1,batchSize:e?.batchSize||10},e?.logger?this.flowLogger=e.logger:e?.debug===!0?this.flowLogger=Tr():this.flowLogger=void 0,this.timingLogger=this.flowLogger?Su(this.flowLogger):void 0,(e?.tracer||e?.meter)&&(this.defaultAIOptions={tracer:e.tracer,meter:e.meter})}static create(e){return new i(e)}ensureProgram(){let e=this.inferSignatureFromFlow();if(!this.program){this.program=new Et(e);for(let[t,n]of Array.from(this.nodeGenerators))this.program.register(n);return}this.program.setSignature(e)}setExamples(e,t){this.ensureProgram(),this.program.setExamples(e,t)}setId(e){this.ensureProgram(),this.program.setId(e)}setParentId(e){this.ensureProgram(),this.program.setParentId(e)}getTraces(){let e=[];for(let[t,n]of Array.from(this.nodeTraces))e.push(...n);return e}setDemos(e){this.ensureProgram(),this.program.setDemos(e)}description(e,t){return this.ensureProgram(),this.flowName=e,this.program.setDescription(t),this}toFunction(){this.ensureProgram();let e=this.program.getSignature(),n=(this.flowName??(e.getDescription()?.trim().split(`
619
+ `)[0]||"axFlow")).replace(/\s+/g,"_"),r=this.toCamelCase(n),o=async(s,a)=>{let l=a?.ai;if(!l)throw new Error("AI service is required to run the flow");let u=await this.forward(l,s??{}),c=e.getOutputFields(),p=u??{};return Object.keys(p).map(d=>{let m=c.find(g=>g.name===d);return m&&m.title?`${m.title}: ${p[d]}`:`${d}: ${p[d]}`}).join(`
620
+ `)};return{name:r,description:e.getDescription()??"Execute this AxFlow",parameters:e.toJSONSchema(),func:o}}getUsage(){let e=[];for(let[t,n]of Array.from(this.nodeUsage))e.push(...n);return pr(e)}resetUsage(){this.nodeUsage.clear();for(let[e,t]of Array.from(this.nodeGenerators))t&&"resetUsage"in t&&t.resetUsage()}resetTraces(){this.nodeTraces.clear()}getUsageReport(){let e={};for(let[t,n]of Array.from(this.nodeUsage))e[t]=pr(n);return e}getNodePrograms(){return Array.from(this.nodeGenerators).map(([e,t])=>({name:e,program:t}))}setNodeInstruction(e,t){let n=this.nodeGenerators.get(e);if(!n)return!1;let r=n;if(typeof r.setInstruction=="function")try{return r.setInstruction(t),!0}catch{return!1}return!1}setAllNodeInstructions(e){for(let[t,n]of Object.entries(e))this.setNodeInstruction(t,n)}getTracesReport(){let e={};for(let[t,n]of Array.from(this.nodeTraces))e[t]=n;return e}async*streamingForward(e,t,n){let r=n?.cachingFunction??ee.cachingFunction,o=(()=>{if(!r)return;this.ensureProgram();let a=this.program.getSignature(),l=a.getInputFields().map(d=>d.name),u=Array.isArray(t)?t.filter(d=>d.role==="user").pop().values:t,c=De("sha256");c.update(a.hash()??"");let p=d=>{let m=typeof d;if(c.update(`|${m}|`),d==null){c.update("null");return}if(m==="string"||m==="number"||m==="boolean"){c.update(String(d));return}if(Array.isArray(d)){c.update("[");for(let g of d)p(g);c.update("]");return}if(typeof d=="object"&&d!==null&&"mimeType"in d&&"data"in d){let g=d;c.update(g.mimeType??"");let h=De("sha256").update(g.data??"").digest("hex");c.update(h);return}if(typeof d=="object"){let g=d,h=Object.keys(g).sort();for(let f of h)c.update(`{${f}}`),p(g[f]);return}c.update(String(d))};for(let d of l)p(u?.[d]);return c.digest("hex")})();if(r&&o){let a;try{a=await r(o)}catch{}if(a!==void 0){yield{version:0,index:0,delta:a};return}}let s=await this.forward(e,t,n);if(r&&o)try{await r(o,s)}catch{}yield{version:1,index:0,delta:s}}async forward(e,t,n){let r=n?.cachingFunction??ee.cachingFunction,o=(()=>{if(!r)return;this.ensureProgram();let l=this.program.getSignature(),u=l.getInputFields().map(m=>m.name),c=Array.isArray(t)?t.filter(m=>m.role==="user").pop().values:t,p=De("sha256");p.update(l.hash()??"");let d=m=>{let g=typeof m;if(p.update(`|${g}|`),m==null){p.update("null");return}if(g==="string"||g==="number"||g==="boolean"){p.update(String(m));return}if(Array.isArray(m)){p.update("[");for(let h of m)d(h);p.update("]");return}if(typeof m=="object"&&m!==null&&"mimeType"in m&&"data"in m){let h=m;p.update(h.mimeType??"");let f=De("sha256").update(h.data??"").digest("hex");p.update(f);return}if(typeof m=="object"){let h=m,f=Object.keys(h).sort();for(let x of f)p.update(`{${x}}`),d(h[x]);return}p.update(String(m))};for(let m of u)d(c?.[m]);return p.digest("hex")})();if(r&&o){let l=await r(o);if(l!==void 0)return l}let s=Date.now();this.timingLogger?.startTiming("flow-execution");let a={};try{this.resetUsage(),this.resetTraces();let l;if(Array.isArray(t)){let f=t.filter(x=>x.role==="user").pop();if(!f)throw new Error("No user message found in values array");l=f.values}else l=t;if(this.nodeGenerators.size>0&&this.ensureProgram(),a={...l},this.flowLogger){let f=this.getExecutionPlan();this.flowLogger({name:"FlowStart",timestamp:s,inputFields:Object.keys(l),totalSteps:f.totalSteps,parallelGroups:f.parallelGroups,maxParallelism:f.maxParallelism,autoParallelEnabled:f.autoParallelEnabled})}let u=n?.tracer??this.defaultAIOptions?.tracer,c=n?.traceContext,p,d=c;if(u){let f=this.getExecutionPlan(),x=n?.traceLabel?`AxFlow > ${n.traceLabel}`:"AxFlow";p=u.startSpan(x,{kind:Be.INTERNAL,attributes:{total_steps:f.totalSteps,parallel_groups:f.parallelGroups,max_parallelism:f.maxParallelism,auto_parallel_enabled:f.autoParallelEnabled}});let A=c??vt.active();d=Bn.setSpan(A,p)}let m={mainAi:e,mainOptions:(()=>{let f={...this.defaultAIOptions??{},...n};return n?.model&&(f.model=String(n.model)),u&&(f.tracer=u),d&&(f.traceContext=d),Object.keys(f).length>0?f:void 0})()},g=n?.autoParallel!==!1&&this.autoParallelConfig.enabled,h=0;if(g){this.executionPlanner.setInitialFields(Object.keys(l));let f=this.executionPlanner.createOptimizedExecution(this.autoParallelConfig.batchSize),x=await this.executeStepsWithLogging(f,a,m,!0);a=x.finalState,h=x.stepsExecuted}else{let f=await this.executeStepsWithLogging(this.flowDefinition,a,m,!1);a=f.finalState,h=f.stepsExecuted}if(this.flowLogger){let f=this.timingLogger?.endTiming("flow-execution")??Date.now()-s;this.flowLogger({name:"FlowComplete",timestamp:Date.now(),totalExecutionTime:f,finalState:a,outputFields:Object.keys(a),stepsExecuted:h})}if(p&&p.end(),r&&o)try{await r(o,a)}catch{}return a}catch(l){throw this.flowLogger&&this.flowLogger({name:"FlowError",timestamp:Date.now(),error:l instanceof Error?l.message:String(l),state:a}),typeof parentSpan<"u"&&parentSpan&&parentSpan.end(),l}}node(e,t){if(typeof t=="string"||t instanceof ye){let n=t;if(!n)throw new Error(`Invalid signature for node '${e}': signature cannot be empty`);this.nodes.set(e,{inputs:{},outputs:{}});let r=_e(n);this.nodeGenerators.set(e,r),this.ensureProgram(),this.program.register(r)}else if(typeof t=="function"){this.nodes.set(e,{inputs:{},outputs:{}});let n=new t;this.nodeGenerators.set(e,n),this.ensureProgram(),this.program.register(n)}else if(t&&typeof t=="object"&&"forward"in t){this.nodes.set(e,{inputs:{},outputs:{}});let n=t;this.nodeGenerators.set(e,n),this.ensureProgram(),this.program.register(n)}else throw new Error(`Invalid second argument for node '${e}': expected string, AxSignature, AxProgrammable instance, or constructor function`);return this}n(e,t){return this.node(e,t)}map(e,t){if(t?.parallel){let n=Array.isArray(e)?e:[e],r=async o=>(await On(n,async(l,u)=>{let c=l(o);return Promise.resolve(c)},this.autoParallelConfig.batchSize)).reduce((l,u)=>({...l,...u}),o);if(this.branchContext?.currentBranchValue!==void 0){let o=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];o.push(r),this.branchContext.branches.set(this.branchContext.currentBranchValue,o)}else this.flowDefinition.push(r),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(r,void 0,void 0,"parallel-map",n)}else{let n=async r=>{if(Array.isArray(e))throw new Error("Array of transforms requires parallel: true option");let o=e(r);return Promise.resolve(o)};if(this.branchContext?.currentBranchValue!==void 0){let r=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];r.push(n),this.branchContext.branches.set(this.branchContext.currentBranchValue,r)}else this.flowDefinition.push(n),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(n,void 0,void 0,"map",e)}return this.nodeGenerators.size>0&&this.ensureProgram(),this}m(e,t){return this.map(e,t)}returns(e){let t=async n=>{let r=e(n);return Promise.resolve(r)};if(this.branchContext?.currentBranchValue!==void 0){let n=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];n.push(t),this.branchContext.branches.set(this.branchContext.currentBranchValue,n)}else this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"map",e);return this.nodeGenerators.size>0&&this.ensureProgram(),this}r(e){return this.returns(e)}label(e){if(this.branchContext?.currentBranchValue!==void 0)throw new Error("Cannot create labels inside branch blocks");return this.stepLabels.set(e,this.flowDefinition.length),this}l(e){return this.label(e)}execute(e,t,n){if(!this.nodes.has(e))throw new Error(`Node '${e}' not found. Make sure to define it with .node() first.`);let r=this.nodeGenerators.get(e);if(!r)throw new Error(`Node program for '${e}' not found.`);let o=async(s,a)=>{let l=n?.ai??a.mainAi,u={...a.mainOptions??{},...n?.options??{}},c=t(s),p=u?.traceLabel?`Node:${e} (${u.traceLabel})`:`Node:${e}`,d;if("forward"in r&&typeof r.forward=="function"){if(d=await r.forward(l,c,{...u,traceLabel:p}),"getUsage"in r&&typeof r.getUsage=="function"){let m=r.getUsage();if(m&&m.length>0){let g=this.nodeUsage.get(e)||[];this.nodeUsage.set(e,[...g,...m])}}if("getTraces"in r&&typeof r.getTraces=="function"){let m=r.getTraces();if(m&&m.length>0){let g=this.nodeTraces.get(e)||[];this.nodeTraces.set(e,[...g,...m])}}}else throw new Error(`Node program for '${e}' does not have a forward method`);return{...s,[`${e}Result`]:d}};if(this.branchContext?.currentBranchValue!==void 0){let s=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];s.push(o),this.branchContext.branches.set(this.branchContext.currentBranchValue,s)}else this.flowDefinition.push(o),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(o,e,t);return this.ensureProgram(),this}applyOptimization(e){this.program&&"applyOptimization"in this.program&&this.program.applyOptimization(e);for(let[t,n]of Array.from(this.nodeGenerators))n&&"applyOptimization"in n&&typeof n.applyOptimization=="function"&&n.applyOptimization(e)}e(e,t,n){return this.execute(e,t,n)}branch(e){if(this.branchContext)throw new Error("Nested branches are not supported");return this.branchContext={predicate:t=>e(t),branches:new Map,currentBranchValue:void 0},this}b(e){return this.branch(e)}when(e){if(!this.branchContext)throw new Error("when() called without matching branch()");return this.branchContext.currentBranchValue=e,this.branchContext.branches.set(e,[]),this}w(e){return this.when(e)}merge(){if(!this.branchContext)throw new Error("merge() called without matching branch()");let e=this.branchContext;this.branchContext=null;let t=async(n,r)=>{let o=e.predicate(n),s=e.branches.get(o);if(this.flowLogger&&this.flowLogger({name:"BranchEvaluation",timestamp:Date.now(),branchValue:o,hasMatchingBranch:!!s,branchStepsCount:s?.length??0}),!s)return n;let a=n;for(let l of s)a=await l(a,r);return a};return this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"merge"),this.ensureProgram(),this}mg(){return this.merge()}parallel(e){let t=async(n,r)=>{let o=await On(e,async(s,a)=>{let l=new Pn(this.nodeGenerators);return await s(l).executeSteps(n,r)},this.autoParallelConfig.batchSize);return{...n,_parallelResults:o}};return this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"parallel",void 0,void 0),this.ensureProgram(),{merge:(n,r)=>{let o=s=>{let a=s._parallelResults;if(!Array.isArray(a))throw new Error("No parallel results found for merge");let l=r(...a),u={...s};return delete u._parallelResults,u[n]=l,u};return this.flowDefinition.push(o),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(o,void 0,void 0,"merge",void 0,{resultKey:n,mergeFunction:r}),this.ensureProgram(),this}}}p(e){return this.parallel(e)}feedback(e,t,n=10){if(!this.stepLabels.has(t))throw new Error(`Label '${t}' not found. Make sure to define it with .label() before the feedback point.`);let r=this.stepLabels.get(t),o=this.flowDefinition.length;return this.flowDefinition.push(async(s,a)=>{let l=s,u=1,c=`_feedback_${t}_iterations`;for(typeof l[c]!="number"&&(l={...l,[c]:1});e(l)&&u<n;){u++,l={...l,[c]:u};for(let p=r;p<o;p++){let d=this.flowDefinition[p];d&&(l=await d(l,a))}}return l}),this.nodeGenerators.size>0&&this.ensureProgram(),this}fb(e,t,n=10){return this.feedback(e,t,n)}while(e,t=100){let n=this.flowDefinition.length;this.loopStack.push(n);let r=Object.assign(o=>o,{_condition:e,_maxIterations:t,_isLoopStart:!0});return this.flowDefinition.push(r),this.nodeGenerators.size>0&&this.ensureProgram(),this}wh(e,t=100){return this.while(e,t)}endWhile(){if(this.loopStack.length===0)throw new Error("endWhile() called without matching while()");let e=this.loopStack.pop(),t=this.flowDefinition[e];if(!t||!("_isLoopStart"in t))throw new Error("Loop start step not found or invalid");let n=t._condition,r=t._maxIterations,o=this.flowDefinition.splice(e+1);return this.flowDefinition[e]=async(s,a)=>{let l=s,u=0;for(;n(l)&&u<r;){u++;for(let c of o)l=await c(l,a)}if(u>=r&&n(l))throw new Error(`While loop exceeded maximum iterations (${r}). Consider increasing maxIterations or ensuring the loop condition eventually becomes false.`);return l},this.nodeGenerators.size>0&&this.ensureProgram(),this}end(){return this.endWhile()}derive(e,t,n,r){let o=async s=>{let a=s[t];if(a===void 0)throw new Error(`Input field '${t}' not found in state`);let l;if(Array.isArray(a))if(this.autoParallelConfig.enabled){let u=r?.batchSize||this.autoParallelConfig.batchSize;l=await On(a,async(c,p)=>n(c,p,s),u)}else l=a.map((u,c)=>n(u,c,s));else l=n(a,void 0,s);return{...s,[e]:l}};if(this.branchContext?.currentBranchValue!==void 0){let s=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];s.push(o),this.branchContext.branches.set(this.branchContext.currentBranchValue,s)}else this.flowDefinition.push(o),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(o,void 0,void 0,"derive",n,void 0,{inputFieldName:t,outputFieldName:e,batchSize:r?.batchSize});return this.ensureProgram(),this}getExecutionPlan(){let e=this.executionPlanner.getExecutionPlan();return{totalSteps:e.totalSteps,parallelGroups:e.parallelGroups,maxParallelism:e.maxParallelism,autoParallelEnabled:this.autoParallelConfig.enabled,steps:e.steps,groups:e.groups}}getSignature(){return this.ensureProgram(),this.program.getSignature()}nodeExtended(e,t,n){let o=typeof t=="string"?ye.create(t):t;if(n.prependInputs)for(let s of n.prependInputs)o=o.prependInputField(s.name,s.type);if(n.appendInputs)for(let s of n.appendInputs)o=o.appendInputField(s.name,s.type);if(n.prependOutputs)for(let s of n.prependOutputs)o=o.prependOutputField(s.name,s.type);if(n.appendOutputs)for(let s of n.appendOutputs)o=o.appendOutputField(s.name,s.type);return this.node(e,o)}nx(e,t,n){return this.nodeExtended(e,t,n)}mapOutput(e){let t=async n=>{let r=e(n);return{...n,...r}};if(this.branchContext?.currentBranchValue!==void 0){let n=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];n.push(t),this.branchContext.branches.set(this.branchContext.currentBranchValue,n)}else this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"map",e);return this.nodeGenerators.size>0&&this.ensureProgram(),this}mo(e){return this.mapOutput(e)}};function ns(i){return Cr.create(i)}var rs=class{apiUrl;containerId=null;constructor(e="http://localhost:2375"){this.apiUrl=e}async pullImage(e){let t=await this.fetchDockerAPI(`/images/create?fromImage=${encodeURIComponent(e)}`,{method:"POST"});if(!t.ok)throw new Error(`Failed to pull image: ${t.statusText}`);await t.text()}async createContainer({imageName:e,volumes:t=[],doNotPullImage:n,tag:r}){let o=t.map(u=>`${u.hostPath}:${u.containerPath}`);n||await this.pullImage(e);let s={Image:e,Tty:!0,OpenStdin:!1,AttachStdin:!1,AttachStdout:!1,AttachStderr:!1,HostConfig:{Binds:o},Labels:{}};r&&(s.Labels["com.example.tag"]=r);let a=await this.fetchDockerAPI("/containers/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!a.ok)throw new Error(`Failed to create container: ${a.statusText}`);let l=await a.json();return this.containerId=l.Id,l}async findOrCreateContainer({imageName:e,volumes:t=[],doNotPullImage:n,tag:r}){let s=(await this.listContainers(!0)).filter(l=>l.Labels&&l.Labels["com.example.tag"]===r);if(s&&s.length>0){let l=Math.floor(Math.random()*s.length),u=s[l];if(u)return await this.connectToContainer(u.Id),{Id:u.Id,isNew:!1}}return{Id:(await this.createContainer({imageName:e,volumes:t,doNotPullImage:n,tag:r})).Id,isNew:!0}}async startContainer(){if(!this.containerId)throw new Error("No container created or connected");let e=await this.fetchDockerAPI(`/containers/${this.containerId}/start`,{method:"POST"});if(!e.ok)throw new Error(`Failed to start container: ${e.statusText}`)}async connectToContainer(e){let t=await this.fetchDockerAPI(`/containers/${e}/json`);if(!t.ok)throw new Error(`Failed to connect to container: ${t.statusText}`);this.containerId=e}async stopContainers({tag:e,remove:t,timeout:n=10}){let r=[],o=await this.listContainers(!0),s=e?o.filter(a=>a.Labels["com.example.tag"]===e):o;for(let a of s){if(a.State.Status==="running"){let l=await this.fetchDockerAPI(`/containers/${a.Id}/stop?t=${n}`,{method:"POST"});if(!l.ok){console.warn(`Failed to stop container ${a.Id}: ${l.statusText}`);continue}r.push({Id:a.Id,Action:"stopped"})}if(t){let l=await this.fetchDockerAPI(`/containers/${a.Id}`,{method:"DELETE"});if(!l.ok){console.warn(`Failed to remove container ${a.Id}: ${l.statusText}`);continue}r.push({Id:a.Id,Action:"removed"})}}return r}async listContainers(e=!1){return(await this.fetchDockerAPI(`/containers/json?all=${e}`,{method:"GET"})).json()}async getContainerLogs(){if(!this.containerId)throw new Error("No container created or connected");return(await this.fetchDockerAPI(`/containers/${this.containerId}/logs?stdout=true&stderr=true`,{method:"GET"})).text()}async executeCommand(e){if(!this.containerId)throw new Error("No container created or connected");(await this.getContainerInfo(this.containerId)).State.Status!=="running"&&(await this.startContainer(),await this.waitForContainerToBeRunning(this.containerId));let n=await this.fetchDockerAPI(`/containers/${this.containerId}/exec`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({Cmd:["sh","-c",e],AttachStdout:!0,AttachStderr:!0})});if(!n.ok)throw new Error(`Failed to create exec instance: ${n.statusText}`);let r=await n.json(),o=await this.fetchDockerAPI(`/exec/${r.Id}/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({Detach:!1,Tty:!1})});if(!o.ok)throw new Error(`Failed to start exec instance: ${o.statusText}`);return await o.text()}async getContainerInfo(e){let t=await this.fetchDockerAPI(`/containers/${e}/json`);if(!t.ok)throw new Error(`Failed to get container info: ${t.statusText}`);return t.json()}async waitForContainerToBeRunning(e,t=3e4){let n=Date.now();for(;Date.now()-n<t;){if((await this.getContainerInfo(e)).State.Status==="running")return;await new Promise(o=>setTimeout(o,1e3))}throw new Error("Timeout waiting for container to start")}async fetchDockerAPI(e,t){let n=new URL(e,this.apiUrl).toString();return await fetch(n,t)}toFunction(){return{name:"commandExecution",description:"Use this function to execute shell commands, scripts, and programs. This function enables interaction with the file system, running system utilities, and performing tasks that require a shell interface.",parameters:{type:"object",properties:{command:{type:"string",description:'Shell command to execute. eg. `ls -l` or `echo "Hello, World!"`.'}},required:["command"]},func:async({command:e})=>await this.executeCommand(e)}}};var os=class{aiService;info;func;constructor({ai:e,info:t,func:n}){this.aiService=e,this.info=t,this.func=n}async embedAdapter(e,t){let r=(await this.aiService.embed({texts:[e]},{sessionId:t?.sessionId,abortSignal:t?.abortSignal})).embeddings.at(0);if(!r)throw new Error("Failed to embed text");return this.func.length===2?this.func(r,t):this.func(r)}toFunction(){return{name:this.info.name,description:this.info.description,parameters:{type:"object",properties:{text:{type:"string",description:this.info.argumentDescription}},required:["text"]},func:({text:e},t)=>this.embedAdapter(e,t)}}};var ss=class{constructor(e,t={}){this.transport=e;this.options=t;this.logger=t.logger??(n=>{console.log(typeof n=="string"?n:JSON.stringify(n,null,2))})}functions=[];activeRequests=new Map;capabilities={};logger;async init(){"connect"in this.transport&&await this.transport.connect?.();let{result:e}=await this.sendRequest("initialize",{protocolVersion:"2024-11-05",capabilities:{roots:{listChanged:!0},sampling:{}},clientInfo:{name:"AxMCPClient",version:"1.0.0"}}),t="2024-11-05";if(e.protocolVersion!==t)throw new Error(`Protocol version mismatch. Expected ${t} but got ${e.protocolVersion}`);e.capabilities.tools&&(this.capabilities.tools=!0),e.capabilities.resources&&(this.capabilities.resources=!0),e.capabilities.prompts&&(this.capabilities.prompts=!0),await this.sendNotification("notifications/initialized"),await this.discoverFunctions()}async discoverFunctions(){if(!this.capabilities.tools)throw new Error("Tools are not supported");let{result:e}=await this.sendRequest("tools/list");this.functions=e.tools.map(t=>{let n=this.options.functionOverrides?.find(o=>o.name===t.name),r=t.inputSchema.properties?{properties:t.inputSchema.properties,required:t.inputSchema.required??[],type:t.inputSchema.type}:void 0;return{name:n?.updates.name??t.name,description:n?.updates.description??t.description,parameters:r,func:async o=>{let{result:s}=await this.sendRequest("tools/call",{name:t.name,arguments:o});return s}}})}async ping(e=3e3){let t=this.sendRequest("ping"),n=new Promise((s,a)=>setTimeout(()=>a(new Error("Ping response timeout exceeded")),e)),r=await Promise.race([t,n]),{result:o}=r;if(typeof o!="object"||o===null||Object.keys(o).length!==0)throw new Error(`Unexpected ping response: ${JSON.stringify(o)}`)}toFunction(){return this.functions}cancelRequest(e){if(this.activeRequests.has(e)){this.sendNotification("notifications/cancelled",{requestId:e,reason:"Client cancelled request"});let t=this.activeRequests.get(e);t&&t.reject(new Error(`Request ${e} cancelled`)),this.activeRequests.delete(e)}}async sendRequest(e,t={}){let n=Ee(),r={jsonrpc:"2.0",id:n,method:e,params:t},o=new Promise((a,l)=>{this.activeRequests.set(n,{reject:l}),this.transport.send(r).then(u=>{if(this.activeRequests.delete(n),u!==null&&typeof u=="object"&&"error"in u){let c=u;l(new Error(`RPC Error ${c.error.code}: ${c.error.message}`))}else u!==null&&typeof u=="object"&&"result"in u?a({result:u.result}):l(new Error("Invalid response no result or error"))}).catch(u=>{this.activeRequests.delete(n),l(u)})}),{result:s}=await o;return{id:n,result:s}}async sendNotification(e,t={}){let n={jsonrpc:"2.0",method:e,params:t},{debug:r}=this.options;if(r){let o={name:"Notification",id:"mcp_notification",value:`Sending notification: ${JSON.stringify(n,null,2)}`};this.logger(o)}await this.transport.sendNotification(n)}};function Ou(i){if(typeof Buffer<"u")return Buffer.from(i).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"");let e="";for(let n=0;n<i.length;n++)e+=String.fromCharCode(i[n]);return(typeof btoa=="function"?btoa(e):"").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function ku(i){let t=new TextEncoder().encode(i),n=await Ui().subtle.digest("SHA-256",t);return new Uint8Array(n)}async function Gi(){return Ou(await ku(Ee()+Math.random().toString(36)))}async function Mu(i){return Ou(await ku(i))}async function is(i,e){let t=await fetch(i,{headers:e});if(!t.ok)throw new Error(`HTTP ${t.status} fetching ${i}: ${t.statusText}`);return await t.json()}function Eu(i){let e=new URLSearchParams;for(let[t,n]of Object.entries(i))n!==void 0&&e.set(t,n);return e.toString()}function wr(i){return i.endsWith("/")?i.slice(0,-1):i}function Hp(i){if(!i)return null;let e=i.match(/resource_metadata\s*=\s*"([^"]+)"/i)||i.match(/resource_metadata\s*=\s*([^,\s]+)/i);return e?e[1]:null}async function Pu(i,e){let t=Hp(e);if(t){let a=await is(t),l=wr(new URL(i).toString().split("?")[0]),u=wr(a.resource??"");if(!u||u!==l)throw new Error(`Protected resource metadata 'resource' mismatch. Expected ${l} but got ${u}`);let c=Array.isArray(a.authorization_servers)?a.authorization_servers:[];if(c.length===0)throw new Error("No authorization_servers advertised by protected resource");return{resource:l,issuers:c}}let n=new URL(i),r=n.pathname.replace(/\/+$/,""),o=[];r&&r!=="/"&&o.push({url:`${n.origin}/.well-known/oauth-protected-resource${r}`,expected:`${n.origin}${r}`}),o.push({url:`${n.origin}/.well-known/oauth-protected-resource`,expected:`${n.origin}`});let s;for(let a of o)try{let l=await is(a.url),u=wr(l.resource??""),c=wr(a.expected);if(!u||u!==c)throw new Error(`Protected resource metadata 'resource' mismatch. Expected ${c} but got ${u}`);let p=Array.isArray(l.authorization_servers)?l.authorization_servers:[];if(p.length===0)throw new Error("No authorization_servers advertised by protected resource");return{resource:c,issuers:p}}catch(l){s=l}throw new Error(`Failed to resolve protected resource metadata via well-known endpoints. Last error: ${String(s)}`)}async function Fu(i){let e=new URL(i),t=e.pathname.replace(/^\/+/,""),n=[];t?(n.push(`${e.origin}/.well-known/oauth-authorization-server/${t}`),n.push(`${e.origin}/.well-known/openid-configuration/${t}`),n.push(`${e.origin}/${t.replace(/\/+$/,"")}/.well-known/openid-configuration`)):(n.push(`${e.origin}/.well-known/oauth-authorization-server`),n.push(`${e.origin}/.well-known/openid-configuration`));let r;for(let o of n)try{let s=await is(o);if(!s.authorization_endpoint||!s.token_endpoint)throw new Error("AS metadata missing endpoints");let a=s.code_challenge_methods_supported;if(!a||!a.includes("S256"))throw new Error("Authorization server does not advertise PKCE S256 support");return s}catch(s){r=s}throw new Error(`Failed to discover AS metadata for ${i}: ${String(r)}`)}var Fn=class{constructor(e){this.oauth=e}tokenCache=new Map;asMetaCache=new Map;key(e,t){return`${e}::${t}`}async getStoredToken(e,t){let n=this.key(e,t);if(this.tokenCache.has(n))return this.tokenCache.get(n);let r=await this.oauth?.tokenStore?.getToken?.(n);return r&&this.tokenCache.set(n,r),r??null}async setStoredToken(e,t,n){let r=this.key(e,t);this.tokenCache.set(r,n),await this.oauth?.tokenStore?.setToken?.(r,n)}async clearStoredToken(e,t){let n=this.key(e,t);this.tokenCache.delete(n),await this.oauth?.tokenStore?.clearToken?.(n)}isExpired(e){return e?Date.now()>e-6e4:!1}async getASMeta(e){if(this.asMetaCache.has(e))return this.asMetaCache.get(e);let t=await Fu(e);return this.asMetaCache.set(e,t),t}async ensureAccessToken(e){if(!this.oauth)return null;let{resource:t,issuers:n}=await Pu(e.requestedUrl,e.wwwAuthenticate),r=this.oauth.selectAuthorizationServer?await this.oauth.selectAuthorizationServer(n,{}):n[0],o=await this.getASMeta(r),s=e.currentToken??await this.getStoredToken(t,r);if(s?.accessToken&&!this.isExpired(s.expiresAt))return{token:s,issuer:r,asMeta:o,resource:t};if(s?.refreshToken)try{let A=await this.refreshToken(s.refreshToken,t,r,o);return await this.setStoredToken(t,r,A),{token:A,issuer:r,asMeta:o,resource:t}}catch{await this.clearStoredToken(t,r)}let a=this.oauth.redirectUri??"http://localhost:8787/callback",l=this.oauth.clientId?{client_id:this.oauth.clientId,client_secret:this.oauth.clientSecret}:await this.dynamicClientRegistration(o,a),u=await Gi(),c=await Mu(u),p=await Gi(),d=this.oauth.scopes?.join(" "),m=`${o.authorization_endpoint}?${Eu({response_type:"code",client_id:l.client_id,redirect_uri:a,scope:d,state:p,code_challenge:c,code_challenge_method:"S256",resource:t})}`;if(!this.oauth.onAuthCode)throw new Error(`Authorization required. Provide oauth.onAuthCode to complete the flow. Navigate to: ${m}`);let{code:g,redirectUri:h}=await this.oauth.onAuthCode(m),f=h??a,x=await this.exchangeCodeForToken({asMeta:o,code:g,codeVerifier:u,client:l,redirectUri:f,resource:t});return await this.setStoredToken(t,r,x),{token:x,issuer:r,asMeta:o,resource:t}}async dynamicClientRegistration(e,t){if(!e.registration_endpoint)throw new Error("Authorization server does not support dynamic client registration and no clientId was provided.");let r={application_type:t.startsWith("http://localhost")?"native":"web",client_name:"Ax MCP Client",redirect_uris:[t],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"},o=await fetch(e.registration_endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok)throw new Error(`Dynamic client registration failed: ${o.status} ${o.statusText}`);let s=await o.json();if(!s.client_id)throw new Error("Dynamic client registration did not return client_id");return s}async exchangeCodeForToken(e){let t=new URLSearchParams;t.set("grant_type","authorization_code"),t.set("code",e.code),t.set("redirect_uri",e.redirectUri),t.set("client_id",e.client.client_id),t.set("code_verifier",e.codeVerifier),t.set("resource",e.resource),e.client.client_secret&&t.set("client_secret",e.client.client_secret);let n=await fetch(e.asMeta.token_endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t.toString()});if(!n.ok)throw new Error(`Token exchange failed: ${n.status} ${n.statusText}`);let r=await n.json();if(!r.access_token)throw new Error("No access_token in token response");let o=r.expires_in?Date.now()+r.expires_in*1e3:void 0;return{accessToken:r.access_token,refreshToken:r.refresh_token,expiresAt:o}}async refreshToken(e,t,n,r){let o=new URLSearchParams;o.set("grant_type","refresh_token"),o.set("refresh_token",e),o.set("resource",t),this.oauth?.clientId&&o.set("client_id",this.oauth.clientId),this.oauth?.clientSecret&&o.set("client_secret",this.oauth.clientSecret);let s=await fetch(r.token_endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString()});if(!s.ok)throw new Error(`Token refresh failed: ${s.status} ${s.statusText}`);let a=await s.json();if(!a.access_token)throw new Error("No access_token in refresh response");let l=a.expires_in?Date.now()+a.expires_in*1e3:void 0;return{accessToken:a.access_token,refreshToken:a.refresh_token??e,expiresAt:l}}};var as=class{mcpEndpoint;sessionId;eventSource;pendingRequests=new Map;messageHandler;customHeaders;oauthHelper;currentToken;currentIssuer;constructor(e,t){this.mcpEndpoint=e,this.customHeaders={...t?.headers??{}},t?.authorization&&(this.customHeaders.Authorization=t.authorization),this.oauthHelper=new Fn(t?.oauth)}setHeaders(e){this.customHeaders={...e}}setAuthorization(e){this.customHeaders.Authorization=e}getHeaders(){return{...this.customHeaders}}buildHeaders(e){let t={...this.customHeaders,...e};return this.sessionId&&(t["Mcp-Session-Id"]=this.sessionId),t}setMessageHandler(e){this.messageHandler=e}async connect(){return Promise.resolve()}async openListeningStream(){return new Promise((e,t)=>{let n=this.buildHeaders({Accept:"text/event-stream"}),r=new URL(this.mcpEndpoint);if(Object.keys(this.customHeaders).length>0){this.openListeningStreamWithFetch(n).then(e).catch(t);return}this.eventSource=new EventSource(r.toString()),this.eventSource.onopen=()=>e(),this.eventSource.onmessage=o=>{try{let s=JSON.parse(o.data);this.messageHandler&&this.messageHandler(s)}catch(s){console.error("Failed to parse SSE message:",s)}},this.eventSource.onerror=()=>t(new Error("Failed to establish SSE connection"))})}async openListeningStreamWithFetch(e){let t=await fetch(this.mcpEndpoint,{method:"GET",headers:e});if(t.status===401){let a=t.headers.get("WWW-Authenticate"),l=await this.oauthHelper.ensureAccessToken({requestedUrl:this.mcpEndpoint,wwwAuthenticate:a,currentToken:null});if(!l)throw new Error("HTTP 401: Unauthorized");return this.customHeaders.Authorization=`Bearer ${l.token.accessToken}`,this.openListeningStreamWithFetch(this.buildHeaders({Accept:"text/event-stream"}))}if(!t.ok)throw new Error(`Failed to open SSE stream: ${t.status} ${t.statusText}`);if(!t.body)throw new Error("No response body available for SSE stream");let n=t.body.getReader(),r=new TextDecoder,o="",s=async()=>{try{let{done:a,value:l}=await n.read();if(a){n.releaseLock();return}o+=r.decode(l,{stream:!0});let u=o.split(`
621
+ `);o=u.pop()||"";for(let c of u)if(c.startsWith("data: ")){let p=c.slice(6);if(p==="[DONE]")return;try{let d=JSON.parse(p);this.messageHandler&&this.messageHandler(d)}catch(d){console.error("Failed to parse SSE data:",d)}}await s()}catch(a){throw n.releaseLock(),a}};await s()}async send(e){let t=this.buildHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),n=JSON.stringify(e),r=await fetch(this.mcpEndpoint,{method:"POST",headers:t,body:n});if(r.status===401){let a=r.headers.get("WWW-Authenticate"),l=await this.oauthHelper.ensureAccessToken({requestedUrl:this.mcpEndpoint,wwwAuthenticate:a,currentToken:null});if(!l)throw new Error("HTTP 401: Unauthorized");this.customHeaders.Authorization=`Bearer ${l.token.accessToken}`,r=await fetch(this.mcpEndpoint,{method:"POST",headers:this.buildHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),body:n})}if(!r.ok)throw r.status===404&&this.sessionId?(this.sessionId=void 0,new Error("Session expired. Please reinitialize.")):new Error(`HTTP error ${r.status}: ${r.statusText}`);let o=r.headers.get("Mcp-Session-Id");o&&(this.sessionId=o);let s=r.headers.get("Content-Type");if(s?.includes("text/event-stream"))return this.handleSSEResponse(r,e.id);if(s?.includes("application/json"))return r.json();throw new Error(`Unexpected content type: ${s}`)}async handleSSEResponse(e,t){return new Promise((n,r)=>{let o=e.body?.getReader();if(!o){r(new Error("No response body reader available"));return}let s=new TextDecoder,a="",l=async()=>{try{let{done:u,value:c}=await o.read();if(u){o.releaseLock();return}a+=s.decode(c,{stream:!0});let p=a.split(`
622
+ `);a=p.pop()||"";for(let d of p)if(d.startsWith("data: ")){let m=d.slice(6);if(m==="[DONE]")return;try{let g=JSON.parse(m);if("id"in g&&g.id===t){n(g);return}this.messageHandler&&this.messageHandler(g)}catch(g){console.error("Failed to parse SSE data:",g)}}await l()}catch(u){o.releaseLock(),r(u)}};l().catch(r)})}async sendNotification(e){let t=this.buildHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),n=JSON.stringify(e),r=await fetch(this.mcpEndpoint,{method:"POST",headers:t,body:n});if(r.status===401){let o=r.headers.get("WWW-Authenticate"),s=await this.oauthHelper.ensureAccessToken({requestedUrl:this.mcpEndpoint,wwwAuthenticate:o,currentToken:null});if(!s)throw new Error("HTTP 401: Unauthorized");this.customHeaders.Authorization=`Bearer ${s.token.accessToken}`,r=await fetch(this.mcpEndpoint,{method:"POST",headers:this.buildHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),body:n})}if(!r.ok)throw r.status===404&&this.sessionId?(this.sessionId=void 0,new Error("Session expired. Please reinitialize.")):new Error(`HTTP error ${r.status}: ${r.statusText}`);r.status!==202&&console.warn(`Unexpected status for notification: ${r.status}`)}async terminateSession(){if(this.sessionId)try{let e=this.buildHeaders({});(await fetch(this.mcpEndpoint,{method:"DELETE",headers:e})).status===405&&console.info("Server does not support explicit session termination")}catch(e){console.error("Failed to terminate session:",e)}finally{this.sessionId=void 0}}close(){this.eventSource&&(this.eventSource.close(),this.eventSource=void 0)}};var ls=class{endpoint=null;sseUrl;eventSource;customHeaders={};oauthHelper;currentToken;currentIssuer;sseAbort;pendingRequests=new Map;messageHandler;endpointReady;constructor(e,t){this.sseUrl=e,this.customHeaders={...t?.headers??{}},t?.authorization&&(this.customHeaders.Authorization=t.authorization),this.oauthHelper=new Fn(t?.oauth)}buildHeaders(e){return{...this.customHeaders,...e}}async openSSEWithFetch(e){let t=new AbortController;this.sseAbort=t;let n=await fetch(this.sseUrl,{method:"GET",headers:e,signal:t.signal});if(n.status===401){let o=n.headers.get("WWW-Authenticate"),s=await this.oauthHelper.ensureAccessToken({requestedUrl:this.sseUrl,wwwAuthenticate:o,currentToken:null});if(!s)throw new Error("HTTP 401: Unauthorized");return this.customHeaders.Authorization=`Bearer ${s.token.accessToken}`,this.openSSEWithFetch(this.buildHeaders({Accept:"text/event-stream"}))}if(!n.ok)throw new Error("Failed to establish SSE connection");let r=this.createEndpointReady();this.consumeSSEStream(n),await r}createEndpointReady(){if(!this.endpointReady){let e,t=new Promise(n=>{e=n});this.endpointReady={resolve:e,promise:t}}return this.endpointReady.promise}async consumeSSEStream(e){if(!e.body)throw new Error("No response body available for SSE stream");let t=e.body.getReader(),n=new TextDecoder,r="",o=null;for(;;){let{done:s,value:a}=await t.read();if(s)break;r+=n.decode(a,{stream:!0});let l=r.split(`
623
+ `);r=l.pop()||"";for(let u of l)if(u.startsWith("event: "))o=u.slice(7).trim();else if(u.startsWith("data: ")){let c=u.slice(6);if(o==="endpoint"){let p=c.trim(),d;try{let m=JSON.parse(p);typeof m=="string"?d=m:m&&typeof m=="object"&&"uri"in m&&(d=m.uri)}catch{d=p}if(!d)throw new Error("Endpoint URI missing in SSE event data");/^https?:\/\//i.test(d)||(d=new URL(this.sseUrl).origin+(d.startsWith("/")?d:`/${d}`)),this.endpoint=d,this.endpointReady&&(this.endpointReady.resolve(),this.endpointReady=void 0)}else{let p=c.trim();try{let d=JSON.parse(p);if(d&&typeof d=="object"&&"id"in d){let m=d.id,g=this.pendingRequests.get(m);g?(g.resolve(d),this.pendingRequests.delete(m)):this.messageHandler&&this.messageHandler(d)}else this.messageHandler&&this.messageHandler(d)}catch{}}}else u.trim()===""&&(o=null)}}async connect(){let e=this.buildHeaders({Accept:"text/event-stream"});await this.openSSEWithFetch(e)}async send(e){if(!this.endpoint)throw new Error("HTTPTransport endpoint is not initialized. Call connect() first.");let t=this.buildHeaders({"Content-Type":"application/json"}),n=JSON.stringify(e),r=new Promise((a,l)=>{this.pendingRequests.set(e.id,{resolve:a,reject:l})}),o=await fetch(this.endpoint,{method:"POST",headers:t,body:n});if(o.status===401){let a=o.headers.get("WWW-Authenticate"),l=await this.oauthHelper.ensureAccessToken({requestedUrl:this.sseUrl,wwwAuthenticate:a,currentToken:null});if(!l)throw new Error("HTTP 401: Unauthorized");this.customHeaders.Authorization=`Bearer ${l.token.accessToken}`,o=await fetch(this.endpoint,{method:"POST",headers:this.buildHeaders({"Content-Type":"application/json"}),body:n})}if(!o.ok)throw this.pendingRequests.delete(e.id),new Error(`HTTP error ${o.status}: ${o.statusText}`);if(o.headers.get("Content-Type")?.includes("application/json")){let a=await o.json();return this.pendingRequests.delete(e.id),a}return r}async sendNotification(e){if(!this.endpoint)throw new Error("HTTPTransport endpoint is not initialized. Call connect() first.");let t=this.buildHeaders({"Content-Type":"application/json"}),n=JSON.stringify(e),r=await fetch(this.endpoint,{method:"POST",headers:t,body:n});if(r.status===401){let o=r.headers.get("WWW-Authenticate"),s=await this.oauthHelper.ensureAccessToken({requestedUrl:this.sseUrl,wwwAuthenticate:o,currentToken:null});if(!s)throw new Error("HTTP 401: Unauthorized");this.customHeaders.Authorization=`Bearer ${s.token.accessToken}`,r=await fetch(this.endpoint,{method:"POST",headers:this.buildHeaders({"Content-Type":"application/json"}),body:n})}if(!r.ok)throw new Error(`HTTP error ${r.status}: ${r.statusText}`);r.status!==202&&console.warn(`Unexpected status for notification: ${r.status}`)}close(){this.eventSource&&(this.eventSource.close(),this.eventSource=void 0),this.sseAbort&&(this.sseAbort.abort(),this.sseAbort=void 0)}};function Kp(i,e,t,n,r){let o={...i};if(o.parameters){let s=o.parameters.properties?Object.keys(o.parameters.properties):[],l=t.filter(u=>s.includes(u)).filter(u=>u!=="model").filter(u=>!r.excludeFieldsFromPassthrough.includes(u));if(l.length>0){o.parameters=Wp(o.parameters,l);let u=o.func;o.func=async(c,p)=>{let d={};if(Array.isArray(e)){let g=e.filter(h=>h.role==="user").pop();g&&(d=Nu(g.values,l))}else d=Nu(e,l);let m={...c,...d};return await u(m,p)}}return o}return n&&!r.disableSmartModelRouting&&r.canConfigureSmartModelRouting&&(o.parameters=Du(o.parameters,n)),o}var _u=new Error("Agent description must be at least 20 characters (explain in detail what the agent does)"),$u=new Error("Agent definition is the prompt you give to the LLM for the agent. It must be detailed and at least 100 characters"),Rr=class i{ai;program;functions;agents;disableSmartModelRouting;excludeFieldsFromPassthrough;debug;options;name;func;constructor({ai:e,name:t,description:n,definition:r,signature:o,agents:s,functions:a},l){let{disableSmartModelRouting:u,excludeFieldsFromPassthrough:c,debug:p}=l??{};if(this.ai=e,this.agents=s,this.functions=a,this.disableSmartModelRouting=u,this.excludeFieldsFromPassthrough=c??[],this.debug=p,this.options=l,!t||t.length<5)throw new Error("Agent name must be at least 10 characters (more descriptive)");if(!n||n.length<20)throw _u;if(r&&r.length<100)throw $u;this.program=new Ce(o,{...l,description:r??n});for(let m of s??[])this.program.register(m);this.name=t,this.func={name:Vp(this.name),description:n,parameters:this.program.getSignature().toJSONSchema(),func:()=>this.forward};let d=e?.getModelList();d&&!this.disableSmartModelRouting&&(this.func.parameters=Du(this.func.parameters,d))}static create(e,t){let n=ye.create(e),{ai:r,name:o,description:s,definition:a,agents:l,functions:u,...c}=t;return new i({ai:r,name:o,description:s,definition:a,signature:n,agents:l,functions:u},c)}setExamples(e,t){this.program.setExamples(e,t)}setId(e){this.program.setId(e)}setParentId(e){this.program.setParentId(e)}getTraces(){return this.program.getTraces()}setDemos(e){this.program.setDemos(e)}getUsage(){return this.program.getUsage()}resetUsage(){this.program.resetUsage()}getFunction(){let e=this.forward.bind(this),t=async(n,r)=>{let{model:o,...s}=n,a=this.ai??r?.ai;if(!a)throw new Error("AI service is required to run the agent");let l=await e(a,s,{...r,model:o}),c=this.program.getSignature().getOutputFields();return Object.keys(l).map(d=>{let m=c.find(g=>g.name===d);return m?`${m.title}: ${l[d]}`:`${d}: ${l[d]}`}).join(`
624
+ `)};return{...this.func,func:t}}getFeatures(){return{canConfigureSmartModelRouting:this.ai===void 0,excludeFieldsFromPassthrough:this.excludeFieldsFromPassthrough}}init(e,t,n){let r=this.ai??e,o=r?.getModelList(),a=this.program.getSignature().getInputFields().map(p=>p.name),l=this.getDebug(r,n),u=this.agents?.map(p=>{let d=p.getFeatures(),m={debug:l,disableSmartModelRouting:!!this.disableSmartModelRouting,excludeFieldsFromPassthrough:d.excludeFieldsFromPassthrough,canConfigureSmartModelRouting:d.canConfigureSmartModelRouting};return Kp(p.getFunction(),t,a,o,m)}),c=[...n?.functions??this.functions??[],...u??[]];return{ai:r,functions:c,debug:l}}async forward(e,t,n){let{ai:r,functions:o,debug:s}=this.init(e,t,n),a={...this.options,...n,debug:s,functions:o};return await this.program.forward(r,t,a)}async*streamingForward(e,t,n){let{ai:r,functions:o,debug:s}=this.init(e,t,n),a={...this.options,...n,debug:s,functions:o};return yield*this.program.streamingForward(r,t,a)}setDescription(e){if(!e||e.length<20)throw _u;this.program.getSignature().setDescription(e),this.func.description=e}setDefinition(e){if(!e||e.length<100)throw $u;this.program.setDescription(e),this.func.description=e}getSignature(){return this.program.getSignature()}setSignature(e){this.program.setSignature(e)}applyOptimization(e){this.program.applyOptimization?.(e)}getDebug(e,t){return t?.debug??this.debug??e?.getOptions()?.debug??!1}};function Vp(i){return i.split(/[^a-zA-Z0-9]/).map((n,r)=>{let o=n.toLowerCase();return r>0&&o&&o[0]?o[0].toUpperCase()+o.slice(1):o}).join("")}function Du(i,e){let t=i?structuredClone(i):{type:"object",properties:{},required:[]};if(t.properties?.model)return t;let n={type:"string",enum:e.map(s=>s.key),description:`The AI model to use for this function call. Available options: ${e.map(s=>`\`${s.key}\` ${s.description}`).join(", ")}`},r={...t.properties??{},model:n},o=[...t.required??[],"model"];return{...t,properties:r,required:o}}function Wp(i,e){let t=structuredClone(i);if(t.properties)for(let n of e)delete t.properties[n];if(Array.isArray(t.required)){let n=t.required.filter(r=>!e.includes(r));Object.defineProperty(t,"required",{value:n,writable:!0,configurable:!0})}return t}function Nu(i,e){let t={};for(let n of e)n in i&&(t[n]=i[n]);return t}function Gu(i,e){let t=typeof i=="string"?ye.create(i):i,{ai:n,name:r,description:o,definition:s,agents:a,functions:l,...u}=e;return new Rr({ai:n,name:r,description:o,definition:s,signature:t,agents:a,functions:l},u)}var Lu=(i,e)=>{let t=e?.maxHops??3,n=e?.qualityThreshold??.8,r=e?.maxIterations??2,o=e?.qualityTarget??.85,s=e?.disableQualityHealing??!1;return ns({logger:e?.logger,debug:e?.debug}).node("queryGenerator","originalQuestion:string, previousContext?:string -> searchQuery:string, queryReasoning:string").node("contextualizer","retrievedDocument:string, accumulatedContext?:string -> enhancedContext:string").node("qualityAssessor","currentContext:string, originalQuestion:string -> completenessScore:number, missingAspects:string[]").node("questionDecomposer","complexQuestion:string -> subQuestions:string[], decompositionReason:string").node("evidenceSynthesizer","collectedEvidence:string[], originalQuestion:string -> synthesizedEvidence:string, evidenceGaps:string[]").node("gapAnalyzer","synthesizedEvidence:string, evidenceGaps:string[], originalQuestion:string -> needsMoreInfo:boolean, focusedQueries:string[]").node("answerGenerator","finalContext:string, originalQuestion:string -> comprehensiveAnswer:string, confidenceLevel:number").node("queryRefiner","originalQuestion:string, currentContext:string, missingAspects:string[] -> refinedQuery:string").node("qualityValidator","generatedAnswer:string, userQuery:string -> qualityScore:number, issues:string[]").node("answerHealer","originalAnswer:string, healingDocument:string, issues?:string[] -> healedAnswer:string").map(a=>({...a,maxHops:t,qualityThreshold:n,maxIterations:r,qualityTarget:o,disableQualityHealing:s,currentHop:0,accumulatedContext:"",retrievedContexts:[],completenessScore:0,searchQuery:a.originalQuestion,shouldContinue:!0,iteration:0,allEvidence:[],evidenceSources:[],needsMoreInfo:!0,healingAttempts:0,currentQuality:0,shouldContinueHealing:!0,currentAnswer:"",currentIssues:[]})).while(a=>a.currentHop<a.maxHops&&a.completenessScore<a.qualityThreshold&&a.shouldContinue).map(a=>({...a,currentHop:a.currentHop+1})).execute("queryGenerator",a=>({originalQuestion:a.originalQuestion,previousContext:a.accumulatedContext||void 0})).map(async a=>{let l=a.queryGeneratorResult?.searchQuery||a.searchQuery||a.originalQuestion,u=await i(l);return{...a,retrievalResult:{retrievedDocument:u,retrievalConfidence:.9}}}).execute("contextualizer",a=>({retrievedDocument:a.retrievalResult.retrievedDocument,accumulatedContext:a.accumulatedContext||void 0})).execute("qualityAssessor",a=>({currentContext:a.contextualizerResult.enhancedContext,originalQuestion:a.originalQuestion})).map(a=>({...a,accumulatedContext:a.contextualizerResult.enhancedContext,retrievedContexts:[...a.retrievedContexts,a.retrievalResult.retrievedDocument],completenessScore:a.qualityAssessorResult.completenessScore,searchQuery:a.queryGeneratorResult.searchQuery,shouldContinue:a.qualityAssessorResult.completenessScore<a.qualityThreshold})).branch(a=>a.shouldContinue&&a.currentHop<a.maxHops).when(!0).execute("queryRefiner",a=>({originalQuestion:a.originalQuestion,currentContext:a.accumulatedContext,missingAspects:a.qualityAssessorResult.missingAspects})).map(a=>({...a,searchQuery:a.queryRefinerResult?.refinedQuery||a.searchQuery})).when(!1).map(a=>a).merge().endWhile().map(a=>({...a,allEvidence:a.retrievedContexts.length>0?a.retrievedContexts:[]})).while(a=>a.iteration<a.maxIterations&&a.needsMoreInfo).map(a=>({...a,iteration:a.iteration+1})).branch(a=>a.iteration===1).when(!0).execute("questionDecomposer",a=>({complexQuestion:a.originalQuestion})).map(a=>({...a,currentQueries:a.questionDecomposerResult.subQuestions})).when(!1).map(a=>({...a,currentQueries:a.gapAnalyzerResult?.focusedQueries||[]})).merge().map(async a=>{let l=a.currentQueries||[],u=l.length>0?await Promise.all(l.filter(Boolean).map(c=>i(c))):[];return{...a,retrievalResults:u}}).execute("evidenceSynthesizer",a=>{let l=Array.isArray(a.allEvidence)?a.allEvidence:[],u=Array.isArray(a.retrievalResults)?a.retrievalResults:[],c=[...l,...u].filter(Boolean);return{collectedEvidence:c.length>0?c:["No evidence collected yet"],originalQuestion:a.originalQuestion}}).execute("gapAnalyzer",a=>({synthesizedEvidence:a.evidenceSynthesizerResult.synthesizedEvidence,evidenceGaps:a.evidenceSynthesizerResult.evidenceGaps,originalQuestion:a.originalQuestion})).map(a=>({...a,allEvidence:[...Array.isArray(a.allEvidence)?a.allEvidence:[],...Array.isArray(a.retrievalResults)?a.retrievalResults:[]],evidenceSources:[...Array.isArray(a.evidenceSources)?a.evidenceSources:[],`Iteration ${a.iteration} sources`],needsMoreInfo:a.gapAnalyzerResult.needsMoreInfo,synthesizedEvidence:a.evidenceSynthesizerResult.synthesizedEvidence})).endWhile().execute("answerGenerator",a=>({finalContext:(()=>{let l=(a.accumulatedContext||"").toString().trim();if(l.length>0)return l;let u=(a.synthesizedEvidence||"").toString().trim();if(u.length>0)return u;let p=(Array.isArray(a.allEvidence)?a.allEvidence.filter(Boolean).join(`
625
+ `):"").toString().trim();return p.length>0?p:"No context available."})(),originalQuestion:a.originalQuestion})).branch(a=>!a.disableQualityHealing).when(!0).execute("qualityValidator",a=>({generatedAnswer:a.answerGeneratorResult.comprehensiveAnswer,userQuery:a.originalQuestion})).map(a=>({...a,currentAnswer:a.answerGeneratorResult.comprehensiveAnswer,currentQuality:a.qualityValidatorResult.qualityScore,currentIssues:a.qualityValidatorResult.issues,shouldContinueHealing:a.qualityValidatorResult.qualityScore<a.qualityTarget})).while(a=>a.healingAttempts<3&&a.shouldContinueHealing).map(a=>({...a,healingAttempts:a.healingAttempts+1})).map(async a=>{let l=a.currentIssues||[],u=l.length>0?`${a.originalQuestion} addressing issues: ${l.join(", ")}`:`${a.originalQuestion} quality improvement`,c=await i(u);return{...a,healingResult:{healingDocument:c}}}).execute("answerHealer",a=>({originalAnswer:a.currentAnswer,healingDocument:a.healingResult.healingDocument,issues:a.currentIssues})).execute("qualityValidator",a=>({generatedAnswer:a.answerHealerResult.healedAnswer,userQuery:a.originalQuestion})).map(a=>({...a,currentAnswer:a.answerHealerResult.healedAnswer,currentQuality:a.qualityValidatorResult.qualityScore,currentIssues:a.qualityValidatorResult.issues,shouldContinueHealing:a.qualityValidatorResult.qualityScore<a.qualityTarget})).endWhile().when(!1).map(a=>({...a,currentAnswer:a.answerGeneratorResult.comprehensiveAnswer,currentQuality:1,currentIssues:[],shouldContinueHealing:!1})).merge().returns(a=>({finalAnswer:a.currentAnswer,totalHops:a.currentHop,retrievedContexts:a.retrievedContexts,iterationCount:a.iteration,healingAttempts:a.healingAttempts,qualityAchieved:a.currentQuality}))};return Xu(Jp);})();
619
626
  //# sourceMappingURL=index.global.js.map