@ax-llm/ax 19.0.13 → 19.0.16

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,34 +1,34 @@
1
- "use strict";var ax=(()=>{var Qc=Object.create;var Qr=Object.defineProperty;var Xc=Object.getOwnPropertyDescriptor;var Zc=Object.getOwnPropertyNames;var ep=Object.getPrototypeOf,tp=Object.prototype.hasOwnProperty;var np=(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 Xr=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),rp=(s,e)=>{for(var t in e)Qr(s,t,{get:e[t],enumerable:!0})},ka=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Zc(e))!tp.call(s,r)&&r!==t&&Qr(s,r,{get:()=>e[r],enumerable:!(n=Xc(e,r))||n.enumerable});return s};var nr=(s,e,t)=>(t=s!=null?Qc(ep(s)):{},ka(e||!s||!s.__esModule?Qr(t,"default",{value:s,enumerable:!0}):t,s)),op=s=>ka(Qr({},"__esModule",{value:!0}),s);var Cu=Xr((Ni,$i)=>{"use strict";(function(s,e){typeof Ni=="object"&&typeof $i<"u"?$i.exports=e():typeof define=="function"&&define.amd?define(e):(s=typeof globalThis<"u"?globalThis:s||self).dayjs=e()})(Ni,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(L){var T=["th","st","nd","rd"],M=L%100;return"["+L+(T[(M-20)%10]||T[M]||T[0])+"]"}},y=function(L,T,M){var E=String(L);return!E||E.length>=T?L:""+Array(T+1-E.length).join(M)+L},x={s:y,z:function(L){var T=-L.utcOffset(),M=Math.abs(T),E=Math.floor(M/60),N=M%60;return(T<=0?"+":"-")+y(E,2,"0")+":"+y(N,2,"0")},m:function L(T,M){if(T.date()<M.date())return-L(M,T);var E=12*(M.year()-T.year())+(M.month()-T.month()),N=T.clone().add(E,u),P=M-N<0,_=T.clone().add(E+(P?-1:1),u);return+(-(E+(M-N)/(P?N-_:_-N))||0)},a:function(L){return L<0?Math.ceil(L)||0:Math.floor(L)},p:function(L){return{M:u,y:p,w:l,d:a,D:d,h:i,m:o,s:r,ms:n,Q:c}[L]||String(L||"").toLowerCase().replace(/s$/,"")},u:function(L){return L===void 0}},b="en",R={};R[b]=h;var A="$isDayjsObject",w=function(L){return L instanceof D||!(!L||!L[A])},v=function L(T,M,E){var N;if(!T)return b;if(typeof T=="string"){var P=T.toLowerCase();R[P]&&(N=P),M&&(R[P]=M,N=P);var _=T.split("-");if(!N&&_.length>1)return L(_[0])}else{var G=T.name;R[G]=T,N=G}return!E&&N&&(b=N),N||!E&&b},F=function(L,T){if(w(L))return L.clone();var M=typeof T=="object"?T:{};return M.date=L,M.args=arguments,new D(M)},O=x;O.l=v,O.i=w,O.w=function(L,T){return F(L,{locale:T.$L,utc:T.$u,x:T.$x,$offset:T.$offset})};var D=function(){function L(M){this.$L=v(M.locale,null,!0),this.parse(M),this.$x=this.$x||M.x||{},this[A]=!0}var T=L.prototype;return T.parse=function(M){this.$d=function(E){var N=E.date,P=E.utc;if(N===null)return new Date(NaN);if(O.u(N))return new Date;if(N instanceof Date)return new Date(N);if(typeof N=="string"&&!/Z$/i.test(N)){var _=N.match(g);if(_){var G=_[2]-1||0,$=(_[7]||"0").substring(0,3);return P?new Date(Date.UTC(_[1],G,_[3]||1,_[4]||0,_[5]||0,_[6]||0,$)):new Date(_[1],G,_[3]||1,_[4]||0,_[5]||0,_[6]||0,$)}}return new Date(N)}(M),this.init()},T.init=function(){var M=this.$d;this.$y=M.getFullYear(),this.$M=M.getMonth(),this.$D=M.getDate(),this.$W=M.getDay(),this.$H=M.getHours(),this.$m=M.getMinutes(),this.$s=M.getSeconds(),this.$ms=M.getMilliseconds()},T.$utils=function(){return O},T.isValid=function(){return this.$d.toString()!==m},T.isSame=function(M,E){var N=F(M);return this.startOf(E)<=N&&N<=this.endOf(E)},T.isAfter=function(M,E){return F(M)<this.startOf(E)},T.isBefore=function(M,E){return this.endOf(E)<F(M)},T.$g=function(M,E,N){return O.u(M)?this[E]:this.set(N,M)},T.unix=function(){return Math.floor(this.valueOf()/1e3)},T.valueOf=function(){return this.$d.getTime()},T.startOf=function(M,E){var N=this,P=!!O.u(E)||E,_=O.p(M),G=function(Ce,X){var Ie=O.w(N.$u?Date.UTC(N.$y,X,Ce):new Date(N.$y,X,Ce),N);return P?Ie:Ie.endOf(a)},$=function(Ce,X){return O.w(N.toDate()[Ce].apply(N.toDate("s"),(P?[0,0,0,0]:[23,59,59,999]).slice(X)),N)},W=this.$W,se=this.$M,Y=this.$D,ee="set"+(this.$u?"UTC":"");switch(_){case p:return P?G(1,0):G(31,11);case u:return P?G(1,se):G(0,se+1);case l:var oe=this.$locale().weekStart||0,be=(W<oe?W+7:W)-oe;return G(P?Y-be:Y+(6-be),se);case a:case d:return $(ee+"Hours",0);case i:return $(ee+"Minutes",1);case o:return $(ee+"Seconds",2);case r:return $(ee+"Milliseconds",3);default:return this.clone()}},T.endOf=function(M){return this.startOf(M,!1)},T.$set=function(M,E){var N,P=O.p(M),_="set"+(this.$u?"UTC":""),G=(N={},N[a]=_+"Date",N[d]=_+"Date",N[u]=_+"Month",N[p]=_+"FullYear",N[i]=_+"Hours",N[o]=_+"Minutes",N[r]=_+"Seconds",N[n]=_+"Milliseconds",N)[P],$=P===a?this.$D+(E-this.$W):E;if(P===u||P===p){var W=this.clone().set(d,1);W.$d[G]($),W.init(),this.$d=W.set(d,Math.min(this.$D,W.daysInMonth())).$d}else G&&this.$d[G]($);return this.init(),this},T.set=function(M,E){return this.clone().$set(M,E)},T.get=function(M){return this[O.p(M)]()},T.add=function(M,E){var N,P=this;M=Number(M);var _=O.p(E),G=function(se){var Y=F(P);return O.w(Y.date(Y.date()+Math.round(se*M)),P)};if(_===u)return this.set(u,this.$M+M);if(_===p)return this.set(p,this.$y+M);if(_===a)return G(1);if(_===l)return G(7);var $=(N={},N[o]=e,N[i]=t,N[r]=s,N)[_]||1,W=this.$d.getTime()+M*$;return O.w(W,this)},T.subtract=function(M,E){return this.add(-1*M,E)},T.format=function(M){var E=this,N=this.$locale();if(!this.isValid())return N.invalidDate||m;var P=M||"YYYY-MM-DDTHH:mm:ssZ",_=O.z(this),G=this.$H,$=this.$m,W=this.$M,se=N.weekdays,Y=N.months,ee=N.meridiem,oe=function(X,Ie,re,ue){return X&&(X[Ie]||X(E,P))||re[Ie].slice(0,ue)},be=function(X){return O.s(G%12||12,X,"0")},Ce=ee||function(X,Ie,re){var ue=X<12?"AM":"PM";return re?ue.toLowerCase():ue};return P.replace(f,function(X,Ie){return Ie||function(re){switch(re){case"YY":return String(E.$y).slice(-2);case"YYYY":return O.s(E.$y,4,"0");case"M":return W+1;case"MM":return O.s(W+1,2,"0");case"MMM":return oe(N.monthsShort,W,Y,3);case"MMMM":return oe(Y,W);case"D":return E.$D;case"DD":return O.s(E.$D,2,"0");case"d":return String(E.$W);case"dd":return oe(N.weekdaysMin,E.$W,se,2);case"ddd":return oe(N.weekdaysShort,E.$W,se,3);case"dddd":return se[E.$W];case"H":return String(G);case"HH":return O.s(G,2,"0");case"h":return be(1);case"hh":return be(2);case"a":return Ce(G,$,!0);case"A":return Ce(G,$,!1);case"m":return String($);case"mm":return O.s($,2,"0");case"s":return String(E.$s);case"ss":return O.s(E.$s,2,"0");case"SSS":return O.s(E.$ms,3,"0");case"Z":return _}return null}(X)||_.replace(":","")})},T.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},T.diff=function(M,E,N){var P,_=this,G=O.p(E),$=F(M),W=($.utcOffset()-this.utcOffset())*e,se=this-$,Y=function(){return O.m(_,$)};switch(G){case p:P=Y()/12;break;case u:P=Y();break;case c:P=Y()/3;break;case l:P=(se-W)/6048e5;break;case a:P=(se-W)/864e5;break;case i:P=se/t;break;case o:P=se/e;break;case r:P=se/s;break;default:P=se}return N?P:O.a(P)},T.daysInMonth=function(){return this.endOf(u).$D},T.$locale=function(){return R[this.$L]},T.locale=function(M,E){if(!M)return this.$L;var N=this.clone(),P=v(M,E,!0);return P&&(N.$L=P),N},T.clone=function(){return O.w(this.$d,this)},T.toDate=function(){return new Date(this.valueOf())},T.toJSON=function(){return this.isValid()?this.toISOString():null},T.toISOString=function(){return this.$d.toISOString()},T.toString=function(){return this.$d.toUTCString()},L}(),U=D.prototype;return F.prototype=U,[["$ms",n],["$s",r],["$m",o],["$H",i],["$W",a],["$M",u],["$y",p],["$D",d]].forEach(function(L){U[L[1]]=function(T){return this.$g(T,L[0],L[1])}}),F.extend=function(L,T){return L.$i||(L(T,D,F),L.$i=!0),F},F.locale=v,F.isDayjs=w,F.unix=function(L){return F(1e3*L)},F.en=R[b],F.Ls=R,F.p={},F})});var Tu=Xr((Li,Di)=>{"use strict";(function(s,e){typeof Li=="object"&&typeof Di<"u"?Di.exports=e():typeof define=="function"&&define.amd?define(e):(s=typeof globalThis<"u"?globalThis:s||self).dayjs_plugin_customParseFormat=e()})(Li,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),y=60*h[1]+(+h[2]||0);return y===0?0:h[0]==="+"?-y:y}(g)}],c=function(g){var f=i[g];return f&&(f.indexOf?f:f.s.concat(f.f))},p=function(g,f){var h,y=i.meridiem;if(y){for(var x=1;x<=24;x+=1)if(g.indexOf(y(x,0,f))>-1){h=x>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 y=1;y<=31;y+=1)f(y).replace(/\[|\]/g,"")===g&&(this.day=y)}],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(y){return y.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 y=(g=f.replace(/(\[[^\]]+])|(LTS?|l{1,4}|L{1,4})/g,function(F,O,D){var U=D&&D.toUpperCase();return O||h[D]||s[D]||h[U].replace(/(\[[^\]]+])|(MMMM|MM|DD|dddd)/g,function(L,T,M){return T||M.slice(1)})})).match(e),x=y.length,b=0;b<x;b+=1){var R=y[b],A=d[R],w=A&&A[0],v=A&&A[1];y[b]=v?{regex:w,parser:v}:R.replace(/^\[|\]$/g,"")}return function(F){for(var O={},D=0,U=0;D<x;D+=1){var L=y[D];if(typeof L=="string")U+=L.length;else{var T=L.regex,M=L.parser,E=F.slice(U),N=T.exec(E)[0];M.call(O,N),F=F.replace(N,"")}}return function(P){var _=P.afternoon;if(_!==void 0){var G=P.hours;_?G<12&&(P.hours+=12):G===12&&(P.hours=0),delete P.afternoon}}(O),O}}return function(g,f,h){h.p.customParseFormat=!0,g&&g.parseTwoDigitYear&&(a=g.parseTwoDigitYear);var y=f.prototype,x=y.parse;y.parse=function(b){var R=b.date,A=b.utc,w=b.args;this.$u=A;var v=w[1];if(typeof v=="string"){var F=w[2]===!0,O=w[3]===!0,D=F||O,U=w[2];O&&(U=w[2]),i=this.$locale(),!F&&U&&(i=h.Ls[U]),this.$d=function(E,N,P,_){try{if(["x","X"].indexOf(N)>-1)return new Date((N==="X"?1e3:1)*E);var G=m(N)(E),$=G.year,W=G.month,se=G.day,Y=G.hours,ee=G.minutes,oe=G.seconds,be=G.milliseconds,Ce=G.zone,X=G.week,Ie=new Date,re=se||($||W?1:Ie.getDate()),ue=$||Ie.getFullYear(),Pe=0;$&&!W||(Pe=W>0?W-1:Ie.getMonth());var ae,ve=Y||0,C=ee||0,S=oe||0,k=be||0;return Ce?new Date(Date.UTC(ue,Pe,re,ve,C,S,k+60*Ce.offset*1e3)):P?new Date(Date.UTC(ue,Pe,re,ve,C,S,k)):(ae=new Date(ue,Pe,re,ve,C,S,k),X&&(ae=_(ae).week(X).toDate()),ae)}catch{return new Date("")}}(R,v,A,h),this.init(),U&&U!==!0&&(this.$L=this.locale(U).$L),D&&R!=this.format(v)&&(this.$d=new Date("")),i={}}else if(v instanceof Array)for(var L=v.length,T=1;T<=L;T+=1){w[1]=v[T-1];var M=h.apply(this,w);if(M.isValid()){this.$d=M.$d,this.$L=M.$L,this.init();break}T===L&&(this.$d=new Date(""))}else x.call(this,b)}}})});var wu=Xr((Gi,Ui)=>{"use strict";(function(s,e){typeof Gi=="object"&&typeof Ui<"u"?Ui.exports=e():typeof define=="function"&&define.amd?define(e):(s=typeof globalThis<"u"?globalThis:s||self).dayjs_plugin_timezone=e()})(Gi,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 y=h.timeZoneName||"short",x=f+"|"+y,b=e[x];return b||(b=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:y}),e[x]=b),b}(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,y=f.value,x=s[h];x>=0&&(m[x]=parseInt(y,10))}var b=m[3],R=b===24?0:b,A=m[0]+"-"+m[1]+"-"+m[2]+" "+R+":"+m[4]+":"+m[5]+":000",w=+c;return(r.utc(A).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(),f=g.toLocaleString("en-US",{timeZone:c}),h=Math.round((g-new Date(f))/1e3/60),y=15*-Math.round(g.getTimezoneOffset()/15)-h;if(!Number(y))d=this.utcOffset(0,p);else if(d=r(f,{locale:this.$L}).$set("millisecond",this.$ms).utcOffset(y,!0),p){var x=d.utcOffset();d=d.add(m-x,"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(R,A,w){var v=R-60*A*1e3,F=a(v,w);if(A===F)return[v,A];var O=a(v-=60*(F-A)*1e3,w);return F===O?[v,F]:[R-60*Math.min(F,O)*1e3,Math.max(F,O)]}(r.utc(c,m).valueOf(),f,g),y=h[0],x=h[1],b=r(y).utcOffset(x);return b.$x.$timezone=g,b},r.tz.guess=function(){return Intl.DateTimeFormat().resolvedOptions().timeZone},r.tz.setDefault=function(c){o=c}}})});var Ru=Xr((Bi,ji)=>{"use strict";(function(s,e){typeof Bi=="object"&&typeof ji<"u"?ji.exports=e():typeof define=="function"&&define.amd?define(e):(s=typeof globalThis<"u"?globalThis:s||self).dayjs_plugin_utc=e()})(Bi,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(b){b===void 0&&(b="");var R=b.match(e);if(!R)return null;var A=(""+R[0]).match(t)||["-",0,0],w=A[0],v=60*+A[1]+ +A[2];return v===0?0:w==="+"?v:-v}(m),m===null))return this;var h=Math.abs(m)<=16?60*m:m,y=this;if(g)return y.$offset=h,y.$u=m===0,y;if(m!==0){var x=this.$u?this.toDate().getTimezoneOffset():-1*this.utcOffset();(y=this.local().add(h+x,s)).$offset=h,y.$x.$localOffset=x}else y=this.utc();return y};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(),y=o(m).local();return d.call(h,y,g,f)}}})});var Km={};rp(Km,{AxACE:()=>xs,AxACEOptimizedProgram:()=>zr,AxAI:()=>Sr,AxAIAnthropic:()=>ln,AxAIAnthropicModel:()=>cr,AxAIAnthropicVertexModel:()=>pr,AxAIAzureOpenAI:()=>mn,AxAICohere:()=>gn,AxAICohereEmbedModel:()=>fr,AxAICohereModel:()=>gr,AxAIDeepSeek:()=>fn,AxAIDeepSeekModel:()=>hr,AxAIGoogleGemini:()=>hn,AxAIGoogleGeminiEmbedModel:()=>Io,AxAIGoogleGeminiEmbedTypes:()=>di,AxAIGoogleGeminiModel:()=>xr,AxAIGoogleGeminiSafetyCategory:()=>Co,AxAIGoogleGeminiSafetyThreshold:()=>To,AxAIGrok:()=>kn,AxAIGrokEmbedModels:()=>Ri,AxAIGrokModel:()=>vr,AxAIGroq:()=>An,AxAIGroqModel:()=>Ar,AxAIHuggingFace:()=>yn,AxAIHuggingFaceModel:()=>ko,AxAIMistral:()=>bn,AxAIMistralEmbedModels:()=>xi,AxAIMistralModel:()=>yr,AxAIOllama:()=>In,AxAIOpenAI:()=>dn,AxAIOpenAIBase:()=>Ue,AxAIOpenAIEmbedModel:()=>un,AxAIOpenAIModel:()=>mr,AxAIOpenAIResponses:()=>Tn,AxAIOpenAIResponsesBase:()=>br,AxAIOpenAIResponsesImpl:()=>Cn,AxAIOpenAIResponsesModel:()=>cn,AxAIOpenRouter:()=>wn,AxAIRefusalError:()=>Ne,AxAIReka:()=>Rn,AxAIRekaModel:()=>Cr,AxAIServiceAbortedError:()=>Ge,AxAIServiceAuthenticationError:()=>Mt,AxAIServiceError:()=>Qe,AxAIServiceNetworkError:()=>We,AxAIServiceResponseError:()=>Ot,AxAIServiceStatusError:()=>tt,AxAIServiceStreamTerminatedError:()=>ut,AxAIServiceTimeoutError:()=>at,AxAITogether:()=>vn,AxAITogetherModel:()=>wr,AxAIWebLLM:()=>Sn,AxAIWebLLMModel:()=>Rr,AxAgent:()=>Jr,AxApacheTika:()=>as,AxAssertionError:()=>wt,AxBalancer:()=>ho,AxBaseAI:()=>je,AxBaseOptimizer:()=>st,AxBootstrapFewShot:()=>Vn,AxContentProcessingError:()=>yt,AxDB:()=>Bo,AxDBBase:()=>pt,AxDBCloudflare:()=>On,AxDBManager:()=>jo,AxDBMemory:()=>Lt,AxDBPinecone:()=>Mn,AxDBWeaviate:()=>En,AxDefaultCostTracker:()=>Ur,AxDefaultResultReranker:()=>is,AxDockerSession:()=>Ts,AxEmbeddingAdapter:()=>ws,AxEvalUtil:()=>ac,AxFlow:()=>Kr,AxFlowDependencyAnalyzer:()=>Jn,AxFlowExecutionPlanner:()=>Qn,AxFlowSubContextImpl:()=>er,AxFlowTypedSubContextImpl:()=>Is,AxFluentFieldType:()=>Ke,AxFunctionError:()=>Fr,AxFunctionProcessor:()=>Nr,AxGEPA:()=>Kn,AxGEPAFlow:()=>As,AxGen:()=>$e,AxGenerateError:()=>Dr,AxHFDataLoader:()=>hs,AxInstanceRegistry:()=>Dn,AxJSRuntime:()=>en,AxJSRuntimePermission:()=>ba,AxJudge:()=>zn,AxLLMRequestTypeValues:()=>Js,AxLearn:()=>fs,AxMCPClient:()=>Ss,AxMCPHTTPSSETransport:()=>Ms,AxMCPStreambleHTTPTransport:()=>Os,AxMediaNotSupportedError:()=>ct,AxMemory:()=>Pn,AxMiPRO:()=>bs,AxMockAIService:()=>Eo,AxMultiServiceRouter:()=>Po,AxOptimizedProgramImpl:()=>St,AxProgram:()=>Ut,AxPromptTemplate:()=>Yt,AxProviderRouter:()=>$o,AxRateLimiterTokenUsage:()=>xn,AxSignature:()=>Be,AxSignatureBuilder:()=>$r,AxSimpleClassifier:()=>us,AxSimpleClassifierClass:()=>ls,AxSpanKindValues:()=>Ys,AxStepContextImpl:()=>jn,AxStopFunctionCallException:()=>Wt,AxStringUtil:()=>ss,AxSynth:()=>Wn,AxTestPrompt:()=>cs,AxTokenLimitError:()=>rr,AxTraceLogger:()=>Hn,agent:()=>Kc,ai:()=>nu,ax:()=>Ze,axAIAnthropicDefaultConfig:()=>si,axAIAnthropicVertexDefaultConfig:()=>Ol,axAIAzureOpenAIBestConfig:()=>Fl,axAIAzureOpenAICreativeConfig:()=>El,axAIAzureOpenAIDefaultConfig:()=>ai,axAIAzureOpenAIFastConfig:()=>Pl,axAICohereCreativeConfig:()=>Dl,axAICohereDefaultConfig:()=>ci,axAIDeepSeekCodeConfig:()=>Gl,axAIDeepSeekDefaultConfig:()=>pi,axAIGoogleGeminiDefaultConfig:()=>gi,axAIGoogleGeminiDefaultCreativeConfig:()=>ql,axAIGrokBestConfig:()=>tu,axAIGrokDefaultConfig:()=>Uo,axAIHuggingFaceCreativeConfig:()=>zl,axAIHuggingFaceDefaultConfig:()=>hi,axAIMistralBestConfig:()=>Hl,axAIMistralDefaultConfig:()=>Mo,axAIOllamaDefaultConfig:()=>Ai,axAIOllamaDefaultCreativeConfig:()=>Kl,axAIOpenAIBestConfig:()=>mo,axAIOpenAICreativeConfig:()=>go,axAIOpenAIDefaultConfig:()=>zt,axAIOpenAIFastConfig:()=>fo,axAIOpenAIResponsesBestConfig:()=>Wl,axAIOpenAIResponsesCreativeConfig:()=>Vl,axAIOpenAIResponsesDefaultConfig:()=>Ir,axAIOpenRouterDefaultConfig:()=>bi,axAIRekaBestConfig:()=>Ql,axAIRekaCreativeConfig:()=>Xl,axAIRekaDefaultConfig:()=>Tr,axAIRekaFastConfig:()=>Zl,axAITogetherDefaultConfig:()=>Ci,axAIWebLLMCreativeConfig:()=>eu,axAIWebLLMDefaultConfig:()=>wi,axAnalyzeChatPromptRequirements:()=>Jl,axAnalyzeRequestRequirements:()=>Ht,axBaseAIDefaultConfig:()=>Re,axBaseAIDefaultCreativeConfig:()=>He,axBuildActorDefinition:()=>Ps,axBuildResponderDefinition:()=>Fs,axCheckMetricsHealth:()=>ru,axCreateDefaultColorLogger:()=>Vs,axCreateDefaultOptimizerColorLogger:()=>aa,axCreateDefaultOptimizerTextLogger:()=>cc,axCreateDefaultTextLogger:()=>Xa,axCreateFlowColorLogger:()=>Hr,axCreateFlowTextLogger:()=>Ac,axCreateJSRuntime:()=>Ec,axDefaultFlowLogger:()=>yc,axDefaultMetricsConfig:()=>Oi,axDefaultOptimizerLogger:()=>Gr,axDefaultOptimizerMetricsConfig:()=>la,axGetCompatibilityReport:()=>_l,axGetFormatCompatibility:()=>$l,axGetMetricsConfig:()=>su,axGetOptimizerMetricsConfig:()=>dc,axGetProvidersWithMediaSupport:()=>Nl,axGlobals:()=>fe,axModelInfoAnthropic:()=>dr,axModelInfoCohere:()=>yo,axModelInfoDeepSeek:()=>bo,axModelInfoGoogleGemini:()=>wo,axModelInfoGrok:()=>Go,axModelInfoGroq:()=>vo,axModelInfoHuggingFace:()=>So,axModelInfoMistral:()=>Oo,axModelInfoOpenAI:()=>pn,axModelInfoOpenAIResponses:()=>po,axModelInfoReka:()=>No,axModelInfoTogether:()=>Lo,axModelInfoWebLLM:()=>Do,axProcessContentForProvider:()=>_o,axRAG:()=>Jc,axScoreProvidersForRequest:()=>xo,axSelectOptimalProvider:()=>Ao,axSpanAttributes:()=>xe,axSpanEvents:()=>bt,axUpdateMetricsConfig:()=>ou,axUpdateOptimizerMetricsConfig:()=>pc,axValidateChatRequestMessage:()=>an,axValidateChatResponseResult:()=>co,axValidateProviderCapabilities:()=>li,axWorkerRuntime:()=>Rs,f:()=>ye,flow:()=>Cs,s:()=>mc});function lt({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 Ds=(()=>{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 Ye(){return Ds.randomUUID()}async function sp(s){let e=new TextEncoder,t=typeof s=="string"?e.encode(s):s,n=await Ds.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}var Ls=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 sp(this.data)}};function it(s){if(s!=="sha256")throw new Error("Only SHA-256 algorithm is supported");return new Ls}function Oa(){return Ds}var Zr=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 Mp=Object.create;var Zr=Object.defineProperty;var Ep=Object.getOwnPropertyDescriptor;var Pp=Object.getOwnPropertyNames;var Fp=Object.getPrototypeOf,_p=Object.prototype.hasOwnProperty;var Np=(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 eo=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),$p=(s,e)=>{for(var t in e)Zr(s,t,{get:e[t],enumerable:!0})},Ba=(s,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Pp(e))!_p.call(s,r)&&r!==t&&Zr(s,r,{get:()=>e[r],enumerable:!(n=Ep(e,r))||n.enumerable});return s};var tr=(s,e,t)=>(t=s!=null?Mp(Fp(s)):{},Ba(e||!s||!s.__esModule?Zr(t,"default",{value:s,enumerable:!0}):t,s)),Lp=s=>Ba(Zr({},"__esModule",{value:!0}),s);var Nu=eo((Bi,ji)=>{"use strict";(function(s,e){typeof Bi=="object"&&typeof ji<"u"?ji.exports=e():typeof define=="function"&&define.amd?define(e):(s=typeof globalThis<"u"?globalThis:s||self).dayjs=e()})(Bi,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(L){var w=["th","st","nd","rd"],R=L%100;return"["+L+(w[(R-20)%10]||w[R]||w[0])+"]"}},A=function(L,w,R){var E=String(L);return!E||E.length>=w?L:""+Array(w+1-E.length).join(R)+L},x={s:A,z:function(L){var w=-L.utcOffset(),R=Math.abs(w),E=Math.floor(R/60),_=R%60;return(w<=0?"+":"-")+A(E,2,"0")+":"+A(_,2,"0")},m:function L(w,R){if(w.date()<R.date())return-L(R,w);var E=12*(R.year()-w.year())+(R.month()-w.month()),_=w.clone().add(E,u),M=R-_<0,N=w.clone().add(E+(M?-1:1),u);return+(-(E+(R-_)/(M?_-N:N-_))||0)},a:function(L){return L<0?Math.ceil(L)||0:Math.floor(L)},p:function(L){return{M:u,y:p,w:l,d:a,D:d,h:i,m:o,s:r,ms:n,Q:c}[L]||String(L||"").toLowerCase().replace(/s$/,"")},u:function(L){return L===void 0}},b="en",C={};C[b]=h;var I="$isDayjsObject",v=function(L){return L instanceof $||!(!L||!L[I])},O=function L(w,R,E){var _;if(!w)return b;if(typeof w=="string"){var M=w.toLowerCase();C[M]&&(_=M),R&&(C[M]=R,_=M);var N=w.split("-");if(!_&&N.length>1)return L(N[0])}else{var q=w.name;C[q]=w,_=q}return!E&&_&&(b=_),_||!E&&b},k=function(L,w){if(v(L))return L.clone();var R=typeof w=="object"?w:{};return R.date=L,R.args=arguments,new $(R)},S=x;S.l=O,S.i=v,S.w=function(L,w){return k(L,{locale:w.$L,utc:w.$u,x:w.$x,$offset:w.$offset})};var $=function(){function L(R){this.$L=O(R.locale,null,!0),this.parse(R),this.$x=this.$x||R.x||{},this[I]=!0}var w=L.prototype;return w.parse=function(R){this.$d=function(E){var _=E.date,M=E.utc;if(_===null)return new Date(NaN);if(S.u(_))return new Date;if(_ instanceof Date)return new Date(_);if(typeof _=="string"&&!/Z$/i.test(_)){var N=_.match(g);if(N){var q=N[2]-1||0,U=(N[7]||"0").substring(0,3);return M?new Date(Date.UTC(N[1],q,N[3]||1,N[4]||0,N[5]||0,N[6]||0,U)):new Date(N[1],q,N[3]||1,N[4]||0,N[5]||0,N[6]||0,U)}}return new Date(_)}(R),this.init()},w.init=function(){var R=this.$d;this.$y=R.getFullYear(),this.$M=R.getMonth(),this.$D=R.getDate(),this.$W=R.getDay(),this.$H=R.getHours(),this.$m=R.getMinutes(),this.$s=R.getSeconds(),this.$ms=R.getMilliseconds()},w.$utils=function(){return S},w.isValid=function(){return this.$d.toString()!==m},w.isSame=function(R,E){var _=k(R);return this.startOf(E)<=_&&_<=this.endOf(E)},w.isAfter=function(R,E){return k(R)<this.startOf(E)},w.isBefore=function(R,E){return this.endOf(E)<k(R)},w.$g=function(R,E,_){return S.u(R)?this[E]:this.set(_,R)},w.unix=function(){return Math.floor(this.valueOf()/1e3)},w.valueOf=function(){return this.$d.getTime()},w.startOf=function(R,E){var _=this,M=!!S.u(E)||E,N=S.p(R),q=function(Te,Z){var fe=S.w(_.$u?Date.UTC(_.$y,Z,Te):new Date(_.$y,Z,Te),_);return M?fe:fe.endOf(a)},U=function(Te,Z){return S.w(_.toDate()[Te].apply(_.toDate("s"),(M?[0,0,0,0]:[23,59,59,999]).slice(Z)),_)},W=this.$W,Y=this.$M,Q=this.$D,V="set"+(this.$u?"UTC":"");switch(N){case p:return M?q(1,0):q(31,11);case u:return M?q(1,Y):q(0,Y+1);case l:var te=this.$locale().weekStart||0,ye=(W<te?W+7:W)-te;return q(M?Q-ye:Q+(6-ye),Y);case a:case d:return U(V+"Hours",0);case i:return U(V+"Minutes",1);case o:return U(V+"Seconds",2);case r:return U(V+"Milliseconds",3);default:return this.clone()}},w.endOf=function(R){return this.startOf(R,!1)},w.$set=function(R,E){var _,M=S.p(R),N="set"+(this.$u?"UTC":""),q=(_={},_[a]=N+"Date",_[d]=N+"Date",_[u]=N+"Month",_[p]=N+"FullYear",_[i]=N+"Hours",_[o]=N+"Minutes",_[r]=N+"Seconds",_[n]=N+"Milliseconds",_)[M],U=M===a?this.$D+(E-this.$W):E;if(M===u||M===p){var W=this.clone().set(d,1);W.$d[q](U),W.init(),this.$d=W.set(d,Math.min(this.$D,W.daysInMonth())).$d}else q&&this.$d[q](U);return this.init(),this},w.set=function(R,E){return this.clone().$set(R,E)},w.get=function(R){return this[S.p(R)]()},w.add=function(R,E){var _,M=this;R=Number(R);var N=S.p(E),q=function(Y){var Q=k(M);return S.w(Q.date(Q.date()+Math.round(Y*R)),M)};if(N===u)return this.set(u,this.$M+R);if(N===p)return this.set(p,this.$y+R);if(N===a)return q(1);if(N===l)return q(7);var U=(_={},_[o]=e,_[i]=t,_[r]=s,_)[N]||1,W=this.$d.getTime()+R*U;return S.w(W,this)},w.subtract=function(R,E){return this.add(-1*R,E)},w.format=function(R){var E=this,_=this.$locale();if(!this.isValid())return _.invalidDate||m;var M=R||"YYYY-MM-DDTHH:mm:ssZ",N=S.z(this),q=this.$H,U=this.$m,W=this.$M,Y=_.weekdays,Q=_.months,V=_.meridiem,te=function(Z,fe,Re,re){return Z&&(Z[fe]||Z(E,M))||Re[fe].slice(0,re)},ye=function(Z){return S.s(q%12||12,Z,"0")},Te=V||function(Z,fe,Re){var re=Z<12?"AM":"PM";return Re?re.toLowerCase():re};return M.replace(f,function(Z,fe){return fe||function(Re){switch(Re){case"YY":return String(E.$y).slice(-2);case"YYYY":return S.s(E.$y,4,"0");case"M":return W+1;case"MM":return S.s(W+1,2,"0");case"MMM":return te(_.monthsShort,W,Q,3);case"MMMM":return te(Q,W);case"D":return E.$D;case"DD":return S.s(E.$D,2,"0");case"d":return String(E.$W);case"dd":return te(_.weekdaysMin,E.$W,Y,2);case"ddd":return te(_.weekdaysShort,E.$W,Y,3);case"dddd":return Y[E.$W];case"H":return String(q);case"HH":return S.s(q,2,"0");case"h":return ye(1);case"hh":return ye(2);case"a":return Te(q,U,!0);case"A":return Te(q,U,!1);case"m":return String(U);case"mm":return S.s(U,2,"0");case"s":return String(E.$s);case"ss":return S.s(E.$s,2,"0");case"SSS":return S.s(E.$ms,3,"0");case"Z":return N}return null}(Z)||N.replace(":","")})},w.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},w.diff=function(R,E,_){var M,N=this,q=S.p(E),U=k(R),W=(U.utcOffset()-this.utcOffset())*e,Y=this-U,Q=function(){return S.m(N,U)};switch(q){case p:M=Q()/12;break;case u:M=Q();break;case c:M=Q()/3;break;case l:M=(Y-W)/6048e5;break;case a:M=(Y-W)/864e5;break;case i:M=Y/t;break;case o:M=Y/e;break;case r:M=Y/s;break;default:M=Y}return _?M:S.a(M)},w.daysInMonth=function(){return this.endOf(u).$D},w.$locale=function(){return C[this.$L]},w.locale=function(R,E){if(!R)return this.$L;var _=this.clone(),M=O(R,E,!0);return M&&(_.$L=M),_},w.clone=function(){return S.w(this.$d,this)},w.toDate=function(){return new Date(this.valueOf())},w.toJSON=function(){return this.isValid()?this.toISOString():null},w.toISOString=function(){return this.$d.toISOString()},w.toString=function(){return this.$d.toUTCString()},L}(),G=$.prototype;return k.prototype=G,[["$ms",n],["$s",r],["$m",o],["$H",i],["$W",a],["$M",u],["$y",p],["$D",d]].forEach(function(L){G[L[1]]=function(w){return this.$g(w,L[0],L[1])}}),k.extend=function(L,w){return L.$i||(L(w,$,k),L.$i=!0),k},k.locale=O,k.isDayjs=v,k.unix=function(L){return k(1e3*L)},k.en=C[b],k.Ls=C,k.p={},k})});var $u=eo((qi,zi)=>{"use strict";(function(s,e){typeof qi=="object"&&typeof zi<"u"?zi.exports=e():typeof define=="function"&&define.amd?define(e):(s=typeof globalThis<"u"?globalThis:s||self).dayjs_plugin_customParseFormat=e()})(qi,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),A=60*h[1]+(+h[2]||0);return A===0?0:h[0]==="+"?-A:A}(g)}],c=function(g){var f=i[g];return f&&(f.indexOf?f:f.s.concat(f.f))},p=function(g,f){var h,A=i.meridiem;if(A){for(var x=1;x<=24;x+=1)if(g.indexOf(A(x,0,f))>-1){h=x>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 A=1;A<=31;A+=1)f(A).replace(/\[|\]/g,"")===g&&(this.day=A)}],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(A){return A.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 A=(g=f.replace(/(\[[^\]]+])|(LTS?|l{1,4}|L{1,4})/g,function(k,S,$){var G=$&&$.toUpperCase();return S||h[$]||s[$]||h[G].replace(/(\[[^\]]+])|(MMMM|MM|DD|dddd)/g,function(L,w,R){return w||R.slice(1)})})).match(e),x=A.length,b=0;b<x;b+=1){var C=A[b],I=d[C],v=I&&I[0],O=I&&I[1];A[b]=O?{regex:v,parser:O}:C.replace(/^\[|\]$/g,"")}return function(k){for(var S={},$=0,G=0;$<x;$+=1){var L=A[$];if(typeof L=="string")G+=L.length;else{var w=L.regex,R=L.parser,E=k.slice(G),_=w.exec(E)[0];R.call(S,_),k=k.replace(_,"")}}return function(M){var N=M.afternoon;if(N!==void 0){var q=M.hours;N?q<12&&(M.hours+=12):q===12&&(M.hours=0),delete M.afternoon}}(S),S}}return function(g,f,h){h.p.customParseFormat=!0,g&&g.parseTwoDigitYear&&(a=g.parseTwoDigitYear);var A=f.prototype,x=A.parse;A.parse=function(b){var C=b.date,I=b.utc,v=b.args;this.$u=I;var O=v[1];if(typeof O=="string"){var k=v[2]===!0,S=v[3]===!0,$=k||S,G=v[2];S&&(G=v[2]),i=this.$locale(),!k&&G&&(i=h.Ls[G]),this.$d=function(E,_,M,N){try{if(["x","X"].indexOf(_)>-1)return new Date((_==="X"?1e3:1)*E);var q=m(_)(E),U=q.year,W=q.month,Y=q.day,Q=q.hours,V=q.minutes,te=q.seconds,ye=q.milliseconds,Te=q.zone,Z=q.week,fe=new Date,Re=Y||(U||W?1:fe.getDate()),re=U||fe.getFullYear(),xe=0;U&&!W||(xe=W>0?W-1:fe.getMonth());var le,Ie=Q||0,T=V||0,F=te||0,P=ye||0;return Te?new Date(Date.UTC(re,xe,Re,Ie,T,F,P+60*Te.offset*1e3)):M?new Date(Date.UTC(re,xe,Re,Ie,T,F,P)):(le=new Date(re,xe,Re,Ie,T,F,P),Z&&(le=N(le).week(Z).toDate()),le)}catch{return new Date("")}}(C,O,I,h),this.init(),G&&G!==!0&&(this.$L=this.locale(G).$L),$&&C!=this.format(O)&&(this.$d=new Date("")),i={}}else if(O instanceof Array)for(var L=O.length,w=1;w<=L;w+=1){v[1]=O[w-1];var R=h.apply(this,v);if(R.isValid()){this.$d=R.$d,this.$L=R.$L,this.init();break}w===L&&(this.$d=new Date(""))}else x.call(this,b)}}})});var Lu=eo((Hi,Ki)=>{"use strict";(function(s,e){typeof Hi=="object"&&typeof Ki<"u"?Ki.exports=e():typeof define=="function"&&define.amd?define(e):(s=typeof globalThis<"u"?globalThis:s||self).dayjs_plugin_timezone=e()})(Hi,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 A=h.timeZoneName||"short",x=f+"|"+A,b=e[x];return b||(b=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:A}),e[x]=b),b}(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,A=f.value,x=s[h];x>=0&&(m[x]=parseInt(A,10))}var b=m[3],C=b===24?0:b,I=m[0]+"-"+m[1]+"-"+m[2]+" "+C+":"+m[4]+":"+m[5]+":000",v=+c;return(r.utc(I).valueOf()-(v-=v%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),A=15*-Math.round(g.getTimezoneOffset()/15)-h;if(!Number(A))d=this.utcOffset(0,p);else if(d=r(f,{locale:this.$L}).$set("millisecond",this.$ms).utcOffset(A,!0),p){var x=d.utcOffset();d=d.add(m-x,"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(C,I,v){var O=C-60*I*1e3,k=a(O,v);if(I===k)return[O,I];var S=a(O-=60*(k-I)*1e3,v);return k===S?[O,k]:[C-60*Math.min(k,S)*1e3,Math.max(k,S)]}(r.utc(c,m).valueOf(),f,g),A=h[0],x=h[1],b=r(A).utcOffset(x);return b.$x.$timezone=g,b},r.tz.guess=function(){return Intl.DateTimeFormat().resolvedOptions().timeZone},r.tz.setDefault=function(c){o=c}}})});var Du=eo((Wi,Vi)=>{"use strict";(function(s,e){typeof Wi=="object"&&typeof Vi<"u"?Vi.exports=e():typeof define=="function"&&define.amd?define(e):(s=typeof globalThis<"u"?globalThis:s||self).dayjs_plugin_utc=e()})(Wi,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(b){b===void 0&&(b="");var C=b.match(e);if(!C)return null;var I=(""+C[0]).match(t)||["-",0,0],v=I[0],O=60*+I[1]+ +I[2];return O===0?0:v==="+"?O:-O}(m),m===null))return this;var h=Math.abs(m)<=16?60*m:m,A=this;if(g)return A.$offset=h,A.$u=m===0,A;if(m!==0){var x=this.$u?this.toDate().getTimezoneOffset():-1*this.utcOffset();(A=this.local().add(h+x,s)).$offset=h,A.$x.$localOffset=x}else A=this.utc();return A};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(),A=o(m).local();return d.call(h,A,g,f)}}})});var $g={};$p($g,{AxACE:()=>bs,AxACEOptimizedProgram:()=>qr,AxAI:()=>vr,AxAIAnthropic:()=>rn,AxAIAnthropicModel:()=>ur,AxAIAnthropicVertexModel:()=>cr,AxAIAzureOpenAI:()=>un,AxAICohere:()=>cn,AxAICohereEmbedModel:()=>gr,AxAICohereModel:()=>mr,AxAIDeepSeek:()=>pn,AxAIDeepSeekModel:()=>fr,AxAIGoogleGemini:()=>dn,AxAIGoogleGeminiEmbedModel:()=>To,AxAIGoogleGeminiEmbedTypes:()=>Ai,AxAIGoogleGeminiModel:()=>hr,AxAIGoogleGeminiSafetyCategory:()=>wo,AxAIGoogleGeminiSafetyThreshold:()=>Ro,AxAIGrok:()=>wn,AxAIGrokEmbedModels:()=>Ei,AxAIGrokModel:()=>Rr,AxAIGroq:()=>gn,AxAIGroqModel:()=>xr,AxAIHuggingFace:()=>fn,AxAIHuggingFaceModel:()=>Mo,AxAIMistral:()=>hn,AxAIMistralEmbedModels:()=>Ti,AxAIMistralModel:()=>Ar,AxAIOllama:()=>xn,AxAIOpenAI:()=>ln,AxAIOpenAIBase:()=>Fe,AxAIOpenAIEmbedModel:()=>on,AxAIOpenAIModel:()=>dr,AxAIOpenAIResponses:()=>yn,AxAIOpenAIResponsesBase:()=>yr,AxAIOpenAIResponsesImpl:()=>An,AxAIOpenAIResponsesModel:()=>sn,AxAIOpenRouter:()=>bn,AxAIRefusalError:()=>Se,AxAIReka:()=>In,AxAIRekaModel:()=>Ir,AxAIServiceAbortedError:()=>Pe,AxAIServiceAuthenticationError:()=>wt,AxAIServiceError:()=>Ue,AxAIServiceNetworkError:()=>Le,AxAIServiceResponseError:()=>Tt,AxAIServiceStatusError:()=>ze,AxAIServiceStreamTerminatedError:()=>nt,AxAIServiceTimeoutError:()=>et,AxAITogether:()=>Cn,AxAITogetherModel:()=>Tr,AxAIWebLLM:()=>Tn,AxAIWebLLMModel:()=>wr,AxAgent:()=>Jr,AxApacheTika:()=>cs,AxAssertionError:()=>xt,AxBalancer:()=>Ao,AxBaseAI:()=>_e,AxBaseOptimizer:()=>Je,AxBootstrapFewShot:()=>qn,AxContentProcessingError:()=>pt,AxDB:()=>qo,AxDBBase:()=>ot,AxDBCloudflare:()=>Rn,AxDBManager:()=>zo,AxDBMemory:()=>_t,AxDBPinecone:()=>vn,AxDBWeaviate:()=>Sn,AxDefaultCostTracker:()=>Gr,AxDefaultResultReranker:()=>us,AxDockerSession:()=>vs,AxEmbeddingAdapter:()=>Ss,AxEvalUtil:()=>Cc,AxFlow:()=>Hr,AxFlowDependencyAnalyzer:()=>zn,AxFlowExecutionPlanner:()=>Kn,AxFlowSubContextImpl:()=>Jn,AxFlowTypedSubContextImpl:()=>ws,AxFluentFieldType:()=>$e,AxFunctionError:()=>Pr,AxFunctionProcessor:()=>_r,AxGEPA:()=>Bn,AxGEPAFlow:()=>Is,AxGen:()=>ke,AxGenerateError:()=>Lr,AxHFDataLoader:()=>ys,AxInstanceRegistry:()=>Fn,AxJSRuntime:()=>Qt,AxJSRuntimePermission:()=>Oa,AxJudge:()=>Gn,AxLLMRequestTypeValues:()=>ti,AxLearn:()=>As,AxMCPClient:()=>Ps,AxMCPHTTPSSETransport:()=>Ns,AxMCPStreambleHTTPTransport:()=>_s,AxMediaNotSupportedError:()=>rt,AxMemory:()=>kn,AxMiPRO:()=>Ts,AxMockAIService:()=>Fo,AxMultiServiceRouter:()=>_o,AxOptimizedProgramImpl:()=>bt,AxProgram:()=>Dt,AxPromptTemplate:()=>Wt,AxProviderRouter:()=>Do,AxRateLimiterTokenUsage:()=>mn,AxSignature:()=>Me,AxSignatureBuilder:()=>Nr,AxSimpleClassifier:()=>ds,AxSimpleClassifierClass:()=>ps,AxSpanKindValues:()=>ni,AxStepContextImpl:()=>Ln,AxStopFunctionCallException:()=>zt,AxStringUtil:()=>ls,AxSynth:()=>jn,AxTestPrompt:()=>ms,AxTokenLimitError:()=>nr,AxTraceLogger:()=>Un,agent:()=>bp,ai:()=>fu,ax:()=>je,axAIAnthropicDefaultConfig:()=>pi,axAIAnthropicVertexDefaultConfig:()=>jl,axAIAzureOpenAIBestConfig:()=>Kl,axAIAzureOpenAICreativeConfig:()=>zl,axAIAzureOpenAIDefaultConfig:()=>mi,axAIAzureOpenAIFastConfig:()=>Hl,axAICohereCreativeConfig:()=>Ql,axAICohereDefaultConfig:()=>hi,axAIDeepSeekCodeConfig:()=>Xl,axAIDeepSeekDefaultConfig:()=>xi,axAIGoogleGeminiDefaultConfig:()=>bi,axAIGoogleGeminiDefaultCreativeConfig:()=>nu,axAIGrokBestConfig:()=>gu,axAIGrokDefaultConfig:()=>jo,axAIHuggingFaceCreativeConfig:()=>ru,axAIHuggingFaceDefaultConfig:()=>Ci,axAIMistralBestConfig:()=>ou,axAIMistralDefaultConfig:()=>Po,axAIOllamaDefaultConfig:()=>wi,axAIOllamaDefaultCreativeConfig:()=>su,axAIOpenAIBestConfig:()=>fo,axAIOpenAICreativeConfig:()=>ho,axAIOpenAIDefaultConfig:()=>Bt,axAIOpenAIFastConfig:()=>xo,axAIOpenAIResponsesBestConfig:()=>iu,axAIOpenAIResponsesCreativeConfig:()=>au,axAIOpenAIResponsesDefaultConfig:()=>br,axAIOpenRouterDefaultConfig:()=>vi,axAIRekaBestConfig:()=>cu,axAIRekaCreativeConfig:()=>pu,axAIRekaDefaultConfig:()=>Cr,axAIRekaFastConfig:()=>du,axAITogetherDefaultConfig:()=>ki,axAIWebLLMCreativeConfig:()=>mu,axAIWebLLMDefaultConfig:()=>Mi,axAnalyzeChatPromptRequirements:()=>lu,axAnalyzeRequestRequirements:()=>jt,axBaseAIDefaultConfig:()=>be,axBaseAIDefaultCreativeConfig:()=>Ne,axBuildActorDefinition:()=>$s,axBuildResponderDefinition:()=>Ls,axCheckMetricsHealth:()=>hu,axCreateDefaultColorLogger:()=>ei,axCreateDefaultOptimizerColorLogger:()=>ga,axCreateDefaultOptimizerTextLogger:()=>Rc,axCreateDefaultTextLogger:()=>pl,axCreateFlowColorLogger:()=>zr,axCreateFlowTextLogger:()=>Fc,axCreateJSRuntime:()=>Kc,axDefaultFlowLogger:()=>_c,axDefaultMetricsConfig:()=>Ni,axDefaultOptimizerLogger:()=>Dr,axDefaultOptimizerMetricsConfig:()=>fa,axGetCompatibilityReport:()=>Wl,axGetFormatCompatibility:()=>Jl,axGetMetricsConfig:()=>Au,axGetOptimizerMetricsConfig:()=>Sc,axGetProvidersWithMediaSupport:()=>Vl,axGlobals:()=>ce,axModelInfoAnthropic:()=>pr,axModelInfoCohere:()=>Io,axModelInfoDeepSeek:()=>Co,axModelInfoGoogleGemini:()=>vo,axModelInfoGrok:()=>Bo,axModelInfoGroq:()=>ko,axModelInfoHuggingFace:()=>Oo,axModelInfoMistral:()=>Eo,axModelInfoOpenAI:()=>an,axModelInfoOpenAIResponses:()=>go,axModelInfoReka:()=>Lo,axModelInfoTogether:()=>Go,axModelInfoWebLLM:()=>Uo,axProcessContentForProvider:()=>$o,axRAG:()=>wp,axScoreProvidersForRequest:()=>yo,axSelectOptimalProvider:()=>bo,axSpanAttributes:()=>ge,axSpanEvents:()=>dt,axUpdateMetricsConfig:()=>xu,axUpdateOptimizerMetricsConfig:()=>vc,axValidateChatRequestMessage:()=>nn,axValidateChatResponseResult:()=>mo,axValidateProviderCapabilities:()=>gi,axWorkerRuntime:()=>Ms,f:()=>he,flow:()=>Rs,fn:()=>ac,s:()=>kc});function tt({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 zs=(()=>{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 Ge(){return zs.randomUUID()}async function Dp(s){let e=new TextEncoder,t=typeof s=="string"?e.encode(s):s,n=await zs.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}var qs=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 Dp(this.data)}};function Ze(s){if(s!=="sha256")throw new Error("Only SHA-256 algorithm is supported");return new qs}function ja(){return zs}var to=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 Gs=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)}},eo=class extends TransformStream{constructor(){super(new Gs)}};var ip={maxRetries:3,initialDelayMs:1e3,maxDelayMs:6e4,backoffFactor:2,retryableStatusCodes:[500,408,429,502,503,504]},ap=globalThis.TextDecoderStream??eo,Qe=class extends Error{constructor(t,n,r,o,i={},a=!0){super(t);this.url=n;this.requestBody=r;this.responseBody=o;this.name="AxAIServiceError",this.timestamp=new Date().toISOString(),this.errorId=Ye(),this.context=i,this.includeRequestBodyInErrors=a,this.stack=this.toString()}timestamp;errorId;context;includeRequestBodyInErrors;toString(){let t=[`${this.name}: ${this.message}`,`URL: ${this.url}`];return this.includeRequestBodyInErrors&&t.push(`Request Body: ${JSON.stringify(this.requestBody,null,2)}`),t.push(`Response Body: ${JSON.stringify(this.responseBody,null,2)}`,`Context: ${JSON.stringify(this.context,null,2)}`,`Timestamp: ${this.timestamp}`,`Error ID: ${this.errorId}`),t.join(`
8
- `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},tt=class extends Qe{constructor(t,n,r,o,i,a,l,u=!0){let c=l?` (after ${l} retries)`:"";super(`HTTP ${t} - ${n}${c}`,r,o,{httpStatus:t,httpStatusText:n,responseBody:i,...a},{},u);this.status=t;this.statusText=n;this.name="AxAIServiceStatusError"}},We=class extends Qe{constructor(t,n,r,o,i,a=!0){super(`Network Error: ${t.message}`,n,r,o,{originalErrorName:t.name,originalErrorStack:t.stack,...i},a);this.originalError=t;this.name="AxAIServiceNetworkError",this.stack=t.stack}},Ot=class extends Qe{constructor(e,t,n,r,o=!0){super(e,t,n,void 0,r,o),this.name="AxAIServiceResponseError"}},ut=class extends Qe{constructor(t,n,r,o,i=!0){super("Stream terminated unexpectedly by remote host",t,n,void 0,{lastChunk:r,...o},i);this.lastChunk=r;this.name="AxAIServiceStreamTerminatedError"}},at=class extends Qe{constructor(e,t,n,r,o=!0){super(`Request timed out after ${t}ms`,e,n,void 0,{timeoutMs:t,...r},o),this.name="AxAIServiceTimeoutError"}},rr=class extends tt{constructor(e,t,n,r,o,i,a=!0){super(e,t,n,r,o,i,void 0,a),this.name="AxTokenLimitError"}},Ge=class extends Qe{constructor(e,t,n,r,o=!0){super(`Request aborted${t?`: ${t}`:""}`,e,n,void 0,{abortReason:t,...r},o),this.name="AxAIServiceAbortedError"}},Mt=class extends Qe{constructor(e,t,n,r,o=!0){super("Authentication failed",e,t,n,r,o),this.name="AxAIServiceAuthenticationError"}},Ne=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=Ye()}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()}},ct=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=Ye()}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()}},yt=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=Ye()}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 Us(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 Ma(s,e){return Math.min(e.maxDelayMs,e.initialDelayMs*e.backoffFactor**s)*(.75+Math.random()*.5)}function lp(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 up(){return{startTime:Date.now(),retryCount:0}}function Ea(s){s.retryCount++,s.lastRetryTime=Date.now()}function Pa(s,e,t,n){return t>=n.maxRetries?!1:e&&n.retryableStatusCodes.includes(e)?!0:s instanceof We&&!(s instanceof Mt)}var Xe=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={...ip,...s.retry},n=s.timeout,r=up(),o=s.verbose??!1,i=s.includeRequestBodyInErrors??!0,a,l=new URL(s.url),u=`${[l.pathname,s.name].filter(Boolean).join("/").replace(/\/+/g,"/")}${l.search}`,c=new URL(u,l);if(s.corsProxy){let m=c.href;c=new URL(`${s.corsProxy}?url=${encodeURIComponent(m)}`)}let p=Ye();if(s.validateRequest&&!await s.validateRequest(e))throw new Ot("Invalid request data",c.href,e,{validation:"request"},i);s.span?.setAttributes({"http.request.method":s.put?"PUT":"POST","url.full":c.href,"request.id":p,"request.startTime":r.startTime});let d=0;for(;;){let m=new AbortController;if(s.abortSignal){if(s.abortSignal.aborted)throw new Ge(c.href,s.abortSignal.reason,e,{metrics:r},i);let g=()=>{m.abort(s.abortSignal.reason||"User aborted request")};s.abortSignal.addEventListener("abort",g,{once:!0});let f=m.abort.bind(m);m.abort=h=>{s.abortSignal.removeEventListener("abort",g),f(h)}}n&&(a=setTimeout(()=>{m.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 Hs=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)}},no=class extends TransformStream{constructor(){super(new Hs)}};var Gp={maxRetries:3,initialDelayMs:1e3,maxDelayMs:6e4,backoffFactor:2,retryableStatusCodes:[500,408,429,502,503,504]},Up=globalThis.TextDecoderStream??no,Ue=class extends Error{constructor(t,n,r,o,i={},a=!0){super(t);this.url=n;this.requestBody=r;this.responseBody=o;this.name="AxAIServiceError",this.timestamp=new Date().toISOString(),this.errorId=Ge(),this.context=i,this.includeRequestBodyInErrors=a,this.stack=this.toString()}timestamp;errorId;context;includeRequestBodyInErrors;toString(){let t=[`${this.name}: ${this.message}`,`URL: ${this.url}`];return this.includeRequestBodyInErrors&&t.push(`Request Body: ${JSON.stringify(this.requestBody,null,2)}`),t.push(`Response Body: ${JSON.stringify(this.responseBody,null,2)}`,`Context: ${JSON.stringify(this.context,null,2)}`,`Timestamp: ${this.timestamp}`,`Error ID: ${this.errorId}`),t.join(`
8
+ `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},ze=class extends Ue{constructor(t,n,r,o,i,a,l,u=!0){let c=l?` (after ${l} retries)`:"";super(`HTTP ${t} - ${n}${c}`,r,o,{httpStatus:t,httpStatusText:n,responseBody:i,...a},{},u);this.status=t;this.statusText=n;this.name="AxAIServiceStatusError"}},Le=class extends Ue{constructor(t,n,r,o,i,a=!0){super(`Network Error: ${t.message}`,n,r,o,{originalErrorName:t.name,originalErrorStack:t.stack,...i},a);this.originalError=t;this.name="AxAIServiceNetworkError",this.stack=t.stack}},Tt=class extends Ue{constructor(e,t,n,r,o=!0){super(e,t,n,void 0,r,o),this.name="AxAIServiceResponseError"}},nt=class extends Ue{constructor(t,n,r,o,i=!0){super("Stream terminated unexpectedly by remote host",t,n,void 0,{lastChunk:r,...o},i);this.lastChunk=r;this.name="AxAIServiceStreamTerminatedError"}},et=class extends Ue{constructor(e,t,n,r,o=!0){super(`Request timed out after ${t}ms`,e,n,void 0,{timeoutMs:t,...r},o),this.name="AxAIServiceTimeoutError"}},nr=class extends ze{constructor(e,t,n,r,o,i,a=!0){super(e,t,n,r,o,i,void 0,a),this.name="AxTokenLimitError"}},Pe=class extends Ue{constructor(e,t,n,r,o=!0){super(`Request aborted${t?`: ${t}`:""}`,e,n,void 0,{abortReason:t,...r},o),this.name="AxAIServiceAbortedError"}},wt=class extends Ue{constructor(e,t,n,r,o=!0){super("Authentication failed",e,t,n,r,o),this.name="AxAIServiceAuthenticationError"}},Se=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=Ge()}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()}},rt=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=Ge()}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()}},pt=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=Ge()}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 Ks(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 qa(s,e){return Math.min(e.maxDelayMs,e.initialDelayMs*e.backoffFactor**s)*(.75+Math.random()*.5)}function Bp(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 jp(){return{startTime:Date.now(),retryCount:0}}function za(s){s.retryCount++,s.lastRetryTime=Date.now()}function Ha(s,e,t,n){return t>=n.maxRetries?!1:e&&n.retryableStatusCodes.includes(e)?!0:s instanceof Le&&!(s instanceof wt)}var Be=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={...Gp,...s.retry},n=s.timeout,r=jp(),o=s.verbose??!1,i=s.includeRequestBodyInErrors??!0,a,l=new URL(s.url),u=`${[l.pathname,s.name].filter(Boolean).join("/").replace(/\/+/g,"/")}${l.search}`,c=new URL(u,l);if(s.corsProxy){let m=c.href;c=new URL(`${s.corsProxy}?url=${encodeURIComponent(m)}`)}let p=Ge();if(s.validateRequest&&!await s.validateRequest(e))throw new Tt("Invalid request data",c.href,e,{validation:"request"},i);s.span?.setAttributes({"http.request.method":s.put?"PUT":"POST","url.full":c.href,"request.id":p,"request.startTime":r.startTime});let d=0;for(;;){let m=new AbortController;if(s.abortSignal){if(s.abortSignal.aborted)throw new Pe(c.href,s.abortSignal.reason,e,{metrics:r},i);let g=()=>{m.abort(s.abortSignal.reason||"User aborted request")};s.abortSignal.addEventListener("abort",g,{once:!0});let f=m.abort.bind(m);m.abort=h=>{s.abortSignal.removeEventListener("abort",g),f(h)}}n&&(a=setTimeout(()=>{m.abort("Request timeout")},n));try{o&&console.log(`
12
12
  --- [AxAI API Request] ---
13
13
  `,`URL: ${c.href}
14
14
  `,`Method: ${s.put?"PUT":"POST"}
15
15
  `,"Headers:",JSON.stringify({"Content-Type":"application/json","X-Request-ID":p,"X-Retry-Count":d.toString(),...s.headers},null,2),`
16
16
  Body:`,JSON.stringify(e,null,2),`
17
17
  ------------------------
18
- `);let g=await(s.fetch??fetch)(c,{method:s.put?"PUT":"POST",headers:{"Content-Type":"application/json","X-Request-ID":p,"X-Retry-Count":d.toString(),...s.headers},body:JSON.stringify(e),signal:m.signal});if(a&&clearTimeout(a),g.status===401||g.status===403){let R=await Us(g);throw new Mt(c.href,e,R,{metrics:r},i)}if(g.status===400){let R=await Us(g),A=R,w=!1;if(A?.error?.code==="context_length_exceeded")w=!0;else if(A?.type==="invalid_request_error"&&(A?.error?.message?.includes("prompt is too long")||A?.error?.message?.includes("max_tokens")||A?.error?.message?.includes("token limit")))w=!0;else if(A?.error?.code===400&&A?.error?.status==="INVALID_ARGUMENT"&&(A?.error?.message?.includes("token")||A?.error?.message?.includes("limit")))w=!0;else{let v=JSON.stringify(R).toLowerCase();(v.includes("token")&&v.includes("limit")||v.includes("context length")||v.includes("prompt is too long"))&&(w=!0)}if(w)throw new rr(g.status,g.statusText,c.href,e,R,{metrics:r},i)}if(g.status>=400&&Pa(new Error,g.status,d,t)){let R=Ma(d,t),A=lp(g.headers.get("Retry-After"));A!==void 0&&A<=t.maxDelayMs&&(R=A,o&&console.log(`[AxAI] Respecting Retry-After header: ${R}ms`)),d++,Ea(r),s.span?.addEvent("retry",{attempt:d,delay:R,status:g.status,"metrics.startTime":r.startTime,"metrics.retryCount":r.retryCount,"metrics.lastRetryTime":r.lastRetryTime}),await new Promise(w=>setTimeout(w,R));continue}if(g.status>=400){let R=await Us(g);throw new tt(g.status,g.statusText,c.href,e,R,{metrics:r},d>0?d:void 0,i)}if(!s.stream){let R=await g.json();if(o&&console.log(`
18
+ `);let g=await(s.fetch??fetch)(c,{method:s.put?"PUT":"POST",headers:{"Content-Type":"application/json","X-Request-ID":p,"X-Retry-Count":d.toString(),...s.headers},body:JSON.stringify(e),signal:m.signal});if(a&&clearTimeout(a),g.status===401||g.status===403){let C=await Ks(g);throw new wt(c.href,e,C,{metrics:r},i)}if(g.status===400){let C=await Ks(g),I=C,v=!1;if(I?.error?.code==="context_length_exceeded")v=!0;else if(I?.type==="invalid_request_error"&&(I?.error?.message?.includes("prompt is too long")||I?.error?.message?.includes("max_tokens")||I?.error?.message?.includes("token limit")))v=!0;else if(I?.error?.code===400&&I?.error?.status==="INVALID_ARGUMENT"&&(I?.error?.message?.includes("token")||I?.error?.message?.includes("limit")))v=!0;else{let O=JSON.stringify(C).toLowerCase();(O.includes("token")&&O.includes("limit")||O.includes("context length")||O.includes("prompt is too long"))&&(v=!0)}if(v)throw new nr(g.status,g.statusText,c.href,e,C,{metrics:r},i)}if(g.status>=400&&Ha(new Error,g.status,d,t)){let C=qa(d,t),I=Bp(g.headers.get("Retry-After"));I!==void 0&&I<=t.maxDelayMs&&(C=I,o&&console.log(`[AxAI] Respecting Retry-After header: ${C}ms`)),d++,za(r),s.span?.addEvent("retry",{attempt:d,delay:C,status:g.status,"metrics.startTime":r.startTime,"metrics.retryCount":r.retryCount,"metrics.lastRetryTime":r.lastRetryTime}),await new Promise(v=>setTimeout(v,C));continue}if(g.status>=400){let C=await Ks(g);throw new ze(g.status,g.statusText,c.href,e,C,{metrics:r},d>0?d:void 0,i)}if(!s.stream){let C=await g.json();if(o&&console.log(`
19
19
  --- [AxAI API Response] ---
20
20
  `,`Status: ${g.status} ${g.statusText}
21
- `,"Body:",JSON.stringify(R,null,2),`
21
+ `,"Body:",JSON.stringify(C,null,2),`
22
22
  -------------------------
23
- `),s.validateResponse&&!await s.validateResponse(R))throw new Ot("Invalid response data",c.href,e,{validation:"response"},i);return s.span?.setAttributes({"response.time":Date.now()-r.startTime,"response.retries":r.retryCount}),R}if(o&&console.log(`
23
+ `),s.validateResponse&&!await s.validateResponse(C))throw new Tt("Invalid response data",c.href,e,{validation:"response"},i);return s.span?.setAttributes({"response.time":Date.now()-r.startTime,"response.retries":r.retryCount}),C}if(o&&console.log(`
24
24
  --- [AxAI API Streaming Response Started] ---
25
25
  `,`Status: ${g.status} ${g.statusText}
26
26
  `,`
27
27
  -------------------------------------------
28
- `),!g.body)throw new Ot("Response body is null",c.href,e,{metrics:r},i);let f,h=0;if(typeof window<"u"&&typeof EventSource<"u")return new ReadableStream({start(R){let A=g.body.getReader(),w=new TextDecoder,v="";async function F(){try{for(;;){let{done:O,value:D}=await A.read();if(O){b=!0,R.close();break}v+=w.decode(D,{stream:!0});let U=v.split(`
28
+ `),!g.body)throw new Tt("Response body is null",c.href,e,{metrics:r},i);let f,h=0;if(typeof window<"u"&&typeof EventSource<"u")return new ReadableStream({start(C){let I=g.body.getReader(),v=new TextDecoder,O="";async function k(){try{for(;;){let{done:S,value:$}=await I.read();if(S){b=!0,C.close();break}O+=v.decode($,{stream:!0});let G=O.split(`
29
29
 
30
- `);v=U.pop()||"";for(let L of U){if(!L.trim())continue;let T=L.split(`
31
- `),M="",E="message";for(let N of T)N.startsWith("data: ")?M=N.slice(6):N.startsWith("event: ")&&(E=N.slice(7));if(M){if(M==="[DONE]"){R.close();return}try{let N=JSON.parse(M);f=N,h++,r.streamChunks=h,r.lastChunkTime=Date.now(),R.enqueue(N),s.span?.addEvent("stream.chunk",{"stream.chunks":h,"stream.duration":Date.now()-r.startTime,"response.retries":r.retryCount,"sse.event.type":E})}catch(N){o&&console.warn("Skipping non-JSON SSE data:",M,N)}}}}}catch(O){let D=O,U={...r,streamDuration:Date.now()-r.startTime};D.name==="AbortError"||D.message?.includes("aborted")?R.error(new ut(c.href,e,f,{streamMetrics:U},i)):R.error(new We(D,c.href,e,"[ReadableStream - consumed during streaming]",{streamMetrics:U},i))}finally{A.releaseLock()}}F()}});let x=new TransformStream({transform(R,A){f=R,h++,r.streamChunks=h,r.lastChunkTime=Date.now(),A.enqueue(R),s.span?.addEvent("stream.chunk",{"stream.chunks":h,"stream.duration":Date.now()-r.startTime,"response.retries":r.retryCount})}}),b=!1;return new ReadableStream({start(R){let A=g.body.pipeThrough(new ap).pipeThrough(new Zr).pipeThrough(x).getReader();async function w(){try{for(;;){let{done:v,value:F}=await A.read();if(v){b||(b=!0,R.close());break}if(b)break;R.enqueue(F)}}catch(v){let F=v,O={...r,streamDuration:Date.now()-r.startTime};throw F.name==="AbortError"||F.message?.includes("aborted")?R.error(new ut(c.href,e,f,{streamMetrics:O},i)):F instanceof TypeError&&F.message.includes("cancelled")?R.error(new ut(c.href,e,f,{streamMetrics:O,cancelReason:"Stream cancelled by client"},i)):R.error(new We(F,c.href,e,"[ReadableStream - consumed during streaming]",{streamMetrics:O},i)),F}finally{a&&clearTimeout(a),A.releaseLock()}}w()},cancel(){b=!0}})}catch(g){if(g instanceof Error&&g.name==="AbortError")throw s.abortSignal?.aborted?new Ge(c.href,s.abortSignal.reason,e,{metrics:r},i):new at(c.href,n||0,e,{metrics:r},i);let f=g;if(!(g instanceof Qe)&&g instanceof Error&&(f=new We(g,c.href,e,void 0,{metrics:r},i)),s.span?.isRecording()&&(s.span.recordException(f),s.span.setAttributes({"error.time":Date.now()-r.startTime,"error.retries":r.retryCount})),f instanceof We&&Pa(f,void 0,d,t)){let h=Ma(d,t);d++,Ea(r),s.span?.addEvent("retry",{attempt:d,delay:h,error:f.message,"metrics.startTime":r.startTime,"metrics.retryCount":r.retryCount,"metrics.lastRetryTime":r.lastRetryTime}),await new Promise(y=>setTimeout(y,h));continue}throw f instanceof Qe&&(f.context.metrics=r),f}finally{a!==void 0&&clearTimeout(a)}}};var Fa=typeof globalThis=="object"?globalThis:global;var Et="1.9.0";var _a=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function cp(s){var e=new Set([s]),t=new Set,n=s.match(_a);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(_a);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 Na=cp(Et);var pp=Et.split(".")[0],or=Symbol.for("opentelemetry.js.api."+pp),sr=Fa;function nn(s,e,t,n){var r;n===void 0&&(n=!1);var o=sr[or]=(r=sr[or])!==null&&r!==void 0?r:{version:Et};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!==Et){var i=new Error("@opentelemetry/api: Registration of version v"+o.version+" for "+s+" does not match previously registered API v"+Et);return t.error(i.stack||i.message),!1}return o[s]=e,t.debug("@opentelemetry/api: Registered a global for "+s+" v"+Et+"."),!0}function Pt(s){var e,t,n=(e=sr[or])===null||e===void 0?void 0:e.version;if(!(!n||!Na(n)))return(t=sr[or])===null||t===void 0?void 0:t[s]}function rn(s,e){e.debug("@opentelemetry/api: Unregistering a global for "+s+" v"+Et+".");var t=sr[or];t&&delete t[s]}var dp=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},mp=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))},$a=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 ir("debug",this._namespace,e)},s.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return ir("error",this._namespace,e)},s.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return ir("info",this._namespace,e)},s.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return ir("warn",this._namespace,e)},s.prototype.verbose=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return ir("verbose",this._namespace,e)},s}();function ir(s,e,t){var n=Pt("diag");if(n)return t.unshift(e),n[s].apply(n,mp([],dp(t),!1))}var nt;(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"})(nt||(nt={}));function La(s,e){s<nt.NONE?s=nt.NONE:s>nt.ALL&&(s=nt.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",nt.ERROR),warn:t("warn",nt.WARN),info:t("info",nt.INFO),debug:t("debug",nt.DEBUG),verbose:t("verbose",nt.VERBOSE)}}var gp=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},fp=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))},hp="diag",on=function(){function s(){function e(r){return function(){for(var o=[],i=0;i<arguments.length;i++)o[i]=arguments[i];var a=Pt("diag");if(a)return a[r].apply(a,fp([],gp(o),!1))}}var t=this,n=function(r,o){var i,a,l;if(o===void 0&&(o={logLevel:nt.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=Pt("diag"),p=La((a=o.logLevel)!==null&&a!==void 0?a:nt.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 nn("diag",p,t,!0)};t.setLogger=n,t.disable=function(){rn(hp,t)},t.createComponentLogger=function(r){return new $a(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 Da(s){return Symbol.for(s)}var xp=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}(),Ga=new xp;var Ap=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},yp=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))},Ua=function(){function s(){}return s.prototype.active=function(){return Ga},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,yp([n],Ap(r),!1))},s.prototype.bind=function(e,t){return t},s.prototype.enable=function(){return this},s.prototype.disable=function(){return this},s}();var bp=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},Ip=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))},Bs="context",Cp=new Ua,sn=function(){function s(){}return s.getInstance=function(){return this._instance||(this._instance=new s),this._instance},s.prototype.setGlobalContextManager=function(e){return nn(Bs,e,on.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,Ip([e,t,n],bp(o),!1))},s.prototype.bind=function(e,t){return this._getContextManager().bind(e,t)},s.prototype._getContextManager=function(){return Pt(Bs)||Cp},s.prototype.disable=function(){this._getContextManager().disable(),rn(Bs,on.instance())},s}();var to;(function(s){s[s.NONE=0]="NONE",s[s.SAMPLED=1]="SAMPLED"})(to||(to={}));var js="0000000000000000",qs="00000000000000000000000000000000",Ba={traceId:qs,spanId:js,traceFlags:to.NONE};var _t=function(){function s(e){e===void 0&&(e=Ba),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 zs=Da("OpenTelemetry Context Key SPAN");function no(s){return s.getValue(zs)||void 0}function ja(){return no(sn.getInstance().active())}function ar(s,e){return s.setValue(zs,e)}function qa(s){return s.deleteValue(zs)}function za(s,e){return ar(s,new _t(e))}function ro(s){var e;return(e=no(s))===null||e===void 0?void 0:e.spanContext()}var Tp=/^([0-9a-f]{32})$/i,wp=/^[0-9a-f]{16}$/i;function Rp(s){return Tp.test(s)&&s!==qs}function vp(s){return wp.test(s)&&s!==js}function oo(s){return Rp(s.traceId)&&vp(s.spanId)}function Ha(s){return new _t(s)}var Hs=sn.getInstance(),so=function(){function s(){}return s.prototype.startSpan=function(e,t,n){n===void 0&&(n=Hs.active());var r=!!t?.root;if(r)return new _t;var o=n&&ro(n);return Sp(o)&&oo(o)?new _t(o):new _t},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??Hs.active(),u=this.startSpan(e,o,l),c=ar(l,u);return Hs.with(c,a,void 0,u)}},s}();function Sp(s){return typeof s=="object"&&typeof s.spanId=="string"&&typeof s.traceId=="string"&&typeof s.traceFlags=="number"}var kp=new so,Ka=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):kp},s}();var Wa=function(){function s(){}return s.prototype.getTracer=function(e,t,n){return new so},s}();var Op=new Wa,Ks=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 Ka(this,e,t,n)},s.prototype.getDelegate=function(){var e;return(e=this._delegate)!==null&&e!==void 0?e:Op},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 ot;(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"})(ot||(ot={}));var Nt=sn.getInstance();var Ws="trace",Va=function(){function s(){this._proxyTracerProvider=new Ks,this.wrapSpanContext=Ha,this.isSpanContextValid=oo,this.deleteSpan=qa,this.getSpan=no,this.getActiveSpan=ja,this.getSpanContext=ro,this.setSpan=ar,this.setSpanContext=za}return s.getInstance=function(){return this._instance||(this._instance=new s),this._instance},s.prototype.setGlobalTracerProvider=function(e){var t=nn(Ws,this._proxyTracerProvider,on.instance());return t&&this._proxyTracerProvider.setDelegate(e),t},s.prototype.getTracerProvider=function(){return Pt(Ws)||this._proxyTracerProvider},s.prototype.getTracer=function(e,t){return this.getTracerProvider().getTracer(e,t)},s.prototype.disable=function(){rn(Ws,on.instance()),this._proxyTracerProvider=new Ks},s}();var lr=Va.getInstance();var fe={signatureStrict:!0,useStructuredPrompt:!0,tracer:void 0,meter:void 0,logger:void 0,optimizerLogger:void 0,debug:void 0,abortSignal:void 0,customLabels:void 0,cachingFunction:void 0,functionResultFormatter:s=>typeof s=="string"?s:s==null?"":JSON.stringify(s,null,2)};var rt=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 hf=new rt,Ja=s=>{console.log(s)},Ya=(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")}
30
+ `);O=G.pop()||"";for(let L of G){if(!L.trim())continue;let w=L.split(`
31
+ `),R="",E="message";for(let _ of w)_.startsWith("data: ")?R=_.slice(6):_.startsWith("event: ")&&(E=_.slice(7));if(R){if(R==="[DONE]"){C.close();return}try{let _=JSON.parse(R);f=_,h++,r.streamChunks=h,r.lastChunkTime=Date.now(),C.enqueue(_),s.span?.addEvent("stream.chunk",{"stream.chunks":h,"stream.duration":Date.now()-r.startTime,"response.retries":r.retryCount,"sse.event.type":E})}catch(_){o&&console.warn("Skipping non-JSON SSE data:",R,_)}}}}}catch(S){let $=S,G={...r,streamDuration:Date.now()-r.startTime};$.name==="AbortError"||$.message?.includes("aborted")?C.error(new nt(c.href,e,f,{streamMetrics:G},i)):C.error(new Le($,c.href,e,"[ReadableStream - consumed during streaming]",{streamMetrics:G},i))}finally{I.releaseLock()}}k()}});let x=new TransformStream({transform(C,I){f=C,h++,r.streamChunks=h,r.lastChunkTime=Date.now(),I.enqueue(C),s.span?.addEvent("stream.chunk",{"stream.chunks":h,"stream.duration":Date.now()-r.startTime,"response.retries":r.retryCount})}}),b=!1;return new ReadableStream({start(C){let I=g.body.pipeThrough(new Up).pipeThrough(new to).pipeThrough(x).getReader();async function v(){try{for(;;){let{done:O,value:k}=await I.read();if(O){b||(b=!0,C.close());break}if(b)break;C.enqueue(k)}}catch(O){let k=O,S={...r,streamDuration:Date.now()-r.startTime};throw k.name==="AbortError"||k.message?.includes("aborted")?C.error(new nt(c.href,e,f,{streamMetrics:S},i)):k instanceof TypeError&&k.message.includes("cancelled")?C.error(new nt(c.href,e,f,{streamMetrics:S,cancelReason:"Stream cancelled by client"},i)):C.error(new Le(k,c.href,e,"[ReadableStream - consumed during streaming]",{streamMetrics:S},i)),k}finally{a&&clearTimeout(a),I.releaseLock()}}v()},cancel(){b=!0}})}catch(g){if(g instanceof Error&&g.name==="AbortError")throw s.abortSignal?.aborted?new Pe(c.href,s.abortSignal.reason,e,{metrics:r},i):new et(c.href,n||0,e,{metrics:r},i);let f=g;if(!(g instanceof Ue)&&g instanceof Error&&(f=new Le(g,c.href,e,void 0,{metrics:r},i)),s.span?.isRecording()&&(s.span.recordException(f),s.span.setAttributes({"error.time":Date.now()-r.startTime,"error.retries":r.retryCount})),f instanceof Le&&Ha(f,void 0,d,t)){let h=qa(d,t);d++,za(r),s.span?.addEvent("retry",{attempt:d,delay:h,error:f.message,"metrics.startTime":r.startTime,"metrics.retryCount":r.retryCount,"metrics.lastRetryTime":r.lastRetryTime}),await new Promise(A=>setTimeout(A,h));continue}throw f instanceof Ue&&(f.context.metrics=r),f}finally{a!==void 0&&clearTimeout(a)}}};var Ka=typeof globalThis=="object"?globalThis:global;var Rt="1.9.0";var Wa=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function qp(s){var e=new Set([s]),t=new Set,n=s.match(Wa);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(Wa);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 Va=qp(Rt);var zp=Rt.split(".")[0],rr=Symbol.for("opentelemetry.js.api."+zp),or=Ka;function Xt(s,e,t,n){var r;n===void 0&&(n=!1);var o=or[rr]=(r=or[rr])!==null&&r!==void 0?r:{version:Rt};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!==Rt){var i=new Error("@opentelemetry/api: Registration of version v"+o.version+" for "+s+" does not match previously registered API v"+Rt);return t.error(i.stack||i.message),!1}return o[s]=e,t.debug("@opentelemetry/api: Registered a global for "+s+" v"+Rt+"."),!0}function vt(s){var e,t,n=(e=or[rr])===null||e===void 0?void 0:e.version;if(!(!n||!Va(n)))return(t=or[rr])===null||t===void 0?void 0:t[s]}function Zt(s,e){e.debug("@opentelemetry/api: Unregistering a global for "+s+" v"+Rt+".");var t=or[rr];t&&delete t[s]}var Hp=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},Kp=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))},Ja=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 sr("debug",this._namespace,e)},s.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return sr("error",this._namespace,e)},s.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return sr("info",this._namespace,e)},s.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return sr("warn",this._namespace,e)},s.prototype.verbose=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return sr("verbose",this._namespace,e)},s}();function sr(s,e,t){var n=vt("diag");if(n)return t.unshift(e),n[s].apply(n,Kp([],Hp(t),!1))}var He;(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"})(He||(He={}));function Ya(s,e){s<He.NONE?s=He.NONE:s>He.ALL&&(s=He.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",He.ERROR),warn:t("warn",He.WARN),info:t("info",He.INFO),debug:t("debug",He.DEBUG),verbose:t("verbose",He.VERBOSE)}}var Wp=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},Vp=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))},Jp="diag",en=function(){function s(){function e(r){return function(){for(var o=[],i=0;i<arguments.length;i++)o[i]=arguments[i];var a=vt("diag");if(a)return a[r].apply(a,Vp([],Wp(o),!1))}}var t=this,n=function(r,o){var i,a,l;if(o===void 0&&(o={logLevel:He.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=vt("diag"),p=Ya((a=o.logLevel)!==null&&a!==void 0?a:He.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 Xt("diag",p,t,!0)};t.setLogger=n,t.disable=function(){Zt(Jp,t)},t.createComponentLogger=function(r){return new Ja(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 Qa(s){return Symbol.for(s)}var Yp=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}(),Xa=new Yp;var Qp=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},Xp=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))},Za=function(){function s(){}return s.prototype.active=function(){return Xa},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,Xp([n],Qp(r),!1))},s.prototype.bind=function(e,t){return t},s.prototype.enable=function(){return this},s.prototype.disable=function(){return this},s}();var Zp=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},ed=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))},Ws="context",td=new Za,tn=function(){function s(){}return s.getInstance=function(){return this._instance||(this._instance=new s),this._instance},s.prototype.setGlobalContextManager=function(e){return Xt(Ws,e,en.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,ed([e,t,n],Zp(o),!1))},s.prototype.bind=function(e,t){return this._getContextManager().bind(e,t)},s.prototype._getContextManager=function(){return vt(Ws)||td},s.prototype.disable=function(){this._getContextManager().disable(),Zt(Ws,en.instance())},s}();var ro;(function(s){s[s.NONE=0]="NONE",s[s.SAMPLED=1]="SAMPLED"})(ro||(ro={}));var Vs="0000000000000000",Js="00000000000000000000000000000000",el={traceId:Js,spanId:Vs,traceFlags:ro.NONE};var Et=function(){function s(e){e===void 0&&(e=el),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 Ys=Qa("OpenTelemetry Context Key SPAN");function oo(s){return s.getValue(Ys)||void 0}function tl(){return oo(tn.getInstance().active())}function ir(s,e){return s.setValue(Ys,e)}function nl(s){return s.deleteValue(Ys)}function rl(s,e){return ir(s,new Et(e))}function so(s){var e;return(e=oo(s))===null||e===void 0?void 0:e.spanContext()}var nd=/^([0-9a-f]{32})$/i,rd=/^[0-9a-f]{16}$/i;function od(s){return nd.test(s)&&s!==Js}function sd(s){return rd.test(s)&&s!==Vs}function io(s){return od(s.traceId)&&sd(s.spanId)}function ol(s){return new Et(s)}var Qs=tn.getInstance(),ao=function(){function s(){}return s.prototype.startSpan=function(e,t,n){n===void 0&&(n=Qs.active());var r=!!t?.root;if(r)return new Et;var o=n&&so(n);return id(o)&&io(o)?new Et(o):new Et},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??Qs.active(),u=this.startSpan(e,o,l),c=ir(l,u);return Qs.with(c,a,void 0,u)}},s}();function id(s){return typeof s=="object"&&typeof s.spanId=="string"&&typeof s.traceId=="string"&&typeof s.traceFlags=="number"}var ad=new ao,sl=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):ad},s}();var il=function(){function s(){}return s.prototype.getTracer=function(e,t,n){return new ao},s}();var ld=new il,Xs=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 sl(this,e,t,n)},s.prototype.getDelegate=function(){var e;return(e=this._delegate)!==null&&e!==void 0?e:ld},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 Ve;(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"})(Ve||(Ve={}));var Pt=tn.getInstance();var Zs="trace",al=function(){function s(){this._proxyTracerProvider=new Xs,this.wrapSpanContext=ol,this.isSpanContextValid=io,this.deleteSpan=nl,this.getSpan=oo,this.getActiveSpan=tl,this.getSpanContext=so,this.setSpan=ir,this.setSpanContext=rl}return s.getInstance=function(){return this._instance||(this._instance=new s),this._instance},s.prototype.setGlobalTracerProvider=function(e){var t=Xt(Zs,this._proxyTracerProvider,en.instance());return t&&this._proxyTracerProvider.setDelegate(e),t},s.prototype.getTracerProvider=function(){return vt(Zs)||this._proxyTracerProvider},s.prototype.getTracer=function(e,t){return this.getTracerProvider().getTracer(e,t)},s.prototype.disable=function(){Zt(Zs,en.instance()),this._proxyTracerProvider=new Xs},s}();var ar=al.getInstance();var ce={signatureStrict:!0,useStructuredPrompt:!0,tracer:void 0,meter:void 0,logger:void 0,optimizerLogger:void 0,debug:void 0,abortSignal:void 0,customLabels:void 0,cachingFunction:void 0,functionResultFormatter:s=>typeof s=="string"?s:s==null?"":JSON.stringify(s,null,2)};var Ke=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 ah=new Ke,ll=s=>{console.log(s)},ul=(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
32
  ${n(s.content,"magenta")}`;case"function":return`${n("[ FUNCTION RESULT ]","yellow")}
33
33
  ${n(s.result??"[No result]","yellowDim")}`;case"user":{let r=`${n("[ USER ]","greenBright")}
34
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(`
@@ -38,11 +38,11 @@ ${n(s.result??"[No result]","yellowDim")}`;case"user":{let r=`${n("[ USER ]","gr
38
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+=`
39
39
  `)}),o+=`
40
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")}`}},Vs=(s=Ja)=>{let e=new rt,t=e.gray(`${"\u2500".repeat(60)}
41
+ ${n(JSON.stringify(s),"gray")}`}},ei=(s=ll)=>{let e=new Ke,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+=Ya(i,void 0,e),a<r.value.length-1&&(o+=`
45
+ `,r.value.forEach((i,a)=>{o+=ul(i,void 0,e),a<r.value.length-1&&(o+=`
46
46
  ${t}
47
47
  `)}),o+=`
48
48
  ${t}`;break;case"FunctionResults":o=`
@@ -102,10 +102,10 @@ ${t}
102
102
  [ CHAT RESPONSE CITATIONS ]`)}
103
103
  `,r.value.forEach(i=>{o+=`${e.white("- ")}${e.cyan(i.title||i.url)}
104
104
  `,i.description&&(o+=` ${e.gray(i.description)}
105
- `)}),o+=t;break}default:o=e.gray(JSON.stringify(r,null,2))}s(o)}},Qa=Vs(),Xa=(s=Ja)=>{let e="\u2500".repeat(60);return t=>{let n=t,r="";switch(n.name){case"ChatRequestChatPrompt":r=`
105
+ `)}),o+=t;break}default:o=e.gray(JSON.stringify(r,null,2))}s(o)}},cl=ei(),pl=(s=ll)=>{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+=Ya(o),i<n.value.length-1&&(r+=`
108
+ `,n.value.forEach((o,i)=>{r+=ul(o),i<n.value.length-1&&(r+=`
109
109
  ${e}
110
110
  `)}),r+=`
111
111
  ${e}`;break;case"FunctionResults":r=`
@@ -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 xe={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"},bt={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"},Js=(r=>(r.COMPLETION="completion",r.CHAT="chat",r.RERANK="rerank",r.UNKNOWN="unknown",r))(Js||{}),Ys=(o=>(o.WORKFLOW="workflow",o.TASK="task",o.AGENT="agent",o.TOOL="tool",o.UNKNOWN="unknown",o))(Ys||{});var Qs=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()}},io=class extends TransformStream{constructor(e,t){super(new Qs(e,t))}};function ao(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 Za=(s,e,t,n)=>{let r=n?s.filter(i=>i.role!=="system"):[...s];t({name:"ChatRequestChatPrompt",step:e,value:r})};var el=(s,e)=>{if(!s.results)return;let t={name:"ChatResponseResults",value:s.results};e(t)};function tl(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?ao(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 nl=(s,e)=>{e({name:"FunctionResults",value:s})},Xs=(s,e,t,n)=>{n({name:"FunctionError",index:e,fixingInstructions:t,error:s})},rl=(s,e,t,n)=>{n({name:"ValidationError",index:e,fixingInstructions:t,error:s})},ol=(s,e,t,n)=>{n({name:"AssertionError",index:e,fixingInstructions:t,error:s})},sl=(s,e,t)=>{t({name:"RefusalError",index:e,error:s})};var il=(s,e,t)=>{t({name:"EmbedRequest",embedModel:e,value:s})},al=(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)},ll=(s,e,t,n)=>{n({name:"ResultPickerUsed",sampleCount:s,selectedIndex:e,latency:t})};var uo=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},qt=(...s)=>{let e={};for(let t of s)t&&Object.assign(e,t);return e},lo,ul=s=>{if(lo)return lo;if(s)return lo=Mp(s),lo};var Mp=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)"}),cacheReadTokensCounter:s.createCounter("ax_llm_cache_read_tokens_total",{description:"Total number of tokens read from cache (prompt caching)"}),cacheWriteTokensCounter:s.createCounter("ax_llm_cache_write_tokens_total",{description:"Total number of tokens written to cache (prompt caching)"})}),cl=(s,e,t,n,r,o)=>{try{if(s.latencyHistogram){let i=uo({operation:e,ai_service:n,...r?{model:r}:{},...o});s.latencyHistogram.record(t,i)}}catch(i){console.warn("Failed to record latency metric:",i)}},pl=(s,e,t,n,r,o,i,a)=>{let l={operation:e,ai_service:o,...i?{model:i}:{},...a};s.meanLatencyGauge&&s.meanLatencyGauge.record(t,l),s.p95LatencyGauge&&s.p95LatencyGauge.record(n,l),s.p99LatencyGauge&&s.p99LatencyGauge.record(r,l)},dl=(s,e,t,n,r)=>{try{if(s.errorCounter){let o=uo({operation:e,ai_service:t,...n?{model:n}:{},...r});s.errorCounter.add(1,o)}}catch(o){console.warn("Failed to record error metric:",o)}},ml=(s,e,t,n,r,o)=>{s.errorRateGauge&&s.errorRateGauge.record(t*100,{operation:e,ai_service:n,...r?{model:r}:{},...o})},gl=(s,e,t,n,r)=>{s.requestCounter&&s.requestCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{},...r})},ur=(s,e,t,n,r,o)=>{try{let i=uo({ai_service:n,...r?{model:r}:{},...o});s.tokenCounter&&s.tokenCounter.add(t,{token_type:e,...i}),e==="input"&&s.inputTokenCounter&&s.inputTokenCounter.add(t,i),e==="output"&&s.outputTokenCounter&&s.outputTokenCounter.add(t,i)}catch(i){console.warn("Failed to record token metric:",i)}},fl=(s,e,t,n,r,o)=>{t&&s.streamingRequestsCounter&&s.streamingRequestsCounter.add(1,{operation:e,ai_service:n,...r?{model:r}:{},...o})},hl=(s,e,t,n,r,o)=>{let i={function_name:e,...n?{ai_service:n}:{},...r?{model:r}:{},...o};s.functionCallsCounter&&s.functionCallsCounter.add(1,i),t&&s.functionCallLatencyHistogram&&s.functionCallLatencyHistogram.record(t,i)},Zs=(s,e,t,n,r,o)=>{s.requestSizeHistogram&&s.requestSizeHistogram.record(t,{operation:e,ai_service:n,...r?{model:r}:{},...o})},ei=(s,e,t,n,r,o)=>{s.responseSizeHistogram&&s.responseSizeHistogram.record(t,{operation:e,ai_service:n,...r?{model:r}:{},...o})},xl=(s,e,t,n,r,o)=>{let i={...n?{ai_service:n}:{},...r?{model:r}:{},...o};e!==void 0&&s.temperatureGauge&&s.temperatureGauge.record(e,i),t!==void 0&&s.maxTokensGauge&&s.maxTokensGauge.record(t,i)},ti=(s,e,t,n,r,o)=>{s.estimatedCostCounter&&s.estimatedCostCounter.add(t,{operation:e,ai_service:n,...r?{model:r}:{},...o})},Al=(s,e,t,n,r)=>{s.promptLengthHistogram&&s.promptLengthHistogram.record(e,{ai_service:t,...n?{model:n}:{},...r})},yl=(s,e,t,n,r)=>{s.contextWindowUsageGauge&&s.contextWindowUsageGauge.record(e,{ai_service:t,...n?{model:n}:{},...r})},bl=(s,e,t,n,r)=>{s.timeoutsCounter&&s.timeoutsCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{},...r})},Il=(s,e,t,n,r)=>{s.abortsCounter&&s.abortsCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{},...r})},Cl=(s,e,t,n,r)=>{s.thinkingBudgetUsageCounter&&s.thinkingBudgetUsageCounter.add(e,{ai_service:t,...n?{model:n}:{},...r})},Tl=(s,e,t,n,r,o)=>{(e||t)&&s.multimodalRequestsCounter&&s.multimodalRequestsCounter.add(1,{ai_service:n,has_images:e.toString(),has_audio:t.toString(),...r?{model:r}:{},...o})},ni=(s,e,t,n,r,o)=>{try{if(t<=0)return;let i=uo({ai_service:n,...r?{model:r}:{},...o});e==="read"&&s.cacheReadTokensCounter&&s.cacheReadTokensCounter.add(t,i),e==="write"&&s.cacheWriteTokensCounter&&s.cacheWriteTokensCounter.add(t,i)}catch(i){console.warn("Failed to record cache token metric:",i)}};function wl(s){try{return JSON.stringify(s,null,2)}catch{return String(s)}}function It(s,e={}){let t=[s];throw e.fieldPath!==void 0&&t.push(`Field: ${e.fieldPath}`),e.value!==void 0&&t.push(`Value: ${wl(e.value)}`),e.note&&t.push(`Note: ${e.note}`),e.item!==void 0&&t.push(`Chat item: ${wl(e.item)}`),new Error(t.join(`
168
- `))}function an(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&&It("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"&&It("Assistant message content must be a string",{fieldPath:"content",value:n,item:s}),r!==void 0&&!Array.isArray(r)&&It("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")&&It("functionCalls entry must be an object",{fieldPath:`functionCalls[${u}]`,value:c,item:s}),(!("id"in c)||typeof c.id!="string"||c.id.trim()==="")&&It("functionCalls entry must include a non-empty string id",{fieldPath:`functionCalls[${u}].id`,value:c.id,item:s}),(!("type"in c)||c.type!=="function")&&It("functionCalls entry must have type 'function'",{fieldPath:`functionCalls[${u}].type`,value:c.type,item:s}),!("function"in c)||!c.function)It("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()==="")&&It("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"&&It("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()==="")&&It("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"&&It("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 co(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 ri=new Map;function Ep(s){return`${s.providerName}:${s.contentHash}`}function Pp(s,e){e.type==="text"?s.update(`text:${e.text}`):e.type==="image"?s.update(`image:${e.mimeType}:${e.image.slice(0,100)}`):e.type==="audio"?s.update(`audio:${e.format}:${e.data.slice(0,100)}`):e.type==="file"&&("fileUri"in e?s.update(`file:${e.mimeType}:${e.fileUri}`):s.update(`file:${e.mimeType}:${e.data.slice(0,100)}`))}function Fp(s){let e=it("sha256"),t=-1;for(let n=s.length-1;n>=0;n--){let r=s[n];if("cache"in r&&r.cache){t=n;break}}for(let n=0;n<s.length;n++){let r=s[n];if(r.role==="system"){e.update(`system:${r.content}`);continue}if(t>=0&&n<=t)if(r.role==="user"){if(typeof r.content=="string")e.update(`user:${r.content}`);else if(Array.isArray(r.content))for(let o of r.content)Pp(e,o)}else r.role==="assistant"&&r.content&&e.update(`assistant:${r.content}`)}return e.digest("hex")}var Re=()=>structuredClone({temperature:0}),He=()=>structuredClone({temperature:.4,frequencyPenalty:.2}),je=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??fe.tracer,this.meter=a.meter??fe.meter,this.modelInfo=o,this.models=u,this.id=Ye();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&&_p(u)}#e=!1;#t=!1;rt;fetch;tracer;meter;timeout;excludeContentFromTrace;models;abortSignal;logger=fe.logger??Qa;corsProxy;retry;customLabels;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 ul(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??fe.debug??!1,this.#t=e.verbose??!1,this.rt=e.rateLimiter,this.fetch=e.fetch,this.timeout=e.timeout,this.tracer=e.tracer??fe.tracer,this.meter=e.meter??fe.meter,this.excludeContentFromTrace=e.excludeContentFromTrace,this.abortSignal=e.abortSignal,this.logger=e.logger??fe.logger??this.logger,this.corsProxy=e.corsProxy,this.retry=e.retry,this.customLabels=e.customLabels}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,customLabels:this.customLabels}}getLogger(){return this.logger}getMergedCustomLabels(e){return qt(fe.customLabels,this.customLabels,e)}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,n){let r=this.metrics.latency[e];r.samples.push(t),r.samples.length>1e3&&r.samples.shift(),r.mean=r.samples.reduce((i,a)=>i+a,0)/r.samples.length,r.p95=this.calculatePercentile(r.samples,95),r.p99=this.calculatePercentile(r.samples,99);let o=this.getMetricsInstruments();if(o){let i=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel,a=this.getMergedCustomLabels(n);cl(o,e,t,this.name,i,a),pl(o,e,r.mean,r.p95,r.p99,this.name,i,a)}}updateErrorMetrics(e,t,n){let r=this.metrics.errors[e];r.total++,t&&r.count++,r.rate=r.count/r.total;let o=this.getMetricsInstruments();if(o){let i=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel,a=this.getMergedCustomLabels(n);gl(o,e,this.name,i,a),t&&dl(o,e,this.name,i,a),ml(o,e,r.rate,this.name,i,a)}}recordTokenUsage(e,t){let n=this.getMetricsInstruments();if(n&&e?.tokens){let{promptTokens:r,completionTokens:o,totalTokens:i,thoughtsTokens:a,cacheReadTokens:l,cacheCreationTokens:u}=e.tokens,c=this.getMergedCustomLabels(t);r&&ur(n,"input",r,this.name,e.model,c),o&&ur(n,"output",o,this.name,e.model,c),i&&ur(n,"total",i,this.name,e.model,c),a&&ur(n,"thoughts",a,this.name,e.model,c),l&&ni(n,"read",l,this.name,e.model,c),u&&ni(n,"write",u,this.name,e.model,c)}}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,n){let r=this.getMetricsInstruments();if(!(!r||!e))for(let o of e)o&&typeof o=="object"&&"function"in o&&o.function&&typeof o.function=="object"&&"name"in o.function&&hl(r,o.function.name,void 0,this.name,t,this.getMergedCustomLabels(n))}recordTimeoutMetric(e,t){let n=this.getMetricsInstruments();if(n){let r=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;bl(n,e,this.name,r,this.getMergedCustomLabels(t))}}recordAbortMetric(e,t){let n=this.getMetricsInstruments();if(n){let r=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;Il(n,e,this.name,r,this.getMergedCustomLabels(t))}}recordChatMetrics(e,t,n){let r=this.getMetricsInstruments();if(!r)return;let o=this.lastUsedChatModel,i=this.lastUsedModelConfig,a=this.getMergedCustomLabels(t?.customLabels),l=i?.stream??!1;fl(r,"chat",l,this.name,o,a);let{hasImages:u,hasAudio:c}=this.detectMultimodalContent(e);Tl(r,u,c,this.name,o,a);let p=this.calculatePromptLength(e);Al(r,p,this.name,o,a),xl(r,i?.temperature,i?.maxTokens,this.name,o,a),t?.thinkingTokenBudget&&this.modelUsage?.tokens?.thoughtsTokens&&Cl(r,this.modelUsage.tokens.thoughtsTokens,this.name,o,a);let d=this.calculateRequestSize(e);if(Zs(r,"chat",d,this.name,o,a),n&&!l){let m=n,g=this.calculateResponseSize(m);if(ei(r,"chat",g,this.name,o,a),m.results)for(let y of m.results)y.functionCalls&&this.recordFunctionCallMetrics(y.functionCalls,this.lastUsedChatModel,a);let f=this.calculateContextWindowUsage(this.lastUsedChatModel,m.modelUsage);f>0&&yl(r,f,this.name,o,a);let h=this.estimateCost(this.lastUsedChatModel,m.modelUsage);h>0&&ti(r,"chat",h,this.name,o,a)}}recordEmbedMetrics(e,t,n){let r=this.getMetricsInstruments();if(!r)return;let o=this.lastUsedEmbedModel,i=this.getMergedCustomLabels(n?.customLabels),a=this.calculateRequestSize(e);Zs(r,"embed",a,this.name,o,i);let l=this.calculateResponseSize(t);ei(r,"embed",l,this.name,o,i);let u=this.estimateCostByName(o,t.modelUsage);u>0&&ti(r,"embed",u,this.name,o,i)}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",l?.customLabels):(u.message.includes("abort")||u.name==="AbortError")&&this.recordAbortMetric("chat",l?.customLabels)),u}finally{let u=performance.now()-n;this.updateLatencyMetrics("chat",u,l?.customLabels),this.updateErrorMetrics("chat",r,l?.customLabels),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)an(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:ot.SERVER,attributes:{[xe.LLM_SYSTEM]:this.name,[xe.LLM_OPERATION_NAME]:"chat",[xe.LLM_REQUEST_MODEL]:n,[xe.LLM_REQUEST_MAX_TOKENS]:o.maxTokens??"Not set",[xe.LLM_REQUEST_TEMPERATURE]:o.temperature,[xe.LLM_REQUEST_TOP_P]:o.topP??"Not set",[xe.LLM_REQUEST_TOP_K]:o.topK??"Not set",[xe.LLM_REQUEST_FREQUENCY_PENALTY]:o.frequencyPenalty??"Not set",[xe.LLM_REQUEST_PRESENCE_PENALTY]:o.presencePenalty??"Not set",[xe.LLM_REQUEST_STOP_SEQUENCES]:o.stopSequences?.join(", ")??"Not set",[xe.LLM_REQUEST_LLM_IS_STREAMING]:o.stream??"Not set"}},t?.traceContext??Nt.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(b=>this.cleanupFunctionSchema(b)));let u={...n,model:e,functions:l,modelConfig:t};this.lastUsedChatModel=e,this.lastUsedModelConfig=t,i&&Za(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(b=>{if(b.role==="assistant"){let{content:R,name:A,cache:w}=b;return{role:"assistant",content:R,name:A,cache:w}}return b.role==="function"?{role:"user",content:b.result}:b}),functions:[]}:u,g=await this.handleContextCaching(e,m,r,o),f=async()=>{if(g?.preparedRequest){let{apiConfig:w,request:v}=g.preparedRequest;return o?.isRecording()&&Rl(n,o,this.excludeContentFromTrace),await Xe({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},v)}let[b,R]=await this.aiImpl.createChatReq(m,r);return o?.isRecording()&&Rl(n,o,this.excludeContentFromTrace),await Xe({name:b.name,url:this.apiURL,localCall:b.localCall,headers:await this.buildHeaders(b.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},R)},h=r?.rateLimiter??this.rt,y=h?await h(f,{modelUsage:this.modelUsage}):await f();if(t.stream){if(!this.aiImpl.createChatStreamResp)throw new Error("createChatStreamResp not implemented");let b=this.aiImpl.createChatStreamResp.bind(this),R=F=>O=>{let D=b(O,F);if(D.sessionId=r?.sessionId,!D.modelUsage){let U=this.aiImpl.getTokenUsage();U&&(D.modelUsage={ai:this.name,model:e,tokens:U})}return this.modelUsage=D.modelUsage,this.recordTokenUsage(D.modelUsage,r?.customLabels),o?.isRecording()&&vl(D,o,this.excludeContentFromTrace),D},A=async F=>{o?.isRecording()&&o.end(),i&&tl(F,r?.logger??this.logger)};if(typeof window<"u"){let F=y,O={},D=[],U=r?.abortSignal??this.abortSignal;return new ReadableStream({start:L=>{let T=F.getReader(),M=()=>{try{T.cancel().catch(()=>{})}catch{}try{this.recordAbortMetric("chat",r?.customLabels)}catch{}try{o?.isRecording()&&o.end()}catch{}try{L.error(new DOMException("Aborted","AbortError"))}catch{L.error(new Error("Aborted"))}};if(U){if(U.aborted){M();return}U.addEventListener("abort",M,{once:!0})}async function E(){try{for(;;){let{done:N,value:P}=await T.read();if(N){A&&await A(D),L.close();break}let _=R(O)(P);_&&(D.push(_),L.enqueue(_))}}catch(N){if(L.error(N),o?.isRecording())try{o.end()}catch{}}finally{if(T.releaseLock(),U)try{U.removeEventListener("abort",M)}catch{}}}E()}})}return y.pipeThrough(new io(R({}),A))}if(!this.aiImpl.createChatResp)throw new Error("createChatResp not implemented");let x=this.aiImpl.createChatResp(y);if(x.sessionId=r?.sessionId,!x.modelUsage){let b=this.aiImpl.getTokenUsage();b&&(x.modelUsage={ai:this.name,model:e,tokens:b})}return x.modelUsage&&(this.modelUsage=x.modelUsage,this.recordTokenUsage(x.modelUsage,r?.customLabels)),o?.isRecording()&&(vl(x,o,this.excludeContentFromTrace),o.end()),i&&el(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",a?.customLabels):(l.message.includes("abort")||l.name==="AbortError")&&this.recordAbortMetric("embed",a?.customLabels)),l}finally{let l=performance.now()-n;this.updateLatencyMetrics("embed",l,a?.customLabels),this.updateErrorMetrics("embed",r,a?.customLabels),!r&&o&&this.recordEmbedMetrics(e,o,a)}}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:ot.SERVER,attributes:{[xe.LLM_SYSTEM]:this.name,[xe.LLM_OPERATION_NAME]:"embeddings",[xe.LLM_REQUEST_MODEL]:n}},t?.traceContext??Nt.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&&il(l.texts??[],e,n?.logger??this.logger);let u=async()=>{let[m,g]=await o(l);return await Xe({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,n?.customLabels),r?.isRecording()&&d.modelUsage?.tokens&&r.addEvent(bt.GEN_AI_USAGE,{[xe.LLM_USAGE_INPUT_TOKENS]:d.modelUsage.tokens.promptTokens,[xe.LLM_USAGE_OUTPUT_TOKENS]:d.modelUsage.tokens.completionTokens??0,[xe.LLM_USAGE_TOTAL_TOKENS]:d.modelUsage.tokens.totalTokens}),i&&al(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 i=this.aiImpl.supportsContextCache?.(e)??!1,a=this.aiImpl.supportsImplicitCaching?.(e)??!1;if(!i&&!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(!i)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=Fp(t.chatPrompt);if(!p||p===it("sha256").digest("hex"))return null;let d={providerName:this.getName(),contentHash:p},m=Ep(d),g=Date.now(),f=o.registry,h=f?await f.get(m):ri.get(m);if(h&&h.expiresAt>g){if(h.expiresAt-g<u*1e3&&this.aiImpl.buildCacheUpdateTTLOp){await this.executeCacheOperation(this.aiImpl.buildCacheUpdateTTLOp(h.cacheName,l),n,r);let R={cacheName:h.cacheName,expiresAt:g+l*1e3,tokenCount:h.tokenCount};f?await f.set(m,R):ri.set(m,{...R,contentHash:p,lastTouchedAt:g})}return this.useCacheByName(e,t,h.cacheName,n,r)}if(this.estimateCacheableTokens(t.chatPrompt)<c)return null;let x=this.aiImpl.buildCacheCreateOp?.(t,n);if(x){let b=await this.executeCacheOperation(x,n,r);if(b){let R={cacheName:b.name,expiresAt:new Date(b.expiresAt).getTime(),tokenCount:b.tokenCount};return f?await f.set(m,R):ri.set(m,{...R,contentHash:p,lastTouchedAt:g}),this.useCacheByName(e,t,b.name,n,r)}}return null}async useCacheByName(e,t,n,r,o){if(this.aiImpl.prepareCachedChatReq){let i=await this.aiImpl.prepareCachedChatReq(t,r??{},n);return{preparedRequest:{apiConfig:i.apiConfig,request:i.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 Xe({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 Rl(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(bt.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(bt.GEN_AI_ASSISTANT_MESSAGE,a)}else if(o.content){let a={};t||(a.content=o.content),e.addEvent(bt.GEN_AI_ASSISTANT_MESSAGE,a)}break}case"function":{let i={id:o.functionId};t||(i.content=o.result),e.addEvent(bt.GEN_AI_TOOL_MESSAGE,i);break}}let r={};t||(r.content=n.join(`
169
- `)),e.addEvent(bt.GEN_AI_USER_MESSAGE,r)}function vl(s,e,t){if(s.modelUsage?.tokens){let n=s.modelUsage.tokens.thoughtsTokens?{[xe.LLM_USAGE_THOUGHTS_TOKENS]:s.modelUsage.tokens.thoughtsTokens}:{};e.addEvent(bt.GEN_AI_USAGE,{[xe.LLM_USAGE_INPUT_TOKENS]:s.modelUsage.tokens.promptTokens,[xe.LLM_USAGE_OUTPUT_TOKENS]:s.modelUsage.tokens.completionTokens??0,[xe.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(bt.GEN_AI_CHOICE,{finish_reason:r.finishReason,index:n,message:JSON.stringify(i,null,2)})}}function Sl(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 _p(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 cr=(h=>(h.Claude46Opus="claude-opus-4-6",h.Claude46Sonnet="claude-sonnet-4-6",h.Claude45Opus="claude-opus-4-5-20251101",h.Claude41Opus="claude-opus-4-1-20250805",h.Claude4Opus="claude-opus-4-20250514",h.Claude4Sonnet="claude-sonnet-4-20250514",h.Claude45Sonnet="claude-sonnet-4-5-20250929",h.Claude45Haiku="claude-haiku-4-5",h.Claude37Sonnet="claude-3-7-sonnet-latest",h.Claude35Sonnet="claude-3-5-sonnet-latest",h.Claude35Haiku="claude-3-5-haiku-latest",h.Claude3Opus="claude-3-opus-latest",h.Claude3Sonnet="claude-3-sonnet-20240229",h.Claude3Haiku="claude-3-haiku-20240307",h.Claude21="claude-2.1",h.ClaudeInstant12="claude-instant-1.2",h))(cr||{}),pr=(g=>(g.Claude46Opus="claude-opus-4-6",g.Claude46Sonnet="claude-sonnet-4-6",g.Claude45Opus="claude-opus-4-5@20251101",g.Claude41Opus="claude-opus-4-1@20250805",g.Claude4Opus="claude-opus-4@20250514",g.Claude45Sonnet="claude-sonnet-4-5@20250929",g.Claude4Sonnet="claude-sonnet-4@20250514",g.Claude37Sonnet="claude-3-7-sonnet@20250219",g.Claude35SonnetV2="claude-3-5-sonnet-v2@20241022",g.Claude45Haiku="claude-haiku-4-5@20251001",g.Claude35Haiku="claude-3-5-haiku@20241022",g.Claude35Sonnet="claude-3-5-sonnet@20240620",g.Claude3Opus="claude-3-opus@20240229",g.Claude3Haiku="claude-3-haiku@20240307",g))(pr||{});var dr=[{name:"claude-opus-4-6",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:25,maxTokens:128e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-6",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:25,maxTokens:128e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4-6",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4-6",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,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-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 $t=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)return e;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,$t(r)]))),e.items&&(e.items=$t(e.items)),Array.isArray(e.anyOf)&&(e.anyOf=e.anyOf.map(n=>$t(n))),Array.isArray(e.allOf)&&(e.allOf=e.allOf.map(n=>$t(n))),Array.isArray(e.oneOf)&&(e.oneOf=e.oneOf.map(n=>$t(n))),e},si=()=>structuredClone({model:"claude-3-7-sonnet-latest",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},effortLevelMapping:{minimal:"low",low:"low",medium:"medium",high:"high",highest:"max"},...Re()}),Ol=()=>structuredClone({model:"claude-3-7-sonnet@20250219",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},effortLevelMapping:{minimal:"low",low:"low",medium:"medium",high:"high",highest:"max"},...Re()}),oi=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.some(E=>"cache"in E&&E.cache)||e.functions?.some(E=>E.cache),l=e.chatPrompt.filter(E=>E.role==="system"),u=l.map((E,N)=>({type:"text",text:E.content,...E.cache||a&&N===l.length-1?{cache_control:{type:"ephemeral"}}:{}})),c=e.chatPrompt.filter(E=>E.role!=="system"),p=e.functions?.map((E,N,P)=>{let _={type:"object",properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]},G=E.parameters?$t(E.parameters):void 0;return G===void 0||G&&typeof G=="object"&&Object.keys(G).length===0?G={..._}:G&&typeof G=="object"&&G.type==="object"&&(!("properties"in G)||!G.properties||Object.keys(G.properties).length===0)&&(G={...G,properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]}),{name:E.name,description:E.description,input_schema:G,...E.cache||a&&N===P.length-1?{cache_control:{type:"ephemeral"}}:{}}}),m=(this.config.tools??[]).map(E=>E&&typeof E=="object"&&"type"in E?E:{name:E.name,description:E.description,input_schema:E.input_schema?$t(E.input_schema):void 0,...E.cache_control?{cache_control:E.cache_control}:{}}),g=[...p??[],...m];g.length===0&&(g=void 0);let f=e.modelConfig?.maxTokens??this.config.maxTokens,h=e.modelConfig?.stopSequences??this.config.stopSequences,y=e.modelConfig?.temperature,x=e.modelConfig?.topP,b=e.modelConfig?.topK??this.config.topK,R=e.modelConfig?.n??this.config.n;if(R&&R>1)throw new Error("Anthropic does not support sampling (n > 1)");let A=E=>E.includes("claude-opus-4-6"),w=E=>E.includes("claude-opus-4-5"),v,F,O=n;if(t?.thinkingTokenBudget){let E=this.config.thinkingTokenBudgetLevels,N=this.config.effortLevelMapping;if(t.thinkingTokenBudget==="none")v=void 0,F=void 0;else{let P=t.thinkingTokenBudget;if(A(O))v={type:"adaptive"},F={effort:N?.[P]??"medium"};else if(w(O)){v={type:"enabled",budget_tokens:E?.[P]??1e4};let G=N?.[P]??"medium";G==="max"&&(G="high"),F={effort:G}}else v={type:"enabled",budget_tokens:E?.[P]??1e4}}}let U=Np(c,!!v);U.some(E=>E.role==="assistant"&&Array.isArray(E.content)&&E.content.length>0&&E.content[0]?.type==="tool_use")&&(v=void 0,F=void 0);let T;if(this.usedStructuredOutput=!1,e.responseFormat&&e.responseFormat.type==="json_schema"&&e.responseFormat.schema){let E=e.responseFormat.schema.schema||e.responseFormat.schema;T={type:"json_schema",schema:$t(E)},this.usedStructuredOutput=!0}let M={...this.isVertex?{anthropic_version:"vertex-2023-10-16"}:{model:n},...f?{max_tokens:f}:{},...h&&h.length>0?{stop_sequences:h}:{},...y!==void 0&&!v?{temperature:y}:{},...x!==void 0&&(!v||x>=.95)?{top_p:x}:{},...b&&!v?{top_k:b}:{},...i,...g?{tools:g}:{},...r?{stream:!0}:{},...u?{system:u}:{},...v?{thinking:v}:{},...F?{output_config:F}:{},...T?{output_format:T}:{},messages:U};return[o,M]};createChatResp=e=>{if(e.type==="error")throw new Ne(e.error.message,void 0,void 0);let t=kl(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 Ne(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:kl(o.stop_reason)}]}}return{results:[{index:r,content:""}]}};supportsImplicitCaching=()=>!0},ln=class s extends je{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={...si(),...r},p=new oi(c,a),d=g=>{let f=lt({model:g,modelInfo:dr,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"],cacheBreakpoints:!1},thinking:f?.supported?.thinkingBudget??!1,multiTurn:!0}},m=i?.map(g=>{let f=g,h=f?.config;if(!h)return g;let y={};h.maxTokens!==void 0&&(y.maxTokens=h.maxTokens),h.temperature!==void 0&&(y.temperature=h.temperature),h.topP!==void 0&&(y.topP=h.topP),h.topK!==void 0&&(y.topK=h.topK),h.presencePenalty!==void 0&&(y.presencePenalty=h.presencePenalty),h.frequencyPenalty!==void 0&&(y.frequencyPenalty=h.frequencyPenalty),h.stopSequences!==void 0&&(y.stopSequences=h.stopSequences),h.endSequences!==void 0&&(y.endSequences=h.endSequences),h.stream!==void 0&&(y.stream=h.stream),h.n!==void 0&&(y.n=h.n);let x={...f};Object.keys(y).length>0&&(x.modelConfig={...f.modelConfig??{},...y});let b=h.thinking?.thinkingTokenBudget;if(typeof b=="number"){let R=c.thinkingTokenBudgetLevels,A=[["minimal",R?.minimal??1024],["low",R?.low??5e3],["medium",R?.medium??1e4],["high",R?.high??2e4],["highest",R?.highest??32e3]],w="minimal",v=Number.POSITIVE_INFINITY;for(let[F,O]of A){let D=Math.abs(b-O);D<v&&(v=D,w=F)}x.thinkingTokenBudget=w}return h.thinking?.includeThoughts!==void 0&&(x.showThoughts=!!h.thinking.includeThoughts),x});super(p,{name:"Anthropic",apiURL:l,headers:u,modelInfo:dr,defaults:{model:c.model},options:o,supportFor:d,models:m??i})}};function Np(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,...r.cache?{cache_control:{type:"ephemeral"}}:{}}:{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});if(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])),r.cache){if(typeof o=="string")o=[{type:"text",text:o,cache_control:{type:"ephemeral"}}];else if(Array.isArray(o)&&o.length>0){let l=o.length-1,u=o[l];u&&u.type==="text"&&(o[l]={...u,cache_control:{type:"ephemeral"}})}}return{role:"assistant",content:o}}default:throw new Error("Invalid role")}}),n=$p(t);return Lp(n)}function $p(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 Lp(s){return s.map(e=>e.role==="assistant"&&typeof e.content=="string"?{...e,content:e.content.replace(/\s+$/,"")}:e)}function kl(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 mr=(_=>(_.GPT4="gpt-4",_.GPT41="gpt-4.1",_.GPT41Mini="gpt-4.1-mini",_.GPT41Nano="gpt-4.1-nano",_.GPT4O="gpt-4o",_.GPT4OMini="gpt-4o-mini",_.GPT4ChatGPT4O="chatgpt-4o-latest",_.GPT4Turbo="gpt-4-turbo",_.GPT35Turbo="gpt-3.5-turbo",_.GPT35TurboInstruct="gpt-3.5-turbo-instruct",_.GPT35TextDavinci002="text-davinci-002",_.GPT3TextBabbage002="text-babbage-002",_.GPT3TextAda001="text-ada-001",_.GPT5="gpt-5",_.GPT5Nano="gpt-5-nano",_.GPT5Mini="gpt-5-mini",_.GPT5Chat="gpt-5-chat",_.GPT5ChatLatest="gpt-5-chat-latest",_.GPT5Codex="gpt-5-codex",_.GPT5Pro="gpt-5-pro",_.GPT51="gpt-5.1",_.GPT51ChatLatest="gpt-5.1-chat-latest",_.GPT51Codex="gpt-5.1-codex",_.GPT51CodexMini="gpt-5.1-codex-mini",_.GPT51CodexMax="gpt-5.1-codex-max",_.GPT52="gpt-5.2",_.GPT52ChatLatest="gpt-5.2-chat-latest",_.GPT52Codex="gpt-5.2-codex",_.GPT52Pro="gpt-5.2-pro",_.O1="o1",_.O1Mini="o1-mini",_.O3="o3",_.O3Mini="o3-mini",_.O4Mini="o4-mini",_))(mr||{}),un=(n=>(n.TextEmbeddingAda002="text-embedding-ada-002",n.TextEmbedding3Small="text-embedding-3-small",n.TextEmbedding3Large="text-embedding-3-large",n))(un||{});var cn=($=>($.GPT4="gpt-4",$.GPT41="gpt-4.1",$.GPT41Mini="gpt-4.1-mini",$.GPT41Nano="gpt-4.1-nano",$.GPT4O="gpt-4o",$.GPT4OMini="gpt-4o-mini",$.GPT4ChatGPT4O="chatgpt-4o-latest",$.GPT4Turbo="gpt-4-turbo",$.GPT35Turbo="gpt-3.5-turbo",$.GPT35TurboInstruct="gpt-3.5-turbo-instruct",$.GPT35TextDavinci002="text-davinci-002",$.GPT3TextBabbage002="text-babbage-002",$.GPT3TextAda001="text-ada-001",$.GPT5="gpt-5",$.GPT5Nano="gpt-5-nano",$.GPT5Mini="gpt-5-mini",$.GPT5Chat="gpt-5-chat",$.GPT5ChatLatest="gpt-5-chat-latest",$.GPT5Codex="gpt-5-codex",$.GPT5Pro="gpt-5-pro",$.GPT51="gpt-5.1",$.GPT51ChatLatest="gpt-5.1-chat-latest",$.GPT51Codex="gpt-5.1-codex",$.GPT51CodexMini="gpt-5.1-codex-mini",$.GPT51CodexMax="gpt-5.1-codex-max",$.GPT52="gpt-5.2",$.GPT52ChatLatest="gpt-5.2-chat-latest",$.GPT52Codex="gpt-5.2-codex",$.GPT52Pro="gpt-5.2-pro",$.O1Pro="o1-pro",$.O1="o1",$.O1Mini="o1-mini",$.O3Pro="o3-pro",$.O3="o3",$.O3Mini="o3-mini",$.O4Mini="o4-mini",$))(cn||{});var pn=[{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:.05,completionTokenCostPer1M:.4,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5-mini",currency:"usd",promptTokenCostPer1M:.25,completionTokenCostPer1M:2,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5-chat",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5-chat-latest",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,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-codex",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:40,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.1-codex",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.1-codex-mini",currency:"usd",promptTokenCostPer1M:.25,completionTokenCostPer1M:2,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.1-codex-max",currency:"usd",promptTokenCostPer1M:2.5,completionTokenCostPer1M:20,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.2",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.2-chat-latest",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.2-codex",currency:"usd",promptTokenCostPer1M:1.5,completionTokenCostPer1M:6,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.2-pro",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:160,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}],po=[{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:.05,completionTokenCostPer1M:.4,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5-mini",currency:"usd",promptTokenCostPer1M:.25,completionTokenCostPer1M:2,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5-chat",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5-chat-latest",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,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-codex",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:40,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.1-codex",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.1-codex-mini",currency:"usd",promptTokenCostPer1M:.25,completionTokenCostPer1M:2,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.1-codex-max",currency:"usd",promptTokenCostPer1M:2.5,completionTokenCostPer1M:20,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.2",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.2-chat-latest",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.2-codex",currency:"usd",promptTokenCostPer1M:1.5,completionTokenCostPer1M:6,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.2-pro",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:160,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 Dp=s=>{let e=["o1","o1-mini","o3","o3-mini","o4-mini","o1-pro","o3-pro"];return e.includes(s)||e.includes(s)},zt=()=>structuredClone({model:"gpt-5-mini",embedModel:"text-embedding-3-small",...Re()}),mo=()=>structuredClone({...zt(),model:"gpt-5"}),go=()=>structuredClone({model:"gpt-5-mini",embedModel:"text-embedding-3-small",...He()}),fo=()=>({...zt(),model:"gpt-5-nano"}),ii=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=Gp(e),l=e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,u=e.modelConfig?.stream??this.config.stream,c=this.config.store,p=Dp(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 Ne(a.message.refusal,e.model,e.id);let l=Ml(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 Ne(p,void 0,n);let h=Ml(f),y=d?.map(({id:x,index:b,function:{name:R,arguments:A}})=>{typeof x=="string"&&typeof b=="number"&&!i.indexIdMap[b]&&(i.indexIdMap[b]=x);let w=i.indexIdMap[b];return w?{id:w,type:"function",function:{name:R,params:A}}:null}).filter(x=>x!==null);return{index:l,content:u??void 0,role:c,thought:m,citations:g?.filter(x=>x?.type==="url_citation"&&x.url_citation).map(x=>({url:x.url_citation?.url,title:x.url_citation?.title,description:x.url_citation?.description})),functionCalls:y,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)}}},Ml=s=>{switch(s){case"stop":return"stop";case"length":return"length";case"content_filter":return"error";case"tool_calls":return"function_call"}};function Gp(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 Ue=class extends je{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 ii(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})}},dn=class extends Ue{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=[...pn,...i??[]];let a=u=>{let c=lt({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]],y="minimal",x=Number.POSITIVE_INFINITY;for(let[b,R]of h){let A=Math.abs(f-R);A<x&&(x=A,y=b)}g.thinkingTokenBudget=y}return p?.thinking?.includeThoughts!==void 0&&(g.showThoughts=!!p.thinking.includeThoughts),g});super({apiKey:e,apiURL:t,config:{...zt(),...n},options:r,modelInfo:i,models:l??o,supportFor:a}),super.setName("OpenAI")}};var Up=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},Bp=s=>{let e=s.match(/^(\d{4}-\d{2}-\d{2})/);return e?e[1]>="2024-08-01":!1},ai=zt,El=go,Pl=fo,Fl=mo,mn=class extends Ue{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={...ai(),...o},c=Up(r),p=Bp(c);l=[...pn,...l??[]];let d=g=>{let f=lt({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 ho=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.");jp(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 Qe))throw p;switch(p.constructor){case Mt:throw p;case tt:{if(![408,429,500,502,503,504].includes(p.status))throw p;break}case We:break;case Ot:break;case ut:break;case at: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 Qe)||r instanceof tt&&![408,429,500,502,503,504].includes(r.status)||r instanceof Mt)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 jp(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 Ht(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 li(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 xo(s,e){return s.map(t=>{let n=t.getFeatures(),r=li(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 Ao(s,e,t={}){if(e.length===0)throw new Error("No providers available");let n=Ht(s),r=xo(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 _l(s,e){let t=Ht(s),n=xo(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 Nl(s,e){return s.filter(t=>t.getFeatures().media[e].supported)}function $l(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 gr=(r=>(r.CommandRPlus="command-r-plus",r.CommandR="command-r",r.Command="command",r.CommandLight="command-light",r))(gr||{}),fr=(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))(fr||{});var yo=[{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}];function qp(s){if(Array.isArray(s)){let t=["string","number","integer","boolean","object","array"].find(n=>s.includes(n));return t||(s.find(n=>n!=="null")??s[0]??"string")}return typeof s=="string"?s:"string"}var ci=()=>structuredClone({model:"command-r-plus",embedModel:"embed-english-v3.0",...Re()}),Dl=()=>structuredClone({model:"command-r",embedModel:"embed-english-v3.0",...He()}),ui=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=zp(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:qp(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}}},gn=class extends je{constructor({apiKey:e,config:t,options:n,models:r}){if(!e||e==="")throw new Error("Cohere API key not set");let o={...ci(),...t},i=new ui(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:yo,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 zp(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=Ll(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=Ll(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 Ll(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 hr=(n=>(n.DeepSeekChat="deepseek-chat",n.DeepSeekCoder="deepseek-coder",n.DeepSeekReasoner="deepseek-reasoner",n))(hr||{});var bo=[{name:"deepseek-chat",currency:"USD",promptTokenCostPer1M:.27,completionTokenCostPer1M:1.1},{name:"deepseek-reasoner",currency:"USD",promptTokenCostPer1M:.55,completionTokenCostPer1M:2.19}];var pi=()=>structuredClone({model:"deepseek-chat",...Re()}),Gl=()=>structuredClone({model:"deepseek-coder",...He()}),fn=class extends Ue{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("DeepSeek API key not set");let i={...pi(),...t};o=[...bo,...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 xr=(R=>(R.Gemini31Pro="gemini-3.1-pro-preview",R.Gemini3FlashLite="gemini-3.1-flash-lite-preview",R.Gemini3Flash="gemini-3-flash-preview",R.Gemini3Pro="gemini-3.1-pro-preview",R.Gemini3ProImage="gemini-3-pro-image-preview",R.Gemini25Pro="gemini-2.5-pro",R.Gemini25Flash="gemini-2.5-flash",R.Gemini25FlashLite="gemini-2.5-flash-lite",R.Gemini20Flash="gemini-2.0-flash",R.Gemini20FlashLite="gemini-2.0-flash-lite",R.Gemini20ProExp="gemini-2.0-pro-exp-02-05",R.Gemini20FlashThinkingExp="gemini-2.0-flash-thinking-exp-01-21",R.Gemini1Pro="gemini-1.0-pro",R.Gemini15Flash="gemini-1.5-flash",R.Gemini15Flash002="gemini-1.5-flash-002",R.Gemini15Flash8B="gemini-1.5-flash-8b",R.Gemini15Pro="gemini-1.5-pro",R.GeminiFlashLatest="gemini-flash-latest",R.GeminiFlashLiteLatest="gemini-flash-lite-latest",R.GeminiProLatest="gemini-pro-latest",R))(xr||{}),Io=(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))(Io||{}),Co=(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))(Co||{}),To=(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))(To||{}),di=(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))(di||{}),Ul=["gemini-3.1-pro-preview","gemini-3.1-pro-preview-customtools","gemini-3.1-flash-lite-preview","gemini-3-flash-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 wo=[{name:"gemini-3.1-pro-preview",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2,completionTokenCostPer1M:12,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-3-flash-preview",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.5,completionTokenCostPer1M:3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-3.1-flash-lite-preview",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.25,completionTokenCostPer1M:1.5,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 Kt=s=>s.includes("gemini-3"),Bl=s=>s.includes("gemini-3")&&s.includes("pro"),Ro=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,Array.isArray(e.type)&&(e.type=e.type.includes("object")?"object":e.type[0]??"string"),e.properties&&typeof e.properties=="object"&&(e.properties=Object.fromEntries(Object.entries(e.properties).map(([t,n])=>[t,Ro(n)]))),e.items&&(e.items=Ro(e.items)),e},jl=[{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"}],gi=()=>structuredClone({model:"gemini-2.5-flash",embedModel:"text-embedding-005",safetySettings:jl,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},thinkingLevelMapping:{minimal:"minimal",low:"low",medium:"medium",high:"high",highest:"high"},...Re()}),ql=()=>structuredClone({model:"gemini-2.0-flash",embedModel:"text-embedding-005",safetySettings:jl,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},thinkingLevelMapping:{minimal:"minimal",low:"low",medium:"medium",high:"high",highest:"high"},...He()}),mi=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");let i=this.config.model;if(Kt(i)){if(this.config.thinking?.thinkingTokenBudget!==void 0&&typeof this.config.thinking.thinkingTokenBudget=="number")throw new Error(`Gemini 3 models (${i}) do not support numeric thinkingTokenBudget. Use thinkingLevel ('low', 'medium', 'high') instead, or pass thinkingTokenBudget as a string level via options.`);if(Bl(i)&&this.config.thinking?.thinkingLevel){let a=this.config.thinking.thinkingLevel;if(a!=="low"&&a!=="high")throw new Error(`Gemini 3 Pro (${i}) only supports thinkingLevel 'low' or 'high', got '${a}'. Use 'low' for less thinking or 'high' for more thinking.`)}}}tokensUsed;models;setModels(e){this.models=e}getEffectiveMappings(e){let t=this.models?.find(n=>n.model===e);return{thinkingLevelMapping:{...this.config.thinkingLevelMapping,...t?.thinkingLevelMapping??{}},thinkingTokenBudgetLevels:{...this.config.thinkingTokenBudgetLevels,...t?.thinkingTokenBudgetLevels??{}}}}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?"&":"?",b=typeof this.apiKey=="function"?await this.apiKey():this.apiKey;o.name+=`${x}key=${b}`}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 b=u[x];switch(b.role){case"user":{let R=Array.isArray(b.content)?b.content.map((A,w)=>{switch(A.type){case"text":return{text:A.text};case"image":return{inlineData:{mimeType:A.mimeType,data:A.image}};case"audio":return{inlineData:{mimeType:`audio/${A.format??"mp3"}`,data:A.data}};case"file":return"fileUri"in A?{fileData:{mimeType:A.mimeType,fileUri:A.fileUri}}:{inlineData:{mimeType:A.mimeType,data:A.data}};default:throw new Error(`Chat prompt content type not supported (index: ${w})`)}}):[{text:b.content}];l.push({role:"user",parts:R});break}case"assistant":{let R=[],A=b.thoughtBlocks,w=b.functionCalls&&b.functionCalls.length>0,v=A?.[0],F=A?.map(D=>D.data).join("")??"",O=v?.signature;if(F&&R.push({...w?{}:{thought:!0},text:F,...O&&!w?{thought_signature:O}:{}}),b.functionCalls){let D=b.functionCalls.map((U,L)=>{let T;if(typeof U.function.params=="string"){let E=U.function.params;if(E.trim().length===0)T={};else try{T=JSON.parse(E)}catch{throw new Error(`Failed to parse function params JSON: ${E}`)}}else T=U.function.params;let M={functionCall:{name:U.function.name,args:T}};return O&&L===0&&(M.thought_signature=O),M});R.push(...D)}if(b.content&&R.push({text:b.content}),R.length===0)throw new Error("Assistant content is empty");l.push({role:"model",parts:R});break}case"function":{let R=[],A=b,w=x;for(;;){if(!("functionId"in A))throw new Error(`Chat prompt functionId is empty (index: ${w})`);if(R.push({functionResponse:{name:A.functionId,response:{result:A.result}}}),w+1<u.length&&u[w+1].role==="function")w++,A=u[w];else break}x=w,l.push({role:"user",parts:R});break}default:throw new Error(`Invalid role: ${JSON.stringify(b)} (index: ${x})`)}}let c=[];if(e.functions&&e.functions.length>0){let x=e.functions.map(b=>{let R={type:"object",properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]},A=b.parameters?Ro(b.parameters):void 0;return A===void 0||A&&typeof A=="object"&&Object.keys(A).length===0?A={...R}:A&&typeof A=="object"&&A.type==="object"&&(!("properties"in A)||!A.properties||Object.keys(A.properties).length===0)&&(A={...A,properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]}),{name:b.name,description:b.description,parameters:A}});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,b=x?.enableWidget!==void 0?{enableWidget:x.enableWidget}:{};c.push({google_maps:b})}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&&Kt(n)&&(m.thinkingLevel=this.config.thinking.thinkingLevel),t?.thinkingTokenBudget){let x=this.getEffectiveMappings(n),b=x.thinkingTokenBudgetLevels;if(Kt(n)){let A=Bl(n),w=x.thinkingLevelMapping;if(t.thinkingTokenBudget==="none")m.thinkingLevel=w?.minimal??"minimal";else{let v=t.thinkingTokenBudget,F=w?.[v];F||(F=v==="highest"?"high":v),m.thinkingLevel=F}if(A&&m.thinkingLevel){let v=m.thinkingLevel;v!=="low"&&v!=="high"&&(m.thinkingLevel=v==="minimal"?"low":"high")}}else switch(t.thinkingTokenBudget){case"none":m.thinkingBudget=0,m.includeThoughts=!1,delete m.thinkingLevel;break;case"minimal":m.thinkingBudget=b?.minimal??200;break;case"low":m.thinkingBudget=b?.low??800;break;case"medium":m.thinkingBudget=b?.medium??5e3;break;case"high":m.thinkingBudget=b?.high??1e4;break;case"highest":m.thinkingBudget=b?.highest??24500;break}}m.thinkingLevel&&delete m.thinkingBudget,Kt(n)||delete m.thinkingLevel,Kt(n)&&delete m.thinkingBudget;let g=e.modelConfig?.maxTokens??this.config.maxTokens;if(m.thinkingLevel&&g!==void 0)throw new Error("Cannot set maxTokens when using thinkingLevel with Gemini models. When thinking is enabled, the model manages output tokens automatically. Remove the maxTokens setting or disable thinking.");t?.showThoughts!==void 0&&t?.thinkingTokenBudget!=="none"&&(m.includeThoughts=t.showThoughts);let f={maxOutputTokens:e.modelConfig?.maxTokens??this.config.maxTokens,temperature:e.modelConfig?.temperature??this.config.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(Kt(n)&&(f.temperature===void 0||f.temperature<1)&&(f.temperature=1),e.responseFormat){if(f.responseMimeType="application/json",e.responseFormat.type==="json_schema"&&e.responseFormat.schema){let x=e.responseFormat.schema.schema||e.responseFormat.schema;f.responseSchema=Ro(x)}}else this.config.responseFormat&&this.config.responseFormat==="json_object"&&(f.responseMimeType="application/json");let h=this.config.safetySettings;return[o,{contents:l,tools:c,toolConfig:p,systemInstruction:a,generationConfig:f,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(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 Ne("Content was blocked due to safety settings",void 0,void 0);case"RECITATION":throw new Ne("Content was blocked due to recitation policy",void 0,void 0);case"MALFORMED_FUNCTION_CALL":throw new Ne("Function call was malformed and blocked",void 0,void 0);case"UNEXPECTED_TOOL_CALL":throw new Ne("Unexpected tool call",void 0,void 0);case"FINISH_REASON_UNSPECIFIED":throw new Ne("Finish reason unspecified",void 0,void 0);case"BLOCKLIST":throw new Ne("Content was blocked due to blocklist",void 0,void 0);case"PROHIBITED_CONTENT":throw new Ne("Content was blocked due to prohibited content",void 0,void 0);case"SPII":throw new Ne("Content was blocked due to SPII",void 0,void 0);case"OTHER":throw new Ne("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:Ye(),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,...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 Ul.some(n=>t.includes(n)||n.includes(t))};buildCacheCreateOp=(e,t)=>{let n=e.model,r=t.contextCache?.ttlSeconds??3600,{systemInstruction:o,contents:i}=this.extractCacheableContent(e.chatPrompt);if(!o&&(!i||i.length===0))return;let a={model:this.isVertex?n:`models/${n}`,ttl:`${r}s`,displayName:`ax-cache-${Date.now()}`};o&&(a.systemInstruction=o),i&&i.length>0&&(a.contents=i);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 i=o;if(i?.name)return{name:i.name,expiresAt:i.expireTime,tokenCount:i.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:i,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,temperature:e.modelConfig?.temperature??this.config.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"};Kt(r)&&(u.temperature===void 0||u.temperature<1)&&(u.temperature=1);let c=this.config.safetySettings,p={contents:i,cachedContent:n,generationConfig:u,safetySettings:c};return a&&(p.systemInstruction=a),{apiConfig:l,request:p}};extractCacheableContent(e){let t,n=[],r=-1;for(let o=e.length-1;o>=0;o--){let i=e[o];if("cache"in i&&i.cache){r=o;break}}for(let o=0;o<e.length;o++){let i=e[o];if(i.role==="system"){t={role:"user",parts:[{text:i.content}]};continue}if(r>=0&&o<=r)if(i.role==="user"){let a=[];if(typeof i.content=="string")a.push({text:i.content});else if(Array.isArray(i.content))for(let l of i.content)switch(l.type){case"text":a.push({text:l.text});break;case"image":a.push({inlineData:{mimeType:l.mimeType,data:l.image}});break;case"audio":a.push({inlineData:{mimeType:`audio/${l.format??"mp3"}`,data:l.data}});break;case"file":"fileUri"in l?a.push({fileData:{mimeType:l.mimeType,fileUri:l.fileUri}}):a.push({inlineData:{mimeType:l.mimeType,data:l.data}});break}a.length>0&&n.push({role:"user",parts:a})}else i.role==="assistant"&&i.content&&n.push({role:"model",parts:[{text:i.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 i of r.content)if(!("cache"in i&&i.cache))switch(i.type){case"text":o.push({text:i.text});break;case"image":o.push({inlineData:{mimeType:i.mimeType,data:i.image}});break;case"audio":o.push({inlineData:{mimeType:`audio/${i.format??"mp3"}`,data:i.data}});break;case"file":"fileUri"in i?o.push({fileData:{mimeType:i.mimeType,fileUri:i.fileUri}}):o.push({inlineData:{mimeType:i.mimeType,data:i.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 i of r.functionCalls){let a;if(typeof i.function.params=="string")try{a=JSON.parse(i.function.params)}catch{a={}}else a=i.function.params??{};o.push({functionCall:{name:i.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}}},hn=class s extends je{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={...gi(),...o},m=new mi(d,u,r,e,i);l=[...wo,...l??[]];let g=h=>{let y=lt({model:h,modelInfo:l,models:a});return{functions:!0,streaming:!0,hasThinkingBudget:y?.supported?.thinkingBudget??!1,hasShowThoughts:y?.supported?.showThoughts??!1,structuredOutputs:y?.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(h),types:["persistent"]},thinking:y?.supported?.thinkingBudget??!1,multiTurn:!0}},f=a?.map(h=>{let y=h,x=y?.config;if(!x)return h;let b={};x.maxTokens!==void 0&&(b.maxTokens=x.maxTokens),x.temperature!==void 0&&(b.temperature=x.temperature),x.topP!==void 0&&(b.topP=x.topP),x.topK!==void 0&&(b.topK=x.topK),x.presencePenalty!==void 0&&(b.presencePenalty=x.presencePenalty),x.frequencyPenalty!==void 0&&(b.frequencyPenalty=x.frequencyPenalty),x.stopSequences!==void 0&&(b.stopSequences=x.stopSequences),x.endSequences!==void 0&&(b.endSequences=x.endSequences),x.stream!==void 0&&(b.stream=x.stream),x.n!==void 0&&(b.n=x.n);let R={...y};Object.keys(b).length>0&&(R.modelConfig={...y.modelConfig??{},...b});let A=x.thinking?.thinkingTokenBudget;if(typeof A=="number"){let w=d.thinkingTokenBudgetLevels,v=[["minimal",w?.minimal??200],["low",w?.low??800],["medium",w?.medium??5e3],["high",w?.high??1e4],["highest",w?.highest??24500]],F="minimal",O=Number.POSITIVE_INFINITY;for(let[D,U]of v){let L=Math.abs(A-U);L<O&&(O=L,F=D)}R.thinkingTokenBudget=F}return x.thinking?.includeThoughts!==void 0&&(R.showThoughts=!!x.thinking.includeThoughts),x.thinkingLevelMapping&&(R.thinkingLevelMapping=x.thinkingLevelMapping),x.thinkingTokenBudgetLevels&&(R.thinkingTokenBudgetLevels=x.thinkingTokenBudgetLevels),R});f?m.setModels(f):a&&m.setModels(a),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 Hp=new rt,xn=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(Hp.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 Ar=(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))(Ar||{});var vo=[{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 Kp=()=>structuredClone({model:"llama-3.3-70b-versatile",...Re()}),An=class extends Ue{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("Groq API key not set");let i={...Kp(),...t},a={...n,streamingUsage:!1};o=[...vo,...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 xn(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 So=[];var ko=(e=>(e.MetaLlama270BChatHF="meta-llama/Llama-2-70b-chat-hf",e))(ko||{});var hi=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...Re()}),zl=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...He()}),fi=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)}s(r)}};var ge={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"},dt={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"},ti=(r=>(r.COMPLETION="completion",r.CHAT="chat",r.RERANK="rerank",r.UNKNOWN="unknown",r))(ti||{}),ni=(o=>(o.WORKFLOW="workflow",o.TASK="task",o.AGENT="agent",o.TOOL="tool",o.UNKNOWN="unknown",o))(ni||{});var ri=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()}},lo=class extends TransformStream{constructor(e,t){super(new ri(e,t))}};function uo(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 dl=(s,e,t,n)=>{let r=n?s.filter(i=>i.role!=="system"):[...s];t({name:"ChatRequestChatPrompt",step:e,value:r})};var ml=(s,e)=>{if(!s.results)return;let t={name:"ChatResponseResults",value:s.results};e(t)};function gl(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?uo(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 fl=(s,e)=>{e({name:"FunctionResults",value:s})},oi=(s,e,t,n)=>{n({name:"FunctionError",index:e,fixingInstructions:t,error:s})},hl=(s,e,t,n)=>{n({name:"ValidationError",index:e,fixingInstructions:t,error:s})},xl=(s,e,t,n)=>{n({name:"AssertionError",index:e,fixingInstructions:t,error:s})},Al=(s,e,t)=>{t({name:"RefusalError",index:e,error:s})};var yl=(s,e,t)=>{t({name:"EmbedRequest",embedModel:e,value:s})},bl=(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)},Il=(s,e,t,n)=>{n({name:"ResultPickerUsed",sampleCount:s,selectedIndex:e,latency:t})};var po=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},Ut=(...s)=>{let e={};for(let t of s)t&&Object.assign(e,t);return e},co,Cl=s=>{if(co)return co;if(s)return co=ud(s),co};var ud=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)"}),cacheReadTokensCounter:s.createCounter("ax_llm_cache_read_tokens_total",{description:"Total number of tokens read from cache (prompt caching)"}),cacheWriteTokensCounter:s.createCounter("ax_llm_cache_write_tokens_total",{description:"Total number of tokens written to cache (prompt caching)"})}),Tl=(s,e,t,n,r,o)=>{try{if(s.latencyHistogram){let i=po({operation:e,ai_service:n,...r?{model:r}:{},...o});s.latencyHistogram.record(t,i)}}catch(i){console.warn("Failed to record latency metric:",i)}},wl=(s,e,t,n,r,o,i,a)=>{let l={operation:e,ai_service:o,...i?{model:i}:{},...a};s.meanLatencyGauge&&s.meanLatencyGauge.record(t,l),s.p95LatencyGauge&&s.p95LatencyGauge.record(n,l),s.p99LatencyGauge&&s.p99LatencyGauge.record(r,l)},Rl=(s,e,t,n,r)=>{try{if(s.errorCounter){let o=po({operation:e,ai_service:t,...n?{model:n}:{},...r});s.errorCounter.add(1,o)}}catch(o){console.warn("Failed to record error metric:",o)}},vl=(s,e,t,n,r,o)=>{s.errorRateGauge&&s.errorRateGauge.record(t*100,{operation:e,ai_service:n,...r?{model:r}:{},...o})},Sl=(s,e,t,n,r)=>{s.requestCounter&&s.requestCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{},...r})},lr=(s,e,t,n,r,o)=>{try{let i=po({ai_service:n,...r?{model:r}:{},...o});s.tokenCounter&&s.tokenCounter.add(t,{token_type:e,...i}),e==="input"&&s.inputTokenCounter&&s.inputTokenCounter.add(t,i),e==="output"&&s.outputTokenCounter&&s.outputTokenCounter.add(t,i)}catch(i){console.warn("Failed to record token metric:",i)}},kl=(s,e,t,n,r,o)=>{t&&s.streamingRequestsCounter&&s.streamingRequestsCounter.add(1,{operation:e,ai_service:n,...r?{model:r}:{},...o})},Ol=(s,e,t,n,r,o)=>{let i={function_name:e,...n?{ai_service:n}:{},...r?{model:r}:{},...o};s.functionCallsCounter&&s.functionCallsCounter.add(1,i),t&&s.functionCallLatencyHistogram&&s.functionCallLatencyHistogram.record(t,i)},si=(s,e,t,n,r,o)=>{s.requestSizeHistogram&&s.requestSizeHistogram.record(t,{operation:e,ai_service:n,...r?{model:r}:{},...o})},ii=(s,e,t,n,r,o)=>{s.responseSizeHistogram&&s.responseSizeHistogram.record(t,{operation:e,ai_service:n,...r?{model:r}:{},...o})},Ml=(s,e,t,n,r,o)=>{let i={...n?{ai_service:n}:{},...r?{model:r}:{},...o};e!==void 0&&s.temperatureGauge&&s.temperatureGauge.record(e,i),t!==void 0&&s.maxTokensGauge&&s.maxTokensGauge.record(t,i)},ai=(s,e,t,n,r,o)=>{s.estimatedCostCounter&&s.estimatedCostCounter.add(t,{operation:e,ai_service:n,...r?{model:r}:{},...o})},El=(s,e,t,n,r)=>{s.promptLengthHistogram&&s.promptLengthHistogram.record(e,{ai_service:t,...n?{model:n}:{},...r})},Pl=(s,e,t,n,r)=>{s.contextWindowUsageGauge&&s.contextWindowUsageGauge.record(e,{ai_service:t,...n?{model:n}:{},...r})},Fl=(s,e,t,n,r)=>{s.timeoutsCounter&&s.timeoutsCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{},...r})},_l=(s,e,t,n,r)=>{s.abortsCounter&&s.abortsCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{},...r})},Nl=(s,e,t,n,r)=>{s.thinkingBudgetUsageCounter&&s.thinkingBudgetUsageCounter.add(e,{ai_service:t,...n?{model:n}:{},...r})},$l=(s,e,t,n,r,o)=>{(e||t)&&s.multimodalRequestsCounter&&s.multimodalRequestsCounter.add(1,{ai_service:n,has_images:e.toString(),has_audio:t.toString(),...r?{model:r}:{},...o})},li=(s,e,t,n,r,o)=>{try{if(t<=0)return;let i=po({ai_service:n,...r?{model:r}:{},...o});e==="read"&&s.cacheReadTokensCounter&&s.cacheReadTokensCounter.add(t,i),e==="write"&&s.cacheWriteTokensCounter&&s.cacheWriteTokensCounter.add(t,i)}catch(i){console.warn("Failed to record cache token metric:",i)}};function Ll(s){try{return JSON.stringify(s,null,2)}catch{return String(s)}}function mt(s,e={}){let t=[s];throw e.fieldPath!==void 0&&t.push(`Field: ${e.fieldPath}`),e.value!==void 0&&t.push(`Value: ${Ll(e.value)}`),e.note&&t.push(`Note: ${e.note}`),e.item!==void 0&&t.push(`Chat item: ${Ll(e.item)}`),new Error(t.join(`
168
+ `))}function nn(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&&mt("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"&&mt("Assistant message content must be a string",{fieldPath:"content",value:n,item:s}),r!==void 0&&!Array.isArray(r)&&mt("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")&&mt("functionCalls entry must be an object",{fieldPath:`functionCalls[${u}]`,value:c,item:s}),(!("id"in c)||typeof c.id!="string"||c.id.trim()==="")&&mt("functionCalls entry must include a non-empty string id",{fieldPath:`functionCalls[${u}].id`,value:c.id,item:s}),(!("type"in c)||c.type!=="function")&&mt("functionCalls entry must have type 'function'",{fieldPath:`functionCalls[${u}].type`,value:c.type,item:s}),!("function"in c)||!c.function)mt("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()==="")&&mt("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"&&mt("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()==="")&&mt("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"&&mt("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 mo(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 ui=new Map;function cd(s){return`${s.providerName}:${s.contentHash}`}function pd(s,e){e.type==="text"?s.update(`text:${e.text}`):e.type==="image"?s.update(`image:${e.mimeType}:${e.image.slice(0,100)}`):e.type==="audio"?s.update(`audio:${e.format}:${e.data.slice(0,100)}`):e.type==="file"&&("fileUri"in e?s.update(`file:${e.mimeType}:${e.fileUri}`):s.update(`file:${e.mimeType}:${e.data.slice(0,100)}`))}function dd(s){let e=Ze("sha256"),t=-1;for(let n=s.length-1;n>=0;n--){let r=s[n];if("cache"in r&&r.cache){t=n;break}}for(let n=0;n<s.length;n++){let r=s[n];if(r.role==="system"){e.update(`system:${r.content}`);continue}if(t>=0&&n<=t)if(r.role==="user"){if(typeof r.content=="string")e.update(`user:${r.content}`);else if(Array.isArray(r.content))for(let o of r.content)pd(e,o)}else r.role==="assistant"&&r.content&&e.update(`assistant:${r.content}`)}return e.digest("hex")}var be=()=>structuredClone({temperature:0}),Ne=()=>structuredClone({temperature:.4,frequencyPenalty:.2}),_e=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??ce.tracer,this.meter=a.meter??ce.meter,this.modelInfo=o,this.models=u,this.id=Ge();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&&md(u)}#e=!1;#t=!1;rt;fetch;tracer;meter;timeout;excludeContentFromTrace;models;abortSignal;logger=ce.logger??cl;corsProxy;retry;customLabels;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 Cl(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??ce.debug??!1,this.#t=e.verbose??!1,this.rt=e.rateLimiter,this.fetch=e.fetch,this.timeout=e.timeout,this.tracer=e.tracer??ce.tracer,this.meter=e.meter??ce.meter,this.excludeContentFromTrace=e.excludeContentFromTrace,this.abortSignal=e.abortSignal,this.logger=e.logger??ce.logger??this.logger,this.corsProxy=e.corsProxy,this.retry=e.retry,this.customLabels=e.customLabels}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,customLabels:this.customLabels}}getLogger(){return this.logger}getMergedCustomLabels(e){return Ut(ce.customLabels,this.customLabels,e)}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,n){let r=this.metrics.latency[e];r.samples.push(t),r.samples.length>1e3&&r.samples.shift(),r.mean=r.samples.reduce((i,a)=>i+a,0)/r.samples.length,r.p95=this.calculatePercentile(r.samples,95),r.p99=this.calculatePercentile(r.samples,99);let o=this.getMetricsInstruments();if(o){let i=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel,a=this.getMergedCustomLabels(n);Tl(o,e,t,this.name,i,a),wl(o,e,r.mean,r.p95,r.p99,this.name,i,a)}}updateErrorMetrics(e,t,n){let r=this.metrics.errors[e];r.total++,t&&r.count++,r.rate=r.count/r.total;let o=this.getMetricsInstruments();if(o){let i=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel,a=this.getMergedCustomLabels(n);Sl(o,e,this.name,i,a),t&&Rl(o,e,this.name,i,a),vl(o,e,r.rate,this.name,i,a)}}recordTokenUsage(e,t){let n=this.getMetricsInstruments();if(n&&e?.tokens){let{promptTokens:r,completionTokens:o,totalTokens:i,thoughtsTokens:a,cacheReadTokens:l,cacheCreationTokens:u}=e.tokens,c=this.getMergedCustomLabels(t);r&&lr(n,"input",r,this.name,e.model,c),o&&lr(n,"output",o,this.name,e.model,c),i&&lr(n,"total",i,this.name,e.model,c),a&&lr(n,"thoughts",a,this.name,e.model,c),l&&li(n,"read",l,this.name,e.model,c),u&&li(n,"write",u,this.name,e.model,c)}}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,n){let r=this.getMetricsInstruments();if(!(!r||!e))for(let o of e)o&&typeof o=="object"&&"function"in o&&o.function&&typeof o.function=="object"&&"name"in o.function&&Ol(r,o.function.name,void 0,this.name,t,this.getMergedCustomLabels(n))}recordTimeoutMetric(e,t){let n=this.getMetricsInstruments();if(n){let r=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;Fl(n,e,this.name,r,this.getMergedCustomLabels(t))}}recordAbortMetric(e,t){let n=this.getMetricsInstruments();if(n){let r=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;_l(n,e,this.name,r,this.getMergedCustomLabels(t))}}recordChatMetrics(e,t,n){let r=this.getMetricsInstruments();if(!r)return;let o=this.lastUsedChatModel,i=this.lastUsedModelConfig,a=this.getMergedCustomLabels(t?.customLabels),l=i?.stream??!1;kl(r,"chat",l,this.name,o,a);let{hasImages:u,hasAudio:c}=this.detectMultimodalContent(e);$l(r,u,c,this.name,o,a);let p=this.calculatePromptLength(e);El(r,p,this.name,o,a),Ml(r,i?.temperature,i?.maxTokens,this.name,o,a),t?.thinkingTokenBudget&&this.modelUsage?.tokens?.thoughtsTokens&&Nl(r,this.modelUsage.tokens.thoughtsTokens,this.name,o,a);let d=this.calculateRequestSize(e);if(si(r,"chat",d,this.name,o,a),n&&!l){let m=n,g=this.calculateResponseSize(m);if(ii(r,"chat",g,this.name,o,a),m.results)for(let A of m.results)A.functionCalls&&this.recordFunctionCallMetrics(A.functionCalls,this.lastUsedChatModel,a);let f=this.calculateContextWindowUsage(this.lastUsedChatModel,m.modelUsage);f>0&&Pl(r,f,this.name,o,a);let h=this.estimateCost(this.lastUsedChatModel,m.modelUsage);h>0&&ai(r,"chat",h,this.name,o,a)}}recordEmbedMetrics(e,t,n){let r=this.getMetricsInstruments();if(!r)return;let o=this.lastUsedEmbedModel,i=this.getMergedCustomLabels(n?.customLabels),a=this.calculateRequestSize(e);si(r,"embed",a,this.name,o,i);let l=this.calculateResponseSize(t);ii(r,"embed",l,this.name,o,i);let u=this.estimateCostByName(o,t.modelUsage);u>0&&ai(r,"embed",u,this.name,o,i)}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",l?.customLabels):(u.message.includes("abort")||u.name==="AbortError")&&this.recordAbortMetric("chat",l?.customLabels)),u}finally{let u=performance.now()-n;this.updateLatencyMetrics("chat",u,l?.customLabels),this.updateErrorMetrics("chat",r,l?.customLabels),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)nn(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:Ve.SERVER,attributes:{[ge.LLM_SYSTEM]:this.name,[ge.LLM_OPERATION_NAME]:"chat",[ge.LLM_REQUEST_MODEL]:n,[ge.LLM_REQUEST_MAX_TOKENS]:o.maxTokens??"Not set",[ge.LLM_REQUEST_TEMPERATURE]:o.temperature,[ge.LLM_REQUEST_TOP_P]:o.topP??"Not set",[ge.LLM_REQUEST_TOP_K]:o.topK??"Not set",[ge.LLM_REQUEST_FREQUENCY_PENALTY]:o.frequencyPenalty??"Not set",[ge.LLM_REQUEST_PRESENCE_PENALTY]:o.presencePenalty??"Not set",[ge.LLM_REQUEST_STOP_SEQUENCES]:o.stopSequences?.join(", ")??"Not set",[ge.LLM_REQUEST_LLM_IS_STREAMING]:o.stream??"Not set"}},t?.traceContext??Pt.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(b=>this.cleanupFunctionSchema(b)));let u={...n,model:e,functions:l,modelConfig:t};this.lastUsedChatModel=e,this.lastUsedModelConfig=t,i&&dl(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(b=>{if(b.role==="assistant"){let{content:C,name:I,cache:v}=b;return{role:"assistant",content:C,name:I,cache:v}}return b.role==="function"?{role:"user",content:b.result}:b}),functions:[]}:u,g=await this.handleContextCaching(e,m,r,o),f=async()=>{if(g?.preparedRequest){let{apiConfig:v,request:O}=g.preparedRequest;return o?.isRecording()&&Dl(n,o,this.excludeContentFromTrace),await Be({name:v.name,url:this.apiURL,localCall:v.localCall,headers:await this.buildHeaders(v.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},O)}let[b,C]=await this.aiImpl.createChatReq(m,r);return o?.isRecording()&&Dl(n,o,this.excludeContentFromTrace),await Be({name:b.name,url:this.apiURL,localCall:b.localCall,headers:await this.buildHeaders(b.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},C)},h=r?.rateLimiter??this.rt,A=h?await h(f,{modelUsage:this.modelUsage}):await f();if(t.stream){if(!this.aiImpl.createChatStreamResp)throw new Error("createChatStreamResp not implemented");let b=this.aiImpl.createChatStreamResp.bind(this),C=k=>S=>{let $=b(S,k);if($.sessionId=r?.sessionId,!$.modelUsage){let G=this.aiImpl.getTokenUsage();G&&($.modelUsage={ai:this.name,model:e,tokens:G})}return this.modelUsage=$.modelUsage,this.recordTokenUsage($.modelUsage,r?.customLabels),o?.isRecording()&&Gl($,o,this.excludeContentFromTrace),$},I=async k=>{o?.isRecording()&&o.end(),i&&gl(k,r?.logger??this.logger)};if(typeof window<"u"){let k=A,S={},$=[],G=r?.abortSignal??this.abortSignal;return new ReadableStream({start:L=>{let w=k.getReader(),R=()=>{try{w.cancel().catch(()=>{})}catch{}try{this.recordAbortMetric("chat",r?.customLabels)}catch{}try{o?.isRecording()&&o.end()}catch{}try{L.error(new DOMException("Aborted","AbortError"))}catch{L.error(new Error("Aborted"))}};if(G){if(G.aborted){R();return}G.addEventListener("abort",R,{once:!0})}async function E(){try{for(;;){let{done:_,value:M}=await w.read();if(_){I&&await I($),L.close();break}let N=C(S)(M);N&&($.push(N),L.enqueue(N))}}catch(_){if(L.error(_),o?.isRecording())try{o.end()}catch{}}finally{if(w.releaseLock(),G)try{G.removeEventListener("abort",R)}catch{}}}E()}})}return A.pipeThrough(new lo(C({}),I))}if(!this.aiImpl.createChatResp)throw new Error("createChatResp not implemented");let x=this.aiImpl.createChatResp(A);if(x.sessionId=r?.sessionId,!x.modelUsage){let b=this.aiImpl.getTokenUsage();b&&(x.modelUsage={ai:this.name,model:e,tokens:b})}return x.modelUsage&&(this.modelUsage=x.modelUsage,this.recordTokenUsage(x.modelUsage,r?.customLabels)),o?.isRecording()&&(Gl(x,o,this.excludeContentFromTrace),o.end()),i&&ml(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",a?.customLabels):(l.message.includes("abort")||l.name==="AbortError")&&this.recordAbortMetric("embed",a?.customLabels)),l}finally{let l=performance.now()-n;this.updateLatencyMetrics("embed",l,a?.customLabels),this.updateErrorMetrics("embed",r,a?.customLabels),!r&&o&&this.recordEmbedMetrics(e,o,a)}}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:Ve.SERVER,attributes:{[ge.LLM_SYSTEM]:this.name,[ge.LLM_OPERATION_NAME]:"embeddings",[ge.LLM_REQUEST_MODEL]:n}},t?.traceContext??Pt.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&&yl(l.texts??[],e,n?.logger??this.logger);let u=async()=>{let[m,g]=await o(l);return await Be({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,n?.customLabels),r?.isRecording()&&d.modelUsage?.tokens&&r.addEvent(dt.GEN_AI_USAGE,{[ge.LLM_USAGE_INPUT_TOKENS]:d.modelUsage.tokens.promptTokens,[ge.LLM_USAGE_OUTPUT_TOKENS]:d.modelUsage.tokens.completionTokens??0,[ge.LLM_USAGE_TOTAL_TOKENS]:d.modelUsage.tokens.totalTokens}),i&&bl(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 i=this.aiImpl.supportsContextCache?.(e)??!1,a=this.aiImpl.supportsImplicitCaching?.(e)??!1;if(!i&&!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(!i)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=dd(t.chatPrompt);if(!p||p===Ze("sha256").digest("hex"))return null;let d={providerName:this.getName(),contentHash:p},m=cd(d),g=Date.now(),f=o.registry,h=f?await f.get(m):ui.get(m);if(h&&h.expiresAt>g){if(h.expiresAt-g<u*1e3&&this.aiImpl.buildCacheUpdateTTLOp){await this.executeCacheOperation(this.aiImpl.buildCacheUpdateTTLOp(h.cacheName,l),n,r);let C={cacheName:h.cacheName,expiresAt:g+l*1e3,tokenCount:h.tokenCount};f?await f.set(m,C):ui.set(m,{...C,contentHash:p,lastTouchedAt:g})}return this.useCacheByName(e,t,h.cacheName,n,r)}if(this.estimateCacheableTokens(t.chatPrompt)<c)return null;let x=this.aiImpl.buildCacheCreateOp?.(t,n);if(x){let b=await this.executeCacheOperation(x,n,r);if(b){let C={cacheName:b.name,expiresAt:new Date(b.expiresAt).getTime(),tokenCount:b.tokenCount};return f?await f.set(m,C):ui.set(m,{...C,contentHash:p,lastTouchedAt:g}),this.useCacheByName(e,t,b.name,n,r)}}return null}async useCacheByName(e,t,n,r,o){if(this.aiImpl.prepareCachedChatReq){let i=await this.aiImpl.prepareCachedChatReq(t,r??{},n);return{preparedRequest:{apiConfig:i.apiConfig,request:i.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 Be({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 Dl(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(dt.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(dt.GEN_AI_ASSISTANT_MESSAGE,a)}else if(o.content){let a={};t||(a.content=o.content),e.addEvent(dt.GEN_AI_ASSISTANT_MESSAGE,a)}break}case"function":{let i={id:o.functionId};t||(i.content=o.result),e.addEvent(dt.GEN_AI_TOOL_MESSAGE,i);break}}let r={};t||(r.content=n.join(`
169
+ `)),e.addEvent(dt.GEN_AI_USER_MESSAGE,r)}function Gl(s,e,t){if(s.modelUsage?.tokens){let n=s.modelUsage.tokens.thoughtsTokens?{[ge.LLM_USAGE_THOUGHTS_TOKENS]:s.modelUsage.tokens.thoughtsTokens}:{};e.addEvent(dt.GEN_AI_USAGE,{[ge.LLM_USAGE_INPUT_TOKENS]:s.modelUsage.tokens.promptTokens,[ge.LLM_USAGE_OUTPUT_TOKENS]:s.modelUsage.tokens.completionTokens??0,[ge.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(dt.GEN_AI_CHOICE,{finish_reason:r.finishReason,index:n,message:JSON.stringify(i,null,2)})}}function Ul(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 md(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 ur=(h=>(h.Claude46Opus="claude-opus-4-6",h.Claude46Sonnet="claude-sonnet-4-6",h.Claude45Opus="claude-opus-4-5-20251101",h.Claude41Opus="claude-opus-4-1-20250805",h.Claude4Opus="claude-opus-4-20250514",h.Claude4Sonnet="claude-sonnet-4-20250514",h.Claude45Sonnet="claude-sonnet-4-5-20250929",h.Claude45Haiku="claude-haiku-4-5",h.Claude37Sonnet="claude-3-7-sonnet-latest",h.Claude35Sonnet="claude-3-5-sonnet-latest",h.Claude35Haiku="claude-3-5-haiku-latest",h.Claude3Opus="claude-3-opus-latest",h.Claude3Sonnet="claude-3-sonnet-20240229",h.Claude3Haiku="claude-3-haiku-20240307",h.Claude21="claude-2.1",h.ClaudeInstant12="claude-instant-1.2",h))(ur||{}),cr=(g=>(g.Claude46Opus="claude-opus-4-6",g.Claude46Sonnet="claude-sonnet-4-6",g.Claude45Opus="claude-opus-4-5@20251101",g.Claude41Opus="claude-opus-4-1@20250805",g.Claude4Opus="claude-opus-4@20250514",g.Claude45Sonnet="claude-sonnet-4-5@20250929",g.Claude4Sonnet="claude-sonnet-4@20250514",g.Claude37Sonnet="claude-3-7-sonnet@20250219",g.Claude35SonnetV2="claude-3-5-sonnet-v2@20241022",g.Claude45Haiku="claude-haiku-4-5@20251001",g.Claude35Haiku="claude-3-5-haiku@20241022",g.Claude35Sonnet="claude-3-5-sonnet@20240620",g.Claude3Opus="claude-3-opus@20240229",g.Claude3Haiku="claude-3-haiku@20240307",g))(cr||{});var pr=[{name:"claude-opus-4-6",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:25,maxTokens:128e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-6",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:25,maxTokens:128e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4-6",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4-6",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,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-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 Ft=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)return e;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,Ft(r)]))),e.items&&(e.items=Ft(e.items)),Array.isArray(e.anyOf)&&(e.anyOf=e.anyOf.map(n=>Ft(n))),Array.isArray(e.allOf)&&(e.allOf=e.allOf.map(n=>Ft(n))),Array.isArray(e.oneOf)&&(e.oneOf=e.oneOf.map(n=>Ft(n))),e},pi=()=>structuredClone({model:"claude-3-7-sonnet-latest",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},effortLevelMapping:{minimal:"low",low:"low",medium:"medium",high:"high",highest:"max"},...be()}),jl=()=>structuredClone({model:"claude-3-7-sonnet@20250219",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},effortLevelMapping:{minimal:"low",low:"low",medium:"medium",high:"high",highest:"max"},...be()}),ci=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.some(E=>"cache"in E&&E.cache)||e.functions?.some(E=>E.cache),l=e.chatPrompt.filter(E=>E.role==="system"),u=l.map((E,_)=>({type:"text",text:E.content,...E.cache||a&&_===l.length-1?{cache_control:{type:"ephemeral"}}:{}})),c=e.chatPrompt.filter(E=>E.role!=="system"),p=e.functions?.map((E,_,M)=>{let N={type:"object",properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]},q=E.parameters?Ft(E.parameters):void 0;return q===void 0||q&&typeof q=="object"&&Object.keys(q).length===0?q={...N}:q&&typeof q=="object"&&q.type==="object"&&(!("properties"in q)||!q.properties||Object.keys(q.properties).length===0)&&(q={...q,properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]}),{name:E.name,description:E.description,input_schema:q,...E.cache||a&&_===M.length-1?{cache_control:{type:"ephemeral"}}:{}}}),m=(this.config.tools??[]).map(E=>E&&typeof E=="object"&&"type"in E?E:{name:E.name,description:E.description,input_schema:E.input_schema?Ft(E.input_schema):void 0,...E.cache_control?{cache_control:E.cache_control}:{}}),g=[...p??[],...m];g.length===0&&(g=void 0);let f=e.modelConfig?.maxTokens??this.config.maxTokens,h=e.modelConfig?.stopSequences??this.config.stopSequences,A=e.modelConfig?.temperature,x=e.modelConfig?.topP,b=e.modelConfig?.topK??this.config.topK,C=e.modelConfig?.n??this.config.n;if(C&&C>1)throw new Error("Anthropic does not support sampling (n > 1)");let I=E=>E.includes("claude-opus-4-6"),v=E=>E.includes("claude-opus-4-5"),O,k,S=n;if(t?.thinkingTokenBudget){let E=this.config.thinkingTokenBudgetLevels,_=this.config.effortLevelMapping;if(t.thinkingTokenBudget==="none")O=void 0,k=void 0;else{let M=t.thinkingTokenBudget;if(I(S))O={type:"adaptive"},k={effort:_?.[M]??"medium"};else if(v(S)){O={type:"enabled",budget_tokens:E?.[M]??1e4};let q=_?.[M]??"medium";q==="max"&&(q="high"),k={effort:q}}else O={type:"enabled",budget_tokens:E?.[M]??1e4}}}let G=gd(c,!!O);G.some(E=>E.role==="assistant"&&Array.isArray(E.content)&&E.content.length>0&&E.content[0]?.type==="tool_use")&&(O=void 0,k=void 0);let w;if(this.usedStructuredOutput=!1,e.responseFormat&&e.responseFormat.type==="json_schema"&&e.responseFormat.schema){let E=e.responseFormat.schema.schema||e.responseFormat.schema;w={type:"json_schema",schema:Ft(E)},this.usedStructuredOutput=!0}let R={...this.isVertex?{anthropic_version:"vertex-2023-10-16"}:{model:n},...f?{max_tokens:f}:{},...h&&h.length>0?{stop_sequences:h}:{},...A!==void 0&&!O?{temperature:A}:{},...x!==void 0&&(!O||x>=.95)?{top_p:x}:{},...b&&!O?{top_k:b}:{},...i,...g?{tools:g}:{},...r?{stream:!0}:{},...u?{system:u}:{},...O?{thinking:O}:{},...k?{output_config:k}:{},...w?{output_format:w}:{},messages:G};return[o,R]};createChatResp=e=>{if(e.type==="error")throw new Se(e.error.message,void 0,void 0);let t=Bl(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 Se(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:Bl(o.stop_reason)}]}}return{results:[{index:r,content:""}]}};supportsImplicitCaching=()=>!0},rn=class s extends _e{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={...pi(),...r},p=new ci(c,a),d=g=>{let f=tt({model:g,modelInfo:pr,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"],cacheBreakpoints:!1},thinking:f?.supported?.thinkingBudget??!1,multiTurn:!0}},m=i?.map(g=>{let f=g,h=f?.config;if(!h)return g;let A={};h.maxTokens!==void 0&&(A.maxTokens=h.maxTokens),h.temperature!==void 0&&(A.temperature=h.temperature),h.topP!==void 0&&(A.topP=h.topP),h.topK!==void 0&&(A.topK=h.topK),h.presencePenalty!==void 0&&(A.presencePenalty=h.presencePenalty),h.frequencyPenalty!==void 0&&(A.frequencyPenalty=h.frequencyPenalty),h.stopSequences!==void 0&&(A.stopSequences=h.stopSequences),h.endSequences!==void 0&&(A.endSequences=h.endSequences),h.stream!==void 0&&(A.stream=h.stream),h.n!==void 0&&(A.n=h.n);let x={...f};Object.keys(A).length>0&&(x.modelConfig={...f.modelConfig??{},...A});let b=h.thinking?.thinkingTokenBudget;if(typeof b=="number"){let C=c.thinkingTokenBudgetLevels,I=[["minimal",C?.minimal??1024],["low",C?.low??5e3],["medium",C?.medium??1e4],["high",C?.high??2e4],["highest",C?.highest??32e3]],v="minimal",O=Number.POSITIVE_INFINITY;for(let[k,S]of I){let $=Math.abs(b-S);$<O&&(O=$,v=k)}x.thinkingTokenBudget=v}return h.thinking?.includeThoughts!==void 0&&(x.showThoughts=!!h.thinking.includeThoughts),x});super(p,{name:"Anthropic",apiURL:l,headers:u,modelInfo:pr,defaults:{model:c.model},options:o,supportFor:d,models:m??i})}};function gd(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,...r.cache?{cache_control:{type:"ephemeral"}}:{}}:{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});if(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])),r.cache){if(typeof o=="string")o=[{type:"text",text:o,cache_control:{type:"ephemeral"}}];else if(Array.isArray(o)&&o.length>0){let l=o.length-1,u=o[l];u&&u.type==="text"&&(o[l]={...u,cache_control:{type:"ephemeral"}})}}return{role:"assistant",content:o}}default:throw new Error("Invalid role")}}),n=fd(t);return hd(n)}function fd(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 hd(s){return s.map(e=>e.role==="assistant"&&typeof e.content=="string"?{...e,content:e.content.replace(/\s+$/,"")}:e)}function Bl(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 dr=(N=>(N.GPT4="gpt-4",N.GPT41="gpt-4.1",N.GPT41Mini="gpt-4.1-mini",N.GPT41Nano="gpt-4.1-nano",N.GPT4O="gpt-4o",N.GPT4OMini="gpt-4o-mini",N.GPT4ChatGPT4O="chatgpt-4o-latest",N.GPT4Turbo="gpt-4-turbo",N.GPT35Turbo="gpt-3.5-turbo",N.GPT35TurboInstruct="gpt-3.5-turbo-instruct",N.GPT35TextDavinci002="text-davinci-002",N.GPT3TextBabbage002="text-babbage-002",N.GPT3TextAda001="text-ada-001",N.GPT5="gpt-5",N.GPT5Nano="gpt-5-nano",N.GPT5Mini="gpt-5-mini",N.GPT5Chat="gpt-5-chat",N.GPT5ChatLatest="gpt-5-chat-latest",N.GPT5Codex="gpt-5-codex",N.GPT5Pro="gpt-5-pro",N.GPT51="gpt-5.1",N.GPT51ChatLatest="gpt-5.1-chat-latest",N.GPT51Codex="gpt-5.1-codex",N.GPT51CodexMini="gpt-5.1-codex-mini",N.GPT51CodexMax="gpt-5.1-codex-max",N.GPT52="gpt-5.2",N.GPT52ChatLatest="gpt-5.2-chat-latest",N.GPT52Codex="gpt-5.2-codex",N.GPT52Pro="gpt-5.2-pro",N.O1="o1",N.O1Mini="o1-mini",N.O3="o3",N.O3Mini="o3-mini",N.O4Mini="o4-mini",N))(dr||{}),on=(n=>(n.TextEmbeddingAda002="text-embedding-ada-002",n.TextEmbedding3Small="text-embedding-3-small",n.TextEmbedding3Large="text-embedding-3-large",n))(on||{});var sn=(U=>(U.GPT4="gpt-4",U.GPT41="gpt-4.1",U.GPT41Mini="gpt-4.1-mini",U.GPT41Nano="gpt-4.1-nano",U.GPT4O="gpt-4o",U.GPT4OMini="gpt-4o-mini",U.GPT4ChatGPT4O="chatgpt-4o-latest",U.GPT4Turbo="gpt-4-turbo",U.GPT35Turbo="gpt-3.5-turbo",U.GPT35TurboInstruct="gpt-3.5-turbo-instruct",U.GPT35TextDavinci002="text-davinci-002",U.GPT3TextBabbage002="text-babbage-002",U.GPT3TextAda001="text-ada-001",U.GPT5="gpt-5",U.GPT5Nano="gpt-5-nano",U.GPT5Mini="gpt-5-mini",U.GPT5Chat="gpt-5-chat",U.GPT5ChatLatest="gpt-5-chat-latest",U.GPT5Codex="gpt-5-codex",U.GPT5Pro="gpt-5-pro",U.GPT51="gpt-5.1",U.GPT51ChatLatest="gpt-5.1-chat-latest",U.GPT51Codex="gpt-5.1-codex",U.GPT51CodexMini="gpt-5.1-codex-mini",U.GPT51CodexMax="gpt-5.1-codex-max",U.GPT52="gpt-5.2",U.GPT52ChatLatest="gpt-5.2-chat-latest",U.GPT52Codex="gpt-5.2-codex",U.GPT52Pro="gpt-5.2-pro",U.O1Pro="o1-pro",U.O1="o1",U.O1Mini="o1-mini",U.O3Pro="o3-pro",U.O3="o3",U.O3Mini="o3-mini",U.O4Mini="o4-mini",U))(sn||{});var an=[{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:.05,completionTokenCostPer1M:.4,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5-mini",currency:"usd",promptTokenCostPer1M:.25,completionTokenCostPer1M:2,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5-chat",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5-chat-latest",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,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-codex",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:40,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.1-codex",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.1-codex-mini",currency:"usd",promptTokenCostPer1M:.25,completionTokenCostPer1M:2,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.1-codex-max",currency:"usd",promptTokenCostPer1M:2.5,completionTokenCostPer1M:20,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.2",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.2-chat-latest",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.2-codex",currency:"usd",promptTokenCostPer1M:1.5,completionTokenCostPer1M:6,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.2-pro",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:160,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}],go=[{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:.05,completionTokenCostPer1M:.4,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5-mini",currency:"usd",promptTokenCostPer1M:.25,completionTokenCostPer1M:2,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5-chat",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5-chat-latest",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,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-codex",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:40,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.1-codex",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.1-codex-mini",currency:"usd",promptTokenCostPer1M:.25,completionTokenCostPer1M:2,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.1-codex-max",currency:"usd",promptTokenCostPer1M:2.5,completionTokenCostPer1M:20,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.2",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.2-chat-latest",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.2-codex",currency:"usd",promptTokenCostPer1M:1.5,completionTokenCostPer1M:6,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.2-pro",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:160,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 xd=s=>{let e=["o1","o1-mini","o3","o3-mini","o4-mini","o1-pro","o3-pro"];return e.includes(s)||e.includes(s)},Bt=()=>structuredClone({model:"gpt-5-mini",embedModel:"text-embedding-3-small",...be()}),fo=()=>structuredClone({...Bt(),model:"gpt-5"}),ho=()=>structuredClone({model:"gpt-5-mini",embedModel:"text-embedding-3-small",...Ne()}),xo=()=>({...Bt(),model:"gpt-5-nano"}),di=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=Ad(e),l=e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,u=e.modelConfig?.stream??this.config.stream,c=this.config.store,p=xd(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 Se(a.message.refusal,e.model,e.id);let l=ql(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 Se(p,void 0,n);let h=ql(f),A=d?.map(({id:x,index:b,function:{name:C,arguments:I}})=>{typeof x=="string"&&typeof b=="number"&&!i.indexIdMap[b]&&(i.indexIdMap[b]=x);let v=i.indexIdMap[b];return v?{id:v,type:"function",function:{name:C,params:I}}:null}).filter(x=>x!==null);return{index:l,content:u??void 0,role:c,thought:m,citations:g?.filter(x=>x?.type==="url_citation"&&x.url_citation).map(x=>({url:x.url_citation?.url,title:x.url_citation?.title,description:x.url_citation?.description})),functionCalls:A,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)}}},ql=s=>{switch(s){case"stop":return"stop";case"length":return"length";case"content_filter":return"error";case"tool_calls":return"function_call"}};function Ad(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 Fe=class extends _e{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 di(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})}},ln=class extends Fe{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=[...an,...i??[]];let a=u=>{let c=tt({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]],A="minimal",x=Number.POSITIVE_INFINITY;for(let[b,C]of h){let I=Math.abs(f-C);I<x&&(x=I,A=b)}g.thinkingTokenBudget=A}return p?.thinking?.includeThoughts!==void 0&&(g.showThoughts=!!p.thinking.includeThoughts),g});super({apiKey:e,apiURL:t,config:{...Bt(),...n},options:r,modelInfo:i,models:l??o,supportFor:a}),super.setName("OpenAI")}};var yd=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},bd=s=>{let e=s.match(/^(\d{4}-\d{2}-\d{2})/);return e?e[1]>="2024-08-01":!1},mi=Bt,zl=ho,Hl=xo,Kl=fo,un=class extends Fe{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={...mi(),...o},c=yd(r),p=bd(c);l=[...an,...l??[]];let d=g=>{let f=tt({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 Ao=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.");Id(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 Ue))throw p;switch(p.constructor){case wt:throw p;case ze:{if(![408,429,500,502,503,504].includes(p.status))throw p;break}case Le:break;case Tt:break;case nt:break;case et: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 Ue)||r instanceof ze&&![408,429,500,502,503,504].includes(r.status)||r instanceof wt)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 Id(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 jt(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 gi(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 yo(s,e){return s.map(t=>{let n=t.getFeatures(),r=gi(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 bo(s,e,t={}){if(e.length===0)throw new Error("No providers available");let n=jt(s),r=yo(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 Wl(s,e){let t=jt(s),n=yo(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 Vl(s,e){return s.filter(t=>t.getFeatures().media[e].supported)}function Jl(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 mr=(r=>(r.CommandRPlus="command-r-plus",r.CommandR="command-r",r.Command="command",r.CommandLight="command-light",r))(mr||{}),gr=(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))(gr||{});var Io=[{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}];function Cd(s){if(Array.isArray(s)){let t=["string","number","integer","boolean","object","array"].find(n=>s.includes(n));return t||(s.find(n=>n!=="null")??s[0]??"string")}return typeof s=="string"?s:"string"}var hi=()=>structuredClone({model:"command-r-plus",embedModel:"embed-english-v3.0",...be()}),Ql=()=>structuredClone({model:"command-r",embedModel:"embed-english-v3.0",...Ne()}),fi=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=Td(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:Cd(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}}},cn=class extends _e{constructor({apiKey:e,config:t,options:n,models:r}){if(!e||e==="")throw new Error("Cohere API key not set");let o={...hi(),...t},i=new fi(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:Io,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 Td(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=Yl(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=Yl(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 Yl(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 fr=(n=>(n.DeepSeekChat="deepseek-chat",n.DeepSeekCoder="deepseek-coder",n.DeepSeekReasoner="deepseek-reasoner",n))(fr||{});var Co=[{name:"deepseek-chat",currency:"USD",promptTokenCostPer1M:.27,completionTokenCostPer1M:1.1},{name:"deepseek-reasoner",currency:"USD",promptTokenCostPer1M:.55,completionTokenCostPer1M:2.19}];var xi=()=>structuredClone({model:"deepseek-chat",...be()}),Xl=()=>structuredClone({model:"deepseek-coder",...Ne()}),pn=class extends Fe{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("DeepSeek API key not set");let i={...xi(),...t};o=[...Co,...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 hr=(C=>(C.Gemini31Pro="gemini-3.1-pro-preview",C.Gemini3FlashLite="gemini-3.1-flash-lite-preview",C.Gemini3Flash="gemini-3-flash-preview",C.Gemini3Pro="gemini-3.1-pro-preview",C.Gemini3ProImage="gemini-3-pro-image-preview",C.Gemini25Pro="gemini-2.5-pro",C.Gemini25Flash="gemini-2.5-flash",C.Gemini25FlashLite="gemini-2.5-flash-lite",C.Gemini20Flash="gemini-2.0-flash",C.Gemini20FlashLite="gemini-2.0-flash-lite",C.Gemini20ProExp="gemini-2.0-pro-exp-02-05",C.Gemini20FlashThinkingExp="gemini-2.0-flash-thinking-exp-01-21",C.Gemini1Pro="gemini-1.0-pro",C.Gemini15Flash="gemini-1.5-flash",C.Gemini15Flash002="gemini-1.5-flash-002",C.Gemini15Flash8B="gemini-1.5-flash-8b",C.Gemini15Pro="gemini-1.5-pro",C.GeminiFlashLatest="gemini-flash-latest",C.GeminiFlashLiteLatest="gemini-flash-lite-latest",C.GeminiProLatest="gemini-pro-latest",C))(hr||{}),To=(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))(To||{}),wo=(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))(wo||{}),Ro=(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))(Ro||{}),Ai=(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))(Ai||{}),Zl=["gemini-3.1-pro-preview","gemini-3.1-pro-preview-customtools","gemini-3.1-flash-lite-preview","gemini-3-flash-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 vo=[{name:"gemini-3.1-pro-preview",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2,completionTokenCostPer1M:12,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-3-flash-preview",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.5,completionTokenCostPer1M:3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-3.1-flash-lite-preview",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.25,completionTokenCostPer1M:1.5,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 qt=s=>s.includes("gemini-3"),eu=s=>s.includes("gemini-3")&&s.includes("pro"),So=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,Array.isArray(e.type)&&(e.type=e.type.includes("object")?"object":e.type[0]??"string"),e.properties&&typeof e.properties=="object"&&(e.properties=Object.fromEntries(Object.entries(e.properties).map(([t,n])=>[t,So(n)]))),e.items&&(e.items=So(e.items)),e},tu=[{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"}],bi=()=>structuredClone({model:"gemini-2.5-flash",embedModel:"text-embedding-005",safetySettings:tu,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},thinkingLevelMapping:{minimal:"minimal",low:"low",medium:"medium",high:"high",highest:"high"},...be()}),nu=()=>structuredClone({model:"gemini-2.0-flash",embedModel:"text-embedding-005",safetySettings:tu,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},thinkingLevelMapping:{minimal:"minimal",low:"low",medium:"medium",high:"high",highest:"high"},...Ne()}),yi=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");let i=this.config.model;if(qt(i)){if(this.config.thinking?.thinkingTokenBudget!==void 0&&typeof this.config.thinking.thinkingTokenBudget=="number")throw new Error(`Gemini 3 models (${i}) do not support numeric thinkingTokenBudget. Use thinkingLevel ('low', 'medium', 'high') instead, or pass thinkingTokenBudget as a string level via options.`);if(eu(i)&&this.config.thinking?.thinkingLevel){let a=this.config.thinking.thinkingLevel;if(a!=="low"&&a!=="high")throw new Error(`Gemini 3 Pro (${i}) only supports thinkingLevel 'low' or 'high', got '${a}'. Use 'low' for less thinking or 'high' for more thinking.`)}}}tokensUsed;models;setModels(e){this.models=e}getEffectiveMappings(e){let t=this.models?.find(n=>n.model===e);return{thinkingLevelMapping:{...this.config.thinkingLevelMapping,...t?.thinkingLevelMapping??{}},thinkingTokenBudgetLevels:{...this.config.thinkingTokenBudgetLevels,...t?.thinkingTokenBudgetLevels??{}}}}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?"&":"?",b=typeof this.apiKey=="function"?await this.apiKey():this.apiKey;o.name+=`${x}key=${b}`}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 b=u[x];switch(b.role){case"user":{let C=Array.isArray(b.content)?b.content.map((I,v)=>{switch(I.type){case"text":return{text:I.text};case"image":return{inlineData:{mimeType:I.mimeType,data:I.image}};case"audio":return{inlineData:{mimeType:`audio/${I.format??"mp3"}`,data:I.data}};case"file":return"fileUri"in I?{fileData:{mimeType:I.mimeType,fileUri:I.fileUri}}:{inlineData:{mimeType:I.mimeType,data:I.data}};default:throw new Error(`Chat prompt content type not supported (index: ${v})`)}}):[{text:b.content}];l.push({role:"user",parts:C});break}case"assistant":{let C=[],I=b.thoughtBlocks,v=b.functionCalls&&b.functionCalls.length>0,O=I?.[0],k=I?.map($=>$.data).join("")??"",S=O?.signature;if(k&&C.push({...v?{}:{thought:!0},text:k,...S&&!v?{thought_signature:S}:{}}),b.functionCalls){let $=b.functionCalls.map((G,L)=>{let w;if(typeof G.function.params=="string"){let E=G.function.params;if(E.trim().length===0)w={};else try{w=JSON.parse(E)}catch{throw new Error(`Failed to parse function params JSON: ${E}`)}}else w=G.function.params;let R={functionCall:{name:G.function.name,args:w}};return S&&L===0&&(R.thought_signature=S),R});C.push(...$)}if(b.content&&C.push({text:b.content}),C.length===0)throw new Error("Assistant content is empty");l.push({role:"model",parts:C});break}case"function":{let C=[],I=b,v=x;for(;;){if(!("functionId"in I))throw new Error(`Chat prompt functionId is empty (index: ${v})`);if(C.push({functionResponse:{name:I.functionId,response:{result:I.result}}}),v+1<u.length&&u[v+1].role==="function")v++,I=u[v];else break}x=v,l.push({role:"user",parts:C});break}default:throw new Error(`Invalid role: ${JSON.stringify(b)} (index: ${x})`)}}let c=[];if(e.functions&&e.functions.length>0){let x=e.functions.map(b=>{let C={type:"object",properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]},I=b.parameters?So(b.parameters):void 0;return I===void 0||I&&typeof I=="object"&&Object.keys(I).length===0?I={...C}:I&&typeof I=="object"&&I.type==="object"&&(!("properties"in I)||!I.properties||Object.keys(I.properties).length===0)&&(I={...I,properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]}),{name:b.name,description:b.description,parameters:I}});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,b=x?.enableWidget!==void 0?{enableWidget:x.enableWidget}:{};c.push({google_maps:b})}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&&qt(n)&&(m.thinkingLevel=this.config.thinking.thinkingLevel),t?.thinkingTokenBudget){let x=this.getEffectiveMappings(n),b=x.thinkingTokenBudgetLevels;if(qt(n)){let I=eu(n),v=x.thinkingLevelMapping;if(t.thinkingTokenBudget==="none")m.thinkingLevel=v?.minimal??"minimal";else{let O=t.thinkingTokenBudget,k=v?.[O];k||(k=O==="highest"?"high":O),m.thinkingLevel=k}if(I&&m.thinkingLevel){let O=m.thinkingLevel;O!=="low"&&O!=="high"&&(m.thinkingLevel=O==="minimal"?"low":"high")}}else switch(t.thinkingTokenBudget){case"none":m.thinkingBudget=0,m.includeThoughts=!1,delete m.thinkingLevel;break;case"minimal":m.thinkingBudget=b?.minimal??200;break;case"low":m.thinkingBudget=b?.low??800;break;case"medium":m.thinkingBudget=b?.medium??5e3;break;case"high":m.thinkingBudget=b?.high??1e4;break;case"highest":m.thinkingBudget=b?.highest??24500;break}}m.thinkingLevel&&delete m.thinkingBudget,qt(n)||delete m.thinkingLevel,qt(n)&&delete m.thinkingBudget;let g=e.modelConfig?.maxTokens??this.config.maxTokens;if(m.thinkingLevel&&g!==void 0)throw new Error("Cannot set maxTokens when using thinkingLevel with Gemini models. When thinking is enabled, the model manages output tokens automatically. Remove the maxTokens setting or disable thinking.");t?.showThoughts!==void 0&&t?.thinkingTokenBudget!=="none"&&(m.includeThoughts=t.showThoughts);let f={maxOutputTokens:e.modelConfig?.maxTokens??this.config.maxTokens,temperature:e.modelConfig?.temperature??this.config.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(qt(n)&&(f.temperature===void 0||f.temperature<1)&&(f.temperature=1),e.responseFormat){if(f.responseMimeType="application/json",e.responseFormat.type==="json_schema"&&e.responseFormat.schema){let x=e.responseFormat.schema.schema||e.responseFormat.schema;f.responseSchema=So(x)}}else this.config.responseFormat&&this.config.responseFormat==="json_object"&&(f.responseMimeType="application/json");let h=this.config.safetySettings;return[o,{contents:l,tools:c,toolConfig:p,systemInstruction:a,generationConfig:f,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(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 Se("Content was blocked due to safety settings",void 0,void 0);case"RECITATION":throw new Se("Content was blocked due to recitation policy",void 0,void 0);case"MALFORMED_FUNCTION_CALL":throw new Se("Function call was malformed and blocked",void 0,void 0);case"UNEXPECTED_TOOL_CALL":throw new Se("Unexpected tool call",void 0,void 0);case"FINISH_REASON_UNSPECIFIED":throw new Se("Finish reason unspecified",void 0,void 0);case"BLOCKLIST":throw new Se("Content was blocked due to blocklist",void 0,void 0);case"PROHIBITED_CONTENT":throw new Se("Content was blocked due to prohibited content",void 0,void 0);case"SPII":throw new Se("Content was blocked due to SPII",void 0,void 0);case"OTHER":throw new Se("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:Ge(),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,...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 Zl.some(n=>t.includes(n)||n.includes(t))};buildCacheCreateOp=(e,t)=>{let n=e.model,r=t.contextCache?.ttlSeconds??3600,{systemInstruction:o,contents:i}=this.extractCacheableContent(e.chatPrompt);if(!o&&(!i||i.length===0))return;let a={model:this.isVertex?n:`models/${n}`,ttl:`${r}s`,displayName:`ax-cache-${Date.now()}`};o&&(a.systemInstruction=o),i&&i.length>0&&(a.contents=i);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 i=o;if(i?.name)return{name:i.name,expiresAt:i.expireTime,tokenCount:i.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:i,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,temperature:e.modelConfig?.temperature??this.config.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"};qt(r)&&(u.temperature===void 0||u.temperature<1)&&(u.temperature=1);let c=this.config.safetySettings,p={contents:i,cachedContent:n,generationConfig:u,safetySettings:c};return a&&(p.systemInstruction=a),{apiConfig:l,request:p}};extractCacheableContent(e){let t,n=[],r=-1;for(let o=e.length-1;o>=0;o--){let i=e[o];if("cache"in i&&i.cache){r=o;break}}for(let o=0;o<e.length;o++){let i=e[o];if(i.role==="system"){t={role:"user",parts:[{text:i.content}]};continue}if(r>=0&&o<=r)if(i.role==="user"){let a=[];if(typeof i.content=="string")a.push({text:i.content});else if(Array.isArray(i.content))for(let l of i.content)switch(l.type){case"text":a.push({text:l.text});break;case"image":a.push({inlineData:{mimeType:l.mimeType,data:l.image}});break;case"audio":a.push({inlineData:{mimeType:`audio/${l.format??"mp3"}`,data:l.data}});break;case"file":"fileUri"in l?a.push({fileData:{mimeType:l.mimeType,fileUri:l.fileUri}}):a.push({inlineData:{mimeType:l.mimeType,data:l.data}});break}a.length>0&&n.push({role:"user",parts:a})}else i.role==="assistant"&&i.content&&n.push({role:"model",parts:[{text:i.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 i of r.content)if(!("cache"in i&&i.cache))switch(i.type){case"text":o.push({text:i.text});break;case"image":o.push({inlineData:{mimeType:i.mimeType,data:i.image}});break;case"audio":o.push({inlineData:{mimeType:`audio/${i.format??"mp3"}`,data:i.data}});break;case"file":"fileUri"in i?o.push({fileData:{mimeType:i.mimeType,fileUri:i.fileUri}}):o.push({inlineData:{mimeType:i.mimeType,data:i.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 i of r.functionCalls){let a;if(typeof i.function.params=="string")try{a=JSON.parse(i.function.params)}catch{a={}}else a=i.function.params??{};o.push({functionCall:{name:i.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}}},dn=class s extends _e{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={...bi(),...o},m=new yi(d,u,r,e,i);l=[...vo,...l??[]];let g=h=>{let A=tt({model:h,modelInfo:l,models:a});return{functions:!0,streaming:!0,hasThinkingBudget:A?.supported?.thinkingBudget??!1,hasShowThoughts:A?.supported?.showThoughts??!1,structuredOutputs:A?.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(h),types:["persistent"]},thinking:A?.supported?.thinkingBudget??!1,multiTurn:!0}},f=a?.map(h=>{let A=h,x=A?.config;if(!x)return h;let b={};x.maxTokens!==void 0&&(b.maxTokens=x.maxTokens),x.temperature!==void 0&&(b.temperature=x.temperature),x.topP!==void 0&&(b.topP=x.topP),x.topK!==void 0&&(b.topK=x.topK),x.presencePenalty!==void 0&&(b.presencePenalty=x.presencePenalty),x.frequencyPenalty!==void 0&&(b.frequencyPenalty=x.frequencyPenalty),x.stopSequences!==void 0&&(b.stopSequences=x.stopSequences),x.endSequences!==void 0&&(b.endSequences=x.endSequences),x.stream!==void 0&&(b.stream=x.stream),x.n!==void 0&&(b.n=x.n);let C={...A};Object.keys(b).length>0&&(C.modelConfig={...A.modelConfig??{},...b});let I=x.thinking?.thinkingTokenBudget;if(typeof I=="number"){let v=d.thinkingTokenBudgetLevels,O=[["minimal",v?.minimal??200],["low",v?.low??800],["medium",v?.medium??5e3],["high",v?.high??1e4],["highest",v?.highest??24500]],k="minimal",S=Number.POSITIVE_INFINITY;for(let[$,G]of O){let L=Math.abs(I-G);L<S&&(S=L,k=$)}C.thinkingTokenBudget=k}return x.thinking?.includeThoughts!==void 0&&(C.showThoughts=!!x.thinking.includeThoughts),x.thinkingLevelMapping&&(C.thinkingLevelMapping=x.thinkingLevelMapping),x.thinkingTokenBudgetLevels&&(C.thinkingTokenBudgetLevels=x.thinkingTokenBudgetLevels),C});f?m.setModels(f):a&&m.setModels(a),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 wd=new Ke,mn=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(wd.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 xr=(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))(xr||{});var ko=[{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 Rd=()=>structuredClone({model:"llama-3.3-70b-versatile",...be()}),gn=class extends Fe{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("Groq API key not set");let i={...Rd(),...t},a={...n,streamingUsage:!1};o=[...ko,...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 mn(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 Oo=[];var Mo=(e=>(e.MetaLlama270BChatHF="meta-llama/Llama-2-70b-chat-hf",e))(Mo||{});var Ci=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...be()}),ru=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...Ne()}),Ii=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}]})},yn=class extends je{constructor({apiKey:e,config:t,options:n,models:r}){if(!e||e==="")throw new Error("HuggingFace API key not set");let o={...hi(),...t},i=new fi(o);super(i,{name:"HuggingFace",apiURL:"https://api-inference.huggingface.co",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:So,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 yr=(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))(yr||{}),xi=(e=>(e.MistralEmbed="mistral-embed",e))(xi||{});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 Mo=()=>structuredClone({model:"mistral-small-latest",...Re(),topP:1}),Hl=()=>structuredClone({...Mo(),model:"mistral-large-latest"}),bn=class extends Ue{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("Mistral API key not set");let i={...Mo(),...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: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 Eo=class{constructor(e={}){this.config=e;this.config.id=this.config.id??Ye()}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 Po=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 Ai=()=>structuredClone({...Re(),model:"nous-hermes2",embedModel:"all-minilm"}),Kl=()=>structuredClone({...He(),model:"nous-hermes2",embedModel:"all-minilm"}),In=class extends Ue{constructor({apiKey:e="not-set",url:t="http://localhost:11434/v1",config:n,options:r,models:o}){let i={...Ai(),...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 Wp=s=>["o1","o1-mini","o1-pro","o3","o3-mini","o3-pro","o4-mini"].includes(s),Cn=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 y of e.chatPrompt)if(y.role==="system"&&typeof y.content=="string"){o=y.content,i=!0;break}}let a=o??this.config.systemPrompt??null,l=e.functions?.map(y=>({type:"function",name:y.name,description:y.description,parameters:y.parameters??{}})),u=[],c=Wp(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=yi(i.content,t),o.finishReason=i.status==="completed"?"stop":"content_filter",o.citations=Fo(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=yi(t.item.content,t.item.id),n.citations=Fo(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=yi([t.part],t.item_id),n.citations=Fo([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=Fo(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]}},yi=(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 Ne(n,void 0,e)}return s.filter(n=>n.type==="output_text").map(n=>n.text).join(`
178
- `)};function Fo(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 Ir=()=>({model:"gpt-4o",embedModel:"text-embedding-ada-002",temperature:.7,topP:1,stream:!0}),Wl=()=>({...Ir(),model:"gpt-4o",temperature:.5}),Vl=()=>({...Ir(),model:"gpt-4o",temperature:.9}),br=class extends je{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 Cn(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 y=m?.thinking?.thinkingTokenBudget;if(typeof y=="number"){let x=[["minimal",200],["low",800],["medium",5e3],["high",1e4],["highest",24500]],b="minimal",R=Number.POSITIVE_INFINITY;for(let[A,w]of x){let v=Math.abs(y-w);v<R&&(R=v,b=A)}h.thinkingTokenBudget=b}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})}},Tn=class extends br{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("OpenAI API key not set");o=[...po,...o??[]];let i=a=>{let l=lt({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:{...Ir(),...t},options:n,modelInfo:o,models:r,supportFor:i})}};var bi=()=>structuredClone({model:"openrouter/auto",...Re()}),wn=class extends Ue{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={...bi(),...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 _o(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 yt(i,"image","vision analysis")}else switch(t.fallbackBehavior){case"error":throw new ct("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 yt(i,"audio","transcription")}else switch(t.fallbackBehavior){case"error":throw new ct("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 yt(i,"file","text extraction")}else switch(t.fallbackBehavior){case"error":throw new ct("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 yt(i,"url","content fetching")}else switch(t.fallbackBehavior){case"error":throw new ct("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 ct||i instanceof yt?i:new yt(i,o.type||"unknown","content processing")}return r}function Jl(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 Cr=(n=>(n.RekaCore="reka-core",n.RekaFlash="reka-flash",n.RekaEdge="reka-edge",n))(Cr||{});var No=[{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 Tr=()=>structuredClone({model:"reka-core",...Re()}),Ql=()=>structuredClone({...Tr(),model:"reka-core"}),Xl=()=>structuredClone({model:"reka-core",...He()}),Zl=()=>({...Tr(),model:"reka-flash"}),Ii=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=Vp(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=Yl(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=Yl(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}})}}},Yl=s=>{switch(s){case"stop":return"stop";case"context":return"length";case"length":return"length"}};function Vp(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 Rn=class extends je{constructor({apiKey:e,config:t,options:n,apiURL:r,modelInfo:o=No,models:i}){if(!e||e==="")throw new Error("Reka API key not set");let a={...Tr(),...t},l=new Ii(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 $o=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 ct&&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 _o(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=Ht(e),r=[],o=[],i=[];try{let a=Ao(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=Ht(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 wr=(x=>(x.KimiK25="moonshotai/Kimi-K2.5",x.KimiK2Instruct0905="moonshotai/Kimi-K2-Instruct-0905",x.KimiK2Thinking="moonshotai/Kimi-K2-Thinking",x.DeepSeekV31="deepseek-ai/DeepSeek-V3.1",x.DeepSeekR1="deepseek-ai/DeepSeek-R1",x.GPTOSS120B="openai/gpt-oss-120b",x.GPTOSS20B="openai/gpt-oss-20b",x.Qwen35_397B="Qwen/Qwen3.5-397B-A17B",x.Qwen3CoderNext="Qwen/Qwen3-Coder-Next-FP8",x.Qwen3Coder480B="Qwen/Qwen3-Coder-480B-A35B-Instruct-FP8",x.Qwen3_235BInstruct2507="Qwen/Qwen3-235B-A22B-Instruct-2507-tput",x.Qwen3_235BThinking2507="Qwen/Qwen3-235B-A22B-Thinking-2507",x.Qwen3Next80BInstruct="Qwen/Qwen3-Next-80B-A3B-Instruct",x.Qwen3Next80BThinking="Qwen/Qwen3-Next-80B-A3B-Thinking",x.GLM5="zai-org/GLM-5",x.GLM47="zai-org/GLM-4.7",x.Llama4Maverick="meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8",x.Llama33_70B="meta-llama/Llama-3.3-70B-Instruct-Turbo",x))(wr||{});var Lo=[{name:"moonshotai/Kimi-K2.5",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:2.8},{name:"moonshotai/Kimi-K2-Instruct-0905",currency:"usd",promptTokenCostPer1M:1,completionTokenCostPer1M:3},{name:"moonshotai/Kimi-K2-Thinking",currency:"usd",promptTokenCostPer1M:1.2,completionTokenCostPer1M:4},{name:"deepseek-ai/DeepSeek-V3.1",currency:"usd",promptTokenCostPer1M:.6,completionTokenCostPer1M:1.7},{name:"deepseek-ai/DeepSeek-R1",currency:"usd",promptTokenCostPer1M:1.4,completionTokenCostPer1M:2.2},{name:"openai/gpt-oss-120b",currency:"usd",promptTokenCostPer1M:.15,completionTokenCostPer1M:.6},{name:"openai/gpt-oss-20b",currency:"usd",promptTokenCostPer1M:.05,completionTokenCostPer1M:.2},{name:"Qwen/Qwen3.5-397B-A17B",currency:"usd",promptTokenCostPer1M:.6,completionTokenCostPer1M:3.6},{name:"Qwen/Qwen3-Coder-Next-FP8",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.2},{name:"Qwen/Qwen3-Coder-480B-A35B-Instruct-FP8",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:2},{name:"Qwen/Qwen3-235B-A22B-Instruct-2507-tput",currency:"usd",promptTokenCostPer1M:.2,completionTokenCostPer1M:.6},{name:"Qwen/Qwen3-235B-A22B-Thinking-2507",currency:"usd",promptTokenCostPer1M:.65,completionTokenCostPer1M:3},{name:"Qwen/Qwen3-Next-80B-A3B-Instruct",currency:"usd",promptTokenCostPer1M:.15,completionTokenCostPer1M:1.5},{name:"Qwen/Qwen3-Next-80B-A3B-Thinking",currency:"usd",promptTokenCostPer1M:.15,completionTokenCostPer1M:1.5},{name:"zai-org/GLM-5",currency:"usd",promptTokenCostPer1M:1,completionTokenCostPer1M:3.2},{name:"zai-org/GLM-4.7",currency:"usd",promptTokenCostPer1M:.45,completionTokenCostPer1M:2},{name:"meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8",currency:"usd",promptTokenCostPer1M:.27,completionTokenCostPer1M:.85},{name:"meta-llama/Llama-3.3-70B-Instruct-Turbo",currency:"usd",promptTokenCostPer1M:.88,completionTokenCostPer1M:.88}];var Ci=()=>structuredClone({model:"meta-llama/Llama-3.3-70B-Instruct-Turbo",...Re()}),vn=class extends Ue{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("Together API key not set");let i={...Ci(),...t};o=[...Lo,...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 Do=[{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 wi=()=>structuredClone({model:"Llama-3.2-3B-Instruct-q4f32_1-MLC",...Re()}),eu=()=>structuredClone({model:"Llama-3.2-3B-Instruct-q4f32_1-MLC",...He()}),Ti=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")}},Sn=class extends je{constructor({engine:e,config:t,options:n,models:r}){if(!e)throw new Error("WebLLM engine instance is required");let o={...wi(),...t},i=new Ti(o,e);super(i,{name:"WebLLM",apiURL:void 0,headers:async()=>({}),modelInfo:Do,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 vr=(r=>(r.Grok3="grok-3",r.Grok3Mini="grok-3-mini",r.Grok3Fast="grok-3-fast",r.Grok3MiniFast="grok-3-mini-fast",r))(vr||{}),Ri=(e=>(e.GrokEmbedSmall="grok-embed-small",e))(Ri||{});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 Uo=()=>structuredClone({model:"grok-3-mini",...Re()}),tu=()=>structuredClone({...Uo(),model:"grok-3"}),kn=class extends Ue{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("Grok API key not set");let i={...Uo(),...t};o=[...Go,...o??[]];let a=u=>{let c=lt({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 nu(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 dn(e);break;case"openai-responses":this.ai=new Tn(e);break;case"azure-openai":this.ai=new mn(e);break;case"grok":this.ai=new kn(e);break;case"huggingface":this.ai=new yn(e);break;case"groq":this.ai=new An(e);break;case"together":this.ai=new vn(e);break;case"openrouter":this.ai=new wn(e);break;case"cohere":this.ai=new gn(e);break;case"google-gemini":this.ai=new hn(e);break;case"anthropic":this.ai=new ln(e);break;case"mistral":this.ai=new bn(e);break;case"deepseek":this.ai=new fn(e);break;case"ollama":this.ai=new In(e);break;case"reka":this.ai=new Rn(e);break;case"webllm":this.ai=new Sn(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 pt=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:ot.SERVER,attributes:{[xe.DB_SYSTEM]:this.name,[xe.DB_OPERATION_NAME]:"upsert",[xe.DB_TABLE]:e.table,[xe.DB_NAMESPACE]:e.namespace,[xe.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:ot.SERVER,attributes:{[xe.DB_SYSTEM]:this.name,[xe.DB_OPERATION_NAME]:"upsert",[xe.DB_TABLE]:e[0].table,[xe.DB_NAMESPACE]:e[0].namespace,[xe.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:ot.SERVER,attributes:{[xe.DB_SYSTEM]:this.name,[xe.DB_OPERATION_NAME]:"upsert",[xe.DB_TABLE]:e.table,[xe.DB_NAMESPACE]:e.namespace,[xe.DB_OPERATION_NAME]:"query"}},async t=>{try{return await this._query(e,{span:t})}finally{t.end()}}):await this._query(e)}};var vi="https://api.cloudflare.com/client/v4/accounts/",On=class extends pt{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 Xe({url:new URL(`${this.accountId}/vectorize/indexes/${e.table}/upsert`,vi),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 Xe({url:new URL(`${this.accountId}/vectorize/indexes/${r}/upsert`,vi),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 Xe({url:new URL(`${this.accountId}/vectorize/indexes/${e.table}/query`,vi),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 Lt=class extends pt{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=Jp(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={}}},Jp=(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 Yp=s=>({namespace:s.namespace,topK:s.limit||10,filter:{},includeValues:!0,includeMetadata:!0,vector:s.values??[],id:s.id}),Mn=class extends pt{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 Xe({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 Xe({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/query",fetch:this.fetch,span:t?.span},Yp(e))).matches.map(({id:o,score:i,values:a,metadata:l})=>({id:o,score:i,metadata:l,values:a}))}}};var En=class extends pt{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 Xe({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 Xe({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(),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}]})},fn=class extends _e{constructor({apiKey:e,config:t,options:n,models:r}){if(!e||e==="")throw new Error("HuggingFace API key not set");let o={...Ci(),...t},i=new Ii(o);super(i,{name:"HuggingFace",apiURL:"https://api-inference.huggingface.co",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:Oo,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 Ar=(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))(Ar||{}),Ti=(e=>(e.MistralEmbed="mistral-embed",e))(Ti||{});var Eo=[{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 Po=()=>structuredClone({model:"mistral-small-latest",...be(),topP:1}),ou=()=>structuredClone({...Po(),model:"mistral-large-latest"}),hn=class extends Fe{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("Mistral API key not set");let i={...Po(),...t};o=[...Eo,...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 Fo=class{constructor(e={}){this.config=e;this.config.id=this.config.id??Ge()}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 _o=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 wi=()=>structuredClone({...be(),model:"nous-hermes2",embedModel:"all-minilm"}),su=()=>structuredClone({...Ne(),model:"nous-hermes2",embedModel:"all-minilm"}),xn=class extends Fe{constructor({apiKey:e="not-set",url:t="http://localhost:11434/v1",config:n,options:r,models:o}){let i={...wi(),...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 vd=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 A of e.chatPrompt)if(A.role==="system"&&typeof A.content=="string"){o=A.content,i=!0;break}}let a=o??this.config.systemPrompt??null,l=e.functions?.map(A=>({type:"function",name:A.name,description:A.description,parameters:A.parameters??{}})),u=[],c=vd(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=Ri(i.content,t),o.finishReason=i.status==="completed"?"stop":"content_filter",o.citations=No(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=Ri(t.item.content,t.item.id),n.citations=No(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=Ri([t.part],t.item_id),n.citations=No([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=No(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]}},Ri=(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 Se(n,void 0,e)}return s.filter(n=>n.type==="output_text").map(n=>n.text).join(`
178
+ `)};function No(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 br=()=>({model:"gpt-4o",embedModel:"text-embedding-ada-002",temperature:.7,topP:1,stream:!0}),iu=()=>({...br(),model:"gpt-4o",temperature:.5}),au=()=>({...br(),model:"gpt-4o",temperature:.9}),yr=class extends _e{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 A=m?.thinking?.thinkingTokenBudget;if(typeof A=="number"){let x=[["minimal",200],["low",800],["medium",5e3],["high",1e4],["highest",24500]],b="minimal",C=Number.POSITIVE_INFINITY;for(let[I,v]of x){let O=Math.abs(A-v);O<C&&(C=O,b=I)}h.thinkingTokenBudget=b}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})}},yn=class extends yr{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("OpenAI API key not set");o=[...go,...o??[]];let i=a=>{let l=tt({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:{...br(),...t},options:n,modelInfo:o,models:r,supportFor:i})}};var vi=()=>structuredClone({model:"openrouter/auto",...be()}),bn=class extends Fe{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={...vi(),...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 $o(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 pt(i,"image","vision analysis")}else switch(t.fallbackBehavior){case"error":throw new rt("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 pt(i,"audio","transcription")}else switch(t.fallbackBehavior){case"error":throw new rt("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 pt(i,"file","text extraction")}else switch(t.fallbackBehavior){case"error":throw new rt("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 pt(i,"url","content fetching")}else switch(t.fallbackBehavior){case"error":throw new rt("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 rt||i instanceof pt?i:new pt(i,o.type||"unknown","content processing")}return r}function lu(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 Ir=(n=>(n.RekaCore="reka-core",n.RekaFlash="reka-flash",n.RekaEdge="reka-edge",n))(Ir||{});var Lo=[{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 Cr=()=>structuredClone({model:"reka-core",...be()}),cu=()=>structuredClone({...Cr(),model:"reka-core"}),pu=()=>structuredClone({model:"reka-core",...Ne()}),du=()=>({...Cr(),model:"reka-flash"}),Si=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=Sd(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=uu(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=uu(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}})}}},uu=s=>{switch(s){case"stop":return"stop";case"context":return"length";case"length":return"length"}};function Sd(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 In=class extends _e{constructor({apiKey:e,config:t,options:n,apiURL:r,modelInfo:o=Lo,models:i}){if(!e||e==="")throw new Error("Reka API key not set");let a={...Cr(),...t},l=new Si(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 Do=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 rt&&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 $o(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=jt(e),r=[],o=[],i=[];try{let a=bo(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=jt(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 Tr=(x=>(x.KimiK25="moonshotai/Kimi-K2.5",x.KimiK2Instruct0905="moonshotai/Kimi-K2-Instruct-0905",x.KimiK2Thinking="moonshotai/Kimi-K2-Thinking",x.DeepSeekV31="deepseek-ai/DeepSeek-V3.1",x.DeepSeekR1="deepseek-ai/DeepSeek-R1",x.GPTOSS120B="openai/gpt-oss-120b",x.GPTOSS20B="openai/gpt-oss-20b",x.Qwen35_397B="Qwen/Qwen3.5-397B-A17B",x.Qwen3CoderNext="Qwen/Qwen3-Coder-Next-FP8",x.Qwen3Coder480B="Qwen/Qwen3-Coder-480B-A35B-Instruct-FP8",x.Qwen3_235BInstruct2507="Qwen/Qwen3-235B-A22B-Instruct-2507-tput",x.Qwen3_235BThinking2507="Qwen/Qwen3-235B-A22B-Thinking-2507",x.Qwen3Next80BInstruct="Qwen/Qwen3-Next-80B-A3B-Instruct",x.Qwen3Next80BThinking="Qwen/Qwen3-Next-80B-A3B-Thinking",x.GLM5="zai-org/GLM-5",x.GLM47="zai-org/GLM-4.7",x.Llama4Maverick="meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8",x.Llama33_70B="meta-llama/Llama-3.3-70B-Instruct-Turbo",x))(Tr||{});var Go=[{name:"moonshotai/Kimi-K2.5",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:2.8},{name:"moonshotai/Kimi-K2-Instruct-0905",currency:"usd",promptTokenCostPer1M:1,completionTokenCostPer1M:3},{name:"moonshotai/Kimi-K2-Thinking",currency:"usd",promptTokenCostPer1M:1.2,completionTokenCostPer1M:4},{name:"deepseek-ai/DeepSeek-V3.1",currency:"usd",promptTokenCostPer1M:.6,completionTokenCostPer1M:1.7},{name:"deepseek-ai/DeepSeek-R1",currency:"usd",promptTokenCostPer1M:1.4,completionTokenCostPer1M:2.2},{name:"openai/gpt-oss-120b",currency:"usd",promptTokenCostPer1M:.15,completionTokenCostPer1M:.6},{name:"openai/gpt-oss-20b",currency:"usd",promptTokenCostPer1M:.05,completionTokenCostPer1M:.2},{name:"Qwen/Qwen3.5-397B-A17B",currency:"usd",promptTokenCostPer1M:.6,completionTokenCostPer1M:3.6},{name:"Qwen/Qwen3-Coder-Next-FP8",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.2},{name:"Qwen/Qwen3-Coder-480B-A35B-Instruct-FP8",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:2},{name:"Qwen/Qwen3-235B-A22B-Instruct-2507-tput",currency:"usd",promptTokenCostPer1M:.2,completionTokenCostPer1M:.6},{name:"Qwen/Qwen3-235B-A22B-Thinking-2507",currency:"usd",promptTokenCostPer1M:.65,completionTokenCostPer1M:3},{name:"Qwen/Qwen3-Next-80B-A3B-Instruct",currency:"usd",promptTokenCostPer1M:.15,completionTokenCostPer1M:1.5},{name:"Qwen/Qwen3-Next-80B-A3B-Thinking",currency:"usd",promptTokenCostPer1M:.15,completionTokenCostPer1M:1.5},{name:"zai-org/GLM-5",currency:"usd",promptTokenCostPer1M:1,completionTokenCostPer1M:3.2},{name:"zai-org/GLM-4.7",currency:"usd",promptTokenCostPer1M:.45,completionTokenCostPer1M:2},{name:"meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8",currency:"usd",promptTokenCostPer1M:.27,completionTokenCostPer1M:.85},{name:"meta-llama/Llama-3.3-70B-Instruct-Turbo",currency:"usd",promptTokenCostPer1M:.88,completionTokenCostPer1M:.88}];var ki=()=>structuredClone({model:"meta-llama/Llama-3.3-70B-Instruct-Turbo",...be()}),Cn=class extends Fe{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("Together API key not set");let i={...ki(),...t};o=[...Go,...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 wr=(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))(wr||{});var Uo=[{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 Mi=()=>structuredClone({model:"Llama-3.2-3B-Instruct-q4f32_1-MLC",...be()}),mu=()=>structuredClone({model:"Llama-3.2-3B-Instruct-q4f32_1-MLC",...Ne()}),Oi=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")}},Tn=class extends _e{constructor({engine:e,config:t,options:n,models:r}){if(!e)throw new Error("WebLLM engine instance is required");let o={...Mi(),...t},i=new Oi(o,e);super(i,{name:"WebLLM",apiURL:void 0,headers:async()=>({}),modelInfo:Uo,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 Rr=(r=>(r.Grok3="grok-3",r.Grok3Mini="grok-3-mini",r.Grok3Fast="grok-3-fast",r.Grok3MiniFast="grok-3-mini-fast",r))(Rr||{}),Ei=(e=>(e.GrokEmbedSmall="grok-embed-small",e))(Ei||{});var Bo=[{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 jo=()=>structuredClone({model:"grok-3-mini",...be()}),gu=()=>structuredClone({...jo(),model:"grok-3"}),wn=class extends Fe{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("Grok API key not set");let i={...jo(),...t};o=[...Bo,...o??[]];let a=u=>{let c=tt({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 fu(s){return vr.create(s)}var vr=class s{ai;static create(e){return new s(e)}constructor(e){switch(e.name){case"openai":this.ai=new ln(e);break;case"openai-responses":this.ai=new yn(e);break;case"azure-openai":this.ai=new un(e);break;case"grok":this.ai=new wn(e);break;case"huggingface":this.ai=new fn(e);break;case"groq":this.ai=new gn(e);break;case"together":this.ai=new Cn(e);break;case"openrouter":this.ai=new bn(e);break;case"cohere":this.ai=new cn(e);break;case"google-gemini":this.ai=new dn(e);break;case"anthropic":this.ai=new rn(e);break;case"mistral":this.ai=new hn(e);break;case"deepseek":this.ai=new pn(e);break;case"ollama":this.ai=new xn(e);break;case"reka":this.ai=new In(e);break;case"webllm":this.ai=new Tn(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 ot=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:Ve.SERVER,attributes:{[ge.DB_SYSTEM]:this.name,[ge.DB_OPERATION_NAME]:"upsert",[ge.DB_TABLE]:e.table,[ge.DB_NAMESPACE]:e.namespace,[ge.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:Ve.SERVER,attributes:{[ge.DB_SYSTEM]:this.name,[ge.DB_OPERATION_NAME]:"upsert",[ge.DB_TABLE]:e[0].table,[ge.DB_NAMESPACE]:e[0].namespace,[ge.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:Ve.SERVER,attributes:{[ge.DB_SYSTEM]:this.name,[ge.DB_OPERATION_NAME]:"upsert",[ge.DB_TABLE]:e.table,[ge.DB_NAMESPACE]:e.namespace,[ge.DB_OPERATION_NAME]:"query"}},async t=>{try{return await this._query(e,{span:t})}finally{t.end()}}):await this._query(e)}};var Pi="https://api.cloudflare.com/client/v4/accounts/",Rn=class extends ot{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 Be({url:new URL(`${this.accountId}/vectorize/indexes/${e.table}/upsert`,Pi),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 Be({url:new URL(`${this.accountId}/vectorize/indexes/${r}/upsert`,Pi),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 Be({url:new URL(`${this.accountId}/vectorize/indexes/${e.table}/query`,Pi),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 _t=class extends ot{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=kd(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={}}},kd=(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 Od=s=>({namespace:s.namespace,topK:s.limit||10,filter:{},includeValues:!0,includeMetadata:!0,vector:s.values??[],id:s.id}),vn=class extends ot{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 Be({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 Be({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/query",fetch:this.fetch,span:t?.span},Od(e))).matches.map(({id:o,score:i,values:a,metadata:l})=>({id:o,score:i,metadata:l,values:a}))}}};var Sn=class extends ot{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 Be({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 Be({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: {
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 Xe({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 Be({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,9 +190,9 @@ ${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 Bo=class{db;constructor(e){switch(e.name){case"weaviate":this.db=new En(e);break;case"pinecone":this.db=new Mn(e);break;case"cloudflare":this.db=new On(e);break;case"memory":this.db=new Lt(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 Si="_internal",jo=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 qo=class{db;constructor(e){switch(e.name){case"weaviate":this.db=new Sn(e);break;case"pinecone":this.db=new vn(e);break;case"cloudflare":this.db=new Rn(e);break;case"memory":this.db=new _t(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 Fi="_internal",zo=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=Qp({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:Si,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:Si,values:u})):o=r.map(l=>this.db.query({table:Si,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?Xp(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}},Qp=({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,i=t?.minWordsPerChunk,a=Md({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:Fi,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:Fi,values:u})):o=r.map(l=>this.db.query({table:Fi,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?Ed(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}},Md=({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}
196
196
 
197
197
  `,o+=l;else if(o>0&&o+l<=e*1.5)r+=`${i}
198
198
 
@@ -200,21 +200,21 @@ ${u}`:`Assistant: ${l.content}`}default:throw new Error("Unknown role")}}).join(
200
200
 
201
201
  `,o+=u.length)}else r=`${i}
202
202
 
203
- `,o=l}),(o>t||n.length===0)&&n.push(r.trim()),n},Xp=(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 kr=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}},Pn=class{memories=new Map;defaultMemory;constructor(){this.defaultMemory=new kr}getMemory(e){return e?(this.memories.has(e)||this.memories.set(e,new kr),this.memories.get(e)):this.defaultMemory}addRequest(e,t){for(let n of e)an(n);this.getMemory(t).addRequest(e,0)}addResponse(e,t){co(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 kr):this.defaultMemory.reset()}};function Ft(s,e){if(!s&&!e)return;if(!s)return e;if(!e||s===e||s.aborted)return s;if(e.aborted)return e;if(typeof AbortSignal.any=="function")return AbortSignal.any([s,e]);let t=new AbortController,n=()=>{t.abort(s.aborted?s.reason:e.reason),r()},r=()=>{s.removeEventListener("abort",n),e.removeEventListener("abort",n)};return s.addEventListener("abort",n,{once:!0}),e.addEventListener("abort",n,{once:!0}),t.signal}var wt=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()}},Fn=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 wt({message:o});if(!o)throw r?new wt({message:r}):new Error("Assertion Failed: No message provided for assertion")}}},ki=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 wt({message:u});if(!u&&a)throw new wt({message:a})}}};var Oi={enabled:!0,enabledCategories:["generation","streaming","functions","errors","performance"],maxLabelLength:100,samplingRate:1},Or,Mi=s=>{if(Or)return Or;let e=s??fe.meter;if(e)return Or=Zp(e),Or};var ru=()=>{let s=[];return fe.meter||s.push("Global meter not initialized"),!Or&&fe.meter&&s.push("Metrics instruments not created despite available meter"),{healthy:s.length===0,issues:s}},Zp=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"})}),qo=Oi,ou=s=>{qo={...qo,...s}},su=()=>({...qo}),Ct=s=>{let e={};for(let[t,n]of Object.entries(s))if(n!=null){let r=String(n),o=qo.maxLabelLength;e[t]=r.length>o?r.substring(0,o):r}return e};var iu=(s,e,t,n,r,o,i)=>{try{let a=Ct({success:t.toString(),...n?{signature:n}:{},...r?{ai_service:r}:{},...o?{model:o}:{},...i});s.generationLatencyHistogram&&s.generationLatencyHistogram.record(e,a),s.generationRequestsCounter&&s.generationRequestsCounter.add(1,a),!t&&s.generationErrorsCounter&&s.generationErrorsCounter.add(1,a)}catch(a){console.warn("Failed to record generation metric:",a)}},zo=(s,e,t,n,r)=>{try{let o=Ct({...n?{signature:n}:{},...r});e>1&&s.multiStepGenerationsCounter&&s.multiStepGenerationsCounter.add(1,o),s.stepsPerGenerationHistogram&&s.stepsPerGenerationHistogram.record(e,o),e>=t&&s.maxStepsReachedCounter&&s.maxStepsReachedCounter.add(1,o)}catch(o){console.warn("Failed to record multi-step metric:",o)}},Ei=(s,e,t,n)=>{try{let r=Ct({error_type:e,...t?{signature:t}:{},...n});e==="validation"&&s.validationErrorsCounter&&s.validationErrorsCounter.add(1,r),e==="assertion"&&s.assertionErrorsCounter&&s.assertionErrorsCounter.add(1,r)}catch(r){console.warn("Failed to record validation error metric:",r)}},au=(s,e,t)=>{try{let n=Ct({error_type:"refusal",...e?{signature:e}:{},...t});s.validationErrorsCounter&&s.validationErrorsCounter.add(1,n)}catch(n){console.warn("Failed to record refusal error metric:",n)}},Pi=(s,e,t,n,r,o)=>{try{let i=Ct({success:t.toString(),...r?{signature:r}:{},...o});s.errorCorrectionAttemptsHistogram&&s.errorCorrectionAttemptsHistogram.record(e,i),t&&s.errorCorrectionSuccessCounter&&s.errorCorrectionSuccessCounter.add(1,i),t||(s.errorCorrectionFailureCounter&&s.errorCorrectionFailureCounter.add(1,i),e>=n&&s.maxRetriesReachedCounter&&s.maxRetriesReachedCounter.add(1,i))}catch(i){console.warn("Failed to record error correction metric:",i)}},lu=(s,e,t,n,r=!1,o,i)=>{try{let a=Ct({functions_enabled:e.toString(),had_function_calls:n.toString(),...o?{signature:o}:{},...i});e&&s.functionsEnabledGenerationsCounter&&s.functionsEnabledGenerationsCounter.add(1,a),n&&s.functionCallStepsCounter&&s.functionCallStepsCounter.add(1,a),t>0&&s.functionsExecutedPerGenerationHistogram&&s.functionsExecutedPerGenerationHistogram.record(t,a),r&&s.functionErrorCorrectionCounter&&s.functionErrorCorrectionCounter.add(1,a)}catch(a){console.warn("Failed to record function calling metric:",a)}},uu=(s,e,t,n,r)=>{try{let o=Ct({...n?{signature:n}:{},...r});e>0&&s.fieldProcessorsExecutedCounter&&s.fieldProcessorsExecutedCounter.add(e,o),t>0&&s.streamingFieldProcessorsExecutedCounter&&s.streamingFieldProcessorsExecutedCounter.add(t,o)}catch(o){console.warn("Failed to record field processing metric:",o)}},cu=(s,e,t,n,r,o)=>{try{let i=Ct({is_streaming:e.toString(),...r?{signature:r}:{},...o});e&&s.streamingGenerationsCounter&&s.streamingGenerationsCounter.add(1,i),t>0&&s.streamingDeltasEmittedCounter&&s.streamingDeltasEmittedCounter.add(t,i),n&&s.streamingFinalizationLatencyHistogram&&s.streamingFinalizationLatencyHistogram.record(n,i)}catch(i){console.warn("Failed to record streaming metric:",i)}},pu=(s,e,t,n,r,o)=>{try{let i=Ct({result_picker_used:t.toString(),...r?{signature:r}:{},...o});s.samplesGeneratedHistogram&&s.samplesGeneratedHistogram.record(e,i),t&&s.resultPickerUsageCounter&&s.resultPickerUsageCounter.add(1,i),n&&s.resultPickerLatencyHistogram&&s.resultPickerLatencyHistogram.record(n,i)}catch(i){console.warn("Failed to record samples metric:",i)}},du=(s,e,t,n,r,o,i)=>{try{let a=Ct({...o?{signature:o}:{},...i});s.inputFieldsGauge&&s.inputFieldsGauge.record(e,a),s.outputFieldsGauge&&s.outputFieldsGauge.record(t,a),s.examplesUsedGauge&&s.examplesUsedGauge.record(n,a),s.demosUsedGauge&&s.demosUsedGauge.record(r,a)}catch(a){console.warn("Failed to record signature complexity metrics:",a)}},Ho=(s,e,t,n,r)=>{try{let o=Ct({metric_type:e,...n?{signature:n}:{},...r});switch(e){case"prompt_render":s.promptRenderLatencyHistogram&&s.promptRenderLatencyHistogram.record(t,o);break;case"extraction":s.extractionLatencyHistogram&&s.extractionLatencyHistogram.record(t,o);break;case"assertion":s.assertionLatencyHistogram&&s.assertionLatencyHistogram.record(t,o);break;case"state_creation":s.stateCreationLatencyHistogram&&s.stateCreationLatencyHistogram.record(t,o);break;case"memory_update":s.memoryUpdateLatencyHistogram&&s.memoryUpdateLatencyHistogram.record(t,o);break}}catch(o){console.warn("Failed to record performance metric:",o)}};var _n=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},Ve=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()}},mu=s=>{let t=s.map(n=>`'${n.title}' (${_n(n.type)})`).join(", ");return new Ve(`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 ${_n(s[0]?.type)} value. Keep the output concise and avoid unrelated text.`)},Ko=s=>new Ve(`Expected (Required) field not found: '${s.title}'. Begin a new section with "${s.title}:" and then provide a valid ${_n(s.type)} value directly after.`);var Wo=s=>new Ve(`Required field is missing: '${s.title}'. After the "${s.title}:" label, provide a non-empty ${_n(s.type)}. Do not use null, undefined, or leave it blank.`),gu=(s,e)=>new Ve(`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.`),fu=(s,e)=>new Ve(`Invalid Array: ${e} for '${s.title}'. Provide a JSON array of ${_n(s.type)} items (e.g., [ ... ]). Markdown lists are also accepted if each item is on its own line starting with a hyphen.`),hu=(s,e,t)=>new Ve(`Field '${s.title}' has an invalid value '${e}': ${t}. Provide a ${_n(s.type)}. Ensure formatting exactly matches the expected type.`),xu=(s,e,t)=>new Ve(`Invalid date for '${s.title}': ${t}. Use the exact format YYYY-MM-DD (e.g., 2024-05-09). You provided: ${e}.`),Au=(s,e,t)=>new Ve(`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}.`),Fi=(s,e,t)=>new Ve(`Invalid URL for '${s.title}': ${t}. Use a valid URL format (e.g., https://example.com). You provided: ${e}.`),Nn=(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 Ve(r)},_i=(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 Ve(r)};var yu=({error:s,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:o,span:i,customLabels:a})=>{let l=s.getFixingInstructions();if(t&&n){let u=l?.map(c=>c.title).join(", ")??"";rl(s,e,u,n)}return r&&Ei(r,"validation",o,a),i&&i.addEvent("validation.error",{message:s.toString(),fixing_instructions:l?.map(u=>u.title).join(", ")??""}),l},bu=({error:s,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:o,span:i,customLabels:a})=>{let l=s.getFixingInstructions();if(t&&n){let u=l?.map(c=>c.title).join(", ")??"";ol(s,e,u,n)}return r&&Ei(r,"assertion",o,a),i&&i.addEvent("assertion.error",{message:s.toString(),fixing_instructions:l?.map(u=>u.title).join(", ")??""}),l},Iu=({error:s,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:o,span:i,customLabels:a})=>{t&&n&&sl(s,e,n),r&&au(r,o,a),i&&i.addEvent("refusal.error",{message:s.toString()})};var Dt=nr(Cu(),1),vu=nr(Tu(),1),Su=nr(wu(),1),ku=nr(Ru(),1);Dt.default.extend(ku.default);Dt.default.extend(Su.default);Dt.default.extend(vu.default);function Ou(s,e,t=!1){try{return ed(e)}catch(n){if(s.isOptional&&!t)return;let r=n.message;throw xu(s,e,r)}}function ed(s){if(!(0,Dt.default)(s,"YYYY-MM-DD",!0).isValid())throw new Error('Invalid date format. Please provide the date in "YYYY-MM-DD" format.');return Dt.default.utc(s,"YYYY-MM-DD").startOf("day").toDate()}function Mu(s,e,t=!1){try{return td(e)}catch(n){if(s.isOptional&&!t)return;let r=n.message;throw Au(s,e,r)}}function td(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=Dt.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 Eu=s=>(0,Dt.default)(s).utc().format("YYYY-MM-DD HH:mm:ss [UTC]");var oy=new rt,Mr=(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 Er(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 Pu=s=>{if(!s.trim())return[];let e=new Set(["-","*","+"]),t=/^\d+[\s]*[.)\]]\s*/,n=s.split(`
204
- `),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 zi(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 qi=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)}},nd=new qi(500);function Fu(s,e,t=0,n=nd){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 Gt(s,e){if(typeof s!="string")throw Fi(e,String(s),"URL must be a string");try{new URL(s)}catch{throw Fi(e,s,"Invalid URL format. Expected a valid URL like https://example.com")}}function dt(s,e){if(typeof s!="string")return;let t=e.type;if(t){if(t.minLength!==void 0&&s.length<t.minLength)throw Nn(e,s,"minLength",t.minLength);if(t.maxLength!==void 0&&s.length>t.maxLength)throw Nn(e,s,"maxLength",t.maxLength);if(t.pattern!==void 0&&!new RegExp(t.pattern).test(s))throw Nn(e,s,"pattern",t.pattern);if(t.format==="email"&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s))throw Nn(e,s,"format","valid email address");if(t.format==="uri"||t.format==="url")try{new URL(s)}catch{throw Nn(e,s,"format","valid URL")}}}function mt(s,e){if(typeof s!="number")return;let t=e.type;if(t){if(t.minimum!==void 0&&s<t.minimum)throw _i(e,s,"minimum",t.minimum);if(t.maximum!==void 0&&s>t.maximum)throw _i(e,s,"maximum",t.maximum)}}var Yo=(s,e,t,n)=>{let r=n?.strictMode??!1,o=n?.treatAllFieldsOptional??!1,i=n?.treatAllFieldsOptional??!1,a={extractedFields:[],streamedIndex:{},s:-1};Wi(s,e,a,t,{strictMode:r,skipEarlyFail:i,treatAllFieldsOptional:o}),Vi(s,e,a,t,{strictMode:r,treatAllFieldsOptional:o,forceFinalize:!0});for(let l of s.getOutputFields())l.isInternal&&delete e[l.name]},Hi=(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 mu(n)},Wi=(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 y=`${(t.extractedFields.length===0?"":`
205
- `)+f.title}:`,x=Fu(n,y,t.s);if(x===-2||x===-3)return!0;if(x===-4)return t.inBlock=!0,!0;x>=0&&(d===-1||x<d)&&(d=x,m=y.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 Ko(g)}break}if(a&&p&&a.name!==p.name)throw Ko(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=Vo(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)}},Vi=(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=`
206
- ${m.title}:`,f=n.indexOf(g,t.s);f!==-1&&f<u&&(u=f)}let p=n.substring(t.s,u).trim(),d=Vo(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 Ko(p)}if(rd(s,e,n,t),!i){let u=t.currField!==void 0||(t.extractedFields?.length??0)>0;o||l?Hi(t,e,s.getOutputFields()):u||Hi(t,e,s.getOutputFields())}},rd=(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=`
207
- ${i.title}:`,p=t.indexOf(c,u),d=t.substring(u,p===-1?t.length:p).trim();if(d)try{let m=Vo(i,d);if(m!==void 0){e[i.name]=m;return}}catch{}}}}let o=t.split(`
208
- `);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=Vo(i,c);if(p!==void 0){e[i.name]=p;break}}catch(p){if(!i.isOptional)throw p}break}}}},_u=(s,e,t=!1)=>{switch(s.type?.name){case"code":return Ki(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 Ou(s,e,t);case"datetime":return Mu(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*Nu(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*Ji(s,e,t,n,r){for(let i of n.prevFields??[]){let{field:a,s:l,e:u}=i;yield*Nu(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*Nu(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 Vo(s,e){if(!e||e===""||/^(null|undefined)\s*$/i.test(e)){if(s.isOptional)return;throw Wo(s)}let t;if(s.type?.name==="json"&&!s.type?.isArray)try{let r=Ki(e);return t=JSON.parse(r),t}catch(r){throw gu(s,r.message)}if(s.type?.isArray)try{try{t=JSON.parse(e)}catch{t=Pu(e)}if(!Array.isArray(t))throw new Error("Expected an array")}catch(r){let o=r.message;if(o.includes("no valid list items found")||o==="Expected an array")t=[e];else throw fu(s,o)}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=Ki(i);i=JSON.parse(a)}catch{}t[r]=_u(s,i,!0)}}else t=_u(s,e)}catch(r){throw hu(s,e,r.message)}if(typeof t=="string"&&t==="")return;let n=s.type;if(n&&t!==void 0&&(n.name==="url"&&Gt(t,s),(n.name==="string"||n.name==="code")&&dt(t,s),n.name==="number"&&mt(t,s),n.isArray&&Array.isArray(t)))for(let r of t)r!==void 0&&(n.name==="string"||n.name==="code"?dt(r,s):n.name==="number"&&mt(r,s));return t}function $n(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 Wo(r);continue}let i=r.type;if(i){if(i.name==="url"&&Gt(o,r),(i.name==="string"||i.name==="code")&&dt(o,r),i.name==="number"&&mt(o,r),i.isArray&&Array.isArray(o))for(let a of o)a!=null&&(i.name==="url"?Gt(a,r):i.name==="string"||i.name==="code"?dt(a,r):i.name==="number"&&mt(a,r));if(i.name==="object"&&i.fields&&typeof o=="object"&&!Array.isArray(o)&&Jo(r,o,t),i.isArray&&i.fields&&Array.isArray(o)&&i.name==="object")for(let a of o)a&&typeof a=="object"&&Jo(r,a,t)}}}function Jo(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 Wo(i);continue}let l=i.type;if(l){if(l.name==="url"&&Gt(a,i),(l.name==="string"||l.name==="code")&&dt(a,i),l.name==="number"&&mt(a,i),l.isArray&&Array.isArray(a))for(let u of a)u!=null&&(l.name==="url"?Gt(u,i):l.name==="string"||l.name==="code"?dt(u,i):l.name==="number"&&mt(u,i));if(l.name==="object"&&l.fields&&typeof a=="object"&&!Array.isArray(a)&&Jo(i,a,t),l.isArray&&l.fields&&Array.isArray(a)&&l.name==="object")for(let u of a)u&&typeof u=="object"&&Jo(i,u,t)}}}var Ki=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 Pr(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});$u(r.field,t,i,n)}}async function Yi(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});$u(t.currField,n,c,o)}}var $u=(s,e,t,n)=>{if(t===void 0||typeof t=="string"&&(t===""||/^(null|undefined)\s*$/i.test(t)))return;let r=String(t),o=r;e.addRequest([{role:"user",content:[{type:"text",text:o}]}],n),e.addTag("processor",n)};function Lu(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 Ln(s,e="Schema"){if("name"in s&&"type"in s)return Qo(s);let t={},n=[];for(let r of s){if(r.isInternal)continue;let o=Qo(r);t[r.name]=o,r.isOptional||n.push(r.name)}return{type:"object",title:e,properties:t,required:n,additionalProperties:!1}}function Qo(s,e=!1){let t=s.type,n=Lu(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]=Qo(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=Lu(t.description||s.description,t);r.items={type:Du(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]=Qo(a,!0),i.isOptional||r.required.push(o)}}else t?.name==="class"&&t.options?(r.type="string",r.enum=t.options):(r.type=Du(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 Du(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 Xo(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)');Xo(s.items)}else if(s.type==="object"&&s.properties)for(let e of Object.values(s.properties))Xo(e)}var Wt=class extends Error{calls;constructor(e){super(`Stop function executed: ${e.map(t=>t.func.name).join(", ")}`),this.name="AxStopFunctionCallException",this.calls=e}},Fr=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(`
209
- `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},_r=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}'
203
+ `,o=l}),(o>t||n.length===0)&&n.push(r.trim()),n},Ed=(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 Sr=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}},kn=class{memories=new Map;defaultMemory;constructor(){this.defaultMemory=new Sr}getMemory(e){return e?(this.memories.has(e)||this.memories.set(e,new Sr),this.memories.get(e)):this.defaultMemory}addRequest(e,t){for(let n of e)nn(n);this.getMemory(t).addRequest(e,0)}addResponse(e,t){mo(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 Sr):this.defaultMemory.reset()}};function St(s,e){if(!s&&!e)return;if(!s)return e;if(!e||s===e||s.aborted)return s;if(e.aborted)return e;if(typeof AbortSignal.any=="function")return AbortSignal.any([s,e]);let t=new AbortController,n=()=>{t.abort(s.aborted?s.reason:e.reason),r()},r=()=>{s.removeEventListener("abort",n),e.removeEventListener("abort",n)};return s.addEventListener("abort",n,{once:!0}),e.addEventListener("abort",n,{once:!0}),t.signal}var xt=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()}},On=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 xt({message:o});if(!o)throw r?new xt({message:r}):new Error("Assertion Failed: No message provided for assertion")}}},_i=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 xt({message:u});if(!u&&a)throw new xt({message:a})}}};var Ni={enabled:!0,enabledCategories:["generation","streaming","functions","errors","performance"],maxLabelLength:100,samplingRate:1},kr,$i=s=>{if(kr)return kr;let e=s??ce.meter;if(e)return kr=Pd(e),kr};var hu=()=>{let s=[];return ce.meter||s.push("Global meter not initialized"),!kr&&ce.meter&&s.push("Metrics instruments not created despite available meter"),{healthy:s.length===0,issues:s}},Pd=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"})}),Ho=Ni,xu=s=>{Ho={...Ho,...s}},Au=()=>({...Ho}),gt=s=>{let e={};for(let[t,n]of Object.entries(s))if(n!=null){let r=String(n),o=Ho.maxLabelLength;e[t]=r.length>o?r.substring(0,o):r}return e};var yu=(s,e,t,n,r,o,i)=>{try{let a=gt({success:t.toString(),...n?{signature:n}:{},...r?{ai_service:r}:{},...o?{model:o}:{},...i});s.generationLatencyHistogram&&s.generationLatencyHistogram.record(e,a),s.generationRequestsCounter&&s.generationRequestsCounter.add(1,a),!t&&s.generationErrorsCounter&&s.generationErrorsCounter.add(1,a)}catch(a){console.warn("Failed to record generation metric:",a)}},Ko=(s,e,t,n,r)=>{try{let o=gt({...n?{signature:n}:{},...r});e>1&&s.multiStepGenerationsCounter&&s.multiStepGenerationsCounter.add(1,o),s.stepsPerGenerationHistogram&&s.stepsPerGenerationHistogram.record(e,o),e>=t&&s.maxStepsReachedCounter&&s.maxStepsReachedCounter.add(1,o)}catch(o){console.warn("Failed to record multi-step metric:",o)}},Li=(s,e,t,n)=>{try{let r=gt({error_type:e,...t?{signature:t}:{},...n});e==="validation"&&s.validationErrorsCounter&&s.validationErrorsCounter.add(1,r),e==="assertion"&&s.assertionErrorsCounter&&s.assertionErrorsCounter.add(1,r)}catch(r){console.warn("Failed to record validation error metric:",r)}},bu=(s,e,t)=>{try{let n=gt({error_type:"refusal",...e?{signature:e}:{},...t});s.validationErrorsCounter&&s.validationErrorsCounter.add(1,n)}catch(n){console.warn("Failed to record refusal error metric:",n)}},Di=(s,e,t,n,r,o)=>{try{let i=gt({success:t.toString(),...r?{signature:r}:{},...o});s.errorCorrectionAttemptsHistogram&&s.errorCorrectionAttemptsHistogram.record(e,i),t&&s.errorCorrectionSuccessCounter&&s.errorCorrectionSuccessCounter.add(1,i),t||(s.errorCorrectionFailureCounter&&s.errorCorrectionFailureCounter.add(1,i),e>=n&&s.maxRetriesReachedCounter&&s.maxRetriesReachedCounter.add(1,i))}catch(i){console.warn("Failed to record error correction metric:",i)}},Iu=(s,e,t,n,r=!1,o,i)=>{try{let a=gt({functions_enabled:e.toString(),had_function_calls:n.toString(),...o?{signature:o}:{},...i});e&&s.functionsEnabledGenerationsCounter&&s.functionsEnabledGenerationsCounter.add(1,a),n&&s.functionCallStepsCounter&&s.functionCallStepsCounter.add(1,a),t>0&&s.functionsExecutedPerGenerationHistogram&&s.functionsExecutedPerGenerationHistogram.record(t,a),r&&s.functionErrorCorrectionCounter&&s.functionErrorCorrectionCounter.add(1,a)}catch(a){console.warn("Failed to record function calling metric:",a)}},Cu=(s,e,t,n,r)=>{try{let o=gt({...n?{signature:n}:{},...r});e>0&&s.fieldProcessorsExecutedCounter&&s.fieldProcessorsExecutedCounter.add(e,o),t>0&&s.streamingFieldProcessorsExecutedCounter&&s.streamingFieldProcessorsExecutedCounter.add(t,o)}catch(o){console.warn("Failed to record field processing metric:",o)}},Tu=(s,e,t,n,r,o)=>{try{let i=gt({is_streaming:e.toString(),...r?{signature:r}:{},...o});e&&s.streamingGenerationsCounter&&s.streamingGenerationsCounter.add(1,i),t>0&&s.streamingDeltasEmittedCounter&&s.streamingDeltasEmittedCounter.add(t,i),n&&s.streamingFinalizationLatencyHistogram&&s.streamingFinalizationLatencyHistogram.record(n,i)}catch(i){console.warn("Failed to record streaming metric:",i)}},wu=(s,e,t,n,r,o)=>{try{let i=gt({result_picker_used:t.toString(),...r?{signature:r}:{},...o});s.samplesGeneratedHistogram&&s.samplesGeneratedHistogram.record(e,i),t&&s.resultPickerUsageCounter&&s.resultPickerUsageCounter.add(1,i),n&&s.resultPickerLatencyHistogram&&s.resultPickerLatencyHistogram.record(n,i)}catch(i){console.warn("Failed to record samples metric:",i)}},Ru=(s,e,t,n,r,o,i)=>{try{let a=gt({...o?{signature:o}:{},...i});s.inputFieldsGauge&&s.inputFieldsGauge.record(e,a),s.outputFieldsGauge&&s.outputFieldsGauge.record(t,a),s.examplesUsedGauge&&s.examplesUsedGauge.record(n,a),s.demosUsedGauge&&s.demosUsedGauge.record(r,a)}catch(a){console.warn("Failed to record signature complexity metrics:",a)}},Wo=(s,e,t,n,r)=>{try{let o=gt({metric_type:e,...n?{signature:n}:{},...r});switch(e){case"prompt_render":s.promptRenderLatencyHistogram&&s.promptRenderLatencyHistogram.record(t,o);break;case"extraction":s.extractionLatencyHistogram&&s.extractionLatencyHistogram.record(t,o);break;case"assertion":s.assertionLatencyHistogram&&s.assertionLatencyHistogram.record(t,o);break;case"state_creation":s.stateCreationLatencyHistogram&&s.stateCreationLatencyHistogram.record(t,o);break;case"memory_update":s.memoryUpdateLatencyHistogram&&s.memoryUpdateLatencyHistogram.record(t,o);break}}catch(o){console.warn("Failed to record performance metric:",o)}};var Mn=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},De=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()}},vu=s=>{let t=s.map(n=>`'${n.title}' (${Mn(n.type)})`).join(", ");return new De(`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 ${Mn(s[0]?.type)} value. Keep the output concise and avoid unrelated text.`)},Vo=s=>new De(`Expected (Required) field not found: '${s.title}'. Begin a new section with "${s.title}:" and then provide a valid ${Mn(s.type)} value directly after.`);var Jo=s=>new De(`Required field is missing: '${s.title}'. After the "${s.title}:" label, provide a non-empty ${Mn(s.type)}. Do not use null, undefined, or leave it blank.`),Su=(s,e)=>new De(`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.`),ku=(s,e)=>new De(`Invalid Array: ${e} for '${s.title}'. Provide a JSON array of ${Mn(s.type)} items (e.g., [ ... ]). Markdown lists are also accepted if each item is on its own line starting with a hyphen.`),Ou=(s,e,t)=>new De(`Field '${s.title}' has an invalid value '${e}': ${t}. Provide a ${Mn(s.type)}. Ensure formatting exactly matches the expected type.`),Mu=(s,e,t)=>new De(`Invalid date for '${s.title}': ${t}. Use the exact format YYYY-MM-DD (e.g., 2024-05-09). You provided: ${e}.`),Eu=(s,e,t)=>new De(`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}.`),Gi=(s,e,t)=>new De(`Invalid URL for '${s.title}': ${t}. Use a valid URL format (e.g., https://example.com). You provided: ${e}.`),En=(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 De(r)},Ui=(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 De(r)};var Pu=({error:s,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:o,span:i,customLabels:a})=>{let l=s.getFixingInstructions();if(t&&n){let u=l?.map(c=>c.title).join(", ")??"";hl(s,e,u,n)}return r&&Li(r,"validation",o,a),i&&i.addEvent("validation.error",{message:s.toString(),fixing_instructions:l?.map(u=>u.title).join(", ")??""}),l},Fu=({error:s,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:o,span:i,customLabels:a})=>{let l=s.getFixingInstructions();if(t&&n){let u=l?.map(c=>c.title).join(", ")??"";xl(s,e,u,n)}return r&&Li(r,"assertion",o,a),i&&i.addEvent("assertion.error",{message:s.toString(),fixing_instructions:l?.map(u=>u.title).join(", ")??""}),l},_u=({error:s,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:o,span:i,customLabels:a})=>{t&&n&&Al(s,e,n),r&&bu(r,o,a),i&&i.addEvent("refusal.error",{message:s.toString()})};var Nt=tr(Nu(),1),Gu=tr($u(),1),Uu=tr(Lu(),1),Bu=tr(Du(),1);Nt.default.extend(Bu.default);Nt.default.extend(Uu.default);Nt.default.extend(Gu.default);function ju(s,e,t=!1){try{return Fd(e)}catch(n){if(s.isOptional&&!t)return;let r=n.message;throw Mu(s,e,r)}}function Fd(s){if(!(0,Nt.default)(s,"YYYY-MM-DD",!0).isValid())throw new Error('Invalid date format. Please provide the date in "YYYY-MM-DD" format.');return Nt.default.utc(s,"YYYY-MM-DD").startOf("day").toDate()}function qu(s,e,t=!1){try{return _d(e)}catch(n){if(s.isOptional&&!t)return;let r=n.message;throw Eu(s,e,r)}}function _d(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=Nt.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 zu=s=>(0,Nt.default)(s).utc().format("YYYY-MM-DD HH:mm:ss [UTC]");var Jy=new Ke,Or=(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 Mr(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 Hu=s=>{if(!s.trim())return[];let e=new Set(["-","*","+"]),t=/^\d+[\s]*[.)\]]\s*/,n=s.split(`
204
+ `),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 Yi(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 Ji=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)}},Nd=new Ji(500);function Ku(s,e,t=0,n=Nd){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 $t(s,e){if(typeof s!="string")throw Gi(e,String(s),"URL must be a string");try{new URL(s)}catch{throw Gi(e,s,"Invalid URL format. Expected a valid URL like https://example.com")}}function st(s,e){if(typeof s!="string")return;let t=e.type;if(t){if(t.minLength!==void 0&&s.length<t.minLength)throw En(e,s,"minLength",t.minLength);if(t.maxLength!==void 0&&s.length>t.maxLength)throw En(e,s,"maxLength",t.maxLength);if(t.pattern!==void 0&&!new RegExp(t.pattern).test(s))throw En(e,s,"pattern",t.pattern);if(t.format==="email"&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s))throw En(e,s,"format","valid email address");if(t.format==="uri"||t.format==="url")try{new URL(s)}catch{throw En(e,s,"format","valid URL")}}}function it(s,e){if(typeof s!="number")return;let t=e.type;if(t){if(t.minimum!==void 0&&s<t.minimum)throw Ui(e,s,"minimum",t.minimum);if(t.maximum!==void 0&&s>t.maximum)throw Ui(e,s,"maximum",t.maximum)}}var Xo=(s,e,t,n)=>{let r=n?.strictMode??!1,o=n?.treatAllFieldsOptional??!1,i=n?.treatAllFieldsOptional??!1,a={extractedFields:[],streamedIndex:{},s:-1};Zi(s,e,a,t,{strictMode:r,skipEarlyFail:i,treatAllFieldsOptional:o}),ea(s,e,a,t,{strictMode:r,treatAllFieldsOptional:o,forceFinalize:!0});for(let l of s.getOutputFields())l.isInternal&&delete e[l.name]},Qi=(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 vu(n)},Zi=(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 A=`${(t.extractedFields.length===0?"":`
205
+ `)+f.title}:`,x=Ku(n,A,t.s);if(x===-2||x===-3)return!0;if(x===-4)return t.inBlock=!0,!0;x>=0&&(d===-1||x<d)&&(d=x,m=A.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 Vo(g)}break}if(a&&p&&a.name!==p.name)throw Vo(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=Yo(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)}},ea=(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=`
206
+ ${m.title}:`,f=n.indexOf(g,t.s);f!==-1&&f<u&&(u=f)}let p=n.substring(t.s,u).trim(),d=Yo(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 Vo(p)}if($d(s,e,n,t),!i){let u=t.currField!==void 0||(t.extractedFields?.length??0)>0;o||l?Qi(t,e,s.getOutputFields()):u||Qi(t,e,s.getOutputFields())}},$d=(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=`
207
+ ${i.title}:`,p=t.indexOf(c,u),d=t.substring(u,p===-1?t.length:p).trim();if(d)try{let m=Yo(i,d);if(m!==void 0){e[i.name]=m;return}}catch{}}}}let o=t.split(`
208
+ `);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=Yo(i,c);if(p!==void 0){e[i.name]=p;break}}catch(p){if(!i.isOptional)throw p}break}}}},Wu=(s,e,t=!1)=>{switch(s.type?.name){case"code":return Xi(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 ju(s,e,t);case"datetime":return qu(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*Vu(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*ta(s,e,t,n,r){for(let i of n.prevFields??[]){let{field:a,s:l,e:u}=i;yield*Vu(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*Vu(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 Yo(s,e){if(!e||e===""||/^(null|undefined)\s*$/i.test(e)){if(s.isOptional)return;throw Jo(s)}let t;if(s.type?.name==="json"&&!s.type?.isArray)try{let r=Xi(e);return t=JSON.parse(r),t}catch(r){throw Su(s,r.message)}if(s.type?.isArray)try{try{t=JSON.parse(e)}catch{t=Hu(e)}if(!Array.isArray(t))throw new Error("Expected an array")}catch(r){let o=r.message;if(o.includes("no valid list items found")||o==="Expected an array")t=[e];else throw ku(s,o)}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=Xi(i);i=JSON.parse(a)}catch{}t[r]=Wu(s,i,!0)}}else t=Wu(s,e)}catch(r){throw Ou(s,e,r.message)}if(typeof t=="string"&&t==="")return;let n=s.type;if(n&&t!==void 0&&(n.name==="url"&&$t(t,s),(n.name==="string"||n.name==="code")&&st(t,s),n.name==="number"&&it(t,s),n.isArray&&Array.isArray(t)))for(let r of t)r!==void 0&&(n.name==="string"||n.name==="code"?st(r,s):n.name==="number"&&it(r,s));return t}function Pn(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 Jo(r);continue}let i=r.type;if(i){if(i.name==="url"&&$t(o,r),(i.name==="string"||i.name==="code")&&st(o,r),i.name==="number"&&it(o,r),i.isArray&&Array.isArray(o))for(let a of o)a!=null&&(i.name==="url"?$t(a,r):i.name==="string"||i.name==="code"?st(a,r):i.name==="number"&&it(a,r));if(i.name==="object"&&i.fields&&typeof o=="object"&&!Array.isArray(o)&&Qo(r,o,t),i.isArray&&i.fields&&Array.isArray(o)&&i.name==="object")for(let a of o)a&&typeof a=="object"&&Qo(r,a,t)}}}function Qo(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 Jo(i);continue}let l=i.type;if(l){if(l.name==="url"&&$t(a,i),(l.name==="string"||l.name==="code")&&st(a,i),l.name==="number"&&it(a,i),l.isArray&&Array.isArray(a))for(let u of a)u!=null&&(l.name==="url"?$t(u,i):l.name==="string"||l.name==="code"?st(u,i):l.name==="number"&&it(u,i));if(l.name==="object"&&l.fields&&typeof a=="object"&&!Array.isArray(a)&&Qo(i,a,t),l.isArray&&l.fields&&Array.isArray(a)&&l.name==="object")for(let u of a)u&&typeof u=="object"&&Qo(i,u,t)}}}var Xi=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 Er(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});Ju(r.field,t,i,n)}}async function na(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});Ju(t.currField,n,c,o)}}var Ju=(s,e,t,n)=>{if(t===void 0||typeof t=="string"&&(t===""||/^(null|undefined)\s*$/i.test(t)))return;let r=String(t),o=r;e.addRequest([{role:"user",content:[{type:"text",text:o}]}],n),e.addTag("processor",n)};function Yu(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 Lt(s,e="Schema"){if("name"in s&&"type"in s)return Zo(s);let t={},n=[];for(let r of s){if(r.isInternal)continue;let o=Zo(r);t[r.name]=o,r.isOptional||n.push(r.name)}return{type:"object",title:e,properties:t,required:n,additionalProperties:!1}}function Zo(s,e=!1){let t=s.type,n=Yu(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]=Zo(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=Yu(t.description||s.description,t);r.items={type:Qu(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]=Zo(a,!0),i.isOptional||r.required.push(o)}}else t?.name==="class"&&t.options?(r.type="string",r.enum=t.options):(r.type=Qu(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 Qu(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 es(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)');es(s.items)}else if(s.type==="object"&&s.properties)for(let e of Object.values(s.properties))es(e)}var zt=class extends Error{calls;constructor(e){super(`Stop function executed: ${e.map(t=>t.func.name).join(", ")}`),this.name="AxStopFunctionCallException",this.calls=e}},Pr=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(`
209
+ `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},Fr=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}'
210
210
  ${t.join(`
211
211
  `)}`};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(`
212
- `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},Nr=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,step:n.step,abortSignal:n.abortSignal}: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??fe.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 Fr?new _r(i.getFields(),o,e.id):i}};execute=async(e,t)=>(await this.executeWithDetails(e,t)).formatted},Vt=(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{Xo(n.parameters)}catch(r){throw r instanceof Error?new Error(`Function '${n.name}' parameters schema is invalid.
212
+ `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},_r=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,step:n.step,abortSignal:n.abortSignal}: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??ce.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 Pr?new Fr(i.getFields(),o,e.id):i}};execute=async(e,t)=>(await this.executeWithDetails(e,t)).formatted},Ht=(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{es(n.parameters)}catch(r){throw r instanceof Error?new Error(`Function '${n.name}' parameters schema is invalid.
213
213
  ${r.message}
214
- Tip: Arrays must include an "items" schema (e.g., { items: { type: "string" } } or items: { type: "object", properties: { ... } }).`,{cause:r}):r}return[...e??[],...t]},Zo=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,step:m,abortSignal:g})=>{let f=new Nr(e),h=new Set,y=[],x=w=>{let v=D=>D.replace(/[^a-zA-Z0-9]/g,"").toLowerCase(),F=v(w),O=e.find(D=>D.name===w);return O||(O=e.find(D=>v(D.name)===F)),O},b=t.map(w=>{if(!w.id)throw new Error(`Function ${w.name} did not return an ID`);let v=s.getOptions().tracer??fe.tracer;return v?v.startActiveSpan(`Tool: ${w.name}`,async F=>{try{F?.setAttributes?.({"tool.name":w.name,"tool.mode":"native","function.id":w.id,"session.id":r??""});let{formatted:O,rawResult:D,parsedArgs:U}=await f.executeWithDetails(w,{sessionId:r,ai:s,functionResultFormatter:u,traceId:F?.spanContext?.().traceId??o,stopFunctionNames:d,step:m,abortSignal:g});if(h.add(w.name.toLowerCase()),m?._recordFunctionCall(w.name,U,D),d?.includes(w.name.toLowerCase())){let L=x(w.name);L&&y.push({func:L,args:U,result:D})}if(a?F.addEvent("gen_ai.tool.message",{name:w.name}):F.addEvent("gen_ai.tool.message",{name:w.name,args:w.args,result:O??""}),i){let L={name:w.name};a||(L.args=w.args,L.result=O??""),i.addEvent("function.call",L)}return{result:O??"",role:"function",functionId:w.id,index:l}}catch(O){if(F?.recordException?.(O),O instanceof _r){let D=O.getFixingInstructions(),U={name:w.name,message:O.toString()};return a||(U.args=w.args,U.fixing_instructions=D),F?.addEvent?.("function.error",U),p&&Xs(O,l,D,c),{functionId:w.id,isError:!0,index:l,result:D,role:"function"}}throw O}finally{F?.end?.()}}):f.executeWithDetails(w,{sessionId:r,ai:s,functionResultFormatter:u,traceId:o,stopFunctionNames:d,step:m,abortSignal:g}).then(({formatted:F,rawResult:O,parsedArgs:D})=>{if(h.add(w.name.toLowerCase()),m?._recordFunctionCall(w.name,D,O),d?.includes(w.name.toLowerCase())){let U=x(w.name);U&&y.push({func:U,args:D,result:O})}if(i){let U={name:w.name};a||(U.args=w.args,U.result=F??""),i.addEvent("function.call",U)}return{result:F??"",role:"function",functionId:w.id,index:l}}).catch(F=>{if(!(F instanceof _r))throw F;let O=F.getFixingInstructions();if(i){let D={name:w.name,message:F.toString()};a||(D.args=w.args,D.fixing_instructions=O),i.addEvent("function.error",D)}return p&&Xs(F,l,O,c),{functionId:w.id,isError:!0,index:l,result:O,role:"function"}})}),A=(await Promise.all(b)).map(w=>w.result===void 0||w.result===""?{...w,result:"done"}:w);if(n.addFunctionResults(A,r),p){let w=A.filter(v=>!v.isError);w.length>0&&nl(w,c)}if(y.length>0)throw new Wt(y);return h};function Qi(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 Gu(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 od(s){let e=0,t=!1,n=!1,r=!1,o=!1,i=[];for(let a=0;a<s.length;a++){let l=s[a];if(n){n=!1;continue}if(l==="\\"){n=!0;continue}if(l==='"'){t=!t;continue}t||(l==="{"?(i.push("{"),e++):l==="["?(i.push("["),e++):l==="}"?i.length>0&&i[i.length-1]==="{"&&(i.pop(),e--):l==="]"&&i.length>0&&i[i.length-1]==="["&&(i.pop(),e--))}if(i.length>0){let a=i[i.length-1];r=a==="[",o=a==="{"}return{nestingLevel:e,inString:t,inArray:r,inObject:o}}function Uu(s){if(!s.trim())return{parsed:null,partialMarker:null};try{return{parsed:JSON.parse(s),partialMarker:null}}catch{}let e=od(s),t=sd(s);try{return{parsed:JSON.parse(t),partialMarker:e}}catch{return{parsed:null,partialMarker:e}}}function sd(s){let e=s.trim();for(e.endsWith(",")&&(e=e.slice(0,-1)),e.match(/,\s*"[^"]*"\s*:\s*$/)?e=e.replace(/,\s*"[^"]*"\s*:\s*$/,""):e.match(/\{\s*"[^"]*"\s*:\s*$/)&&(e=e.replace(/"[^"]*"\s*:\s*$/,""));e.match(/[0-9][eE.+-]$/)||e.match(/[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}async function*Bu({res:s,usage:e,states:t,debug:n,stepContext:r,...o}){let i=(o.ai.getFeatures().functionCot??!1)&&o.functions!==void 0&&o.functions.length>0,a,l=[],u=s.getReader();try{for(;;){let{done:c,value:p}=await u.read();if(c)break;let d=p;d.modelUsage&&(a=d.modelUsage);for(let m of d.results){if(Array.isArray(m.citations))for(let f of m.citations)f?.url&&l.push({url:f.url,title:f.title,description:f.description,license:f.license,publicationDate:f.publicationDate,snippet:f.snippet});if((!m.content||m.content==="")&&(!m.thought||m.thought==="")&&(!m.thoughtBlocks||m.thoughtBlocks.length===0)&&(!m.functionCalls||m.functionCalls.length===0))continue;let g=t.find(f=>f.index===m.index);if(!g)throw new Error(`No state found for result (index: ${m.index})`);yield*id({...o,result:m,skipEarlyFail:i,state:g,debug:n})}}}finally{u.releaseLock()}for(let c of t)yield*ad({...o,state:c,debug:n,stepContext:r});if(a){if(l.length){let c=Array.from(new Map(l.filter(p=>p.url).map(p=>[p.url,p])).values());a.citations=c}if(e.push(a),n&&o.logger){let c=structuredClone(a);delete c.citations,o.logger({name:"ChatResponseUsage",value:c}),a.citations&&a.citations.length>0&&o.logger({name:"ChatResponseCitations",value:a.citations})}}}async function*id({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)ao(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{parsed:f,partialMarker:h}=Uu(i.content);if(f&&typeof f=="object"){let y={},x={};for(let b of Object.keys(f))if(d.some(R=>R.name===b)){let R=f[b],A=i.values[b];if(Array.isArray(R)&&R.length>0&&ld(R,h)&&(R=R.slice(0,-1)),x[b]=R,typeof R=="string"&&typeof A=="string"&&R.startsWith(A)){let w=R.slice(A.length);w&&(y[b]=w)}else Array.isArray(R)&&Array.isArray(A)?R.length>A.length&&(y[b]=R.slice(A.length)):JSON.stringify(R)!==JSON.stringify(A)&&(Array.isArray(R)||(y[b]=R))}try{$n(a,x,{allowMissingRequired:!0})}catch{}Object.assign(i.values,x),Object.keys(y).length>0&&(yield{index:s.index,delta:y});return}}if(Wi(a,i.values,i.xstate,i.content,{strictMode:n,skipEarlyFail:r,treatAllFieldsOptional:o}))return;c.length!==0&&await ki(c,i.xstate,i.content),l.length!==0&&await Yi(l,i.content,i.xstate,e,i.values,t),yield*Ji(a,i.content,i.values,i.xstate,s.index),await Fn(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*ad({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:y,debug:x,stopFunctionNames:b,stepContext:R,abortSignal:A}){let w=h?void 0:Qi(t,s.functionCalls,s.values,n);if(w){if(!r)throw new Error("Functions are not defined");let v=await Zo({ai:t,functionList:r,functionCalls:w,mem:o,sessionId:i,traceId:a,span:l,index:s.index,excludeContentFromTrace:c,functionResultFormatter:f,logger:y,debug:x,stopFunctionNames:b,step:R,abortSignal:A});s.functionsExecuted=new Set([...s.functionsExecuted,...v]),s.functionCalls=[]}else{let v=e.getOutputFields(),F=e.hasComplexFields(),O=!1;if(F)try{let D=JSON.parse(s.content),U={};for(let L of Object.keys(D))if(v.some(T=>T.name===L)){let T=D[L],M=s.values[L];if(typeof T=="string"&&typeof M=="string"&&T.startsWith(M)){let E=T.slice(M.length);E&&(U[L]=E)}else Array.isArray(T)&&Array.isArray(M)?T.length>M.length&&(U[L]=T.slice(M.length)):JSON.stringify(T)!==JSON.stringify(M)&&(Array.isArray(T)||(U[L]=T))}try{$n(e,U,{allowMissingRequired:!0})}catch(L){let T=(L.message||"").toLowerCase();if(T.includes("at least")||T.includes("at most")||T.includes("must match pattern")||T.includes("invalid url")||T.includes("required")||T.includes("missing")||T.includes("valid email")||T.includes("number must be"))throw L}for(let L of Object.keys(D))v.some(T=>T.name===L)&&(s.values[L]=D[L]);yield{index:s.index,delta:U},O=!0}catch(D){let U=(D.message||"").toLowerCase();if(U.includes("at least")||U.includes("at most")||U.includes("must match pattern")||U.includes("invalid url")||U.includes("required")||U.includes("missing")||U.includes("valid email")||U.includes("number must be"))throw D}if(!O){let D=h!==void 0;Vi(e,s.values,s.xstate,s.content,{strictMode:u,treatAllFieldsOptional:D,deferRequiredCheckForStreaming:!0,forceFinalize:!0})}if(h){let D=await h.processResults(s.values);if(D&&D.length>0){if(!r)throw new Error("Functions are not defined");let U=await Zo({ai:t,functionList:r,functionCalls:D,mem:o,sessionId:i,traceId:a,span:l,index:s.index,excludeContentFromTrace:c,functionResultFormatter:f,logger:y,debug:x,stopFunctionNames:b,step:R,abortSignal:A});s.functionsExecuted=new Set([...s.functionsExecuted,...U]),o.updateResult({name:void 0,content:s.content,functionCalls:D.map(L=>({id:L.id,type:"function",function:{name:L.name,params:L.args}})),index:s.index},i);return}}await ki(p,s.xstate,s.content,!0),await Fn(d,s.values),m.length&&await Pr(m,s.values,o,i),g.length!==0&&await Yi(g,s.content,s.xstate,o,s.values,i,!0),yield*Ji(e,s.content,s.values,s.xstate,s.index)}}async function*ju({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:y,signatureToolCallingManager:x,stopFunctionNames:b,disableMemoryCleanup:R,stepContext:A,abortSignal:w}){let v=e.results??[],F=x!==void 0;t.addResponse(v,n);let O=[];for(let T of v)if(Array.isArray(T?.citations))for(let M of T.citations)M?.url&&O.push({url:M.url,title:M.title,description:M.description,license:M.license,publicationDate:M.publicationDate,snippet:M.snippet});for(let T of v){let M=l[T.index];if(!M)throw new Error(`No state found for result (index: ${T.index})`);if(e.modelUsage){let E=Array.from(new Map(O.filter(P=>P.url).map(P=>[P.url,P])).values()),N={...e.modelUsage,...E.length?{citations:E}:{}};if(u.push(N),y&&h){let P=structuredClone(N);delete P.citations,h({name:"ChatResponseUsage",value:P}),N.citations&&N.citations.length>0&&h({name:"ChatResponseCitations",value:N.citations})}}if(x&&T.content){T.thought&&T.thought.length>0&&(M.values[m]=T.thought),Yo(g,M.values,T.content,{strictMode:a,treatAllFieldsOptional:F});let N=(await x.processResults(M.values))?.map(P=>({id:P.id,type:"function",function:{name:P.name,params:P.args}}));N&&N.length>0&&t.updateResult({name:T.name,content:T.content,functionCalls:N,index:T.index},n)}if(T.functionCalls?.length){let E=Qi(s,T.functionCalls,M.values);if(E&&E.length>0){if(!o)throw new Error("Functions are not defined");let N;try{N=await Zo({ai:s,functionList:o,functionCalls:E,mem:t,sessionId:n,traceId:r,span:i,excludeContentFromTrace:c,index:T.index,functionResultFormatter:f,logger:h,debug:y,stopFunctionNames:b,step:A,abortSignal:w})}catch(P){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),P}M.functionsExecuted=new Set([...M.functionsExecuted,...N])}}else if(T.content){T.thought&&T.thought.length>0&&(M.values[m]=T.thought);let E=g.getOutputFields();if(g.hasComplexFields())try{let P=JSON.parse(T.content),_={};for(let G of Object.keys(P))E.some($=>$.name===G)&&(_[G]=P[G]);$n(g,_),Object.assign(M.values,_)}catch(P){let _=P instanceof SyntaxError;if((P.name?.includes("ValidationError")||P.name?.includes("Error"))&&!_){let $=(P.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 P}if(_)Yo(g,M.values,T.content,{strictMode:a,treatAllFieldsOptional:F});else throw P}else Yo(g,M.values,T.content,{strictMode:a,treatAllFieldsOptional:F})}if(await Fn(p,M.values),R||(t.removeByTag("correction",n),t.removeByTag("error",n)),d.length&&await Pr(d,M.values,t,n),T.finishReason==="length")throw new Error(`Max tokens reached before completion
216
- Content: ${T.content}`)}let D=l.map(T=>T.values);for(let T of D)for(let M of g.getOutputFields())M.isInternal&&delete T[M.name];let U=g.getOutputFields(),L=D.map((T,M)=>{let E={};for(let N of U)N.isInternal||(E[N.name]=T[N.name]);return T[m]!==void 0&&(E[m]=T[m]),{index:M,delta:E}});for(let T of L)yield T}function ld(s,e){return e?!!(e.nestingLevel>0||e.inArray||e.inObject):!1}function qu(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 ud=["none","minimal","low","medium","high","highest"];function Xi(s,e,t){let n={};if(e.model!==!1){let a=s.getModelList();if(a&&a.length>0){let l=a.filter(u=>"model"in u);if(l.length>0){let u=l.map(p=>p.key),c=l.map(p=>`${p.key} (${p.description})`);n.model={type:"string",enum:u,description:`${t&&u.includes(t)?`Currently using model: ${t}. `:""}Switch model for the next step. Prefer faster/cheaper models for simple tasks; use more capable models for complex reasoning, math, or multi-step analysis. Available: ${c.join(", ")}`}}}}e.thinkingBudget!==!1&&(n.thinkingBudget={type:"string",enum:[...ud],description:"Reasoning depth for the next step. none/minimal: simple lookups or reformatting. low/medium: moderate analysis, summarization. high/highest: math, logic, code analysis, or multi-step reasoning. Higher budgets use more tokens."}),e.temperature&&(n.temperature={type:"number",description:"Sampling temperature for the next step. Lower values (0\u20130.3) for deterministic tasks like math or code; higher values (0.7\u20131.0) for creative or exploratory tasks."});let r;if(e.functions&&e.functions.length>0){r=Vt(e.functions);let a=r.map(u=>u.name),l=r.map(u=>`${u.name} (${u.description})`);n.addFunctions={type:"array",items:{type:"string",enum:a},description:`Activate tools you need for the current sub-task. Only add what you will use immediately \u2014 fewer active tools means less noise. Available: ${l.join(", ")}`},n.removeFunctions={type:"array",items:{type:"string",enum:a},description:"Remove tools you are done with to reduce context size and maintain focus on remaining work."}}let o=r;return{name:"adjustGeneration",description:"Adjust model, reasoning depth, or active tools for the next step. Call when task complexity changes \u2014 upgrade for hard reasoning or analysis, downgrade for simple follow-ups. Only call when there is a clear reason to change.",parameters:Object.keys(n).length>0?{type:"object",properties:n}:void 0,func:(a,l)=>{let u=l?.step;if(!u)return"Generation parameters adjusted for next response.";if(a?.model&&u.setModel(a.model),a?.thinkingBudget&&u.setThinkingBudget(a.thinkingBudget),a?.temperature!==void 0&&u.setTemperature(a.temperature),a?.addFunctions?.length&&o){let c=o.filter(p=>a.addFunctions.includes(p.name));c.length>0&&u.addFunctions(c)}return a?.removeFunctions?.length&&u.removeFunctions(...a.removeFunctions),"Generation parameters adjusted for next response."}}}var Dn=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 he=class extends Error{constructor(t,n,r,o){super(t);this.position=n;this.context=r;this.suggestion=o;this.name="SignatureValidationError"}},Zi=class{input;position;currentFieldName=null;currentSection="description";constructor(e){if(this.input=e.trim(),this.position=0,!this.input)throw new he("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 he("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 he('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 he(`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 he)throw e;let t=e instanceof Error?e.message:"Unknown error";throw new he(t,this.position,this.getErrorContext())}}validateParsedSignature(e){let t=new Set;for(let r of e.inputs){if(t.has(r.name))throw new he(`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 he(`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 he(`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 he("Signature must have at least one input field",0,"",'Add an input field before "->". Example: "userInput:string -> ..."');if(e.outputs.length===0)throw new he("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 he(`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 he?r:new he(`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 he(`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 he?r:new he(`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 he(`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 he(`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 he?o:new he(`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 he(`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 he(`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 he(`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 he(`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 he(`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 he(`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 he?i:new he(`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(fe.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 he(`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 he(`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 he(`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 he(`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 he(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 he("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 he(`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 he(`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 he(`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 he(`Expected "->" but found "${e}..."`,this.position,this.getErrorContext(),t)}}};function zu(s){return new Zi(s).parse()}var $r=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,ea(i)])):void 0},description:t.description,isOptional:t.isOptional||void 0,isInternal:t.isInternal||void 0,isCached:t.isCached||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,ea(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}addInputFields(e){for(let t of e)this.inputFields.push(t);return this}addOutputFields(e){for(let t of e)this.outputFields.push(t);return 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}},Ke=class s{type;isArray;options;description;isOptional;isInternal;isCached;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.isCached=e.isCached,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})}cache(){return new s({...this,isCached:!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}},ye=Object.assign(()=>new $r,{string:s=>new Ke({type:"string",isArray:!1,description:s,isOptional:!1,isInternal:!1,isCached:!1}),number:s=>new Ke({type:"number",isArray:!1,description:s,isOptional:!1,isInternal:!1,isCached:!1}),boolean:s=>new Ke({type:"boolean",isArray:!1,description:s,isOptional:!1,isInternal:!1,isCached:!1}),json:s=>new Ke({type:"json",isArray:!1,description:s,isOptional:!1,isInternal:!1,isCached:!1}),datetime:s=>new Ke({type:"datetime",isArray:!1,description:s,isOptional:!1,isInternal:!1,isCached:!1}),date:s=>new Ke({type:"date",isArray:!1,description:s,isOptional:!1,isInternal:!1,isCached:!1}),class:(s,e)=>new Ke({type:"class",isArray:!1,options:s,description:e,isOptional:!1,isInternal:!1,isCached:!1}),image:s=>new Ke({type:"image",isArray:!1,description:s,isOptional:!1,isInternal:!1,isCached:!1}),audio:s=>new Ke({type:"audio",isArray:!1,description:s,isOptional:!1,isInternal:!1,isCached:!1}),file:s=>new Ke({type:"file",isArray:!1,description:s,isOptional:!1,isInternal:!1,isCached:!1}),url:s=>new Ke({type:"url",isArray:!1,description:s,isOptional:!1,isInternal:!1,isCached:!1}),email:s=>new Ke({type:"string",isArray:!1,description:s,isOptional:!1,isInternal:!1,isCached:!1,format:"email"}),code:(s,e)=>new Ke({type:"code",isArray:!1,description:e||s,isOptional:!1,isInternal:!1,isCached:!1}),object:(s,e)=>new Ke({type:"object",isArray:!1,fields:s,description:e,isOptional:!1,isInternal:!1,isCached:!1})});function ea(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,ea(t)])):void 0}}function es(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 ie=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=zu(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 ie(`Invalid Signature: ${n.message}`,void 0,r)}throw new ie(`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 ie("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 ie("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 ie?t:new ie(`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 ie("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 ie("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 ie("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 ie("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);Rt(t,"input");for(let n of this.inputFields)if(n.name===t.name)throw new ie(`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 ie(`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 ie?t:new ie(`Failed to add input field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}};addOutputField=e=>{try{let t=this.parseField(e);Rt(t,"output");for(let n of this.outputFields)if(n.name===t.name)throw new ie(`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 ie(`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 ie?t:new ie(`Failed to add output field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}};setInputFields=e=>{if(!Array.isArray(e))throw new ie("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 Rt(r,"input"),r});this.inputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof ie?t:new ie(`Failed to set input fields: ${t instanceof Error?t.message:"Unknown error"}`)}};setOutputFields=e=>{if(!Array.isArray(e))throw new ie("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 Rt(r,"output"),r});this.outputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof ie?t:new ie(`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,...es(t)}),n};prependInputField=(e,t)=>{let n=new s(this),r={name:e,...es(t)},o=n.parseField(r);Rt(o,"input");for(let i of n.inputFields)if(i.name===o.name)throw new ie(`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 ie(`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,...es(t)}),n};prependOutputField=(e,t)=>{let n=new s(this),r={name:e,...es(t)},o=n.parseField(r);Rt(o,"output");for(let i of n.outputFields)if(i.name===o.name)throw new ie(`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 ie(`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=>{Rt(e,"input")}),this.getOutputFields().forEach(e=>{Rt(e,"output")}),this.sigHash=it("sha256").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=Ku(this.description,this.inputFields,this.outputFields),this._hasComplexFields=this.computeHasComplexFields(),[this.sigHash,this.sigString]}catch(e){throw e instanceof ie?e:new ie(`Signature validation failed: ${e instanceof Error?e.message:"Unknown error"}`)}};updateHash=()=>{try{return this.getInputFields().forEach(e=>{Rt(e,"input")}),this.getOutputFields().forEach(e=>{Rt(e,"output")}),this.validateSignatureConsistency(),this.sigHash=it("sha256").update(this.description??"").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=Ku(this.description,this.inputFields,this.outputFields),this._hasComplexFields=this.computeHasComplexFields(),[this.sigHash,this.sigString]}catch(e){throw e instanceof ie?e:new ie(`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 ie(`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 ie(`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 ie(`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 ie("Signature must have at least one input field",void 0,'Add an input field. Example: "userInput:string -> ..."');if(this.outputFields.length===0)throw new ie("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 Ln(e,this.description??"Schema")};toInputJSONSchema=()=>Ln(this.inputFields,this.description??"Schema")};function Hu(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 Ku(s,e,t){let n=s?`"${s}" `:"",r=e.map(Hu).join(", "),o=t.map(Hu).join(", ");return`${n}${r} -> ${o}`}function cd(s){let e=/^[a-z][a-zA-Z0-9]*$/,t=/^[a-z]+(_[a-z0-9]+)*$/;return e.test(s)||t.test(s)}function Rt(s,e){if(!s.name||s.name.length===0)throw new ie("Field name cannot be blank",s.name,"Every field must have a descriptive name");if(!cd(s.name))throw new ie(`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(fe.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 ie(`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 ie(`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 ie(`Field name '${s.name}' is too long (${s.name.length} characters)`,s.name,"Field names should be 50 characters or less");s.type&&pd(s,e)}function pd(s,e){if(!s.type)return;let{type:t}=s;if((t.name==="image"||t.name==="audio"||t.name==="file")&&e==="output")throw new ie(`${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 ie("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 ie("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 ie("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 ie(`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 ie("Duplicate class options found",s.name,"Each class option must be unique (case-insensitive)")}if(t.name==="code"&&t.isArray)throw new ie("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 ie("Internal marker (!) is not allowed on input fields",s.name,"Internal markers are only allowed on output fields");t.name==="object"&&t.fields&&ta(t.fields,s.name,e)}function ta(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 ie(`${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&&ta(o.fields,i,t,n+1),o.isArray&&o.fields&&ta(o.fields,`${i}[]`,t,n+1)}}var Ut=class s{signature;sigHash;examples;examplesOptions;demos;trace;usage=[];traceLabel;key;children;childNames=new Map;childCount=0;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 Dn,this.key={id:"root"}}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()}getId(){return this.key.id}register(e,t){let n=t??`p${this.childCount}`;this.childCount++,e.setId([this.key.id,n].join(".")),this.childNames.set(e,n),this.children.register(e)}setId(e){this.key={id:e,custom:!0};for(let[t,n]of this.childNames)t.setId([e,n].join("."))}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&&(Mr(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 Er(e)}resetUsage(){this.usage=[];for(let e of Array.from(this.children))e?.resetUsage()}static _propagating=!1;setDemos(e,t){if(!s._propagating&&e.length>0){let u=new Set(this.namedPrograms().map(p=>p.id)),c=[...new Set(e.map(p=>p.programId))].filter(p=>!u.has(p));if(c.length>0){let p=[...u].join(", ");throw new Error(`Unknown program ID(s) in demos: ${c.join(", ")}. Valid IDs: ${p}. Use namedPrograms() to discover available IDs.`)}}let n=e.filter(u=>u.programId===this.key.id).map(u=>u.traces).flat(),r=this.signature,o=[...r.getInputFields(),...r.getOutputFields()],i=new Set(r.getInputFields().map(u=>u.name)),a=new Set(r.getOutputFields().map(u=>u.name));this.demos=n.map((u,c)=>{let p={};for(let g of o){let f=u[g.name];f!==void 0&&(Mr(g,f),p[g.name]=f)}let d=Object.keys(p).some(g=>i.has(g));if(!Object.keys(p).some(g=>a.has(g)))throw new Error(`Demo trace[${c}] for '${this.key.id}' has no output field values. Expected at least one of: ${[...a].join(", ")}`);if(!d)throw new Error(`Demo trace[${c}] for '${this.key.id}' has no input field values. Expected at least one of: ${[...i].join(", ")}. Provide input context so the demo renders as a complete few-shot example.`);return p}),t?.modelConfig&&(this._optimizedModelConfig=t.modelConfig);let l=s._propagating;s._propagating=!0;try{for(let u of Array.from(this.children))u?.setDemos(e,t)}finally{s._propagating=l}}namedPrograms(){let e=[];[...this.signature.getInputFields(),...this.signature.getOutputFields()].length>0&&e.push({id:this.key.id,signature:this.signature.toString()});for(let n of Array.from(this.children))n&&"namedPrograms"in n&&typeof n.namedPrograms=="function"?e.push(...n.namedPrograms()):n&&e.push({id:n.getId()});return e}applyOptimization(e){this.setDemos(e.demos??[],{modelConfig:e.modelConfig})}};var Wu={"dsp/example-disclaimer.md":`## Example Demonstrations
214
+ Tip: Arrays must include an "items" schema (e.g., { items: { type: "string" } } or items: { type: "object", properties: { ... } }).`,{cause:r}):r}return[...e??[],...t]},ts=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,step:m,abortSignal:g})=>{let f=new _r(e),h=new Set,A=[],x=v=>{let O=$=>$.replace(/[^a-zA-Z0-9]/g,"").toLowerCase(),k=O(v),S=e.find($=>$.name===v);return S||(S=e.find($=>O($.name)===k)),S},b=t.map(v=>{if(!v.id)throw new Error(`Function ${v.name} did not return an ID`);let O=s.getOptions().tracer??ce.tracer;return O?O.startActiveSpan(`Tool: ${v.name}`,async k=>{try{k?.setAttributes?.({"tool.name":v.name,"tool.mode":"native","function.id":v.id,"session.id":r??""});let{formatted:S,rawResult:$,parsedArgs:G}=await f.executeWithDetails(v,{sessionId:r,ai:s,functionResultFormatter:u,traceId:k?.spanContext?.().traceId??o,stopFunctionNames:d,step:m,abortSignal:g});if(h.add(v.name.toLowerCase()),m?._recordFunctionCall(v.name,G,$),d?.includes(v.name.toLowerCase())){let L=x(v.name);L&&A.push({func:L,args:G,result:$})}if(a?k.addEvent("gen_ai.tool.message",{name:v.name}):k.addEvent("gen_ai.tool.message",{name:v.name,args:v.args,result:S??""}),i){let L={name:v.name};a||(L.args=v.args,L.result=S??""),i.addEvent("function.call",L)}return{result:S??"",role:"function",functionId:v.id,index:l}}catch(S){if(k?.recordException?.(S),S instanceof Fr){let $=S.getFixingInstructions(),G={name:v.name,message:S.toString()};return a||(G.args=v.args,G.fixing_instructions=$),k?.addEvent?.("function.error",G),p&&oi(S,l,$,c),{functionId:v.id,isError:!0,index:l,result:$,role:"function"}}throw S}finally{k?.end?.()}}):f.executeWithDetails(v,{sessionId:r,ai:s,functionResultFormatter:u,traceId:o,stopFunctionNames:d,step:m,abortSignal:g}).then(({formatted:k,rawResult:S,parsedArgs:$})=>{if(h.add(v.name.toLowerCase()),m?._recordFunctionCall(v.name,$,S),d?.includes(v.name.toLowerCase())){let G=x(v.name);G&&A.push({func:G,args:$,result:S})}if(i){let G={name:v.name};a||(G.args=v.args,G.result=k??""),i.addEvent("function.call",G)}return{result:k??"",role:"function",functionId:v.id,index:l}}).catch(k=>{if(!(k instanceof Fr))throw k;let S=k.getFixingInstructions();if(i){let $={name:v.name,message:k.toString()};a||($.args=v.args,$.fixing_instructions=S),i.addEvent("function.error",$)}return p&&oi(k,l,S,c),{functionId:v.id,isError:!0,index:l,result:S,role:"function"}})}),I=(await Promise.all(b)).map(v=>v.result===void 0||v.result===""?{...v,result:"done"}:v);if(n.addFunctionResults(I,r),p){let v=I.filter(O=>!O.isError);v.length>0&&fl(v,c)}if(A.length>0)throw new zt(A);return h};function ra(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 Xu(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 Ld(s){let e=0,t=!1,n=!1,r=!1,o=!1,i=[];for(let a=0;a<s.length;a++){let l=s[a];if(n){n=!1;continue}if(l==="\\"){n=!0;continue}if(l==='"'){t=!t;continue}t||(l==="{"?(i.push("{"),e++):l==="["?(i.push("["),e++):l==="}"?i.length>0&&i[i.length-1]==="{"&&(i.pop(),e--):l==="]"&&i.length>0&&i[i.length-1]==="["&&(i.pop(),e--))}if(i.length>0){let a=i[i.length-1];r=a==="[",o=a==="{"}return{nestingLevel:e,inString:t,inArray:r,inObject:o}}function Zu(s){if(!s.trim())return{parsed:null,partialMarker:null};try{return{parsed:JSON.parse(s),partialMarker:null}}catch{}let e=Ld(s),t=Dd(s);try{return{parsed:JSON.parse(t),partialMarker:e}}catch{return{parsed:null,partialMarker:e}}}function Dd(s){let e=s.trim();for(e.endsWith(",")&&(e=e.slice(0,-1)),e.match(/,\s*"[^"]*"\s*:\s*$/)?e=e.replace(/,\s*"[^"]*"\s*:\s*$/,""):e.match(/\{\s*"[^"]*"\s*:\s*$/)&&(e=e.replace(/"[^"]*"\s*:\s*$/,""));e.match(/[0-9][eE.+-]$/)||e.match(/[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}async function*ec({res:s,usage:e,states:t,debug:n,stepContext:r,...o}){let i=(o.ai.getFeatures().functionCot??!1)&&o.functions!==void 0&&o.functions.length>0,a,l=[],u=s.getReader();try{for(;;){let{done:c,value:p}=await u.read();if(c)break;let d=p;d.modelUsage&&(a=d.modelUsage);for(let m of d.results){if(Array.isArray(m.citations))for(let f of m.citations)f?.url&&l.push({url:f.url,title:f.title,description:f.description,license:f.license,publicationDate:f.publicationDate,snippet:f.snippet});if((!m.content||m.content==="")&&(!m.thought||m.thought==="")&&(!m.thoughtBlocks||m.thoughtBlocks.length===0)&&(!m.functionCalls||m.functionCalls.length===0))continue;let g=t.find(f=>f.index===m.index);if(!g)throw new Error(`No state found for result (index: ${m.index})`);yield*Gd({...o,result:m,skipEarlyFail:i,state:g,debug:n})}}}finally{u.releaseLock()}for(let c of t)yield*Ud({...o,state:c,debug:n,stepContext:r});if(a){if(l.length){let c=Array.from(new Map(l.filter(p=>p.url).map(p=>[p.url,p])).values());a.citations=c}if(e.push(a),n&&o.logger){let c=structuredClone(a);delete c.citations,o.logger({name:"ChatResponseUsage",value:c}),a.citations&&a.citations.length>0&&o.logger({name:"ChatResponseCitations",value:a.citations})}}}async function*Gd({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)uo(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{parsed:f,partialMarker:h}=Zu(i.content);if(f&&typeof f=="object"){let A={},x={};for(let b of Object.keys(f))if(d.some(C=>C.name===b)){let C=f[b],I=i.values[b];if(Array.isArray(C)&&C.length>0&&Bd(C,h)&&(C=C.slice(0,-1)),x[b]=C,typeof C=="string"&&typeof I=="string"&&C.startsWith(I)){let v=C.slice(I.length);v&&(A[b]=v)}else Array.isArray(C)&&Array.isArray(I)?C.length>I.length&&(A[b]=C.slice(I.length)):JSON.stringify(C)!==JSON.stringify(I)&&(Array.isArray(C)||(A[b]=C))}try{Pn(a,x,{allowMissingRequired:!0})}catch{}Object.assign(i.values,x),Object.keys(A).length>0&&(yield{index:s.index,delta:A});return}}if(Zi(a,i.values,i.xstate,i.content,{strictMode:n,skipEarlyFail:r,treatAllFieldsOptional:o}))return;c.length!==0&&await _i(c,i.xstate,i.content),l.length!==0&&await na(l,i.content,i.xstate,e,i.values,t),yield*ta(a,i.content,i.values,i.xstate,s.index),await On(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*Ud({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:A,debug:x,stopFunctionNames:b,stepContext:C,abortSignal:I}){let v=h?void 0:ra(t,s.functionCalls,s.values,n);if(v){if(!r)throw new Error("Functions are not defined");let O=await ts({ai:t,functionList:r,functionCalls:v,mem:o,sessionId:i,traceId:a,span:l,index:s.index,excludeContentFromTrace:c,functionResultFormatter:f,logger:A,debug:x,stopFunctionNames:b,step:C,abortSignal:I});s.functionsExecuted=new Set([...s.functionsExecuted,...O]),s.functionCalls=[]}else{let O=e.getOutputFields(),k=e.hasComplexFields(),S=!1;if(k)try{let $=JSON.parse(s.content),G={};for(let L of Object.keys($))if(O.some(w=>w.name===L)){let w=$[L],R=s.values[L];if(typeof w=="string"&&typeof R=="string"&&w.startsWith(R)){let E=w.slice(R.length);E&&(G[L]=E)}else Array.isArray(w)&&Array.isArray(R)?w.length>R.length&&(G[L]=w.slice(R.length)):JSON.stringify(w)!==JSON.stringify(R)&&(Array.isArray(w)||(G[L]=w))}try{Pn(e,G,{allowMissingRequired:!0})}catch(L){let w=(L.message||"").toLowerCase();if(w.includes("at least")||w.includes("at most")||w.includes("must match pattern")||w.includes("invalid url")||w.includes("required")||w.includes("missing")||w.includes("valid email")||w.includes("number must be"))throw L}for(let L of Object.keys($))O.some(w=>w.name===L)&&(s.values[L]=$[L]);yield{index:s.index,delta:G},S=!0}catch($){let G=($.message||"").toLowerCase();if(G.includes("at least")||G.includes("at most")||G.includes("must match pattern")||G.includes("invalid url")||G.includes("required")||G.includes("missing")||G.includes("valid email")||G.includes("number must be"))throw $}if(!S){let $=h!==void 0;ea(e,s.values,s.xstate,s.content,{strictMode:u,treatAllFieldsOptional:$,deferRequiredCheckForStreaming:!0,forceFinalize:!0})}if(h){let $=await h.processResults(s.values);if($&&$.length>0){if(!r)throw new Error("Functions are not defined");let G=await ts({ai:t,functionList:r,functionCalls:$,mem:o,sessionId:i,traceId:a,span:l,index:s.index,excludeContentFromTrace:c,functionResultFormatter:f,logger:A,debug:x,stopFunctionNames:b,step:C,abortSignal:I});s.functionsExecuted=new Set([...s.functionsExecuted,...G]),o.updateResult({name:void 0,content:s.content,functionCalls:$.map(L=>({id:L.id,type:"function",function:{name:L.name,params:L.args}})),index:s.index},i);return}}await _i(p,s.xstate,s.content,!0),await On(d,s.values),m.length&&await Er(m,s.values,o,i),g.length!==0&&await na(g,s.content,s.xstate,o,s.values,i,!0),yield*ta(e,s.content,s.values,s.xstate,s.index)}}async function*tc({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:A,signatureToolCallingManager:x,stopFunctionNames:b,disableMemoryCleanup:C,stepContext:I,abortSignal:v}){let O=e.results??[],k=x!==void 0;t.addResponse(O,n);let S=[];for(let w of O)if(Array.isArray(w?.citations))for(let R of w.citations)R?.url&&S.push({url:R.url,title:R.title,description:R.description,license:R.license,publicationDate:R.publicationDate,snippet:R.snippet});for(let w of O){let R=l[w.index];if(!R)throw new Error(`No state found for result (index: ${w.index})`);if(e.modelUsage){let E=Array.from(new Map(S.filter(M=>M.url).map(M=>[M.url,M])).values()),_={...e.modelUsage,...E.length?{citations:E}:{}};if(u.push(_),A&&h){let M=structuredClone(_);delete M.citations,h({name:"ChatResponseUsage",value:M}),_.citations&&_.citations.length>0&&h({name:"ChatResponseCitations",value:_.citations})}}if(x&&w.content){w.thought&&w.thought.length>0&&(R.values[m]=w.thought),Xo(g,R.values,w.content,{strictMode:a,treatAllFieldsOptional:k});let _=(await x.processResults(R.values))?.map(M=>({id:M.id,type:"function",function:{name:M.name,params:M.args}}));_&&_.length>0&&t.updateResult({name:w.name,content:w.content,functionCalls:_,index:w.index},n)}if(w.functionCalls?.length){let E=ra(s,w.functionCalls,R.values);if(E&&E.length>0){if(!o)throw new Error("Functions are not defined");let _;try{_=await ts({ai:s,functionList:o,functionCalls:E,mem:t,sessionId:n,traceId:r,span:i,excludeContentFromTrace:c,index:w.index,functionResultFormatter:f,logger:h,debug:A,stopFunctionNames:b,step:I,abortSignal:v})}catch(M){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),M}R.functionsExecuted=new Set([...R.functionsExecuted,..._])}}else if(w.content){w.thought&&w.thought.length>0&&(R.values[m]=w.thought);let E=g.getOutputFields();if(g.hasComplexFields())try{let M=JSON.parse(w.content),N={};for(let q of Object.keys(M))E.some(U=>U.name===q)&&(N[q]=M[q]);Pn(g,N),Object.assign(R.values,N)}catch(M){let N=M instanceof SyntaxError;if((M.name?.includes("ValidationError")||M.name?.includes("Error"))&&!N){let U=(M.message||"").toLowerCase();if(U.includes("at least")||U.includes("at most")||U.includes("must match pattern")||U.includes("invalid url")||U.includes("required")||U.includes("missing")||U.includes("valid email")||U.includes("number must be"))throw M}if(N)Xo(g,R.values,w.content,{strictMode:a,treatAllFieldsOptional:k});else throw M}else Xo(g,R.values,w.content,{strictMode:a,treatAllFieldsOptional:k})}if(await On(p,R.values),C||(t.removeByTag("correction",n),t.removeByTag("error",n)),d.length&&await Er(d,R.values,t,n),w.finishReason==="length")throw new Error(`Max tokens reached before completion
216
+ Content: ${w.content}`)}let $=l.map(w=>w.values);for(let w of $)for(let R of g.getOutputFields())R.isInternal&&delete w[R.name];let G=g.getOutputFields(),L=$.map((w,R)=>{let E={};for(let _ of G)_.isInternal||(E[_.name]=w[_.name]);return w[m]!==void 0&&(E[m]=w[m]),{index:R,delta:E}});for(let w of L)yield w}function Bd(s,e){return e?!!(e.nestingLevel>0||e.inArray||e.inObject):!1}function nc(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 jd=["none","minimal","low","medium","high","highest"];function oa(s,e,t){let n={};if(e.model!==!1){let a=s.getModelList();if(a&&a.length>0){let l=a.filter(u=>"model"in u);if(l.length>0){let u=l.map(p=>p.key),c=l.map(p=>`${p.key} (${p.description})`);n.model={type:"string",enum:u,description:`${t&&u.includes(t)?`Currently using model: ${t}. `:""}Switch model for the next step. Prefer faster/cheaper models for simple tasks; use more capable models for complex reasoning, math, or multi-step analysis. Available: ${c.join(", ")}`}}}}e.thinkingBudget!==!1&&(n.thinkingBudget={type:"string",enum:[...jd],description:"Reasoning depth for the next step. none/minimal: simple lookups or reformatting. low/medium: moderate analysis, summarization. high/highest: math, logic, code analysis, or multi-step reasoning. Higher budgets use more tokens."}),e.temperature&&(n.temperature={type:"number",description:"Sampling temperature for the next step. Lower values (0\u20130.3) for deterministic tasks like math or code; higher values (0.7\u20131.0) for creative or exploratory tasks."});let r;if(e.functions&&e.functions.length>0){r=Ht(e.functions);let a=r.map(u=>u.name),l=r.map(u=>`${u.name} (${u.description})`);n.addFunctions={type:"array",items:{type:"string",enum:a},description:`Activate tools you need for the current sub-task. Only add what you will use immediately \u2014 fewer active tools means less noise. Available: ${l.join(", ")}`},n.removeFunctions={type:"array",items:{type:"string",enum:a},description:"Remove tools you are done with to reduce context size and maintain focus on remaining work."}}let o=r;return{name:"adjustGeneration",description:"Adjust model, reasoning depth, or active tools for the next step. Call when task complexity changes \u2014 upgrade for hard reasoning or analysis, downgrade for simple follow-ups. Only call when there is a clear reason to change.",parameters:Object.keys(n).length>0?{type:"object",properties:n}:void 0,func:(a,l)=>{let u=l?.step;if(!u)return"Generation parameters adjusted for next response.";if(a?.model&&u.setModel(a.model),a?.thinkingBudget&&u.setThinkingBudget(a.thinkingBudget),a?.temperature!==void 0&&u.setTemperature(a.temperature),a?.addFunctions?.length&&o){let c=o.filter(p=>a.addFunctions.includes(p.name));c.length>0&&u.addFunctions(c)}return a?.removeFunctions?.length&&u.removeFunctions(...a.removeFunctions),"Generation parameters adjusted for next response."}}}var Fn=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 pe=class extends Error{constructor(t,n,r,o){super(t);this.position=n;this.context=r;this.suggestion=o;this.name="SignatureValidationError"}},sa=class{input;position;currentFieldName=null;currentSection="description";constructor(e){if(this.input=e.trim(),this.position=0,!this.input)throw new pe("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 pe("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 pe('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 pe(`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 pe)throw e;let t=e instanceof Error?e.message:"Unknown error";throw new pe(t,this.position,this.getErrorContext())}}validateParsedSignature(e){let t=new Set;for(let r of e.inputs){if(t.has(r.name))throw new pe(`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 pe(`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 pe(`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 pe("Signature must have at least one input field",0,"",'Add an input field before "->". Example: "userInput:string -> ..."');if(e.outputs.length===0)throw new pe("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 pe(`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 pe?r:new pe(`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 pe(`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 pe?r:new pe(`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 pe(`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 pe(`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 pe?o:new pe(`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 pe(`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 pe(`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 pe(`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 pe(`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 pe(`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 pe(`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 pe?i:new pe(`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(ce.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 pe(`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 pe(`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 pe(`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 pe(`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 pe(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 pe("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 pe(`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 pe(`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 pe(`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 pe(`Expected "->" but found "${e}..."`,this.position,this.getErrorContext(),t)}}};function rc(s){return new sa(s).parse()}var Nr=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,rs(i)])):void 0},description:t.description,isOptional:t.isOptional||void 0,isInternal:t.isInternal||void 0,isCached:t.isCached||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,rs(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}addInputFields(e){for(let t of e)this.inputFields.push(t);return this}addOutputFields(e){for(let t of e)this.outputFields.push(t);return 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 Me(e);return this._useStructuredOutputs&&(t._forceComplexFields=!0,t._hasComplexFields=void 0),t}},$e=class s{type;isArray;options;description;isOptional;isInternal;isCached;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.isCached=e.isCached,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})}cache(){return new s({...this,isCached:!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}},he=Object.assign(()=>new Nr,{string:s=>new $e({type:"string",isArray:!1,description:s,isOptional:!1,isInternal:!1,isCached:!1}),number:s=>new $e({type:"number",isArray:!1,description:s,isOptional:!1,isInternal:!1,isCached:!1}),boolean:s=>new $e({type:"boolean",isArray:!1,description:s,isOptional:!1,isInternal:!1,isCached:!1}),json:s=>new $e({type:"json",isArray:!1,description:s,isOptional:!1,isInternal:!1,isCached:!1}),datetime:s=>new $e({type:"datetime",isArray:!1,description:s,isOptional:!1,isInternal:!1,isCached:!1}),date:s=>new $e({type:"date",isArray:!1,description:s,isOptional:!1,isInternal:!1,isCached:!1}),class:(s,e)=>new $e({type:"class",isArray:!1,options:s,description:e,isOptional:!1,isInternal:!1,isCached:!1}),image:s=>new $e({type:"image",isArray:!1,description:s,isOptional:!1,isInternal:!1,isCached:!1}),audio:s=>new $e({type:"audio",isArray:!1,description:s,isOptional:!1,isInternal:!1,isCached:!1}),file:s=>new $e({type:"file",isArray:!1,description:s,isOptional:!1,isInternal:!1,isCached:!1}),url:s=>new $e({type:"url",isArray:!1,description:s,isOptional:!1,isInternal:!1,isCached:!1}),email:s=>new $e({type:"string",isArray:!1,description:s,isOptional:!1,isInternal:!1,isCached:!1,format:"email"}),code:(s,e)=>new $e({type:"code",isArray:!1,description:e||s,isOptional:!1,isInternal:!1,isCached:!1}),object:(s,e)=>new $e({type:"object",isArray:!1,fields:s,description:e,isOptional:!1,isInternal:!1,isCached:!1})});function rs(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,rs(t)])):void 0}}function ns(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}}function ia(s,e){return{name:s,type:{name:e.type,isArray:e.isArray||void 0,options:e.options?[...e.options]:void 0,minLength:e.minLength,maxLength:e.maxLength,minimum:e.minimum,maximum:e.maximum,pattern:e.pattern,patternDescription:e.patternDescription,format:e.format,description:e.itemDescription,fields:e.fields?Object.fromEntries(Object.entries(e.fields).map(([t,n])=>[t,rs(n)])):void 0},description:e.description,isOptional:e.isOptional||void 0,isInternal:e.isInternal||void 0,isCached:e.isCached||void 0}}function oc(s){return s.length===0?{type:"object",properties:{}}:Lt(s,"Schema")}function qd(s){let e=ia("__value",s);return Lt([e],"Schema").properties?.__value??{type:"json"}}var aa=class{name;desc;ns;argFields=[];returnFields=[];returnFieldType;returnMode;fnHandler;fnExamples=[];constructor(e){this.name=e}description(e){return this.desc=e,this}namespace(e){return this.ns=e,this}arg(e,t){return this.argFields.push(ia(e,t)),this}args(e,t){return this.arg(e,t)}returns(e){if(this.returnMode==="fields")throw new Error("Cannot use fn().returns(...) after fn().returnsField(...); choose exactly one return schema style");return this.returnMode="single",this.returnFieldType=e,this}returnsField(e,t){if(this.returnMode==="single")throw new Error("Cannot use fn().returnsField(...) after fn().returns(...); choose exactly one return schema style");return this.returnMode="fields",this.returnFields.push(ia(e,t)),this}example(e){return this.fnExamples.push(e),this}examples(e){return this.fnExamples.push(...e),this}handler(e){return this.fnHandler=e,this}build(){let e=this.name.trim(),t=this.desc?.trim(),n=this.ns?.trim();if(!e)throw new Error("fn() requires a non-empty function name");if(!t)throw new Error(`Function "${e}" must define a non-empty description`);if(!this.fnHandler)throw new Error(`Function "${e}" must define a handler`);if(this.fnExamples.some(o=>!o.code.trim()))throw new Error(`Function "${e}" examples must define non-empty code`);return{name:e,description:t,...n?{namespace:n}:{},parameters:oc(this.argFields),...this.returnMode==="single"&&this.returnFieldType?{returns:qd(this.returnFieldType)}:this.returnMode==="fields"?{returns:oc(this.returnFields)}:{},...this.fnExamples.length>0?{examples:this.fnExamples.map(o=>({...o}))}:{},func:this.fnHandler}}},ac=s=>new aa(s),ne=class extends Error{constructor(t,n,r){super(t);this.fieldName=n;this.suggestion=r;this.name="AxSignatureValidationError"}},Me=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=rc(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 ne(`Invalid Signature: ${n.message}`,void 0,r)}throw new ne(`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 ne("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 ne("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 ne?t:new ne(`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 ne("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 ne("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 ne("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 ne("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);At(t,"input");for(let n of this.inputFields)if(n.name===t.name)throw new ne(`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 ne(`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 ne?t:new ne(`Failed to add input field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}};addOutputField=e=>{try{let t=this.parseField(e);At(t,"output");for(let n of this.outputFields)if(n.name===t.name)throw new ne(`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 ne(`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 ne?t:new ne(`Failed to add output field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}};setInputFields=e=>{if(!Array.isArray(e))throw new ne("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 At(r,"input"),r});this.inputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof ne?t:new ne(`Failed to set input fields: ${t instanceof Error?t.message:"Unknown error"}`)}};setOutputFields=e=>{if(!Array.isArray(e))throw new ne("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 At(r,"output"),r});this.outputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof ne?t:new ne(`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,...ns(t)}),n};prependInputField=(e,t)=>{let n=new s(this),r={name:e,...ns(t)},o=n.parseField(r);At(o,"input");for(let i of n.inputFields)if(i.name===o.name)throw new ne(`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 ne(`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,...ns(t)}),n};prependOutputField=(e,t)=>{let n=new s(this),r={name:e,...ns(t)},o=n.parseField(r);At(o,"output");for(let i of n.outputFields)if(i.name===o.name)throw new ne(`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 ne(`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=>{At(e,"input")}),this.getOutputFields().forEach(e=>{At(e,"output")}),this.sigHash=Ze("sha256").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=ic(this.description,this.inputFields,this.outputFields),this._hasComplexFields=this.computeHasComplexFields(),[this.sigHash,this.sigString]}catch(e){throw e instanceof ne?e:new ne(`Signature validation failed: ${e instanceof Error?e.message:"Unknown error"}`)}};updateHash=()=>{try{return this.getInputFields().forEach(e=>{At(e,"input")}),this.getOutputFields().forEach(e=>{At(e,"output")}),this.validateSignatureConsistency(),this.sigHash=Ze("sha256").update(this.description??"").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=ic(this.description,this.inputFields,this.outputFields),this._hasComplexFields=this.computeHasComplexFields(),[this.sigHash,this.sigString]}catch(e){throw e instanceof ne?e:new ne(`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 ne(`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 ne(`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 ne(`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 ne("Signature must have at least one input field",void 0,'Add an input field. Example: "userInput:string -> ..."');if(this.outputFields.length===0)throw new ne("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 Lt(e,this.description??"Schema")};toInputJSONSchema=()=>Lt(this.inputFields,this.description??"Schema")};function sc(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 ic(s,e,t){let n=s?`"${s}" `:"",r=e.map(sc).join(", "),o=t.map(sc).join(", ");return`${n}${r} -> ${o}`}function zd(s){let e=/^[a-z][a-zA-Z0-9]*$/,t=/^[a-z]+(_[a-z0-9]+)*$/;return e.test(s)||t.test(s)}function At(s,e){if(!s.name||s.name.length===0)throw new ne("Field name cannot be blank",s.name,"Every field must have a descriptive name");if(!zd(s.name))throw new ne(`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(ce.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 ne(`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 ne(`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 ne(`Field name '${s.name}' is too long (${s.name.length} characters)`,s.name,"Field names should be 50 characters or less");s.type&&Hd(s,e)}function Hd(s,e){if(!s.type)return;let{type:t}=s;if((t.name==="image"||t.name==="audio"||t.name==="file")&&e==="output")throw new ne(`${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 ne("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 ne("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 ne("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 ne(`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 ne("Duplicate class options found",s.name,"Each class option must be unique (case-insensitive)")}if(t.name==="code"&&t.isArray)throw new ne("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 ne("Internal marker (!) is not allowed on input fields",s.name,"Internal markers are only allowed on output fields");t.name==="object"&&t.fields&&la(t.fields,s.name,e)}function la(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 ne(`${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&&la(o.fields,i,t,n+1),o.isArray&&o.fields&&la(o.fields,`${i}[]`,t,n+1)}}var Dt=class s{signature;sigHash;examples;examplesOptions;demos;trace;usage=[];traceLabel;key;children;childNames=new Map;childCount=0;constructor(e,t){this.signature=new Me(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 Fn,this.key={id:"root"}}getSignature(){return new Me(this.signature)}setSignature(e){this.signature=new Me(e),e&&this.signature.validate(),this.updateSignatureHash()}setDescription(e){this.signature.setDescription(e),this.updateSignatureHash()}updateSignatureHash(){this.sigHash=this.signature.hash()}getId(){return this.key.id}register(e,t){let n=t??`p${this.childCount}`;this.childCount++,e.setId([this.key.id,n].join(".")),this.childNames.set(e,n),this.children.register(e)}setId(e){this.key={id:e,custom:!0};for(let[t,n]of this.childNames)t.setId([e,n].join("."))}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&&(Or(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 Mr(e)}resetUsage(){this.usage=[];for(let e of Array.from(this.children))e?.resetUsage()}static _propagating=!1;setDemos(e,t){if(!s._propagating&&e.length>0){let u=new Set(this.namedPrograms().map(p=>p.id)),c=[...new Set(e.map(p=>p.programId))].filter(p=>!u.has(p));if(c.length>0){let p=[...u].join(", ");throw new Error(`Unknown program ID(s) in demos: ${c.join(", ")}. Valid IDs: ${p}. Use namedPrograms() to discover available IDs.`)}}let n=e.filter(u=>u.programId===this.key.id).map(u=>u.traces).flat(),r=this.signature,o=[...r.getInputFields(),...r.getOutputFields()],i=new Set(r.getInputFields().map(u=>u.name)),a=new Set(r.getOutputFields().map(u=>u.name));this.demos=n.map((u,c)=>{let p={};for(let g of o){let f=u[g.name];f!==void 0&&(Or(g,f),p[g.name]=f)}let d=Object.keys(p).some(g=>i.has(g));if(!Object.keys(p).some(g=>a.has(g)))throw new Error(`Demo trace[${c}] for '${this.key.id}' has no output field values. Expected at least one of: ${[...a].join(", ")}`);if(!d)throw new Error(`Demo trace[${c}] for '${this.key.id}' has no input field values. Expected at least one of: ${[...i].join(", ")}. Provide input context so the demo renders as a complete few-shot example.`);return p}),t?.modelConfig&&(this._optimizedModelConfig=t.modelConfig);let l=s._propagating;s._propagating=!0;try{for(let u of Array.from(this.children))u?.setDemos(e,t)}finally{s._propagating=l}}namedPrograms(){let e=[];[...this.signature.getInputFields(),...this.signature.getOutputFields()].length>0&&e.push({id:this.key.id,signature:this.signature.toString()});for(let n of Array.from(this.children))n&&"namedPrograms"in n&&typeof n.namedPrograms=="function"?e.push(...n.namedPrograms()):n&&e.push({id:n.getId()});return e}applyOptimization(e){this.setDemos(e.demos??[],{modelConfig:e.modelConfig})}};var lc={"dsp/example-disclaimer.md":`## Example Demonstrations
218
218
  The conversation history preceding the final user query consists of **few-shot examples** (demonstrations).
219
219
  - These alternating User/Assistant messages are provided **solely** to illustrate the correct reasoning steps, function usage, and output format.
220
220
  - **Do not** treat the specific data, entities, or facts in these examples as valid context for the current task.
@@ -281,6 +281,11 @@ The responder is looking to produce the following output fields: {{ responderOut
281
281
  {{ if discoveryMode }}
282
282
  - \`await listModuleFunctions(modules:string | string[]) : string\` \u2014 Returns markdown listing available callables for one or more modules.
283
283
  - \`await getFunctionDefinitions(functions:string | string[]) : string\` \u2014 Returns markdown with API description and call signature for one or more callables.
284
+ - In \`### Available Modules\`, grouped modules are shown as \`<namespace> - <selection criteria>\` when selection criteria is defined.
285
+ - When you need multiple modules, prefer one batched call such as \`await listModuleFunctions(['timeRange', 'schedulingOrganizer'])\`.
286
+ - When you need multiple callable definitions, prefer one batched call to \`getFunctionDefinitions([...])\`.
287
+ - Treat discovery results as markdown meant for direct \`console.log(...)\` inspection.
288
+ - Do not split discovery into \`Promise.all(...)\` calls or reformat discovery results into JSON or custom objects.
284
289
  {{ /if }}
285
290
 
286
291
  {{ if discoveryMode }}
@@ -299,11 +304,16 @@ The responder is looking to produce the following output fields: {{ responderOut
299
304
  {{ /if }}
300
305
  {{ /if }}
301
306
  ### Important guidance and guardrails
307
+ - Treat any context field excerpt already shown in the prompt as first-pass evidence. If that visible excerpt is enough, do not re-log the full runtime field.
308
+ - When a context field is marked as \`inline-truncated(...)\`, prefer targeted inspection such as \`slice(...)\`, regex extraction, or focused parsing over \`console.log(inputs.<field>)\`.
309
+ - Do not dump full chat histories, documents, or other large context fields unless the task truly requires the entire raw value.
302
310
  - Start with targeted code-based exploration on a small portion of context. Use \`contextMetadata\` to choose scope.
303
311
  - Use code (filter/map/slice/regex/property access) for structural work; use \`llmQuery\` for semantic interpretation and summarization.
304
312
  - Only \`final(...args)\` and \`ask_clarification(...args)\` transmit payload to the responder.
305
313
  - Runtime output may be truncated. If output is incomplete, rerun with narrower scope.
306
314
 
315
+ - The runtime session is the source of truth for current state. If a \`Live Runtime State\` block is present, trust it over older action log details.
316
+ - Prior actions may be summarized or omitted. Only depend on old code when it is still shown in full; otherwise use the summary plus current runtime state.
307
317
  {{ if enforceIncrementalConsoleTurns }}
308
318
  - Treat each turn as one observable step.
309
319
  - If you are not calling \`final(...)\` or \`ask_clarification(...)\`, your code must include exactly one \`console.log(...)\` and stop immediately after it.
@@ -323,12 +333,12 @@ You synthesize a final answer from the provided actorResult payload. The payload
323
333
  1. Base your answer ONLY on evidence from actorResult payload arguments.
324
334
  2. If actorResult lacks sufficient information, provide the best possible answer from available evidence.
325
335
  3. If actorResult.type is \`ask_clarification\`, ask for the missing information clearly in your output fields.
326
- `};var na=/{{\s*([^}]+?)\s*}}/g,Vu=/^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*$/,Ju=new Map;function vt(s,e,t,n){let o=e.slice(0,t).split(`
327
- `),i=o.length,a=(o.at(-1)?.length??0)+1;return`${s}:${i}:${a} ${n}`}function dd(s){let e=[],t=0;na.lastIndex=0;let n=na.exec(s);for(;n;){let[r,o]=n,i=n.index;i>t&&e.push({type:"text",value:s.slice(t,i)}),e.push({type:"tag",value:o.trim(),index:i}),t=i+r.length,n=na.exec(s)}return t<s.length&&e.push({type:"text",value:s.slice(t)}),e}function ra(s,e,t,n=0,r=new Set){let o=[],i=n;for(;i<s.length;){let a=s[i];if(a.type==="text"){o.push({type:"text",value:a.value}),i++;continue}let l=a.value;if(r.has(l))return{nodes:o,nextIndex:i,terminator:l};if(l.startsWith("if ")){let u=l.slice(3).trim();if(!Vu.test(u))throw new Error(vt(t,e,a.index,`Invalid if condition '${u}'`));let c=ra(s,e,t,i+1,new Set(["else","/if"]));if(!c.terminator)throw new Error(vt(t,e,a.index,"Unclosed 'if' block"));let p=[],d=c.nextIndex+1;if(c.terminator==="else"){let m=ra(s,e,t,c.nextIndex+1,new Set(["/if"]));if(m.terminator!=="/if")throw new Error(vt(t,e,a.index,"Unclosed 'if' block"));p=m.nodes,d=m.nextIndex+1}o.push({type:"if",condition:u,thenNodes:c.nodes,elseNodes:p,index:a.index}),i=d;continue}if(l==="else")throw new Error(vt(t,e,a.index,"Unexpected 'else'"));if(l==="/if")throw new Error(vt(t,e,a.index,"Unexpected '/if'"));if(l.startsWith("include "))throw new Error(vt(t,e,a.index,"Unexpected 'include' directive at runtime (includes must be compiled)"));if(!Vu.test(l))throw new Error(vt(t,e,a.index,`Invalid tag '${l}'`));o.push({type:"var",name:l,index:a.index}),i++}return{nodes:o,nextIndex:i}}function Yu(s,e,t,n,r){let o=e.split("."),i=s;for(let a of o){if(i===null||typeof i!="object"||!(a in i))throw new Error(vt(n,t,r,`Missing template variable '${e}'`));i=i[a]}return i}function oa(s,e,t,n){let r="";for(let o of s){if(o.type==="text"){r+=o.value;continue}if(o.type==="var"){let a=Yu(e,o.name,t,n,o.index);if(typeof a!="string"&&typeof a!="number"&&typeof a!="boolean")throw new Error(vt(n,t,o.index,`Variable '${o.name}' must be string, number, or boolean`));r+=String(a);continue}let i=Yu(e,o.condition,t,n,o.index);if(typeof i!="boolean")throw new Error(vt(n,t,o.index,`Condition '${o.condition}' must be boolean`));i?r+=oa(o.thenNodes,e,t,n):r+=oa(o.elseNodes,e,t,n)}return r}function md(s,e){let t=dd(s),n=ra(t,s,e);if(n.terminator)throw new Error(`Unexpected template terminator '${n.terminator}' in ${e}`);return n.nodes}function gt(s,e={}){let t=Wu[s],n=`template:${s}`;if(!t)throw new Error(`Unknown template id: ${String(s)}`);let r=Ju.get(s);return r||(r=md(t,n),Ju.set(s,r)),oa(r,e,t,n)}var Qu=gt("dsp/function-call-instructions.md"),gd=gt("dsp/strict-output-formatting-rules.md"),fd=gt("dsp/example-disclaimer.md"),Gn=gt("dsp/example-separator.md"),Yt=class{sig;fieldTemplates;task;customInstruction;setInstruction(e){this.customInstruction=e,this.task={type:"text",text:e}}getInstruction(){return this.customInstruction}thoughtFieldName;functions;contextCache;examplesInSystem;ignoreBreakpoints;structuredOutputFunctionName;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,this.ignoreBreakpoints=t?.ignoreBreakpoints??!1,this.structuredOutputFunctionName=t?.structuredOutputFunctionName,fe.useStructuredPrompt?this.task=this.buildStructuredPrompt():this.task=this.buildLegacyPrompt()}getFieldNameToTitleMap=()=>{let e=new Map;for(let t of this.sig.getInputFields())e.set(t.name,t.title);for(let t of this.sig.getOutputFields())e.set(t.name,t.title);return e};sortFieldsCachedFirst=e=>[...e].sort((t,n)=>t.isCached&&!n.isCached?-1:!t.isCached&&n.isCached?1:0);buildLegacyPrompt(){let e=[],t=this.sig.hasComplexFields(),n=ts(this.sig.getInputFields()),r=ts(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(c=>"toFunction"in c?c.toFunction():c)?.flat()?.map(c=>`- \`${c.name}\`: ${Un(c.description)}`).join(`
336
+ `};var ua=/{{\s*([^}]+?)\s*}}/g,uc=/^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*$/,cc=new Map;function yt(s,e,t,n){let o=e.slice(0,t).split(`
337
+ `),i=o.length,a=(o.at(-1)?.length??0)+1;return`${s}:${i}:${a} ${n}`}function Kd(s){let e=[],t=0;ua.lastIndex=0;let n=ua.exec(s);for(;n;){let[r,o]=n,i=n.index;i>t&&e.push({type:"text",value:s.slice(t,i)}),e.push({type:"tag",value:o.trim(),index:i}),t=i+r.length,n=ua.exec(s)}return t<s.length&&e.push({type:"text",value:s.slice(t)}),e}function ca(s,e,t,n=0,r=new Set){let o=[],i=n;for(;i<s.length;){let a=s[i];if(a.type==="text"){o.push({type:"text",value:a.value}),i++;continue}let l=a.value;if(r.has(l))return{nodes:o,nextIndex:i,terminator:l};if(l.startsWith("if ")){let u=l.slice(3).trim();if(!uc.test(u))throw new Error(yt(t,e,a.index,`Invalid if condition '${u}'`));let c=ca(s,e,t,i+1,new Set(["else","/if"]));if(!c.terminator)throw new Error(yt(t,e,a.index,"Unclosed 'if' block"));let p=[],d=c.nextIndex+1;if(c.terminator==="else"){let m=ca(s,e,t,c.nextIndex+1,new Set(["/if"]));if(m.terminator!=="/if")throw new Error(yt(t,e,a.index,"Unclosed 'if' block"));p=m.nodes,d=m.nextIndex+1}o.push({type:"if",condition:u,thenNodes:c.nodes,elseNodes:p,index:a.index}),i=d;continue}if(l==="else")throw new Error(yt(t,e,a.index,"Unexpected 'else'"));if(l==="/if")throw new Error(yt(t,e,a.index,"Unexpected '/if'"));if(l.startsWith("include "))throw new Error(yt(t,e,a.index,"Unexpected 'include' directive at runtime (includes must be compiled)"));if(!uc.test(l))throw new Error(yt(t,e,a.index,`Invalid tag '${l}'`));o.push({type:"var",name:l,index:a.index}),i++}return{nodes:o,nextIndex:i}}function pc(s,e,t,n,r){let o=e.split("."),i=s;for(let a of o){if(i===null||typeof i!="object"||!(a in i))throw new Error(yt(n,t,r,`Missing template variable '${e}'`));i=i[a]}return i}function pa(s,e,t,n){let r="";for(let o of s){if(o.type==="text"){r+=o.value;continue}if(o.type==="var"){let a=pc(e,o.name,t,n,o.index);if(typeof a!="string"&&typeof a!="number"&&typeof a!="boolean")throw new Error(yt(n,t,o.index,`Variable '${o.name}' must be string, number, or boolean`));r+=String(a);continue}let i=pc(e,o.condition,t,n,o.index);if(typeof i!="boolean")throw new Error(yt(n,t,o.index,`Condition '${o.condition}' must be boolean`));i?r+=pa(o.thenNodes,e,t,n):r+=pa(o.elseNodes,e,t,n)}return r}function Wd(s,e){let t=Kd(s),n=ca(t,s,e);if(n.terminator)throw new Error(`Unexpected template terminator '${n.terminator}' in ${e}`);return n.nodes}function at(s,e={}){let t=lc[s],n=`template:${s}`;if(!t)throw new Error(`Unknown template id: ${String(s)}`);let r=cc.get(s);return r||(r=Wd(t,n),cc.set(s,r)),pa(r,e,t,n)}var dc=at("dsp/function-call-instructions.md"),Vd=at("dsp/strict-output-formatting-rules.md"),Jd=at("dsp/example-disclaimer.md"),_n=at("dsp/example-separator.md"),Wt=class{sig;fieldTemplates;task;customInstruction;setInstruction(e){this.customInstruction=e,this.task={type:"text",text:e}}getInstruction(){return this.customInstruction}thoughtFieldName;functions;contextCache;examplesInSystem;ignoreBreakpoints;structuredOutputFunctionName;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,this.ignoreBreakpoints=t?.ignoreBreakpoints??!1,this.structuredOutputFunctionName=t?.structuredOutputFunctionName,ce.useStructuredPrompt?this.task=this.buildStructuredPrompt():this.task=this.buildLegacyPrompt()}getFieldNameToTitleMap=()=>{let e=new Map;for(let t of this.sig.getInputFields())e.set(t.name,t.title);for(let t of this.sig.getOutputFields())e.set(t.name,t.title);return e};sortFieldsCachedFirst=e=>[...e].sort((t,n)=>t.isCached&&!n.isCached?-1:!t.isCached&&n.isCached?1:0);buildLegacyPrompt(){let e=[],t=this.sig.hasComplexFields(),n=os(this.sig.getInputFields()),r=os(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(c=>"toFunction"in c?c.toFunction():c)?.flat()?.map(c=>`- \`${c.name}\`: ${Nn(c.description)}`).join(`
328
338
  `);i&&i.length>0&&e.push(`## Available Functions
329
- ${i}`);let a=this.getFieldNameToTitleMap(),l=Xu(this.sig.getInputFields(),a);if(e.push(`## Input Fields
330
- ${l}`),!t){let c=Zu(this.sig.getOutputFields(),a);e.push(`## Output Fields
331
- ${c}`)}i&&i.length>0&&e.push(Qu.trim()),t&&this.structuredOutputFunctionName?e.push(gt("dsp/legacy-formatting-rules-structured-function.md",{structuredOutputFunctionName:this.structuredOutputFunctionName}).trim()):t||e.push(gd.trim());let u=this.sig.getDescription();if(u){let c=Un(u);c=ns(c,a),e.push(c)}return{type:"text",text:e.join(`
339
+ ${i}`);let a=this.getFieldNameToTitleMap(),l=mc(this.sig.getInputFields(),a);if(e.push(`## Input Fields
340
+ ${l}`),!t){let c=gc(this.sig.getOutputFields(),a);e.push(`## Output Fields
341
+ ${c}`)}i&&i.length>0&&e.push(dc.trim()),t&&this.structuredOutputFunctionName?e.push(at("dsp/legacy-formatting-rules-structured-function.md",{structuredOutputFunctionName:this.structuredOutputFunctionName}).trim()):t||e.push(Vd.trim());let u=this.sig.getDescription();if(u){let c=Nn(u);c=ss(c,a),e.push(c)}return{type:"text",text:e.join(`
332
342
 
333
343
  `)}}buildStructuredPrompt(){let e=[],t=this.sig.hasComplexFields();e.push("<identity>"),e.push(this.buildIdentitySection()),e.push("</identity>");let n=this.buildTaskDefinitionSection();n&&(e.push(`
334
344
  <task_definition>`),e.push(n),e.push("</task_definition>"));let r=this.functions?.flatMap(o=>"toFunction"in o?o.toFunction():o);return r&&r.length>0&&(e.push(`
@@ -336,32 +346,32 @@ ${c}`)}i&&i.length>0&&e.push(Qu.trim()),t&&this.structuredOutputFunctionName?e.p
336
346
  <input_fields>`),e.push(this.buildInputFieldsSection()),e.push("</input_fields>"),t||(e.push(`
337
347
  <output_fields>`),e.push(this.buildOutputFieldsSection()),e.push("</output_fields>")),e.push(`
338
348
  <formatting_rules>`),e.push(this.buildFormattingRulesSection()),e.push("</formatting_rules>"),{type:"text",text:e.join(`
339
- `)}}buildIdentitySection(){let e=ts(this.sig.getInputFields()),t=ts(this.sig.getOutputFields());return`You will be provided with the following fields: ${e}. Your task is to generate new fields: ${t}.`}buildTaskDefinitionSection(){let e=this.sig.getDescription();if(!e)return"";let t=this.getFieldNameToTitleMap(),n=Un(e);return n=ns(n,t),n}buildFunctionsSection(e){let t=[];t.push(`**Available Functions**: You can call the following functions to complete the task:
340
- `);let n=e.map(r=>`- \`${r.name}\`: ${Un(r.description??"")}`).join(`
349
+ `)}}buildIdentitySection(){let e=os(this.sig.getInputFields()),t=os(this.sig.getOutputFields());return`You will be provided with the following fields: ${e}. Your task is to generate new fields: ${t}.`}buildTaskDefinitionSection(){let e=this.sig.getDescription();if(!e)return"";let t=this.getFieldNameToTitleMap(),n=Nn(e);return n=ss(n,t),n}buildFunctionsSection(e){let t=[];t.push(`**Available Functions**: You can call the following functions to complete the task:
350
+ `);let n=e.map(r=>`- \`${r.name}\`: ${Nn(r.description??"")}`).join(`
341
351
  `);return t.push(n),t.push(`
342
- ${Qu.trim()}`),t.join(`
352
+ ${dc.trim()}`),t.join(`
343
353
  `)}buildInputFieldsSection(){let e=this.getFieldNameToTitleMap();return`**Input Fields**: The following fields will be provided to you:
344
354
 
345
- ${Xu(this.sig.getInputFields(),e)}`}buildOutputFieldsSection(){let e=this.getFieldNameToTitleMap();return`**Output Fields**: You must generate the following fields:
355
+ ${mc(this.sig.getInputFields(),e)}`}buildOutputFieldsSection(){let e=this.getFieldNameToTitleMap();return`**Output Fields**: You must generate the following fields:
346
356
 
347
- ${Zu(this.sig.getOutputFields(),e)}`}buildFormattingRulesSection(){let e=this.sig.hasComplexFields();return e&&this.structuredOutputFunctionName?gt("dsp/formatting-rules-structured-function.md",{structuredOutputFunctionName:this.structuredOutputFunctionName}).trim():e?gt("dsp/formatting-rules-structured-json.md").trim():gt("dsp/formatting-rules-plain-text.md").trim()}renderSingleValueUserContent=(e,t,n,r)=>{let o=this.renderInputFields(e),i;if(r)i=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})}i=[...l,...o]}let a=i.filter(l=>l!==void 0);return a.every(l=>l.type==="text")?a.map(l=>l.text).join(`
348
- `):a.reduce(Jt(`
357
+ ${gc(this.sig.getOutputFields(),e)}`}buildFormattingRulesSection(){let e=this.sig.hasComplexFields();return e&&this.structuredOutputFunctionName?at("dsp/formatting-rules-structured-function.md",{structuredOutputFunctionName:this.structuredOutputFunctionName}).trim():e?at("dsp/formatting-rules-structured-json.md").trim():at("dsp/formatting-rules-plain-text.md").trim()}renderSingleValueUserContent=(e,t,n,r)=>{let o=this.renderInputFields(e),i;if(r)i=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})}i=[...l,...o]}let a=i.filter(l=>l!==void 0);return a.every(l=>l.type==="text")?a.map(l=>l.text).join(`
358
+ `):a.reduce(Kt(`
349
359
  `),[])};render=(e,{examples:t,demos:n})=>{if(!this.examplesInSystem)return this.renderWithMessagePairs(e,{examples:t,demos:n});let r=t?[{type:"text",text:`
350
360
 
351
361
  ## Examples
352
- `},...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(Jt(""),[]),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 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}]};renderWithMessagePairs=(e,{examples:t,demos:n})=>{let r=t&&t.length>0||n&&n.length>0,i={role:"system",content:r?`${this.task.text}
353
- ${fd}`:this.task.text,cache:!!this.contextCache},a=t?this.renderExamplesAsMessages(t):[],l=n?this.renderDemosAsMessages(n):[],u=[];for(let A of[...a,...l])u.push(A.userMessage),u.push(A.assistantMessage),A.functionResultMessage&&u.push(A.functionResultMessage);let c=this.contextCache?.cacheBreakpoint??"after-examples",p=this.ignoreBreakpoints||c==="after-examples";if(this.contextCache&&u.length>0&&p){let A=u.length-1,w=u[A];w?.role==="assistant"&&(u[A]={...w,cache:!0})}if(Array.isArray(e)){let A=[],w=e,v=!0;for(let F of w){let O=this.renderInputFields(F.values),D=O.every(U=>U.type==="text")?O.map(U=>U.text).join(`
354
- `):O.reduce(Jt(`
355
- `),[]);if(F.role==="user"){v&&r&&(typeof D=="string"?D=Gn+D:D=[{type:"text",text:Gn},...D],v=!1),A.push({role:"user",content:D});continue}if(F.role!=="assistant")throw new Error("Invalid message role");if(typeof D!="string")throw new Error("Assistant message cannot contain non-text content like images, files, etc");A.push({role:"assistant",content:D})}return[i,...u,...A]}let d=this.sig.getInputFields(),m=d.filter(A=>A.isCached),g=d.filter(A=>!A.isCached),f=m.length>0;if(this.contextCache&&f&&(this.ignoreBreakpoints||c!=="system"&&c!=="after-functions")&&g.length>0){let A=m.map(O=>this.renderInField(O,e,void 0)).filter(O=>O!==void 0).flat();A.filter(O=>O.type==="text").forEach(O=>{O.text=`${O.text}
356
- `});let w=A.every(O=>O.type==="text")?A.map(O=>O.text).join(`
357
- `):A.reduce(Jt(`
358
- `),[]);r&&(typeof w=="string"?w=Gn+w:w=[{type:"text",text:Gn},...w]);let v=g.map(O=>this.renderInField(O,e,void 0)).filter(O=>O!==void 0).flat();v.filter(O=>O.type==="text").forEach(O=>{O.text=`${O.text}
359
- `});let F=v.every(O=>O.type==="text")?v.map(O=>O.text).join(`
360
- `):v.reduce(Jt(`
361
- `),[]);return[i,...u,{role:"user",content:w,cache:!0},{role:"user",content:F}]}let x=this.sortFieldsCachedFirst(d).map(A=>this.renderInField(A,e,void 0)).filter(A=>A!==void 0).flat();x.filter(A=>A.type==="text").forEach(A=>{A.text=`${A.text}
362
- `});let b=x.every(A=>A.type==="text")?x.map(A=>A.text).join(`
363
- `):x.reduce(Jt(`
364
- `),[]);r&&(typeof b=="string"?b=Gn+b:b=[{type:"text",text:Gn},...b]);let R=f&&g.length===0&&this.contextCache;return[i,...u,{role:"user",content:b,...R?{cache:!0}:{}}]};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}
362
+ `},...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(Kt(""),[]),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 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}]};renderWithMessagePairs=(e,{examples:t,demos:n})=>{let r=t&&t.length>0||n&&n.length>0,i={role:"system",content:r?`${this.task.text}
363
+ ${Jd}`:this.task.text,cache:!!this.contextCache},a=t?this.renderExamplesAsMessages(t):[],l=n?this.renderDemosAsMessages(n):[],u=[];for(let I of[...a,...l])u.push(I.userMessage),u.push(I.assistantMessage),I.functionResultMessage&&u.push(I.functionResultMessage);let c=this.contextCache?.cacheBreakpoint??"after-examples",p=this.ignoreBreakpoints||c==="after-examples";if(this.contextCache&&u.length>0&&p){let I=u.length-1,v=u[I];v?.role==="assistant"&&(u[I]={...v,cache:!0})}if(Array.isArray(e)){let I=[],v=e,O=!0;for(let k of v){let S=this.renderInputFields(k.values),$=S.every(G=>G.type==="text")?S.map(G=>G.text).join(`
364
+ `):S.reduce(Kt(`
365
+ `),[]);if(k.role==="user"){O&&r&&(typeof $=="string"?$=_n+$:$=[{type:"text",text:_n},...$],O=!1),I.push({role:"user",content:$});continue}if(k.role!=="assistant")throw new Error("Invalid message role");if(typeof $!="string")throw new Error("Assistant message cannot contain non-text content like images, files, etc");I.push({role:"assistant",content:$})}return[i,...u,...I]}let d=this.sig.getInputFields(),m=d.filter(I=>I.isCached),g=d.filter(I=>!I.isCached),f=m.length>0;if(this.contextCache&&f&&(this.ignoreBreakpoints||c!=="system"&&c!=="after-functions")&&g.length>0){let I=m.map(S=>this.renderInField(S,e,void 0)).filter(S=>S!==void 0).flat();I.filter(S=>S.type==="text").forEach(S=>{S.text=`${S.text}
366
+ `});let v=I.every(S=>S.type==="text")?I.map(S=>S.text).join(`
367
+ `):I.reduce(Kt(`
368
+ `),[]);r&&(typeof v=="string"?v=_n+v:v=[{type:"text",text:_n},...v]);let O=g.map(S=>this.renderInField(S,e,void 0)).filter(S=>S!==void 0).flat();O.filter(S=>S.type==="text").forEach(S=>{S.text=`${S.text}
369
+ `});let k=O.every(S=>S.type==="text")?O.map(S=>S.text).join(`
370
+ `):O.reduce(Kt(`
371
+ `),[]);return[i,...u,{role:"user",content:v,cache:!0},{role:"user",content:k}]}let x=this.sortFieldsCachedFirst(d).map(I=>this.renderInField(I,e,void 0)).filter(I=>I!==void 0).flat();x.filter(I=>I.type==="text").forEach(I=>{I.text=`${I.text}
372
+ `});let b=x.every(I=>I.type==="text")?x.map(I=>I.text).join(`
373
+ `):x.reduce(Kt(`
374
+ `),[]);r&&(typeof b=="string"?b=_n+b:b=[{type:"text",text:_n},...b]);let C=f&&g.length===0&&this.contextCache;return[i,...u,{role:"user",content:b,...C?{cache:!0}:{}}]};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}
365
375
  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(`
366
376
  `);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
367
377
  ${m}
@@ -378,32 +388,32 @@ ${m}
378
388
  `}].slice(0,-1).forEach(f=>{"text"in f&&(f.text=`${f.text}
379
389
  `),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}
380
390
  `),t.push(p)})}return t};renderExamplesAsMessages=e=>{let t=[],n={isExample:!0},r=this.sig.hasComplexFields();for(let o of e){let a=this.sortFieldsCachedFirst(this.sig.getInputFields()).map(d=>this.renderInField(d,o,{...n,isInputField:!0})).filter(d=>d!==void 0).flat(),l=a.every(d=>d.type==="text")?a.map(d=>d.text).join(`
381
- `):a.reduce(Jt(`
391
+ `):a.reduce(Kt(`
382
392
  `),[]);if(r&&this.structuredOutputFunctionName){let d={};for(let f of this.sig.getOutputFields())f.name in o&&(d[f.name]=o[f.name]);if(typeof l=="string"&&l.trim()===""||Array.isArray(l)&&l.length===0||Object.keys(d).length===0)continue;let g=`example-${t.length}`;t.push({userMessage:{role:"user",content:l},assistantMessage:{role:"assistant",functionCalls:[{id:g,type:"function",function:{name:this.structuredOutputFunctionName,params:d}}]},functionResultMessage:{role:"function",result:"done",functionId:g}});continue}let u;if(r){let d={};for(let m of this.sig.getOutputFields())m.name in o&&(d[m.name]=o[m.name]);u=JSON.stringify(d,null,2)}else u=this.sig.getOutputFields().map(m=>this.renderInField(m,o,{...n,isInputField:!1})).filter(m=>m!==void 0).flat().filter(m=>m.type==="text").map(m=>m.text).join(`
383
393
  `);let c=u.trim()==="";typeof l=="string"&&l.trim()===""||Array.isArray(l)&&l.length===0||c||t.push({userMessage:{role:"user",content:l},assistantMessage:{role:"assistant",content:u}})}return t};renderDemosAsMessages=e=>this.renderExamplesAsMessages(e);renderInputFields=e=>{let n=this.sortFieldsCachedFirst(this.sig.getInputFields()).map(r=>this.renderInField(r,e,void 0)).filter(r=>r!==void 0).flat();return n.filter(r=>r.type==="text").forEach(r=>{r.text=`${r.text}
384
- `}),n};renderInField=(e,t,n)=>{let r=t[e.name];if(Ad(e,r,n))return;e.type&&Mr(e,r);let o=hd(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(`
394
+ `}),n};renderInField=(e,t,n)=>{let r=t[e.name];if(Xd(e,r,n))return;e.type&&Or(e,r);let o=Yd(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(`
385
395
  `),n.push(t.map(r=>`- ${r}`).join(`
386
- `))):n.push(t),[{type:"text",text:n.join("")}]}},ts=s=>s.map(e=>`\`${e.title}\``).join(", "),Xu=(s,e)=>s.map(n=>{let r=n.title,o=n.type?.name?Bn(n.type):"string",i=n.isOptional?`This optional ${o} field may be omitted`:`${/^[aeiou]/i.test(o)?"An":"A"} ${o} field`,a="";if(n.description){let l=Un(n.description);e&&(l=ns(l,e)),a=` ${l}`}return`${r}: (${i})${a}`.trim()}).join(`
387
- `),Zu=(s,e)=>s.map(n=>{let r=n.title,o=n.type?.name?Bn(n.type):"string",i=n.isOptional?`Only include this ${o} field if its value is available`:`This ${o} field must be included`,a="";if(n.description&&n.description.length>0){let l=n.type?.name==="class"?n.description:Un(n.description);e&&(l=ns(l,e)),a=` ${l}`}return n.type?.options&&n.type.options.length>0&&(a.length>0&&(a+=". "),a+=`Allowed values: ${n.type.options.join(", ")}`),`${r}: (${i})${a}`.trim()}).join(`
388
- `),hd=(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?Eu(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)};function xd(s){return`{ ${Object.entries(s).map(([t,n])=>{let r=n.isOptional?"?":"",o=Bn({name:n.type,isArray:n.isArray,fields:n.fields,options:n.options});return`${t}${r}: ${o}`}).join(", ")} }`}var Bn=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 s?.fields?`object ${xd(s.fields)}`:"object";default:return"string"}})();return s?.isArray?`json array of ${e} items`:e};function Jt(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 Ad=(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 Un(s){let e=s.trim();return e.length>0?`${e.charAt(0).toUpperCase()}${e.slice(1)}${e.endsWith(".")?"":"."}`:""}function ns(s,e){if(e.size===0)return s;let t=s,n=Array.from(e.keys()).sort((r,o)=>o.length-r.length);for(let r of n){let o=e.get(r),i=new RegExp(`\`${r}\``,"g");t=t.replace(i,`\`${o}\``);let a=new RegExp(`"${r}"`,"g");t=t.replace(a,`"${o}"`);let l=new RegExp(`'${r}'`,"g");t=t.replace(l,`'${o}'`);let u=new RegExp(`\\[${r}\\]`,"g");t=t.replace(u,`[${o}]`);let c=new RegExp(`\\(${r}\\)`,"g");t=t.replace(c,`(${o})`);let p=new RegExp(`\\$${r}\\b`,"g");t=t.replace(p,`\`${o}\``)}return t}function yd(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 bd(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 rs(s,e,t,n){if(!e?.resultPicker||s.length<=1)return 0;let r=e.resultPicker;if((t?yd(t,n):!1)&&t){let l=bd(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 ec(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 rs(r,t,s,e)}var jn=class{_stepIndex=0;maxSteps;_functionsExecuted=new Set;_lastFunctionCalls=[];_usage={promptTokens:0,completionTokens:0,totalTokens:0};state=new Map;_pendingOptions={};_functionsToAdd=[];_functionsToRemove=[];_stopRequested=!1;_stopResultValues;constructor(e){this.maxSteps=e}get stepIndex(){return this._stepIndex}get isFirstStep(){return this._stepIndex===0}get functionsExecuted(){return this._functionsExecuted}get lastFunctionCalls(){return this._lastFunctionCalls}get usage(){return this._usage}setModel(e){this._pendingOptions.model=e}setThinkingBudget(e){this._pendingOptions.thinkingTokenBudget=e}setTemperature(e){this._pendingOptions.modelConfig||(this._pendingOptions.modelConfig={}),this._pendingOptions.modelConfig.temperature=e}setMaxTokens(e){this._pendingOptions.modelConfig||(this._pendingOptions.modelConfig={}),this._pendingOptions.modelConfig.maxTokens=e}setOptions(e){Object.assign(this._pendingOptions,e)}addFunctions(e){this._functionsToAdd.push(...e)}removeFunctions(...e){this._functionsToRemove.push(...e)}stop(e){this._stopRequested=!0,this._stopResultValues=e}_beginStep(e){this._stepIndex=e,this._functionsExecuted=new Set,this._lastFunctionCalls=[]}_recordFunctionCall(e,t,n){this._functionsExecuted.add(e.toLowerCase()),this._lastFunctionCalls.push({name:e,args:t,result:n})}_addUsage(e,t,n){this._usage.promptTokens+=e,this._usage.completionTokens+=t,this._usage.totalTokens+=n}_consumePendingOptions(){if(Object.keys(this._pendingOptions).length===0)return;let e=this._pendingOptions;return this._pendingOptions={},e}_consumeFunctionsToAdd(){if(this._functionsToAdd.length===0)return;let e=this._functionsToAdd;return this._functionsToAdd=[],e}_consumeFunctionsToRemove(){if(this._functionsToRemove.length===0)return;let e=this._functionsToRemove;return this._functionsToRemove=[],e}get _isStopRequested(){return this._stopRequested}get _stopValues(){return this._stopResultValues}};var os=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}=Id(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 Ve(`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 Id(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=Cd(c);e.push({name:wd(d),title:Td(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 Cd(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 Td(s,e){return`${s} ${e.replace(/\./g," ")}`}function wd(s){return s.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}function rc(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=sa(o.name),l=nc(o.parameters);n.getOutputFields().some(c=>c.name===a)||n.addOutputField({name:a,title:tc(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}=Rd(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=sa(o.name),a=nc(o.parameters);n.getOutputFields().some(u=>u.name===i)||n.addOutputField({name:i,title:tc(o.name),type:a,description:o.description||`Parameters for ${o.name}`,isOptional:!0})}return{signature:n,toolParamFieldMap:r}}}function Rd(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=vd(c),g={name:sa(d),title:Sd(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 vd(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 Sd(s,e){return`${s} ${e.replace(/\./g," ")}`}function sa(s){return s.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}function tc(s){return s.replace(/([A-Z])/g," $1").replace(/^./,e=>e.toUpperCase()).trim()}function nc(s){return!s||!s.properties||Object.keys(s.properties).length===0?{name:"string",isArray:!1}:{name:"json",isArray:!1}}var Lr=class{tools;router;injectedToolFieldNames=new Set;constructor(e){this.tools=e,this.router=new os(e)}processSignature(e){let{signature:t}=rc(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 qn="__finalResult",$e=class s extends Ut{clone=()=>new s(this.signature,this.options);promptTemplate;asserts;streamingAsserts;options;functions;fieldProcessors=[];streamingFieldProcessors=[];excludeContentFromTrace=!1;thoughtFieldName;signatureToolCallingManager;structuredOutputFunctionFallback=!1;activeAbortControllers=new Set;_stopRequested=!1;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??Yt)(this.signature,n),this.asserts=this.options?.asserts??[],this.streamingAsserts=this.options?.streamingAsserts??[],this.excludeContentFromTrace=t?.excludeContentFromTrace??!1,this.functions=t?.functions?Vt(t.functions):[],this.usage=[]}stop(){this._stopRequested=!0;for(let e of this.activeAbortControllers)e.abort("Stopped by user")}setInstruction(e){this.promptTemplate.setInstruction(e)}getInstruction(){return this.promptTemplate.getInstruction()}getSignatureName(){return this.signature.getDescription()||"unknown_signature"}getMetricsInstruments(){return Mi()}getMergedCustomLabels(e,t){return qt(fe.customLabels,e?.getOptions?.()?.customLabels,t?.customLabels)}updateMeter(e){Mi(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 ec(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}:{}},y=this.isDebug(e,n),x=a===0,b=this.getLogger(e,n);o=this.signatureToolCallingManager?[]:o;let R,A=this.signature.getOutputFields();if(this.signature.hasComplexFields()&&!this.structuredOutputFunctionFallback){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).`);R={type:"json_schema",schema:{name:"output",strict:!0,schema:Ln(A)}}}let v=n?.contextCache?.cacheBreakpoint??"after-examples",F=e.getFeatures?.(u)?.caching?.cacheBreakpoints===!1,O=n?.contextCache&&(F||v==="after-functions"||v==="after-examples"),D=o?.length&&O?o.map((L,T)=>({...L,cache:T===o.length-1})):o;return await e.chat({chatPrompt:f,functions:D,functionCall:i,modelConfig:h,model:u,responseFormat:R},{sessionId:l,rateLimiter:c,stream:p,debug:y,debugHideSystemPrompt:n?.debugHideSystemPrompt??this.options?.debugHideSystemPrompt??!x,thinkingTokenBudget:d,showThoughts:m,traceContext:r,abortSignal:n?.abortSignal??fe.abortSignal,stepIndex:a,logger:b,functionCallMode:n?.functionCallMode??this.options?.functionCallMode??"auto",retry:n?.retry??this.options?.retry,customLabels:n?.customLabels})}async*forwardCore({ai:e,mem:t,options:n,stepIndex:r,span:o,traceContext:i,states:a,stopFunctionNames:l,stepContext:u}){let{sessionId:c,functions:p}=n??{},d=n?.functionResultFormatter??this.options?.functionResultFormatter,m=n?.functionCall??this.options?.functionCall,g=this.signatureToolCallingManager,f=n?.strictMode??!1,h=n.model,y=this.usage,x=r===0,b=this.isDebug(e,n),R=this.getLogger(e,n),{functions:A,functionCall:w}=Gu(p,m,x,n);this.structuredOutputFunctionFallback&&A.filter(O=>O.name!==qn).length===0&&(w={type:"function",function:{name:qn}});let v=await this.forwardSendRequest({ai:e,mem:t,options:n,traceContext:i,functions:A,functionCall:w,stepIndex:r});v instanceof ReadableStream?yield*Bu({ai:e,model:h,res:v,mem:t,sessionId:c,traceId:o?o.spanContext?.().traceId:void 0,functions:A,strictMode:f,span:o,states:a,usage:y,asserts:this.asserts,streamingAsserts:this.streamingAsserts,fieldProcessors:this.fieldProcessors,streamingFieldProcessors:this.streamingFieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,logger:R,debug:b,functionResultFormatter:d,signatureToolCallingManager:g,stopFunctionNames:l,disableMemoryCleanup:n.disableMemoryCleanup,stepContext:u,abortSignal:n.abortSignal}):yield*ju({ai:e,model:h,res:v,mem:t,sessionId:c,traceId:o?o.spanContext?.().traceId:void 0,functions:A,span:o,strictMode:f,states:a,usage:y,asserts:this.asserts,fieldProcessors:this.fieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,logger:R,debug:b,functionResultFormatter:d,signatureToolCallingManager:g,stopFunctionNames:l,disableMemoryCleanup:n.disableMemoryCleanup,stepContext:u,abortSignal:n.abortSignal})}async*_forward2(e,t,n,r,o,i){this.signatureToolCallingManager=void 0;let a=r?.stopFunction??this.options?.stopFunction,l=Array.isArray(a)?a.map(W=>W.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 Pn,d=r.functions?Vt(r.functions):[...this.functions],m=new jn(c),g;if(r.selfTuning){if(g=r.selfTuning===!0?{model:!0,thinkingBudget:!0}:r.selfTuning,g.model!==!1){let Y=e.getModelList()?.filter(ee=>"model"in ee);if(!Y||Y.length<2)throw new Error("Self-tuning with model selection requires the AI service to have a `models` list with at least 2 chat models. Either configure models on your AI service or disable model selection with `selfTuning: { model: false }`.")}let W=Xi(e,g,r.model?String(r.model):void 0);d.push(W)}let f={...r},h=r.stepHooks,y=d&&d.length>0,x=r.functionCallMode??this.options?.functionCallMode??"auto";y&&x==="prompt"&&(this.signatureToolCallingManager=new Lr(d)),y&&x==="auto"&&!e.getFeatures(r.model).functions&&(this.signatureToolCallingManager=new Lr(d));let b,R,A=this.options?.promptTemplate??Yt;this.signatureToolCallingManager&&(this.signature=this.signatureToolCallingManager.processSignature(this.signature),this.setSignature(this.signature));let w=this.signature.hasComplexFields(),v=e.getFeatures?.(r.model),F=r.structuredOutputMode??this.options?.structuredOutputMode??"auto";if(this.structuredOutputFunctionFallback=w&&(F==="function"||F==="auto"&&!v?.structuredOutputs),this.structuredOutputFunctionFallback){let W={name:qn,description:"Return the final result. Call this function with the complete output data.",parameters:Ln(this.signature.getOutputFields()),func:async()=>"done"};d.push(W),l=[...l??[],qn.toLowerCase()]}let O=e.getFeatures?.(r.model)?.caching?.cacheBreakpoints===!1,D={functions:this.signatureToolCallingManager?[]:d,thoughtFieldName:this.thoughtFieldName,contextCache:r.contextCache,examplesInSystem:r.examplesInSystem,ignoreBreakpoints:O,structuredOutputFunctionName:this.structuredOutputFunctionFallback?qn:void 0};this.promptTemplate=new A(this.signature,D);let U,L=performance.now();Array.isArray(t)?(Sl(t),U=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos})):U=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos});let T=performance.now()-L,M=this.getMetricsInstruments(),E=this.getMergedCustomLabels(e,r);M&&Ho(M,"prompt_render",T,this.getSignatureName(),E);let N=performance.now();p.addRequest(U,r.sessionId);let P=performance.now()-N;M&&Ho(M,"memory_update",P,this.getSignatureName(),E);let _=new Map;n.forEach(W=>{_.set(W.index,{})});let G=()=>{let W=m._consumePendingOptions();if(W){let{modelConfig:ee,...oe}=W;f={...f,...oe},ee&&(f.modelConfig={...f.modelConfig,...ee})}let se=m._consumeFunctionsToAdd();if(se){let ee=Vt(se);for(let oe of ee)d.some(be=>be.name===oe.name)||d.push(oe)}let Y=m._consumeFunctionsToRemove();if(Y){let ee=new Set(Y.map(oe=>oe.toLowerCase()));for(let oe=d.length-1;oe>=0;oe--)ee.has(d[oe].name.toLowerCase())&&d.splice(oe,1)}},$=r?.abortSignal??fe.abortSignal;e:for(let W=0;W<c;W++){if(m._beginStep(W),G(),g&&g.model!==!1){let Y=d.findIndex(ee=>ee.name==="adjustGeneration");if(Y!==-1){let ee=f.model?String(f.model):void 0;d[Y]=Xi(e,g,ee)}}if(m._isStopRequested)break;if($?.aborted)throw new Ge("between-steps",$.reason??"Aborted between steps");if(h?.beforeStep&&(await h.beforeStep(m),G(),m._isStopRequested))break;let se=u;for(let Y=0;Y<=se;Y++)try{let ee=u+1;for(let be=0;be<ee;be++){n.forEach(X=>{X.content="",X.values={},X.functionCalls=[],X.functionsExecuted=new Set,X.xstate={extractedFields:[],streamedIndex:{},s:-1}}),be>0&&_.forEach((X,Ie)=>{_.set(Ie,{})});let Ce=new Map;n.forEach(X=>{Ce.set(X.index,{})});try{let X=this.forwardCore({options:{...f,functions:d},ai:e,mem:p,stepIndex:W,span:o,traceContext:i,states:n,stopFunctionNames:l,stepContext:m}),Ie=!1;try{for await(let ae of X)if(ae!==void 0){let ve=ae.index,C=ae.delta,S=Ce.get(ve)??{},k=_.get(ve)??{},I={},B=!1;for(let K of Object.keys(C)){let q=C[K],H=S[K],j;typeof q=="string"&&(typeof H=="string"||H===void 0)?j=(H??"")+q:Array.isArray(q)&&(Array.isArray(H)||H===void 0)?j=[...H??[],...q]:j=q,S[K]=j;let V=j,ne=k[K];if(typeof V=="string"&&typeof ne=="string")if(V.startsWith(ne)){let le=V.slice(ne.length);le&&(I[K]=le,B=!0,k[K]=V)}else ne.startsWith(V)||V!==ne&&(I[K]=V,B=!0,k[K]=V);else if(Array.isArray(V)&&Array.isArray(ne)){if(V.length>ne.length){let le=V.slice(ne.length);I[K]=le,B=!0,k[K]=V}}else JSON.stringify(V)!==JSON.stringify(ne)&&(I[K]=V,B=!0,k[K]=V)}B&&(yield{version:be,index:ae.index,delta:I})}}catch(ae){if(ae instanceof Wt){if(Ie=!0,this.structuredOutputFunctionFallback){let ve=ae.calls.find(C=>C.func.name===qn);if(ve?.args){let C=ve.args;$n(this.signature,C);let S=this.signature.getOutputFields();for(let k of n){let I={};for(let B of S)B.name in C&&!B.isInternal&&(I[B.name]=C[B.name],k.values[B.name]=C[B.name]);yield{version:be,index:k.index,delta:I}}for(let k of n)await Fn(this.asserts,k.values);if(this.fieldProcessors.length>0)for(let k of n)await Pr(this.fieldProcessors,k.values,p,r.sessionId)}}}else throw ae}if(this.usage.length>0){let ae=this.usage[this.usage.length-1];ae?.tokens&&m._addUsage(ae.tokens.promptTokens??0,ae.tokens.completionTokens??0,ae.tokens.totalTokens??0)}n.some(ae=>ae.functionsExecuted.size>0)&&h?.afterFunctionExecution&&(await h.afterFunctionExecution(m),G());let ue=Ie||m._isStopRequested?!1:qu(p,l,n,f?.sessionId);if(h?.afterStep&&(await h.afterStep(m),G()),ue&&!m._isStopRequested&&!$?.aborted){let ae=this.getMetricsInstruments();ae&&zo(ae,W+1,c,this.getSignatureName(),E);continue e}if($?.aborted)throw new Ge("mid-step",$.reason??"Aborted");r?.disableMemoryCleanup||(p.removeByTag("invalid-assistant",r.sessionId),p.removeByTag("correction",r.sessionId),p.removeByTag("error",r.sessionId));let Pe=this.getMetricsInstruments();if(Pe){zo(Pe,W+1,c,this.getSignatureName(),E);let ae=new Set;n.forEach(ve=>{ve.functionsExecuted.forEach(C=>ae.add(C))}),ae.size>0&&lu(Pe,!0,ae.size,!0,!1,this.getSignatureName(),E),uu(Pe,this.fieldProcessors.length,this.streamingFieldProcessors.length,this.getSignatureName(),E)}return}catch(X){if(X instanceof Ge)throw X;R=X;let Ie,re=this.isDebug(e,r),ue=this.getLogger(e,r),Pe=this.getMetricsInstruments(),ae=this.getSignatureName(),ve={error:X,errCount:be,logger:ue,metricsInstruments:Pe,signatureName:ae,span:o,debug:re,customLabels:E};if(o?.recordException(X),X instanceof Ve)Ie=yu(ve),b=X;else if(X instanceof wt)Ie=bu(ve),b=X;else if(X instanceof Ne)Iu(ve);else{if(X instanceof ut)throw X;{let C=X,S=C instanceof tt&&C.status>=500&&C.status<600,k=C instanceof We,I=C instanceof at;throw S||k||I?X:ia(X,e,this.signature)}}if(Ie&&(p.addTag("error",r.sessionId),p.addRequest([{role:"user",content:this.promptTemplate.renderExtraFields(Ie)}],r.sessionId),p.addTag("correction",r.sessionId),this.signature.hasComplexFields()))for(let S of n)S.content="",S.values={},S.xstate={extractedFields:[],streamedIndex:{},s:-1}}}let oe=this.getMetricsInstruments();throw oe&&Pi(oe,u,!1,u,this.getSignatureName(),E),ia(new Error(`Unable to fix validation error: ${(b??R)?.message??(b??R)?.toString()??"unknown error"}
396
+ `))):n.push(t),[{type:"text",text:n.join("")}]}},os=s=>s.map(e=>`\`${e.title}\``).join(", "),mc=(s,e)=>s.map(n=>{let r=n.title,o=n.type?.name?$n(n.type):"string",i=n.isOptional?`This optional ${o} field may be omitted`:`${/^[aeiou]/i.test(o)?"An":"A"} ${o} field`,a="";if(n.description){let l=Nn(n.description);e&&(l=ss(l,e)),a=` ${l}`}return`${r}: (${i})${a}`.trim()}).join(`
397
+ `),gc=(s,e)=>s.map(n=>{let r=n.title,o=n.type?.name?$n(n.type):"string",i=n.isOptional?`Only include this ${o} field if its value is available`:`This ${o} field must be included`,a="";if(n.description&&n.description.length>0){let l=n.type?.name==="class"?n.description:Nn(n.description);e&&(l=ss(l,e)),a=` ${l}`}return n.type?.options&&n.type.options.length>0&&(a.length>0&&(a+=". "),a+=`Allowed values: ${n.type.options.join(", ")}`),`${r}: (${i})${a}`.trim()}).join(`
398
+ `),Yd=(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?zu(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)};function Qd(s){return`{ ${Object.entries(s).map(([t,n])=>{let r=n.isOptional?"?":"",o=$n({name:n.type,isArray:n.isArray,fields:n.fields,options:n.options});return`${t}${r}: ${o}`}).join(", ")} }`}var $n=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 s?.fields?`object ${Qd(s.fields)}`:"object";default:return"string"}})();return s?.isArray?`json array of ${e} items`:e};function Kt(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 Xd=(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 Nn(s){let e=s.trim();return e.length>0?`${e.charAt(0).toUpperCase()}${e.slice(1)}${e.endsWith(".")?"":"."}`:""}function ss(s,e){if(e.size===0)return s;let t=s,n=Array.from(e.keys()).sort((r,o)=>o.length-r.length);for(let r of n){let o=e.get(r),i=new RegExp(`\`${r}\``,"g");t=t.replace(i,`\`${o}\``);let a=new RegExp(`"${r}"`,"g");t=t.replace(a,`"${o}"`);let l=new RegExp(`'${r}'`,"g");t=t.replace(l,`'${o}'`);let u=new RegExp(`\\[${r}\\]`,"g");t=t.replace(u,`[${o}]`);let c=new RegExp(`\\(${r}\\)`,"g");t=t.replace(c,`(${o})`);let p=new RegExp(`\\$${r}\\b`,"g");t=t.replace(p,`\`${o}\``)}return t}function Zd(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 em(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 is(s,e,t,n){if(!e?.resultPicker||s.length<=1)return 0;let r=e.resultPicker;if((t?Zd(t,n):!1)&&t){let l=em(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 fc(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 is(r,t,s,e)}var Ln=class{_stepIndex=0;maxSteps;_functionsExecuted=new Set;_lastFunctionCalls=[];_usage={promptTokens:0,completionTokens:0,totalTokens:0};state=new Map;_pendingOptions={};_functionsToAdd=[];_functionsToRemove=[];_stopRequested=!1;_stopResultValues;constructor(e){this.maxSteps=e}get stepIndex(){return this._stepIndex}get isFirstStep(){return this._stepIndex===0}get functionsExecuted(){return this._functionsExecuted}get lastFunctionCalls(){return this._lastFunctionCalls}get usage(){return this._usage}setModel(e){this._pendingOptions.model=e}setThinkingBudget(e){this._pendingOptions.thinkingTokenBudget=e}setTemperature(e){this._pendingOptions.modelConfig||(this._pendingOptions.modelConfig={}),this._pendingOptions.modelConfig.temperature=e}setMaxTokens(e){this._pendingOptions.modelConfig||(this._pendingOptions.modelConfig={}),this._pendingOptions.modelConfig.maxTokens=e}setOptions(e){Object.assign(this._pendingOptions,e)}addFunctions(e){this._functionsToAdd.push(...e)}removeFunctions(...e){this._functionsToRemove.push(...e)}stop(e){this._stopRequested=!0,this._stopResultValues=e}_beginStep(e){this._stepIndex=e,this._functionsExecuted=new Set,this._lastFunctionCalls=[]}_recordFunctionCall(e,t,n){this._functionsExecuted.add(e.toLowerCase()),this._lastFunctionCalls.push({name:e,args:t,result:n})}_addUsage(e,t,n){this._usage.promptTokens+=e,this._usage.completionTokens+=t,this._usage.totalTokens+=n}_consumePendingOptions(){if(Object.keys(this._pendingOptions).length===0)return;let e=this._pendingOptions;return this._pendingOptions={},e}_consumeFunctionsToAdd(){if(this._functionsToAdd.length===0)return;let e=this._functionsToAdd;return this._functionsToAdd=[],e}_consumeFunctionsToRemove(){if(this._functionsToRemove.length===0)return;let e=this._functionsToRemove;return this._functionsToRemove=[],e}get _isStopRequested(){return this._stopRequested}get _stopValues(){return this._stopResultValues}};var as=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}=tm(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 De(`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 tm(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=nm(c);e.push({name:om(d),title:rm(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 nm(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 rm(s,e){return`${s} ${e.replace(/\./g," ")}`}function om(s){return s.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}function Ac(s,e,t){let n=new Me(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=da(o.name),l=xc(o.parameters);n.getOutputFields().some(c=>c.name===a)||n.addOutputField({name:a,title:hc(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}=sm(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=da(o.name),a=xc(o.parameters);n.getOutputFields().some(u=>u.name===i)||n.addOutputField({name:i,title:hc(o.name),type:a,description:o.description||`Parameters for ${o.name}`,isOptional:!0})}return{signature:n,toolParamFieldMap:r}}}function sm(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=im(c),g={name:da(d),title:am(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 im(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 am(s,e){return`${s} ${e.replace(/\./g," ")}`}function da(s){return s.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}function hc(s){return s.replace(/([A-Z])/g," $1").replace(/^./,e=>e.toUpperCase()).trim()}function xc(s){return!s||!s.properties||Object.keys(s.properties).length===0?{name:"string",isArray:!1}:{name:"json",isArray:!1}}var $r=class{tools;router;injectedToolFieldNames=new Set;constructor(e){this.tools=e,this.router=new as(e)}processSignature(e){let{signature:t}=Ac(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 Dn="__finalResult",ke=class s extends Dt{clone=()=>new s(this.signature,this.options);promptTemplate;asserts;streamingAsserts;options;functions;fieldProcessors=[];streamingFieldProcessors=[];excludeContentFromTrace=!1;thoughtFieldName;signatureToolCallingManager;structuredOutputFunctionFallback=!1;activeAbortControllers=new Set;_stopRequested=!1;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??Wt)(this.signature,n),this.asserts=this.options?.asserts??[],this.streamingAsserts=this.options?.streamingAsserts??[],this.excludeContentFromTrace=t?.excludeContentFromTrace??!1,this.functions=t?.functions?Ht(t.functions):[],this.usage=[]}stop(){this._stopRequested=!0;for(let e of this.activeAbortControllers)e.abort("Stopped by user")}setInstruction(e){this.promptTemplate.setInstruction(e)}getInstruction(){return this.promptTemplate.getInstruction()}getSignatureName(){return this.signature.getDescription()||"unknown_signature"}getMetricsInstruments(){return $i()}getMergedCustomLabels(e,t){return Ut(ce.customLabels,e?.getOptions?.()?.customLabels,t?.customLabels)}updateMeter(e){$i(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 fc(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}:{}},A=this.isDebug(e,n),x=a===0,b=this.getLogger(e,n);o=this.signatureToolCallingManager?[]:o;let C,I=this.signature.getOutputFields();if(this.signature.hasComplexFields()&&!this.structuredOutputFunctionFallback){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).`);C={type:"json_schema",schema:{name:"output",strict:!0,schema:Lt(I)}}}let O=n?.contextCache?.cacheBreakpoint??"after-examples",k=e.getFeatures?.(u)?.caching?.cacheBreakpoints===!1,S=n?.contextCache&&(k||O==="after-functions"||O==="after-examples"),$=o?.length&&S?o.map((L,w)=>({...L,cache:w===o.length-1})):o;return await e.chat({chatPrompt:f,functions:$,functionCall:i,modelConfig:h,model:u,responseFormat:C},{sessionId:l,rateLimiter:c,stream:p,debug:A,debugHideSystemPrompt:n?.debugHideSystemPrompt??this.options?.debugHideSystemPrompt??!x,thinkingTokenBudget:d,showThoughts:m,traceContext:r,abortSignal:n?.abortSignal??ce.abortSignal,stepIndex:a,logger:b,functionCallMode:n?.functionCallMode??this.options?.functionCallMode??"auto",retry:n?.retry??this.options?.retry,customLabels:n?.customLabels})}async*forwardCore({ai:e,mem:t,options:n,stepIndex:r,span:o,traceContext:i,states:a,stopFunctionNames:l,stepContext:u}){let{sessionId:c,functions:p}=n??{},d=n?.functionResultFormatter??this.options?.functionResultFormatter,m=n?.functionCall??this.options?.functionCall,g=this.signatureToolCallingManager,f=n?.strictMode??!1,h=n.model,A=this.usage,x=r===0,b=this.isDebug(e,n),C=this.getLogger(e,n),{functions:I,functionCall:v}=Xu(p,m,x,n);this.structuredOutputFunctionFallback&&I.filter(S=>S.name!==Dn).length===0&&(v={type:"function",function:{name:Dn}});let O=await this.forwardSendRequest({ai:e,mem:t,options:n,traceContext:i,functions:I,functionCall:v,stepIndex:r});O instanceof ReadableStream?yield*ec({ai:e,model:h,res:O,mem:t,sessionId:c,traceId:o?o.spanContext?.().traceId:void 0,functions:I,strictMode:f,span:o,states:a,usage:A,asserts:this.asserts,streamingAsserts:this.streamingAsserts,fieldProcessors:this.fieldProcessors,streamingFieldProcessors:this.streamingFieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,logger:C,debug:b,functionResultFormatter:d,signatureToolCallingManager:g,stopFunctionNames:l,disableMemoryCleanup:n.disableMemoryCleanup,stepContext:u,abortSignal:n.abortSignal}):yield*tc({ai:e,model:h,res:O,mem:t,sessionId:c,traceId:o?o.spanContext?.().traceId:void 0,functions:I,span:o,strictMode:f,states:a,usage:A,asserts:this.asserts,fieldProcessors:this.fieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,logger:C,debug:b,functionResultFormatter:d,signatureToolCallingManager:g,stopFunctionNames:l,disableMemoryCleanup:n.disableMemoryCleanup,stepContext:u,abortSignal:n.abortSignal})}async*_forward2(e,t,n,r,o,i){this.signatureToolCallingManager=void 0;let a=r?.stopFunction??this.options?.stopFunction,l=Array.isArray(a)?a.map(W=>W.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 kn,d=r.functions?Ht(r.functions):[...this.functions],m=new Ln(c),g;if(r.selfTuning){if(g=r.selfTuning===!0?{model:!0,thinkingBudget:!0}:r.selfTuning,g.model!==!1){let Q=e.getModelList()?.filter(V=>"model"in V);if(!Q||Q.length<2)throw new Error("Self-tuning with model selection requires the AI service to have a `models` list with at least 2 chat models. Either configure models on your AI service or disable model selection with `selfTuning: { model: false }`.")}let W=oa(e,g,r.model?String(r.model):void 0);d.push(W)}let f={...r},h=r.stepHooks,A=d&&d.length>0,x=r.functionCallMode??this.options?.functionCallMode??"auto";A&&x==="prompt"&&(this.signatureToolCallingManager=new $r(d)),A&&x==="auto"&&!e.getFeatures(r.model).functions&&(this.signatureToolCallingManager=new $r(d));let b,C,I=this.options?.promptTemplate??Wt;this.signatureToolCallingManager&&(this.signature=this.signatureToolCallingManager.processSignature(this.signature),this.setSignature(this.signature));let v=this.signature.hasComplexFields(),O=e.getFeatures?.(r.model),k=r.structuredOutputMode??this.options?.structuredOutputMode??"auto";if(this.structuredOutputFunctionFallback=v&&(k==="function"||k==="auto"&&!O?.structuredOutputs),this.structuredOutputFunctionFallback){let W={name:Dn,description:"Return the final result. Call this function with the complete output data.",parameters:Lt(this.signature.getOutputFields()),func:async()=>"done"};d.push(W),l=[...l??[],Dn.toLowerCase()]}let S=e.getFeatures?.(r.model)?.caching?.cacheBreakpoints===!1,$={functions:this.signatureToolCallingManager?[]:d,thoughtFieldName:this.thoughtFieldName,contextCache:r.contextCache,examplesInSystem:r.examplesInSystem,ignoreBreakpoints:S,structuredOutputFunctionName:this.structuredOutputFunctionFallback?Dn:void 0};this.promptTemplate=new I(this.signature,$);let G,L=performance.now();Array.isArray(t)?(Ul(t),G=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos})):G=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos});let w=performance.now()-L,R=this.getMetricsInstruments(),E=this.getMergedCustomLabels(e,r);R&&Wo(R,"prompt_render",w,this.getSignatureName(),E);let _=performance.now();p.addRequest(G,r.sessionId);let M=performance.now()-_;R&&Wo(R,"memory_update",M,this.getSignatureName(),E);let N=new Map;n.forEach(W=>{N.set(W.index,{})});let q=()=>{let W=m._consumePendingOptions();if(W){let{modelConfig:V,...te}=W;f={...f,...te},V&&(f.modelConfig={...f.modelConfig,...V})}let Y=m._consumeFunctionsToAdd();if(Y){let V=Ht(Y);for(let te of V)d.some(ye=>ye.name===te.name)||d.push(te)}let Q=m._consumeFunctionsToRemove();if(Q){let V=new Set(Q.map(te=>te.toLowerCase()));for(let te=d.length-1;te>=0;te--)V.has(d[te].name.toLowerCase())&&d.splice(te,1)}},U=r?.abortSignal??ce.abortSignal;e:for(let W=0;W<c;W++){if(m._beginStep(W),q(),g&&g.model!==!1){let Q=d.findIndex(V=>V.name==="adjustGeneration");if(Q!==-1){let V=f.model?String(f.model):void 0;d[Q]=oa(e,g,V)}}if(m._isStopRequested)break;if(U?.aborted)throw new Pe("between-steps",U.reason??"Aborted between steps");if(h?.beforeStep&&(await h.beforeStep(m),q(),m._isStopRequested))break;let Y=u;for(let Q=0;Q<=Y;Q++)try{let V=u+1;for(let ye=0;ye<V;ye++){n.forEach(Z=>{Z.content="",Z.values={},Z.functionCalls=[],Z.functionsExecuted=new Set,Z.xstate={extractedFields:[],streamedIndex:{},s:-1}}),ye>0&&N.forEach((Z,fe)=>{N.set(fe,{})});let Te=new Map;n.forEach(Z=>{Te.set(Z.index,{})});try{let Z=this.forwardCore({options:{...f,functions:d},ai:e,mem:p,stepIndex:W,span:o,traceContext:i,states:n,stopFunctionNames:l,stepContext:m}),fe=!1;try{for await(let le of Z)if(le!==void 0){let Ie=le.index,T=le.delta,F=Te.get(Ie)??{},P=N.get(Ie)??{},y={},D=!1;for(let B of Object.keys(T)){let j=T[B],H=F[B],z;typeof j=="string"&&(typeof H=="string"||H===void 0)?z=(H??"")+j:Array.isArray(j)&&(Array.isArray(H)||H===void 0)?z=[...H??[],...j]:z=j,F[B]=z;let K=z,J=P[B];if(typeof K=="string"&&typeof J=="string")if(K.startsWith(J)){let oe=K.slice(J.length);oe&&(y[B]=oe,D=!0,P[B]=K)}else J.startsWith(K)||K!==J&&(y[B]=K,D=!0,P[B]=K);else if(Array.isArray(K)&&Array.isArray(J)){if(K.length>J.length){let oe=K.slice(J.length);y[B]=oe,D=!0,P[B]=K}}else JSON.stringify(K)!==JSON.stringify(J)&&(y[B]=K,D=!0,P[B]=K)}D&&(yield{version:ye,index:le.index,delta:y})}}catch(le){if(le instanceof zt){if(fe=!0,this.structuredOutputFunctionFallback){let Ie=le.calls.find(T=>T.func.name===Dn);if(Ie?.args){let T=Ie.args;Pn(this.signature,T);let F=this.signature.getOutputFields();for(let P of n){let y={};for(let D of F)D.name in T&&!D.isInternal&&(y[D.name]=T[D.name],P.values[D.name]=T[D.name]);yield{version:ye,index:P.index,delta:y}}for(let P of n)await On(this.asserts,P.values);if(this.fieldProcessors.length>0)for(let P of n)await Er(this.fieldProcessors,P.values,p,r.sessionId)}}}else throw le}if(this.usage.length>0){let le=this.usage[this.usage.length-1];le?.tokens&&m._addUsage(le.tokens.promptTokens??0,le.tokens.completionTokens??0,le.tokens.totalTokens??0)}n.some(le=>le.functionsExecuted.size>0)&&h?.afterFunctionExecution&&(await h.afterFunctionExecution(m),q());let re=fe||m._isStopRequested?!1:nc(p,l,n,f?.sessionId);if(h?.afterStep&&(await h.afterStep(m),q()),re&&!m._isStopRequested&&!U?.aborted){let le=this.getMetricsInstruments();le&&Ko(le,W+1,c,this.getSignatureName(),E);continue e}if(U?.aborted)throw new Pe("mid-step",U.reason??"Aborted");r?.disableMemoryCleanup||(p.removeByTag("invalid-assistant",r.sessionId),p.removeByTag("correction",r.sessionId),p.removeByTag("error",r.sessionId));let xe=this.getMetricsInstruments();if(xe){Ko(xe,W+1,c,this.getSignatureName(),E);let le=new Set;n.forEach(Ie=>{Ie.functionsExecuted.forEach(T=>le.add(T))}),le.size>0&&Iu(xe,!0,le.size,!0,!1,this.getSignatureName(),E),Cu(xe,this.fieldProcessors.length,this.streamingFieldProcessors.length,this.getSignatureName(),E)}return}catch(Z){if(Z instanceof Pe)throw Z;C=Z;let fe,Re=this.isDebug(e,r),re=this.getLogger(e,r),xe=this.getMetricsInstruments(),le=this.getSignatureName(),Ie={error:Z,errCount:ye,logger:re,metricsInstruments:xe,signatureName:le,span:o,debug:Re,customLabels:E};if(o?.recordException(Z),Z instanceof De)fe=Pu(Ie),b=Z;else if(Z instanceof xt)fe=Fu(Ie),b=Z;else if(Z instanceof Se)_u(Ie);else{if(Z instanceof nt)throw Z;{let T=Z,F=T instanceof ze&&T.status>=500&&T.status<600,P=T instanceof Le,y=T instanceof et;throw F||P||y?Z:ma(Z,e,this.signature)}}if(fe&&(p.addTag("error",r.sessionId),p.addRequest([{role:"user",content:this.promptTemplate.renderExtraFields(fe)}],r.sessionId),p.addTag("correction",r.sessionId),this.signature.hasComplexFields()))for(let F of n)F.content="",F.values={},F.xstate={extractedFields:[],streamedIndex:{},s:-1}}}let te=this.getMetricsInstruments();throw te&&Di(te,u,!1,u,this.getSignatureName(),E),ma(new Error(`Unable to fix validation error: ${(b??C)?.message??(b??C)?.toString()??"unknown error"}
389
399
 
390
400
  LLM Output:
391
- ${n.map(be=>be.content).join(`
401
+ ${n.map(ye=>ye.content).join(`
392
402
  ---
393
- `)}`),e,this.signature)}catch(ee){let oe=ee,be=oe instanceof tt&&oe.status>=500&&oe.status<600,Ce=oe instanceof We,X=oe instanceof at,Ie=oe instanceof ut;if((be||Ce||X||Ie)&&Y<se){let ue=this.isDebug(e,r),Pe=this.getLogger(e,r),C=Math.min(6e4,1e3*Math.pow(2,Y));ue&&Pe&&Pe({name:"Notification",id:"infrastructure-retry",value:`Infrastructure error (attempt ${Y+1}/${se+1}): ${oe.message}. Retrying in ${C}ms...`}),o?.addEvent("infrastructure.retry",{attempt:Y+1,maxRetries:se,delay:C,errorType:oe instanceof tt?"status_error":oe instanceof We?"network_error":oe instanceof at?"timeout_error":"stream_terminated",errorMessage:oe.message}),await new Promise((S,k)=>{let I=!1,B,K=()=>{$&&B&&$.removeEventListener("abort",B)},H=setTimeout(()=>{I||(I=!0,K(),S())},C);if($){if(B=()=>{I||(I=!0,clearTimeout(H),K(),k(new Ge("infrastructure-retry-backoff",$.reason?String($.reason):"Aborted during retry backoff")))},$.aborted){B();return}$.addEventListener("abort",B,{once:!0})}});continue}throw ee}}throw M&&zo(M,c,c,this.getSignatureName(),E),ia(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"&&Gt(r,n),o.name,o.name,(o.name==="string"||o.name==="code")&&dt(r,n),o.name==="number"&&mt(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"?dt(a,n):o.name==="number"?mt(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"?dt(i,a):o.type==="number"?mt(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"?dt(u,a):o.type==="number"?mt(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(a=>"role"in a))&&this.validateInputs(t);let r=new AbortController;this.activeAbortControllers.add(r),this._stopRequested&&r.abort("Stopped by user (pre-forward)");let o=Ft(r.signal,n?.abortSignal??fe.abortSignal),i=o?{...n,abortSignal:o}:n;try{let a=performance.now(),l=this.createStates(n.sampleCount??1),u=performance.now()-a,c=this.getMetricsInstruments(),p=this.getMergedCustomLabels(e,n);c&&Ho(c,"state_creation",u,this.getSignatureName(),p);let d=n?.tracer??this.options?.tracer??e.getOptions().tracer,m=this.functions;if(n?.functions&&(m=Vt(n.functions,this.functions)),!d){yield*this._forward2(e,t,l,{...i,functions:m});return}let g=m?.map(A=>A.name).join(","),f={signature:JSON.stringify(this.signature.toJSON(),null,2),...this.examples?{examples:JSON.stringify(this.examples,null,2)}:{},...g?{provided_functions:g}:{},...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}:{}},h=this.traceLabel&&n.traceLabel?`${this.traceLabel} > ${n.traceLabel}`:n.traceLabel??this.traceLabel,y=h?`AxGen > ${h}`:"AxGen",x=d.startSpan(y,{kind:ot.SERVER,attributes:f}),b=Nt.active(),R=lr.setSpan(b,x);try{if(this.excludeContentFromTrace||x.addEvent("input",{content:JSON.stringify(t,null,2)}),yield*this._forward2(e,t,l,{...i,functions:m},x,R),!this.excludeContentFromTrace){let A=l.map(v=>v.values),w=A.length===1?A[0]:A;x.addEvent("output",{content:JSON.stringify(w,null,2)})}}finally{x.end()}}finally{this.activeAbortControllers.delete(r),this._stopRequested=!1}}async forward(e,t,n){let r=n?.cachingFunction??this.options?.cachingFunction??fe.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(),m=this.getMergedCustomLabels(e,n);d&&du(d,this.signature.getInputFields().length,this.signature.getOutputFields().length,this.examples?.length??0,this.demos?.length??0,a,m);let g=this._forward1(e,t,n??{}),f=[],h=0,y=0;for await(let F of g)F.version!==h&&(f=[]),h=F.version,f=zi(f,F),y++;c=h;let x=performance.now();p=!!n?.resultPicker;let b=await rs(f,{resultPicker:n?.resultPicker},n?.mem,n?.sessionId),R=performance.now()-x,w=f[b]?.delta??{},v=Array.isArray(t)?{}:t??{};if(this.trace={...v,...w},p&&this.isDebug(e,n)){let F=this.getLogger(e,n);ll(f.length,b,R,F)}if(u=!0,d&&(pu(d,f.length,p,p?R:void 0,a,m),cu(d,l,y,void 0,a,m)),r&&o)try{await r(o,w)}catch{}return w}catch(d){throw u=!1,d}finally{let d=performance.now()-i,m=this.getMetricsInstruments(),g=this.getMergedCustomLabels(e,n);m&&(iu(m,d,u,a,e.getName(),n?.model?String(n.model):void 0,g),c>0&&Pi(m,c,u,n?.maxRetries??this.options?.maxRetries??3,a,g))}}async*streamingForward(e,t,n){let r=n?.cachingFunction??this.options?.cachingFunction??fe.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=zi(a,p);let u=await rs(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??fe.debug??e.getOptions().debug??!1}getLogger(e,t){return t?.logger??this.options?.logger??fe.logger??e.getLogger()}computeCacheKey(e,t){let n=it("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=it("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")}},Dr=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 ia(s,e,t){let n=s instanceof Error?s:new Error(String(s));if(n instanceof Ge)return n;let 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 Dr(`Generate failed: ${n.message}`,l,{cause:n})}var kd=s=>s.replace(/^\W+|\W+$/g,""),Od=(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]},Md=s=>{let e=new Set,t=[];for(let n of s)e.has(n)||(e.add(n),t.push(n));return t},Ed=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}},Pd=s=>{let e=s.match(/^(\d+)[.,\s]+(.*)$/);return e&&e[2]!==void 0?e[2].trim():s},Fd=(s,e)=>{let t=[];for(let n=0;n<s.length;n+=e)t.push(s.slice(n,n+e));return t},ss={trimNonAlphaNum:kd,splitIntoTwo:Od,dedup:Md,extractIdAndText:Ed,extractIndexPrefixedText:Pd,batchArray:Fd};var is=class extends $e{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."
394
- 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}=ss.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 as=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 $b=new rt,ls=class{name;context;constructor(e,t){this.name=e,this.context=t}getName(){return this.name}getContext(){return this.context}},us=class{ai;db;debug;constructor(e){this.db=new Lt,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 oc=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 sc(s,e){return s.filter(t=>!e.has(t))}function ic(s){let e={};for(let t of s)e[t]=(e[t]||0)+1;return e}function Qt(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 _d(s,e){return Qt(s)===Qt(e)?1:0}function Nd(s,e){let t=Qt(s).split(" "),n=Qt(e).split(" "),r=ic(t),o=ic(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 $d(s,e,t,n=!1){let r=Qt(s).split(" "),o=Qt(e).split(" "),i=Qt(t).split(" "),a=new Set([...oc,...r]);o=sc(o,a),i=sc(i,a);let l=0,u=l/o.length,c=l/i.length,p=2*u*c/(u+c);return n?c:p}var ac={emScore:_d,f1Score:Nd,novelF1ScoreOptimized:$d};var cs=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(`
403
+ `)}`),e,this.signature)}catch(V){let te=V,ye=te instanceof ze&&te.status>=500&&te.status<600,Te=te instanceof Le,Z=te instanceof et,fe=te instanceof nt;if((ye||Te||Z||fe)&&Q<Y){let re=this.isDebug(e,r),xe=this.getLogger(e,r),T=Math.min(6e4,1e3*Math.pow(2,Q));re&&xe&&xe({name:"Notification",id:"infrastructure-retry",value:`Infrastructure error (attempt ${Q+1}/${Y+1}): ${te.message}. Retrying in ${T}ms...`}),o?.addEvent("infrastructure.retry",{attempt:Q+1,maxRetries:Y,delay:T,errorType:te instanceof ze?"status_error":te instanceof Le?"network_error":te instanceof et?"timeout_error":"stream_terminated",errorMessage:te.message}),await new Promise((F,P)=>{let y=!1,D,B=()=>{U&&D&&U.removeEventListener("abort",D)},H=setTimeout(()=>{y||(y=!0,B(),F())},T);if(U){if(D=()=>{y||(y=!0,clearTimeout(H),B(),P(new Pe("infrastructure-retry-backoff",U.reason?String(U.reason):"Aborted during retry backoff")))},U.aborted){D();return}U.addEventListener("abort",D,{once:!0})}});continue}throw V}}throw R&&Ko(R,c,c,this.getSignatureName(),E),ma(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"&&$t(r,n),o.name,o.name,(o.name==="string"||o.name==="code")&&st(r,n),o.name==="number"&&it(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"?st(a,n):o.name==="number"?it(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"?st(i,a):o.type==="number"?it(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"?st(u,a):o.type==="number"?it(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(a=>"role"in a))&&this.validateInputs(t);let r=new AbortController;this.activeAbortControllers.add(r),this._stopRequested&&r.abort("Stopped by user (pre-forward)");let o=St(r.signal,n?.abortSignal??ce.abortSignal),i=o?{...n,abortSignal:o}:n;try{let a=performance.now(),l=this.createStates(n.sampleCount??1),u=performance.now()-a,c=this.getMetricsInstruments(),p=this.getMergedCustomLabels(e,n);c&&Wo(c,"state_creation",u,this.getSignatureName(),p);let d=n?.tracer??this.options?.tracer??e.getOptions().tracer,m=this.functions;if(n?.functions&&(m=Ht(n.functions,this.functions)),!d){yield*this._forward2(e,t,l,{...i,functions:m});return}let g=m?.map(I=>I.name).join(","),f={signature:JSON.stringify(this.signature.toJSON(),null,2),...this.examples?{examples:JSON.stringify(this.examples,null,2)}:{},...g?{provided_functions:g}:{},...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}:{}},h=this.traceLabel&&n.traceLabel?`${this.traceLabel} > ${n.traceLabel}`:n.traceLabel??this.traceLabel,A=h?`AxGen > ${h}`:"AxGen",x=d.startSpan(A,{kind:Ve.SERVER,attributes:f}),b=Pt.active(),C=ar.setSpan(b,x);try{if(this.excludeContentFromTrace||x.addEvent("input",{content:JSON.stringify(t,null,2)}),yield*this._forward2(e,t,l,{...i,functions:m},x,C),!this.excludeContentFromTrace){let I=l.map(O=>O.values),v=I.length===1?I[0]:I;x.addEvent("output",{content:JSON.stringify(v,null,2)})}}finally{x.end()}}finally{this.activeAbortControllers.delete(r),this._stopRequested=!1}}async forward(e,t,n){let r=n?.cachingFunction??this.options?.cachingFunction??ce.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(),m=this.getMergedCustomLabels(e,n);d&&Ru(d,this.signature.getInputFields().length,this.signature.getOutputFields().length,this.examples?.length??0,this.demos?.length??0,a,m);let g=this._forward1(e,t,n??{}),f=[],h=0,A=0;for await(let k of g)k.version!==h&&(f=[]),h=k.version,f=Yi(f,k),A++;c=h;let x=performance.now();p=!!n?.resultPicker;let b=await is(f,{resultPicker:n?.resultPicker},n?.mem,n?.sessionId),C=performance.now()-x,v=f[b]?.delta??{},O=Array.isArray(t)?{}:t??{};if(this.trace={...O,...v},p&&this.isDebug(e,n)){let k=this.getLogger(e,n);Il(f.length,b,C,k)}if(u=!0,d&&(wu(d,f.length,p,p?C:void 0,a,m),Tu(d,l,A,void 0,a,m)),r&&o)try{await r(o,v)}catch{}return v}catch(d){throw u=!1,d}finally{let d=performance.now()-i,m=this.getMetricsInstruments(),g=this.getMergedCustomLabels(e,n);m&&(yu(m,d,u,a,e.getName(),n?.model?String(n.model):void 0,g),c>0&&Di(m,c,u,n?.maxRetries??this.options?.maxRetries??3,a,g))}}async*streamingForward(e,t,n){let r=n?.cachingFunction??this.options?.cachingFunction??ce.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=Yi(a,p);let u=await is(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??ce.debug??e.getOptions().debug??!1}getLogger(e,t){return t?.logger??this.options?.logger??ce.logger??e.getLogger()}computeCacheKey(e,t){let n=Ze("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=Ze("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")}},Lr=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 ma(s,e,t){let n=s instanceof Error?s:new Error(String(s));if(n instanceof Pe)return n;let 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 Lr(`Generate failed: ${n.message}`,l,{cause:n})}var lm=s=>s.replace(/^\W+|\W+$/g,""),um=(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]},cm=s=>{let e=new Set,t=[];for(let n of s)e.has(n)||(e.add(n),t.push(n));return t},pm=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}},dm=s=>{let e=s.match(/^(\d+)[.,\s]+(.*)$/);return e&&e[2]!==void 0?e[2].trim():s},mm=(s,e)=>{let t=[];for(let n=0;n<s.length;n+=e)t.push(s.slice(n,n+e));return t},ls={trimNonAlphaNum:lm,splitIntoTwo:um,dedup:cm,extractIdAndText:pm,extractIndexPrefixedText:dm,batchArray:mm};var us=class extends ke{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."
404
+ 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}=ls.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 cs=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 SI=new Ke,ps=class{name;context;constructor(e,t){this.name=e,this.context=t}getName(){return this.name}getContext(){return this.context}},ds=class{ai;db;debug;constructor(e){this.db=new _t,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 yc=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 bc(s,e){return s.filter(t=>!e.has(t))}function Ic(s){let e={};for(let t of s)e[t]=(e[t]||0)+1;return e}function Vt(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 gm(s,e){return Vt(s)===Vt(e)?1:0}function fm(s,e){let t=Vt(s).split(" "),n=Vt(e).split(" "),r=Ic(t),o=Ic(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 hm(s,e,t,n=!1){let r=Vt(s).split(" "),o=Vt(e).split(" "),i=Vt(t).split(" "),a=new Set([...yc,...r]);o=bc(o,a),i=bc(i,a);let l=0,u=l/o.length,c=l/i.length,p=2*u*c/(u+c);return n?c:p}var Cc={emScore:gm,f1Score:fm,novelF1ScoreOptimized:hm};var ms=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(`
395
405
  Performance: `,r,"/",n,"Average Score: ",o,`
396
- `)}};function ps(s){return s.map(e=>{let t=e.type?.name??"string",n=e.description?`: ${e.description}`:"";return`- ${e.name} (${t})${n}`}).join(`
397
- `)}function Ld(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 Dd(s){return s==null?!1:!!(typeof s=="string"||typeof s=="number"||typeof s=="boolean"||Array.isArray(s)&&s.every(e=>typeof e!="object"))}var zn=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&&Dd(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++,Ld(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=`
406
+ `)}};function gs(s){return s.map(e=>{let t=e.type?.name??"string",n=e.description?`: ${e.description}`:"";return`- ${e.name} (${t})${n}`}).join(`
407
+ `)}function xm(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 Am(s){return s==null?!1:!!(typeof s=="string"||typeof s=="number"||typeof s=="boolean"||Array.isArray(s)&&s.every(e=>typeof e!="object"))}var Gn=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&&Am(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++,xm(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=`
398
408
  You are an impartial judge comparing two AI responses to the same input.
399
409
 
400
410
  **Task Description:** ${r||"Complete the task based on the input."}
401
411
 
402
412
  **Input Fields:**
403
- ${ps(o)}
413
+ ${gs(o)}
404
414
 
405
415
  **Output Fields:**
406
- ${ps(i)}
416
+ ${gs(i)}
407
417
 
408
418
  **Instructions:**
409
419
  1. Carefully analyze both Response A and Response B
@@ -412,7 +422,7 @@ ${ps(i)}
412
422
  4. Provide clear reasoning for your decision
413
423
 
414
424
  **Important:** Do not be swayed by response length alone. Focus on quality and correctness.
415
- `.trim(),p=new $e(`
425
+ `.trim(),p=new ke(`
416
426
  input:string "The original input",
417
427
  response_a:string "Response A",
418
428
  response_b:string "Response B"
@@ -431,10 +441,10 @@ You are evaluating the quality of an AI response.
431
441
  **Task Description:** ${n||"Complete the task based on the input."}
432
442
 
433
443
  **Input Fields:**
434
- ${ps(r)}
444
+ ${gs(r)}
435
445
 
436
446
  **Output Fields:**
437
- ${ps(o)}
447
+ ${gs(o)}
438
448
 
439
449
  **Evaluation Criteria:**
440
450
  ${i}
@@ -447,13 +457,13 @@ ${i}
447
457
  - unacceptable: Response is wrong, harmful, or completely off-topic
448
458
 
449
459
  First explain your reasoning, then classify the response into one of the quality tiers.
450
- `.trim(),l=new $e(`
460
+ `.trim(),l=new ke(`
451
461
  input:string "The original input",
452
462
  response:string "The AI response to evaluate"
453
463
  ->
454
464
  reasoning:string "Detailed explanation for the quality assessment",
455
465
  quality:class "excellent, good, acceptable, poor, unacceptable" "Quality tier"
456
- `);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 lc(){let s=Date.now().toString(36),e=Math.random().toString(36).substring(2,8);return`trace-${s}-${e}`}var Hn=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=lc(),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=lc(),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 uc=s=>{console.log(s)},aa=(s=uc)=>{let e=new rt,t=e.gray("\u2500".repeat(50)),n=e.gray("\u2501".repeat(50));return r=>{let o="";switch(r.name){case"OptimizationStart":o=`
466
+ `);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 Tc(){let s=Date.now().toString(36),e=Math.random().toString(36).substring(2,8);return`trace-${s}-${e}`}var Un=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=Tc(),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=Tc(),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 wc=s=>{console.log(s)},ga=(s=wc)=>{let e=new Ke,t=e.gray("\u2500".repeat(50)),n=e.gray("\u2501".repeat(50));return r=>{let o="";switch(r.name){case"OptimizationStart":o=`
457
467
  ${e.blueBright("\u25CF ")}${e.whiteBright("Optimization Started")}
458
468
  ${t}
459
469
  ${e.white("Optimizer:")} ${e.cyan(r.value.optimizerType)}
@@ -496,7 +506,7 @@ ${t}
496
506
  ${e.white("Config:")} ${e.cyan(JSON.stringify(r.value.config).slice(0,80))}${JSON.stringify(r.value.config).length>80?"...":""}
497
507
  `;break;default:o=`${e.red("\u25CF ")}${e.whiteBright("Unknown Event")}
498
508
  ${e.white(JSON.stringify(r).slice(0,100))}${JSON.stringify(r).length>100?"...":""}
499
- `}s(o)}},cc=(s=uc)=>{let e="\u2500".repeat(60);return t=>{let n="";switch(t.name){case"OptimizationStart":n=`[ OPTIMIZATION START: ${t.value.optimizerType} ]
509
+ `}s(o)}},Rc=(s=wc)=>{let e="\u2500".repeat(60);return t=>{let n="";switch(t.name){case"OptimizationStart":n=`[ OPTIMIZATION START: ${t.value.optimizerType} ]
500
510
  ${e}
501
511
  Config: ${JSON.stringify(t.value.config,null,2)}
502
512
  Examples: ${t.value.exampleCount}, Validation: ${t.value.validationCount}
@@ -522,7 +532,7 @@ Score: ${t.value.score.toFixed(3)}
522
532
  Config: ${JSON.stringify(t.value.config)}
523
533
  ${e}`;break;default:n=`[ UNKNOWN OPTIMIZER EVENT ]
524
534
  ${JSON.stringify(t)}
525
- ${e}`}s(n)}},Gr=aa();var la={enabled:!0,enabledCategories:["optimization","convergence","resource_usage","teacher_student","checkpointing","pareto"],maxLabelLength:100,samplingRate:1},ds,Gd=s=>{if(ds)return ds;if(s)return ds=Ud(s),ds};var ms=la,pc=s=>{ms={...ms,...s}},dc=()=>({...ms}),Ud=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"})}),Tt=s=>{let e={};for(let[t,n]of Object.entries(s))if(n!=null){let r=String(n),o=ms.maxLabelLength;e[t]=r.length>o?r.substring(0,o):r}return e},Bd=(s,e,t,n,r,o)=>{try{let i=Tt({success:t.toString(),optimizer_type:n,...r?{program_signature:r}:{},...o});s.optimizationLatencyHistogram&&s.optimizationLatencyHistogram.record(e,i),s.optimizationRequestsCounter&&s.optimizationRequestsCounter.add(1,i),!t&&s.optimizationErrorsCounter&&s.optimizationErrorsCounter.add(1,i)}catch(i){console.warn("Failed to record optimization metric:",i)}},jd=(s,e,t,n,r,o,i)=>{try{let a=Tt({optimizer_type:o,...i});s.convergenceRoundsHistogram&&s.convergenceRoundsHistogram.record(e,a),s.convergenceScoreGauge&&s.convergenceScoreGauge.record(t,a),s.convergenceImprovementGauge&&s.convergenceImprovementGauge.record(n,a),s.stagnationRoundsGauge&&s.stagnationRoundsGauge.record(r,a)}catch(a){console.warn("Failed to record convergence metric:",a)}},qd=(s,e,t,n)=>{try{let r=Tt({reason:e,optimizer_type:t,...n});s.earlyStoppingCounter&&s.earlyStoppingCounter.add(1,r)}catch(r){console.warn("Failed to record early stopping metric:",r)}},zd=(s,e,t,n,r,o)=>{try{let i=Tt({optimizer_type:n,...o});s.tokenUsageCounter&&s.tokenUsageCounter.add(e,i),s.costUsageCounter&&s.costUsageCounter.add(t,i),r!==void 0&&s.memoryUsageGauge&&s.memoryUsageGauge.record(r,i)}catch(i){console.warn("Failed to record resource usage metric:",i)}},Hd=(s,e,t,n)=>{try{let r=Tt({optimizer_type:t,...n});s.optimizationDurationHistogram&&s.optimizationDurationHistogram.record(e,r)}catch(r){console.warn("Failed to record optimization duration metric:",r)}},Kd=(s,e,t,n,r)=>{try{let o=Tt({optimizer_type:n,...r});s.teacherStudentUsageCounter&&s.teacherStudentUsageCounter.add(1,o),s.teacherStudentLatencyHistogram&&s.teacherStudentLatencyHistogram.record(e,o),s.teacherStudentScoreImprovementGauge&&s.teacherStudentScoreImprovementGauge.record(t,o)}catch(o){console.warn("Failed to record teacher-student metric:",o)}},Wd=(s,e,t,n,r,o)=>{try{let i=Tt({operation:e,success:n.toString(),optimizer_type:r,...o});e==="save"?(s.checkpointSaveCounter&&s.checkpointSaveCounter.add(1,i),s.checkpointSaveLatencyHistogram&&s.checkpointSaveLatencyHistogram.record(t,i)):(s.checkpointLoadCounter&&s.checkpointLoadCounter.add(1,i),s.checkpointLoadLatencyHistogram&&s.checkpointLoadLatencyHistogram.record(t,i))}catch(i){console.warn("Failed to record checkpoint metric:",i)}},Vd=(s,e,t,n,r,o)=>{try{let i=Tt({optimizer_type:n,...o});s.paretoOptimizationsCounter&&s.paretoOptimizationsCounter.add(1,i),s.paretoFrontSizeHistogram&&s.paretoFrontSizeHistogram.record(e,i),r!==void 0&&s.paretoHypervolumeGauge&&s.paretoHypervolumeGauge.record(r,i),s.paretoSolutionsGeneratedHistogram&&s.paretoSolutionsGeneratedHistogram.record(t,i)}catch(i){console.warn("Failed to record Pareto metric:",i)}},Jd=(s,e,t,n,r,o,i)=>{try{let a=Tt({optimizer_type:o,...i});s.programInputFieldsGauge&&s.programInputFieldsGauge.record(e,a),s.programOutputFieldsGauge&&s.programOutputFieldsGauge.record(t,a),s.examplesCountGauge&&s.examplesCountGauge.record(n,a),s.validationSetSizeGauge&&s.validationSetSizeGauge.record(r,a)}catch(a){console.warn("Failed to record program complexity metric:",a)}},Yd=(s,e,t,n,r)=>{try{let o=Tt({metric_type:e,optimizer_type:n,...r});switch(e){case"evaluation":s.evaluationLatencyHistogram&&s.evaluationLatencyHistogram.record(t,o);break;case"demo_generation":s.demoGenerationLatencyHistogram&&s.demoGenerationLatencyHistogram.record(t,o);break;case"metric_computation":s.metricComputationLatencyHistogram&&s.metricComputationLatencyHistogram.record(t,o);break}}catch(o){console.warn("Failed to record optimizer performance metric:",o)}},Qd=(s,e,t,n,r)=>{try{let o=Tt({optimizer_type:e,...r});s.optimizerTypeGauge&&s.optimizerTypeGauge.record(1,o),t!==void 0&&s.targetScoreGauge&&s.targetScoreGauge.record(t,o),n!==void 0&&s.maxRoundsGauge&&s.maxRoundsGauge.record(n,o)}catch(o){console.warn("Failed to record optimizer configuration metric:",o)}},St=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,{modelConfig:this.modelConfig}):this.modelConfig&&e.setDemos([],{modelConfig:this.modelConfig})}},Ur=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}},st=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 Ur({maxTokens:1e6});this.costTracker=e.costTracker??t,this.metricsInstruments=Gd(fe.meter),this.stats=this.initializeStats(),this.debugOptimizer=e.debugOptimizer??!1,this.optimizerLogger=e.optimizerLogger??(this.verbose?Gr:void 0),this.initializeResultExplainer()}getMergedCustomLabels(e){return qt(fe.customLabels,this.studentAI?.getOptions?.()?.customLabels,this.teacherAI?.getOptions?.()?.customLabels,e?.customLabels)}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,n){this.stats.earlyStopped=!0,this.stats.earlyStopping={bestScoreRound:t,patienceExhausted:e.includes("improvement"),reason:e},this.recordEarlyStoppingMetrics(e,"unknown",n),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,r);let l,u=(g,f,h,y,x,b,R,A={},w)=>{this.getOptimizerLogger(w)?.({name:"RoundProgress",value:{round:g,totalRounds:w?.maxIterations??0,currentScore:f,bestScore:b,configuration:h}}),this.updateOptimizationProgress(g,f,h,y,x,b,R,A,w)},c=(g,f)=>{l=g,this.triggerEarlyStopping(g,this.currentRound,r)},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,r),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,r);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}),y=0;for(let[x,b]of Object.entries(h))y+=b*(d[x]||0);return y};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[y,x]of Object.entries(g))y!==c&&x<.3&&(h+=(.3-x)*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 $e(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,i)}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",t)}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,n){if(!this.metricsInstruments)return;let r=this.getMergedCustomLabels(n);if(t){let o=(t.match(/input:/g)||[]).length,i=(t.match(/output:/g)||[]).length;Jd(this.metricsInstruments,o,i,0,0,e,r)}Qd(this.metricsInstruments,e,this.targetScore,void 0,r)}recordOptimizationComplete(e,t,n,r,o){if(!this.metricsInstruments)return;let i=this.getMergedCustomLabels(o);Bd(this.metricsInstruments,e,t,n,r,i),Hd(this.metricsInstruments,e,n,i);let a=this.costTracker?.getCurrentCost()??0,l=this.costTracker?.getTotalTokens()??0;zd(this.metricsInstruments,l,a,n,void 0,i)}recordConvergenceMetrics(e,t,n,r,o,i){if(!this.metricsInstruments)return;let a=this.getMergedCustomLabels(i);jd(this.metricsInstruments,e,t,n,r,o,a)}recordEarlyStoppingMetrics(e,t,n){if(!this.metricsInstruments)return;let r=this.getMergedCustomLabels(n);qd(this.metricsInstruments,e,t,r)}recordTeacherStudentMetrics(e,t,n,r){if(!this.metricsInstruments)return;let o=this.getMergedCustomLabels(r);Kd(this.metricsInstruments,e,t,n,o)}recordCheckpointMetrics(e,t,n,r,o){if(!this.metricsInstruments)return;let i=this.getMergedCustomLabels(o);Wd(this.metricsInstruments,e,t,n,r,i)}recordParetoMetrics(e,t,n,r,o){if(!this.metricsInstruments)return;let i=this.getMergedCustomLabels(o);Vd(this.metricsInstruments,e,t,n,r,i)}recordPerformanceMetrics(e,t,n,r){if(!this.metricsInstruments)return;let o=this.getMergedCustomLabels(r);Yd(this.metricsInstruments,e,t,n,o)}isOptimizerLoggingEnabled(e){return this.debugOptimizer||(e?.verbose??this.verbose??!1)}getOptimizerLogger(e){if(this.isOptimizerLoggingEnabled(e))return this.optimizerLogger??fe.optimizerLogger??Gr}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 mc(s){return Be.create(s)}function Ze(s,e){let t=typeof s=="string"?Be.create(s):s;return new $e(t,e)}function gc(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 kt(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(gc(s[i].scores,s[n].scores,e)){o=!0;break}gc(s[n].scores,s[i].scores,e)&&r++}o||t.push({idx:s[n].idx,scores:s[n].scores,dominated:r})}return t}function ft(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 Xt(s){if(s.length===0)return 0;let e=0;for(let t of s)e+=t;return e/s.length}function gs(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 Br(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 jr(s,e,t){let n=Br(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 Kn=class s extends st{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(P,_)=>{try{e.setInstruction?.(P);let G=await e.forward(this.studentAI,_,{sampleCount:this.sampleCount});return this.stats.totalCalls+=1,await n({prediction:G,example:_})||{}}catch{return{}}},p=async(P,_)=>{let G=[];for(let $ of _)G.push(await c(P,$));return gs(G)},d=await this.getBaseInstruction(e),m=[{instruction:d,parent:void 0,scores:await p(d,l)}],g=P=>{let _=r?.paretoMetricKey,G=r?.paretoScalarize;if(typeof G=="function")return G(P);if(_)return Number.isFinite(P[_])?P[_]:0;let $=Object.values(P);return $.length?$.reduce((W,se)=>W+se,0)/$.length:0},f=[],h=async(P,_)=>{let G=[];for(let $ of _){let W=await c(P,$);G.push(g(W))}return G};f.push(await h(d,l));let y=()=>{let P=f[0]?.length??0,_=[];for(let $=0;$<P;$++){let W=Number.NEGATIVE_INFINITY,se=new Set;for(let Y=0;Y<f.length;Y++){let ee=f[Y][$];ee>W+this.tieEpsilon?(W=ee,se.clear(),se.add(Y)):Math.abs(ee-W)<=this.tieEpsilon&&se.add(Y)}_.push(se)}let G=f.map($=>Xt($));return jr(_,G)},x=r?.maxMetricCalls;if(!Number.isFinite(x)||x<=0)throw new Error("AxGEPA: options.maxMetricCalls must be set to a positive integer");let b=Math.floor(x),R=this.getOptimizerLogger(r),A=r?.verbose??this.verbose?P=>console.log(`[GEPA] ${P}`):P=>{};R?.({name:"OptimizationStart",value:{optimizerType:"GEPA",exampleCount:t.length,validationCount:l.length,config:{numTrials:this.numTrials,minibatch:this.minibatch,mergeMax:this.mergeMax}}}),A(`Starting GEPA optimization: ${t.length} train, ${l.length} validation, maxCalls=${b}`);let w=0,v=kt(m.map((P,_)=>({idx:_,scores:P.scores})),this.tieEpsilon).map(P=>P.idx),F;for(let P=0;P<this.numTrials&&!(b!==void 0&&this.stats.totalCalls>=Math.max(1,Math.floor(b)));P++){let _=f[0]?.length??0,G=[];for(let k=0;k<_;k++){let I=Number.NEGATIVE_INFINITY,B=new Set;for(let K=0;K<f.length;K++){let q=f[K][k];q>I+this.tieEpsilon?(I=q,B.clear(),B.add(K)):Math.abs(q-I)<=this.tieEpsilon&&B.add(K)}G.push(B)}let $=f.map(k=>Xt(k));if(this.mergeMax>0&&this.mergesDue>0&&this.lastIterFoundNewProgram){let k=j=>{let V=[],ne=j;for(;ne!==void 0;)V.push(ne),ne=m[ne]?.parent;return V},I=j=>j.length?j[Math.floor(this.rand()*j.length)]:void 0,B=Br(G,$),K=new Set;for(let j of B)for(let V of j)K.add(V);let q=Array.from(K),H;for(let j=0;j<10&&!H&&!(q.length<2);j++){let V=I(q),ne=I(q);if(V===ne)continue;ne<V&&([V,ne]=[ne,V]);let le=new Set(k(V)),ce=new Set(k(ne));if(le.has(ne)||ce.has(V))continue;let ge=[...le].filter(Ee=>ce.has(Ee));if(ge.length===0)continue;let Ae=ge.map(Ee=>Math.max(1e-9,$[Ee])),Se=this.rand()*Ae.reduce((Ee,Z)=>Ee+Z,0),Fe=ge[ge.length-1];for(let Ee=0;Ee<ge.length;Ee++){if(Se<Ae[Ee]){Fe=ge[Ee];break}Se-=Ae[Ee]}H={i:V,j:ne,a:Fe}}if(this.lastIterFoundNewProgram=!1,H){let{i:j,j:V,a:ne}=H,le=$[ne],ce=$[j],ge=$[V],Ae=m[ne].instruction,Se=m[j].instruction,Fe=m[V].instruction,Ee=Se===Ae&&Fe!==Se||Fe===Ae&&Se!==Fe,Z=le<=Math.min(ce,ge)&&Ee,J="",pe="i",me=!1;if(Z){let Oe=`${j}|${V}|${ne}`;if(this.mergeAttemptKeys.has(Oe))Z=!1;else{Se===Ae&&Fe!==Se?(J=Fe,pe="j"):Fe===Ae&&Se!==Fe?(J=Se,pe="i"):Se!==Ae&&Fe!==Ae&&Se!==Fe?ce>ge||ce===ge&&this.rand()<.5?(J=Se,pe="i"):(J=Fe,pe="j"):(J=Se,pe="i");let et=`${Math.min(j,V)}|${Math.max(j,V)}|${pe}`;if(this.mergeCompositionKeys.has(et))Z=!1;else{this.mergeAttemptKeys.add(Oe),this.mergeCompositionKeys.add(et);let z=f[j],Q=f[V],Me=Array.from({length:z.length},(we,Je)=>Je),Le=Me.filter(we=>(z[we]??0)>(Q[we]??0)),de=Me.filter(we=>(Q[we]??0)>(z[we]??0)),_e=Me.filter(we=>!(Le.includes(we)||de.includes(we))),te=5,ke=Math.ceil(te/3),Te=(we,Je)=>{if(Je<=0||we.length===0)return[];if(we.length<=Je)return[...we];let jt=[],Yr=new Set;for(;jt.length<Je;){let At=Math.floor(this.rand()*we.length);Yr.has(At)||(Yr.add(At),jt.push(we[At]))}return jt},De=[];De.push(...Te(Le,Math.min(ke,Le.length))),De.push(...Te(de,Math.min(ke,de.length)));let qe=te-De.length;De.push(...Te(_e,Math.max(0,qe)));let ze=te-De.length;if(ze>0){let we=Me.filter(Je=>!De.includes(Je));De.push(...Te(we,Math.min(ze,we.length)))}let xt=De.slice(0,Math.min(te,Me.length)),Ns=xt.map(we=>l[we]);me=!0;let $s=(await h(J,Ns)).reduce((we,Je)=>we+Je,0),tn=xt.reduce((we,Je)=>we+(z[Je]??0),0),Bt=xt.reduce((we,Je)=>we+(Q[Je]??0),0);if($s>=Math.max(tn,Bt)+this.tieEpsilon){A(`Iteration ${P+1}: Merge accepted (programs ${j} + ${V} via ancestor ${ne})`);let we=await p(J,l);m.push({instruction:J,parent:ne,scores:we}),f.push(await h(J,l));let Je=v.length,jt=ft(v.map(At=>m[At].scores))??0;v=kt(m.map((At,Yc)=>({idx:Yc,scores:At.scores})),this.tieEpsilon).map(At=>At.idx);let Yr=ft(v.map(At=>m[At].scores))??0;(v.length>Je||Yr>jt+1e-6)&&(w=0),this.mergesDue-=1,this.totalMergesTested+=1}}}}if(me)continue}}let W=jr(G,$,()=>this.rand()),se=this.minibatch?this.nextMinibatchIndices(u.length,P).map(k=>u[k]):u;if(r?.skipPerfectScore??!0){let k=Number(r?.perfectScore??1),I=await h(m[W].instruction,se);if(I.length>0&&I.every(B=>B>=k))continue}let Y=!1,ee=m[W].instruction,oe="reflective_mutation",be,Ce;if(Y){let k=(W+1)%m.length;ee=await this.mergeInstructions(m[W].instruction,m[k].instruction,r),oe="merge",this.mergesUsed+=1}else{let k=r?.gepaAdapter;if(k){try{let I={instruction:m[W].instruction},B=await k.evaluate(se,I,!0);be=Array.isArray(B?.scores)?B.scores.reduce((j,V)=>j+(Number(V)||0),0):void 0;let K=k.make_reflective_dataset(I,B,["instruction"]),q=await k.propose_new_texts?.(I,K,["instruction"]),H=q?.instruction??(q?Object.values(q)[0]:void 0);typeof H=="string"&&H.length>0?ee=H:ee=await this.reflectInstruction(m[W].instruction,e,se,async({prediction:j,example:V})=>{let ne=await n({prediction:j,example:V}),le=Object.values(ne||{});return le.length?le.reduce((ce,ge)=>ce+ge,0)/le.length:0},r)}catch{ee=await this.reflectInstruction(m[W].instruction,e,se,async({prediction:I,example:B})=>{let K=await n({prediction:I,example:B}),q=Object.values(K||{});return q.length?q.reduce((H,j)=>H+j,0)/q.length:0},r)}if(be!==void 0)try{let I=await k.evaluate(se,{instruction:ee},!1);Ce=Array.isArray(I?.scores)?I.scores.reduce((B,K)=>B+(Number(K)||0),0):void 0}catch{}}else ee=await this.reflectInstruction(m[W].instruction,e,se,async({prediction:I,example:B})=>{let K=await n({prediction:I,example:B}),q=Object.values(K||{});return q.length?q.reduce((H,j)=>H+j,0)/q.length:0},r)}let X=await h(m[W].instruction,se),Ie=await h(ee,se),re=X.reduce((k,I)=>k+I,0),ue=Ie.reduce((k,I)=>k+I,0);if(this.currentRound=P+1,await this.updateOptimizationProgress(this.currentRound,ue,{instructionLen:ee.length,parent:W,totalRounds:this.numTrials},"GEPA",{strategy:oe,paretoSetSize:l.length},ue,{instructionLen:m[W].instruction.length,idx:W},{...r??{},maxIterations:this.numTrials}),!(ue>re+this.tieEpsilon&&(be===void 0||Ce===void 0||Ce>be+this.tieEpsilon))){if(A(`Iteration ${P+1}: Rejected (child=${ue.toFixed(3)} <= parent=${re.toFixed(3)})`),++w>=this.earlyStoppingTrials){A(`Early stopping: ${w} iterations without improvement`);break}continue}A(`Iteration ${P+1}: Accepted (child=${ue.toFixed(3)} > parent=${re.toFixed(3)})`);let ae=await p(ee,l);m.push({instruction:ee,parent:W,scores:ae}),f.push(await h(ee,l));let ve=v.length,C=ft(v.map(k=>m[k].scores))??0;v=kt(m.map((k,I)=>({idx:I,scores:k.scores})),this.tieEpsilon).map(k=>k.idx);let S=ft(v.map(k=>m[k].scores))??0;if(v.length>ve||S>C+1e-6)w=0,A(`Iteration ${P+1}: Archive improved (size=${v.length}, hv=${S.toFixed(4)})`);else if(w++,A(`Iteration ${P+1}: Archive unchanged (stagnation=${w}/${this.earlyStoppingTrials})`),w>=this.earlyStoppingTrials){A(`Early stopping: ${w} iterations without archive improvement`);break}this.lastIterFoundNewProgram=!0,this.mergeMax>0&&this.totalMergesTested<this.mergeMax&&(this.mergesDue+=1)}let O=kt(m.map((P,_)=>({idx:_,scores:P.scores})),this.tieEpsilon),D=O.length>0?Math.max(...O.map(P=>g(P.scores))):0,U;if(O.length>0){let P=Number.NEGATIVE_INFINITY;for(let _ of O){let G=g(_.scores);G>P&&(P=G,U=_.idx)}}let L=ft(O.map(P=>P.scores));this.stats.convergenceInfo.converged=!0;let T=this.getMergedCustomLabels(r);this.recordParetoMetrics(O.length,m.length,"GEPA",L,T);let M=Date.now()-o,E=typeof U=="number"?new St({bestScore:D,stats:this.stats,instruction:m[U].instruction,demos:[],examples:t,modelConfig:void 0,optimizerType:"GEPA",optimizationTime:M,totalRounds:this.numTrials,converged:this.stats.convergenceInfo.converged}):void 0,N=this.generateOptimizationReport(O,L,D);return{demos:[],stats:this.stats,bestScore:D,paretoFront:O.map(P=>({demos:[],scores:P.scores,configuration:{candidate:P.idx,instruction:m[P.idx].instruction},dominatedSolutions:P.dominated})),paretoFrontSize:O.length,hypervolume:L,finalConfiguration:{strategy:"gepa",candidates:m.length},optimizedProgram:E,report:N}}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?Xt(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}
535
+ ${e}`}s(n)}},Dr=ga();var fa={enabled:!0,enabledCategories:["optimization","convergence","resource_usage","teacher_student","checkpointing","pareto"],maxLabelLength:100,samplingRate:1},fs,ym=s=>{if(fs)return fs;if(s)return fs=bm(s),fs};var hs=fa,vc=s=>{hs={...hs,...s}},Sc=()=>({...hs}),bm=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"})}),ft=s=>{let e={};for(let[t,n]of Object.entries(s))if(n!=null){let r=String(n),o=hs.maxLabelLength;e[t]=r.length>o?r.substring(0,o):r}return e},Im=(s,e,t,n,r,o)=>{try{let i=ft({success:t.toString(),optimizer_type:n,...r?{program_signature:r}:{},...o});s.optimizationLatencyHistogram&&s.optimizationLatencyHistogram.record(e,i),s.optimizationRequestsCounter&&s.optimizationRequestsCounter.add(1,i),!t&&s.optimizationErrorsCounter&&s.optimizationErrorsCounter.add(1,i)}catch(i){console.warn("Failed to record optimization metric:",i)}},Cm=(s,e,t,n,r,o,i)=>{try{let a=ft({optimizer_type:o,...i});s.convergenceRoundsHistogram&&s.convergenceRoundsHistogram.record(e,a),s.convergenceScoreGauge&&s.convergenceScoreGauge.record(t,a),s.convergenceImprovementGauge&&s.convergenceImprovementGauge.record(n,a),s.stagnationRoundsGauge&&s.stagnationRoundsGauge.record(r,a)}catch(a){console.warn("Failed to record convergence metric:",a)}},Tm=(s,e,t,n)=>{try{let r=ft({reason:e,optimizer_type:t,...n});s.earlyStoppingCounter&&s.earlyStoppingCounter.add(1,r)}catch(r){console.warn("Failed to record early stopping metric:",r)}},wm=(s,e,t,n,r,o)=>{try{let i=ft({optimizer_type:n,...o});s.tokenUsageCounter&&s.tokenUsageCounter.add(e,i),s.costUsageCounter&&s.costUsageCounter.add(t,i),r!==void 0&&s.memoryUsageGauge&&s.memoryUsageGauge.record(r,i)}catch(i){console.warn("Failed to record resource usage metric:",i)}},Rm=(s,e,t,n)=>{try{let r=ft({optimizer_type:t,...n});s.optimizationDurationHistogram&&s.optimizationDurationHistogram.record(e,r)}catch(r){console.warn("Failed to record optimization duration metric:",r)}},vm=(s,e,t,n,r)=>{try{let o=ft({optimizer_type:n,...r});s.teacherStudentUsageCounter&&s.teacherStudentUsageCounter.add(1,o),s.teacherStudentLatencyHistogram&&s.teacherStudentLatencyHistogram.record(e,o),s.teacherStudentScoreImprovementGauge&&s.teacherStudentScoreImprovementGauge.record(t,o)}catch(o){console.warn("Failed to record teacher-student metric:",o)}},Sm=(s,e,t,n,r,o)=>{try{let i=ft({operation:e,success:n.toString(),optimizer_type:r,...o});e==="save"?(s.checkpointSaveCounter&&s.checkpointSaveCounter.add(1,i),s.checkpointSaveLatencyHistogram&&s.checkpointSaveLatencyHistogram.record(t,i)):(s.checkpointLoadCounter&&s.checkpointLoadCounter.add(1,i),s.checkpointLoadLatencyHistogram&&s.checkpointLoadLatencyHistogram.record(t,i))}catch(i){console.warn("Failed to record checkpoint metric:",i)}},km=(s,e,t,n,r,o)=>{try{let i=ft({optimizer_type:n,...o});s.paretoOptimizationsCounter&&s.paretoOptimizationsCounter.add(1,i),s.paretoFrontSizeHistogram&&s.paretoFrontSizeHistogram.record(e,i),r!==void 0&&s.paretoHypervolumeGauge&&s.paretoHypervolumeGauge.record(r,i),s.paretoSolutionsGeneratedHistogram&&s.paretoSolutionsGeneratedHistogram.record(t,i)}catch(i){console.warn("Failed to record Pareto metric:",i)}},Om=(s,e,t,n,r,o,i)=>{try{let a=ft({optimizer_type:o,...i});s.programInputFieldsGauge&&s.programInputFieldsGauge.record(e,a),s.programOutputFieldsGauge&&s.programOutputFieldsGauge.record(t,a),s.examplesCountGauge&&s.examplesCountGauge.record(n,a),s.validationSetSizeGauge&&s.validationSetSizeGauge.record(r,a)}catch(a){console.warn("Failed to record program complexity metric:",a)}},Mm=(s,e,t,n,r)=>{try{let o=ft({metric_type:e,optimizer_type:n,...r});switch(e){case"evaluation":s.evaluationLatencyHistogram&&s.evaluationLatencyHistogram.record(t,o);break;case"demo_generation":s.demoGenerationLatencyHistogram&&s.demoGenerationLatencyHistogram.record(t,o);break;case"metric_computation":s.metricComputationLatencyHistogram&&s.metricComputationLatencyHistogram.record(t,o);break}}catch(o){console.warn("Failed to record optimizer performance metric:",o)}},Em=(s,e,t,n,r)=>{try{let o=ft({optimizer_type:e,...r});s.optimizerTypeGauge&&s.optimizerTypeGauge.record(1,o),t!==void 0&&s.targetScoreGauge&&s.targetScoreGauge.record(t,o),n!==void 0&&s.maxRoundsGauge&&s.maxRoundsGauge.record(n,o)}catch(o){console.warn("Failed to record optimizer configuration metric:",o)}},bt=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,{modelConfig:this.modelConfig}):this.modelConfig&&e.setDemos([],{modelConfig:this.modelConfig})}},Gr=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 Gr({maxTokens:1e6});this.costTracker=e.costTracker??t,this.metricsInstruments=ym(ce.meter),this.stats=this.initializeStats(),this.debugOptimizer=e.debugOptimizer??!1,this.optimizerLogger=e.optimizerLogger??(this.verbose?Dr:void 0),this.initializeResultExplainer()}getMergedCustomLabels(e){return Ut(ce.customLabels,this.studentAI?.getOptions?.()?.customLabels,this.teacherAI?.getOptions?.()?.customLabels,e?.customLabels)}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,n){this.stats.earlyStopped=!0,this.stats.earlyStopping={bestScoreRound:t,patienceExhausted:e.includes("improvement"),reason:e},this.recordEarlyStoppingMetrics(e,"unknown",n),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,r);let l,u=(g,f,h,A,x,b,C,I={},v)=>{this.getOptimizerLogger(v)?.({name:"RoundProgress",value:{round:g,totalRounds:v?.maxIterations??0,currentScore:f,bestScore:b,configuration:h}}),this.updateOptimizationProgress(g,f,h,A,x,b,C,I,v)},c=(g,f)=>{l=g,this.triggerEarlyStopping(g,this.currentRound,r)},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,r),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,r);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}),A=0;for(let[x,b]of Object.entries(h))A+=b*(d[x]||0);return A};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[A,x]of Object.entries(g))A!==c&&x<.3&&(h+=(.3-x)*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 ke(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,i)}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",t)}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,n){if(!this.metricsInstruments)return;let r=this.getMergedCustomLabels(n);if(t){let o=(t.match(/input:/g)||[]).length,i=(t.match(/output:/g)||[]).length;Om(this.metricsInstruments,o,i,0,0,e,r)}Em(this.metricsInstruments,e,this.targetScore,void 0,r)}recordOptimizationComplete(e,t,n,r,o){if(!this.metricsInstruments)return;let i=this.getMergedCustomLabels(o);Im(this.metricsInstruments,e,t,n,r,i),Rm(this.metricsInstruments,e,n,i);let a=this.costTracker?.getCurrentCost()??0,l=this.costTracker?.getTotalTokens()??0;wm(this.metricsInstruments,l,a,n,void 0,i)}recordConvergenceMetrics(e,t,n,r,o,i){if(!this.metricsInstruments)return;let a=this.getMergedCustomLabels(i);Cm(this.metricsInstruments,e,t,n,r,o,a)}recordEarlyStoppingMetrics(e,t,n){if(!this.metricsInstruments)return;let r=this.getMergedCustomLabels(n);Tm(this.metricsInstruments,e,t,r)}recordTeacherStudentMetrics(e,t,n,r){if(!this.metricsInstruments)return;let o=this.getMergedCustomLabels(r);vm(this.metricsInstruments,e,t,n,o)}recordCheckpointMetrics(e,t,n,r,o){if(!this.metricsInstruments)return;let i=this.getMergedCustomLabels(o);Sm(this.metricsInstruments,e,t,n,r,i)}recordParetoMetrics(e,t,n,r,o){if(!this.metricsInstruments)return;let i=this.getMergedCustomLabels(o);km(this.metricsInstruments,e,t,n,r,i)}recordPerformanceMetrics(e,t,n,r){if(!this.metricsInstruments)return;let o=this.getMergedCustomLabels(r);Mm(this.metricsInstruments,e,t,n,o)}isOptimizerLoggingEnabled(e){return this.debugOptimizer||(e?.verbose??this.verbose??!1)}getOptimizerLogger(e){if(this.isOptimizerLoggingEnabled(e))return this.optimizerLogger??ce.optimizerLogger??Dr}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 kc(s){return Me.create(s)}function je(s,e){let t=typeof s=="string"?Me.create(s):s;return new ke(t,e)}function Oc(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 It(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(Oc(s[i].scores,s[n].scores,e)){o=!0;break}Oc(s[n].scores,s[i].scores,e)&&r++}o||t.push({idx:s[n].idx,scores:s[n].scores,dominated:r})}return t}function lt(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 Jt(s){if(s.length===0)return 0;let e=0;for(let t of s)e+=t;return e/s.length}function xs(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 Ur(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 Br(s,e,t){let n=Ur(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 Bn=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(M,N)=>{try{e.setInstruction?.(M);let q=await e.forward(this.studentAI,N,{sampleCount:this.sampleCount});return this.stats.totalCalls+=1,await n({prediction:q,example:N})||{}}catch{return{}}},p=async(M,N)=>{let q=[];for(let U of N)q.push(await c(M,U));return xs(q)},d=await this.getBaseInstruction(e),m=[{instruction:d,parent:void 0,scores:await p(d,l)}],g=M=>{let N=r?.paretoMetricKey,q=r?.paretoScalarize;if(typeof q=="function")return q(M);if(N)return Number.isFinite(M[N])?M[N]:0;let U=Object.values(M);return U.length?U.reduce((W,Y)=>W+Y,0)/U.length:0},f=[],h=async(M,N)=>{let q=[];for(let U of N){let W=await c(M,U);q.push(g(W))}return q};f.push(await h(d,l));let A=()=>{let M=f[0]?.length??0,N=[];for(let U=0;U<M;U++){let W=Number.NEGATIVE_INFINITY,Y=new Set;for(let Q=0;Q<f.length;Q++){let V=f[Q][U];V>W+this.tieEpsilon?(W=V,Y.clear(),Y.add(Q)):Math.abs(V-W)<=this.tieEpsilon&&Y.add(Q)}N.push(Y)}let q=f.map(U=>Jt(U));return Br(N,q)},x=r?.maxMetricCalls;if(!Number.isFinite(x)||x<=0)throw new Error("AxGEPA: options.maxMetricCalls must be set to a positive integer");let b=Math.floor(x),C=this.getOptimizerLogger(r),I=r?.verbose??this.verbose?M=>console.log(`[GEPA] ${M}`):M=>{};C?.({name:"OptimizationStart",value:{optimizerType:"GEPA",exampleCount:t.length,validationCount:l.length,config:{numTrials:this.numTrials,minibatch:this.minibatch,mergeMax:this.mergeMax}}}),I(`Starting GEPA optimization: ${t.length} train, ${l.length} validation, maxCalls=${b}`);let v=0,O=It(m.map((M,N)=>({idx:N,scores:M.scores})),this.tieEpsilon).map(M=>M.idx),k;for(let M=0;M<this.numTrials&&!(b!==void 0&&this.stats.totalCalls>=Math.max(1,Math.floor(b)));M++){let N=f[0]?.length??0,q=[];for(let P=0;P<N;P++){let y=Number.NEGATIVE_INFINITY,D=new Set;for(let B=0;B<f.length;B++){let j=f[B][P];j>y+this.tieEpsilon?(y=j,D.clear(),D.add(B)):Math.abs(j-y)<=this.tieEpsilon&&D.add(B)}q.push(D)}let U=f.map(P=>Jt(P));if(this.mergeMax>0&&this.mergesDue>0&&this.lastIterFoundNewProgram){let P=z=>{let K=[],J=z;for(;J!==void 0;)K.push(J),J=m[J]?.parent;return K},y=z=>z.length?z[Math.floor(this.rand()*z.length)]:void 0,D=Ur(q,U),B=new Set;for(let z of D)for(let K of z)B.add(K);let j=Array.from(B),H;for(let z=0;z<10&&!H&&!(j.length<2);z++){let K=y(j),J=y(j);if(K===J)continue;J<K&&([K,J]=[J,K]);let oe=new Set(P(K)),se=new Set(P(J));if(oe.has(J)||se.has(K))continue;let ue=[...oe].filter(Oe=>se.has(Oe));if(ue.length===0)continue;let de=ue.map(Oe=>Math.max(1e-9,U[Oe])),Ae=this.rand()*de.reduce((Oe,X)=>Oe+X,0),Ce=ue[ue.length-1];for(let Oe=0;Oe<ue.length;Oe++){if(Ae<de[Oe]){Ce=ue[Oe];break}Ae-=de[Oe]}H={i:K,j:J,a:Ce}}if(this.lastIterFoundNewProgram=!1,H){let{i:z,j:K,a:J}=H,oe=U[J],se=U[z],ue=U[K],de=m[J].instruction,Ae=m[z].instruction,Ce=m[K].instruction,Oe=Ae===de&&Ce!==Ae||Ce===de&&Ae!==Ce,X=oe<=Math.min(se,ue)&&Oe,ee="",ie="i",ae=!1;if(X){let we=`${z}|${K}|${J}`;if(this.mergeAttemptKeys.has(we))X=!1;else{Ae===de&&Ce!==Ae?(ee=Ce,ie="j"):Ce===de&&Ae!==Ce?(ee=Ae,ie="i"):Ae!==de&&Ce!==de&&Ae!==Ce?se>ue||se===ue&&this.rand()<.5?(ee=Ae,ie="i"):(ee=Ce,ie="j"):(ee=Ae,ie="i");let We=`${Math.min(z,K)}|${Math.max(z,K)}|${ie}`;if(this.mergeCompositionKeys.has(We))X=!1;else{this.mergeAttemptKeys.add(we),this.mergeCompositionKeys.add(We);let Ye=f[z],kt=f[K],Ot=Array.from({length:Ye.length},(ve,qe)=>qe),Ct=Ot.filter(ve=>(Ye[ve]??0)>(kt[ve]??0)),Mt=Ot.filter(ve=>(kt[ve]??0)>(Ye[ve]??0)),Gt=Ot.filter(ve=>!(Ct.includes(ve)||Mt.includes(ve))),me=5,Ee=Math.ceil(me/3),ht=(ve,qe)=>{if(qe<=0||ve.length===0)return[];if(ve.length<=qe)return[...ve];let er=[],Xr=new Set;for(;er.length<qe;){let ct=Math.floor(this.rand()*ve.length);Xr.has(ct)||(Xr.add(ct),er.push(ve[ct]))}return er},Qe=[];Qe.push(...ht(Ct,Math.min(Ee,Ct.length))),Qe.push(...ht(Mt,Math.min(Ee,Mt.length)));let Xe=me-Qe.length;Qe.push(...ht(Gt,Math.max(0,Xe)));let Qr=me-Qe.length;if(Qr>0){let ve=Ot.filter(qe=>!Qe.includes(qe));Qe.push(...ht(ve,Math.min(Qr,ve.length)))}let js=Qe.slice(0,Math.min(me,Ot.length)),Rp=js.map(ve=>l[ve]);ae=!0;let vp=(await h(ee,Rp)).reduce((ve,qe)=>ve+qe,0),Sp=js.reduce((ve,qe)=>ve+(Ye[qe]??0),0),kp=js.reduce((ve,qe)=>ve+(kt[qe]??0),0);if(vp>=Math.max(Sp,kp)+this.tieEpsilon){I(`Iteration ${M+1}: Merge accepted (programs ${z} + ${K} via ancestor ${J})`);let ve=await p(ee,l);m.push({instruction:ee,parent:J,scores:ve}),f.push(await h(ee,l));let qe=O.length,er=lt(O.map(ct=>m[ct].scores))??0;O=It(m.map((ct,Op)=>({idx:Op,scores:ct.scores})),this.tieEpsilon).map(ct=>ct.idx);let Xr=lt(O.map(ct=>m[ct].scores))??0;(O.length>qe||Xr>er+1e-6)&&(v=0),this.mergesDue-=1,this.totalMergesTested+=1}}}}if(ae)continue}}let W=Br(q,U,()=>this.rand()),Y=this.minibatch?this.nextMinibatchIndices(u.length,M).map(P=>u[P]):u;if(r?.skipPerfectScore??!0){let P=Number(r?.perfectScore??1),y=await h(m[W].instruction,Y);if(y.length>0&&y.every(D=>D>=P))continue}let Q=!1,V=m[W].instruction,te="reflective_mutation",ye,Te;if(Q){let P=(W+1)%m.length;V=await this.mergeInstructions(m[W].instruction,m[P].instruction,r),te="merge",this.mergesUsed+=1}else{let P=r?.gepaAdapter;if(P){try{let y={instruction:m[W].instruction},D=await P.evaluate(Y,y,!0);ye=Array.isArray(D?.scores)?D.scores.reduce((z,K)=>z+(Number(K)||0),0):void 0;let B=P.make_reflective_dataset(y,D,["instruction"]),j=await P.propose_new_texts?.(y,B,["instruction"]),H=j?.instruction??(j?Object.values(j)[0]:void 0);typeof H=="string"&&H.length>0?V=H:V=await this.reflectInstruction(m[W].instruction,e,Y,async({prediction:z,example:K})=>{let J=await n({prediction:z,example:K}),oe=Object.values(J||{});return oe.length?oe.reduce((se,ue)=>se+ue,0)/oe.length:0},r)}catch{V=await this.reflectInstruction(m[W].instruction,e,Y,async({prediction:y,example:D})=>{let B=await n({prediction:y,example:D}),j=Object.values(B||{});return j.length?j.reduce((H,z)=>H+z,0)/j.length:0},r)}if(ye!==void 0)try{let y=await P.evaluate(Y,{instruction:V},!1);Te=Array.isArray(y?.scores)?y.scores.reduce((D,B)=>D+(Number(B)||0),0):void 0}catch{}}else V=await this.reflectInstruction(m[W].instruction,e,Y,async({prediction:y,example:D})=>{let B=await n({prediction:y,example:D}),j=Object.values(B||{});return j.length?j.reduce((H,z)=>H+z,0)/j.length:0},r)}let Z=await h(m[W].instruction,Y),fe=await h(V,Y),Re=Z.reduce((P,y)=>P+y,0),re=fe.reduce((P,y)=>P+y,0);if(this.currentRound=M+1,await this.updateOptimizationProgress(this.currentRound,re,{instructionLen:V.length,parent:W,totalRounds:this.numTrials},"GEPA",{strategy:te,paretoSetSize:l.length},re,{instructionLen:m[W].instruction.length,idx:W},{...r??{},maxIterations:this.numTrials}),!(re>Re+this.tieEpsilon&&(ye===void 0||Te===void 0||Te>ye+this.tieEpsilon))){if(I(`Iteration ${M+1}: Rejected (child=${re.toFixed(3)} <= parent=${Re.toFixed(3)})`),++v>=this.earlyStoppingTrials){I(`Early stopping: ${v} iterations without improvement`);break}continue}I(`Iteration ${M+1}: Accepted (child=${re.toFixed(3)} > parent=${Re.toFixed(3)})`);let le=await p(V,l);m.push({instruction:V,parent:W,scores:le}),f.push(await h(V,l));let Ie=O.length,T=lt(O.map(P=>m[P].scores))??0;O=It(m.map((P,y)=>({idx:y,scores:P.scores})),this.tieEpsilon).map(P=>P.idx);let F=lt(O.map(P=>m[P].scores))??0;if(O.length>Ie||F>T+1e-6)v=0,I(`Iteration ${M+1}: Archive improved (size=${O.length}, hv=${F.toFixed(4)})`);else if(v++,I(`Iteration ${M+1}: Archive unchanged (stagnation=${v}/${this.earlyStoppingTrials})`),v>=this.earlyStoppingTrials){I(`Early stopping: ${v} iterations without archive improvement`);break}this.lastIterFoundNewProgram=!0,this.mergeMax>0&&this.totalMergesTested<this.mergeMax&&(this.mergesDue+=1)}let S=It(m.map((M,N)=>({idx:N,scores:M.scores})),this.tieEpsilon),$=S.length>0?Math.max(...S.map(M=>g(M.scores))):0,G;if(S.length>0){let M=Number.NEGATIVE_INFINITY;for(let N of S){let q=g(N.scores);q>M&&(M=q,G=N.idx)}}let L=lt(S.map(M=>M.scores));this.stats.convergenceInfo.converged=!0;let w=this.getMergedCustomLabels(r);this.recordParetoMetrics(S.length,m.length,"GEPA",L,w);let R=Date.now()-o,E=typeof G=="number"?new bt({bestScore:$,stats:this.stats,instruction:m[G].instruction,demos:[],examples:t,modelConfig:void 0,optimizerType:"GEPA",optimizationTime:R,totalRounds:this.numTrials,converged:this.stats.convergenceInfo.converged}):void 0,_=this.generateOptimizationReport(S,L,$);return{demos:[],stats:this.stats,bestScore:$,paretoFront:S.map(M=>({demos:[],scores:M.scores,configuration:{candidate:M.idx,instruction:m[M.idx].instruction},dominatedSolutions:M.dominated})),paretoFrontSize:S.length,hypervolume:L,finalConfiguration:{strategy:"gepa",candidates:m.length},optimizedProgram:E,report:_}}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?Jt(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}
526
536
  `;if(h+=`## Inputs
527
537
  `,typeof f.input=="object"&&f.input!==null)for(let[x,b]of Object.entries(f.input))h+=`### ${x}
528
538
  ${String(b).trim()}
@@ -536,37 +546,37 @@ ${String(b).trim()}
536
546
  `;else h+=`${String(f.prediction).trim()}
537
547
 
538
548
  `;h+=`## Feedback
539
- `;let y=`This trajectory got a score of ${f.score.toFixed(3)}.`;if(typeof u=="function")try{let x=u({prediction:f.prediction,example:f.input});x&&(y=Array.isArray(x)?x.join(`
540
- `):x)}catch{}h+=`${y}
549
+ `;let A=`This trajectory got a score of ${f.score.toFixed(3)}.`;if(typeof u=="function")try{let x=u({prediction:f.prediction,example:f.input});x&&(A=Array.isArray(x)?x.join(`
550
+ `):x)}catch{}h+=`${A}
541
551
  `,m.push(h)}return m.join(`
542
552
 
543
- `)},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 y=`Iteration feedback: ${a.map(x=>`score=${x.score.toFixed(2)}`).join(", ")}`;return this.feedbackMemory.unshift(y),this.feedbackMemory.length>this.feedbackMemorySize&&this.feedbackMemory.pop(),h}}}catch{}let d=Ze('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=Ze(`instructionA:string "Parent A instruction",
553
+ `)},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 A=`Iteration feedback: ${a.map(x=>`score=${x.score.toFixed(2)}`).join(", ")}`;return this.feedbackMemory.unshift(A),this.feedbackMemory.length>this.feedbackMemorySize&&this.feedbackMemory.pop(),h}}}catch{}let d=je('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=je(`instructionA:string "Parent A instruction",
544
554
  instructionB:string "Parent B instruction",
545
555
  recentFeedback?:string[] "Past feedback memory"
546
- -> 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 fc(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(`
547
- `)}function Xd(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(`
548
- `)}var Wn=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=`
556
+ -> 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 Mc(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(`
557
+ `)}function Pm(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(`
558
+ `)}var jn=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=`
549
559
  You are generating realistic input data for an AI system.
550
560
 
551
561
  ${r?`Task description: ${r}`:""}
552
562
  ${this.options.domain?`Domain: ${this.options.domain}`:""}
553
563
 
554
564
  The system expects these INPUT fields:
555
- ${fc(t)}
565
+ ${Mc(t)}
556
566
 
557
567
  The system produces these OUTPUT fields:
558
- ${Xd(n)}
568
+ ${Pm(n)}
559
569
 
560
570
  Generate ${e} diverse, realistic input examples as a JSON array.
561
571
  Each example should be an object with the input fields defined above.
562
572
  Make the examples varied and realistic for the domain.
563
573
 
564
574
  Output ONLY the JSON array, no explanation.
565
- `.trim(),i=new $e("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=`
575
+ `.trim(),i=new ke("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=`
566
576
  You are generating challenging edge case input data to test an AI system's robustness.
567
577
 
568
578
  The system expects these INPUT fields:
569
- ${fc(t)}
579
+ ${Mc(t)}
570
580
 
571
581
  Generate ${e} edge case examples as a JSON array.
572
582
  Focus on these types of edge cases:
@@ -574,7 +584,7 @@ ${n.map(i=>`- ${i}`).join(`
574
584
  `)}
575
585
 
576
586
  Output ONLY the JSON array, no explanation.
577
- `.trim(),o=new $e("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 $e(this.signature).forward(this.options.teacher,e,{model:this.options.model})}getSignature(){return this.signature}getTeacher(){return this.options.teacher}};var fs=class s{gen;options;tracer;currentScore;constructor(e,t){this.gen=e,this.options={...t,enableTracing:t.enableTracing??!0},this.tracer=new Hn(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 w=(await this.getTraces()).filter(v=>v.input&&v.output).map(v=>({...v.input,...v.output}));i=[...i,...w]}if(n.generateExamples||i.length===0){let A=n.synthCount??20,w={teacher:r,...n.synthOptions},O=(await new Wn(this.gen.getSignature(),w).generate(A)).examples.map(D=>({...D.input,...D.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 A={ai:r,criteria:n.criteria,...n.judgeOptions};d=new zn(this.gen.getSignature(),A).toMetricFn()}let m=new Kn({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,y=h,b=((await this.options.storage.load(this.options.name,{type:"checkpoint",limit:1}))[0]?.version??0)+1,R={type:"checkpoint",name:this.options.name,version:b,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,R),{score:h,improvement:y,checkpointVersion:b,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 hs=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 hc=nr(np("crypto"),1);function ua(s){let e=new Date().toISOString();return{version:1,sections:{},stats:{bulletCount:0,helpfulCount:0,harmfulCount:0,tokenEstimate:0},updatedAt:e,description:s}}function Zt(s){return JSON.parse(JSON.stringify(s))}function Zd(s){return Math.ceil(s.length/4)}function ca(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=tm(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??em(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 ma(s),s.updatedAt=u,{updatedBulletIds:n,autoRemoved:r}}function pa(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(),ma(s);return}}}function qr(s){let e=s.description?`## Context Playbook
587
+ `.trim(),o=new ke("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 ke(this.signature).forward(this.options.teacher,e,{model:this.options.model})}getSignature(){return this.signature}getTeacher(){return this.options.teacher}};var As=class s{gen;options;tracer;currentScore;constructor(e,t){this.gen=e,this.options={...t,enableTracing:t.enableTracing??!0},this.tracer=new Un(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 v=(await this.getTraces()).filter(O=>O.input&&O.output).map(O=>({...O.input,...O.output}));i=[...i,...v]}if(n.generateExamples||i.length===0){let I=n.synthCount??20,v={teacher:r,...n.synthOptions},S=(await new jn(this.gen.getSignature(),v).generate(I)).examples.map($=>({...$.input,...$.expected}));i=[...i,...S]}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 I={ai:r,criteria:n.criteria,...n.judgeOptions};d=new Gn(this.gen.getSignature(),I).toMetricFn()}let m=new Bn({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,A=h,b=((await this.options.storage.load(this.options.name,{type:"checkpoint",limit:1}))[0]?.version??0)+1,C={type:"checkpoint",name:this.options.name,version:b,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,C),{score:h,improvement:A,checkpointVersion:b,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 ys=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 Ec=tr(Np("crypto"),1);function ha(s){let e=new Date().toISOString();return{version:1,sections:{},stats:{bulletCount:0,helpfulCount:0,harmfulCount:0,tokenEstimate:0},updatedAt:e,description:s}}function Yt(s){return JSON.parse(JSON.stringify(s))}function Fm(s){return Math.ceil(s.length/4)}function xa(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=Nm(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??_m(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 ba(s),s.updatedAt=u,{updatedBulletIds:n,autoRemoved:r}}function Aa(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(),ba(s);return}}}function jr(s){let e=s.description?`## Context Playbook
578
588
  ${s.description.trim()}
579
589
  `:`## Context Playbook
580
590
  `,t=Object.entries(s.sections).map(([n,r])=>{let o=r.map(i=>`- [${i.id}] ${i.content}`).join(`
@@ -583,11 +593,11 @@ ${o}`:`### ${n}
583
593
  _(empty)_`}).join(`
584
594
 
585
595
  `);return`${e}
586
- ${t}`.trim()}function em(s){let e=s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,6),t=hc.default.randomBytes(4).toString("hex");return`${e||"ctx"}-${t}`}function tm(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),y=[f,m,Number.isFinite(h)?h:Number.POSITIVE_INFINITY];(p[0]<y[0]||p[0]===y[0]&&p[1]<y[1]||p[0]===y[0]&&p[1]===y[1]&&p[2]<y[2])&&(t=o,n=p)}if(t===-1)return;let[r]=s.splice(t,1);return r}function da(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}ma(s)}function ma(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+=Zd(i.content);s.stats={bulletCount:e,helpfulCount:t,harmfulCount:n,tokenEstimate:r}}var nm={maxEpochs:1,maxReflectorRounds:2,maxSectionSize:25,similarityThreshold:.95,allowDynamicSections:!0},zr=class extends St{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=Zt(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(),"",qr(this.playbook)].filter(o=>o&&o.trim().length>0).join(`
596
+ ${t}`.trim()}function _m(s){let e=s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,6),t=Ec.default.randomBytes(4).toString("hex");return`${e||"ctx"}-${t}`}function Nm(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),A=[f,m,Number.isFinite(h)?h:Number.POSITIVE_INFINITY];(p[0]<A[0]||p[0]===A[0]&&p[1]<A[1]||p[0]===A[0]&&p[1]===A[1]&&p[2]<A[2])&&(t=o,n=p)}if(t===-1)return;let[r]=s.splice(t,1);return r}function ya(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}ba(s)}function ba(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+=Fm(i.content);s.stats={bulletCount:e,helpfulCount:t,harmfulCount:n,tokenEstimate:r}}var $m={maxEpochs:1,maxReflectorRounds:2,maxSectionSize:25,similarityThreshold:.95,allowDynamicSections:!0},qr=class extends bt{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=Yt(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(),"",jr(this.playbook)].filter(o=>o&&o.trim().length>0).join(`
587
597
 
588
- `);e.setDescription(r)}},xs=class extends st{aceConfig;playbook;generatorHistory=[];deltaHistory=[];reflectorProgram;curatorProgram;program;constructor(e,t){super(e),this.aceConfig={...nm,...t},this.playbook=t?.initialPlaybook!==void 0?Zt(t.initialPlaybook):ua()}reset(){super.reset(),this.playbook=this.aceConfig.initialPlaybook!==void 0?Zt(this.aceConfig.initialPlaybook):ua(),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=Zt(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 y=0;y<p;y++)for(let x=0;x<t.length;x++){let b=t[x],R=this.composeInstruction(a??l,this.playbook);e.setDescription?.(R);let A=await e.forward(this.studentAI,b);this.stats.totalCalls+=1;let w=await n({prediction:A,example:b});typeof w=="number"&&(this.stats.bestScore=Math.max(this.stats.bestScore,w),u=Math.max(u,w));let v=A?.severity,F=b?.severity,O=this.createGeneratorOutput(A,b),D=F&&v&&F!==v,U=await this.runReflectionRounds({example:b,generatorOutput:O,feedback:F&&v&&F!==v?`Expected severity "${F}" but model predicted "${v}".`:void 0}),L=await this.runCurator({program:e,example:b,reflection:U,playbook:this.playbook}),T=this.normalizeCuratorOperations(L?.operations);T.length===0&&D&&(T=this.inferOperationsFromReflection(U)),T=this.resolveCuratorOperationTargets(T,this.playbook,U,O);let M=L||T.length>0?{...L??{},operations:T}:void 0,E=[];if(T.length>0){let $=this.collectProtectedBulletIds(T),W=ca(this.playbook,T,{maxSectionSize:this.aceConfig.maxSectionSize,allowDynamicSections:this.aceConfig.allowDynamicSections,enableAutoPrune:!0,protectedBulletIds:$});E=W.updatedBulletIds,W.autoRemoved.length>0&&(T.push(...W.autoRemoved),M&&(M.operations=T))}if(U?.bulletTags)for(let $ of U.bulletTags)pa(this.playbook,$.id,$.tag);T.length>0&&E.length>0&&da(this.playbook,this.aceConfig.similarityThreshold);let N={example:b,prediction:A,score:typeof w=="number"?w:0,generatorOutput:O,reflection:U,curator:M,timestamp:new Date().toISOString()};this.generatorHistory.push(N),E.length>0&&M?.operations?.length&&this.deltaHistory.push({epoch:y,exampleIndex:x,operations:M.operations}),c+=1,this.currentRound=c;let P=typeof w=="number"&&Number.isFinite(w)?w:0,_=Number.isFinite(u)?u:P,G={...r??{},maxIterations:d};await this.updateOptimizationProgress(c,P,{epoch:y,exampleIndex:x,playbookBullets:this.playbook.stats.bulletCount},"ACE",{epochs:p,totalRounds:d},_,{playbookBullets:this.playbook.stats.bulletCount},void 0,G),this.stats.convergenceInfo.finalImprovement=Math.max(this.stats.convergenceInfo.finalImprovement,P)}}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:Zt(this.playbook),feedback:[...this.generatorHistory],history:[...this.deltaHistory]},f=new zr({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:Zt(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)pa(this.playbook,p.id,p.tag);if(a.length>0){let p=this.collectProtectedBulletIds(a),d=ca(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)),da(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(),"",qr(t)].filter(r=>r.trim().length>0).join(`
598
+ `);e.setDescription(r)}},bs=class extends Je{aceConfig;playbook;generatorHistory=[];deltaHistory=[];reflectorProgram;curatorProgram;program;constructor(e,t){super(e),this.aceConfig={...$m,...t},this.playbook=t?.initialPlaybook!==void 0?Yt(t.initialPlaybook):ha()}reset(){super.reset(),this.playbook=this.aceConfig.initialPlaybook!==void 0?Yt(this.aceConfig.initialPlaybook):ha(),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=Yt(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 A=0;A<p;A++)for(let x=0;x<t.length;x++){let b=t[x],C=this.composeInstruction(a??l,this.playbook);e.setDescription?.(C);let I=await e.forward(this.studentAI,b);this.stats.totalCalls+=1;let v=await n({prediction:I,example:b});typeof v=="number"&&(this.stats.bestScore=Math.max(this.stats.bestScore,v),u=Math.max(u,v));let O=I?.severity,k=b?.severity,S=this.createGeneratorOutput(I,b),$=k&&O&&k!==O,G=await this.runReflectionRounds({example:b,generatorOutput:S,feedback:k&&O&&k!==O?`Expected severity "${k}" but model predicted "${O}".`:void 0}),L=await this.runCurator({program:e,example:b,reflection:G,playbook:this.playbook}),w=this.normalizeCuratorOperations(L?.operations);w.length===0&&$&&(w=this.inferOperationsFromReflection(G)),w=this.resolveCuratorOperationTargets(w,this.playbook,G,S);let R=L||w.length>0?{...L??{},operations:w}:void 0,E=[];if(w.length>0){let U=this.collectProtectedBulletIds(w),W=xa(this.playbook,w,{maxSectionSize:this.aceConfig.maxSectionSize,allowDynamicSections:this.aceConfig.allowDynamicSections,enableAutoPrune:!0,protectedBulletIds:U});E=W.updatedBulletIds,W.autoRemoved.length>0&&(w.push(...W.autoRemoved),R&&(R.operations=w))}if(G?.bulletTags)for(let U of G.bulletTags)Aa(this.playbook,U.id,U.tag);w.length>0&&E.length>0&&ya(this.playbook,this.aceConfig.similarityThreshold);let _={example:b,prediction:I,score:typeof v=="number"?v:0,generatorOutput:S,reflection:G,curator:R,timestamp:new Date().toISOString()};this.generatorHistory.push(_),E.length>0&&R?.operations?.length&&this.deltaHistory.push({epoch:A,exampleIndex:x,operations:R.operations}),c+=1,this.currentRound=c;let M=typeof v=="number"&&Number.isFinite(v)?v:0,N=Number.isFinite(u)?u:M,q={...r??{},maxIterations:d};await this.updateOptimizationProgress(c,M,{epoch:A,exampleIndex:x,playbookBullets:this.playbook.stats.bulletCount},"ACE",{epochs:p,totalRounds:d},N,{playbookBullets:this.playbook.stats.bulletCount},void 0,q),this.stats.convergenceInfo.finalImprovement=Math.max(this.stats.convergenceInfo.finalImprovement,M)}}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:Yt(this.playbook),feedback:[...this.generatorHistory],history:[...this.deltaHistory]},f=new qr({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:Yt(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)Aa(this.playbook,p.id,p.tag);if(a.length>0){let p=this.collectProtectedBulletIds(a),d=xa(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)),ya(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(),"",jr(t)].filter(r=>r.trim().length>0).join(`
589
599
 
590
- `)}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 y=r.metadata;y&&typeof y=="object"&&(h.metadata={...y}),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:qr(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:qr(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=ye().input("question",ye.string("Original task input serialized as JSON")).input("generator_answer",ye.string("Generator output serialized as JSON")).input("generator_reasoning",ye.string("Generator reasoning trace").optional()).input("playbook",ye.string("Current context playbook rendered as markdown")).input("expected_answer",ye.string("Expected output when ground truth is available").optional()).input("feedback",ye.string("External feedback or reward signal").optional()).input("previous_reflection",ye.string("Most recent reflection JSON when running multi-round refinement").optional()).output("reasoning",ye.string("Step-by-step analysis of generator performance")).output("errorIdentification",ye.string("Specific mistakes detected")).output("rootCauseAnalysis",ye.string("Underlying cause of the error")).output("correctApproach",ye.string("What the generator should do differently")).output("keyInsight",ye.string("Reusable insight to remember")).output("bulletTags",ye.json("Array of {id, tag} entries referencing playbook bullets")).build();this.reflectorProgram=Ze(e)}return this.reflectorProgram}getOrCreateCuratorProgram(){if(!this.curatorProgram){let e=ye().input("playbook",ye.string("Current playbook serialized as JSON")).input("reflection",ye.string("Latest reflection output serialized as JSON")).input("question_context",ye.string("Original task input serialized as JSON")).input("token_budget",ye.number("Approximate token budget for curator response").optional()).output("reasoning",ye.string("Justification for the proposed updates")).output("operations",ye.json("List of operations with type/section/content fields")).build();this.curatorProgram=Ze(e)}return this.curatorProgram}};var Vn=class extends st{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=om([...t],this.maxExamples),c=this.traces.length,p=e.getId();for(let d=0;d<u.length;d+=this.batchSize){d>0&&(l.modelConfig.temperature=.7+.001*d);let m=u.slice(d,d+this.batchSize);for(let g of m){if(!g||typeof g!="object")continue;let f=t.filter(x=>x!==g);e.setDemos([{traces:f,programId:p}]);let h=this.getTeacherOrStudentAI();this.stats.totalCalls++;let y;try{let x={...l,maxRetries:1};y=await e.forward(h,g,x),this.costMonitoring&&(this.stats.estimatedTokenUsage+=JSON.stringify(g).length/4+JSON.stringify(y).length/4),await r({prediction:y,example:g})>=.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"}`),y={}}if(this.traces.length>=a)return}}if(this.earlyStoppingPatience>0){let m=this.traces.length-c;if(!this.stats.earlyStopping)this.stats.earlyStopping={bestScoreRound:m>0?n:0,patienceExhausted:!1,reason:"No improvement detected"};else if(m>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=rm(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 rm(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 om=(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 As=class extends st{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(T,M)=>{try{i.setAllNodeInstructions?.(T);let E=await i.forward(this.studentAI,M,{sampleCount:this.sampleCount});return this.stats.totalCalls+=1,await n({prediction:E,example:M})||{}}catch{return{}}},g=async(T,M)=>{let E=[];for(let N of M)E.push(await m(T,N));return gs(E)},f={};for(let T of a)f[T.name]=await this.getBaseInstruction(T.program);let h=[{cfg:{...f},parent:void 0,scores:await g(f,c)}],y=T=>{let M=r?.paretoMetricKey,E=r?.paretoScalarize;if(typeof E=="function")return E(T);if(M)return Number.isFinite(T[M])?T[M]:0;let N=Object.values(T);return N.length?N.reduce((P,_)=>P+_,0)/N.length:0},x=[],b=async(T,M)=>{let E=[];for(let N of M){let P=await m(T,N);E.push(y(P))}return E};x.push(await b(f,c));let R=kt(h.map((T,M)=>({idx:M,scores:T.scores})),this.tieEpsilon).map(T=>T.idx),A=0,w=new Set,v=r?.maxMetricCalls;if(!Number.isFinite(v)||v<=0)throw new Error("AxGEPA-Flow: options.maxMetricCalls must be set to a positive integer");let F=Math.floor(v);for(let T=0;T<this.numTrials&&!(F!==void 0&&this.stats.totalCalls>=Math.max(1,Math.floor(F)));T++){let M=x[0]?.length??0,E=[];for(let C=0;C<M;C++){let S=Number.NEGATIVE_INFINITY,k=new Set;for(let I=0;I<x.length;I++){let B=x[I][C];B>S+this.tieEpsilon?(S=B,k.clear(),k.add(I)):Math.abs(B-S)<=this.tieEpsilon&&k.add(I)}E.push(k)}let N=x.map(C=>Xt(C));if(this.mergeMax>0&&this.mergesDue>0&&this.lastIterFoundNewProgram){let C=Br(E,N),S=new Set;for(let q of C)for(let H of q)S.add(H);let k=Array.from(S),I=q=>{let H=[],j=q;for(;j!==void 0;)H.push(j),j=h[j]?.parent;return H},B=q=>q.length?q[Math.floor(this.rand()*q.length)]:void 0,K;for(let q=0;q<10&&!K&&!(k.length<2);q++){let H=B(k),j=B(k);if(H===j)continue;j<H&&([H,j]=[j,H]);let V=new Set(I(H)),ne=new Set(I(j));if(V.has(j)||ne.has(H))continue;let le=[...V].filter(me=>ne.has(me));if(le.length===0)continue;let ce=[];for(let me of le){let Oe=h[me].cfg,et=h[H].cfg,z=h[j].cfg,Q=!1,Me=new Set([...Object.keys(Oe),...Object.keys(et),...Object.keys(z)]);for(let Le of Me){let de=Oe[Le],_e=et[Le],te=z[Le];if(_e===de&&te!==_e||te===de&&_e!==te){Q=!0;break}}Q&&ce.push(me)}if(ce.length===0)continue;let ge=ce.map(me=>Math.max(1e-9,N[me])),Ae=this.rand()*ge.reduce((me,Oe)=>me+Oe,0),Se=ce[ce.length-1];for(let me=0;me<ce.length;me++){if(Ae<ge[me]){Se=ce[me];break}Ae-=ge[me]}let Fe=N[Se],Ee=N[H],Z=N[j];if(Fe>Math.min(Ee,Z))continue;let J=`${H}|${j}|${Se}`;if(this.mergeAttemptKeys.has(J))continue;this.mergeAttemptKeys.add(J);let pe=`${H}|${j}|${Se}`;w.has(pe)||(K={i:H,j,a:Se})}if(this.lastIterFoundNewProgram=!1,K){let{i:q,j:H,a:j}=K,{cfg:V,descSig:ne}=this.systemAwareMergeWithSig(h,q,H,(te,ke)=>N[te]>=N[ke]?te:ke),le=`${Math.min(q,H)}|${Math.max(q,H)}|${ne}`;if(this.mergeCompositionKeys.has(le))continue;this.mergeCompositionKeys.add(le);let ce=x[q],ge=x[H],Ae=Array.from({length:ce.length},(te,ke)=>ke),Se=Ae.filter(te=>(ce[te]??0)>(ge[te]??0)),Fe=Ae.filter(te=>(ge[te]??0)>(ce[te]??0)),Ee=Ae.filter(te=>!(Se.includes(te)||Fe.includes(te))),Z=5,J=Math.ceil(Z/3),pe=(te,ke)=>{if(ke<=0||te.length===0)return[];if(te.length<=ke)return[...te];let Te=[],De=new Set;for(;Te.length<ke;){let qe=Math.floor(this.rand()*te.length);De.has(qe)||(De.add(qe),Te.push(te[qe]))}return Te},me=[];me.push(...pe(Se,Math.min(J,Se.length))),me.push(...pe(Fe,Math.min(J,Fe.length)));let Oe=Z-me.length;me.push(...pe(Ee,Math.max(0,Oe)));let et=Z-me.length;if(et>0){let te=Ae.filter(ke=>!me.includes(ke));me.push(...pe(te,Math.min(et,te.length)))}let z=me.slice(0,Math.min(Z,Ae.length)),Q=z.map(te=>c[te]),Le=(await b(V,Q)).reduce((te,ke)=>te+ke,0),de=z.reduce((te,ke)=>te+(ce[ke]??0),0),_e=z.reduce((te,ke)=>te+(ge[ke]??0),0);if(Le>=Math.max(de,_e)+this.tieEpsilon){let te=await g(V,c);h.push({cfg:V,parent:j,scores:te}),x.push(await b(V,c));let ke=R.length,Te=ft(R.map(qe=>h[qe].scores))??0;R=kt(h.map((qe,ze)=>({idx:ze,scores:qe.scores})),this.tieEpsilon).map(qe=>qe.idx);let De=ft(R.map(qe=>h[qe].scores))??0;(R.length>ke||De>Te+1e-6)&&(A=0),this.mergesDue-=1,this.totalMergesTested+=1,w.add(`${Math.min(q,H)}|${Math.max(q,H)}|${j}`)}continue}}let P=jr(E,N,()=>this.rand());this.lastIterFoundNewProgram=!1;let _=this.minibatch?this.nextMinibatchIndices(p.length,T).map(C=>p[C]):p;if(r?.skipPerfectScore??!0){let C=Number(r?.perfectScore??1),S=await b(h[P].cfg,_);if(S.length>0&&S.every(k=>k>=C))continue}let G=!1,$={...h[P].cfg},W="reflective_mutation",se=T%a.length,Y=a[se],ee,oe;if(G&&this.mergesUsed<this.mergeMax){let C=(P+1)%h.length,S=q=>{let H=[],j=q;for(;j!==void 0;)H.push(j),j=h[j]?.parent;return H},k=S(P),I=S(C),B=k.find(q=>I.includes(q)),K=!0;if(B||(K=!1),(I.includes(P)||k.includes(C))&&(K=!1),K){let q=h[B].cfg,H=h[P].cfg,j=h[C].cfg,V=!1,ne=new Set([...Object.keys(q),...Object.keys(H),...Object.keys(j)]);for(let le of ne){let ce=q[le],ge=H[le],Ae=j[le];if(ge===ce&&Ae!==ge||Ae===ce&&ge!==Ae){V=!0;break}}V||(K=!1)}if(K){let q=Math.min(P,C),H=Math.max(P,C),j=`${q}|${H}|${B}`;if(!w.has(j)){let V=y(h[B].scores),ne=y(h[P].scores),le=y(h[C].scores);V<=Math.min(ne,le)&&($=this.systemAwareMerge(h,P,C,(ce,ge)=>{let Ae=y(h[ce].scores),Se=y(h[ge].scores);return Ae>=Se?ce:ge}),W="system_merge",this.mergesUsed+=1,w.add(j))}}else{let q=h[P].cfg[Y.name],H=r?.gepaAdapter,j;if(H)try{let V=await H.evaluate(_,{...h[P].cfg},!0);ee=Array.isArray(V?.scores)?V.scores.reduce((ge,Ae)=>ge+(Number(Ae)||0),0):void 0;let ne=H.make_reflective_dataset({...h[P].cfg},V,[Y.name]),ce=(await H.propose_new_texts?.({...h[P].cfg},ne,[Y.name]))?.[Y.name];typeof ce=="string"&&ce.length>0&&(j=ce)}catch{}if(j||(j=await this.reflectModuleInstruction(Y.name,q,i,a,{...h[P].cfg},_,async({prediction:V,example:ne})=>{let le=await n({prediction:V,example:ne}),ce=Object.values(le||{});return ce.length?ce.reduce((ge,Ae)=>ge+Ae,0)/ce.length:0},r)),$[Y.name]=j,H&&ee!==void 0)try{let V=await H.evaluate(_,$,!1);oe=Array.isArray(V?.scores)?V.scores.reduce((ne,le)=>ne+(Number(le)||0),0):void 0}catch{}}}else{let C=h[P].cfg[Y.name],S=r?.gepaAdapter,k;if(S)try{let I=await S.evaluate(_,{...h[P].cfg},!0);ee=Array.isArray(I?.scores)?I.scores.reduce((H,j)=>H+(Number(j)||0),0):void 0;let B=S.make_reflective_dataset({...h[P].cfg},I,[Y.name]),q=(await S.propose_new_texts?.({...h[P].cfg},B,[Y.name]))?.[Y.name];typeof q=="string"&&q.length>0&&(k=q)}catch{}if(k||(k=await this.reflectModuleInstruction(Y.name,C,i,a,{...h[P].cfg},_,async({prediction:I,example:B})=>{let K=await n({prediction:I,example:B}),q=Object.values(K||{});return q.length?q.reduce((H,j)=>H+j,0)/q.length:0},r)),$[Y.name]=k,S&&ee!==void 0)try{let I=await S.evaluate(_,$,!1);oe=Array.isArray(I?.scores)?I.scores.reduce((B,K)=>B+(Number(K)||0),0):void 0}catch{}}let be=await b(h[P].cfg,_),Ce=await b($,_),X=be.reduce((C,S)=>C+S,0),Ie=Ce.reduce((C,S)=>C+S,0);if(this.currentRound=T+1,await this.updateOptimizationProgress(this.currentRound,Ie,{modules:a.length,mutatedModule:Y.name,totalRounds:this.numTrials},"GEPA-Flow",{strategy:W,paretoSetSize:c.length},Ie,{idx:P},{...r??{},maxIterations:this.numTrials}),!(Ie>X+this.tieEpsilon&&(ee===void 0||oe===void 0||oe>ee+this.tieEpsilon))){if(++A>=this.earlyStoppingTrials)break;continue}let ue=await g($,c);h.push({cfg:$,parent:P,scores:ue}),x.push(await b($,c));let Pe=R.length,ae=ft(R.map(C=>h[C].scores))??0;R=kt(h.map((C,S)=>({idx:S,scores:C.scores})),this.tieEpsilon).map(C=>C.idx);let ve=ft(R.map(C=>h[C].scores))??0;if(R.length>Pe||ve>ae+1e-6)A=0;else if(A++,A>=this.earlyStoppingTrials)break;this.lastIterFoundNewProgram=!0,this.mergeMax>0&&this.totalMergesTested<this.mergeMax&&(this.mergesDue+=1)}let O=kt(h.map((T,M)=>({idx:M,scores:T.scores})),this.tieEpsilon),D=O.length>0?Math.max(...O.map(T=>y(T.scores))):0,U=ft(O.map(T=>T.scores));this.stats.convergenceInfo.converged=!0;let L=this.getMergedCustomLabels(r);return this.recordParetoMetrics(O.length,h.length,"GEPA-Flow",U,L),{demos:[],stats:this.stats,bestScore:D,paretoFront:O.map(T=>({demos:[],scores:T.scores,configuration:{candidate:T.idx},dominatedSolutions:T.dominated})),paretoFrontSize:O.length,hypervolume:U,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?Xt(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 y of i)try{o[e]=t,n.setAllNodeInstructions?.(o);let x=await n.forward(this.studentAI,y,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let b=await a({prediction:x,example:y});c.push({input:y,prediction:x,score:typeof b=="number"?b:0})}catch{c.push({input:y,prediction:{},score:0})}let p=l?.overrideTeacherAI??this.teacherAI??this.studentAI,d=Ze('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 y of c){let x=g({prediction:y.prediction,example:y.input});x&&(Array.isArray(x)?m.push(...x):m.push(x))}let f="";try{f=(await d.forward(p,{moduleName:e,minibatch:c,evalFeedback:m}))?.feedbackSummary?.trim()||""}catch{}let h=Ze('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 x=(await h.forward(p,{moduleName:e,currentInstruction:t,feedbackSummary:f,minibatch:c}))?.newInstruction?.trim();if(x&&x.length>16)return x}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 y=[],x=h;for(;x!==void 0;)y.push(x),x=e[x]?.parent;return y},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 y=c[h],x=p[h],b=d[h];if(x===y&&b!==x)m[h]=b,g.push("j");else if(b===y&&x!==b)m[h]=x,g.push("i");else if(x!==b&&x!==y&&b!==y){let R=r(t,n);m[h]=R===t?x:b,g.push(R===t?"i":"j")}else m[h]=x??b??y,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=[],y=f;for(;y!==void 0;)h.push(y),y=e[y]?.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],y=p[f],x=d[f];if(y===h&&x!==y)m[f]=x;else if(x===h&&y!==x)m[f]=y;else if(y!==x&&y!==h&&x!==h){let b=r(t,n);m[f]=b===t?y:x}else m[f]=y??x??h}return m}};var ys=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 bs=class extends st{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 ys(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=`
600
+ `)}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 A=r.metadata;A&&typeof A=="object"&&(h.metadata={...A}),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:jr(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:jr(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=he().input("question",he.string("Original task input serialized as JSON")).input("generator_answer",he.string("Generator output serialized as JSON")).input("generator_reasoning",he.string("Generator reasoning trace").optional()).input("playbook",he.string("Current context playbook rendered as markdown")).input("expected_answer",he.string("Expected output when ground truth is available").optional()).input("feedback",he.string("External feedback or reward signal").optional()).input("previous_reflection",he.string("Most recent reflection JSON when running multi-round refinement").optional()).output("reasoning",he.string("Step-by-step analysis of generator performance")).output("errorIdentification",he.string("Specific mistakes detected")).output("rootCauseAnalysis",he.string("Underlying cause of the error")).output("correctApproach",he.string("What the generator should do differently")).output("keyInsight",he.string("Reusable insight to remember")).output("bulletTags",he.json("Array of {id, tag} entries referencing playbook bullets")).build();this.reflectorProgram=je(e)}return this.reflectorProgram}getOrCreateCuratorProgram(){if(!this.curatorProgram){let e=he().input("playbook",he.string("Current playbook serialized as JSON")).input("reflection",he.string("Latest reflection output serialized as JSON")).input("question_context",he.string("Original task input serialized as JSON")).input("token_budget",he.number("Approximate token budget for curator response").optional()).output("reasoning",he.string("Justification for the proposed updates")).output("operations",he.json("List of operations with type/section/content fields")).build();this.curatorProgram=je(e)}return this.curatorProgram}};var qn=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=Dm([...t],this.maxExamples),c=this.traces.length,p=e.getId();for(let d=0;d<u.length;d+=this.batchSize){d>0&&(l.modelConfig.temperature=.7+.001*d);let m=u.slice(d,d+this.batchSize);for(let g of m){if(!g||typeof g!="object")continue;let f=t.filter(x=>x!==g);e.setDemos([{traces:f,programId:p}]);let h=this.getTeacherOrStudentAI();this.stats.totalCalls++;let A;try{let x={...l,maxRetries:1};A=await e.forward(h,g,x),this.costMonitoring&&(this.stats.estimatedTokenUsage+=JSON.stringify(g).length/4+JSON.stringify(A).length/4),await r({prediction:A,example:g})>=.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"}`),A={}}if(this.traces.length>=a)return}}if(this.earlyStoppingPatience>0){let m=this.traces.length-c;if(!this.stats.earlyStopping)this.stats.earlyStopping={bestScoreRound:m>0?n:0,patienceExhausted:!1,reason:"No improvement detected"};else if(m>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=Lm(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 Lm(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 Dm=(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 Is=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(w,R)=>{try{i.setAllNodeInstructions?.(w);let E=await i.forward(this.studentAI,R,{sampleCount:this.sampleCount});return this.stats.totalCalls+=1,await n({prediction:E,example:R})||{}}catch{return{}}},g=async(w,R)=>{let E=[];for(let _ of R)E.push(await m(w,_));return xs(E)},f={};for(let w of a)f[w.name]=await this.getBaseInstruction(w.program);let h=[{cfg:{...f},parent:void 0,scores:await g(f,c)}],A=w=>{let R=r?.paretoMetricKey,E=r?.paretoScalarize;if(typeof E=="function")return E(w);if(R)return Number.isFinite(w[R])?w[R]:0;let _=Object.values(w);return _.length?_.reduce((M,N)=>M+N,0)/_.length:0},x=[],b=async(w,R)=>{let E=[];for(let _ of R){let M=await m(w,_);E.push(A(M))}return E};x.push(await b(f,c));let C=It(h.map((w,R)=>({idx:R,scores:w.scores})),this.tieEpsilon).map(w=>w.idx),I=0,v=new Set,O=r?.maxMetricCalls;if(!Number.isFinite(O)||O<=0)throw new Error("AxGEPA-Flow: options.maxMetricCalls must be set to a positive integer");let k=Math.floor(O);for(let w=0;w<this.numTrials&&!(k!==void 0&&this.stats.totalCalls>=Math.max(1,Math.floor(k)));w++){let R=x[0]?.length??0,E=[];for(let T=0;T<R;T++){let F=Number.NEGATIVE_INFINITY,P=new Set;for(let y=0;y<x.length;y++){let D=x[y][T];D>F+this.tieEpsilon?(F=D,P.clear(),P.add(y)):Math.abs(D-F)<=this.tieEpsilon&&P.add(y)}E.push(P)}let _=x.map(T=>Jt(T));if(this.mergeMax>0&&this.mergesDue>0&&this.lastIterFoundNewProgram){let T=Ur(E,_),F=new Set;for(let j of T)for(let H of j)F.add(H);let P=Array.from(F),y=j=>{let H=[],z=j;for(;z!==void 0;)H.push(z),z=h[z]?.parent;return H},D=j=>j.length?j[Math.floor(this.rand()*j.length)]:void 0,B;for(let j=0;j<10&&!B&&!(P.length<2);j++){let H=D(P),z=D(P);if(H===z)continue;z<H&&([H,z]=[z,H]);let K=new Set(y(H)),J=new Set(y(z));if(K.has(z)||J.has(H))continue;let oe=[...K].filter(ae=>J.has(ae));if(oe.length===0)continue;let se=[];for(let ae of oe){let we=h[ae].cfg,We=h[H].cfg,Ye=h[z].cfg,kt=!1,Ot=new Set([...Object.keys(we),...Object.keys(We),...Object.keys(Ye)]);for(let Ct of Ot){let Mt=we[Ct],Gt=We[Ct],me=Ye[Ct];if(Gt===Mt&&me!==Gt||me===Mt&&Gt!==me){kt=!0;break}}kt&&se.push(ae)}if(se.length===0)continue;let ue=se.map(ae=>Math.max(1e-9,_[ae])),de=this.rand()*ue.reduce((ae,we)=>ae+we,0),Ae=se[se.length-1];for(let ae=0;ae<se.length;ae++){if(de<ue[ae]){Ae=se[ae];break}de-=ue[ae]}let Ce=_[Ae],Oe=_[H],X=_[z];if(Ce>Math.min(Oe,X))continue;let ee=`${H}|${z}|${Ae}`;if(this.mergeAttemptKeys.has(ee))continue;this.mergeAttemptKeys.add(ee);let ie=`${H}|${z}|${Ae}`;v.has(ie)||(B={i:H,j:z,a:Ae})}if(this.lastIterFoundNewProgram=!1,B){let{i:j,j:H,a:z}=B,{cfg:K,descSig:J}=this.systemAwareMergeWithSig(h,j,H,(me,Ee)=>_[me]>=_[Ee]?me:Ee),oe=`${Math.min(j,H)}|${Math.max(j,H)}|${J}`;if(this.mergeCompositionKeys.has(oe))continue;this.mergeCompositionKeys.add(oe);let se=x[j],ue=x[H],de=Array.from({length:se.length},(me,Ee)=>Ee),Ae=de.filter(me=>(se[me]??0)>(ue[me]??0)),Ce=de.filter(me=>(ue[me]??0)>(se[me]??0)),Oe=de.filter(me=>!(Ae.includes(me)||Ce.includes(me))),X=5,ee=Math.ceil(X/3),ie=(me,Ee)=>{if(Ee<=0||me.length===0)return[];if(me.length<=Ee)return[...me];let ht=[],Qe=new Set;for(;ht.length<Ee;){let Xe=Math.floor(this.rand()*me.length);Qe.has(Xe)||(Qe.add(Xe),ht.push(me[Xe]))}return ht},ae=[];ae.push(...ie(Ae,Math.min(ee,Ae.length))),ae.push(...ie(Ce,Math.min(ee,Ce.length)));let we=X-ae.length;ae.push(...ie(Oe,Math.max(0,we)));let We=X-ae.length;if(We>0){let me=de.filter(Ee=>!ae.includes(Ee));ae.push(...ie(me,Math.min(We,me.length)))}let Ye=ae.slice(0,Math.min(X,de.length)),kt=Ye.map(me=>c[me]),Ct=(await b(K,kt)).reduce((me,Ee)=>me+Ee,0),Mt=Ye.reduce((me,Ee)=>me+(se[Ee]??0),0),Gt=Ye.reduce((me,Ee)=>me+(ue[Ee]??0),0);if(Ct>=Math.max(Mt,Gt)+this.tieEpsilon){let me=await g(K,c);h.push({cfg:K,parent:z,scores:me}),x.push(await b(K,c));let Ee=C.length,ht=lt(C.map(Xe=>h[Xe].scores))??0;C=It(h.map((Xe,Qr)=>({idx:Qr,scores:Xe.scores})),this.tieEpsilon).map(Xe=>Xe.idx);let Qe=lt(C.map(Xe=>h[Xe].scores))??0;(C.length>Ee||Qe>ht+1e-6)&&(I=0),this.mergesDue-=1,this.totalMergesTested+=1,v.add(`${Math.min(j,H)}|${Math.max(j,H)}|${z}`)}continue}}let M=Br(E,_,()=>this.rand());this.lastIterFoundNewProgram=!1;let N=this.minibatch?this.nextMinibatchIndices(p.length,w).map(T=>p[T]):p;if(r?.skipPerfectScore??!0){let T=Number(r?.perfectScore??1),F=await b(h[M].cfg,N);if(F.length>0&&F.every(P=>P>=T))continue}let q=!1,U={...h[M].cfg},W="reflective_mutation",Y=w%a.length,Q=a[Y],V,te;if(q&&this.mergesUsed<this.mergeMax){let T=(M+1)%h.length,F=j=>{let H=[],z=j;for(;z!==void 0;)H.push(z),z=h[z]?.parent;return H},P=F(M),y=F(T),D=P.find(j=>y.includes(j)),B=!0;if(D||(B=!1),(y.includes(M)||P.includes(T))&&(B=!1),B){let j=h[D].cfg,H=h[M].cfg,z=h[T].cfg,K=!1,J=new Set([...Object.keys(j),...Object.keys(H),...Object.keys(z)]);for(let oe of J){let se=j[oe],ue=H[oe],de=z[oe];if(ue===se&&de!==ue||de===se&&ue!==de){K=!0;break}}K||(B=!1)}if(B){let j=Math.min(M,T),H=Math.max(M,T),z=`${j}|${H}|${D}`;if(!v.has(z)){let K=A(h[D].scores),J=A(h[M].scores),oe=A(h[T].scores);K<=Math.min(J,oe)&&(U=this.systemAwareMerge(h,M,T,(se,ue)=>{let de=A(h[se].scores),Ae=A(h[ue].scores);return de>=Ae?se:ue}),W="system_merge",this.mergesUsed+=1,v.add(z))}}else{let j=h[M].cfg[Q.name],H=r?.gepaAdapter,z;if(H)try{let K=await H.evaluate(N,{...h[M].cfg},!0);V=Array.isArray(K?.scores)?K.scores.reduce((ue,de)=>ue+(Number(de)||0),0):void 0;let J=H.make_reflective_dataset({...h[M].cfg},K,[Q.name]),se=(await H.propose_new_texts?.({...h[M].cfg},J,[Q.name]))?.[Q.name];typeof se=="string"&&se.length>0&&(z=se)}catch{}if(z||(z=await this.reflectModuleInstruction(Q.name,j,i,a,{...h[M].cfg},N,async({prediction:K,example:J})=>{let oe=await n({prediction:K,example:J}),se=Object.values(oe||{});return se.length?se.reduce((ue,de)=>ue+de,0)/se.length:0},r)),U[Q.name]=z,H&&V!==void 0)try{let K=await H.evaluate(N,U,!1);te=Array.isArray(K?.scores)?K.scores.reduce((J,oe)=>J+(Number(oe)||0),0):void 0}catch{}}}else{let T=h[M].cfg[Q.name],F=r?.gepaAdapter,P;if(F)try{let y=await F.evaluate(N,{...h[M].cfg},!0);V=Array.isArray(y?.scores)?y.scores.reduce((H,z)=>H+(Number(z)||0),0):void 0;let D=F.make_reflective_dataset({...h[M].cfg},y,[Q.name]),j=(await F.propose_new_texts?.({...h[M].cfg},D,[Q.name]))?.[Q.name];typeof j=="string"&&j.length>0&&(P=j)}catch{}if(P||(P=await this.reflectModuleInstruction(Q.name,T,i,a,{...h[M].cfg},N,async({prediction:y,example:D})=>{let B=await n({prediction:y,example:D}),j=Object.values(B||{});return j.length?j.reduce((H,z)=>H+z,0)/j.length:0},r)),U[Q.name]=P,F&&V!==void 0)try{let y=await F.evaluate(N,U,!1);te=Array.isArray(y?.scores)?y.scores.reduce((D,B)=>D+(Number(B)||0),0):void 0}catch{}}let ye=await b(h[M].cfg,N),Te=await b(U,N),Z=ye.reduce((T,F)=>T+F,0),fe=Te.reduce((T,F)=>T+F,0);if(this.currentRound=w+1,await this.updateOptimizationProgress(this.currentRound,fe,{modules:a.length,mutatedModule:Q.name,totalRounds:this.numTrials},"GEPA-Flow",{strategy:W,paretoSetSize:c.length},fe,{idx:M},{...r??{},maxIterations:this.numTrials}),!(fe>Z+this.tieEpsilon&&(V===void 0||te===void 0||te>V+this.tieEpsilon))){if(++I>=this.earlyStoppingTrials)break;continue}let re=await g(U,c);h.push({cfg:U,parent:M,scores:re}),x.push(await b(U,c));let xe=C.length,le=lt(C.map(T=>h[T].scores))??0;C=It(h.map((T,F)=>({idx:F,scores:T.scores})),this.tieEpsilon).map(T=>T.idx);let Ie=lt(C.map(T=>h[T].scores))??0;if(C.length>xe||Ie>le+1e-6)I=0;else if(I++,I>=this.earlyStoppingTrials)break;this.lastIterFoundNewProgram=!0,this.mergeMax>0&&this.totalMergesTested<this.mergeMax&&(this.mergesDue+=1)}let S=It(h.map((w,R)=>({idx:R,scores:w.scores})),this.tieEpsilon),$=S.length>0?Math.max(...S.map(w=>A(w.scores))):0,G=lt(S.map(w=>w.scores));this.stats.convergenceInfo.converged=!0;let L=this.getMergedCustomLabels(r);return this.recordParetoMetrics(S.length,h.length,"GEPA-Flow",G,L),{demos:[],stats:this.stats,bestScore:$,paretoFront:S.map(w=>({demos:[],scores:w.scores,configuration:{candidate:w.idx},dominatedSolutions:w.dominated})),paretoFrontSize:S.length,hypervolume:G,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?Jt(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 A of i)try{o[e]=t,n.setAllNodeInstructions?.(o);let x=await n.forward(this.studentAI,A,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let b=await a({prediction:x,example:A});c.push({input:A,prediction:x,score:typeof b=="number"?b:0})}catch{c.push({input:A,prediction:{},score:0})}let p=l?.overrideTeacherAI??this.teacherAI??this.studentAI,d=je('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 A of c){let x=g({prediction:A.prediction,example:A.input});x&&(Array.isArray(x)?m.push(...x):m.push(x))}let f="";try{f=(await d.forward(p,{moduleName:e,minibatch:c,evalFeedback:m}))?.feedbackSummary?.trim()||""}catch{}let h=je('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 x=(await h.forward(p,{moduleName:e,currentInstruction:t,feedbackSummary:f,minibatch:c}))?.newInstruction?.trim();if(x&&x.length>16)return x}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 A=[],x=h;for(;x!==void 0;)A.push(x),x=e[x]?.parent;return A},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 A=c[h],x=p[h],b=d[h];if(x===A&&b!==x)m[h]=b,g.push("j");else if(b===A&&x!==b)m[h]=x,g.push("i");else if(x!==b&&x!==A&&b!==A){let C=r(t,n);m[h]=C===t?x:b,g.push(C===t?"i":"j")}else m[h]=x??b??A,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=[],A=f;for(;A!==void 0;)h.push(A),A=e[A]?.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],A=p[f],x=d[f];if(A===h&&x!==A)m[f]=x;else if(x===h&&A!==x)m[f]=A;else if(A!==x&&A!==h&&x!==h){let b=r(t,n);m[f]=b===t?A:x}else m[f]=A??x??h}return m}};var Cs=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 Ts=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 Cs(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=`
591
601
  Analyze this language model program and provide a concise summary of its purpose and structure.
592
602
 
593
603
  Program Signature: ${e.getSignature()}
@@ -627,12 +637,12 @@ Requirements:
627
637
  5. Keep it concise but comprehensive
628
638
 
629
639
  Generate a single, well-crafted instruction:
630
- Instruction:`;try{let m=(await Ze('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){if(e.setInstruction&&e.setInstruction(t.instruction),e.setDemos){let o=[...n.slice(0,t.bootstrappedDemos)];if(t.labeledExamples>0&&e.getId){let i=e.getId();o.push({traces:r.slice(0,t.labeledExamples),programId:i})}o.length>0&&e.setDemos(o)}}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);let o=[...n.slice(0,t.bootstrappedDemos)];if(t.labeledExamples>0){let i=e.getId();o.push({traces:r.slice(0,t.labeledExamples),programId:i})}o.length>0&&e.setDemos(o)}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 w=0;w<this.numTrials;w++)try{let v=await this.pythonClient.suggestParameters(a),F=v.params.temperature,O=v.params.bootstrappedDemos,D=v.params.instruction,U=v.params.labeledExamples,L=this.optimizeTopP?v.params.topP:void 0;if(F===void 0)throw new Error(`Missing temperature parameter in suggestion: ${JSON.stringify(v)}`);if(O===void 0)throw new Error(`Missing bootstrappedDemos parameter in suggestion: ${JSON.stringify(v)}`);if(D===void 0)throw new Error(`Missing instruction parameter in suggestion: ${JSON.stringify(v)}`);if(U===void 0)throw new Error(`Missing labeledExamples parameter in suggestion: ${JSON.stringify(v)}`);let T=e.clone();T.setInstruction(D);let M=T.getId();T.setDemos([{traces:this.selectLabeledExamples(t).slice(0,U),programId:M}]);let N=!this.minibatch||this.minibatchFullEvalSteps>0&&w%this.minibatchFullEvalSteps===this.minibatchFullEvalSteps-1?[...t]:(()=>{let G=Math.min(this.minibatchSize,t.length),$=new Set;for(;$.size<G;)$.add(Math.floor(Math.random()*t.length));return Array.from($).map(W=>t[W])})(),P=await this.evaluateConfiguration(T,n,{temperature:F,bootstrappedDemos:O,topP:L},N);m++,await this.pythonClient.evaluateTrial({study_name:a,trial_number:v.trial_number,value:P}),P>p+this.minImprovementThreshold?(p=P,d={temperature:F,bootstrappedDemos:O,...L!==void 0?{topP:L}:{},trialNumber:v.trial_number},g=0):g+=1,this.currentRound=w+1;let _={temperature:F,bootstrappedDemos:O,...L!==void 0?{topP:L}:{},trialNumber:v.trial_number};if(this.localScoreHistory.push(P),this.localConfigurationHistory.push(_),await this.updateOptimizationProgress(this.currentRound,P,_,"MiPRO (Python)",{sampler:"TPESampler"},p,d),this.onProgress?.({round:w+1,totalRounds:this.numTrials,currentScore:P,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={},y=[];try{let w=await this.pythonClient.getStudyResults(a);if(f=w.best_value||p,h=w.best_params||{},h&&Object.keys(h).length>0){let v=h.bootstrappedDemos||0;v>0&&(y=await this.bootstrapFewShotExamples(e,n,t.slice(0,Math.floor(t.length*.8))),y=y.slice(0,v))}}catch{}let x;try{let v=await Ze('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||{}});x={humanExplanation:v.humanExplanation??"",recommendations:v.recommendations??[],performanceAssessment:v.performanceAssessment??""}}catch{}await this.logOptimizationComplete("MiPRO (Python)",f,h,r,x);try{await this.pythonClient.deleteStudy(a)}catch{}this.stats.bestScore=f;let b=new $e(e.getSignature());h.instruction&&b.setInstruction(h.instruction);let R=h.temperature?{temperature:h.temperature}:void 0;b.setDemos(y,{modelConfig:R});let A=new St({bestScore:f,stats:this.stats,instruction:h.instruction,demos:y,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,y.length),{bestScore:f,demos:y,stats:this.stats,optimizedGen:b,optimizedProgram:A,finalConfiguration:{temperature:h.temperature,bootstrappedDemos:h.bootstrappedDemos||0,...h}}}generateOptimizationReport(e,t){console.log(`
640
+ Instruction:`;try{let m=(await je('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 qn({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){if(e.setInstruction&&e.setInstruction(t.instruction),e.setDemos){let o=[...n.slice(0,t.bootstrappedDemos)];if(t.labeledExamples>0&&e.getId){let i=e.getId();o.push({traces:r.slice(0,t.labeledExamples),programId:i})}o.length>0&&e.setDemos(o)}}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);let o=[...n.slice(0,t.bootstrappedDemos)];if(t.labeledExamples>0){let i=e.getId();o.push({traces:r.slice(0,t.labeledExamples),programId:i})}o.length>0&&e.setDemos(o)}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 v=0;v<this.numTrials;v++)try{let O=await this.pythonClient.suggestParameters(a),k=O.params.temperature,S=O.params.bootstrappedDemos,$=O.params.instruction,G=O.params.labeledExamples,L=this.optimizeTopP?O.params.topP:void 0;if(k===void 0)throw new Error(`Missing temperature parameter in suggestion: ${JSON.stringify(O)}`);if(S===void 0)throw new Error(`Missing bootstrappedDemos parameter in suggestion: ${JSON.stringify(O)}`);if($===void 0)throw new Error(`Missing instruction parameter in suggestion: ${JSON.stringify(O)}`);if(G===void 0)throw new Error(`Missing labeledExamples parameter in suggestion: ${JSON.stringify(O)}`);let w=e.clone();w.setInstruction($);let R=w.getId();w.setDemos([{traces:this.selectLabeledExamples(t).slice(0,G),programId:R}]);let _=!this.minibatch||this.minibatchFullEvalSteps>0&&v%this.minibatchFullEvalSteps===this.minibatchFullEvalSteps-1?[...t]:(()=>{let q=Math.min(this.minibatchSize,t.length),U=new Set;for(;U.size<q;)U.add(Math.floor(Math.random()*t.length));return Array.from(U).map(W=>t[W])})(),M=await this.evaluateConfiguration(w,n,{temperature:k,bootstrappedDemos:S,topP:L},_);m++,await this.pythonClient.evaluateTrial({study_name:a,trial_number:O.trial_number,value:M}),M>p+this.minImprovementThreshold?(p=M,d={temperature:k,bootstrappedDemos:S,...L!==void 0?{topP:L}:{},trialNumber:O.trial_number},g=0):g+=1,this.currentRound=v+1;let N={temperature:k,bootstrappedDemos:S,...L!==void 0?{topP:L}:{},trialNumber:O.trial_number};if(this.localScoreHistory.push(M),this.localConfigurationHistory.push(N),await this.updateOptimizationProgress(this.currentRound,M,N,"MiPRO (Python)",{sampler:"TPESampler"},p,d),this.onProgress?.({round:v+1,totalRounds:this.numTrials,currentScore:M,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={},A=[];try{let v=await this.pythonClient.getStudyResults(a);if(f=v.best_value||p,h=v.best_params||{},h&&Object.keys(h).length>0){let O=h.bootstrappedDemos||0;O>0&&(A=await this.bootstrapFewShotExamples(e,n,t.slice(0,Math.floor(t.length*.8))),A=A.slice(0,O))}}catch{}let x;try{let O=await je('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||{}});x={humanExplanation:O.humanExplanation??"",recommendations:O.recommendations??[],performanceAssessment:O.performanceAssessment??""}}catch{}await this.logOptimizationComplete("MiPRO (Python)",f,h,r,x);try{await this.pythonClient.deleteStudy(a)}catch{}this.stats.bestScore=f;let b=new ke(e.getSignature());h.instruction&&b.setInstruction(h.instruction);let C=h.temperature?{temperature:h.temperature}:void 0;b.setDemos(A,{modelConfig:C});let I=new bt({bestScore:f,stats:this.stats,instruction:h.instruction,demos:A,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,A.length),{bestScore:f,demos:A,stats:this.stats,optimizedGen:b,optimizedProgram:I,finalConfiguration:{temperature:h.temperature,bootstrappedDemos:h.bootstrappedDemos||0,...h}}}generateOptimizationReport(e,t){console.log(`
631
641
  \u{1F389} MiPRO Optimization Complete!
632
642
  `),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
633
643
  `),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
634
644
  `),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
635
- `),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 Jn=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 Yn(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 Qn=class{steps=[];parallelGroups=[];analyzer=new Jn;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 Yn(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 xc=s=>{console.log(s)},Xn=(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)},Zn=s=>s<1e3?`${s.toFixed(1)}ms`:s<6e4?`${(s/1e3).toFixed(2)}s`:`${(s/6e4).toFixed(2)}min`,Hr=(s=xc)=>{let e=new rt,t=e.gray(`${"\u2501".repeat(80)}
645
+ `),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 zn=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 Hn(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 zn;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 Hn(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 Pc=s=>{console.log(s)},Wn=(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)},Vn=s=>s<1e3?`${s.toFixed(1)}ms`:s<6e4?`${(s/1e3).toFixed(2)}s`:`${(s/6e4).toFixed(2)}min`,zr=(s=Pc)=>{let e=new Ke,t=e.gray(`${"\u2501".repeat(80)}
636
646
  `),n=e.gray(`${"\u2500".repeat(40)}
637
647
  `);return r=>{let o="";switch(r.name){case"FlowStart":o=`
638
648
  ${e.blueBright("\u{1F504} [ AXFLOW START ]")}
@@ -644,13 +654,13 @@ ${t}`,o+=`${e.white("Input Fields:")} ${e.cyan(r.inputFields.join(", "))}
644
654
  `,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+=`
645
655
  `,r.dependencies.length>0&&(o+=`${e.white("Dependencies:")} ${e.gray(r.dependencies.join(", "))}
646
656
  `),r.produces.length>0&&(o+=`${e.white("Produces:")} ${e.cyan(r.produces.join(", "))}
647
- `),o+=`${e.white("State:")} ${e.gray(Xn(r.state,!0))}
648
- `,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 ${Zn(r.executionTime)}`)}
657
+ `),o+=`${e.white("State:")} ${e.gray(Wn(r.state,!0))}
658
+ `,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 ${Vn(r.executionTime)}`)}
649
659
  `,r.newFields&&r.newFields.length>0&&(o+=`${e.white("New Fields:")} ${e.green(r.newFields.join(", "))}
650
660
  `),r.result&&r.nodeName&&(o+=`${e.white("Result:")} ${e.yellow(JSON.stringify(r.result,null,2))}
651
661
  `),o+=n;break}case"ParallelGroupStart":o=`${e.blueBright("\u2696\uFE0F [ PARALLEL GROUP START ]")} ${e.white(`Level ${r.groupLevel}`)}
652
662
  `,o+=`${e.white("Steps:")} ${e.yellow(r.stepsCount.toString())} ${e.gray(`(${r.stepTypes.join(", ")})`)}
653
- `,o+=n;break;case"ParallelGroupComplete":o=`${e.blueBright("\u2705 [ PARALLEL GROUP COMPLETE ]")} ${e.white(`Level ${r.groupLevel}`)}`,o+=` ${e.magenta(`in ${Zn(r.executionTime)}`)}
663
+ `,o+=n;break;case"ParallelGroupComplete":o=`${e.blueBright("\u2705 [ PARALLEL GROUP COMPLETE ]")} ${e.white(`Level ${r.groupLevel}`)}`,o+=` ${e.magenta(`in ${Vn(r.executionTime)}`)}
654
664
  `,o+=`${e.white("Steps Executed:")} ${e.yellow(r.stepsCount.toString())}
655
665
  `,o+=n;break;case"BranchEvaluation":o=`${e.yellow("\u{1F500} [ BRANCH EVALUATION ]")}
656
666
  `,o+=`${e.white("Branch Value:")} ${e.cyan(JSON.stringify(r.branchValue))}
@@ -658,16 +668,16 @@ ${t}`,o+=`${e.white("Input Fields:")} ${e.cyan(r.inputFields.join(", "))}
658
668
  `,r.hasMatchingBranch&&(o+=`${e.white("Branch Steps:")} ${e.yellow(r.branchStepsCount.toString())}
659
669
  `),o+=n;break;case"FlowComplete":o=`
660
670
  ${e.greenBright("\u2705 [ AXFLOW COMPLETE ]")}
661
- ${t}`,o+=`${e.white("Total Time:")} ${e.magenta(Zn(r.totalExecutionTime))}
671
+ ${t}`,o+=`${e.white("Total Time:")} ${e.magenta(Vn(r.totalExecutionTime))}
662
672
  `,o+=`${e.white("Steps Executed:")} ${e.yellow(r.stepsExecuted.toString())}
663
673
  `,o+=`${e.white("Output Fields:")} ${e.green(r.outputFields.join(", "))}
664
- `,o+=`${e.white("Final State:")} ${e.gray(Xn(r.finalState,!0))}
674
+ `,o+=`${e.white("Final State:")} ${e.gray(Wn(r.finalState,!0))}
665
675
  `,o+=t;break;case"FlowError":o=`
666
676
  ${e.redBright("\u274C [ AXFLOW ERROR ]")}
667
677
  ${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+=`
668
678
  `),o+=`${e.white("Error:")} ${e.red(r.error)}
669
- `,r.state&&(o+=`${e.white("State:")} ${e.gray(Xn(r.state,!0))}
670
- `),o+=t;break;default:o=e.gray(JSON.stringify(r,null,2))}s(o)}},Ac=(s=xc)=>{let e="=".repeat(80),t="-".repeat(40);return n=>{let r="";switch(n.name){case"FlowStart":r=`
679
+ `,r.state&&(o+=`${e.white("State:")} ${e.gray(Wn(r.state,!0))}
680
+ `),o+=t;break;default:o=e.gray(JSON.stringify(r,null,2))}s(o)}},Fc=(s=Pc)=>{let e="=".repeat(80),t="-".repeat(40);return n=>{let r="";switch(n.name){case"FlowStart":r=`
671
681
  [ AXFLOW START ]
672
682
  ${e}
673
683
  `,r+=`Input Fields: ${n.inputFields.join(", ")}
@@ -679,16 +689,16 @@ ${e}
679
689
  `;break;case"StepStart":r=`[ STEP ${n.stepIndex} START ] (${n.stepType})`,n.nodeName&&(r+=` Node: ${n.nodeName}`),r+=`
680
690
  `,n.dependencies.length>0&&(r+=`Dependencies: ${n.dependencies.join(", ")}
681
691
  `),n.produces.length>0&&(r+=`Produces: ${n.produces.join(", ")}
682
- `),r+=`State: ${Xn(n.state,!0)}
692
+ `),r+=`State: ${Wn(n.state,!0)}
683
693
  `,r+=`${t}
684
- `;break;case"StepComplete":r=`[ STEP ${n.stepIndex} COMPLETE ] (${n.stepType})`,n.nodeName&&(r+=` Node: ${n.nodeName}`),r+=` in ${Zn(n.executionTime)}
694
+ `;break;case"StepComplete":r=`[ STEP ${n.stepIndex} COMPLETE ] (${n.stepType})`,n.nodeName&&(r+=` Node: ${n.nodeName}`),r+=` in ${Vn(n.executionTime)}
685
695
  `,n.newFields&&n.newFields.length>0&&(r+=`New Fields: ${n.newFields.join(", ")}
686
696
  `),n.result&&n.nodeName&&(r+=`Result: ${JSON.stringify(n.result,null,2)}
687
697
  `),r+=`${t}
688
698
  `;break;case"ParallelGroupStart":r=`[ PARALLEL GROUP START ] Level ${n.groupLevel}
689
699
  `,r+=`Steps: ${n.stepsCount} (${n.stepTypes.join(", ")})
690
700
  `,r+=`${t}
691
- `;break;case"ParallelGroupComplete":r=`[ PARALLEL GROUP COMPLETE ] Level ${n.groupLevel} in ${Zn(n.executionTime)}
701
+ `;break;case"ParallelGroupComplete":r=`[ PARALLEL GROUP COMPLETE ] Level ${n.groupLevel} in ${Vn(n.executionTime)}
692
702
  `,r+=`Steps Executed: ${n.stepsCount}
693
703
  `,r+=`${t}
694
704
  `;break;case"BranchEvaluation":r=`[ BRANCH EVALUATION ]
@@ -699,61 +709,75 @@ ${e}
699
709
  `;break;case"FlowComplete":r=`
700
710
  [ AXFLOW COMPLETE ]
701
711
  ${e}
702
- `,r+=`Total Time: ${Zn(n.totalExecutionTime)}
712
+ `,r+=`Total Time: ${Vn(n.totalExecutionTime)}
703
713
  `,r+=`Steps Executed: ${n.stepsExecuted}
704
714
  `,r+=`Output Fields: ${n.outputFields.join(", ")}
705
- `,r+=`Final State: ${Xn(n.finalState,!0)}
715
+ `,r+=`Final State: ${Wn(n.finalState,!0)}
706
716
  `,r+=`${e}
707
717
  `;break;case"FlowError":r=`
708
718
  [ AXFLOW ERROR ]
709
719
  ${e}
710
720
  `,n.stepIndex!==void 0&&(r+=`Step: ${n.stepIndex}`,n.stepType&&(r+=` (${n.stepType})`),n.nodeName&&(r+=` Node: ${n.nodeName}`),r+=`
711
721
  `),r+=`Error: ${n.error}
712
- `,n.state&&(r+=`State: ${Xn(n.state,!0)}
722
+ `,n.state&&(r+=`State: ${Wn(n.state,!0)}
713
723
  `),r+=`${e}
714
- `;break;default:r=JSON.stringify(n,null,2)}s(r)}},yc=Hr(),bc=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 er=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}},Is=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 Kr=class s{static _ctorWarned=!1;nodes=new Map;flowDefinition=[];nodeGenerators=new Map;loopStack=[];stepLabels=new Map;branchContext=null;autoParallelConfig;executionPlanner=new Qn;program;flowName;nodeUsage=new Map;nodeTraces=new Map;flowLogger;timingLogger;defaultAIOptions;activeAbortControllers=new Set;_stopRequested=!1;toCamelCase(e){return e.replace(/_([a-z])/g,(t,n)=>n.toUpperCase())}stop(){this._stopRequested=!0;for(let e of this.activeAbortControllers)e.abort("Stopped by user")}extractInputValues(e){if(!Array.isArray(e))return e;let t=e.filter(n=>n.role==="user").pop();if(!t)throw new Error("No user message found in values array");return t.values}getCacheKey(e,t){if(!t)return;this.ensureProgram();let n=this.program.getSignature(),r=n.getInputFields().map(l=>l.name),o=this.extractInputValues(e),i=it("sha256");i.update(n.hash()??"");let a=l=>{let u=typeof l;if(i.update(`|${u}|`),l==null){i.update("null");return}if(u==="string"||u==="number"||u==="boolean"){i.update(String(l));return}if(Array.isArray(l)){i.update("[");for(let c of l)a(c);i.update("]");return}if(typeof l=="object"&&l!==null&&"mimeType"in l&&"data"in l){let c=l;i.update(c.mimeType??"");let p=it("sha256").update(c.data??"").digest("hex");i.update(p);return}if(typeof l=="object"){let c=l,p=Object.keys(c).sort();for(let d of p)i.update(`{${d}}`),a(c[d]);return}i.update(String(l))};for(let l of r)a(o?.[l]);return i.digest("hex")}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=n.mainOptions?.abortSignal;if(u?.aborted)throw new Ge("flow-between-steps",u.reason??"Flow aborted between steps");let c=this.getStepType(l,a),p=this.getStepMetadata(l,a),d=Object.keys(o);this.flowLogger&&this.flowLogger({name:"StepStart",timestamp:Date.now(),stepIndex:a,stepType:c,nodeName:p.nodeName,dependencies:p.dependencies,produces:p.produces,state:{...o}});let m=Date.now();this.timingLogger?.startTiming(`step-${a}`);try{o=await l(o,n),i++;let f=this.timingLogger?.endTiming(`step-${a}`)??Date.now()-m,y=Object.keys(o).filter(b=>!d.includes(b)),x;if(c==="execute"&&p.nodeName&&y.length>0){let b=`${p.nodeName}Result`;x=o[b]}this.flowLogger&&this.flowLogger({name:"StepComplete",timestamp:Date.now(),stepIndex:a,stepType:c,nodeName:p.nodeName,executionTime:f,state:{...o},newFields:y,result:x})}catch(g){throw this.flowLogger&&this.flowLogger({name:"FlowError",timestamp:Date.now(),error:g instanceof Error?g.message:String(g),stepIndex:a,stepType:c,nodeName:p.nodeName,state:{...o}}),g}}return{finalState:o,stepsExecuted:i}}getStepType(e,t){let n=this.executionPlanner.getExecutionPlan().steps.find(o=>o.stepIndex===t);if(n)return n.type;let r=e.toString();return r.includes("nodeName")||r.includes("nodeProgram")?"execute":r.includes("_parallelResults")||r.includes("processBatches")?"parallel":r.includes("branchValue")||r.includes("branches.get")||r.includes("mergeFunction")?"merge":r.includes("transform(")||r.includes("...state,")?"map":r.includes("inputValue")&&r.includes("transformFn")?"derive":r.includes("condition(")&&r.includes("iterations")?r.includes("while")?"while":"feedback":r.includes("branchSteps")||r.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 ye().input("userInput",ye.string("User input to the flow")).output("flowOutput",ye.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 y=this.toCamelCase(`${m}_${h.name}`);c.push({name:y,type:h.type,description:h.description,isOptional:h.isOptional,isInternal:h.isInternal})}for(let h of f.getOutputFields()){let y=this.toCamelCase(`${m}_${h.name}`);p.push({name:y,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=Hr():this.flowLogger=void 0,this.timingLogger=this.flowLogger?bc(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 Ut(e);for(let[t,n]of Array.from(this.nodeGenerators))this.program.register(n,t);return}this.program.setSignature(e)}getId(){return this.ensureProgram(),this.program.getId()}setId(e){this.ensureProgram(),this.program.setId(e)}namedPrograms(){return this.ensureProgram(),this.program.namedPrograms()}getTraces(){let e=[];for(let[t,n]of Array.from(this.nodeTraces))e.push(...n);return e}setDemos(e,t){this.ensureProgram(),this.program.setDemos(e,t)}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(`
724
+ `;break;default:r=JSON.stringify(n,null,2)}s(r)}},_c=zr(),Nc=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 Jn=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}},ws=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 Hr=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;activeAbortControllers=new Set;_stopRequested=!1;toCamelCase(e){return e.replace(/_([a-z])/g,(t,n)=>n.toUpperCase())}stop(){this._stopRequested=!0;for(let e of this.activeAbortControllers)e.abort("Stopped by user")}extractInputValues(e){if(!Array.isArray(e))return e;let t=e.filter(n=>n.role==="user").pop();if(!t)throw new Error("No user message found in values array");return t.values}getCacheKey(e,t){if(!t)return;this.ensureProgram();let n=this.program.getSignature(),r=n.getInputFields().map(l=>l.name),o=this.extractInputValues(e),i=Ze("sha256");i.update(n.hash()??"");let a=l=>{let u=typeof l;if(i.update(`|${u}|`),l==null){i.update("null");return}if(u==="string"||u==="number"||u==="boolean"){i.update(String(l));return}if(Array.isArray(l)){i.update("[");for(let c of l)a(c);i.update("]");return}if(typeof l=="object"&&l!==null&&"mimeType"in l&&"data"in l){let c=l;i.update(c.mimeType??"");let p=Ze("sha256").update(c.data??"").digest("hex");i.update(p);return}if(typeof l=="object"){let c=l,p=Object.keys(c).sort();for(let d of p)i.update(`{${d}}`),a(c[d]);return}i.update(String(l))};for(let l of r)a(o?.[l]);return i.digest("hex")}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=n.mainOptions?.abortSignal;if(u?.aborted)throw new Pe("flow-between-steps",u.reason??"Flow aborted between steps");let c=this.getStepType(l,a),p=this.getStepMetadata(l,a),d=Object.keys(o);this.flowLogger&&this.flowLogger({name:"StepStart",timestamp:Date.now(),stepIndex:a,stepType:c,nodeName:p.nodeName,dependencies:p.dependencies,produces:p.produces,state:{...o}});let m=Date.now();this.timingLogger?.startTiming(`step-${a}`);try{o=await l(o,n),i++;let f=this.timingLogger?.endTiming(`step-${a}`)??Date.now()-m,A=Object.keys(o).filter(b=>!d.includes(b)),x;if(c==="execute"&&p.nodeName&&A.length>0){let b=`${p.nodeName}Result`;x=o[b]}this.flowLogger&&this.flowLogger({name:"StepComplete",timestamp:Date.now(),stepIndex:a,stepType:c,nodeName:p.nodeName,executionTime:f,state:{...o},newFields:A,result:x})}catch(g){throw this.flowLogger&&this.flowLogger({name:"FlowError",timestamp:Date.now(),error:g instanceof Error?g.message:String(g),stepIndex:a,stepType:c,nodeName:p.nodeName,state:{...o}}),g}}return{finalState:o,stepsExecuted:i}}getStepType(e,t){let n=this.executionPlanner.getExecutionPlan().steps.find(o=>o.stepIndex===t);if(n)return n.type;let r=e.toString();return r.includes("nodeName")||r.includes("nodeProgram")?"execute":r.includes("_parallelResults")||r.includes("processBatches")?"parallel":r.includes("branchValue")||r.includes("branches.get")||r.includes("mergeFunction")?"merge":r.includes("transform(")||r.includes("...state,")?"map":r.includes("inputValue")&&r.includes("transformFn")?"derive":r.includes("condition(")&&r.includes("iterations")?r.includes("while")?"while":"feedback":r.includes("branchSteps")||r.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 he().input("userInput",he.string("User input to the flow")).output("flowOutput",he.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 A=this.toCamelCase(`${m}_${h.name}`);c.push({name:A,type:h.type,description:h.description,isOptional:h.isOptional,isInternal:h.isInternal})}for(let h of f.getOutputFields()){let A=this.toCamelCase(`${m}_${h.name}`);p.push({name:A,type:h.type,description:h.description,isOptional:h.isOptional,isInternal:h.isInternal})}}let d=new Me;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 Me,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=zr():this.flowLogger=void 0,this.timingLogger=this.flowLogger?Nc(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 Dt(e);for(let[t,n]of Array.from(this.nodeGenerators))this.program.register(n,t);return}this.program.setSignature(e)}getId(){return this.ensureProgram(),this.program.getId()}setId(e){this.ensureProgram(),this.program.setId(e)}namedPrograms(){return this.ensureProgram(),this.program.namedPrograms()}getTraces(){let e=[];for(let[t,n]of Array.from(this.nodeTraces))e.push(...n);return e}setDemos(e,t){this.ensureProgram(),this.program.setDemos(e,t)}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(`
715
725
  `)[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(`
716
- `)};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 Er(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]=Er(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??fe.cachingFunction,o=this.getCacheKey(t,r);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??fe.cachingFunction,o=this.getCacheKey(t,r);if(r&&o){let c;try{c=await r(o)}catch{}if(c!==void 0)return c}let i=Date.now();this.timingLogger?.startTiming("flow-execution");let a={},l,u;try{this.resetUsage(),this.resetTraces();let c=this.extractInputValues(t);if(this.nodeGenerators.size>0&&this.ensureProgram(),a={...c},this.flowLogger){let b=this.getExecutionPlan();this.flowLogger({name:"FlowStart",timestamp:i,inputFields:Object.keys(c),totalSteps:b.totalSteps,parallelGroups:b.parallelGroups,maxParallelism:b.maxParallelism,autoParallelEnabled:b.autoParallelEnabled})}let p=n?.tracer??this.defaultAIOptions?.tracer,d=n?.traceContext,m=d;if(p){let b=this.getExecutionPlan(),R=n?.traceLabel?`AxFlow > ${n.traceLabel}`:"AxFlow";l=p.startSpan(R,{kind:ot.INTERNAL,attributes:{total_steps:b.totalSteps,parallel_groups:b.parallelGroups,max_parallelism:b.maxParallelism,auto_parallel_enabled:b.autoParallelEnabled}});let A=d??Nt.active();m=lr.setSpan(A,l)}u=new AbortController,this.activeAbortControllers.add(u),this._stopRequested&&u.abort("Stopped by user (pre-forward)");let g=Ft(n?.abortSignal,n?.abortController?.signal),f=Ft(u.signal,Ft(g,fe.abortSignal)),h={mainAi:e,mainOptions:(()=>{let b={...this.defaultAIOptions??{},...n};return n?.model&&(b.model=String(n.model)),p&&(b.tracer=p),m&&(b.traceContext=m),f&&(b.abortSignal=f),Object.keys(b).length>0?b:void 0})()},y=n?.autoParallel!==!1&&this.autoParallelConfig.enabled,x=0;if(y){this.executionPlanner.setInitialFields(Object.keys(c));let b=this.executionPlanner.createOptimizedExecution(this.autoParallelConfig.batchSize),R=await this.executeStepsWithLogging(b,a,h,!0);a=R.finalState,x=R.stepsExecuted}else{let b=await this.executeStepsWithLogging(this.flowDefinition,a,h,!1);a=b.finalState,x=b.stepsExecuted}if(this.flowLogger){let b=this.timingLogger?.endTiming("flow-execution")??Date.now()-i;this.flowLogger({name:"FlowComplete",timestamp:Date.now(),totalExecutionTime:b,finalState:a,outputFields:Object.keys(a),stepsExecuted:x})}if(r&&o)try{await r(o,a)}catch{}return a}catch(c){throw this.flowLogger&&this.flowLogger({name:"FlowError",timestamp:Date.now(),error:c instanceof Error?c.message:String(c),state:a}),c}finally{l&&l.end(),u&&this.activeAbortControllers.delete(u),this._stopRequested=!1}}node(e,t){if(this.nodes.has(e)||this.nodeGenerators.has(e))throw new Error(`Node '${e}' is already defined. Use a unique node name in this flow.`);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=Ze(n);this.nodeGenerators.set(e,r),this.ensureProgram(),this.program.register(r,e)}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,e)}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,e)}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 Yn(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 Yn(e,async(i,a)=>{let l=new er(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 Yn(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 Cs(s){return Kr.create(s)}var Ts=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 ws=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)}}};function Rs(s){let e=typeof self<"u"?self:globalThis,t=Object.getPrototypeOf(async()=>{}).constructor,n=s.functionRefKey,r="return",o="stdout",i=/^(if|for|while|switch|try|catch|finally|function|class|import|export|throw|return|var|let|const|break|continue|debugger)\b/,a=/^\s*return\s+([^\n;]+?)\s*;?\s*$/,l={network:["fetch","XMLHttpRequest","WebSocket","EventSource"],storage:["indexedDB","caches"],"code-loading":["importScripts"],communication:["BroadcastChannel"],timing:["performance"],workers:["Worker","SharedWorker"]},u=()=>{let C;if(typeof process<"u"&&typeof process.getBuiltinModule=="function"&&(C=process.getBuiltinModule.bind(process)),!C)try{C=new Function('return typeof require==="function"?require:undefined')()}catch{C=void 0}if(!(typeof C=="function"&&typeof process<"u"&&!!process.versions?.node))return{isNodeWorker:!1,parentPort:null};try{return{isNodeWorker:!0,parentPort:C("node:worker_threads").parentPort??null}}catch{return{isNodeWorker:!0,parentPort:null}}},{isNodeWorker:c,parentPort:p}=u(),d=()=>{if(!p&&typeof e.postMessage!="function")throw new Error("Worker transport unavailable: no postMessage channel");return{send:k=>{if(p){p.postMessage(k);return}e.postMessage(k)},setOnMessage:k=>{if(p){p.on("message",I=>k({data:I}));return}e.onmessage=k}}},{send:m,setOnMessage:g}=d(),f=C=>C&&(/\r?\n$/.test(C)?C:`${C}
717
- `),h=C=>{let S=C.trim();return S.startsWith("//")||S.startsWith("/*")||S.startsWith("*")},y=C=>{let S=C.length-1;for(;S>=0;){let k=C[S].trim();if(k&&!h(k))break;S-=1}return S},x=C=>{if(!C)return!0;let S=C.split(`
718
- `).find(k=>k.trim().length>0)?.trim();return!S||i.test(S)?!0:S.startsWith("{")&&!S.startsWith("({")||S==="}"||S==="};"||h(S)},b=(C,S)=>{let k=C,I=S.trim().replace(/;\s*$/,"");if(!I)return null;let B=I.lastIndexOf(";");if(B!==-1){let K=I.slice(B+1).trim(),q=I.slice(0,B).trim();K&&(K.startsWith("//")||K.startsWith("/*")?q&&(I=q):(q&&(k=k?`${k}
719
- ${q};`:`${q};`),I=K))}return x(I)?null:{head:k,expression:I}},R=(C,S,k)=>{let I=C.slice(0,S).join(`
720
- `),B=C.slice(S,k+1).join(`
721
- `).trim();if(!B)return null;if(!B.includes(`
722
- `)){let K=b(I,B);return K?K.head?`${K.head}
726
+ `)};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 Mr(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]=Mr(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??ce.cachingFunction,o=this.getCacheKey(t,r);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??ce.cachingFunction,o=this.getCacheKey(t,r);if(r&&o){let c;try{c=await r(o)}catch{}if(c!==void 0)return c}let i=Date.now();this.timingLogger?.startTiming("flow-execution");let a={},l,u;try{this.resetUsage(),this.resetTraces();let c=this.extractInputValues(t);if(this.nodeGenerators.size>0&&this.ensureProgram(),a={...c},this.flowLogger){let b=this.getExecutionPlan();this.flowLogger({name:"FlowStart",timestamp:i,inputFields:Object.keys(c),totalSteps:b.totalSteps,parallelGroups:b.parallelGroups,maxParallelism:b.maxParallelism,autoParallelEnabled:b.autoParallelEnabled})}let p=n?.tracer??this.defaultAIOptions?.tracer,d=n?.traceContext,m=d;if(p){let b=this.getExecutionPlan(),C=n?.traceLabel?`AxFlow > ${n.traceLabel}`:"AxFlow";l=p.startSpan(C,{kind:Ve.INTERNAL,attributes:{total_steps:b.totalSteps,parallel_groups:b.parallelGroups,max_parallelism:b.maxParallelism,auto_parallel_enabled:b.autoParallelEnabled}});let I=d??Pt.active();m=ar.setSpan(I,l)}u=new AbortController,this.activeAbortControllers.add(u),this._stopRequested&&u.abort("Stopped by user (pre-forward)");let g=St(n?.abortSignal,n?.abortController?.signal),f=St(u.signal,St(g,ce.abortSignal)),h={mainAi:e,mainOptions:(()=>{let b={...this.defaultAIOptions??{},...n};return n?.model&&(b.model=String(n.model)),p&&(b.tracer=p),m&&(b.traceContext=m),f&&(b.abortSignal=f),Object.keys(b).length>0?b:void 0})()},A=n?.autoParallel!==!1&&this.autoParallelConfig.enabled,x=0;if(A){this.executionPlanner.setInitialFields(Object.keys(c));let b=this.executionPlanner.createOptimizedExecution(this.autoParallelConfig.batchSize),C=await this.executeStepsWithLogging(b,a,h,!0);a=C.finalState,x=C.stepsExecuted}else{let b=await this.executeStepsWithLogging(this.flowDefinition,a,h,!1);a=b.finalState,x=b.stepsExecuted}if(this.flowLogger){let b=this.timingLogger?.endTiming("flow-execution")??Date.now()-i;this.flowLogger({name:"FlowComplete",timestamp:Date.now(),totalExecutionTime:b,finalState:a,outputFields:Object.keys(a),stepsExecuted:x})}if(r&&o)try{await r(o,a)}catch{}return a}catch(c){throw this.flowLogger&&this.flowLogger({name:"FlowError",timestamp:Date.now(),error:c instanceof Error?c.message:String(c),state:a}),c}finally{l&&l.end(),u&&this.activeAbortControllers.delete(u),this._stopRequested=!1}}node(e,t){if(this.nodes.has(e)||this.nodeGenerators.has(e))throw new Error(`Node '${e}' is already defined. Use a unique node name in this flow.`);if(typeof t=="string"||t instanceof Me){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=je(n);this.nodeGenerators.set(e,r),this.ensureProgram(),this.program.register(r,e)}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,e)}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,e)}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 Hn(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 Hn(e,async(i,a)=>{let l=new Jn(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 Hn(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"?Me.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 Rs(s){return Hr.create(s)}var vs=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 Ss=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)}}};function Yn(s){return!!s&&/[A-Za-z0-9_$]/.test(s)}function ks(s){let e="",t=0,n="normal",r=!1;for(;t<s.length;){let o=s[t]??"",i=s[t+1]??"";if(n==="lineComment"){o===`
727
+ `?(e+=`
728
+ `,n="normal"):e+=" ",t++;continue}if(n==="blockComment"){o==="*"&&i==="/"?(e+=" ",t+=2,n="normal"):(e+=o===`
729
+ `?`
730
+ `:" ",t++);continue}if(n==="single"||n==="double"||n==="template"){let a=n==="single"?"'":n==="double"?'"':"`";if(r){e+=o===`
731
+ `?`
732
+ `:" ",r=!1,t++;continue}if(o==="\\"){e+=" ",r=!0,t++;continue}if(o===a){e+=" ",n="normal",t++;continue}e+=o===`
733
+ `?`
734
+ `:" ",t++;continue}if(o==="/"&&i==="/"){e+=" ",t+=2,n="lineComment";continue}if(o==="/"&&i==="*"){e+=" ",t+=2,n="blockComment";continue}if(o==="'"){e+=" ",t++,n="single";continue}if(o==='"'){e+=" ",t++,n="double";continue}if(o==="`"){e+=" ",t++,n="template";continue}e+=o,t++}return e}function Os(s){let e=[],t=s.length,n=0,r=0,o=0,i=A=>{if(n++,A==="`"){let x=0;for(;n<t;){let b=s[n];if(b==="\\"){n+=2;continue}if(x>0){b==="{"?x++:b==="}"&&x--,n++;continue}if(b==="$"&&n+1<t&&s[n+1]==="{"){x++,n+=2;continue}if(b==="`"){n++;return}n++}return}for(;n<t;){let x=s[n];if(x==="\\"){n+=2;continue}if(x===A){n++;return}n++}},a=()=>{for(n+=2;n<t&&s[n]!==`
735
+ `;)n++},l=()=>{for(n+=2;n<t;){if(s[n]==="*"&&n+1<t&&s[n+1]==="/"){n+=2;return}n++}},u=()=>{let A=n;for(;n<t&&Yn(s[n]);)n++;return s.slice(A,n)},c=()=>{let A=n;for(;n<t;){let x=s[n];if(x===" "||x===" "||x===`
736
+ `||x==="\r"){n++;continue}if(x==="/"&&n+1<t){if(s[n+1]==="/"){a();continue}if(s[n+1]==="*"){l();continue}}break}return n>A},p=A=>{let x=1;for(;n<t&&x>0;){if(c(),n>=t)return;let b=s[n];if(b===A){x--,n++;continue}if(b==="{"||b==="["){let C=b==="{"?"}":"]";n++,p(C);continue}if(b==="."&&n+2<t&&s[n+1]==="."&&s[n+2]==="."){if(n+=3,c(),n<t&&Yn(s[n])){let C=u();C&&e.push(C)}continue}if(b===","){n++;continue}if(b==="="){n++;let C=0;for(;n<t;){let I=s[n];if(I==="'"||I==='"'||I==="`"){i(I);continue}if(I==="("||I==="["||I==="{"){C++,n++;continue}if(I===")"||I==="]"||I==="}"){if(C>0){C--,n++;continue}break}if(I===","&&C===0)break;n++}continue}if(Yn(b)){let C=u();if(c(),n<t&&s[n]===":"){if(n++,c(),n<t){let I=s[n];if(I==="{"||I==="["){let v=I==="{"?"}":"]";n++,p(v)}else if(Yn(I)){let v=u();v&&e.push(v)}}}else C&&e.push(C);continue}n++}},d=()=>{let A=0;for(;n<t;){let x=s[n];if(x==="'"||x==='"'||x==="`"){i(x);continue}if(x==="/"&&n+1<t){if(s[n+1]==="/"){a();continue}if(s[n+1]==="*"){l();continue}}if(x==="("||x==="["||x==="{"){A++,n++;continue}if(x===")"||x==="]"||x==="}"){if(A>0){A--,n++;continue}return!1}if(x===","&&A===0)return n++,!0;if(x===";"&&A===0)return n++,!1;if(x===`
737
+ `&&A===0){let b=n;return n++,c(),n<t&&s[n]===","?(n++,!0):(n=b,!1)}n++}return!1},m=()=>{for(;n<t;){if(c(),n>=t)return;let A=s[n];if(A==="{"){if(n++,p("}"),!d())return;continue}if(A==="["){if(n++,p("]"),!d())return;continue}if(Yn(A)){let x=u();if(x&&e.push(x),!d())return;continue}return}},g=A=>{if(A===0)return!0;let x=A-1;for(;x>=0;){let b=s[x];if(b===" "||b===" "||b==="\r"){x--;continue}return b===`
738
+ `||b===";"||b==="{"||b==="}"}return!0};for(;n<t;){let A=s[n];if(A==="'"||A==='"'||A==="`"){i(A);continue}if(A==="/"&&n+1<t){if(s[n+1]==="/"){a();continue}if(s[n+1]==="*"){l();continue}}if(A==="{"){r++,n++;continue}if(A==="}"){r--,n++;continue}if(A==="("){o++,n++;continue}if(A===")"){o--,n++;continue}if(r===0&&o===0&&Yn(A)){let x=n,b=u();(b==="var"||b==="let"||b==="const")&&n<t&&(s[n]===" "||s[n]===" "||s[n]===`
739
+ `)&&g(x)&&m();continue}n++}let f=new Set,h=[];for(let A of e)f.has(A)||(f.add(A),h.push(A));return h}function Ms(s){let e=typeof self<"u"?self:globalThis,t=Object.getPrototypeOf(async()=>{}).constructor,n=s.functionRefKey,r="return",o="stdout",i=/^(if|for|while|switch|try|catch|finally|function|class|import|export|throw|return|var|let|const|break|continue|debugger)\b/,a=/^\s*return\s+([^\n;]+?)\s*;?\s*$/,l={network:["fetch","XMLHttpRequest","WebSocket","EventSource"],storage:["indexedDB","caches"],"code-loading":["importScripts"],communication:["BroadcastChannel"],timing:["performance"],workers:["Worker","SharedWorker"]},u=()=>{let T;if(typeof process<"u"&&typeof process.getBuiltinModule=="function"&&(T=process.getBuiltinModule.bind(process)),!T)try{T=new Function('return typeof require==="function"?require:undefined')()}catch{T=void 0}if(!(typeof T=="function"&&typeof process<"u"&&!!process.versions?.node))return{isNodeWorker:!1,parentPort:null};try{return{isNodeWorker:!0,parentPort:T("node:worker_threads").parentPort??null}}catch{return{isNodeWorker:!0,parentPort:null}}},{isNodeWorker:c,parentPort:p}=u(),d=()=>{if(!p&&typeof e.postMessage!="function")throw new Error("Worker transport unavailable: no postMessage channel");return{send:P=>{if(p){p.postMessage(P);return}e.postMessage(P)},setOnMessage:P=>{if(p){p.on("message",y=>P({data:y}));return}e.onmessage=P}}},{send:m,setOnMessage:g}=d(),f=T=>T&&(/\r?\n$/.test(T)?T:`${T}
740
+ `),h=T=>{let F=T.trim();return F.startsWith("//")||F.startsWith("/*")||F.startsWith("*")},A=T=>{let F=T.length-1;for(;F>=0;){let P=T[F].trim();if(P&&!h(P))break;F-=1}return F},x=T=>{if(!T)return!0;let F=T.split(`
741
+ `).find(P=>P.trim().length>0)?.trim();return!F||i.test(F)?!0:F.startsWith("{")&&!F.startsWith("({")||F==="}"||F==="};"||h(F)},b=(T,F)=>{let P=T,y=F.trim().replace(/;\s*$/,"");if(!y)return null;let D=y.lastIndexOf(";");if(D!==-1){let B=y.slice(D+1).trim(),j=y.slice(0,D).trim();B&&(B.startsWith("//")||B.startsWith("/*")?j&&(y=j):(j&&(P=P?`${P}
742
+ ${j};`:`${j};`),y=B))}return x(y)?null:{head:P,expression:y}},C=(T,F,P)=>{let y=T.slice(0,F).join(`
743
+ `),D=T.slice(F,P+1).join(`
744
+ `).trim();if(!D)return null;if(!D.includes(`
745
+ `)){let B=b(y,D);return B?B.head?`${B.head}
723
746
  return (
724
- ${K.expression}
747
+ ${B.expression}
725
748
  );`:`return (
726
- ${K.expression}
727
- );`:null}return x(B)?null:I?`${I}
749
+ ${B.expression}
750
+ );`:null}return x(D)?null:y?`${y}
728
751
  return (
729
- ${B}
752
+ ${D}
730
753
  );`:`return (
731
- ${B}
732
- );`},A=C=>{try{return new t(C),!0}catch{return!1}},w=C=>{let S=C.split(`
733
- `),k=y(S);if(k<0)return C;let I=new Set;for(let B=k;B>=0;B-=1){let K=S[B]??"";if(!K.trim()||h(K))continue;let q=R(S,B,k);if(q&&!I.has(q)&&(I.add(q),A(q)))return q}return C},v=C=>{let S=a.exec(C);return S&&(S[1]||"").trim()||C},F=C=>{let S=[],k=C.length,I=0,B=0,K=0,q=Z=>Z>="a"&&Z<="z"||Z>="A"&&Z<="Z"||Z>="0"&&Z<="9"||Z==="_"||Z==="$",H=Z=>{if(I++,Z==="`"){let J=0;for(;I<k;){let pe=C[I];if(pe==="\\"){I+=2;continue}if(J>0){pe==="{"?J++:pe==="}"&&J--,I++;continue}if(pe==="$"&&I+1<k&&C[I+1]==="{"){J++,I+=2;continue}if(pe==="`"){I++;return}I++}}else for(;I<k;){let J=C[I];if(J==="\\"){I+=2;continue}if(J===Z){I++;return}I++}},j=()=>{for(I+=2;I<k&&C[I]!==`
734
- `;)I++},V=()=>{for(I+=2;I<k;){if(C[I]==="*"&&I+1<k&&C[I+1]==="/"){I+=2;return}I++}},ne=()=>{let Z=I;for(;I<k&&q(C[I]);)I++;return C.slice(Z,I)},le=()=>{let Z=I;for(;I<k;){let J=C[I];if(J===" "||J===" "||J===`
735
- `||J==="\r"){I++;continue}if(J==="/"&&I+1<k){if(C[I+1]==="/"){j();continue}if(C[I+1]==="*"){V();continue}}break}return I>Z},ce=Z=>{let J=1;for(;I<k&&J>0;){if(le(),I>=k)return;let pe=C[I];if(pe===Z){J--,I++;continue}if(pe==="{"||pe==="["){let me=pe==="{"?"}":"]";I++,J++,I--,J--,I++,ce(me);continue}if(pe==="."&&I+2<k&&C[I+1]==="."&&C[I+2]==="."){if(I+=3,le(),I<k&&q(C[I])){let me=ne();me&&S.push(me)}continue}if(pe===","){I++;continue}if(pe==="="){I++;let me=0;for(;I<k;){let Oe=C[I];if(Oe==="'"||Oe==='"'||Oe==="`"){H(Oe);continue}if(Oe==="("||Oe==="["||Oe==="{"){me++,I++;continue}if(Oe===")"||Oe==="]"||Oe==="}"){if(me>0){me--,I++;continue}break}if(Oe===","&&me===0)break;I++}continue}if(q(pe)){let me=ne();if(le(),I<k&&C[I]===":"){if(I++,le(),I<k){let Oe=C[I];if(Oe==="{"||Oe==="["){let et=Oe==="{"?"}":"]";I++,ce(et)}else if(q(Oe)){let et=ne();et&&S.push(et)}}}else me&&S.push(me);continue}I++}},ge=()=>{let Z=0;for(;I<k;){let J=C[I];if(J==="'"||J==='"'||J==="`"){H(J);continue}if(J==="/"&&I+1<k){if(C[I+1]==="/"){j();continue}if(C[I+1]==="*"){V();continue}}if(J==="("||J==="["||J==="{"){Z++,I++;continue}if(J===")"||J==="]"||J==="}"){if(Z>0){Z--,I++;continue}return!1}if(J===","&&Z===0)return I++,!0;if(J===";"&&Z===0)return I++,!1;if(J===`
736
- `&&Z===0){let pe=I;return I++,le(),I<k&&C[I]===","?(I++,!0):(I=pe,!1)}I++}return!1},Ae=()=>{for(;I<k;){if(le(),I>=k)return;let Z=C[I];if(Z==="{"){if(I++,ce("}"),!ge())return;continue}if(Z==="["){if(I++,ce("]"),!ge())return;continue}if(q(Z)){let J=ne();if(J&&S.push(J),!ge())return;continue}return}},Se=Z=>{if(Z===0)return!0;let J=Z-1;for(;J>=0;){let pe=C[J];if(pe===" "||pe===" "||pe==="\r"){J--;continue}return pe===`
737
- `||pe===";"||pe==="{"||pe==="}"}return!0};for(;I<k;){let Z=C[I];if(Z==="'"||Z==='"'||Z==="`"){H(Z);continue}if(Z==="/"&&I+1<k){if(C[I+1]==="/"){j();continue}if(C[I+1]==="*"){V();continue}}if(Z==="{"){B++,I++;continue}if(Z==="}"){B--,I++;continue}if(Z==="("){K++,I++;continue}if(Z===")"){K--,I++;continue}if(B===0&&K===0&&q(Z)){let J=I,pe=ne();if((pe==="var"||pe==="let"||pe==="const")&&I<k&&(C[I]===" "||C[I]===" "||C[I]===`
738
- `)&&Se(J)){Ae();continue}continue}I++}let Fe=new Set,Ee=[];for(let Z of S)Fe.has(Z)||(Fe.add(Z),Ee.push(Z));return Ee},O=C=>C.length===0?"":`
739
- try { ${C.map(k=>`globalThis[${JSON.stringify(k)}] = ${k};`).join(" ")} } catch (_ax_e) {} void 0;`,D=C=>{if(typeof C=="string")return C;try{return JSON.stringify(C,null,2)}catch{return String(C)}},U=(C,S)=>{let k=e.console&&typeof e.console=="object"?e.console:null,I=k?.[C],B=typeof I=="function"?(...q)=>I.apply(k,q):null,K=(...q)=>{S.push(q.map(D).join(" "))};return(!e.console||typeof e.console!="object")&&(e.console={}),e.console[C]=K,()=>{if(!(!e.console||typeof e.console!="object")){if(B){e.console[C]=B;return}try{delete e.console[C]}catch{e.console[C]=void 0}}}},L=C=>{let S=[];return be&&(S.push(U("log",C)),S.push(U("info",C)),S.push(U("warn",C)),S.push(U("error",C))),S},T=()=>{let C=[],S=L(C),k=e.print;return oe===o&&(e.print=(...B)=>{C.push(B.map(D).join(" "))}),{output:C,cleanup:()=>{for(let B of S)try{B()}catch{}if(oe===o)if(k===void 0)try{delete e.print}catch{e.print=void 0}else e.print=k}}},M=C=>{for(let S of C)try{Object.defineProperty(e,S,{value:void 0,writable:!1,configurable:!1})}catch{}},E=C=>{let S=new Set(Array.isArray(C)?C:[]);for(let[k,I]of Object.entries(l))S.has(k)||M(I)},N=C=>{c&&!C&&M(["process","require"])},P=s.maxErrorCauseDepth,_=(C,S=0,k=new Set)=>{if(S>P)return{name:"Error",message:"[cause chain truncated]"};if(C&&typeof C=="object"){if(k.has(C))return{name:"Error",message:"[circular]"};k.add(C)}let I=C,B=I?.name!=null?String(I.name):"Error",K=I?.message!=null?String(I.message):W(C),q=typeof I?.stack=="string"?I.stack:void 0,H;if(typeof I?.cause<"u"&&S<P)try{let V=I.cause;V instanceof Error||V&&typeof V=="object"&&("message"in V||"name"in V)?H=_(V,S+1,k):H={name:"Error",message:W(V)}}catch{H={name:"Error",message:W(I.cause)}}let j={name:B,message:K};if(q!==void 0&&(j.stack=q),H!==void 0&&(j.cause=H),typeof I?.data<"u")try{j.data=typeof structuredClone=="function"?structuredClone(I.data):I.data}catch{}return j},G=C=>{if(typeof C=="string")return new Error(C);if(!C||typeof C!="object")return new Error(String(C));let S=C,k=new Error(S.message!=null?String(S.message):"");return k.name=S.name!=null?String(S.name):"Error",typeof S.stack=="string"&&(k.stack=S.stack),S.cause!==void 0&&(k.cause=G(S.cause)),S.data!==void 0&&(k.data=S.data),k},$=C=>{let S=globalThis.AggregateError,k=typeof S=="function"&&C instanceof S;return C instanceof SyntaxError||C instanceof TypeError||C instanceof RangeError||C instanceof ReferenceError||k||C instanceof EvalError||C instanceof URIError},W=C=>{if(C==null||typeof C!="object")return String(C);try{return JSON.stringify(C,null,2)}catch{return String(C)}},se=(C,S,k=0)=>{let I=C,B=I?.name!=null?String(I.name):"Error",K=I?.message!=null?String(I.message):W(C),q=[`${B}: ${K}`],H;if(typeof I?.stack=="string"){let j=I.stack.match(/<anonymous>:(\d+):(\d+)/);j&&(H=Math.max(1,Number(j[1])-k),q.push(` at line ${H}, column ${j[2]}`))}if(S&&H!==void 0&&H>=1&&H<=S.split(`
740
- `).length){let j=S.split(`
741
- `),V=Math.max(0,H-2),ne=Math.min(j.length,H+1),ce=j.slice(V,ne).map((ge,Ae)=>` ${String(V+Ae+1).padStart(3)}| ${ge}`).join(`
742
- `);q.push(`Source:
743
- ${ce}`)}if(I?.data!==void 0&&q.push(`Data: ${W(I.data)}`),I?.cause!==void 0){let j=(V,ne)=>{if(ne>4)return"[cause chain truncated]";let le=V,ce=le?.name!=null?String(le.name):"Error",ge=le?.message!=null?String(le.message):W(V),Ae=[`${ce}: ${ge}`];return le?.data!==void 0&&Ae.push(`Data: ${W(le.data)}`),le?.cause!==void 0&&Ae.push(`Caused by: ${j(le.cause,ne+1)}`),Ae.join(`
744
- `)};q.push(`Caused by: ${j(I.cause,1)}`)}return q.join(`
745
- `)},Y=new Map,ee=0,oe=r,be=!1,Ce=C=>(...S)=>{let k=++ee;return new Promise((I,B)=>{Y.set(k,{resolve:I,reject:B}),m({type:"fn-call",id:k,name:C,args:S})})},X=C=>{if(!C||typeof C!="object")return C;if(Array.isArray(C)){for(let k=0;k<C.length;k+=1)C[k]=X(C[k]);return C}let S=C;if(n in S){let k=S[n];return typeof k=="string"?Ce(k):void 0}for(let[k,I]of Object.entries(S))S[k]=X(I);return C},Ie=C=>{if(!C||typeof C!="object"||Array.isArray(C))return!1;let S=Object.getPrototypeOf(C);return S===Object.prototype||S===null},re=C=>{for(let[S,k]of Object.entries(C)){let I=X(k),B=e[S];if(Ie(B)&&Ie(I)){for(let K of Object.keys(B))Object.hasOwn(I,K)||delete B[K];for(let[K,q]of Object.entries(I))B[K]=q;continue}e[S]=I}},ue=C=>{if(C.globals&&typeof C.globals=="object"&&re(C.globals),Array.isArray(C.fnNames))for(let S of C.fnNames)typeof S=="string"&&(e[S]=Ce(S))},Pe=async C=>{let S=f(C),k=[];try{k=F(C)}catch{k=[]}let I=O(k),B=S;try{B=w(S)}catch{B=S}let K=B;if(I){let j=B.lastIndexOf(`
746
- return (`);j!==-1?K=B.slice(0,j)+I+B.slice(j):K=B+I}let q=A(K)?K:A(B)?B:S;return await new t(q)()},ae=C=>{let S=v(C),k=[];try{k=F(C)}catch{k=[]}let I=O(k),B=I?S+I:S;return(0,eval)(B)},ve=(C,S)=>{if(oe!==o)return C;let k=S.join(`
747
- `).trim();return k||C};g(async C=>{let S=C.data;if(!S||typeof S!="object"||typeof S.type!="string")return;if(S.type==="init"){oe=S.outputMode===o?o:r,be=S.captureConsole!==void 0?!!S.captureConsole:oe===o;let H=S.allowUnsafeNodeHostAccess===!0;ue(S),E(S.permissions),N(H);return}if(S.type==="fn-result"){if(typeof S.id!="number")return;let H=Y.get(S.id);H&&(Y.delete(S.id),S.error!==void 0?H.reject(G(S.error)):H.resolve(S.value));return}if(S.type==="update-globals"){if(typeof S.id!="number")return;try{S.globals&&typeof S.globals=="object"&&re(S.globals),m({type:"result",id:S.id,value:void 0})}catch(H){m({type:"result",id:S.id,error:_(H)})}return}if(S.type!=="execute"||typeof S.id!="number"||typeof S.code!="string")return;let k=S.id,I=S.code,B=/\bawait\b/.test(I),{output:K,cleanup:q}=T();try{let H=B?await Pe(I):ae(I),j=ve(H,K);try{m({type:"result",id:k,value:j})}catch{m({type:"result",id:k,value:String(j)})}}catch(H){$(H)?m({type:"result",id:k,value:se(H,I,B?2:0)}):m({type:"result",id:k,error:_(H)})}finally{q()}})}var ga=4,Ic=16,fa="__ax_rlm_fn_ref__",ha=16;function Cc(){let s={functionRefKey:fa,maxErrorCauseDepth:ha},e=`(${Rs.toString()})(${JSON.stringify(s)});
754
+ ${D}
755
+ );`},I=T=>{try{return new t(T),!0}catch{return!1}},v=T=>{let F=T.split(`
756
+ `),P=A(F);if(P<0)return T;let y=new Set;for(let D=P;D>=0;D-=1){let B=F[D]??"";if(!B.trim()||h(B))continue;let j=C(F,D,P);if(j&&!y.has(j)&&(y.add(j),I(j)))return j}return T},O=T=>{let F=a.exec(T);return F&&(F[1]||"").trim()||T},k=T=>{let F=[],P=T.length,y=0,D=0,B=0,j=X=>X>="a"&&X<="z"||X>="A"&&X<="Z"||X>="0"&&X<="9"||X==="_"||X==="$",H=X=>{if(y++,X==="`"){let ee=0;for(;y<P;){let ie=T[y];if(ie==="\\"){y+=2;continue}if(ee>0){ie==="{"?ee++:ie==="}"&&ee--,y++;continue}if(ie==="$"&&y+1<P&&T[y+1]==="{"){ee++,y+=2;continue}if(ie==="`"){y++;return}y++}}else for(;y<P;){let ee=T[y];if(ee==="\\"){y+=2;continue}if(ee===X){y++;return}y++}},z=()=>{for(y+=2;y<P&&T[y]!==`
757
+ `;)y++},K=()=>{for(y+=2;y<P;){if(T[y]==="*"&&y+1<P&&T[y+1]==="/"){y+=2;return}y++}},J=()=>{let X=y;for(;y<P&&j(T[y]);)y++;return T.slice(X,y)},oe=()=>{let X=y;for(;y<P;){let ee=T[y];if(ee===" "||ee===" "||ee===`
758
+ `||ee==="\r"){y++;continue}if(ee==="/"&&y+1<P){if(T[y+1]==="/"){z();continue}if(T[y+1]==="*"){K();continue}}break}return y>X},se=X=>{let ee=1;for(;y<P&&ee>0;){if(oe(),y>=P)return;let ie=T[y];if(ie===X){ee--,y++;continue}if(ie==="{"||ie==="["){let ae=ie==="{"?"}":"]";y++,ee++,y--,ee--,y++,se(ae);continue}if(ie==="."&&y+2<P&&T[y+1]==="."&&T[y+2]==="."){if(y+=3,oe(),y<P&&j(T[y])){let ae=J();ae&&F.push(ae)}continue}if(ie===","){y++;continue}if(ie==="="){y++;let ae=0;for(;y<P;){let we=T[y];if(we==="'"||we==='"'||we==="`"){H(we);continue}if(we==="("||we==="["||we==="{"){ae++,y++;continue}if(we===")"||we==="]"||we==="}"){if(ae>0){ae--,y++;continue}break}if(we===","&&ae===0)break;y++}continue}if(j(ie)){let ae=J();if(oe(),y<P&&T[y]===":"){if(y++,oe(),y<P){let we=T[y];if(we==="{"||we==="["){let We=we==="{"?"}":"]";y++,se(We)}else if(j(we)){let We=J();We&&F.push(We)}}}else ae&&F.push(ae);continue}y++}},ue=()=>{let X=0;for(;y<P;){let ee=T[y];if(ee==="'"||ee==='"'||ee==="`"){H(ee);continue}if(ee==="/"&&y+1<P){if(T[y+1]==="/"){z();continue}if(T[y+1]==="*"){K();continue}}if(ee==="("||ee==="["||ee==="{"){X++,y++;continue}if(ee===")"||ee==="]"||ee==="}"){if(X>0){X--,y++;continue}return!1}if(ee===","&&X===0)return y++,!0;if(ee===";"&&X===0)return y++,!1;if(ee===`
759
+ `&&X===0){let ie=y;return y++,oe(),y<P&&T[y]===","?(y++,!0):(y=ie,!1)}y++}return!1},de=()=>{for(;y<P;){if(oe(),y>=P)return;let X=T[y];if(X==="{"){if(y++,se("}"),!ue())return;continue}if(X==="["){if(y++,se("]"),!ue())return;continue}if(j(X)){let ee=J();if(ee&&F.push(ee),!ue())return;continue}return}},Ae=X=>{if(X===0)return!0;let ee=X-1;for(;ee>=0;){let ie=T[ee];if(ie===" "||ie===" "||ie==="\r"){ee--;continue}return ie===`
760
+ `||ie===";"||ie==="{"||ie==="}"}return!0};for(;y<P;){let X=T[y];if(X==="'"||X==='"'||X==="`"){H(X);continue}if(X==="/"&&y+1<P){if(T[y+1]==="/"){z();continue}if(T[y+1]==="*"){K();continue}}if(X==="{"){D++,y++;continue}if(X==="}"){D--,y++;continue}if(X==="("){B++,y++;continue}if(X===")"){B--,y++;continue}if(D===0&&B===0&&j(X)){let ee=y,ie=J();if((ie==="var"||ie==="let"||ie==="const")&&y<P&&(T[y]===" "||T[y]===" "||T[y]===`
761
+ `)&&Ae(ee)){de();continue}continue}y++}let Ce=new Set,Oe=[];for(let X of F)Ce.has(X)||(Ce.add(X),Oe.push(X));return Oe},S=T=>T.length===0?"":`
762
+ try { ${T.map(P=>`globalThis[${JSON.stringify(P)}] = ${P};`).join(" ")} } catch (_ax_e) {} void 0;`,$=T=>{if(typeof T=="string")return T;try{return JSON.stringify(T,null,2)}catch{return String(T)}},G=(T,F)=>{let P=e.console&&typeof e.console=="object"?e.console:null,y=P?.[T],D=typeof y=="function"?(...j)=>y.apply(P,j):null,B=(...j)=>{F.push(j.map($).join(" "))};return(!e.console||typeof e.console!="object")&&(e.console={}),e.console[T]=B,()=>{if(!(!e.console||typeof e.console!="object")){if(D){e.console[T]=D;return}try{delete e.console[T]}catch{e.console[T]=void 0}}}},L=T=>{let F=[];return ye&&(F.push(G("log",T)),F.push(G("info",T)),F.push(G("warn",T)),F.push(G("error",T))),F},w=()=>{let T=[],F=L(T),P=e.print;return te===o&&(e.print=(...D)=>{T.push(D.map($).join(" "))}),{output:T,cleanup:()=>{for(let D of F)try{D()}catch{}if(te===o)if(P===void 0)try{delete e.print}catch{e.print=void 0}else e.print=P}}},R=T=>{for(let F of T)try{Object.defineProperty(e,F,{value:void 0,writable:!1,configurable:!1})}catch{}},E=T=>{let F=new Set(Array.isArray(T)?T:[]);for(let[P,y]of Object.entries(l))F.has(P)||R(y)},_=T=>{c&&!T&&R(["process","require"])},M=s.maxErrorCauseDepth,N=(T,F=0,P=new Set)=>{if(F>M)return{name:"Error",message:"[cause chain truncated]"};if(T&&typeof T=="object"){if(P.has(T))return{name:"Error",message:"[circular]"};P.add(T)}let y=T,D=y?.name!=null?String(y.name):"Error",B=y?.message!=null?String(y.message):W(T),j=typeof y?.stack=="string"?y.stack:void 0,H;if(typeof y?.cause<"u"&&F<M)try{let K=y.cause;K instanceof Error||K&&typeof K=="object"&&("message"in K||"name"in K)?H=N(K,F+1,P):H={name:"Error",message:W(K)}}catch{H={name:"Error",message:W(y.cause)}}let z={name:D,message:B};if(j!==void 0&&(z.stack=j),H!==void 0&&(z.cause=H),typeof y?.data<"u")try{z.data=typeof structuredClone=="function"?structuredClone(y.data):y.data}catch{}return z},q=T=>{if(typeof T=="string")return new Error(T);if(!T||typeof T!="object")return new Error(String(T));let F=T,P=new Error(F.message!=null?String(F.message):"");return P.name=F.name!=null?String(F.name):"Error",typeof F.stack=="string"&&(P.stack=F.stack),F.cause!==void 0&&(P.cause=q(F.cause)),F.data!==void 0&&(P.data=F.data),P},U=T=>{let F=globalThis.AggregateError,P=typeof F=="function"&&T instanceof F;return T instanceof SyntaxError||T instanceof TypeError||T instanceof RangeError||T instanceof ReferenceError||P||T instanceof EvalError||T instanceof URIError},W=T=>{if(T==null||typeof T!="object")return String(T);try{return JSON.stringify(T,null,2)}catch{return String(T)}},Y=(T,F,P=0)=>{let y=T,D=y?.name!=null?String(y.name):"Error",B=y?.message!=null?String(y.message):W(T),j=[`${D}: ${B}`],H;if(typeof y?.stack=="string"){let z=y.stack.match(/<anonymous>:(\d+):(\d+)/);z&&(H=Math.max(1,Number(z[1])-P),j.push(` at line ${H}, column ${z[2]}`))}if(F&&H!==void 0&&H>=1&&H<=F.split(`
763
+ `).length){let z=F.split(`
764
+ `),K=Math.max(0,H-2),J=Math.min(z.length,H+1),se=z.slice(K,J).map((ue,de)=>` ${String(K+de+1).padStart(3)}| ${ue}`).join(`
765
+ `);j.push(`Source:
766
+ ${se}`)}if(y?.data!==void 0&&j.push(`Data: ${W(y.data)}`),y?.cause!==void 0){let z=(K,J)=>{if(J>4)return"[cause chain truncated]";let oe=K,se=oe?.name!=null?String(oe.name):"Error",ue=oe?.message!=null?String(oe.message):W(K),de=[`${se}: ${ue}`];return oe?.data!==void 0&&de.push(`Data: ${W(oe.data)}`),oe?.cause!==void 0&&de.push(`Caused by: ${z(oe.cause,J+1)}`),de.join(`
767
+ `)};j.push(`Caused by: ${z(y.cause,1)}`)}return j.join(`
768
+ `)},Q=new Map,V=0,te=r,ye=!1,Te=T=>(...F)=>{let P=++V;return new Promise((y,D)=>{Q.set(P,{resolve:y,reject:D}),m({type:"fn-call",id:P,name:T,args:F})})},Z=T=>{if(!T||typeof T!="object")return T;if(Array.isArray(T)){for(let P=0;P<T.length;P+=1)T[P]=Z(T[P]);return T}let F=T;if(n in F){let P=F[n];return typeof P=="string"?Te(P):void 0}for(let[P,y]of Object.entries(F))F[P]=Z(y);return T},fe=T=>{if(!T||typeof T!="object"||Array.isArray(T))return!1;let F=Object.getPrototypeOf(T);return F===Object.prototype||F===null},Re=T=>{for(let[F,P]of Object.entries(T)){let y=Z(P),D=e[F];if(fe(D)&&fe(y)){for(let B of Object.keys(D))Object.hasOwn(y,B)||delete D[B];for(let[B,j]of Object.entries(y))D[B]=j;continue}e[F]=y}},re=T=>{if(T.globals&&typeof T.globals=="object"&&Re(T.globals),Array.isArray(T.fnNames))for(let F of T.fnNames)typeof F=="string"&&(e[F]=Te(F))},xe=async T=>{let F=f(T),P=[];try{P=k(T)}catch{P=[]}let y=S(P),D=F;try{D=v(F)}catch{D=F}let B=D;if(y){let z=D.lastIndexOf(`
769
+ return (`);z!==-1?B=D.slice(0,z)+y+D.slice(z):B=D+y}let j=I(B)?B:I(D)?D:F;return await new t(j)()},le=T=>{let F=O(T),P=[];try{P=k(T)}catch{P=[]}let y=S(P),D=y?F+y:F;return(0,eval)(D)},Ie=(T,F)=>{if(te!==o)return T;let P=F.join(`
770
+ `).trim();return P||T};g(async T=>{let F=T.data;if(!F||typeof F!="object"||typeof F.type!="string")return;if(F.type==="init"){te=F.outputMode===o?o:r,ye=F.captureConsole!==void 0?!!F.captureConsole:te===o;let H=F.allowUnsafeNodeHostAccess===!0;re(F),E(F.permissions),_(H);return}if(F.type==="fn-result"){if(typeof F.id!="number")return;let H=Q.get(F.id);H&&(Q.delete(F.id),F.error!==void 0?H.reject(q(F.error)):H.resolve(F.value));return}if(F.type==="update-globals"){if(typeof F.id!="number")return;try{F.globals&&typeof F.globals=="object"&&Re(F.globals),m({type:"result",id:F.id,value:void 0})}catch(H){m({type:"result",id:F.id,error:N(H)})}return}if(F.type!=="execute"||typeof F.id!="number"||typeof F.code!="string")return;let P=F.id,y=F.code,D=/\bawait\b/.test(y),{output:B,cleanup:j}=w();try{let H=D?await xe(y):le(y),z=Ie(H,B);try{m({type:"result",id:P,value:z})}catch{m({type:"result",id:P,value:String(z)})}}catch(H){U(H)?m({type:"result",id:P,value:Y(H,y,D?2:0)}):m({type:"result",id:P,error:N(H)})}finally{j()}})}var Ia=4,$c=16,Ca="__ax_rlm_fn_ref__",Ta=16;function Lc(){let s={functionRefKey:Ca,maxErrorCauseDepth:Ta},e=`(${Ms.toString()})(${JSON.stringify(s)});
748
771
  `,t="";return e.includes("__name")&&(t+=`var __name=(fn,_n)=>fn;
749
- `),t?`${t}${e}`:e}var Tc=()=>typeof Worker<"u"&&typeof Blob<"u"&&typeof URL<"u"&&typeof URL.createObjectURL=="function",vs=()=>typeof process<"u"&&!!process.versions?.node,sm=()=>!!globalThis.Deno?.version?.deno,im=()=>globalThis.Deno?.version?.deno??null,am=s=>{let e=/^(\d+)\.(\d+)\.(\d+)$/.exec(s.trim());return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3])}:null},wc=s=>Number.isFinite(s)?Math.max(1,Math.min(Ic,Math.floor(s))):ga,lm=()=>{if(!vs())return null;let e=globalThis.process?.getBuiltinModule;if(typeof e!="function")return null;let n=e("node:os")?.availableParallelism;if(typeof n!="function")return null;let r=n();return Number.isFinite(r)&&r>0?r:null},um=s=>{if(s!==void 0)return wc(s);let e=lm();return e?wc(Math.ceil(e/2)):ga},cm=s=>s?.debugNodeWorkerPool?!0:(globalThis.process?.env??{}).AX_RLM_DEBUG_NODE_POOL==="1",pm=s=>{let e=new Set(s),t={};return e.has("network")&&(t.net=!0),Object.keys(t).length>0?t:"none"},dm=(s,e)=>{let t=im(),n=t?am(t):null;if(n?n.major>=1:!0)try{return new Worker(s,{type:"module",deno:{permissions:pm(e)}})}catch{}return new Worker(s,{type:"module"})},Rc=(s,e)=>{let t=new Blob([s],{type:"application/javascript"}),n=URL.createObjectURL(t),r=sm()?dm(n,e):new Worker(n),o=!1,i=()=>{o||(URL.revokeObjectURL(n),o=!0)},a={postMessage:l=>r.postMessage(l),terminate:()=>{r.terminate(),i()},onmessage:null,onerror:null};return r.onmessage=l=>{a.onmessage?.({data:l.data})},r.onerror=l=>{a.onerror?.(new Error(l.message||"Worker error"))},a},Aa=async s=>{let e="node:worker_threads",{Worker:t}=await import(e),n=new t(s,{eval:!0}),r=null,o=null,i=!1;n.on("error",l=>{o?o(l):r=l}),n.on("exit",l=>{if(i=!0,l!==0&&!r){let u=new Error(`Worker exited with code ${l}`);o?o(u):r=u}}),n.on("message",l=>{a.onmessage?.({data:l})});let a={postMessage:l=>n.postMessage(l),terminate:()=>{n.terminate()},onmessage:null,get onerror(){return o},set onerror(l){if(o=l,l&&r){let u=r;r=null,l(u)}},get exited(){return i}};return a},ya=class{source;maxSize;idle=[];pendingCreates=0;constructor(e,t){this.source=e,this.maxSize=t}warm(){if(vs())for(;this.idle.length+this.pendingCreates<this.maxSize;)this.pendingCreates+=1,Aa(this.source).then(e=>{e.onmessage=null,e.onerror=null,this.idle.push(e)}).catch(()=>{}).finally(()=>{this.pendingCreates-=1})}async acquire(){for(;this.idle.length>0;){let e=this.idle.pop();if(!e.exited)return this.warm(),e}return this.warm(),Aa(this.source)}release(e){e.onmessage=null,e.onerror=null,e.terminate(),this.warm()}},vc=new Map,mm=(s,e)=>`${e}:${s}`,gm=(s,e)=>{let t=mm(s,e),n=vc.get(t);if(n)return n;let r=new ya(s,e);return vc.set(t,r),r},Sc=(s,e)=>{let t={},n=new Map,r=0,o=new WeakMap,i=(a,l)=>{if(typeof a=="function"){let g=`fn_${e?.nextFnId?e.nextFnId():++r}_${l||"root"}`;return n.set(g,a),{[fa]:g}}if(!a||typeof a!="object")return a;if(o.has(a))return o.get(a);if(Array.isArray(a)){let m=[];o.set(a,m);for(let g=0;g<a.length;g+=1)m[g]=i(a[g],`${l}[${g}]`);return m}let u=Object.getPrototypeOf(a);if(!(u===Object.prototype||u===null))return a;let p=a,d={};o.set(a,d);for(let[m,g]of Object.entries(p))d[m]=i(g,l?`${l}.${m}`:m);return d};if(s)for(let[a,l]of Object.entries(s))t[a]=i(l,a);return{serializableGlobals:t,fnMap:n}},kc=s=>{if(typeof structuredClone=="function")try{structuredClone(s)}catch(e){let t=e instanceof Error?e.message:String(e);throw new Error(`RLM globals must be structured-cloneable: ${t}`)}};function xa(s){if(s==null||typeof s!="object")return String(s);try{return JSON.stringify(s,null,2)}catch{return String(s)}}function Oc(s,e=ha,t=0,n=new Set){if(t>e)return{name:"Error",message:"[cause chain truncated]"};if(s!==null&&typeof s=="object"){if(n.has(s))return{name:"Error",message:"[circular]"};n.add(s)}let r=s!==null&&typeof s=="object"&&s.name!=null?String(s.name):"Error",o=s!==null&&typeof s=="object"&&s.message!=null?String(s.message):xa(s),i=s!==null&&typeof s=="object"&&typeof s.stack=="string"?s.stack:void 0,a,l=s;if(l&&typeof l=="object"&&l.cause!==void 0&&t<e)try{let p=l.cause;p instanceof Error||p!==null&&typeof p=="object"&&("message"in p||"name"in p)?a=Oc(p,e,t+1,n):a={name:"Error",message:xa(p)}}catch{a={name:"Error",message:xa(l.cause)}}let u={name:r,message:o};i!==void 0&&(u.stack=i),a!==void 0&&(u.cause=a);let c=s;if(c&&typeof c=="object"&&"data"in c&&c.data!==void 0)try{typeof structuredClone=="function"?u.data=structuredClone(c.data):u.data=c.data}catch{}return u}function Mc(s){if(typeof s=="string")return new Error(s);if(!s||typeof s!="object")return new Error(String(s));let e=s.message!=null?String(s.message):"Unknown error",t=new Error(e);return t.name=s.name!=null?String(s.name):"Error",typeof s.stack=="string"&&(t.stack=s.stack),s.cause!==void 0&&(t.cause=Mc(s.cause)),s.data!==void 0&&(t.data=s.data),t}var ba=(i=>(i.NETWORK="network",i.STORAGE="storage",i.CODE_LOADING="code-loading",i.COMMUNICATION="communication",i.TIMING="timing",i.WORKERS="workers",i))(ba||{}),en=class{language="JavaScript";timeout;permissions;allowUnsafeNodeHostAccess;nodeWorkerPoolSize;debugNodeWorkerPool;outputMode;captureConsole;constructor(e){this.timeout=e?.timeout??3e4,this.permissions=e?.permissions??[],this.allowUnsafeNodeHostAccess=e?.allowUnsafeNodeHostAccess??!1,this.outputMode=e?.outputMode??"stdout",this.captureConsole=e?.captureConsole??this.outputMode==="stdout",this.nodeWorkerPoolSize=um(e?.nodeWorkerPoolSize),this.debugNodeWorkerPool=cm(e)}getUsageInstructions(){return["Don't wrap async code in (async()=>{ ... })() \u2014 the runtime automatically handles async execution.","State is session-scoped: all top-level declarations (`var`, `let`, `const`) persist across calls.","Bare assignment (e.g. `x = 1`) also persists via `globalThis`.",...this.outputMode==="stdout"?["Use `console.log(...)` output is captured as the execution result so use it to inspect intermediate values between steps instead of `return`."]:["Use `return` or a trailing expression to produce the execution result."]].map(t=>`- ${t}`).join(`
750
- `)}createSession(e){let t=Cc(),n=vs()?gm(t,this.nodeWorkerPoolSize):null;n&&this.debugNodeWorkerPool&&console.debug(`[AxJSRuntime] Node worker pool size: ${this.nodeWorkerPoolSize}`),n?.warm();let r=null,o=null,i=null,a=!1,l=this.timeout,u=0,{serializableGlobals:c,fnMap:p}=Sc(e,{nextFnId:()=>++u});kc(c);let d=new Map,m=0,g=A=>{let w=A.data;if(!w||typeof w!="object"||!("type"in w)||w.type===void 0)return;let v=w;if(v.type==="result"){if(typeof v.id!="number")return;let F=d.get(v.id);F&&(d.delete(v.id),v.error!==void 0?F.reject(Mc(v.error)):F.resolve(v.value));return}if(v.type==="fn-call"){if(typeof v.id!="number"||typeof v.name!="string")return;let F=p.get(v.name);if(!F){r?.postMessage({type:"fn-result",id:v.id,error:`Function "${v.name}" not found`});return}Promise.resolve().then(()=>F(...v.args??[])).then(O=>{r?.postMessage({type:"fn-result",id:v.id,value:O})}).catch(O=>{r?.postMessage({type:"fn-result",id:v.id,error:Oc(O)})})}},f=()=>{r&&(o==="node"&&n?n.release(r):r.terminate(),r=null,o=null),i=null},h=()=>{a=!0,f();for(let A of d.values())A.reject(new Error("Worker terminated"));d.clear()},y=A=>{f();for(let w of d.values())w.reject(A);d.clear()},x=A=>{A.postMessage({type:"init",globals:c,fnNames:[...p.keys()],permissions:[...this.permissions],allowUnsafeNodeHostAccess:this.allowUnsafeNodeHostAccess,outputMode:this.outputMode,captureConsole:this.captureConsole})};if(Tc()){r=Rc(t,this.permissions),o="browser",r.onmessage=g,r.onerror=y;try{x(r)}catch(A){throw h(),A}}let b=async()=>{if(!r){if(a)throw new Error("Session is closed");if(Tc()){r=Rc(t,this.permissions),o="browser",r.onmessage=g,r.onerror=y;try{x(r)}catch(A){throw h(),A}return}if(!vs())throw new Error("No worker runtime available: Web Worker is unavailable in this environment");i||(i=(n?n.acquire():Aa(t)).then(A=>{if(a)throw n?n.release(A):A.terminate(),new Error("Session is closed");r=A,o="node",r.onmessage=g,r.onerror=y;try{x(r)}catch(w){throw n?n.release(A):A.terminate(),r=null,o=null,w}})),await i}},R=(A,w)=>{if(a)return Promise.reject(new Error("Session is closed"));let v=w.signal;if(v?.aborted)return Promise.reject(new Error(`Aborted: ${v.reason??"execution aborted"}`));let F=++m;return new Promise((O,D)=>{let U=setTimeout(()=>{d.delete(F),f();for(let E of d.values())E.reject(new Error("Worker terminated"));d.clear(),D(new Error(w.timeoutMessage))},l),L=O,T=D,M=()=>{};if(d.set(F,{resolve:E=>{clearTimeout(U),M(),L(E)},reject:E=>{clearTimeout(U),M(),T(E)}}),v){let E=()=>{clearTimeout(U),d.delete(F),h(),T(new Error(`Aborted: ${v.reason??"execution aborted"}`))};v.addEventListener("abort",E,{once:!0}),M=()=>{v.removeEventListener("abort",E)}}b().then(()=>{if(!r)throw new Error("Worker unavailable");r.postMessage({...A,id:F})}).catch(E=>{d.get(F)&&(d.delete(F),clearTimeout(U),M(),T(E))})})};return{execute(A,w){if(a)return Promise.reject(new Error("Session is closed"));if(/['"]use strict['"]/.test(A))return Promise.resolve('[ERROR] "use strict" is not allowed in the runtime session. Remove it and try again.');let v=w?.reservedNames;if(v){for(let F of v)if(new RegExp(`(?:^|[;\\n])\\s*(?:(?:var|let|const)\\s+)?${F}\\s*=`).test(A))return Promise.resolve(`[ERROR] Cannot assign to or redeclare reserved runtime variable '${F}'. Use a different local variable name (for example: \`ctx\`) or access the original via \`inputs.${F}\`.`)}return R({type:"execute",code:A},{signal:w?.signal,timeoutMessage:"Execution timed out"})},async patchGlobals(A,w){if(!A||typeof A!="object"||Array.isArray(A))throw new Error("patchGlobals expects an object");let{serializableGlobals:v,fnMap:F}=Sc(A,{nextFnId:()=>++u});if(kc(v),Object.keys(v).length!==0){await R({type:"update-globals",globals:v},{signal:w?.signal,timeoutMessage:"Global patch timed out"});for(let[O,D]of Object.entries(v))c[O]=D;for(let[O,D]of F.entries())p.set(O,D)}},close(){h()}}}toFunction(){return{name:"javascriptInterpreter",description:"Execute JavaScript code in a persistent session and return output.",parameters:{type:"object",properties:{code:{type:"string",description:"JavaScript code to execute."}},required:["code"]},func:async({code:e},t)=>{let n=this.createSession();try{return await n.execute(e,{signal:t?.abortSignal})}finally{n.close()}}}}};function Ec(s){return new en(s)}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=[];promptFunctions=[];resourceFunctions=[];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"),this.capabilities.tools&&await this.discoverFunctions(),this.capabilities.prompts&&await this.discoverPromptFunctions(),this.capabilities.resources&&await this.discoverResourceFunctions()}async discoverFunctions(){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 discoverPromptFunctions(){let e;do{let t=await this.listPrompts(e);for(let n of t.prompts??[])this.promptFunctions.push(this.promptToFunction(n));e=t.nextCursor}while(e)}async discoverResourceFunctions(){let e;do{let t=await this.listResources(e);for(let n of t.resources??[])this.resourceFunctions.push(this.resourceToFunction(n));e=t.nextCursor}while(e);e=void 0;do{let t=await this.listResourceTemplates(e);for(let n of t.resourceTemplates??[])this.resourceFunctions.push(this.resourceTemplateToFunction(n));e=t.nextCursor}while(e)}promptToFunction(e){let t=`prompt_${e.name}`,n=this.options.functionOverrides?.find(o=>o.name===t),r=e.arguments?.length?{type:"object",properties:Object.fromEntries(e.arguments.map(o=>[o.name,{type:"string",description:o.description??""}])),required:e.arguments.filter(o=>o.required).map(o=>o.name)}:void 0;return{name:n?.updates.name??t,description:n?.updates.description??e.description??`Get the ${e.name} prompt`,parameters:r,func:async o=>{let i=await this.getPrompt(e.name,o);return this.formatPromptMessages(i.messages)}}}resourceToFunction(e){let t=`resource_${this.sanitizeName(e.name)}`,n=this.options.functionOverrides?.find(r=>r.name===t);return{name:n?.updates.name??t,description:n?.updates.description??e.description??`Read ${e.name}`,parameters:void 0,func:async()=>{let r=await this.readResource(e.uri);return this.formatResourceContents(r.contents)}}}resourceTemplateToFunction(e){let t=`resource_${this.sanitizeName(e.name)}`,n=this.options.functionOverrides?.find(o=>o.name===t),r=this.parseUriTemplate(e.uriTemplate);return{name:n?.updates.name??t,description:n?.updates.description??e.description??`Read ${e.name}`,parameters:r.length?{type:"object",properties:Object.fromEntries(r.map(o=>[o,{type:"string",description:`Value for ${o}`}])),required:r}:void 0,func:async o=>{let i=this.expandUriTemplate(e.uriTemplate,o??{}),a=await this.readResource(i);return this.formatResourceContents(a.contents)}}}formatPromptMessages(e){return e.map(t=>{let n=t.role==="user"?"User":"Assistant",r=this.extractContent(t.content);return`${n}: ${r}`}).join(`
772
+ `),t?`${t}${e}`:e}var Dc=()=>typeof Worker<"u"&&typeof Blob<"u"&&typeof URL<"u"&&typeof URL.createObjectURL=="function",Es=()=>typeof process<"u"&&!!process.versions?.node,Gm=()=>!!globalThis.Deno?.version?.deno,Um=()=>globalThis.Deno?.version?.deno??null,Bm=s=>{let e=/^(\d+)\.(\d+)\.(\d+)$/.exec(s.trim());return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3])}:null},Gc=s=>Number.isFinite(s)?Math.max(1,Math.min($c,Math.floor(s))):Ia,jm=()=>{if(!Es())return null;let e=globalThis.process?.getBuiltinModule;if(typeof e!="function")return null;let n=e("node:os")?.availableParallelism;if(typeof n!="function")return null;let r=n();return Number.isFinite(r)&&r>0?r:null},qm=s=>{if(s!==void 0)return Gc(s);let e=jm();return e?Gc(Math.ceil(e/2)):Ia},zm=s=>s?.debugNodeWorkerPool?!0:(globalThis.process?.env??{}).AX_RLM_DEBUG_NODE_POOL==="1",Hm=s=>{let e=new Set(s),t={};return e.has("network")&&(t.net=!0),Object.keys(t).length>0?t:"none"},Km=(s,e)=>{let t=Um(),n=t?Bm(t):null;if(n?n.major>=1:!0)try{return new Worker(s,{type:"module",deno:{permissions:Hm(e)}})}catch{}return new Worker(s,{type:"module"})},Uc=(s,e)=>{let t=new Blob([s],{type:"application/javascript"}),n=URL.createObjectURL(t),r=Gm()?Km(n,e):new Worker(n),o=!1,i=()=>{o||(URL.revokeObjectURL(n),o=!0)},a={postMessage:l=>r.postMessage(l),terminate:()=>{r.terminate(),i()},onmessage:null,onerror:null};return r.onmessage=l=>{a.onmessage?.({data:l.data})},r.onerror=l=>{a.onerror?.(new Error(l.message||"Worker error"))},a},Sa=async s=>{let e="node:worker_threads",{Worker:t}=await import(e),n=new t(s,{eval:!0}),r=null,o=null,i=!1;n.on("error",l=>{o?o(l):r=l}),n.on("exit",l=>{if(i=!0,l!==0&&!r){let u=new Error(`Worker exited with code ${l}`);o?o(u):r=u}}),n.on("message",l=>{a.onmessage?.({data:l})});let a={postMessage:l=>n.postMessage(l),terminate:()=>{n.terminate()},onmessage:null,get onerror(){return o},set onerror(l){if(o=l,l&&r){let u=r;r=null,l(u)}},get exited(){return i}};return a},ka=class{source;maxSize;idle=[];pendingCreates=0;constructor(e,t){this.source=e,this.maxSize=t}warm(){if(Es())for(;this.idle.length+this.pendingCreates<this.maxSize;)this.pendingCreates+=1,Sa(this.source).then(e=>{e.onmessage=null,e.onerror=null,this.idle.push(e)}).catch(()=>{}).finally(()=>{this.pendingCreates-=1})}async acquire(){for(;this.idle.length>0;){let e=this.idle.pop();if(!e.exited)return this.warm(),e}return this.warm(),Sa(this.source)}release(e){e.onmessage=null,e.onerror=null,e.terminate(),this.warm()}},Bc=new Map,Wm=(s,e)=>`${e}:${s}`,Vm=(s,e)=>{let t=Wm(s,e),n=Bc.get(t);if(n)return n;let r=new ka(s,e);return Bc.set(t,r),r},jc=(s,e)=>{let t={},n=new Map,r=0,o=new WeakMap,i=(a,l)=>{if(typeof a=="function"){let g=`fn_${e?.nextFnId?e.nextFnId():++r}_${l||"root"}`;return n.set(g,a),{[Ca]:g}}if(!a||typeof a!="object")return a;if(o.has(a))return o.get(a);if(Array.isArray(a)){let m=[];o.set(a,m);for(let g=0;g<a.length;g+=1)m[g]=i(a[g],`${l}[${g}]`);return m}let u=Object.getPrototypeOf(a);if(!(u===Object.prototype||u===null))return a;let p=a,d={};o.set(a,d);for(let[m,g]of Object.entries(p))d[m]=i(g,l?`${l}.${m}`:m);return d};if(s)for(let[a,l]of Object.entries(s))t[a]=i(l,a);return{serializableGlobals:t,fnMap:n}},qc=s=>{if(typeof structuredClone=="function")try{structuredClone(s)}catch(e){let t=e instanceof Error?e.message:String(e);throw new Error(`RLM globals must be structured-cloneable: ${t}`)}},wa=s=>!!s&&/[A-Za-z0-9_$]/.test(s),Ra=s=>!!s&&/[A-Za-z_$]/.test(s),Jm=(s,e)=>{let t=new Set(e);for(let m of Os(s))if(t.has(m))return m;let n=ks(s),r=n.length,o=0,i=0,a=0,l=m=>{let g=m;for(;g<r&&/\s/.test(n[g]??"");)g++;return g},u=m=>{let g=m;for(;g>=0&&/\s/.test(n[g]??"");)g--;return g},c=m=>{let g=u(m-1);if(g<0)return!0;let f=n[g];return f===`
773
+ `||f===";"||f==="{"||f==="}"},p=()=>{let m=o;for(;o<r&&wa(n[o]);)o++;return n.slice(m,o)},d=m=>{let g=n.slice(m,m+2);return n.slice(m,m+3)==="==="||g==="=="||g==="=>"?!1:n[m]==="="||["+=","-=","*=","/=","%=","&=","|=","^=","&&=","||=","??=","**=","<<=",">>=",">>>="].some(h=>n.startsWith(h,m))};for(;o<r;){let m=n[o];if(m==="{"){i++,o++;continue}if(m==="}"){i--,o++;continue}if(m==="("){a++,o++;continue}if(m===")"){a--,o++;continue}if(i===0&&a===0&&Ra(m)){let g=o,f=p();if((f==="function"||f==="class")&&c(g)){let h=l(o);if(Ra(n[h])){let A=h+1;for(;A<r&&wa(n[A]);)A++;let x=n.slice(h,A);if(t.has(x))return x}continue}if(f==="async"&&c(g)){let h=l(o);if(n.startsWith("function",h)){let A=l(h+8);if(Ra(n[A])){let x=A+1;for(;x<r&&wa(n[x]);)x++;let b=n.slice(A,x);if(t.has(b))return b}}continue}if(t.has(f)){let h=u(g-1),A=h>=0?n[h]:void 0,x=l(o),b=A==="."||A==="?"||A==="["&&n[x]==="]",C=n.startsWith("++",x)||n.startsWith("--",x)||h>0&&(n.slice(h-1,h+1)==="++"||n.slice(h-1,h+1)==="--");if(!b&&(C||d(x)))return f}continue}o++}};function va(s){if(s==null||typeof s!="object")return String(s);try{return JSON.stringify(s,null,2)}catch{return String(s)}}function zc(s,e=Ta,t=0,n=new Set){if(t>e)return{name:"Error",message:"[cause chain truncated]"};if(s!==null&&typeof s=="object"){if(n.has(s))return{name:"Error",message:"[circular]"};n.add(s)}let r=s!==null&&typeof s=="object"&&s.name!=null?String(s.name):"Error",o=s!==null&&typeof s=="object"&&s.message!=null?String(s.message):va(s),i=s!==null&&typeof s=="object"&&typeof s.stack=="string"?s.stack:void 0,a,l=s;if(l&&typeof l=="object"&&l.cause!==void 0&&t<e)try{let p=l.cause;p instanceof Error||p!==null&&typeof p=="object"&&("message"in p||"name"in p)?a=zc(p,e,t+1,n):a={name:"Error",message:va(p)}}catch{a={name:"Error",message:va(l.cause)}}let u={name:r,message:o};i!==void 0&&(u.stack=i),a!==void 0&&(u.cause=a);let c=s;if(c&&typeof c=="object"&&"data"in c&&c.data!==void 0)try{typeof structuredClone=="function"?u.data=structuredClone(c.data):u.data=c.data}catch{}return u}function Hc(s){if(typeof s=="string")return new Error(s);if(!s||typeof s!="object")return new Error(String(s));let e=s.message!=null?String(s.message):"Unknown error",t=new Error(e);return t.name=s.name!=null?String(s.name):"Error",typeof s.stack=="string"&&(t.stack=s.stack),s.cause!==void 0&&(t.cause=Hc(s.cause)),s.data!==void 0&&(t.data=s.data),t}var Oa=(i=>(i.NETWORK="network",i.STORAGE="storage",i.CODE_LOADING="code-loading",i.COMMUNICATION="communication",i.TIMING="timing",i.WORKERS="workers",i))(Oa||{}),Qt=class{language="JavaScript";timeout;permissions;allowUnsafeNodeHostAccess;nodeWorkerPoolSize;debugNodeWorkerPool;outputMode;captureConsole;constructor(e){this.timeout=e?.timeout??3e4,this.permissions=e?.permissions??[],this.allowUnsafeNodeHostAccess=e?.allowUnsafeNodeHostAccess??!1,this.outputMode=e?.outputMode??"stdout",this.captureConsole=e?.captureConsole??this.outputMode==="stdout",this.nodeWorkerPoolSize=qm(e?.nodeWorkerPoolSize),this.debugNodeWorkerPool=zm(e)}getUsageInstructions(){return["Don't wrap async code in (async()=>{ ... })() \u2014 the runtime automatically handles async execution.","State is session-scoped: all top-level declarations (`var`, `let`, `const`) persist across calls.","Bare assignment (e.g. `x = 1`) also persists via `globalThis`.",...this.outputMode==="stdout"?["Use `console.log(...)` output is captured as the execution result so use it to inspect intermediate values between steps instead of `return`."]:["Use `return` or a trailing expression to produce the execution result."]].map(t=>`- ${t}`).join(`
774
+ `)}createSession(e){let t=Lc(),n=Es()?Vm(t,this.nodeWorkerPoolSize):null;n&&this.debugNodeWorkerPool&&console.debug(`[AxJSRuntime] Node worker pool size: ${this.nodeWorkerPoolSize}`),n?.warm();let r=null,o=null,i=null,a=!1,l=this.timeout,u=0,{serializableGlobals:c,fnMap:p}=jc(e,{nextFnId:()=>++u});qc(c);let d=new Map,m=0,g=[],f=null,h=k=>{let S=k.data;if(!S||typeof S!="object"||!("type"in S)||S.type===void 0)return;let $=S;if($.type==="result"){if(typeof $.id!="number")return;let G=d.get($.id);G&&(d.delete($.id),$.error!==void 0?G.reject(Hc($.error)):G.resolve($.value));return}if($.type==="fn-call"){if(typeof $.id!="number"||typeof $.name!="string")return;let G=p.get($.name);if(!G){r?.postMessage({type:"fn-result",id:$.id,error:`Function "${$.name}" not found`});return}Promise.resolve().then(()=>G(...$.args??[])).then(L=>{r?.postMessage({type:"fn-result",id:$.id,value:L})}).catch(L=>{r?.postMessage({type:"fn-result",id:$.id,error:zc(L)})})}},A=()=>{r&&(o==="node"&&n?n.release(r):r.terminate(),r=null,o=null),i=null},x=()=>{a=!0,A();for(let k of g)!k.started&&!k.settled&&(k.settled=!0,k.signal&&k.onAbort&&k.signal.removeEventListener("abort",k.onAbort),k.reject(new Error("Worker terminated")));g.length=0;for(let k of d.values())k.reject(new Error("Worker terminated"));d.clear()},b=k=>{A();for(let S of d.values())S.reject(k);d.clear()},C=k=>{k.postMessage({type:"init",globals:c,fnNames:[...p.keys()],permissions:[...this.permissions],allowUnsafeNodeHostAccess:this.allowUnsafeNodeHostAccess,outputMode:this.outputMode,captureConsole:this.captureConsole})};if(Dc()){r=Uc(t,this.permissions),o="browser",r.onmessage=h,r.onerror=b;try{C(r)}catch(k){throw x(),k}}let I=async()=>{if(!r){if(a)throw new Error("Session is closed");if(Dc()){r=Uc(t,this.permissions),o="browser",r.onmessage=h,r.onerror=b;try{C(r)}catch(k){throw x(),k}return}if(!Es())throw new Error("No worker runtime available: Web Worker is unavailable in this environment");i||(i=(n?n.acquire():Sa(t)).then(k=>{if(a)throw n?n.release(k):k.terminate(),new Error("Session is closed");r=k,o="node",r.onmessage=h,r.onerror=b;try{C(r)}catch(S){throw n?n.release(k):k.terminate(),r=null,o=null,S}})),await i}},v=(k,S)=>{if(a)return Promise.reject(new Error("Session is closed"));let $=S.signal;if($?.aborted)return Promise.reject(new Error(`Aborted: ${$.reason??"execution aborted"}`));let G=++m;return new Promise((L,w)=>{let R=setTimeout(()=>{d.delete(G),A();for(let N of d.values())N.reject(new Error("Worker terminated"));d.clear(),w(new Error(S.timeoutMessage))},l),E=L,_=w,M=()=>{};if(d.set(G,{resolve:N=>{clearTimeout(R),M(),E(N)},reject:N=>{clearTimeout(R),M(),_(N)}}),$){let N=()=>{clearTimeout(R),d.delete(G),x(),_(new Error(`Aborted: ${$.reason??"execution aborted"}`))};$.addEventListener("abort",N,{once:!0}),M=()=>{$.removeEventListener("abort",N)}}I().then(()=>{if(!r)throw new Error("Worker unavailable");r.postMessage({...k,id:G})}).catch(N=>{d.get(G)&&(d.delete(G),clearTimeout(R),M(),_(N))})})},O=(k,S)=>a?Promise.reject(new Error("Session is closed")):k?.aborted?Promise.reject(new Error(`Aborted: ${k.reason??"execution aborted"}`)):new Promise(($,G)=>{let L={started:!1,settled:!1,signal:k,resolve:$,reject:G,operation:S};if(k){let R=()=>{if(L.settled)return;L.settled=!0;let E=g.indexOf(L);E!==-1&&g.splice(E,1),k.removeEventListener("abort",R),G(new Error(`Aborted: ${k.reason??"execution aborted"}`))};L.onAbort=R,k.addEventListener("abort",R,{once:!0})}g.push(L);let w=()=>{if(f)return;let R=g.find(_=>!_.started&&!_.settled);if(!R)return;let E=()=>{f=null,w()};f=(async()=>{if(!R.settled){if(a){R.settled=!0,R.signal&&R.onAbort&&R.signal.removeEventListener("abort",R.onAbort),R.reject(new Error("Worker terminated"));return}if(R.signal?.aborted){R.settled=!0,R.onAbort&&R.signal.removeEventListener("abort",R.onAbort),R.reject(new Error(`Aborted: ${R.signal.reason??"execution aborted"}`));return}R.started=!0;try{let _=await R.operation();if(R.settled)return;R.settled=!0,R.signal&&R.onAbort&&R.signal.removeEventListener("abort",R.onAbort),R.resolve(_)}catch(_){if(R.settled)return;R.settled=!0,R.signal&&R.onAbort&&R.signal.removeEventListener("abort",R.onAbort),R.reject(_)}finally{let _=g.indexOf(R);_!==-1&&g.splice(_,1),E()}}})().catch(()=>{E()})};w()});return{execute(k,S){if(a)return Promise.reject(new Error("Session is closed"));if(/['"]use strict['"]/.test(k))return Promise.resolve('[ERROR] "use strict" is not allowed in the runtime session. Remove it and try again.');let $=S?.reservedNames;if($){let G=Jm(k,$);if(G)return Promise.resolve(`[ERROR] Cannot assign to, redeclare, or shadow reserved runtime variable '${G}'. Use a different local variable name (for example: \`ctx\`) or access the original via \`inputs.${G}\`.`)}return O(S?.signal,()=>v({type:"execute",code:k},{signal:S?.signal,timeoutMessage:"Execution timed out"}))},async patchGlobals(k,S){if(!k||typeof k!="object"||Array.isArray(k))throw new Error("patchGlobals expects an object");let{serializableGlobals:$,fnMap:G}=jc(k,{nextFnId:()=>++u});if(qc($),Object.keys($).length!==0){await O(S?.signal,()=>v({type:"update-globals",globals:$},{signal:S?.signal,timeoutMessage:"Global patch timed out"}));for(let[L,w]of Object.entries($))c[L]=w;for(let[L,w]of G.entries())p.set(L,w)}},close(){x()}}}toFunction(){return{name:"javascriptInterpreter",description:"Execute JavaScript code in a persistent session and return output.",parameters:{type:"object",properties:{code:{type:"string",description:"JavaScript code to execute."}},required:["code"]},func:async({code:e},t)=>{let n=this.createSession();try{return await n.execute(e,{signal:t?.abortSignal})}finally{n.close()}}}}};function Kc(s){return new Qt(s)}var Ps=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=[];promptFunctions=[];resourceFunctions=[];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"),this.capabilities.tools&&await this.discoverFunctions(),this.capabilities.prompts&&await this.discoverPromptFunctions(),this.capabilities.resources&&await this.discoverResourceFunctions()}async discoverFunctions(){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 discoverPromptFunctions(){let e;do{let t=await this.listPrompts(e);for(let n of t.prompts??[])this.promptFunctions.push(this.promptToFunction(n));e=t.nextCursor}while(e)}async discoverResourceFunctions(){let e;do{let t=await this.listResources(e);for(let n of t.resources??[])this.resourceFunctions.push(this.resourceToFunction(n));e=t.nextCursor}while(e);e=void 0;do{let t=await this.listResourceTemplates(e);for(let n of t.resourceTemplates??[])this.resourceFunctions.push(this.resourceTemplateToFunction(n));e=t.nextCursor}while(e)}promptToFunction(e){let t=`prompt_${e.name}`,n=this.options.functionOverrides?.find(o=>o.name===t),r=e.arguments?.length?{type:"object",properties:Object.fromEntries(e.arguments.map(o=>[o.name,{type:"string",description:o.description??""}])),required:e.arguments.filter(o=>o.required).map(o=>o.name)}:void 0;return{name:n?.updates.name??t,description:n?.updates.description??e.description??`Get the ${e.name} prompt`,parameters:r,func:async o=>{let i=await this.getPrompt(e.name,o);return this.formatPromptMessages(i.messages)}}}resourceToFunction(e){let t=`resource_${this.sanitizeName(e.name)}`,n=this.options.functionOverrides?.find(r=>r.name===t);return{name:n?.updates.name??t,description:n?.updates.description??e.description??`Read ${e.name}`,parameters:void 0,func:async()=>{let r=await this.readResource(e.uri);return this.formatResourceContents(r.contents)}}}resourceTemplateToFunction(e){let t=`resource_${this.sanitizeName(e.name)}`,n=this.options.functionOverrides?.find(o=>o.name===t),r=this.parseUriTemplate(e.uriTemplate);return{name:n?.updates.name??t,description:n?.updates.description??e.description??`Read ${e.name}`,parameters:r.length?{type:"object",properties:Object.fromEntries(r.map(o=>[o,{type:"string",description:`Value for ${o}`}])),required:r}:void 0,func:async o=>{let i=this.expandUriTemplate(e.uriTemplate,o??{}),a=await this.readResource(i);return this.formatResourceContents(a.contents)}}}formatPromptMessages(e){return e.map(t=>{let n=t.role==="user"?"User":"Assistant",r=this.extractContent(t.content);return`${n}: ${r}`}).join(`
751
775
 
752
776
  `)}extractContent(e){if(e.type==="text")return e.text;if(e.type==="image")return`[Image: ${e.mimeType}]`;if(e.type==="resource"){let t=e.resource;return"text"in t?t.text:`[Binary: ${t.uri}]`}return""}formatResourceContents(e){return e.map(t=>"text"in t?t.text:`[Binary: ${t.uri}]`).join(`
753
- `)}sanitizeName(e){return e.replace(/[^a-zA-Z0-9_]/g,"_")}parseUriTemplate(e){return(e.match(/\{([^}]+)\}/g)??[]).map(n=>n.slice(1,-1))}expandUriTemplate(e,t){return e.replace(/\{([^}]+)\}/g,(n,r)=>t[r]??"")}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,...this.promptFunctions,...this.resourceFunctions]}getCapabilities(){return{tools:this.capabilities.tools??!1,resources:this.capabilities.resources??!1,prompts:this.capabilities.prompts??!1}}hasToolsCapability(){return this.capabilities.tools??!1}hasPromptsCapability(){return this.capabilities.prompts??!1}hasResourcesCapability(){return this.capabilities.resources??!1}async listPrompts(e){if(!this.capabilities.prompts)throw new Error("Prompts are not supported");let t=e?{cursor:e}:void 0,{result:n}=await this.sendRequest("prompts/list",t);return n}async getPrompt(e,t){if(!this.capabilities.prompts)throw new Error("Prompts are not supported");let{result:n}=await this.sendRequest("prompts/get",{name:e,arguments:t});return n}async listResources(e){if(!this.capabilities.resources)throw new Error("Resources are not supported");let t=e?{cursor:e}:void 0,{result:n}=await this.sendRequest("resources/list",t);return n}async listResourceTemplates(e){if(!this.capabilities.resources)throw new Error("Resources are not supported");let t=e?{cursor:e}:void 0,{result:n}=await this.sendRequest("resources/templates/list",t);return n}async readResource(e){if(!this.capabilities.resources)throw new Error("Resources are not supported");let{result:t}=await this.sendRequest("resources/read",{uri:e});return t}async subscribeResource(e){if(!this.capabilities.resources)throw new Error("Resources are not supported");await this.sendRequest("resources/subscribe",{uri:e})}async unsubscribeResource(e){if(!this.capabilities.resources)throw new Error("Resources are not supported");await this.sendRequest("resources/unsubscribe",{uri:e})}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=Ye(),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 Pc(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 Fc(s){let t=new TextEncoder().encode(s),n=await Oa().subtle.digest("SHA-256",t);return new Uint8Array(n)}async function Ia(){return Pc(await Fc(Ye()+Math.random().toString(36)))}async function _c(s){return Pc(await Fc(s))}async function ks(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 Nc(s){let e=new URLSearchParams;for(let[t,n]of Object.entries(s))n!==void 0&&e.set(t,n);return e.toString()}function Wr(s){return s.endsWith("/")?s.slice(0,-1):s}function fm(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 $c(s,e){let t=fm(e);if(t){let a=await ks(t),l=Wr(new URL(s).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(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 ks(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){i=l}throw new Error(`Failed to resolve protected resource metadata via well-known endpoints. Last error: ${String(i)}`)}async function Lc(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 ks(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 tr=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 Lc(e);return this.asMetaCache.set(e,t),t}async ensureAccessToken(e){if(!this.oauth)return null;let{resource:t,issuers:n}=await $c(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 x=await this.refreshToken(i.refreshToken,t,r,o);return await this.setStoredToken(t,r,x),{token:x,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 Ia(),c=await _c(u),p=await Ia(),d=this.oauth.scopes?.join(" "),m=`${o.authorization_endpoint}?${Nc({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,y=await this.exchangeCodeForToken({asMeta:o,code:g,codeVerifier:u,client:l,redirectUri:h,resource:t});return await this.setStoredToken(t,r,y),{token:y,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 Os=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 tr(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(`
777
+ `)}sanitizeName(e){return e.replace(/[^a-zA-Z0-9_]/g,"_")}parseUriTemplate(e){return(e.match(/\{([^}]+)\}/g)??[]).map(n=>n.slice(1,-1))}expandUriTemplate(e,t){return e.replace(/\{([^}]+)\}/g,(n,r)=>t[r]??"")}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,...this.promptFunctions,...this.resourceFunctions]}getCapabilities(){return{tools:this.capabilities.tools??!1,resources:this.capabilities.resources??!1,prompts:this.capabilities.prompts??!1}}hasToolsCapability(){return this.capabilities.tools??!1}hasPromptsCapability(){return this.capabilities.prompts??!1}hasResourcesCapability(){return this.capabilities.resources??!1}async listPrompts(e){if(!this.capabilities.prompts)throw new Error("Prompts are not supported");let t=e?{cursor:e}:void 0,{result:n}=await this.sendRequest("prompts/list",t);return n}async getPrompt(e,t){if(!this.capabilities.prompts)throw new Error("Prompts are not supported");let{result:n}=await this.sendRequest("prompts/get",{name:e,arguments:t});return n}async listResources(e){if(!this.capabilities.resources)throw new Error("Resources are not supported");let t=e?{cursor:e}:void 0,{result:n}=await this.sendRequest("resources/list",t);return n}async listResourceTemplates(e){if(!this.capabilities.resources)throw new Error("Resources are not supported");let t=e?{cursor:e}:void 0,{result:n}=await this.sendRequest("resources/templates/list",t);return n}async readResource(e){if(!this.capabilities.resources)throw new Error("Resources are not supported");let{result:t}=await this.sendRequest("resources/read",{uri:e});return t}async subscribeResource(e){if(!this.capabilities.resources)throw new Error("Resources are not supported");await this.sendRequest("resources/subscribe",{uri:e})}async unsubscribeResource(e){if(!this.capabilities.resources)throw new Error("Resources are not supported");await this.sendRequest("resources/unsubscribe",{uri:e})}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=Ge(),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 Wc(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 Vc(s){let t=new TextEncoder().encode(s),n=await ja().subtle.digest("SHA-256",t);return new Uint8Array(n)}async function Ma(){return Wc(await Vc(Ge()+Math.random().toString(36)))}async function Jc(s){return Wc(await Vc(s))}async function Fs(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 Yc(s){let e=new URLSearchParams;for(let[t,n]of Object.entries(s))n!==void 0&&e.set(t,n);return e.toString()}function Kr(s){return s.endsWith("/")?s.slice(0,-1):s}function Ym(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 Qc(s,e){let t=Ym(e);if(t){let a=await Fs(t),l=Kr(new URL(s).toString().split("?")[0]),u=Kr(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 Fs(a.url),u=Kr(l.resource??""),c=Kr(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 Xc(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 Fs(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 Qn=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 Xc(e);return this.asMetaCache.set(e,t),t}async ensureAccessToken(e){if(!this.oauth)return null;let{resource:t,issuers:n}=await Qc(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 x=await this.refreshToken(i.refreshToken,t,r,o);return await this.setStoredToken(t,r,x),{token:x,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 Ma(),c=await Jc(u),p=await Ma(),d=this.oauth.scopes?.join(" "),m=`${o.authorization_endpoint}?${Yc({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,A=await this.exchangeCodeForToken({asMeta:o,code:g,codeVerifier:u,client:l,redirectUri:h,resource:t});return await this.setStoredToken(t,r,A),{token:A,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 _s=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 Qn(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(`
754
778
  `);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(`
755
- `);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 Ms=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 tr(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(`
756
- `);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 Dc(s){return s.match(/^(\w+Error:\s*.{0,60})/m)?.[1]??s.slice(0,80)}function hm(s){let e=[],t=/(?:^|[\n;])\s*(?:var|let|const)\s+(\w+)/g,n=t.exec(s);for(;n!==null;)n[1]&&e.push(n[1]),n=t.exec(s);return e}var xm=new Set(["var","let","const","function","return","if","else","for","while","do","switch","case","break","continue","try","catch","finally","throw","new","delete","typeof","void","in","of","instanceof","this","class","extends","super","import","export","default","from","as","async","await","yield","true","false","null","undefined","console","log"]);function Am(s){let e=/\b([a-zA-Z_$][a-zA-Z0-9_$]*)\b/g,t=new Set,n=e.exec(s);for(;n!==null;)n[1]&&!xm.has(n[1])&&t.add(n[1]),n=e.exec(s);return t}function ym(s,e){let t=s.tags.includes("error"),n=e.tags.includes("error");if(t&&!n){s.rank=0,Vr(s,"dead-end");return}if(t&&n){let r=Dc(s.output),o=Dc(e.output);r!==o?(s.rank=3,Vr(s,"pivot")):(s.rank=0,Vr(s,"dead-end"));return}if(!t&&!n){let r=hm(s.code),o=Am(e.code);r.filter(a=>o.has(a)).length>0?(s.rank=5,Vr(s,"foundational")):(s.rank=1,Vr(s,"superseded"));return}}function Vr(s,e){s.tags.includes(e)||s.tags.push(e)}async function bm(s,e,t,n){let r=`Summarize this resolved error in exactly one line (20-40 tokens).
779
+ `);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 Ns=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 Qn(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(`
780
+ `);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 Zc(s){return s.match(/^(\w+Error:\s*.{0,60})/m)?.[1]??s.slice(0,80)}function tp(s){return Os(s)}var Qm=new Set(["var","let","const","function","return","if","else","for","while","do","switch","case","break","continue","try","catch","finally","throw","new","delete","typeof","void","in","of","instanceof","this","class","extends","super","import","export","default","from","as","async","await","yield","true","false","null","undefined","console","log"]);function np(s){let e=ks(s),t=/\b([a-zA-Z_$][a-zA-Z0-9_$]*)\b/g,n=new Set,r=t.exec(e);for(;r!==null;)r[1]&&!Qm.has(r[1])&&n.add(r[1]),r=t.exec(e);return n}function Vr(s,e=120){let t=s.replace(/\s+/g," ").trim();return t.length<=e?t:`${t.slice(0,e-3)}...`}function Xm(s){return/\b(final|ask_clarification)\s*\(/.test(s)}function Zm(s){return s.tags.includes("error")?"error":Xm(s.code)?"finalize":/\b(llmQuery|listModuleFunctions|getFunctionDefinitions)\s*\(/.test(s.code)?"query":(s.producedVars?.length??0)>0?"transform":"explore"}function eg(s){let e=s.producedVars??[];if(e.length>0)return`Created live runtime values: ${e.join(", ")}`;switch(s.stepKind){case"query":return"Gathered external or semantic evidence without creating durable runtime values";case"finalize":return"Prepared completion payload for the responder";case"error":return"Did not produce a durable runtime state update";default:return"Inspected runtime state without creating durable runtime values"}}function Pa(s){if(s.tombstone)return s.tombstone;let e=s.stepKind==="error"?"Error step":s.stepKind==="query"?"Query step":s.stepKind==="transform"?"Transform step":s.stepKind==="finalize"?"Finalize step":"Explore step",t=Vr(s.output||"(no output)"),n=Vr(s.actorFieldsOutput.replace(/^Actor fields:\s*/i,""),80),r=s.stateDelta??"No durable runtime state update",o=n?` Actor fields: ${n}.`:"";return`[SUMMARY]: ${e}. ${r}. Result: ${t}.${o}`}function Xn(s){s.producedVars||(s.producedVars=tp(s.code)),s.referencedVars||(s.referencedVars=[...np(s.code)]),s.stepKind||(s.stepKind=Zm(s)),s.stateDelta||(s.stateDelta=eg(s)),s.summary||(s.summary=Pa(s))}function tg(s){let e=Array.from({length:s.length},()=>new Set),t=new Set;for(let n=s.length-1;n>=0;n--){e[n]=new Set(t);for(let r of s[n]?.referencedVars??[])t.add(r)}return e}function ng(s,e){let t=e.actionReplay??"full",n=Math.max(e.recentFullActions??1,0);for(let i of s)Xn(i);let r=tg(s),o=Math.max(s.length-n,0);s.forEach((i,a)=>{if(i.tombstone){i.replayMode="full";return}if(t==="full"){i.replayMode="full";return}let l=a>=o,u=i.tags.includes("error"),c=i.output.startsWith("[POLICY]"),p=r[a]??new Set,m=(i.producedVars??[]).some(g=>p.has(g));if(l||u||c){i.replayMode="full";return}if(t==="adaptive"&&m){i.replayMode="full";return}i.replayMode="omit"})}function rg(s,e){let t=s.tags.includes("error"),n=e.tags.includes("error");if(t&&!n){s.rank=0,Wr(s,"dead-end");return}if(t&&n){let r=Zc(s.output),o=Zc(e.output);r!==o?(s.rank=3,Wr(s,"pivot")):(s.rank=0,Wr(s,"dead-end"));return}if(!t&&!n){let r=tp(s.code),o=np(e.code);r.filter(a=>o.has(a)).length>0?(s.rank=5,Wr(s,"foundational")):(s.rank=1,Wr(s,"superseded"));return}}function Wr(s,e){s.tags.includes(e)||s.tags.push(e)}async function og(s,e,t,n){let r=`Summarize this resolved error in exactly one line (20-40 tokens).
757
781
 
758
782
  Error code:
759
783
  \`\`\`javascript
@@ -768,16 +792,45 @@ Resolution code:
768
792
  ${n.code.slice(0,500)}
769
793
  \`\`\`
770
794
 
771
- Format: [TOMBSTONE]: Resolved [Error Type] in [Module]. Fix: [1-line-summary]. Avoid: [failed-approach].`;try{let o=await s.chat({chatPrompt:[{role:"system",content:"You are a concise code summarizer."},{role:"user",content:r}],...e?.model?{model:e.model}:{},...e?.modelConfig?{modelConfig:e.modelConfig}:{}});if(!Im(o)&&o.results?.[0]?.content){let i=o.results[0].content;return typeof i=="string"?i.trim():String(i)}return Gc}catch{return Gc}}var Gc="[TOMBSTONE]: Error was resolved in subsequent turn.";function Im(s){return typeof s=="object"&&s!==null&&"getReader"in s}async function Ca(s,e,t,n){let r=s[e];if(!r)return;let o=r.tags.includes("error");if(t.hindsightEvaluation&&s.length>=2){let i=s[s.length-2];ym(i,r)}if(t.tombstoning&&n){for(let i of s)if(i.tags.includes("error")&&!i.tombstone&&!i._tombstonePromise){let a=s.indexOf(i),l=s[a+1];if(l&&!l.tags.includes("error")){let u=typeof t.tombstoning=="object"?t.tombstoning:void 0;i._tombstonePromise=bm(n,u,i,l),i._tombstonePromise.then(c=>{i.tombstone=c}).catch(()=>{}).finally(()=>{i._tombstonePromise=void 0})}}}if(t.errorPruning&&!o){let i=s.filter(a=>!a.tags.includes("error")||a.tombstone!=null||a._tombstonePromise!=null);s.length=0,s.push(...i)}if(t.hindsightEvaluation){let i=s.filter((a,l)=>l===s.length-1||a.rank===void 0||a.rank>=t.pruneRank||a.tombstone!=null||a._tombstonePromise!=null);s.length=0,s.push(...i)}}function Es(s){return s.length===0?"":s.map(e=>e.tombstone?`Action ${e.turn}:
772
- ${e.tombstone}`:`Action ${e.turn}:
795
+ Format: [TOMBSTONE]: Resolved [Error Type] in [Module]. Fix: [1-line-summary]. Avoid: [failed-approach].`;try{let o=await s.chat({chatPrompt:[{role:"system",content:"You are a concise code summarizer."},{role:"user",content:r}],...e?.model?{model:e.model}:{},...e?.modelConfig?{modelConfig:e.modelConfig}:{}});if(!rp(o)&&o.results?.[0]?.content){let i=o.results[0].content;return typeof i=="string"?i.trim():String(i)}return ep}catch{return ep}}var ep="[TOMBSTONE]: Error was resolved in subsequent turn.";function rp(s){return typeof s=="object"&&s!==null&&"getReader"in s}function sg(s){return s.map(e=>{Xn(e);let t=e.actorFieldsOutput.replace(/^Actor fields:\s*/i,"").trim();return[`Turn: ${e.turn}`,`Step kind: ${e.stepKind??"explore"}`,`Referenced inputs: ${(e.referencedVars??[]).join(", ")||"none"}`,`Durable values created: ${(e.producedVars??[]).join(", ")||"none"}`,`State delta: ${e.stateDelta??"none"}`,`Observed result: ${Vr(e.output||"(no output)",240)}`,`Actor fields: ${t||"none"}`,`Code excerpt: ${Vr(e.code||"(no code)",240)}`].join(`
796
+ `)}).join(`
797
+
798
+ `)}function Ea(s){let e=new Set,t=new Set,n=[],r=[],o="Continue from the latest live runtime state.";for(let i of s){Xn(i),e.add(i.stepKind??"explore");for(let u of i.producedVars??[])t.add(u);let a=Vr(i.output||"(no output)",140);n.push(`Turn ${i.turn}: ${a}`);let l=i.actorFieldsOutput.replace(/^Actor fields:\s*/i,"").trim();l&&r.push(`Turn ${i.turn}: ${l}`),o=i.stepKind==="finalize"?"Complete the responder handoff.":"Continue from the latest live runtime state."}return[`Objective: ${[...e].join(", ")||"none"}`,`Durable state: ${[...t].join(", ")||"none"}`,`Evidence: ${n.join(" | ")||"none"}`,"Conclusions: Preserve the durable state and evidence above.",`Actor fields: ${r.join(" | ")||"none"}`,`Next step: ${o}`].join(`
799
+ `)}async function op(s,e){let t=`Compress these older successful agent turns into one compact checkpoint for future turns.
800
+
801
+ Rules:
802
+ - Keep only information needed to continue the task.
803
+ - Do not restate raw code or quote large outputs.
804
+ - Use plain text with exactly these labels:
805
+ Objective:
806
+ Durable state:
807
+ Evidence:
808
+ Conclusions:
809
+ Actor fields:
810
+ Next step:
811
+ - Use "none" when a section has nothing worth preserving.
812
+ - Be concise and factual.
813
+
814
+ Turns:
815
+ ${sg(e)}`;try{let n=await s.chat({chatPrompt:[{role:"system",content:"You compress prior agent progress into checkpoint summaries for future reasoning turns."},{role:"user",content:t}]});if(!rp(n)&&n.results?.[0]?.content){let r=n.results[0].content;return(typeof r=="string"?r.trim():String(r).trim())||Ea(e)}return Ea(e)}catch{return Ea(e)}}async function Fa(s,e,t,n){let r=s[e];if(!r)return;Xn(r);let o=r.tags.includes("error");if(t.hindsightEvaluation&&s.length>=2){let i=s[s.length-2];rg(i,r)}if(t.tombstoning&&n){for(let i of s)if(i.tags.includes("error")&&!i.tombstone&&!i._tombstonePromise){let a=s.indexOf(i),l=s[a+1];if(l&&!l.tags.includes("error")){let u=typeof t.tombstoning=="object"?t.tombstoning:void 0;i._tombstonePromise=og(n,u,i,l),i._tombstonePromise.then(c=>{i.tombstone=c}).catch(()=>{}).finally(()=>{i._tombstonePromise=void 0})}}}if(t.errorPruning&&!o){let i=s.filter(a=>!a.tags.includes("error")||a.tombstone!=null||a._tombstonePromise!=null);s.length=0,s.push(...i)}if(t.hindsightEvaluation){let i=s.filter((a,l)=>l===s.length-1||a.rank===void 0||a.rank>=t.pruneRank||a.tombstone!=null||a._tombstonePromise!=null);s.length=0,s.push(...i)}}function _a(s,e){if(s.length===0&&!e.stateSummary&&!e.checkpointSummary)return"";ng(s,e);let t=new Set(e.checkpointTurns??[]),n=s.map(o=>{if(t.has(o.turn)&&!o.tags.includes("error"))return"";if(o.tombstone)return`Action ${o.turn}:
816
+ ${o.tombstone}`;switch(o.replayMode){case"omit":return Xn(o),`Action ${o.turn}:
817
+ ${o.summary??Pa(o)}`;default:return`Action ${o.turn}:
773
818
  \`\`\`javascript
774
- ${e.code}
819
+ ${o.code}
775
820
  \`\`\`
776
821
  Result:
777
- ${e.output}${e.actorFieldsOutput}`).join(`
778
-
779
- `)}function Uc(s){return`(() => {
780
- const skip = new Set([${s.map(t=>`'${t}'`).join(",")}]);
822
+ ${o.output}${o.actorFieldsOutput}`}}).filter(Boolean).join(`
823
+
824
+ `),r=[];return e.stateSummary&&r.push(`Live Runtime State:
825
+ ${e.stateSummary}`),n&&r.push(n),e.checkpointSummary&&r.push(`Checkpoint Summary:
826
+ ${e.checkpointSummary}`),r.join(`
827
+
828
+ `)}function sp(s,e){let t=new Set(e?.checkpointTurns??[]),n=s.map(o=>{if(t.has(o.turn)&&!o.tags.includes("error"))return"";Xn(o);let i=o.tombstone??o.summary??Pa(o);return`- Action ${o.turn}: ${i}`}).filter(Boolean).join(`
829
+ `),r=["Actor stopped without calling final(...). Evidence summary:"];return e?.checkpointSummary&&r.push(`Checkpoint summary:
830
+ ${e.checkpointSummary}`),n?r.push(n):e?.checkpointSummary||r.push("- No actions were taken."),e?.stateSummary&&r.push(`Current runtime state:
831
+ ${e.stateSummary}`),r.join(`
832
+ `)}function ip(s,e=[]){return`(() => {
833
+ const skip = new Set([${[...s,...e].map(n=>`'${n}'`).join(",")}]);
781
834
  return Object.entries(globalThis)
782
835
  .filter(([k]) => !skip.has(k) && !k.startsWith('_'))
783
836
  .map(([k, v]) => {
@@ -793,30 +846,32 @@ ${e.output}${e.actorFieldsOutput}`).join(`
793
846
  } catch { preview = String(v).slice(0, 80); }
794
847
  return k + ': ' + type + (size ? ' (' + size + ')' : '') + ' = ' + preview;
795
848
  }).join('\\n') || '(no user variables)';
796
- })()`}function Cm(s){let e=s.type;return Array.isArray(e)?e.filter(t=>typeof t=="string"):typeof e=="string"?e.includes(",")?e.split(",").map(t=>t.trim()).filter(Boolean):[e]:[]}function Tm(s){let e=new Set(s);return e.has("object")&&e.has("array")&&e.has("string")&&e.has("number")&&e.has("boolean")&&e.has("null")}function Ta(s){if(s.enum)return s.enum.map(n=>`"${n}"`).join(" | ");let e=Cm(s);if(e.length===0)return"unknown";if(Tm(e))return"any";let t=[...new Set(e)].map(n=>{if(n==="array"){let r=s.items?Ta(s.items):"unknown";return r.includes(" | ")?`(${r})[]`:`${r}[]`}return n==="object"?s.properties&&Object.keys(s.properties).length>0?jc(s):"object":n});return t.length>1?t.join(" | "):t[0]??"unknown"}function jc(s,e){if(!s)return"{}";let t=!!s.properties&&Object.keys(s.properties).length>0,n=s.additionalProperties===!0;if(!t)return n?"{ [key: string]: unknown }":"{}";let r=new Set(s.required??[]),o=e?.respectRequired??!1,i=Object.entries(s.properties).map(([a,l])=>{let u=Ta(l),c=o&&!r.has(a)?"?":"";return`${a}${c}: ${u}`});return s?.additionalProperties===!0&&i.push("[key: string]: unknown"),`{ ${i.join(", ")} }`}function wm(s){return s?Ta(s):"unknown"}function Bc(s){let e=jc(s.parameters,{respectRequired:!0}),t=s.returns?`: Promise<${wm(s.returns)}>`:"";return`- \`${s.qualifiedName}(args: ${e})${t}\``}function Ps(s,e,t,n){let r=e.length>0?e.map(d=>{let m=Bn(d.type),g=d.isOptional?"optional":"required",f=d.description?`: ${d.description}`:"";return`- \`${d.name}\` -> \`inputs.${d.name}\` (${m}, ${g})${f}`}).join(`
797
- `):"(none)",o=t.map(d=>`\`${d.name}\``).join(", "),i=[...n.agents??[]].sort((d,m)=>d.name.localeCompare(m.name)),a=[...n.agentFunctions??[]].sort((d,m)=>d.namespace!==m.namespace?d.namespace.localeCompare(m.namespace):d.name.localeCompare(m.name)),l=n.agentModuleNamespace??"agents",u=!!n.discoveryMode,c=n.availableModules?[...new Set(n.availableModules)].sort((d,m)=>d.localeCompare(m)):[...new Set([...a.map(d=>d.namespace),...i.length>0?[l]:[]])].sort((d,m)=>d.localeCompare(m)),p=gt("rlm/actor.md",{contextVarList:r,responderOutputFieldTitles:o,discoveryMode:u,hasInspectRuntime:!!n.hasInspectRuntime,hasAgentFunctions:!u&&i.length>0,agentModuleNamespace:l,agentFunctionsList:i.map(d=>Bc({qualifiedName:`${l}.${d.name}`,parameters:d.parameters})).join(`
798
- `),hasFunctions:!u&&a.length>0,functionsList:a.map(d=>Bc({qualifiedName:`${d.namespace}.${d.name}`,parameters:d.parameters,returns:d.returns})).join(`
799
- `),hasModules:u&&c.length>0,modulesList:c.map(d=>`- \`${d}\``).join(`
849
+ })()`}function ap(){return"(() => JSON.stringify(Object.getOwnPropertyNames(globalThis).sort()))()"}function ig(s){let e=s.type;return Array.isArray(e)?e.filter(t=>typeof t=="string"):typeof e=="string"?e.includes(",")?e.split(",").map(t=>t.trim()).filter(Boolean):[e]:[]}function ag(s){let e=new Set(s);return e.has("object")&&e.has("array")&&e.has("string")&&e.has("number")&&e.has("boolean")&&e.has("null")}function Na(s){if(s.enum)return s.enum.map(n=>`"${n}"`).join(" | ");let e=ig(s);if(e.length===0)return"unknown";if(ag(e))return"any";let t=[...new Set(e)].map(n=>{if(n==="array"){let r=s.items?Na(s.items):"unknown";return r.includes(" | ")?`(${r})[]`:`${r}[]`}return n==="object"?s.properties&&Object.keys(s.properties).length>0?up(s):"object":n});return t.length>1?t.join(" | "):t[0]??"unknown"}function up(s,e){if(!s)return"{}";let t=!!s.properties&&Object.keys(s.properties).length>0,n=s.additionalProperties===!0;if(!t)return n?"{ [key: string]: unknown }":"{}";let r=new Set(s.required??[]),o=e?.respectRequired??!1,i=Object.entries(s.properties).map(([a,l])=>{let u=Na(l),c=o&&!r.has(a)?"?":"";return`${a}${c}: ${u}`});return s?.additionalProperties===!0&&i.push("[key: string]: unknown"),`{ ${i.join(", ")} }`}function lg(s){return s?Na(s):"unknown"}function lp(s){let e=up(s.parameters,{respectRequired:!0}),t=s.returns?`: Promise<${lg(s.returns)}>`:"";return`- \`${s.qualifiedName}(args: ${e})${t}\``}function $s(s,e,t,n){let r=e.length>0?e.map(d=>{let m=$n(d.type),g=d.isOptional?"optional":"required",f=d.description?`: ${d.description}`:"";return`- \`${d.name}\` -> \`inputs.${d.name}\` (${m}, ${g})${f}`}).join(`
850
+ `):"(none)",o=t.map(d=>`\`${d.name}\``).join(", "),i=[...n.agents??[]].sort((d,m)=>d.name.localeCompare(m.name)),a=[...n.agentFunctions??[]].sort((d,m)=>d.namespace!==m.namespace?d.namespace.localeCompare(m.namespace):d.name.localeCompare(m.name)),l=n.agentModuleNamespace??"agents",u=!!n.discoveryMode,c=n.availableModules?[...n.availableModules].sort((d,m)=>d.namespace.localeCompare(m.namespace)):[...new Set([...a.map(d=>d.namespace),...i.length>0?[l]:[]])].sort((d,m)=>d.localeCompare(m)).map(d=>({namespace:d})),p=at("rlm/actor.md",{contextVarList:r,responderOutputFieldTitles:o,discoveryMode:u,hasInspectRuntime:!!n.hasInspectRuntime,hasAgentFunctions:!u&&i.length>0,agentModuleNamespace:l,agentFunctionsList:i.map(d=>lp({qualifiedName:`${l}.${d.name}`,parameters:d.parameters})).join(`
851
+ `),hasFunctions:!u&&a.length>0,functionsList:a.map(d=>lp({qualifiedName:`${d.namespace}.${d.name}`,parameters:d.parameters,returns:d.returns})).join(`
852
+ `),hasModules:u&&c.length>0,modulesList:c.map(d=>d.selectionCriteria?.trim()?`- \`${d.namespace}\` - ${d.selectionCriteria.trim()}`:`- \`${d.namespace}\``).join(`
800
853
  `),runtimeUsageInstructions:String(n.runtimeUsageInstructions),enforceIncrementalConsoleTurns:!!n.enforceIncrementalConsoleTurns}).replace(/\n{3,}/g,`
801
854
 
802
855
  `).trim();return s?`${p}
803
856
 
804
- ${s}`:p}function Fs(s,e){let t=e.length>0?e.map(r=>{let o=Bn(r.type),i=r.isOptional?"optional":"required";return`- \`${r.name}\` (${o}, ${i})`}).join(`
805
- `):"(none)",n=gt("rlm/responder.md",{contextVarSummary:t}).trim();return s?`${n}
806
-
807
- ${s}`:n}var qc=50,Rm=5e3,vm=8,zc=10,Sm=2,km=1200,_s="agents",wa="listModuleFunctions",Ra="getFunctionDefinitions",Jr=class s{ai;program;actorProgram;responderProgram;agents;agentFunctions;debug;options;rlmConfig;runtime;actorFieldNames;localFieldNames;sharedFieldNames;globalSharedFieldNames;excludedSharedFields;excludedAgents;excludedAgentFunctions;actorDescription;responderDescription;recursionForwardOptions;actorForwardOptions;responderForwardOptions;inputUpdateCallback;contextPromptMaxCharsByField=new Map;agentModuleNamespace=_s;functionDiscoveryEnabled=!1;runtimeUsageInstructions="";enforceIncrementalConsoleTurns=!1;activeAbortControllers=new Set;_stopRequested=!1;func;_parentSharedFields=new Set;_parentSharedAgents=new Set;_parentSharedAgentFunctions=new Set;constructor({ai:e,agentIdentity:t,agentModuleNamespace:n,signature:r},o){let{debug:i,contextFields:a,runtime:l,maxSubAgentCalls:u,maxRuntimeChars:c,maxBatchedLlmQueryConcurrency:p,maxTurns:d,trajectoryPruning:m,contextManagement:g,actorFields:f,actorCallback:h,mode:y,recursionOptions:x,actorOptions:b,responderOptions:R,inputUpdateCallback:A}=o;this.ai=e,this.agents=o.agents?.local,this.agentFunctions=o.functions?.local??[],this.functionDiscoveryEnabled=o.functions?.discovery??!1,this.debug=i,this.options=o,this.runtime=l??new en,this.runtimeUsageInstructions=this.runtime.getUsageInstructions(),this.enforceIncrementalConsoleTurns=_m(this.runtimeUsageInstructions);let w=n??t?.namespace??_s;if(this.agentModuleNamespace=Um(w,{normalize:n===void 0}),new Set(["inputs","llmQuery","final","ask_clarification","inspect_runtime",wa,Ra]).has(this.agentModuleNamespace))throw new Error(`Agent module namespace "${this.agentModuleNamespace}" is reserved`);let{agents:F,fields:O,functions:D,inputUpdateCallback:U,...L}=o;this.program=new $e(r,L);let T=this.program.getSignature().getInputFields(),M=Em(a,T,km);this.contextPromptMaxCharsByField=M.promptMaxCharsByField,this.rlmConfig={contextFields:M.contextFieldNames,sharedFields:o.fields?.shared,runtime:this.runtime,maxSubAgentCalls:u,maxRuntimeChars:c,maxBatchedLlmQueryConcurrency:p,maxTurns:d,trajectoryPruning:m,contextManagement:g,actorFields:f,actorCallback:h,mode:y},this.recursionForwardOptions=x;let{description:E,...N}=b??{},{description:P,..._}=R??{};this.actorDescription=E,this.actorForwardOptions=N,this.responderDescription=P,this.responderForwardOptions=_,this.inputUpdateCallback=A;let G=this.agents;for(let re of G??[]){let ue=re.getFunction().name;this.program.register(re,ue)}if(t&&(this.func={name:Vc(t.name),description:t.description,parameters:this._buildFuncParameters(),func:async()=>{throw new Error("Use getFunction() to get a callable wrapper")}}),this.program.getSignature().getDescription())throw new Error("AxAgent does not support signature-level descriptions. Use setActorDescription() and/or setResponderDescription() to customize the actor and responder prompts independently.");let $=this.program.getSignature().getOutputFields(),W=f??[];this.actorFieldNames=W;for(let re of W)if(!$.some(ue=>ue.name===re))throw new Error(`RLM actorField "${re}" not found in output signature`);let se=o.fields?.shared??[];this.sharedFieldNames=se;for(let re of se)if(!T.some(ue=>ue.name===re))throw new Error(`sharedField "${re}" not found in signature input fields`);this.excludedSharedFields=o.fields?.excluded??[];let Y=o.fields?.globallyShared??[];this.globalSharedFieldNames=Y;for(let re of Y)if(!T.some(ue=>ue.name===re))throw new Error(`globalSharedField "${re}" not found in signature input fields`);this.localFieldNames=o.fields?.local??[];let ee=o.agents?.shared??[],oe=o.agents?.globallyShared??[];this.excludedAgents=o.agents?.excluded??[];let be=o.functions?.shared??[],Ce=o.functions?.globallyShared??[];this.excludedAgentFunctions=o.functions?.excluded??[];let X=[...this.agentFunctions,...be,...Ce];for(let re of X)if(!re.parameters)throw new Error(`Agent function "${re.name}" must define parameters schema for agent runtime usage.`);let Ie=new Set([_s,this.agentModuleNamespace,"llmQuery","final","ask_clarification",...this.functionDiscoveryEnabled?[wa,Ra]:[]]);for(let re of X){let ue=re.namespace??"utils";if(Ie.has(ue))throw new Error(`Agent function namespace "${ue}" is reserved`)}if(se.length>0&&G){let re=T.filter(ue=>se.includes(ue.name));for(let ue of G){if(!(ue instanceof s))continue;let Pe=new Set(ue.getExcludedSharedFields()),ae=re.filter(ve=>!Pe.has(ve.name));ae.length!==0&&ue._extendForSharedFields(ae,this.rlmConfig.contextFields)}}if(ee.length>0&&G)for(let re of G)re instanceof s&&re._extendForSharedAgents(ee);if(Y.length>0&&G){let re=T.filter(ue=>Y.includes(ue.name));for(let ue of G){if(!(ue instanceof s))continue;let Pe=new Set(ue.getExcludedSharedFields()),ae=re.filter(ve=>!Pe.has(ve.name));ae.length!==0&&ue._extendForGlobalSharedFields(ae,this.rlmConfig.contextFields)}}if(oe.length>0&&G)for(let re of G)re instanceof s&&re._extendForGlobalSharedAgents(oe);if(be.length>0&&G)for(let re of G)re instanceof s&&re._extendForSharedAgentFunctions(be);if(Ce.length>0&&G)for(let re of G)re instanceof s&&re._extendForGlobalSharedAgentFunctions(Ce);this._buildSplitPrograms(),this.program.register(this.actorProgram,"actor"),this.program.register(this.responderProgram,"responder")}_buildSplitPrograms(){let e=this.program.getSignature().getInputFields(),t=this.rlmConfig.contextFields,n=this._getBypassedSharedFieldNames(),r=e.filter(A=>t.includes(A.name)),o=r.filter(A=>this.contextPromptMaxCharsByField.has(A.name)&&!n.has(A.name)).map(A=>({...A,isOptional:!0})),i=e.filter(A=>!t.includes(A.name)&&!n.has(A.name)),a=this.program.getSignature().getOutputFields(),l=a.filter(A=>this.actorFieldNames.includes(A.name)),u=a.filter(A=>!this.actorFieldNames.includes(A.name)),c=ye().addInputFields(i).addInputFields(o).input("contextMetadata",ye.string("Metadata about pre-loaded context variables (type and size)")).input("actionLog",ye.string("Chronological trace of code executions or actions and their outputs so far")).output("javascriptCode",ye.code("JavaScript code to execute in runtime session"));l.length>0&&(c=c.addOutputFields(l));let p=c.build(),d=ye().addInputFields(i).input("contextData",ye.json("Context data to help synthesize the final answer.")).addOutputFields(u).build(),m=this.rlmConfig.maxSubAgentCalls??qc,g=this.rlmConfig.maxTurns??zc,f=this.agents?.map(A=>{let w=A.getFunction();return{name:w.name,description:w.description,parameters:w.parameters}})??[],h=this.agentFunctions.map(A=>({name:A.name,description:A.description,parameters:A.parameters,returns:A.returns,namespace:A.namespace??"utils"})),y=new Set(h.map(A=>A.namespace??"utils"));f.length>0&&y.add(this.agentModuleNamespace);let x=[...y].sort((A,w)=>A.localeCompare(w)),b=Ps(this.actorDescription,r,u,{runtimeUsageInstructions:this.runtimeUsageInstructions,maxSubAgentCalls:m,maxTurns:g,hasInspectRuntime:!!this.rlmConfig.contextManagement?.stateInspection,enforceIncrementalConsoleTurns:this.enforceIncrementalConsoleTurns,agentModuleNamespace:this.agentModuleNamespace,discoveryMode:this.functionDiscoveryEnabled,availableModules:x,agents:f,agentFunctions:h}),R=Fs(this.responderDescription,r);this.actorProgram=new $e(p,{...this._genOptions,description:b}),this.responderProgram=new $e(d,{...this._genOptions,description:R})}_extendForSharedFields(e,t){let n=this.program.getSignature(),r=n.getInputFields(),o=!1;for(let i of e){if(r.some(a=>a.name===i.name)){if(this._parentSharedFields.has(i.name))throw new Error(`Duplicate shared field "${i.name}" \u2014 already propagated from a parent`);continue}this._parentSharedFields.add(i.name),n.addInputField(i),o=!0}o&&this.program.setSignature(n);for(let i of e)t.includes(i.name)&&!this.rlmConfig.contextFields.includes(i.name)&&this.rlmConfig.contextFields.push(i.name);this._buildSplitPrograms(),this.func&&(this.func.parameters=this._buildFuncParameters())}_extendForSharedAgents(e){if(e.length===0)return;let t=new Set((this.agents??[]).map(o=>o.getFunction().name)),n=new Set(this.excludedAgents),r=[];for(let o of e){if(o===this)continue;let i=o.getFunction().name;if(!n.has(i)){if(t.has(i)){if(this._parentSharedAgents.has(i))throw new Error(`Duplicate shared agent "${i}" \u2014 already propagated from a parent`);continue}this._parentSharedAgents.add(i),t.add(i),r.push(o)}}if(r.length!==0){this.agents=[...this.agents??[],...r];for(let o of r){let i=o.getFunction().name;this.program.register(o,i)}this._buildSplitPrograms()}}_extendForGlobalSharedFields(e,t){let n=this.program.getSignature(),r=n.getInputFields(),o=!1;for(let i of e){if(r.some(a=>a.name===i.name)){if(this._parentSharedFields.has(i.name))throw new Error(`Duplicate shared field "${i.name}" \u2014 already propagated from a parent`);continue}this._parentSharedFields.add(i.name),n.addInputField(i),o=!0}o&&this.program.setSignature(n);for(let i of e)t.includes(i.name)&&!this.rlmConfig.contextFields.includes(i.name)&&this.rlmConfig.contextFields.push(i.name);for(let i of e)this.sharedFieldNames.includes(i.name)||this.sharedFieldNames.push(i.name);if(this._buildSplitPrograms(),this.func&&(this.func.parameters=this._buildFuncParameters()),this.agents)for(let i of this.agents){if(!(i instanceof s))continue;let a=new Set(i.getExcludedSharedFields()),l=e.filter(u=>!a.has(u.name));l.length!==0&&i._extendForGlobalSharedFields(l,t)}}_extendForGlobalSharedAgents(e){let t=this.agents?this.agents.filter(n=>n instanceof s):[];this._extendForSharedAgents(e);for(let n of t)n._extendForGlobalSharedAgents(e)}_extendForSharedAgentFunctions(e){if(e.length===0)return;let t=new Set(this.agentFunctions.map(o=>`${o.namespace??"utils"}.${o.name}`)),n=new Set(this.excludedAgentFunctions),r=[];for(let o of e){if(n.has(o.name))continue;let i=`${o.namespace??"utils"}.${o.name}`;if(t.has(i)){if(this._parentSharedAgentFunctions.has(i))throw new Error(`Duplicate shared agent function "${i}" \u2014 already propagated from a parent`);continue}this._parentSharedAgentFunctions.add(i),t.add(i),r.push(o)}r.length!==0&&(this.agentFunctions=[...this.agentFunctions,...r],this._buildSplitPrograms())}_extendForGlobalSharedAgentFunctions(e){let t=this.agents?this.agents.filter(n=>n instanceof s):[];this._extendForSharedAgentFunctions(e);for(let n of t)n._extendForGlobalSharedAgentFunctions(e)}stop(){this._stopRequested=!0;for(let e of this.activeAbortControllers)e.abort("Stopped by user");this.program.stop(),this.actorProgram.stop(),this.responderProgram.stop()}getId(){return this.program.getId()}setId(e){this.program.setId(e)}namedPrograms(){return this.program.namedPrograms()}getTraces(){return this.program.getTraces()}setDemos(e,t){this.program.setDemos(e,t)}getUsage(){return this.program.getUsage()}resetUsage(){this.program.resetUsage()}getFunction(){if(!this.func)throw new Error("getFunction() requires agentIdentity to be set in the constructor");let e=this.forward.bind(this);return{...this.func,func:async(r,o)=>{let i=this.ai??o?.ai;if(!i)throw new Error("AI service is required to run the agent");let a=await e(i,r,o),u=this.program.getSignature().getOutputFields();return Object.keys(a).map(p=>{let d=u.find(m=>m.name===p);return d?`${d.title}: ${a[p]}`:`${p}: ${a[p]}`}).join(`
808
- `)}}}getExcludedSharedFields(){return this.excludedSharedFields}_getBypassedSharedFieldNames(){let e=new Set([...this.sharedFieldNames,...this.globalSharedFieldNames]);for(let t of this.localFieldNames)e.delete(t);return e}getExcludedAgents(){return this.excludedAgents}getExcludedAgentFunctions(){return this.excludedAgentFunctions}getSignature(){return this.program.getSignature()}setSignature(e){this.program.setSignature(e)}applyOptimization(e){this.program.applyOptimization?.(e)}async _runActorLoop(e,t,n,r){let o=this.rlmConfig,i=this.runtime,a=n?.debug??this.debug??e?.getOptions()?.debug??!1,l;Array.isArray(t)?l=t.filter(z=>z.role==="user").reduce((z,Q)=>({...z,...Q.values}),{}):l=t;let u={...l},c=new Set(this.program.getSignature().getInputFields().map(z=>z.name)),p=[...this.sharedFieldNames,...this.globalSharedFieldNames],d=this._getBypassedSharedFieldNames(),m={},g={},f={},h={},y="(none)",x=new Set(this.program.getSignature().getInputFields().filter(z=>o.contextFields.includes(z.name)&&z.isOptional).map(z=>z.name)),b=z=>{let Q={},Me={};for(let[de,_e]of Object.entries(u))o.contextFields.includes(de)?Q[de]=_e:d.has(de)||(Me[de]=_e);if(z){for(let de of o.contextFields)if(!x.has(de)&&(!(de in Q)||Q[de]===void 0))throw new Error(`RLM contextField "${de}" is missing from input values`)}let Le={};for(let[de,_e]of this.contextPromptMaxCharsByField){if(d.has(de)||!(de in Q))continue;let te=Q[de];Mm(te)<=_e&&(Le[de]=te)}g=Q,f=Me,h=Le;for(let de of Object.keys(m))delete m[de];for(let de of p)de in u&&(m[de]=u[de]),de in g&&(m[de]=g[de]);y=Pm(g,{promptMaxCharsByField:this.contextPromptMaxCharsByField,inlinedFields:new Set(Object.keys(h))})||"(none)"};b(!1);let R=o.maxSubAgentCalls??qc,A=o.maxRuntimeChars??Rm,w=Math.max(1,o.maxBatchedLlmQueryConcurrency??vm),v=o.maxTurns??zc,F=0,O=Math.floor(R*.8),D=this.recursionForwardOptions?.maxDepth??Sm,U=Math.max(0,D),{maxDepth:L,...T}=this.recursionForwardOptions??{},{functions:M,description:E,mem:N,sessionId:P,..._}=n??{},G={...this.recursionForwardOptions??{},maxDepth:Math.max(0,U-1)},$=["context"],W=ye().input("task",ye.string("Task for recursive analysis")).input("context",ye.json("Optional context for the recursive task")).output("answer",ye.string("Answer from recursive analysis")).build(),Y=(o.mode??"simple")==="advanced"&&(G.maxDepth??0)>0?"advanced":"simple",ee;U>0&&(Y==="advanced"?ee=new s({agentModuleNamespace:this.agentModuleNamespace,signature:W},{debug:a,...o,agents:{local:this.agents},functions:{local:this.agentFunctions,discovery:this.functionDiscoveryEnabled},contextFields:$,actorFields:void 0,recursionOptions:G,actorOptions:this.actorForwardOptions,responderOptions:this.responderForwardOptions}):ee=new $e(W,G));let oe=z=>{if(z==null)return"";if(typeof z=="string")return ht(z,A);try{return ht(JSON.stringify(z),A)}catch{return ht(String(z),A)}},be=async(z,Q)=>{if(!Array.isArray(z)&&typeof z=="object"&&z!==null&&"query"in z)return be(z.query,z.context??Q);if(r?.aborted)throw new Ge("rlm-llm-query",r.reason?String(r.reason):"Aborted");if(Array.isArray(z))return Fm(z,w,async _e=>{try{return await be(_e.query,_e.context)}catch(te){if(te instanceof Ge)throw te;return`[ERROR] ${te instanceof Error?te.message:String(te)}`}});let de=await(async(_e,te)=>{let ke=te===void 0?void 0:typeof te=="string"?ht(te,A):te;if(F++,F>R)return`[ERROR] Sub-query budget exhausted (${R}/${R}). Use the data you have already accumulated to produce your final answer.`;if(U<=0||!ee)return`[ERROR] Recursion depth limit reached (${D}).`;let Te=3,De,qe=ze=>`[ERROR] ${ze instanceof Error?ze.message:String(ze)}`;for(let ze=0;ze<Te;ze++)try{let xt=await ee.forward(e,{task:_e,...ke!==void 0?{context:ke}:Y==="advanced"?{context:""}:{}},{..._,...T,abortSignal:r,debug:a});return oe(xt.answer)}catch(xt){if(xt instanceof Ge)throw xt;if(De=xt,!Om(xt)||ze>=Te-1)return qe(xt);let Ns=Math.min(6e4,1e3*Math.pow(2,ze));await new Promise((Sa,$s)=>{let tn=!1,Bt,we=()=>{r&&Bt&&r.removeEventListener("abort",Bt)},jt=setTimeout(()=>{tn||(tn=!0,we(),Sa())},Ns);if(r){if(Bt=()=>{tn||(tn=!0,clearTimeout(jt),we(),$s(new Ge("rlm-llm-query-retry-backoff",r.reason?String(r.reason):"Aborted during retry backoff")))},r.aborted){Bt();return}r.addEventListener("abort",Bt,{once:!0})}})}return qe(De)})(z,Q);return F===O?`${de}
809
- [WARNING] ${F}/${R} sub-queries used. Plan to wrap up soon.`:de},Ce=this.buildRuntimeGlobals(r,m,e),X,Ie=(z,Q)=>{if(Q.length===0)throw new Error(`${z}() requires at least one argument`);X={type:z,args:Q}},re=(...z)=>Ie("final",z),ue=(...z)=>Ie("ask_clarification",z),Pe=[...new Set(this.agentFunctions.map(z=>z.namespace??"utils"))],ae={...u},ve=new Set(["inputs","llmQuery",_s,this.agentModuleNamespace,"final","ask_clarification",...Pe,...o.contextManagement?.stateInspection?["inspect_runtime"]:[],...Object.keys(Ce)]),C=[...new Set([...Object.keys(ae),...c])].filter(z=>!ve.has(z)),S={};for(let z of C)S[z]=ae[z];let k=()=>{for(let z of Object.keys(ae))delete ae[z];for(let[z,Q]of Object.entries(u))ae[z]=Q;for(let z of C)S[z]=u[z]},I=[...ve],B=[...ve,...C],K=o.contextManagement?.stateInspection?async()=>{try{let z=Uc(B),Q=await j.execute(z,{signal:r,reservedNames:B});return typeof Q=="string"?Q:String(Q)}catch(z){return`[inspect_runtime error: ${z instanceof Error?z.message:String(z)}]`}}:void 0,q=()=>i.createSession({...S,inputs:ae,llmQuery:be,final:re,ask_clarification:ue,...K?{inspect_runtime:K}:{},...Ce}),H="[The JavaScript runtime was restarted; all global state was lost and must be recreated if needed.]",j=q(),V=z=>z instanceof Error&&z.message==="Session is closed",ne=z=>z instanceof Error&&z.message==="Execution timed out",le=z=>{if(z===void 0)return"(no output)";if(typeof z=="string")return ht(z||"(no output)",A);try{return ht(JSON.stringify(z,null,2),A)}catch{return ht(String(z),A)}},ce=z=>{let Q=z,Me=Q?.name??"Error",Le=Q?.message??String(z),de=[`${Me}: ${Le}`];if(Q?.data!==void 0)try{de.push(`Data: ${JSON.stringify(Q.data,null,2)}`)}catch{de.push(`Data: ${String(Q.data)}`)}if(Q?.cause!==void 0){let _e=(te,ke)=>{if(ke>4)return"[cause chain truncated]";let Te=te,De=Te?.name??"Error",qe=Te?.message??String(te),ze=[`${De}: ${qe}`];if(Te?.data!==void 0)try{ze.push(`Data: ${JSON.stringify(Te.data,null,2)}`)}catch{ze.push(`Data: ${String(Te.data)}`)}return Te?.cause!==void 0&&ze.push(`Caused by: ${_e(Te.cause,ke+1)}`),ze.join(`
810
- `)};de.push(`Caused by: ${_e(Q.cause,1)}`)}return ht(de.join(`
811
- `),A)},ge=async z=>{try{let Q=await j.execute(z,{signal:r,reservedNames:I});return{output:le(Q),isError:!1}}catch(Q){if(r?.aborted)throw new Ge("rlm-session",r.reason??"Aborted");if(Q instanceof Error&&(Q.name==="AbortError"||Q.message.startsWith("Aborted")))throw Q;if(ne(Q))return{output:ht(`${H}
812
- ${ce(Q)}`,A),isError:!0};if(V(Q))try{j=q(),X=void 0;let Me=await j.execute(z,{signal:r,reservedNames:I});return{output:ht(`${H}
813
- ${le(Me)}`,A),isError:!1}}catch(Me){return{output:ht(`${H}
814
- ${ce(Me)}`,A),isError:!0}}return{output:ht(ce(Q),A),isError:!0}}},Ae=async()=>{if(!this.inputUpdateCallback)return;let z=await this.inputUpdateCallback({...u});if(z!==void 0){if(!z||typeof z!="object"||Array.isArray(z))throw new Error("inputUpdateCallback must return an object patch or undefined");for(let[Q,Me]of Object.entries(z))c.has(Q)&&(u[Q]=Me)}},Se=z=>{if(typeof z.patchGlobals!="function")throw new Error("AxCodeSession.patchGlobals() is required when using inputUpdateCallback");return z},Fe=async()=>{k();let z=async Q=>{await Se(Q).patchGlobals({inputs:{...ae},...S},{signal:r})};try{await z(j)}catch(Q){if(r?.aborted)throw new Ge("rlm-session",r.reason??"Aborted");if(Q instanceof Error&&(Q.name==="AbortError"||Q.message.startsWith("Aborted")))throw Q;if(V(Q)){j=q(),await z(j);return}throw new Error(`Failed to sync runtime inputs: ${ce(Q)}`)}},Ee=o.contextManagement,Z={errorPruning:Ee?.errorPruning??o.trajectoryPruning??!1,hindsightEvaluation:Ee?.hindsightEvaluation??!1,tombstoning:Ee?.tombstoning,pruneRank:Ee?.pruneRank??2},J=[],pe={...this._genOptions,...this.actorForwardOptions,...n,debug:a,abortSignal:r},me={},Oe=Ee?.stateInspection?.contextThreshold;try{for(let z=0;z<v;z++){await Ae(),b(!0);let Q=Es(J)||"(no actions yet)";Oe&&Q.length>Oe&&(Q+="\n\n[HINT: Action log is large. Call `const state = await inspect_runtime()` for a compact snapshot of current variables instead of re-reading old outputs.]");let Me=await this.actorProgram.forward(e,{...f,...h,contextMetadata:y,actionLog:Q},pe);z===0&&(pe.debugHideSystemPrompt=!0),o.actorCallback&&await o.actorCallback(Me);for(let Te of this.actorFieldNames)Te in Me&&(me[Te]=Me[Te]);let Le=Me.javascriptCode,de=Le?.trim();if(!Le||!de)break;Le=de;let _e="";if(this.actorFieldNames.length>0){let Te=this.actorFieldNames.filter(De=>De in Me).map(De=>`${De}: ${Me[De]}`).join(`
815
- `);Te&&(_e=`
857
+ ${s}`:p}function Ls(s,e){let t=e.length>0?e.map(r=>{let o=$n(r.type),i=r.isOptional?"optional":"required";return`- \`${r.name}\` (${o}, ${i})`}).join(`
858
+ `):"(none)",n=at("rlm/responder.md",{contextVarSummary:t}).trim();return s?`${n}
859
+
860
+ ${s}`:n}var cp=50,ug=5e3,cg=8,pp=10,pg=2,dg=1200,Ds="agents",$a="listModuleFunctions",La="getFunctionDefinitions",dp="AxAgent.test() snippets must not call final(...) or ask_clarification(). Use this harness only to validate runtime code.",mg="AI service is required to use llmQuery(...) in AxAgent.test(). Pass options.ai or configure ai on the agent.",Bs="[The JavaScript runtime was restarted; all global state was lost and must be recreated if needed.]",Zn=class extends Error{constructor(t){super(`AxAgent protocol completion: ${t}`);this.type=t;this.name="AxAgentProtocolCompletionSignal"}};function mp(s){return{finalFunction:(...r)=>{s("final",r)},askClarificationFunction:(...r)=>{s("ask_clarification",r)},protocol:{final:(...r)=>{throw s("final",r),new Zn("final")},askClarification:(...r)=>{throw s("ask_clarification",r),new Zn("ask_clarification")}}}}function gp(s){let e=s?.preset??"full",t=gg(e),n=s?.expert?.rankPruning,r=n?.enabled??(n?.minRank!==void 0?!0:t.hindsight),o=s?.state?.summary??t.stateSummary,i=s?.state?.inspect??t.inspect,a=s?.checkpoints?.enabled??t.checkpointsEnabled;if(a&&!o&&!i)throw new Error("contextPolicy.checkpoints requires either state.summary or state.inspect to be enabled");return{preset:e,actionReplay:s?.expert?.replay??t.actionReplay,recentFullActions:Math.max(s?.expert?.recentFullActions??t.recentFullActions,0),errorPruning:s?.expert?.pruneErrors??t.errorPruning,hindsightEvaluation:r,pruneRank:n?.minRank??t.pruneRank,tombstoning:s?.expert?.tombstones,stateSummary:{enabled:o,maxEntries:s?.state?.maxEntries??t.maxEntries},stateInspection:{enabled:i,contextThreshold:s?.state?.inspectThresholdChars??t.inspectThreshold},checkpoints:{enabled:a,triggerChars:s?.checkpoints?.triggerChars??t.checkpointTriggerChars}}}function gg(s){switch(s){case"adaptive":return{actionReplay:"adaptive",recentFullActions:1,errorPruning:!0,hindsight:!1,pruneRank:2,stateSummary:!0,inspect:!0,inspectThreshold:2e3,maxEntries:6,checkpointsEnabled:!0,checkpointTriggerChars:2e3};case"lean":return{actionReplay:"minimal",recentFullActions:0,errorPruning:!0,hindsight:!0,pruneRank:2,stateSummary:!0,inspect:!0,inspectThreshold:1500,maxEntries:6,checkpointsEnabled:!0,checkpointTriggerChars:1500};default:return{actionReplay:"full",recentFullActions:1,errorPruning:!1,hindsight:!1,pruneRank:2,stateSummary:!1,inspect:!1,inspectThreshold:void 0,maxEntries:void 0,checkpointsEnabled:!1,checkpointTriggerChars:void 0}}}var Jr=class s{ai;program;actorProgram;responderProgram;agents;agentFunctions;agentFunctionModuleMetadata=new Map;debug;options;rlmConfig;runtime;actorFieldNames;localFieldNames;sharedFieldNames;globalSharedFieldNames;excludedSharedFields;excludedAgents;excludedAgentFunctions;actorDescription;responderDescription;recursionForwardOptions;actorForwardOptions;responderForwardOptions;inputUpdateCallback;contextPromptConfigByField=new Map;agentModuleNamespace=Ds;functionDiscoveryEnabled=!1;runtimeUsageInstructions="";enforceIncrementalConsoleTurns=!1;activeAbortControllers=new Set;_stopRequested=!1;func;_parentSharedFields=new Set;_parentSharedAgents=new Set;_parentSharedAgentFunctions=new Set;_reservedAgentFunctionNamespaces(){return new Set(["inputs","llmQuery","final","ask_clarification","inspect_runtime",Ds,this.agentModuleNamespace,...this.functionDiscoveryEnabled?[$a,La]:[]])}_mergeAgentFunctionModuleMetadata(e){let t=!1;for(let n of e){let r=this.agentFunctionModuleMetadata.get(n.namespace);if(!r){this.agentFunctionModuleMetadata.set(n.namespace,n),t=!0;continue}if(r.title!==n.title||r.selectionCriteria!==n.selectionCriteria||r.description!==n.description)throw new Error(`Conflicting agent function group metadata for namespace "${n.namespace}"`)}return t}_validateConfiguredSignature(e){if(e.getDescription())throw new Error("AxAgent does not support signature-level descriptions. Use setActorDescription() and/or setResponderDescription() to customize the actor and responder prompts independently.");let t=new Set(e.getInputFields().map(r=>r.name)),n=new Set(e.getOutputFields().map(r=>r.name));for(let r of this.rlmConfig.contextFields)if(!t.has(r))throw new Error(`RLM contextField "${r}" not found in signature`);for(let r of this.sharedFieldNames)if(!t.has(r))throw new Error(`sharedField "${r}" not found in signature input fields`);for(let r of this.globalSharedFieldNames)if(!t.has(r))throw new Error(`globalSharedField "${r}" not found in signature input fields`);for(let r of this.actorFieldNames)if(!n.has(r))throw new Error(`RLM actorField "${r}" not found in output signature`)}_validateAgentFunctionNamespaces(e){let t=this._reservedAgentFunctionNamespaces();for(let n of e){let r=n.namespace??"utils";if(t.has(r))throw new Error(`Agent function namespace "${r}" conflicts with an AxAgent runtime global and is reserved`)}}constructor({ai:e,agentIdentity:t,agentModuleNamespace:n,signature:r},o){let{debug:i,contextFields:a,runtime:l,maxSubAgentCalls:u,maxRuntimeChars:c,maxBatchedLlmQueryConcurrency:p,maxTurns:d,contextPolicy:m,actorFields:g,actorCallback:f,mode:h,recursionOptions:A,actorOptions:x,responderOptions:b,inputUpdateCallback:C}=o;this.ai=e,this.agents=o.agents?.local,this.functionDiscoveryEnabled=o.functions?.discovery??!1,this.debug=i,this.options=o,this.runtime=l??new Qt,this.runtimeUsageInstructions=this.runtime.getUsageInstructions(),this.enforceIncrementalConsoleTurns=wg(this.runtimeUsageInstructions);let I=n??t?.namespace??Ds;if(this.agentModuleNamespace=Og(I,{normalize:n===void 0}),new Set(["inputs","llmQuery","final","ask_clarification","inspect_runtime",$a,La]).has(this.agentModuleNamespace))throw new Error(`Agent module namespace "${this.agentModuleNamespace}" is reserved`);let O=this._reservedAgentFunctionNamespaces(),k=Da(o.functions?.local,O),S=Da(o.functions?.shared,O),$=Da(o.functions?.globallyShared,O);this.agentFunctions=k.functions,this._mergeAgentFunctionModuleMetadata(k.moduleMetadata);let{agents:G,fields:L,functions:w,inputUpdateCallback:R,...E}=o;this.program=new ke(r,E);let _=this.program.getSignature().getInputFields(),M=Ig(a,_,dg);this.contextPromptConfigByField=M.promptConfigByField,this.rlmConfig={contextFields:M.contextFieldNames,sharedFields:o.fields?.shared,runtime:this.runtime,maxSubAgentCalls:u,maxRuntimeChars:c,maxBatchedLlmQueryConcurrency:p,maxTurns:d,contextPolicy:m,actorFields:g,actorCallback:f,mode:h},this.recursionForwardOptions=A;let{description:N,...q}=x??{},{description:U,...W}=b??{};this.actorDescription=N,this.actorForwardOptions=q,this.responderDescription=U,this.responderForwardOptions=W,this.inputUpdateCallback=C;let Y=this.agents;for(let re of Y??[]){let xe=re.getFunction().name;this.program.register(re,xe)}t&&(this.func={name:Tp(t.name),description:t.description,parameters:this._buildFuncParameters(),func:async()=>{throw new Error("Use getFunction() to get a callable wrapper")}});let Q=g??[];this.actorFieldNames=Q;let V=o.fields?.shared??[];this.sharedFieldNames=V,this.excludedSharedFields=o.fields?.excluded??[];let te=o.fields?.globallyShared??[];this.globalSharedFieldNames=te,this.localFieldNames=o.fields?.local??[];let ye=o.agents?.shared??[],Te=o.agents?.globallyShared??[];this.excludedAgents=o.agents?.excluded??[];let Z=S.functions,fe=$.functions;this.excludedAgentFunctions=o.functions?.excluded??[];let Re=[...this.agentFunctions,...Z,...fe];for(let re of Re){if(!re.parameters)throw new Error(`Agent function "${re.name}" must define parameters schema for agent runtime usage.`);if(re.examples){for(let[xe,le]of re.examples.entries())if(!le.code.trim())throw new Error(`Agent function "${re.name}" example at index ${xe} must define non-empty code`)}}if(this._validateConfiguredSignature(this.program.getSignature()),this._validateAgentFunctionNamespaces(Re),V.length>0&&Y){let re=_.filter(xe=>V.includes(xe.name));for(let xe of Y){if(!(xe instanceof s))continue;let le=new Set(xe.getExcludedSharedFields()),Ie=re.filter(T=>!le.has(T.name));Ie.length!==0&&xe._extendForSharedFields(Ie,this.rlmConfig.contextFields)}}if(ye.length>0&&Y)for(let re of Y)re instanceof s&&re._extendForSharedAgents(ye);if(te.length>0&&Y){let re=_.filter(xe=>te.includes(xe.name));for(let xe of Y){if(!(xe instanceof s))continue;let le=new Set(xe.getExcludedSharedFields()),Ie=re.filter(T=>!le.has(T.name));Ie.length!==0&&xe._extendForGlobalSharedFields(Ie,this.rlmConfig.contextFields)}}if(Te.length>0&&Y)for(let re of Y)re instanceof s&&re._extendForGlobalSharedAgents(Te);if(Z.length>0&&Y)for(let re of Y)re instanceof s&&re._extendForSharedAgentFunctions(S);if(fe.length>0&&Y)for(let re of Y)re instanceof s&&re._extendForGlobalSharedAgentFunctions($);this._buildSplitPrograms(),this.program.register(this.actorProgram,"actor"),this.program.register(this.responderProgram,"responder")}_buildSplitPrograms(){let e=this.program.getSignature().getInputFields(),t=this.rlmConfig.contextFields,n=this._getBypassedSharedFieldNames(),r=e.filter(I=>t.includes(I.name)),o=r.filter(I=>this.contextPromptConfigByField.has(I.name)&&!n.has(I.name)).map(I=>({...I,isOptional:!0})),i=e.filter(I=>!t.includes(I.name)&&!n.has(I.name)),a=this.program.getSignature().getOutputFields(),l=a.filter(I=>this.actorFieldNames.includes(I.name)),u=a.filter(I=>!this.actorFieldNames.includes(I.name)),c=he().addInputFields(i).addInputFields(o).input("contextMetadata",he.string("Metadata about pre-loaded context variables (type and size)")).input("actionLog",he.string("Chronological trace of code executions or actions and their outputs so far")).output("javascriptCode",he.code("JavaScript code to execute in runtime session"));l.length>0&&(c=c.addOutputFields(l));let p=c.build(),d=he().addInputFields(i).input("contextData",he.json("Context data to help synthesize the final answer.")).addOutputFields(u).build(),m=this.rlmConfig.maxSubAgentCalls??cp,g=this.rlmConfig.maxTurns??pp,f=this.agents?.map(I=>{let v=I.getFunction();return{name:v.name,description:v.description,parameters:v.parameters}})??[],h=this.agentFunctions.map(I=>({name:I.name,description:I.description,parameters:I.parameters,returns:I.returns,namespace:I.namespace??"utils"})),A=new Set(h.map(I=>I.namespace??"utils"));f.length>0&&A.add(this.agentModuleNamespace);let x=[...A].sort((I,v)=>I.localeCompare(v)).map(I=>({namespace:I,selectionCriteria:this.agentFunctionModuleMetadata.get(I)?.selectionCriteria})),b=$s(this.actorDescription,r,u,{runtimeUsageInstructions:this.runtimeUsageInstructions,maxSubAgentCalls:m,maxTurns:g,hasInspectRuntime:gp(this.rlmConfig.contextPolicy).stateInspection.enabled,enforceIncrementalConsoleTurns:this.enforceIncrementalConsoleTurns,agentModuleNamespace:this.agentModuleNamespace,discoveryMode:this.functionDiscoveryEnabled,availableModules:x,agents:f,agentFunctions:h}),C=Ls(this.responderDescription,r);this.actorProgram?(this.actorProgram.setSignature(p),this.actorProgram.setDescription(b)):this.actorProgram=new ke(p,{...this._genOptions,description:b}),this.responderProgram?(this.responderProgram.setSignature(d),this.responderProgram.setDescription(C)):this.responderProgram=new ke(d,{...this._genOptions,description:C})}_extendForSharedFields(e,t){let n=this.program.getSignature(),r=n.getInputFields(),o=!1;for(let i of e){if(r.some(a=>a.name===i.name)){if(this._parentSharedFields.has(i.name))throw new Error(`Duplicate shared field "${i.name}" \u2014 already propagated from a parent`);continue}this._parentSharedFields.add(i.name),n.addInputField(i),o=!0}o&&this.program.setSignature(n);for(let i of e)t.includes(i.name)&&!this.rlmConfig.contextFields.includes(i.name)&&this.rlmConfig.contextFields.push(i.name);this._buildSplitPrograms(),this.func&&(this.func.parameters=this._buildFuncParameters())}_extendForSharedAgents(e){if(e.length===0)return;let t=new Set((this.agents??[]).map(o=>o.getFunction().name)),n=new Set(this.excludedAgents),r=[];for(let o of e){if(o===this)continue;let i=o.getFunction().name;if(!n.has(i)){if(t.has(i)){if(this._parentSharedAgents.has(i))throw new Error(`Duplicate shared agent "${i}" \u2014 already propagated from a parent`);continue}this._parentSharedAgents.add(i),t.add(i),r.push(o)}}if(r.length!==0){this.agents=[...this.agents??[],...r];for(let o of r){let i=o.getFunction().name;this.program.register(o,i)}this._buildSplitPrograms()}}_extendForGlobalSharedFields(e,t){let n=this.program.getSignature(),r=n.getInputFields(),o=!1;for(let i of e){if(r.some(a=>a.name===i.name)){if(this._parentSharedFields.has(i.name))throw new Error(`Duplicate shared field "${i.name}" \u2014 already propagated from a parent`);continue}this._parentSharedFields.add(i.name),n.addInputField(i),o=!0}o&&this.program.setSignature(n);for(let i of e)t.includes(i.name)&&!this.rlmConfig.contextFields.includes(i.name)&&this.rlmConfig.contextFields.push(i.name);for(let i of e)this.sharedFieldNames.includes(i.name)||this.sharedFieldNames.push(i.name);if(this._buildSplitPrograms(),this.func&&(this.func.parameters=this._buildFuncParameters()),this.agents)for(let i of this.agents){if(!(i instanceof s))continue;let a=new Set(i.getExcludedSharedFields()),l=e.filter(u=>!a.has(u.name));l.length!==0&&i._extendForGlobalSharedFields(l,t)}}_extendForGlobalSharedAgents(e){let t=this.agents?this.agents.filter(n=>n instanceof s):[];this._extendForSharedAgents(e);for(let n of t)n._extendForGlobalSharedAgents(e)}_extendForSharedAgentFunctions(e){if(e.functions.length===0&&e.moduleMetadata.length===0)return;let t=new Set(this.agentFunctions.map(i=>`${i.namespace??"utils"}.${i.name}`)),n=new Set(this.excludedAgentFunctions),r=[],o=this._mergeAgentFunctionModuleMetadata(e.moduleMetadata);for(let i of e.functions){if(n.has(i.name))continue;let a=`${i.namespace??"utils"}.${i.name}`;if(t.has(a)){if(this._parentSharedAgentFunctions.has(a))throw new Error(`Duplicate shared agent function "${a}" \u2014 already propagated from a parent`);continue}this._parentSharedAgentFunctions.add(a),t.add(a),r.push(i)}r.length===0&&!o||(r.length>0&&(this.agentFunctions=[...this.agentFunctions,...r]),this._buildSplitPrograms())}_extendForGlobalSharedAgentFunctions(e){let t=this.agents?this.agents.filter(n=>n instanceof s):[];this._extendForSharedAgentFunctions(e);for(let n of t)n._extendForGlobalSharedAgentFunctions(e)}stop(){this._stopRequested=!0;for(let e of this.activeAbortControllers)e.abort("Stopped by user");this.program.stop(),this.actorProgram.stop(),this.responderProgram.stop()}getId(){return this.program.getId()}setId(e){this.program.setId(e)}namedPrograms(){return this.program.namedPrograms()}getTraces(){return this.program.getTraces()}setDemos(e,t){this.program.setDemos(e,t)}getUsage(){return this.program.getUsage()}resetUsage(){this.program.resetUsage()}getFunction(){if(!this.func)throw new Error("getFunction() requires agentIdentity to be set in the constructor");let e=this.forward.bind(this);return{...this.func,func:async(r,o)=>{let i=this.ai??o?.ai;if(!i)throw new Error("AI service is required to run the agent");let a=await e(i,r,o),u=this.program.getSignature().getOutputFields();return Object.keys(a).map(p=>{let d=u.find(m=>m.name===p);return d?`${d.title}: ${a[p]}`:`${p}: ${a[p]}`}).join(`
861
+ `)}}}getExcludedSharedFields(){return this.excludedSharedFields}_getBypassedSharedFieldNames(){let e=new Set([...this.sharedFieldNames,...this.globalSharedFieldNames]);for(let t of this.localFieldNames)e.delete(t);return e}_createRuntimeInputState(e,t){let n;Array.isArray(e)?n=e.filter(h=>h.role==="user").reduce((h,A)=>({...h,...A.values}),{}):n=e;let r=t?.allowedFieldNames?new Set(t.allowedFieldNames):void 0;if(r&&t?.validateInputKeys){for(let h of Object.keys(n))if(!r.has(h))throw new Error(`AxAgent.test() only accepts context field values. "${h}" is not configured in contextFields.`)}let o={...n},i=r?new Set(r):new Set(this.program.getSignature().getInputFields().map(h=>h.name)),a=[...this.sharedFieldNames,...this.globalSharedFieldNames],l=this._getBypassedSharedFieldNames(),u={},c={},p={},d={},m="(none)",g=new Set(this.program.getSignature().getInputFields().filter(h=>this.rlmConfig.contextFields.includes(h.name)&&h.isOptional).map(h=>h.name));return{currentInputs:o,signatureInputFieldNames:i,sharedFieldValues:u,recomputeTurnInputs:h=>{let A={},x={};for(let[C,I]of Object.entries(o))this.rlmConfig.contextFields.includes(C)?A[C]=I:l.has(C)||(x[C]=I);if(h){for(let C of this.rlmConfig.contextFields)if(!g.has(C)&&(!(C in A)||A[C]===void 0))throw new Error(`RLM contextField "${C}" is missing from input values`)}let b={};for(let[C,I]of this.contextPromptConfigByField){if(l.has(C)||!(C in A))continue;let v=Ag(A[C],I);v!==void 0&&(b[C]=v)}c=A,p=x,d=b;for(let C of Object.keys(u))delete u[C];for(let C of a)C in o&&(u[C]=o[C]),C in c&&(u[C]=c[C]);m=Cg(c,{promptConfigByField:this.contextPromptConfigByField,inlinedFields:new Set(Object.keys(d))})||"(none)"},getNonContextValues:()=>p,getActorInlineContextValues:()=>d,getContextMetadata:()=>m}}_createRuntimeExecutionContext({ai:e,inputState:t,options:n,effectiveAbortSignal:r,debug:o,completionState:i,completionBindings:a}){let l=this.rlmConfig,u=this.runtime,c=l.maxSubAgentCalls??cp,p=l.maxRuntimeChars??ug,d=Math.max(1,l.maxBatchedLlmQueryConcurrency??cg),m=this.recursionForwardOptions?.maxDepth??pg,g=Math.max(0,m),f=gp(l.contextPolicy),h=0,A=Math.floor(c*.8),{maxDepth:x,...b}=this.recursionForwardOptions??{},{description:C,mem:I,sessionId:v,...O}=n??{},k={...this.recursionForwardOptions??{},maxDepth:Math.max(0,g-1)},S=["context"],$=he().input("task",he.string("Task for recursive analysis")).input("context",he.json("Optional context for the recursive task")).output("answer",he.string("Answer from recursive analysis")).build(),L=(l.mode??"simple")==="advanced"&&(k.maxDepth??0)>0?"advanced":"simple",w;g>0&&(L==="advanced"?w=new s({agentModuleNamespace:this.agentModuleNamespace,signature:$},{debug:o,...l,agents:{local:this.agents},functions:{local:this.agentFunctions,discovery:this.functionDiscoveryEnabled},contextFields:S,actorFields:void 0,recursionOptions:k,actorOptions:this.actorForwardOptions,responderOptions:this.responderForwardOptions}):w=new ke($,k));let R=async(y,D)=>{if(!Array.isArray(y)&&typeof y=="object"&&y!==null&&"query"in y)return R(y.query,y.context??D);if(r?.aborted)throw new Pe("rlm-llm-query",r.reason?String(r.reason):"Aborted");if(Array.isArray(y))return Tg(y,d,async K=>{try{return await R(K.query,K.context)}catch(J){if(J instanceof Pe)throw J;return`[ERROR] ${J instanceof Error?J.message:String(J)}`}});if(!e)throw new Error(mg);let B=y,j=K=>{if(K==null)return"";if(typeof K=="string")return ut(K,p);try{return ut(JSON.stringify(K),p)}catch{return ut(String(K),p)}},z=await(async(K,J)=>{let oe=J===void 0?void 0:typeof J=="string"?ut(J,p):J;if(h++,h>c)return`[ERROR] Sub-query budget exhausted (${c}/${c}). Use the data you have already accumulated to produce your final answer.`;if(g<=0||!w)return`[ERROR] Recursion depth limit reached (${m}).`;let se=3,ue,de=Ae=>`[ERROR] ${Ae instanceof Error?Ae.message:String(Ae)}`;for(let Ae=0;Ae<se;Ae++)try{let Ce=await w.forward(e,{task:K,...oe!==void 0?{context:oe}:L==="advanced"?{context:""}:{}},{...O,...b,abortSignal:r,debug:o});return j(Ce.answer)}catch(Ce){if(Ce instanceof Pe)throw Ce;if(ue=Ce,!fg(Ce)||Ae>=se-1)return de(Ce);let Oe=Math.min(6e4,1e3*Math.pow(2,Ae));await new Promise((X,ee)=>{let ie=!1,ae,we=()=>{r&&ae&&r.removeEventListener("abort",ae)},Ye=setTimeout(()=>{ie||(ie=!0,we(),X())},Oe);if(r){if(ae=()=>{ie||(ie=!0,clearTimeout(Ye),we(),ee(new Pe("rlm-llm-query-retry-backoff",r.reason?String(r.reason):"Aborted during retry backoff")))},r.aborted){ae();return}r.addEventListener("abort",ae,{once:!0})}})}return de(ue)})(B,D);return h===A?`${z}
862
+ [WARNING] ${h}/${c} sub-queries used. Plan to wrap up soon.`:z},E=this.buildRuntimeGlobals(r,t.sharedFieldValues,e,a.protocol),_=[...new Set(this.agentFunctions.map(y=>y.namespace??"utils"))],M={...t.currentInputs},N=new Set(["inputs","llmQuery",Ds,this.agentModuleNamespace,"final","ask_clarification",..._,...f.stateInspection.enabled?["inspect_runtime"]:[],...Object.keys(E)]),q=[...new Set([...Object.keys(M),...t.signatureInputFieldNames])].filter(y=>!N.has(y)),U={};for(let y of q)U[y]=M[y];let W=()=>{for(let y of Object.keys(M))delete M[y];for(let[y,D]of Object.entries(t.currentInputs))M[y]=D;for(let y of q)U[y]=t.currentInputs[y]},Y=[...N],Q=[...N,...q],V,te,ye=async()=>{try{let y=await V.execute(ap(),{signal:r,reservedNames:Q});if(typeof y!="string")return[];let D=JSON.parse(y);return Array.isArray(D)?D.filter(B=>typeof B=="string"):[]}catch{return[]}},Te=async()=>(te||(te=await ye()),te),Z=async()=>{try{let y=await Te(),D=ip(Q,y),B=await V.execute(D,{signal:r,reservedNames:Q});return typeof B=="string"?B:String(B)}catch(y){return`[inspect_runtime error: ${y instanceof Error?y.message:String(y)}]`}},fe=f.stateInspection.enabled?async()=>Z():void 0,Re=()=>(te=void 0,u.createSession({...U,inputs:M,llmQuery:R,final:a.finalFunction,ask_clarification:a.askClarificationFunction,...fe?{inspect_runtime:fe}:{},...E}));V=Re();let re=async()=>{if(!i.payload)for(let y=0;y<3&&!i.payload;y++)await new Promise(D=>{setTimeout(D,0)})},xe=y=>{let D=f.stateSummary.maxEntries&&f.stateSummary.maxEntries>0?f.stateSummary.maxEntries:8;return y.split(`
863
+ `).map(B=>B.trim()).filter(Boolean).slice(0,D).join(`
864
+ `)},le=async()=>{if(!f.stateSummary.enabled)return;let y=await Z();return xe(y)||"(no user variables)"},Ie=y=>{if(typeof y.patchGlobals!="function")throw new Error("AxCodeSession.patchGlobals() is required when using inputUpdateCallback");return y};return{effectiveContextConfig:f,captureRuntimeStateSummary:le,syncRuntimeInputsToSession:async()=>{W();let y=async D=>{await Ie(D).patchGlobals({inputs:{...M},...U},{signal:r})};try{await y(V)}catch(D){if(r?.aborted)throw new Pe("rlm-session",r.reason??"Aborted");if(D instanceof Error&&(D.name==="AbortError"||D.message.startsWith("Aborted")))throw D;if(xp(D)){V=Re(),await y(V);return}throw new Error(`Failed to sync runtime inputs: ${Us(D,p)}`)}},executeActorCode:async y=>{let D={output:Gs(void 0,p),isError:!1};try{let B=await V.execute(y,{signal:r,reservedNames:Y});return i.payload||fp(y)&&hp(B)&&(await re(),i.payload)?D:{output:Gs(B,p),isError:!1}}catch(B){if(B instanceof Zn||i.payload)return D;if(r?.aborted)throw new Pe("rlm-session",r.reason??"Aborted");if(B instanceof Error&&(B.name==="AbortError"||B.message.startsWith("Aborted")))throw B;if(hg(B))return{output:ut(`${Bs}
865
+ ${Us(B,p)}`,p),isError:!0};if(xp(B))try{V=Re(),i.payload=void 0;let j=await V.execute(y,{signal:r,reservedNames:Y});return{output:ut(`${Bs}
866
+ ${Gs(j,p)}`,p),isError:!1}}catch(j){return{output:ut(`${Bs}
867
+ ${Us(j,p)}`,p),isError:!0}}return{output:ut(Us(B,p),p),isError:!0}}},executeTestCode:async y=>{try{let D=await V.execute(y,{signal:r,reservedNames:Y});if(fp(y)&&hp(D)&&await re(),i.payload)throw new Error(dp);let B=Gs(D,p);if(xg(B))throw new Error(B);return B}catch(D){throw D instanceof Zn||i.payload?new Error(dp):D}},close:()=>{V.close()}}}getExcludedAgents(){return this.excludedAgents}getExcludedAgentFunctions(){return this.excludedAgentFunctions}getSignature(){return this.program.getSignature()}async test(e,t,n){let r=this.ai??n?.ai,o=n?.debug??this.debug??r?.getOptions()?.debug??!1,i=this._createRuntimeInputState(t??{},{allowedFieldNames:this.rlmConfig.contextFields,validateInputKeys:!0});i.recomputeTurnInputs(!1);let a={payload:void 0},l=mp((c,p)=>{if(p.length===0)throw new Error(`${c}() requires at least one argument`);a.payload={type:c,args:p}}),u=this._createRuntimeExecutionContext({ai:r,inputState:i,options:void 0,effectiveAbortSignal:n?.abortSignal,debug:o,completionState:a,completionBindings:l});try{return await u.executeTestCode(e)}finally{u.close()}}setSignature(e){let t=new Me(e);this._validateConfiguredSignature(t);let n=this.program.getSignature();try{this.program.setSignature(t),this._buildSplitPrograms(),this.func&&(this.func.parameters=this._buildFuncParameters())}catch(r){throw this.program.setSignature(n),this._buildSplitPrograms(),this.func&&(this.func.parameters=this._buildFuncParameters()),r}}applyOptimization(e){this.program.applyOptimization?.(e)}async _runActorLoop(e,t,n,r){let o=this.rlmConfig,i=n?.debug??this.debug??e?.getOptions()?.debug??!1,a=o.maxTurns??pp,l=this._createRuntimeInputState(t);l.recomputeTurnInputs(!1);let u={payload:void 0},c=mp((O,k)=>{if(k.length===0)throw new Error(`${O}() requires at least one argument`);u.payload={type:O,args:k}}),p=this._createRuntimeExecutionContext({ai:e,inputState:l,options:n,effectiveAbortSignal:r,debug:i,completionState:u,completionBindings:c}),d=async()=>{if(!this.inputUpdateCallback)return;let O=await this.inputUpdateCallback({...l.currentInputs});if(O!==void 0){if(!O||typeof O!="object"||Array.isArray(O))throw new Error("inputUpdateCallback must return an object patch or undefined");for(let[k,S]of Object.entries(O))l.signatureInputFieldNames.has(k)&&(l.currentInputs[k]=S)}},m=[],g,f={...this._genOptions,...this.actorForwardOptions,...n,debug:i,abortSignal:r},h={},A=p.effectiveContextConfig.stateInspection.enabled?p.effectiveContextConfig.stateInspection.contextThreshold:void 0,x,b=()=>{let O=Math.max(m.length-p.effectiveContextConfig.recentFullActions,0);return m.slice(0,O).filter(k=>!k.tags.includes("error"))},C=()=>_a(m,{actionReplay:p.effectiveContextConfig.actionReplay,recentFullActions:p.effectiveContextConfig.recentFullActions,stateSummary:g,checkpointSummary:x?.summary,checkpointTurns:x?.turns})||"(no actions yet)",I=async()=>{if(!p.effectiveContextConfig.checkpoints.enabled){x=void 0;return}let O=_a(m,{actionReplay:p.effectiveContextConfig.actionReplay,recentFullActions:p.effectiveContextConfig.recentFullActions,stateSummary:g}),k=p.effectiveContextConfig.checkpoints.triggerChars;if(!k||O.length<=k){x=void 0;return}let S=b();if(S.length===0){x=void 0;return}let $=JSON.stringify(S.map(G=>({turn:G.turn,code:G.code,output:G.output,actorFieldsOutput:G.actorFieldsOutput,tags:G.tags,tombstone:G.tombstone})));x?.fingerprint!==$&&(x={fingerprint:$,turns:S.map(G=>G.turn),summary:await op(e,S)})};try{for(let O=0;O<a;O++){await d(),l.recomputeTurnInputs(!0),g=await p.captureRuntimeStateSummary(),await I();let k=C();A&&k.length>A&&(k+="\n\n[HINT: Action log is large. Call `const state = await inspect_runtime()` for a compact snapshot of current variables instead of re-reading old outputs.]");let S=await this.actorProgram.forward(e,{...l.getNonContextValues(),...l.getActorInlineContextValues(),contextMetadata:l.getContextMetadata(),actionLog:k},f);O===0&&(f.debugHideSystemPrompt=!0),o.actorCallback&&await o.actorCallback(S);for(let E of this.actorFieldNames)E in S&&(h[E]=S[E]);let $=S.javascriptCode,G=$?.trim();if(!$||!G)break;$=G;let L="";if(this.actorFieldNames.length>0){let E=this.actorFieldNames.filter(_=>_ in S).map(_=>`${_}: ${S[_]}`).join(`
868
+ `);E&&(L=`
816
869
  Actor fields:
817
- ${Te}`)}if(X=void 0,this.enforceIncrementalConsoleTurns){let Te=Nm(Le);if(Te){J.push({turn:z+1,code:Le,output:Te,actorFieldsOutput:_e,tags:["error"]}),await Ca(J,J.length-1,Z,e);continue}}this.inputUpdateCallback&&await Fe();let{output:te,isError:ke}=await ge(Le);if(J.push({turn:z+1,code:Le,output:te,actorFieldsOutput:_e,tags:ke?["error"]:[]}),await Ca(J,J.length-1,Z,e),X)break}}finally{try{j.close()}catch{}}let et=X??{type:"final",args:[Es(J)||"(no actions were taken)"]};return{nonContextValues:f,contextMetadata:y,actionLog:Es(J),actorResult:et,actorFieldValues:me}}async forward(e,t,n){let r=new AbortController;this._stopRequested&&r.abort("Stopped by user (pre-forward)");let o=Ft(r.signal,n?.abortSignal);this.activeAbortControllers.add(r);try{let i=this.ai??e,a=n?.debug??this.debug??i?.getOptions()?.debug??!1,{nonContextValues:l,actorResult:u,actorFieldValues:c}=await this._runActorLoop(i,t,n,o),p={...this._genOptions,...this.responderForwardOptions,...n,debug:a,abortSignal:o,maxSteps:1};return{...await this.responderProgram.forward(i,{...l,contextData:u},p),...c}}finally{this.activeAbortControllers.delete(r),this._stopRequested=!1}}async*streamingForward(e,t,n){let r=new AbortController;this._stopRequested&&r.abort("Stopped by user (pre-forward)");let o=Ft(r.signal,n?.abortSignal);this.activeAbortControllers.add(r);try{let i=this.ai??e,a=n?.debug??this.debug??i?.getOptions()?.debug??!1,{nonContextValues:l,contextMetadata:u,actorResult:c,actorFieldValues:p}=await this._runActorLoop(i,t,n,o),d={...this._genOptions,...this.responderForwardOptions,...n,debug:a,abortSignal:o,maxSteps:1};for await(let m of this.responderProgram.streamingForward(i,{...l,contextMetadata:u,actorResult:c},d))yield m;Object.keys(p).length>0&&(yield{version:1,index:0,delta:p})}finally{this.activeAbortControllers.delete(r),this._stopRequested=!1}}static wrapFunction(e,t,n){return async(...r)=>{let o;if(r.length===1&&typeof r[0]=="object"&&r[0]!==null&&!Array.isArray(r[0]))o=r[0];else{let i=e.parameters?.properties?Object.keys(e.parameters.properties):[];o={},i.forEach((a,l)=>{l<r.length&&(o[a]=r[l])})}return await e.func(o,{abortSignal:t,ai:n})}}static wrapFunctionWithSharedFields(e,t,n,r){return typeof n!="function"&&(!n||Object.keys(n).length===0)?s.wrapFunction(e,t,r):async(...o)=>{let i;if(o.length===1&&typeof o[0]=="object"&&o[0]!==null&&!Array.isArray(o[0]))i=o[0];else{let u=e.parameters?.properties?Object.keys(e.parameters.properties):[];i={},u.forEach((c,p)=>{p<o.length&&(i[c]=o[p])})}let a=typeof n=="function"?n():n,l=a?{...a,...i}:i;return await e.func(l,{abortSignal:t,ai:r})}}buildRuntimeGlobals(e,t,n){let r={},o=new Map,i=new Map,a=(l,u)=>{o.set(u,l),i.has(l.module)||i.set(l.module,[]),i.get(l.module)?.push(u)};for(let l of this.agentFunctions){let u=l.namespace??"utils";(!r[u]||typeof r[u]!="object")&&(r[u]={}),r[u][l.name]=s.wrapFunction(l,e,n),a({module:u,name:l.name,description:l.description,parameters:l.parameters,returns:l.returns},`${u}.${l.name}`)}if(this.agents&&this.agents.length>0){let l={};for(let u of this.agents){let c=u.getFunction(),p=new Set(u.getExcludedSharedFields?.()??[]),d=()=>{let m={};if(t)for(let[g,f]of Object.entries(t))p.has(g)||(m[g]=f);return m};l[c.name]=s.wrapFunctionWithSharedFields(c,e,d,n),a({module:this.agentModuleNamespace,name:c.name,description:c.description,parameters:c.parameters},`${this.agentModuleNamespace}.${c.name}`)}r[this.agentModuleNamespace]=l}return this.functionDiscoveryEnabled&&(r[wa]=async l=>{let u=Hc(l,"modules");return zm(u,i)},r[Ra]=async l=>{let u=Hc(l,"functions");return Hm(u,o)}),r}get _genOptions(){if(!this.options)return{};let{agents:e,fields:t,functions:n,inputUpdateCallback:r,...o}=this.options;return o}_buildFuncParameters(){let e=this.program.getSignature().toInputJSONSchema();return this._parentSharedFields.size>0?Gm(e,this._parentSharedFields):e}};function Kc(s,e){let t=typeof s=="string"?Be.create(s):s,{ai:n,agentIdentity:r,...o}=e;return new Jr({ai:n,agentIdentity:r,signature:t},o)}function Om(s){return s instanceof tt&&s.status>=500&&s.status<600?!0:s instanceof We||s instanceof at}function ht(s,e){return s.length<=e?s:`${s.slice(0,e)}
818
- ...[truncated ${s.length-e} chars]`}function Mm(s){if(typeof s=="string")return s.length;try{return JSON.stringify(s).length}catch{return String(s).length}}function Em(s,e,t){let n=new Set(e.map(a=>a.name)),r=new Set,o=[],i=new Map;for(let a of s){let l=typeof a=="string"?a:a.field;if(!n.has(l))throw new Error(`RLM contextField "${l}" not found in signature`);if(r.has(l))throw new Error(`Duplicate contextField "${l}"`);if(r.add(l),o.push(l),typeof a!="string"){let u=a.promptMaxChars??t;if(!Number.isFinite(u)||u<0)throw new Error(`contextField "${l}" promptMaxChars must be a finite number >= 0`);i.set(l,u)}}return{contextFieldNames:o,promptMaxCharsByField:i}}function Pm(s,e){let t=[];for(let[n,r]of Object.entries(s)){let o=Array.isArray(r)?"array":typeof r,i=typeof r=="string"?`${r.length} chars`:Array.isArray(r)?`${r.length} items`:r&&typeof r=="object"?`${Object.keys(r).length} keys`:"n/a",a=e?.promptMaxCharsByField?.get(n),l=a===void 0?"runtime-only":e?.inlinedFields?.has(n)?`inline (<=${a} chars)`:`runtime-only (>${a} chars)`;t.push(`- ${n}: type=${o}, size=${i}, prompt=${l}`)}return t.join(`
819
- `)}async function Fm(s,e,t){if(s.length===0)return[];let n=new Array(s.length),r=0,o=Math.max(1,Math.min(e,s.length)),i=Array.from({length:o},async()=>{for(;;){let a=r++;if(a>=s.length)return;let l=s[a];if(l===void 0)return;n[a]=await t(l,a)}});return await Promise.all(i),n}function _m(s){return s.includes("console.log")}function Nm(s){let e=$m(s),t=/\bfinal\s*\(/.test(e),n=/\bask_clarification\s*\(/.test(e),r=Number(t)+Number(n),o=Lm(e);if(r>1)return"[POLICY] Use exactly one completion signal per turn: either final(...) or ask_clarification(...), not both.";if(r===1)return o.length>0?"[POLICY] Do not combine console.log(...) with final(...)/ask_clarification(...) in the same turn. Inspect in one turn, then complete in the next turn.":void 0;if(o.length===0)return"[POLICY] Non-final turns must include exactly one console.log(...) so the next turn can reason from its output.";if(o.length>1)return"[POLICY] Use exactly one console.log(...) per non-final turn, then stop.";let i=o[0];if(i===void 0)return"[POLICY] Unable to verify console.log(...) usage. Emit exactly one console.log(...) per non-final turn.";if(i.closeParenIndex===void 0)return"[POLICY] Could not parse console.log(...). Keep a single valid console.log(...) call as the last statement in non-final turns.";if(e.slice(i.closeParenIndex+1).replace(/^[\s;]+/,"").length>0)return"[POLICY] End non-final turns immediately after console.log(...). Do not execute additional statements after logging."}function $m(s){let e="",t=0,n="normal",r=!1;for(;t<s.length;){let o=s[t]??"",i=s[t+1]??"";if(n==="lineComment"){o===`
870
+ ${E}`)}if(u.payload=void 0,this.enforceIncrementalConsoleTurns){let E=Rg($);if(E){m.push({turn:O+1,code:$,output:E,actorFieldsOutput:L,tags:["error"]}),await Fa(m,m.length-1,p.effectiveContextConfig,e),g=await p.captureRuntimeStateSummary(),await I();continue}}this.inputUpdateCallback&&await p.syncRuntimeInputsToSession();let{output:w,isError:R}=await p.executeActorCode($);if(m.push({turn:O+1,code:$,output:w,actorFieldsOutput:L,tags:R?["error"]:[]}),await Fa(m,m.length-1,p.effectiveContextConfig,e),g=await p.captureRuntimeStateSummary(),await I(),u.payload)break}}finally{try{p.close()}catch{}}await I();let v=u.payload??{type:"final",args:[sp(m,{stateSummary:g,checkpointSummary:x?.summary,checkpointTurns:x?.turns})]};return{nonContextValues:l.getNonContextValues(),contextMetadata:l.getContextMetadata(),actionLog:C(),actorResult:v,actorFieldValues:h}}async forward(e,t,n){let r=new AbortController;this._stopRequested&&r.abort("Stopped by user (pre-forward)");let o=St(r.signal,n?.abortSignal);this.activeAbortControllers.add(r);try{let i=this.ai??e,a=n?.debug??this.debug??i?.getOptions()?.debug??!1,{nonContextValues:l,actorResult:u,actorFieldValues:c}=await this._runActorLoop(i,t,n,o),p={...this._genOptions,...this.responderForwardOptions,...n,debug:a,abortSignal:o,maxSteps:1};return{...await this.responderProgram.forward(i,{...l,contextData:u},p),...c}}finally{this.activeAbortControllers.delete(r),this._stopRequested=!1}}async*streamingForward(e,t,n){let r=new AbortController;this._stopRequested&&r.abort("Stopped by user (pre-forward)");let o=St(r.signal,n?.abortSignal);this.activeAbortControllers.add(r);try{let i=this.ai??e,a=n?.debug??this.debug??i?.getOptions()?.debug??!1,{nonContextValues:l,actorResult:u,actorFieldValues:c}=await this._runActorLoop(i,t,n,o),p={...this._genOptions,...this.responderForwardOptions,...n,debug:a,abortSignal:o,maxSteps:1};for await(let d of this.responderProgram.streamingForward(i,{...l,contextData:u},p))yield d;Object.keys(c).length>0&&(yield{version:1,index:0,delta:c})}finally{this.activeAbortControllers.delete(r),this._stopRequested=!1}}static wrapFunction(e,t,n,r){return async(...o)=>{let i;if(o.length===1&&typeof o[0]=="object"&&o[0]!==null&&!Array.isArray(o[0]))i=o[0];else{let a=e.parameters?.properties?Object.keys(e.parameters.properties):[];i={},a.forEach((l,u)=>{u<o.length&&(i[l]=o[u])})}return await e.func(i,{abortSignal:t,ai:n,protocol:r})}}static wrapFunctionWithSharedFields(e,t,n,r,o){return typeof n!="function"&&(!n||Object.keys(n).length===0)?s.wrapFunction(e,t,r,o):async(...i)=>{let a;if(i.length===1&&typeof i[0]=="object"&&i[0]!==null&&!Array.isArray(i[0]))a=i[0];else{let c=e.parameters?.properties?Object.keys(e.parameters.properties):[];a={},c.forEach((p,d)=>{d<i.length&&(a[p]=i[d])})}let l=typeof n=="function"?n():n,u=l?{...l,...a}:a;return await e.func(u,{abortSignal:t,ai:r,protocol:o})}}buildRuntimeGlobals(e,t,n,r){let o={},i=new Map,a=new Map,l=new Map;for(let[c,p]of this.agentFunctionModuleMetadata)l.set(c,p);let u=(c,p)=>{i.set(p,c),a.has(c.module)||a.set(c.module,[]),a.get(c.module)?.push(p)};for(let c of this.agentFunctions){let p=c.namespace??"utils";(!o[p]||typeof o[p]!="object")&&(o[p]={}),o[p][c.name]=s.wrapFunction(c,e,n,r),u({module:p,name:c.name,description:c.description,parameters:c.parameters,returns:c.returns,examples:c.examples},`${p}.${c.name}`)}if(this.agents&&this.agents.length>0){let c={};for(let p of this.agents){let d=p.getFunction(),m=new Set(p.getExcludedSharedFields?.()??[]),g=()=>{let f={};if(t)for(let[h,A]of Object.entries(t))m.has(h)||(f[h]=A);return f};c[d.name]=s.wrapFunctionWithSharedFields(d,e,g,n,r),u({module:this.agentModuleNamespace,name:d.name,description:d.description,parameters:d.parameters},`${this.agentModuleNamespace}.${d.name}`)}o[this.agentModuleNamespace]=c}return this.functionDiscoveryEnabled&&(o[$a]=async c=>{let p=yp(c,"modules");return _g(p,a,l)},o[La]=async c=>{let p=yp(c,"functions");return Ng(p,i)}),o}get _genOptions(){if(!this.options)return{};let{agents:e,fields:t,functions:n,inputUpdateCallback:r,...o}=this.options;return o}_buildFuncParameters(){let e=this.program.getSignature().toInputJSONSchema();return this._parentSharedFields.size>0?kg(e,this._parentSharedFields):e}};function bp(s,e){let t=typeof s=="string"?Me.create(s):s,{ai:n,agentIdentity:r,...o}=e;return new Jr({ai:n,agentIdentity:r,signature:t},o)}function fg(s){return s instanceof ze&&s.status>=500&&s.status<600?!0:s instanceof Le||s instanceof et}function ut(s,e){return s.length<=e?s:`${s.slice(0,e)}
871
+ ...[truncated ${s.length-e} chars]`}function Gs(s,e){if(s===void 0)return"(no output)";if(typeof s=="string")return ut(s||"(no output)",e);try{return ut(JSON.stringify(s,null,2),e)}catch{return ut(String(s),e)}}function Us(s,e){let t=s,n=t?.name??"Error",r=t?.message??String(s),o=[`${n}: ${r}`];if(t?.data!==void 0)try{o.push(`Data: ${JSON.stringify(t.data,null,2)}`)}catch{o.push(`Data: ${String(t.data)}`)}if(t?.cause!==void 0){let i=(a,l)=>{if(l>4)return"[cause chain truncated]";let u=a,c=u?.name??"Error",p=u?.message??String(a),d=[`${c}: ${p}`];if(u?.data!==void 0)try{d.push(`Data: ${JSON.stringify(u.data,null,2)}`)}catch{d.push(`Data: ${String(u.data)}`)}return u?.cause!==void 0&&d.push(`Caused by: ${i(u.cause,l+1)}`),d.join(`
872
+ `)};o.push(`Caused by: ${i(t.cause,1)}`)}return ut(o.join(`
873
+ `),e)}function fp(s){let e=Ip(s);return/\bfinal\s*\(/.test(e)||/\bask_clarification\s*\(/.test(e)}function hp(s){return s&&(typeof s=="object"||typeof s=="function")&&"then"in s&&typeof s.then=="function"?!0:typeof s=="string"&&s.trim()==="[object Promise]"}function xp(s){return s instanceof Error&&s.message==="Session is closed"}function hg(s){return s instanceof Error&&s.message==="Execution timed out"}function xg(s){return s.startsWith("[ERROR]")||s.startsWith(Bs)?!0:/^(AggregateError|Error|EvalError|RangeError|ReferenceError|SyntaxError|TypeError|URIError): /.test(s)}function Ag(s,e){if(e.kind==="threshold")return bg(s)<=e.promptMaxChars?s:void 0;if(typeof s!="string")return;let t=e.keepInPromptChars;if(s.length<=t)return s;let n=s.length-t;if(e.reverseTruncate){let o=t>0?s.slice(-t):"";return`[truncated ${n} chars]...${o}`}return`${t>0?s.slice(0,t):""}...[truncated ${n} chars]`}function yg(s,e,t){return e.kind==="threshold"?t?`inline (<=${e.promptMaxChars} chars)`:`runtime-only (>${e.promptMaxChars} chars)`:typeof s!="string"?"runtime-only (keepInPromptChars requires string)":t?s.length<=e.keepInPromptChars?`inline (<=${e.keepInPromptChars} chars)`:e.reverseTruncate?`inline-truncated(last ${e.keepInPromptChars} chars of ${s.length})`:`inline-truncated(first ${e.keepInPromptChars} chars of ${s.length})`:"runtime-only"}function bg(s){if(typeof s=="string")return s.length;try{return JSON.stringify(s).length}catch{return String(s).length}}function Ig(s,e,t){let n=new Set(e.map(a=>a.name)),r=new Set,o=[],i=new Map;for(let a of s){let l=typeof a=="string"?a:a.field;if(!n.has(l))throw new Error(`RLM contextField "${l}" not found in signature`);if(r.has(l))throw new Error(`Duplicate contextField "${l}"`);if(r.add(l),o.push(l),typeof a!="string"){let u=a.keepInPromptChars!==void 0,c=a.promptMaxChars!==void 0;if(u&&c)throw new Error(`contextField "${l}" cannot set both promptMaxChars and keepInPromptChars`);if("reverseTruncate"in a&&!u)throw new Error(`contextField "${l}" reverseTruncate requires keepInPromptChars`);if(u){let d=a.keepInPromptChars;if(!Number.isFinite(d)||d===void 0||d<0)throw new Error(`contextField "${l}" keepInPromptChars must be a finite number >= 0`);i.set(l,{kind:"truncate",keepInPromptChars:d,reverseTruncate:a.reverseTruncate===!0});continue}let p=a.promptMaxChars??t;if(!Number.isFinite(p)||p<0)throw new Error(`contextField "${l}" promptMaxChars must be a finite number >= 0`);i.set(l,{kind:"threshold",promptMaxChars:p})}}return{contextFieldNames:o,promptConfigByField:i}}function Cg(s,e){let t=[];for(let[n,r]of Object.entries(s)){let o=Array.isArray(r)?"array":typeof r,i=typeof r=="string"?`${r.length} chars`:Array.isArray(r)?`${r.length} items`:r&&typeof r=="object"?`${Object.keys(r).length} keys`:"n/a",a=e?.promptConfigByField?.get(n),l=a===void 0?"runtime-only":yg(r,a,e?.inlinedFields?.has(n)===!0);t.push(`- ${n}: type=${o}, size=${i}, prompt=${l}`)}return t.join(`
874
+ `)}async function Tg(s,e,t){if(s.length===0)return[];let n=new Array(s.length),r=0,o=Math.max(1,Math.min(e,s.length)),i=Array.from({length:o},async()=>{for(;;){let a=r++;if(a>=s.length)return;let l=s[a];if(l===void 0)return;n[a]=await t(l,a)}});return await Promise.all(i),n}function wg(s){return s.includes("console.log")}function Rg(s){let e=Ip(s),t=/\bfinal\s*\(/.test(e),n=/\bask_clarification\s*\(/.test(e),r=Number(t)+Number(n),o=vg(e);if(r>1)return"[POLICY] Use exactly one completion signal per turn: either final(...) or ask_clarification(...), not both.";if(r===1)return o.length>0?"[POLICY] Do not combine console.log(...) with final(...)/ask_clarification(...) in the same turn. Inspect in one turn, then complete in the next turn.":void 0;if(o.length===0)return"[POLICY] Non-final turns must include exactly one console.log(...) so the next turn can reason from its output.";if(o.length>1)return"[POLICY] Use exactly one console.log(...) per non-final turn, then stop.";let i=o[0];if(i===void 0)return"[POLICY] Unable to verify console.log(...) usage. Emit exactly one console.log(...) per non-final turn.";if(i.closeParenIndex===void 0)return"[POLICY] Could not parse console.log(...). Keep a single valid console.log(...) call as the last statement in non-final turns.";if(e.slice(i.closeParenIndex+1).replace(/^[\s;]+/,"").length>0)return"[POLICY] End non-final turns immediately after console.log(...). Do not execute additional statements after logging."}function Ip(s){let e="",t=0,n="normal",r=!1;for(;t<s.length;){let o=s[t]??"",i=s[t+1]??"";if(n==="lineComment"){o===`
820
875
  `?(e+=`
821
876
  `,n="normal"):e+=" ",t++;continue}if(n==="blockComment"){o==="*"&&i==="/"?(e+=" ",t+=2,n="normal"):(e+=o===`
822
877
  `?`
@@ -824,14 +879,19 @@ ${Te}`)}if(X=void 0,this.enforceIncrementalConsoleTurns){let Te=Nm(Le);if(Te){J.
824
879
  `?`
825
880
  `:" ",r=!1,t++;continue}if(o==="\\"){e+=" ",r=!0,t++;continue}if(o===a){e+=" ",n="normal",t++;continue}e+=o===`
826
881
  `?`
827
- `:" ",t++;continue}if(o==="/"&&i==="/"){e+=" ",t+=2,n="lineComment";continue}if(o==="/"&&i==="*"){e+=" ",t+=2,n="blockComment";continue}if(o==="'"){e+=" ",t++,n="single";continue}if(o==='"'){e+=" ",t++,n="double";continue}if(o==="`"){e+=" ",t++,n="template";continue}e+=o,t++}return e}function Lm(s){let e=s.matchAll(/\bconsole\s*\.\s*log\s*\(/g),t=[];for(let n of e){let r=n[0];if(r===void 0)continue;let o=n.index??-1;if(o<0)continue;let i=r.lastIndexOf("("),a=o+i,l=Dm(s,a);t.push({closeParenIndex:l})}return t}function Dm(s,e){if(e<0||s[e]!=="(")return;let t=0;for(let n=e;n<s.length;n++){let r=s[n];if(r==="(")t++;else if(r===")"&&(t--,t===0))return n}}function Gm(s,e){if(!s.properties||e.size===0)return s;let t=Object.fromEntries(Object.entries(s.properties).filter(([r])=>!e.has(r))),n=s.required?.filter(r=>!e.has(r));return{...s,properties:t,...n!==void 0?{required:n}:{}}}function Um(s,e){let t=s.trim(),r=e?.normalize??!0?Vc(t):t;if(!r)throw new Error("Agent module namespace must contain letters or numbers");return r}function Hc(s,e){if(typeof s=="string"){let n=s.trim();if(n.length===0)throw new Error(`${e} must be a non-empty string`);return[n]}if(!Array.isArray(s))throw new Error(`${e} must be a string or string[]`);if(!s.every(n=>typeof n=="string"))throw new Error(`${e} must contain only strings`);let t=s.map(n=>n).map(n=>n.trim()).filter(n=>n.length>0);if(t.length===0)throw new Error(`${e} must contain at least one non-empty string`);return[...new Set(t)]}function Bm(s){let e=s.type;return Array.isArray(e)?e.filter(t=>typeof t=="string"):typeof e=="string"?e.includes(",")?e.split(",").map(t=>t.trim()).filter(Boolean):[e]:[]}function jm(s){let e=new Set(s);return e.has("object")&&e.has("array")&&e.has("string")&&e.has("number")&&e.has("boolean")&&e.has("null")}function va(s){if(s.enum)return s.enum.map(n=>`"${n}"`).join(" | ");let e=Bm(s);if(e.length===0)return"unknown";if(jm(e))return"any";let t=[...new Set(e)].map(n=>{if(n==="array"){let r=s.items?va(s.items):"unknown";return r.includes(" | ")?`(${r})[]`:`${r}[]`}return n==="object"?s.properties&&Object.keys(s.properties).length>0?Wc(s):"object":n});return t.length>1?t.join(" | "):t[0]??"unknown"}function Wc(s,e){if(!s)return"{}";let t=!!s.properties&&Object.keys(s.properties).length>0,n=s.additionalProperties===!0;if(!t)return n?"{ [key: string]: unknown }":"{}";let r=new Set(s.required??[]),o=e?.respectRequired??!1,i=Object.entries(s.properties).map(([a,l])=>{let u=va(l),c=o&&!r.has(a)?"?":"";return`${a}${c}: ${u}`});return s.additionalProperties===!0&&i.push("[key: string]: unknown"),`{ ${i.join(", ")} }`}function qm(s){let e=Wc(s.parameters,{respectRequired:!0}),t=s.returns?`: Promise<${va(s.returns)}>`:"";return`- \`${s.qualifiedName}(args: ${e})${t}\``}function zm(s,e){return s.map(t=>{let n=[...e.get(t)??[]].sort((o,i)=>o.localeCompare(i)),r=n.length>0?n.map(o=>`- \`${o}\``).join(`
828
- `):"- (not found)";return`### Module \`${t}\`
829
- ${r}`}).join(`
882
+ `:" ",t++;continue}if(o==="/"&&i==="/"){e+=" ",t+=2,n="lineComment";continue}if(o==="/"&&i==="*"){e+=" ",t+=2,n="blockComment";continue}if(o==="'"){e+=" ",t++,n="single";continue}if(o==='"'){e+=" ",t++,n="double";continue}if(o==="`"){e+=" ",t++,n="template";continue}e+=o,t++}return e}function vg(s){let e=s.matchAll(/\bconsole\s*\.\s*log\s*\(/g),t=[];for(let n of e){let r=n[0];if(r===void 0)continue;let o=n.index??-1;if(o<0)continue;let i=r.lastIndexOf("("),a=o+i,l=Sg(s,a);t.push({closeParenIndex:l})}return t}function Sg(s,e){if(e<0||s[e]!=="(")return;let t=0;for(let n=e;n<s.length;n++){let r=s[n];if(r==="(")t++;else if(r===")"&&(t--,t===0))return n}}function kg(s,e){if(!s.properties||e.size===0)return s;let t=Object.fromEntries(Object.entries(s.properties).filter(([r])=>!e.has(r))),n=s.required?.filter(r=>!e.has(r));return{...s,properties:t,...n!==void 0?{required:n}:{}}}function Og(s,e){let t=s.trim(),r=e?.normalize??!0?Tp(t):t;if(!r)throw new Error("Agent module namespace must contain letters or numbers");return r}function Ap(s){return Array.isArray(s.functions)}function Da(s,e){if(!s||s.length===0)return{functions:[],moduleMetadata:[]};let t=s.every(a=>Ap(a)),n=s.every(a=>!Ap(a));if(!t&&!n)throw new Error("Agent functions collections must contain either flat functions or grouped function modules, not both");if(n)return{functions:[...s],moduleMetadata:[]};let r=new Set,o=[],i=[];for(let a of s){let l=a.namespace.trim(),u=a.title.trim(),c=a.selectionCriteria.trim(),p=a.description.trim();if(!l)throw new Error("Agent function group namespace must be a non-empty string");if(!u)throw new Error(`Agent function group "${l}" must define a non-empty title`);if(!c)throw new Error(`Agent function group "${l}" must define a non-empty selectionCriteria`);if(!p)throw new Error(`Agent function group "${l}" must define a non-empty description`);if(e.has(l))throw new Error(`Agent function namespace "${l}" conflicts with an AxAgent runtime global and is reserved`);if(r.has(l))throw new Error(`Duplicate agent function group namespace "${l}"`);if(a.functions.length===0)throw new Error(`Agent function group "${l}" must contain at least one function`);r.add(l),o.push({namespace:l,title:u,selectionCriteria:c,description:p});for(let d of a.functions){if("namespace"in d&&d.namespace!==void 0)throw new Error(`Grouped agent function "${l}.${d.name}" must not define namespace; use the parent group namespace instead`);i.push({...d,namespace:l})}}return{functions:i,moduleMetadata:o}}function yp(s,e){if(typeof s=="string"){let n=s.trim();if(n.length===0)throw new Error(`${e} must be a non-empty string`);return[n]}if(!Array.isArray(s))throw new Error(`${e} must be a string or string[]`);if(!s.every(n=>typeof n=="string"))throw new Error(`${e} must contain only strings`);let t=s.map(n=>n).map(n=>n.trim()).filter(n=>n.length>0);if(t.length===0)throw new Error(`${e} must contain at least one non-empty string`);return[...new Set(t)]}function Ga(s){let e=s.type;return Array.isArray(e)?e.filter(t=>typeof t=="string"):typeof e=="string"?e.includes(",")?e.split(",").map(t=>t.trim()).filter(Boolean):[e]:[]}function Mg(s){let e=new Set(s);return e.has("object")&&e.has("array")&&e.has("string")&&e.has("number")&&e.has("boolean")&&e.has("null")}function Yr(s){if(s.enum)return s.enum.map(n=>`"${n}"`).join(" | ");let e=Ga(s);if(e.length===0)return"unknown";if(Mg(e))return"any";let t=[...new Set(e)].map(n=>{if(n==="array"){let r=s.items?Yr(s.items):"unknown";return r.includes(" | ")?`(${r})[]`:`${r}[]`}return n==="object"?s.properties&&Object.keys(s.properties).length>0?Cp(s):"object":n});return t.length>1?t.join(" | "):t[0]??"unknown"}function Cp(s,e){if(!s)return"{}";let t=!!s.properties&&Object.keys(s.properties).length>0,n=s.additionalProperties===!0;if(!t)return n?"{ [key: string]: unknown }":"{}";let r=new Set(s.required??[]),o=e?.respectRequired??!1,i=Object.entries(s.properties).map(([a,l])=>{let u=Yr(l),c=o&&!r.has(a)?"?":"";return`${a}${c}: ${u}`});return s.additionalProperties===!0&&i.push("[key: string]: unknown"),`{ ${i.join(", ")} }`}function Eg(s){let e=Cp(s.parameters,{respectRequired:!0}),t=s.returns?`: Promise<${Yr(s.returns)}>`:"";return`- \`${s.qualifiedName}(args: ${e})${t}\``}function Ua(s,e="",t=!0){if(!s?.properties)return[];let n=new Set(s.required??[]),r=[];for(let[o,i]of Object.entries(s.properties)){let a=e?`${e}.${o}`:o,l=i.description?.trim();l&&r.push({name:a,type:Yr(i),required:t?n.has(o):void 0,description:l});let u=Ga(i);if(u.includes("object")&&i.properties&&r.push(...Ua(i,a,!1)),u.includes("array")&&i.items){let c=i.items.description?.trim(),p=`${a}[]`;c&&r.push({name:p,type:Yr(i.items),description:c}),Ga(i.items).includes("object")&&i.items.properties&&r.push(...Ua(i.items,p,!1))}}return r}function Pg(s){let e=Ua(s);if(e.length!==0)return["#### Arguments",...e.map(t=>{let n=t.required===void 0?`\`${t.type}\``:`\`${t.type}\`, ${t.required?"required":"optional"}`;return`- \`${t.name}\` (${n}): ${t.description}`})].join(`
883
+ `)}function Fg(s){return!s||s.length===0?void 0:["#### Examples",s.map(t=>{let n=[];return t.title?.trim()&&n.push(`##### ${t.title.trim()}`),t.description?.trim()&&n.push(t.description.trim()),n.push(`\`\`\`${t.language?.trim()||"typescript"}`),n.push(t.code),n.push("```"),n.join(`
884
+ `)}).join(`
885
+
886
+ `)].join(`
887
+ `)}function _g(s,e,t){return s.map(n=>{let r=[...e.get(n)??[]].map(u=>u.split(".").pop()??u).sort((u,c)=>u.localeCompare(c)),o=r.length>0,i=o?t.get(n):void 0,a=o?r.map(u=>`- \`${u}\``).join(`
888
+ `):`- Error: module \`${n}\` does not exist.`,l=[`### Module \`${n}\``];return i&&(l.push(`**${i.title}**`),l.push(i.description)),l.push(a),l.join(`
889
+ `)}).join(`
830
890
 
831
- `)}function Hm(s,e){return s.map(t=>{let n=t.includes(".")?t:`utils.${t}`,r=e.get(n);return r?[`### \`${n}\``,r.description,qm({qualifiedName:n,parameters:r.parameters,returns:r.returns})].join(`
891
+ `)}function Ng(s,e){return s.map(t=>{let n=t.includes(".")?t:`utils.${t}`,r=e.get(n);return r?[`### \`${n}\``,r.description,Eg({qualifiedName:n,parameters:r.parameters,returns:r.returns}),Pg(r.parameters),Fg(r.examples)].filter(o=>!!o).join(`
832
892
  `):`### \`${n}\`
833
893
  - Not found.`}).join(`
834
894
 
835
- `)}function Vc(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("")}var Jc=(s,e)=>{let t=e?.maxHops??3,n=e?.qualityThreshold??.8,r=e?.maxIterations??2,o=e?.qualityTarget??.85,i=e?.disableQualityHealing??!1;return Cs({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(`
836
- `):"").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 op(Km);})();
895
+ `)}function Tp(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("")}var wp=(s,e)=>{let t=e?.maxHops??3,n=e?.qualityThreshold??.8,r=e?.maxIterations??2,o=e?.qualityTarget??.85,i=e?.disableQualityHealing??!1;return Rs({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(`
896
+ `):"").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 Lp($g);})();
837
897
  //# sourceMappingURL=index.global.js.map