@ax-llm/ax 19.0.22 → 19.0.23

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 wd=Object.create;var bo=Object.defineProperty;var Rd=Object.getOwnPropertyDescriptor;var vd=Object.getOwnPropertyNames;var Sd=Object.getPrototypeOf,kd=Object.prototype.hasOwnProperty;var Od=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var To=(o,e)=>()=>(e||o((e={exports:{}}).exports,e),e.exports),Ed=(o,e)=>{for(var t in e)bo(o,t,{get:e[t],enumerable:!0})},yu=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of vd(e))!kd.call(o,r)&&r!==t&&bo(o,r,{get:()=>e[r],enumerable:!(n=Rd(e,r))||n.enumerable});return o};var xr=(o,e,t)=>(t=o!=null?wd(Sd(o)):{},yu(e||!o||!o.__esModule?bo(t,"default",{value:o,enumerable:!0}):t,o)),Md=o=>yu(bo({},"__esModule",{value:!0}),o);var ml=To((ua,ca)=>{"use strict";(function(o,e){typeof ua=="object"&&typeof ca<"u"?ca.exports=e():typeof define=="function"&&define.amd?define(e):(o=typeof globalThis<"u"?globalThis:o||self).dayjs=e()})(ua,function(){"use strict";var o=1e3,e=6e4,t=36e5,n="millisecond",r="second",s="minute",i="hour",a="day",u="week",c="month",l="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,x={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(N){var S=["th","st","nd","rd"],v=N%100;return"["+N+(S[(v-20)%10]||S[v]||S[0])+"]"}},A=function(N,S,v){var F=String(N);return!F||F.length>=S?N:""+Array(S+1-F.length).join(v)+N},h={s:A,z:function(N){var S=-N.utcOffset(),v=Math.abs(S),F=Math.floor(v/60),P=v%60;return(S<=0?"+":"-")+A(F,2,"0")+":"+A(P,2,"0")},m:function N(S,v){if(S.date()<v.date())return-N(v,S);var F=12*(v.year()-S.year())+(v.month()-S.month()),P=S.clone().add(F,c),L=v-P<0,D=S.clone().add(F+(L?-1:1),c);return+(-(F+(v-P)/(L?P-D:D-P))||0)},a:function(N){return N<0?Math.ceil(N)||0:Math.floor(N)},p:function(N){return{M:c,y:p,w:u,d:a,D:d,h:i,m:s,s:r,ms:n,Q:l}[N]||String(N||"").toLowerCase().replace(/s$/,"")},u:function(N){return N===void 0}},y="en",T={};T[y]=x;var C="$isDayjsObject",R=function(N){return N instanceof E||!(!N||!N[C])},M=function N(S,v,F){var P;if(!S)return y;if(typeof S=="string"){var L=S.toLowerCase();T[L]&&(P=L),v&&(T[L]=v,P=L);var D=S.split("-");if(!P&&D.length>1)return N(D[0])}else{var j=S.name;T[j]=S,P=j}return!F&&P&&(y=P),P||!F&&y},I=function(N,S){if(R(N))return N.clone();var v=typeof S=="object"?S:{};return v.date=N,v.args=arguments,new E(v)},O=h;O.l=M,O.i=R,O.w=function(N,S){return I(N,{locale:S.$L,utc:S.$u,x:S.$x,$offset:S.$offset})};var E=function(){function N(v){this.$L=M(v.locale,null,!0),this.parse(v),this.$x=this.$x||v.x||{},this[C]=!0}var S=N.prototype;return S.parse=function(v){this.$d=function(F){var P=F.date,L=F.utc;if(P===null)return new Date(NaN);if(O.u(P))return new Date;if(P instanceof Date)return new Date(P);if(typeof P=="string"&&!/Z$/i.test(P)){var D=P.match(g);if(D){var j=D[2]-1||0,G=(D[7]||"0").substring(0,3);return L?new Date(Date.UTC(D[1],j,D[3]||1,D[4]||0,D[5]||0,D[6]||0,G)):new Date(D[1],j,D[3]||1,D[4]||0,D[5]||0,D[6]||0,G)}}return new Date(P)}(v),this.init()},S.init=function(){var v=this.$d;this.$y=v.getFullYear(),this.$M=v.getMonth(),this.$D=v.getDate(),this.$W=v.getDay(),this.$H=v.getHours(),this.$m=v.getMinutes(),this.$s=v.getSeconds(),this.$ms=v.getMilliseconds()},S.$utils=function(){return O},S.isValid=function(){return this.$d.toString()!==m},S.isSame=function(v,F){var P=I(v);return this.startOf(F)<=P&&P<=this.endOf(F)},S.isAfter=function(v,F){return I(v)<this.startOf(F)},S.isBefore=function(v,F){return this.endOf(F)<I(v)},S.$g=function(v,F,P){return O.u(v)?this[F]:this.set(P,v)},S.unix=function(){return Math.floor(this.valueOf()/1e3)},S.valueOf=function(){return this.$d.getTime()},S.startOf=function(v,F){var P=this,L=!!O.u(F)||F,D=O.p(v),j=function(ie,W){var q=O.w(P.$u?Date.UTC(P.$y,W,ie):new Date(P.$y,W,ie),P);return L?q:q.endOf(a)},G=function(ie,W){return O.w(P.toDate()[ie].apply(P.toDate("s"),(L?[0,0,0,0]:[23,59,59,999]).slice(W)),P)},H=this.$W,re=this.$M,le=this.$D,B="set"+(this.$u?"UTC":"");switch(D){case p:return L?j(1,0):j(31,11);case c:return L?j(1,re):j(0,re+1);case u:var V=this.$locale().weekStart||0,Q=(H<V?H+7:H)-V;return j(L?le-Q:le+(6-Q),re);case a:case d:return G(B+"Hours",0);case i:return G(B+"Minutes",1);case s:return G(B+"Seconds",2);case r:return G(B+"Milliseconds",3);default:return this.clone()}},S.endOf=function(v){return this.startOf(v,!1)},S.$set=function(v,F){var P,L=O.p(v),D="set"+(this.$u?"UTC":""),j=(P={},P[a]=D+"Date",P[d]=D+"Date",P[c]=D+"Month",P[p]=D+"FullYear",P[i]=D+"Hours",P[s]=D+"Minutes",P[r]=D+"Seconds",P[n]=D+"Milliseconds",P)[L],G=L===a?this.$D+(F-this.$W):F;if(L===c||L===p){var H=this.clone().set(d,1);H.$d[j](G),H.init(),this.$d=H.set(d,Math.min(this.$D,H.daysInMonth())).$d}else j&&this.$d[j](G);return this.init(),this},S.set=function(v,F){return this.clone().$set(v,F)},S.get=function(v){return this[O.p(v)]()},S.add=function(v,F){var P,L=this;v=Number(v);var D=O.p(F),j=function(re){var le=I(L);return O.w(le.date(le.date()+Math.round(re*v)),L)};if(D===c)return this.set(c,this.$M+v);if(D===p)return this.set(p,this.$y+v);if(D===a)return j(1);if(D===u)return j(7);var G=(P={},P[s]=e,P[i]=t,P[r]=o,P)[D]||1,H=this.$d.getTime()+v*G;return O.w(H,this)},S.subtract=function(v,F){return this.add(-1*v,F)},S.format=function(v){var F=this,P=this.$locale();if(!this.isValid())return P.invalidDate||m;var L=v||"YYYY-MM-DDTHH:mm:ssZ",D=O.z(this),j=this.$H,G=this.$m,H=this.$M,re=P.weekdays,le=P.months,B=P.meridiem,V=function(W,q,oe,Ce){return W&&(W[q]||W(F,L))||oe[q].slice(0,Ce)},Q=function(W){return O.s(j%12||12,W,"0")},ie=B||function(W,q,oe){var Ce=W<12?"AM":"PM";return oe?Ce.toLowerCase():Ce};return L.replace(f,function(W,q){return q||function(oe){switch(oe){case"YY":return String(F.$y).slice(-2);case"YYYY":return O.s(F.$y,4,"0");case"M":return H+1;case"MM":return O.s(H+1,2,"0");case"MMM":return V(P.monthsShort,H,le,3);case"MMMM":return V(le,H);case"D":return F.$D;case"DD":return O.s(F.$D,2,"0");case"d":return String(F.$W);case"dd":return V(P.weekdaysMin,F.$W,re,2);case"ddd":return V(P.weekdaysShort,F.$W,re,3);case"dddd":return re[F.$W];case"H":return String(j);case"HH":return O.s(j,2,"0");case"h":return Q(1);case"hh":return Q(2);case"a":return ie(j,G,!0);case"A":return ie(j,G,!1);case"m":return String(G);case"mm":return O.s(G,2,"0");case"s":return String(F.$s);case"ss":return O.s(F.$s,2,"0");case"SSS":return O.s(F.$ms,3,"0");case"Z":return D}return null}(W)||D.replace(":","")})},S.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},S.diff=function(v,F,P){var L,D=this,j=O.p(F),G=I(v),H=(G.utcOffset()-this.utcOffset())*e,re=this-G,le=function(){return O.m(D,G)};switch(j){case p:L=le()/12;break;case c:L=le();break;case l:L=le()/3;break;case u:L=(re-H)/6048e5;break;case a:L=(re-H)/864e5;break;case i:L=re/t;break;case s:L=re/e;break;case r:L=re/o;break;default:L=re}return P?L:O.a(L)},S.daysInMonth=function(){return this.endOf(c).$D},S.$locale=function(){return T[this.$L]},S.locale=function(v,F){if(!v)return this.$L;var P=this.clone(),L=M(v,F,!0);return L&&(P.$L=L),P},S.clone=function(){return O.w(this.$d,this)},S.toDate=function(){return new Date(this.valueOf())},S.toJSON=function(){return this.isValid()?this.toISOString():null},S.toISOString=function(){return this.$d.toISOString()},S.toString=function(){return this.$d.toUTCString()},N}(),$=E.prototype;return I.prototype=$,[["$ms",n],["$s",r],["$m",s],["$H",i],["$W",a],["$M",c],["$y",p],["$D",d]].forEach(function(N){$[N[1]]=function(S){return this.$g(S,N[0],N[1])}}),I.extend=function(N,S){return N.$i||(N(S,E,I),N.$i=!0),I},I.locale=M,I.isDayjs=R,I.unix=function(N){return I(1e3*N)},I.en=T[y],I.Ls=T,I.p={},I})});var gl=To((la,pa)=>{"use strict";(function(o,e){typeof la=="object"&&typeof pa<"u"?pa.exports=e():typeof define=="function"&&define.amd?define(e):(o=typeof globalThis<"u"?globalThis:o||self).dayjs_plugin_customParseFormat=e()})(la,function(){"use strict";var o={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?/,s=/\d*[^-_:/,()\s\d]+/,i={},a=function(g){return(g=+g)+(g>68?1900:2e3)},u=function(g){return function(f){this[g]=+f}},c=[/[+-]\d\d:?(\d\d)?|Z/,function(g){(this.zone||(this.zone={})).offset=function(f){if(!f||f==="Z")return 0;var x=f.match(/([+-]|\d\d)/g),A=60*x[1]+(+x[2]||0);return A===0?0:x[0]==="+"?-A:A}(g)}],l=function(g){var f=i[g];return f&&(f.indexOf?f:f.s.concat(f.f))},p=function(g,f){var x,A=i.meridiem;if(A){for(var h=1;h<=24;h+=1)if(g.indexOf(A(h,0,f))>-1){x=h>12;break}}else x=g===(f?"pm":"PM");return x},d={A:[s,function(g){this.afternoon=p(g,!1)}],a:[s,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,u("seconds")],ss:[r,u("seconds")],m:[r,u("minutes")],mm:[r,u("minutes")],H:[r,u("hours")],h:[r,u("hours")],HH:[r,u("hours")],hh:[r,u("hours")],D:[r,u("day")],DD:[n,u("day")],Do:[s,function(g){var f=i.ordinal,x=g.match(/\d+/);if(this.day=x[0],f)for(var A=1;A<=31;A+=1)f(A).replace(/\[|\]/g,"")===g&&(this.day=A)}],w:[r,u("week")],ww:[n,u("week")],M:[r,u("month")],MM:[n,u("month")],MMM:[s,function(g){var f=l("months"),x=(l("monthsShort")||f.map(function(A){return A.slice(0,3)})).indexOf(g)+1;if(x<1)throw new Error;this.month=x%12||x}],MMMM:[s,function(g){var f=l("months").indexOf(g)+1;if(f<1)throw new Error;this.month=f%12||f}],Y:[/[+-]?\d+/,u("year")],YY:[n,function(g){this.year=a(g)}],YYYY:[/\d{4}/,u("year")],Z:c,ZZ:c};function m(g){var f,x;f=g,x=i&&i.formats;for(var A=(g=f.replace(/(\[[^\]]+])|(LTS?|l{1,4}|L{1,4})/g,function(I,O,E){var $=E&&E.toUpperCase();return O||x[E]||o[E]||x[$].replace(/(\[[^\]]+])|(MMMM|MM|DD|dddd)/g,function(N,S,v){return S||v.slice(1)})})).match(e),h=A.length,y=0;y<h;y+=1){var T=A[y],C=d[T],R=C&&C[0],M=C&&C[1];A[y]=M?{regex:R,parser:M}:T.replace(/^\[|\]$/g,"")}return function(I){for(var O={},E=0,$=0;E<h;E+=1){var N=A[E];if(typeof N=="string")$+=N.length;else{var S=N.regex,v=N.parser,F=I.slice($),P=S.exec(F)[0];v.call(O,P),I=I.replace(P,"")}}return function(L){var D=L.afternoon;if(D!==void 0){var j=L.hours;D?j<12&&(L.hours+=12):j===12&&(L.hours=0),delete L.afternoon}}(O),O}}return function(g,f,x){x.p.customParseFormat=!0,g&&g.parseTwoDigitYear&&(a=g.parseTwoDigitYear);var A=f.prototype,h=A.parse;A.parse=function(y){var T=y.date,C=y.utc,R=y.args;this.$u=C;var M=R[1];if(typeof M=="string"){var I=R[2]===!0,O=R[3]===!0,E=I||O,$=R[2];O&&($=R[2]),i=this.$locale(),!I&&$&&(i=x.Ls[$]),this.$d=function(F,P,L,D){try{if(["x","X"].indexOf(P)>-1)return new Date((P==="X"?1e3:1)*F);var j=m(P)(F),G=j.year,H=j.month,re=j.day,le=j.hours,B=j.minutes,V=j.seconds,Q=j.milliseconds,ie=j.zone,W=j.week,q=new Date,oe=re||(G||H?1:q.getDate()),Ce=G||q.getFullYear(),Re=0;G&&!H||(Re=H>0?H-1:q.getMonth());var ae,ke=le||0,ce=B||0,me=V||0,be=Q||0;return ie?new Date(Date.UTC(Ce,Re,oe,ke,ce,me,be+60*ie.offset*1e3)):L?new Date(Date.UTC(Ce,Re,oe,ke,ce,me,be)):(ae=new Date(Ce,Re,oe,ke,ce,me,be),W&&(ae=D(ae).week(W).toDate()),ae)}catch{return new Date("")}}(T,M,C,x),this.init(),$&&$!==!0&&(this.$L=this.locale($).$L),E&&T!=this.format(M)&&(this.$d=new Date("")),i={}}else if(M instanceof Array)for(var N=M.length,S=1;S<=N;S+=1){R[1]=M[S-1];var v=x.apply(this,R);if(v.isValid()){this.$d=v.$d,this.$L=v.$L,this.init();break}S===N&&(this.$d=new Date(""))}else h.call(this,y)}}})});var fl=To((da,ma)=>{"use strict";(function(o,e){typeof da=="object"&&typeof ma<"u"?ma.exports=e():typeof define=="function"&&define.amd?define(e):(o=typeof globalThis<"u"?globalThis:o||self).dayjs_plugin_timezone=e()})(da,function(){"use strict";var o={year:0,month:1,day:2,hour:3,minute:4,second:5},e={};return function(t,n,r){var s,i=function(l,p,d){d===void 0&&(d={});var m=new Date(l),g=function(f,x){x===void 0&&(x={});var A=x.timeZoneName||"short",h=f+"|"+A,y=e[h];return y||(y=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:f,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",timeZoneName:A}),e[h]=y),y}(p,d);return g.formatToParts(m)},a=function(l,p){for(var d=i(l,p),m=[],g=0;g<d.length;g+=1){var f=d[g],x=f.type,A=f.value,h=o[x];h>=0&&(m[h]=parseInt(A,10))}var y=m[3],T=y===24?0:y,C=m[0]+"-"+m[1]+"-"+m[2]+" "+T+":"+m[4]+":"+m[5]+":000",R=+l;return(r.utc(C).valueOf()-(R-=R%1e3))/6e4},u=n.prototype;u.tz=function(l,p){l===void 0&&(l=s);var d,m=this.utcOffset(),g=this.toDate(),f=g.toLocaleString("en-US",{timeZone:l}),x=Math.round((g-new Date(f))/1e3/60),A=15*-Math.round(g.getTimezoneOffset()/15)-x;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 h=d.utcOffset();d=d.add(m-h,"minute")}return d.$x.$timezone=l,d},u.offsetName=function(l){var p=this.$x.$timezone||r.tz.guess(),d=i(this.valueOf(),p,{timeZoneName:l}).find(function(m){return m.type.toLowerCase()==="timezonename"});return d&&d.value};var c=u.startOf;u.startOf=function(l,p){if(!this.$x||!this.$x.$timezone)return c.call(this,l,p);var d=r(this.format("YYYY-MM-DD HH:mm:ss:SSS"),{locale:this.$L});return c.call(d,l,p).tz(this.$x.$timezone,!0)},r.tz=function(l,p,d){var m=d&&p,g=d||p||s,f=a(+r(),g);if(typeof l!="string")return r(l).tz(g);var x=function(T,C,R){var M=T-60*C*1e3,I=a(M,R);if(C===I)return[M,C];var O=a(M-=60*(I-C)*1e3,R);return I===O?[M,I]:[T-60*Math.min(I,O)*1e3,Math.max(I,O)]}(r.utc(l,m).valueOf(),f,g),A=x[0],h=x[1],y=r(A).utcOffset(h);return y.$x.$timezone=g,y},r.tz.guess=function(){return Intl.DateTimeFormat().resolvedOptions().timeZone},r.tz.setDefault=function(l){s=l}}})});var hl=To((ga,fa)=>{"use strict";(function(o,e){typeof ga=="object"&&typeof fa<"u"?fa.exports=e():typeof define=="function"&&define.amd?define(e):(o=typeof globalThis<"u"?globalThis:o||self).dayjs_plugin_utc=e()})(ga,function(){"use strict";var o="minute",e=/[+-]\d\d(?::?\d\d)?/g,t=/([+-]|\d\d)/g;return function(n,r,s){var i=r.prototype;s.utc=function(m){var g={date:m,utc:!0,args:arguments};return new r(g)},i.utc=function(m){var g=s(this.toDate(),{locale:this.$L,utc:!0});return m?g.add(this.utcOffset(),o):g},i.local=function(){return s(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 u=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 u.call(this)};var c=i.utcOffset;i.utcOffset=function(m,g){var f=this.$utils().u;if(f(m))return this.$u?0:f(this.$offset)?c.call(this):this.$offset;if(typeof m=="string"&&(m=function(y){y===void 0&&(y="");var T=y.match(e);if(!T)return null;var C=(""+T[0]).match(t)||["-",0,0],R=C[0],M=60*+C[1]+ +C[2];return M===0?0:R==="+"?M:-M}(m),m===null))return this;var x=Math.abs(m)<=16?60*m:m,A=this;if(g)return A.$offset=x,A.$u=m===0,A;if(m!==0){var h=this.$u?this.toDate().getTimezoneOffset():-1*this.utcOffset();(A=this.local().add(x+h,o)).$offset=x,A.$x.$localOffset=h}else A=this.utc();return A};var l=i.format;i.format=function(m){var g=m||(this.$u?"YYYY-MM-DDTHH:mm:ss[Z]":"");return l.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?s(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 x=this.local(),A=s(m).local();return d.call(x,A,g,f)}}})});var Jh={};Ed(Jh,{AxACE:()=>nr,AxACEOptimizedProgram:()=>no,AxAI:()=>jr,AxAIAnthropic:()=>bn,AxAIAnthropicModel:()=>Rr,AxAIAnthropicVertexModel:()=>vr,AxAIAzureOpenAI:()=>Rn,AxAICohere:()=>vn,AxAICohereEmbedModel:()=>Er,AxAICohereModel:()=>Or,AxAIDeepSeek:()=>Sn,AxAIDeepSeekModel:()=>Mr,AxAIGoogleGemini:()=>kn,AxAIGoogleGeminiEmbedModel:()=>zo,AxAIGoogleGeminiEmbedTypes:()=>Ui,AxAIGoogleGeminiModel:()=>Pr,AxAIGoogleGeminiSafetyCategory:()=>qo,AxAIGoogleGeminiSafetyThreshold:()=>Ho,AxAIGrok:()=>Gn,AxAIGrokEmbedModels:()=>Xi,AxAIGrokModel:()=>Br,AxAIGroq:()=>En,AxAIGroqModel:()=>Fr,AxAIHuggingFace:()=>Mn,AxAIHuggingFaceModel:()=>Qo,AxAIMistral:()=>Pn,AxAIMistralEmbedModels:()=>qi,AxAIMistralModel:()=>_r,AxAIOllama:()=>Fn,AxAIOpenAI:()=>wn,AxAIOpenAIBase:()=>Ge,AxAIOpenAIEmbedModel:()=>Tn,AxAIOpenAIModel:()=>kr,AxAIOpenAIResponses:()=>Nn,AxAIOpenAIResponsesBase:()=>Nr,AxAIOpenAIResponsesImpl:()=>_n,AxAIOpenAIResponsesModel:()=>Cn,AxAIOpenRouter:()=>Ln,AxAIRefusalError:()=>Le,AxAIReka:()=>$n,AxAIRekaModel:()=>$r,AxAIServiceAbortedError:()=>Fe,AxAIServiceAuthenticationError:()=>Ut,AxAIServiceError:()=>et,AxAIServiceNetworkError:()=>Je,AxAIServiceResponseError:()=>Dt,AxAIServiceStatusError:()=>rt,AxAIServiceStreamTerminatedError:()=>ht,AxAIServiceTimeoutError:()=>gt,AxAITogether:()=>Dn,AxAITogetherModel:()=>Ur,AxAIWebLLM:()=>Un,AxAIWebLLMModel:()=>Gr,AxAgent:()=>ho,AxAgentClarificationError:()=>pt,AxApacheTika:()=>Es,AxAssertionError:()=>Pt,AxBalancer:()=>Do,AxBaseAI:()=>Be,AxBaseOptimizer:()=>It,AxBootstrapFewShot:()=>sr,AxContentProcessingError:()=>Rt,AxDB:()=>cs,AxDBBase:()=>At,AxDBCloudflare:()=>Bn,AxDBManager:()=>ls,AxDBMemory:()=>Wt,AxDBPinecone:()=>jn,AxDBWeaviate:()=>zn,AxDefaultCostTracker:()=>to,AxDefaultResultReranker:()=>Os,AxDockerSession:()=>qs,AxEmbeddingAdapter:()=>Hs,AxEvalUtil:()=>ep,AxFlow:()=>so,AxFlowDependencyAnalyzer:()=>ir,AxFlowExecutionPlanner:()=>ur,AxFlowSubContextImpl:()=>pr,AxFlowTypedSubContextImpl:()=>js,AxFluentFieldType:()=>We,AxFunctionError:()=>Vr,AxFunctionProcessor:()=>Qr,AxGEPA:()=>Yt,AxGen:()=>Me,AxGenerateError:()=>Zr,AxHFDataLoader:()=>Us,AxInstanceRegistry:()=>Jn,AxJSRuntime:()=>gn,AxJSRuntimePermission:()=>Za,AxLLMRequestTypeValues:()=>Ci,AxLearn:()=>Ds,AxMCPClient:()=>Vs,AxMCPHTTPSSETransport:()=>Ys,AxMCPStreambleHTTPTransport:()=>Qs,AxMediaNotSupportedError:()=>xt,AxMemory:()=>qn,AxMiPRO:()=>Bs,AxMockAIService:()=>Zo,AxMultiServiceRouter:()=>es,AxOptimizedProgramImpl:()=>Ct,AxProgram:()=>Qt,AxPromptTemplate:()=>ln,AxProviderRouter:()=>os,AxRateLimiterTokenUsage:()=>On,AxSignature:()=>Ne,AxSignatureBuilder:()=>Yr,AxSimpleClassifier:()=>Ps,AxSimpleClassifierClass:()=>Ms,AxSpanKindValues:()=>Ii,AxStepContextImpl:()=>Zn,AxStopFunctionCallException:()=>an,AxStringUtil:()=>ks,AxSynth:()=>or,AxTestPrompt:()=>Fs,AxTokenLimitError:()=>Ar,AxTraceLogger:()=>tr,agent:()=>Ad,ai:()=>Kc,ax:()=>it,axAIAnthropicDefaultConfig:()=>Pi,axAIAnthropicVertexDefaultConfig:()=>bc,axAIAzureOpenAIBestConfig:()=>wc,axAIAzureOpenAICreativeConfig:()=>Cc,axAIAzureOpenAIDefaultConfig:()=>_i,axAIAzureOpenAIFastConfig:()=>Ic,axAICohereCreativeConfig:()=>Oc,axAICohereDefaultConfig:()=>$i,axAIDeepSeekCodeConfig:()=>Ec,axAIDeepSeekDefaultConfig:()=>Di,axAIGoogleGeminiDefaultConfig:()=>Bi,axAIGoogleGeminiDefaultCreativeConfig:()=>_c,axAIGrokBestConfig:()=>Wc,axAIGrokDefaultConfig:()=>us,axAIHuggingFaceCreativeConfig:()=>Nc,axAIHuggingFaceDefaultConfig:()=>zi,axAIMistralBestConfig:()=>Lc,axAIMistralDefaultConfig:()=>Xo,axAIOllamaDefaultConfig:()=>Hi,axAIOllamaDefaultCreativeConfig:()=>$c,axAIOpenAIBestConfig:()=>No,axAIOpenAICreativeConfig:()=>Lo,axAIOpenAIDefaultConfig:()=>rn,axAIOpenAIFastConfig:()=>$o,axAIOpenAIResponsesBestConfig:()=>Dc,axAIOpenAIResponsesCreativeConfig:()=>Uc,axAIOpenAIResponsesDefaultConfig:()=>Lr,axAIOpenRouterDefaultConfig:()=>Ki,axAIRekaBestConfig:()=>jc,axAIRekaCreativeConfig:()=>zc,axAIRekaDefaultConfig:()=>Dr,axAIRekaFastConfig:()=>qc,axAITogetherDefaultConfig:()=>Ji,axAIWebLLMCreativeConfig:()=>Hc,axAIWebLLMDefaultConfig:()=>Yi,axAnalyzeChatPromptRequirements:()=>Gc,axAnalyzeRequestRequirements:()=>on,axBaseAIDefaultConfig:()=>Se,axBaseAIDefaultCreativeConfig:()=>He,axBuildActorDefinition:()=>ei,axBuildResponderDefinition:()=>ti,axCheckMetricsHealth:()=>Vc,axCreateDefaultColorLogger:()=>Ti,axCreateDefaultOptimizerColorLogger:()=>La,axCreateDefaultOptimizerTextLogger:()=>op,axCreateDefaultTextLogger:()=>zu,axCreateFlowColorLogger:()=>oo,axCreateFlowTextLogger:()=>mp,axCreateJSRuntime:()=>kp,axDefaultFlowLogger:()=>gp,axDefaultMetricsConfig:()=>na,axDefaultOptimizerLogger:()=>eo,axDefaultOptimizerMetricsConfig:()=>$a,axGetCompatibilityReport:()=>Rc,axGetFormatCompatibility:()=>Sc,axGetMetricsConfig:()=>Qc,axGetOptimizerMetricsConfig:()=>ip,axGetProvidersWithMediaSupport:()=>vc,axGlobals:()=>fe,axModelInfoAnthropic:()=>Sr,axModelInfoCohere:()=>Bo,axModelInfoDeepSeek:()=>jo,axModelInfoGoogleGemini:()=>Wo,axModelInfoGrok:()=>as,axModelInfoGroq:()=>Vo,axModelInfoHuggingFace:()=>Jo,axModelInfoMistral:()=>Yo,axModelInfoOpenAI:()=>In,axModelInfoOpenAIResponses:()=>_o,axModelInfoReka:()=>rs,axModelInfoTogether:()=>ss,axModelInfoWebLLM:()=>is,axProcessContentForProvider:()=>ns,axRAG:()=>Cd,axScoreProvidersForRequest:()=>Uo,axSelectOptimalProvider:()=>Go,axSpanAttributes:()=>ye,axSpanEvents:()=>vt,axUpdateMetricsConfig:()=>Jc,axUpdateOptimizerMetricsConfig:()=>sp,axValidateChatRequestMessage:()=>yn,axValidateChatResponseResult:()=>Fo,axValidateProviderCapabilities:()=>Ni,axWorkerRuntime:()=>Ws,f:()=>ge,flow:()=>zs,fn:()=>Ul,s:()=>np});function ft({model:o,modelInfo:e,models:t}){let n=t?.find(c=>c.key===o),r=n&&"model"in n?n.model:o,s=e.find(c=>c.name===o);if(s)return s;let i=e.find(c=>c.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+$/,""),u=e.find(c=>c.name===a);return u||null}var pi=(()=>{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 Ze(){return pi.randomUUID()}async function Pd(o){let e=new TextEncoder,t=typeof o=="string"?e.encode(o):o,n=await pi.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}var li=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 s=0;s<n.length;s++){let i=n[s];r=(r<<5)-r+i,r=r&r}return Math.abs(r).toString(16).padStart(8,"0")}async digestAsync(){return Pd(this.data)}};function mt(o){if(o!=="sha256")throw new Error("Only SHA-256 algorithm is supported");return new li}function bu(){return pi}var Co=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 Sd=Object.create;var yo=Object.defineProperty;var kd=Object.getOwnPropertyDescriptor;var Od=Object.getOwnPropertyNames;var Ed=Object.getPrototypeOf,Md=Object.prototype.hasOwnProperty;var Pd=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var bo=(o,e)=>()=>(e||o((e={exports:{}}).exports,e),e.exports),Fd=(o,e)=>{for(var t in e)yo(o,t,{get:e[t],enumerable:!0})},Iu=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Od(e))!Md.call(o,r)&&r!==t&&yo(o,r,{get:()=>e[r],enumerable:!(n=kd(e,r))||n.enumerable});return o};var Ar=(o,e,t)=>(t=o!=null?Sd(Ed(o)):{},Iu(e||!o||!o.__esModule?yo(t,"default",{value:o,enumerable:!0}):t,o)),_d=o=>Iu(yo({},"__esModule",{value:!0}),o);var fl=bo((ca,la)=>{"use strict";(function(o,e){typeof ca=="object"&&typeof la<"u"?la.exports=e():typeof define=="function"&&define.amd?define(e):(o=typeof globalThis<"u"?globalThis:o||self).dayjs=e()})(ca,function(){"use strict";var o=1e3,e=6e4,t=36e5,n="millisecond",r="second",s="minute",i="hour",a="day",u="week",c="month",l="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,x={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(N){var S=["th","st","nd","rd"],v=N%100;return"["+N+(S[(v-20)%10]||S[v]||S[0])+"]"}},A=function(N,S,v){var P=String(N);return!P||P.length>=S?N:""+Array(S+1-P.length).join(v)+N},h={s:A,z:function(N){var S=-N.utcOffset(),v=Math.abs(S),P=Math.floor(v/60),F=v%60;return(S<=0?"+":"-")+A(P,2,"0")+":"+A(F,2,"0")},m:function N(S,v){if(S.date()<v.date())return-N(v,S);var P=12*(v.year()-S.year())+(v.month()-S.month()),F=S.clone().add(P,c),U=v-F<0,L=S.clone().add(P+(U?-1:1),c);return+(-(P+(v-F)/(U?F-L:L-F))||0)},a:function(N){return N<0?Math.ceil(N)||0:Math.floor(N)},p:function(N){return{M:c,y:p,w:u,d:a,D:d,h:i,m:s,s:r,ms:n,Q:l}[N]||String(N||"").toLowerCase().replace(/s$/,"")},u:function(N){return N===void 0}},y="en",C={};C[y]=x;var I="$isDayjsObject",R=function(N){return N instanceof E||!(!N||!N[I])},M=function N(S,v,P){var F;if(!S)return y;if(typeof S=="string"){var U=S.toLowerCase();C[U]&&(F=U),v&&(C[U]=v,F=U);var L=S.split("-");if(!F&&L.length>1)return N(L[0])}else{var z=S.name;C[z]=S,F=z}return!P&&F&&(y=F),F||!P&&y},T=function(N,S){if(R(N))return N.clone();var v=typeof S=="object"?S:{};return v.date=N,v.args=arguments,new E(v)},O=h;O.l=M,O.i=R,O.w=function(N,S){return T(N,{locale:S.$L,utc:S.$u,x:S.$x,$offset:S.$offset})};var E=function(){function N(v){this.$L=M(v.locale,null,!0),this.parse(v),this.$x=this.$x||v.x||{},this[I]=!0}var S=N.prototype;return S.parse=function(v){this.$d=function(P){var F=P.date,U=P.utc;if(F===null)return new Date(NaN);if(O.u(F))return new Date;if(F instanceof Date)return new Date(F);if(typeof F=="string"&&!/Z$/i.test(F)){var L=F.match(g);if(L){var z=L[2]-1||0,j=(L[7]||"0").substring(0,3);return U?new Date(Date.UTC(L[1],z,L[3]||1,L[4]||0,L[5]||0,L[6]||0,j)):new Date(L[1],z,L[3]||1,L[4]||0,L[5]||0,L[6]||0,j)}}return new Date(F)}(v),this.init()},S.init=function(){var v=this.$d;this.$y=v.getFullYear(),this.$M=v.getMonth(),this.$D=v.getDate(),this.$W=v.getDay(),this.$H=v.getHours(),this.$m=v.getMinutes(),this.$s=v.getSeconds(),this.$ms=v.getMilliseconds()},S.$utils=function(){return O},S.isValid=function(){return this.$d.toString()!==m},S.isSame=function(v,P){var F=T(v);return this.startOf(P)<=F&&F<=this.endOf(P)},S.isAfter=function(v,P){return T(v)<this.startOf(P)},S.isBefore=function(v,P){return this.endOf(P)<T(v)},S.$g=function(v,P,F){return O.u(v)?this[P]:this.set(F,v)},S.unix=function(){return Math.floor(this.valueOf()/1e3)},S.valueOf=function(){return this.$d.getTime()},S.startOf=function(v,P){var F=this,U=!!O.u(P)||P,L=O.p(v),z=function(le,H){var q=O.w(F.$u?Date.UTC(F.$y,H,le):new Date(F.$y,H,le),F);return U?q:q.endOf(a)},j=function(le,H){return O.w(F.toDate()[le].apply(F.toDate("s"),(U?[0,0,0,0]:[23,59,59,999]).slice(H)),F)},K=this.$W,W=this.$M,pe=this.$D,G="set"+(this.$u?"UTC":"");switch(L){case p:return U?z(1,0):z(31,11);case c:return U?z(1,W):z(0,W+1);case u:var J=this.$locale().weekStart||0,Y=(K<J?K+7:K)-J;return z(U?pe-Y:pe+(6-Y),W);case a:case d:return j(G+"Hours",0);case i:return j(G+"Minutes",1);case s:return j(G+"Seconds",2);case r:return j(G+"Milliseconds",3);default:return this.clone()}},S.endOf=function(v){return this.startOf(v,!1)},S.$set=function(v,P){var F,U=O.p(v),L="set"+(this.$u?"UTC":""),z=(F={},F[a]=L+"Date",F[d]=L+"Date",F[c]=L+"Month",F[p]=L+"FullYear",F[i]=L+"Hours",F[s]=L+"Minutes",F[r]=L+"Seconds",F[n]=L+"Milliseconds",F)[U],j=U===a?this.$D+(P-this.$W):P;if(U===c||U===p){var K=this.clone().set(d,1);K.$d[z](j),K.init(),this.$d=K.set(d,Math.min(this.$D,K.daysInMonth())).$d}else z&&this.$d[z](j);return this.init(),this},S.set=function(v,P){return this.clone().$set(v,P)},S.get=function(v){return this[O.p(v)]()},S.add=function(v,P){var F,U=this;v=Number(v);var L=O.p(P),z=function(W){var pe=T(U);return O.w(pe.date(pe.date()+Math.round(W*v)),U)};if(L===c)return this.set(c,this.$M+v);if(L===p)return this.set(p,this.$y+v);if(L===a)return z(1);if(L===u)return z(7);var j=(F={},F[s]=e,F[i]=t,F[r]=o,F)[L]||1,K=this.$d.getTime()+v*j;return O.w(K,this)},S.subtract=function(v,P){return this.add(-1*v,P)},S.format=function(v){var P=this,F=this.$locale();if(!this.isValid())return F.invalidDate||m;var U=v||"YYYY-MM-DDTHH:mm:ssZ",L=O.z(this),z=this.$H,j=this.$m,K=this.$M,W=F.weekdays,pe=F.months,G=F.meridiem,J=function(H,q,re,Ce){return H&&(H[q]||H(P,U))||re[q].slice(0,Ce)},Y=function(H){return O.s(z%12||12,H,"0")},le=G||function(H,q,re){var Ce=H<12?"AM":"PM";return re?Ce.toLowerCase():Ce};return U.replace(f,function(H,q){return q||function(re){switch(re){case"YY":return String(P.$y).slice(-2);case"YYYY":return O.s(P.$y,4,"0");case"M":return K+1;case"MM":return O.s(K+1,2,"0");case"MMM":return J(F.monthsShort,K,pe,3);case"MMMM":return J(pe,K);case"D":return P.$D;case"DD":return O.s(P.$D,2,"0");case"d":return String(P.$W);case"dd":return J(F.weekdaysMin,P.$W,W,2);case"ddd":return J(F.weekdaysShort,P.$W,W,3);case"dddd":return W[P.$W];case"H":return String(z);case"HH":return O.s(z,2,"0");case"h":return Y(1);case"hh":return Y(2);case"a":return le(z,j,!0);case"A":return le(z,j,!1);case"m":return String(j);case"mm":return O.s(j,2,"0");case"s":return String(P.$s);case"ss":return O.s(P.$s,2,"0");case"SSS":return O.s(P.$ms,3,"0");case"Z":return L}return null}(H)||L.replace(":","")})},S.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},S.diff=function(v,P,F){var U,L=this,z=O.p(P),j=T(v),K=(j.utcOffset()-this.utcOffset())*e,W=this-j,pe=function(){return O.m(L,j)};switch(z){case p:U=pe()/12;break;case c:U=pe();break;case l:U=pe()/3;break;case u:U=(W-K)/6048e5;break;case a:U=(W-K)/864e5;break;case i:U=W/t;break;case s:U=W/e;break;case r:U=W/o;break;default:U=W}return F?U:O.a(U)},S.daysInMonth=function(){return this.endOf(c).$D},S.$locale=function(){return C[this.$L]},S.locale=function(v,P){if(!v)return this.$L;var F=this.clone(),U=M(v,P,!0);return U&&(F.$L=U),F},S.clone=function(){return O.w(this.$d,this)},S.toDate=function(){return new Date(this.valueOf())},S.toJSON=function(){return this.isValid()?this.toISOString():null},S.toISOString=function(){return this.$d.toISOString()},S.toString=function(){return this.$d.toUTCString()},N}(),$=E.prototype;return T.prototype=$,[["$ms",n],["$s",r],["$m",s],["$H",i],["$W",a],["$M",c],["$y",p],["$D",d]].forEach(function(N){$[N[1]]=function(S){return this.$g(S,N[0],N[1])}}),T.extend=function(N,S){return N.$i||(N(S,E,T),N.$i=!0),T},T.locale=M,T.isDayjs=R,T.unix=function(N){return T(1e3*N)},T.en=C[y],T.Ls=C,T.p={},T})});var hl=bo((pa,da)=>{"use strict";(function(o,e){typeof pa=="object"&&typeof da<"u"?da.exports=e():typeof define=="function"&&define.amd?define(e):(o=typeof globalThis<"u"?globalThis:o||self).dayjs_plugin_customParseFormat=e()})(pa,function(){"use strict";var o={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?/,s=/\d*[^-_:/,()\s\d]+/,i={},a=function(g){return(g=+g)+(g>68?1900:2e3)},u=function(g){return function(f){this[g]=+f}},c=[/[+-]\d\d:?(\d\d)?|Z/,function(g){(this.zone||(this.zone={})).offset=function(f){if(!f||f==="Z")return 0;var x=f.match(/([+-]|\d\d)/g),A=60*x[1]+(+x[2]||0);return A===0?0:x[0]==="+"?-A:A}(g)}],l=function(g){var f=i[g];return f&&(f.indexOf?f:f.s.concat(f.f))},p=function(g,f){var x,A=i.meridiem;if(A){for(var h=1;h<=24;h+=1)if(g.indexOf(A(h,0,f))>-1){x=h>12;break}}else x=g===(f?"pm":"PM");return x},d={A:[s,function(g){this.afternoon=p(g,!1)}],a:[s,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,u("seconds")],ss:[r,u("seconds")],m:[r,u("minutes")],mm:[r,u("minutes")],H:[r,u("hours")],h:[r,u("hours")],HH:[r,u("hours")],hh:[r,u("hours")],D:[r,u("day")],DD:[n,u("day")],Do:[s,function(g){var f=i.ordinal,x=g.match(/\d+/);if(this.day=x[0],f)for(var A=1;A<=31;A+=1)f(A).replace(/\[|\]/g,"")===g&&(this.day=A)}],w:[r,u("week")],ww:[n,u("week")],M:[r,u("month")],MM:[n,u("month")],MMM:[s,function(g){var f=l("months"),x=(l("monthsShort")||f.map(function(A){return A.slice(0,3)})).indexOf(g)+1;if(x<1)throw new Error;this.month=x%12||x}],MMMM:[s,function(g){var f=l("months").indexOf(g)+1;if(f<1)throw new Error;this.month=f%12||f}],Y:[/[+-]?\d+/,u("year")],YY:[n,function(g){this.year=a(g)}],YYYY:[/\d{4}/,u("year")],Z:c,ZZ:c};function m(g){var f,x;f=g,x=i&&i.formats;for(var A=(g=f.replace(/(\[[^\]]+])|(LTS?|l{1,4}|L{1,4})/g,function(T,O,E){var $=E&&E.toUpperCase();return O||x[E]||o[E]||x[$].replace(/(\[[^\]]+])|(MMMM|MM|DD|dddd)/g,function(N,S,v){return S||v.slice(1)})})).match(e),h=A.length,y=0;y<h;y+=1){var C=A[y],I=d[C],R=I&&I[0],M=I&&I[1];A[y]=M?{regex:R,parser:M}:C.replace(/^\[|\]$/g,"")}return function(T){for(var O={},E=0,$=0;E<h;E+=1){var N=A[E];if(typeof N=="string")$+=N.length;else{var S=N.regex,v=N.parser,P=T.slice($),F=S.exec(P)[0];v.call(O,F),T=T.replace(F,"")}}return function(U){var L=U.afternoon;if(L!==void 0){var z=U.hours;L?z<12&&(U.hours+=12):z===12&&(U.hours=0),delete U.afternoon}}(O),O}}return function(g,f,x){x.p.customParseFormat=!0,g&&g.parseTwoDigitYear&&(a=g.parseTwoDigitYear);var A=f.prototype,h=A.parse;A.parse=function(y){var C=y.date,I=y.utc,R=y.args;this.$u=I;var M=R[1];if(typeof M=="string"){var T=R[2]===!0,O=R[3]===!0,E=T||O,$=R[2];O&&($=R[2]),i=this.$locale(),!T&&$&&(i=x.Ls[$]),this.$d=function(P,F,U,L){try{if(["x","X"].indexOf(F)>-1)return new Date((F==="X"?1e3:1)*P);var z=m(F)(P),j=z.year,K=z.month,W=z.day,pe=z.hours,G=z.minutes,J=z.seconds,Y=z.milliseconds,le=z.zone,H=z.week,q=new Date,re=W||(j||K?1:q.getDate()),Ce=j||q.getFullYear(),we=0;j&&!K||(we=K>0?K-1:q.getMonth());var ue,Te=pe||0,ae=G||0,de=J||0,X=Y||0;return le?new Date(Date.UTC(Ce,we,re,Te,ae,de,X+60*le.offset*1e3)):U?new Date(Date.UTC(Ce,we,re,Te,ae,de,X)):(ue=new Date(Ce,we,re,Te,ae,de,X),H&&(ue=L(ue).week(H).toDate()),ue)}catch{return new Date("")}}(C,M,I,x),this.init(),$&&$!==!0&&(this.$L=this.locale($).$L),E&&C!=this.format(M)&&(this.$d=new Date("")),i={}}else if(M instanceof Array)for(var N=M.length,S=1;S<=N;S+=1){R[1]=M[S-1];var v=x.apply(this,R);if(v.isValid()){this.$d=v.$d,this.$L=v.$L,this.init();break}S===N&&(this.$d=new Date(""))}else h.call(this,y)}}})});var xl=bo((ma,ga)=>{"use strict";(function(o,e){typeof ma=="object"&&typeof ga<"u"?ga.exports=e():typeof define=="function"&&define.amd?define(e):(o=typeof globalThis<"u"?globalThis:o||self).dayjs_plugin_timezone=e()})(ma,function(){"use strict";var o={year:0,month:1,day:2,hour:3,minute:4,second:5},e={};return function(t,n,r){var s,i=function(l,p,d){d===void 0&&(d={});var m=new Date(l),g=function(f,x){x===void 0&&(x={});var A=x.timeZoneName||"short",h=f+"|"+A,y=e[h];return y||(y=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:f,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",timeZoneName:A}),e[h]=y),y}(p,d);return g.formatToParts(m)},a=function(l,p){for(var d=i(l,p),m=[],g=0;g<d.length;g+=1){var f=d[g],x=f.type,A=f.value,h=o[x];h>=0&&(m[h]=parseInt(A,10))}var y=m[3],C=y===24?0:y,I=m[0]+"-"+m[1]+"-"+m[2]+" "+C+":"+m[4]+":"+m[5]+":000",R=+l;return(r.utc(I).valueOf()-(R-=R%1e3))/6e4},u=n.prototype;u.tz=function(l,p){l===void 0&&(l=s);var d,m=this.utcOffset(),g=this.toDate(),f=g.toLocaleString("en-US",{timeZone:l}),x=Math.round((g-new Date(f))/1e3/60),A=15*-Math.round(g.getTimezoneOffset()/15)-x;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 h=d.utcOffset();d=d.add(m-h,"minute")}return d.$x.$timezone=l,d},u.offsetName=function(l){var p=this.$x.$timezone||r.tz.guess(),d=i(this.valueOf(),p,{timeZoneName:l}).find(function(m){return m.type.toLowerCase()==="timezonename"});return d&&d.value};var c=u.startOf;u.startOf=function(l,p){if(!this.$x||!this.$x.$timezone)return c.call(this,l,p);var d=r(this.format("YYYY-MM-DD HH:mm:ss:SSS"),{locale:this.$L});return c.call(d,l,p).tz(this.$x.$timezone,!0)},r.tz=function(l,p,d){var m=d&&p,g=d||p||s,f=a(+r(),g);if(typeof l!="string")return r(l).tz(g);var x=function(C,I,R){var M=C-60*I*1e3,T=a(M,R);if(I===T)return[M,I];var O=a(M-=60*(T-I)*1e3,R);return T===O?[M,T]:[C-60*Math.min(T,O)*1e3,Math.max(T,O)]}(r.utc(l,m).valueOf(),f,g),A=x[0],h=x[1],y=r(A).utcOffset(h);return y.$x.$timezone=g,y},r.tz.guess=function(){return Intl.DateTimeFormat().resolvedOptions().timeZone},r.tz.setDefault=function(l){s=l}}})});var Al=bo((fa,ha)=>{"use strict";(function(o,e){typeof fa=="object"&&typeof ha<"u"?ha.exports=e():typeof define=="function"&&define.amd?define(e):(o=typeof globalThis<"u"?globalThis:o||self).dayjs_plugin_utc=e()})(fa,function(){"use strict";var o="minute",e=/[+-]\d\d(?::?\d\d)?/g,t=/([+-]|\d\d)/g;return function(n,r,s){var i=r.prototype;s.utc=function(m){var g={date:m,utc:!0,args:arguments};return new r(g)},i.utc=function(m){var g=s(this.toDate(),{locale:this.$L,utc:!0});return m?g.add(this.utcOffset(),o):g},i.local=function(){return s(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 u=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 u.call(this)};var c=i.utcOffset;i.utcOffset=function(m,g){var f=this.$utils().u;if(f(m))return this.$u?0:f(this.$offset)?c.call(this):this.$offset;if(typeof m=="string"&&(m=function(y){y===void 0&&(y="");var C=y.match(e);if(!C)return null;var I=(""+C[0]).match(t)||["-",0,0],R=I[0],M=60*+I[1]+ +I[2];return M===0?0:R==="+"?M:-M}(m),m===null))return this;var x=Math.abs(m)<=16?60*m:m,A=this;if(g)return A.$offset=x,A.$u=m===0,A;if(m!==0){var h=this.$u?this.toDate().getTimezoneOffset():-1*this.utcOffset();(A=this.local().add(x+h,o)).$offset=x,A.$x.$localOffset=h}else A=this.utc();return A};var l=i.format;i.format=function(m){var g=m||(this.$u?"YYYY-MM-DDTHH:mm:ss[Z]":"");return l.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?s(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 x=this.local(),A=s(m).local();return d.call(x,A,g,f)}}})});var Bh={};Fd(Bh,{AxACE:()=>rr,AxACEOptimizedProgram:()=>no,AxAI:()=>zr,AxAIAnthropic:()=>In,AxAIAnthropicModel:()=>vr,AxAIAnthropicVertexModel:()=>Sr,AxAIAzureOpenAI:()=>Sn,AxAICohere:()=>kn,AxAICohereEmbedModel:()=>Mr,AxAICohereModel:()=>Er,AxAIDeepSeek:()=>On,AxAIDeepSeekModel:()=>Pr,AxAIGoogleGemini:()=>En,AxAIGoogleGeminiEmbedModel:()=>zo,AxAIGoogleGeminiEmbedTypes:()=>Gi,AxAIGoogleGeminiModel:()=>Fr,AxAIGoogleGeminiSafetyCategory:()=>qo,AxAIGoogleGeminiSafetyThreshold:()=>Ho,AxAIGrok:()=>Bn,AxAIGrokEmbedModels:()=>Zi,AxAIGrokModel:()=>Br,AxAIGroq:()=>Pn,AxAIGroqModel:()=>_r,AxAIHuggingFace:()=>Fn,AxAIHuggingFaceModel:()=>Qo,AxAIMistral:()=>_n,AxAIMistralEmbedModels:()=>Hi,AxAIMistralModel:()=>Nr,AxAIOllama:()=>Nn,AxAIOpenAI:()=>vn,AxAIOpenAIBase:()=>Ge,AxAIOpenAIEmbedModel:()=>Tn,AxAIOpenAIModel:()=>Or,AxAIOpenAIResponses:()=>Ln,AxAIOpenAIResponsesBase:()=>$r,AxAIOpenAIResponsesImpl:()=>$n,AxAIOpenAIResponsesModel:()=>wn,AxAIOpenRouter:()=>Dn,AxAIRefusalError:()=>$e,AxAIReka:()=>Un,AxAIRekaModel:()=>Dr,AxAIServiceAbortedError:()=>Fe,AxAIServiceAuthenticationError:()=>Dt,AxAIServiceError:()=>et,AxAIServiceNetworkError:()=>Je,AxAIServiceResponseError:()=>Lt,AxAIServiceStatusError:()=>rt,AxAIServiceStreamTerminatedError:()=>ht,AxAIServiceTimeoutError:()=>gt,AxAITogether:()=>Gn,AxAITogetherModel:()=>Gr,AxAIWebLLM:()=>jn,AxAIWebLLMModel:()=>jr,AxAgent:()=>fo,AxAgentClarificationError:()=>pt,AxApacheTika:()=>Es,AxAssertionError:()=>Pt,AxBalancer:()=>Do,AxBaseAI:()=>je,AxBaseOptimizer:()=>Tt,AxBootstrapFewShot:()=>ir,AxContentProcessingError:()=>Rt,AxDB:()=>cs,AxDBBase:()=>At,AxDBCloudflare:()=>zn,AxDBManager:()=>ls,AxDBMemory:()=>Kt,AxDBPinecone:()=>qn,AxDBWeaviate:()=>Hn,AxDefaultCostTracker:()=>to,AxDefaultResultReranker:()=>Os,AxDockerSession:()=>qs,AxEmbeddingAdapter:()=>Hs,AxEvalUtil:()=>tp,AxFlow:()=>so,AxFlowDependencyAnalyzer:()=>ar,AxFlowExecutionPlanner:()=>cr,AxFlowSubContextImpl:()=>dr,AxFlowTypedSubContextImpl:()=>Bs,AxFluentFieldType:()=>Ke,AxFunctionError:()=>Jr,AxFunctionProcessor:()=>Yr,AxGEPA:()=>Xt,AxGen:()=>Me,AxGenerateError:()=>Zr,AxHFDataLoader:()=>Us,AxInstanceRegistry:()=>Yn,AxJSRuntime:()=>hn,AxJSRuntimePermission:()=>tu,AxLLMRequestTypeValues:()=>Ii,AxLearn:()=>Ds,AxMCPClient:()=>Ws,AxMCPHTTPSSETransport:()=>Ys,AxMCPStreambleHTTPTransport:()=>Qs,AxMediaNotSupportedError:()=>xt,AxMemory:()=>Kn,AxMiPRO:()=>js,AxMockAIService:()=>Zo,AxMultiServiceRouter:()=>es,AxOptimizedProgramImpl:()=>It,AxProgram:()=>Qt,AxPromptTemplate:()=>Yt,AxProviderRouter:()=>os,AxRateLimiterTokenUsage:()=>Mn,AxSignature:()=>_e,AxSignatureBuilder:()=>Xr,AxSimpleClassifier:()=>Ps,AxSimpleClassifierClass:()=>Ms,AxSpanKindValues:()=>Ti,AxStepContextImpl:()=>tr,AxStopFunctionCallException:()=>un,AxStringUtil:()=>ks,AxSynth:()=>sr,AxTestPrompt:()=>Fs,AxTokenLimitError:()=>yr,AxTraceLogger:()=>nr,agent:()=>Cd,ai:()=>Jc,ax:()=>it,axAIAnthropicDefaultConfig:()=>Fi,axAIAnthropicVertexDefaultConfig:()=>Ic,axAIAzureOpenAIBestConfig:()=>vc,axAIAzureOpenAICreativeConfig:()=>wc,axAIAzureOpenAIDefaultConfig:()=>Ni,axAIAzureOpenAIFastConfig:()=>Rc,axAICohereCreativeConfig:()=>Mc,axAICohereDefaultConfig:()=>Di,axAIDeepSeekCodeConfig:()=>Pc,axAIDeepSeekDefaultConfig:()=>Ui,axAIGoogleGeminiDefaultConfig:()=>Bi,axAIGoogleGeminiDefaultCreativeConfig:()=>$c,axAIGrokBestConfig:()=>Wc,axAIGrokDefaultConfig:()=>us,axAIHuggingFaceCreativeConfig:()=>Lc,axAIHuggingFaceDefaultConfig:()=>qi,axAIMistralBestConfig:()=>Dc,axAIMistralDefaultConfig:()=>Xo,axAIOllamaDefaultConfig:()=>Ki,axAIOllamaDefaultCreativeConfig:()=>Uc,axAIOpenAIBestConfig:()=>No,axAIOpenAICreativeConfig:()=>$o,axAIOpenAIDefaultConfig:()=>on,axAIOpenAIFastConfig:()=>Lo,axAIOpenAIResponsesBestConfig:()=>Gc,axAIOpenAIResponsesCreativeConfig:()=>jc,axAIOpenAIResponsesDefaultConfig:()=>Lr,axAIOpenRouterDefaultConfig:()=>Wi,axAIRekaBestConfig:()=>qc,axAIRekaCreativeConfig:()=>Hc,axAIRekaDefaultConfig:()=>Ur,axAIRekaFastConfig:()=>Kc,axAITogetherDefaultConfig:()=>Qi,axAIWebLLMCreativeConfig:()=>Vc,axAIWebLLMDefaultConfig:()=>Xi,axAnalyzeChatPromptRequirements:()=>Bc,axAnalyzeRequestRequirements:()=>sn,axBaseAIDefaultConfig:()=>ke,axBaseAIDefaultCreativeConfig:()=>He,axBuildActorDefinition:()=>ei,axBuildResponderDefinition:()=>ti,axCheckMetricsHealth:()=>Qc,axCreateDefaultColorLogger:()=>Ci,axCreateDefaultOptimizerColorLogger:()=>Da,axCreateDefaultOptimizerTextLogger:()=>sp,axCreateDefaultTextLogger:()=>Ku,axCreateFlowColorLogger:()=>oo,axCreateFlowTextLogger:()=>gp,axCreateJSRuntime:()=>Op,axDefaultFlowLogger:()=>fp,axDefaultMetricsConfig:()=>ra,axDefaultOptimizerLogger:()=>eo,axDefaultOptimizerMetricsConfig:()=>Ua,axGetCompatibilityReport:()=>Sc,axGetFormatCompatibility:()=>Oc,axGetMetricsConfig:()=>Xc,axGetOptimizerMetricsConfig:()=>ap,axGetProvidersWithMediaSupport:()=>kc,axGlobals:()=>he,axModelInfoAnthropic:()=>kr,axModelInfoCohere:()=>jo,axModelInfoDeepSeek:()=>Bo,axModelInfoGoogleGemini:()=>Ko,axModelInfoGrok:()=>as,axModelInfoGroq:()=>Wo,axModelInfoHuggingFace:()=>Jo,axModelInfoMistral:()=>Yo,axModelInfoOpenAI:()=>Rn,axModelInfoOpenAIResponses:()=>_o,axModelInfoReka:()=>rs,axModelInfoTogether:()=>ss,axModelInfoWebLLM:()=>is,axProcessContentForProvider:()=>ns,axRAG:()=>Rd,axScoreProvidersForRequest:()=>Uo,axSelectOptimalProvider:()=>Go,axSpanAttributes:()=>be,axSpanEvents:()=>vt,axUpdateMetricsConfig:()=>Yc,axUpdateOptimizerMetricsConfig:()=>ip,axValidateChatRequestMessage:()=>Cn,axValidateChatResponseResult:()=>Po,axValidateProviderCapabilities:()=>$i,axWorkerRuntime:()=>Ks,f:()=>fe,flow:()=>zs,fn:()=>jl,s:()=>rp});function ft({model:o,modelInfo:e,models:t}){let n=t?.find(c=>c.key===o),r=n&&"model"in n?n.model:o,s=e.find(c=>c.name===o);if(s)return s;let i=e.find(c=>c.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+$/,""),u=e.find(c=>c.name===a);return u||null}var pi=(()=>{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 Ze(){return pi.randomUUID()}async function Nd(o){let e=new TextEncoder,t=typeof o=="string"?e.encode(o):o,n=await pi.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}var li=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 s=0;s<n.length;s++){let i=n[s];r=(r<<5)-r+i,r=r&r}return Math.abs(r).toString(16).padStart(8,"0")}async digestAsync(){return Nd(this.data)}};function mt(o){if(o!=="sha256")throw new Error("Only SHA-256 algorithm is supported");return new li}function Tu(){return pi}var Co=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 s=Number.parseInt(r,10);Number.isNaN(s)||(this.currentEvent.retry=s);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 di=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)}},Io=class extends TransformStream{constructor(){super(new di)}};var Fd={maxRetries:3,initialDelayMs:1e3,maxDelayMs:6e4,backoffFactor:2,retryableStatusCodes:[500,408,429,502,503,504]},_d=globalThis.TextDecoderStream??Io,et=class extends Error{constructor(t,n,r,s,i={},a=!0){super(t);this.url=n;this.requestBody=r;this.responseBody=s;this.name="AxAIServiceError",this.timestamp=new Date().toISOString(),this.errorId=Ze(),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()}},rt=class extends et{constructor(t,n,r,s,i,a,u,c=!0){let l=u?` (after ${u} retries)`:"";super(`HTTP ${t} - ${n}${l}`,r,s,{httpStatus:t,httpStatusText:n,responseBody:i,...a},{},c);this.status=t;this.statusText=n;this.name="AxAIServiceStatusError"}},Je=class extends et{constructor(t,n,r,s,i,a=!0){super(`Network Error: ${t.message}`,n,r,s,{originalErrorName:t.name,originalErrorStack:t.stack,...i},a);this.originalError=t;this.name="AxAIServiceNetworkError",this.stack=t.stack}},Dt=class extends et{constructor(e,t,n,r,s=!0){super(e,t,n,void 0,r,s),this.name="AxAIServiceResponseError"}},ht=class extends et{constructor(t,n,r,s,i=!0){super("Stream terminated unexpectedly by remote host",t,n,void 0,{lastChunk:r,...s},i);this.lastChunk=r;this.name="AxAIServiceStreamTerminatedError"}},gt=class extends et{constructor(e,t,n,r,s=!0){super(`Request timed out after ${t}ms`,e,n,void 0,{timeoutMs:t,...r},s),this.name="AxAIServiceTimeoutError"}},Ar=class extends rt{constructor(e,t,n,r,s,i,a=!0){super(e,t,n,r,s,i,void 0,a),this.name="AxTokenLimitError"}},Fe=class extends et{constructor(e,t,n,r,s=!0){super(`Request aborted${t?`: ${t}`:""}`,e,n,void 0,{abortReason:t,...r},s),this.name="AxAIServiceAbortedError"}},Ut=class extends et{constructor(e,t,n,r,s=!0){super("Authentication failed",e,t,n,r,s),this.name="AxAIServiceAuthenticationError"}},Le=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=Ze()}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(`
7
+ `:"")+r;break;case"id":this.currentEvent.id=r;break;case"retry":{let s=Number.parseInt(r,10);Number.isNaN(s)||(this.currentEvent.retry=s);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 di=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)}},Io=class extends TransformStream{constructor(){super(new di)}};var $d={maxRetries:3,initialDelayMs:1e3,maxDelayMs:6e4,backoffFactor:2,retryableStatusCodes:[500,408,429,502,503,504]},Ld=globalThis.TextDecoderStream??Io,et=class extends Error{constructor(t,n,r,s,i={},a=!0){super(t);this.url=n;this.requestBody=r;this.responseBody=s;this.name="AxAIServiceError",this.timestamp=new Date().toISOString(),this.errorId=Ze(),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()}},rt=class extends et{constructor(t,n,r,s,i,a,u,c=!0){let l=u?` (after ${u} retries)`:"";super(`HTTP ${t} - ${n}${l}`,r,s,{httpStatus:t,httpStatusText:n,responseBody:i,...a},{},c);this.status=t;this.statusText=n;this.name="AxAIServiceStatusError"}},Je=class extends et{constructor(t,n,r,s,i,a=!0){super(`Network Error: ${t.message}`,n,r,s,{originalErrorName:t.name,originalErrorStack:t.stack,...i},a);this.originalError=t;this.name="AxAIServiceNetworkError",this.stack=t.stack}},Lt=class extends et{constructor(e,t,n,r,s=!0){super(e,t,n,void 0,r,s),this.name="AxAIServiceResponseError"}},ht=class extends et{constructor(t,n,r,s,i=!0){super("Stream terminated unexpectedly by remote host",t,n,void 0,{lastChunk:r,...s},i);this.lastChunk=r;this.name="AxAIServiceStreamTerminatedError"}},gt=class extends et{constructor(e,t,n,r,s=!0){super(`Request timed out after ${t}ms`,e,n,void 0,{timeoutMs:t,...r},s),this.name="AxAIServiceTimeoutError"}},yr=class extends rt{constructor(e,t,n,r,s,i,a=!0){super(e,t,n,r,s,i,void 0,a),this.name="AxTokenLimitError"}},Fe=class extends et{constructor(e,t,n,r,s=!0){super(`Request aborted${t?`: ${t}`:""}`,e,n,void 0,{abortReason:t,...r},s),this.name="AxAIServiceAbortedError"}},Dt=class extends et{constructor(e,t,n,r,s=!0){super("Authentication failed",e,t,n,r,s),this.name="AxAIServiceAuthenticationError"}},$e=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=Ze()}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
9
  `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},xt=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=Ze()}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
10
  `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},Rt=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=Ze()}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 mi(o){try{return o.headers.get("content-type")?.includes("application/json")?await o.json():await o.clone().text()}catch(e){return`[ReadableStream - read failed: ${e.message}]`}}function Tu(o,e){return Math.min(e.maxDelayMs,e.initialDelayMs*e.backoffFactor**o)*(.75+Math.random()*.5)}function Nd(o){if(!o)return;let e=Number(o);if(!Number.isNaN(e))return e*1e3;let t=Date.parse(o);if(!Number.isNaN(t)){let n=t-Date.now();return Math.max(0,n)}}function Ld(){return{startTime:Date.now(),retryCount:0}}function Cu(o){o.retryCount++,o.lastRetryTime=Date.now()}function Iu(o,e,t,n){return t>=n.maxRetries?!1:e&&n.retryableStatusCodes.includes(e)?!0:o instanceof Je&&!(o instanceof Ut)}var tt=async(o,e)=>{if(o.localCall)return await o.localCall(e,o.stream);if(!o.url)throw new Error("API URL is required when localCall is not provided");let t={...Fd,...o.retry},n=o.timeout,r=Ld(),s=o.verbose??!1,i=o.includeRequestBodyInErrors??!0,a,u=new URL(o.url),c=`${[u.pathname,o.name].filter(Boolean).join("/").replace(/\/+/g,"/")}${u.search}`,l=new URL(c,u);if(o.corsProxy){let m=l.href;l=new URL(`${o.corsProxy}?url=${encodeURIComponent(m)}`)}let p=Ze();if(o.validateRequest&&!await o.validateRequest(e))throw new Dt("Invalid request data",l.href,e,{validation:"request"},i);o.span?.setAttributes({"http.request.method":o.put?"PUT":"POST","url.full":l.href,"request.id":p,"request.startTime":r.startTime});let d=0;for(;;){let m=new AbortController;if(o.abortSignal){if(o.abortSignal.aborted)throw new Fe(l.href,o.abortSignal.reason,e,{metrics:r},i);let g=()=>{m.abort(o.abortSignal.reason||"User aborted request")};o.abortSignal.addEventListener("abort",g,{once:!0});let f=m.abort.bind(m);m.abort=x=>{o.abortSignal.removeEventListener("abort",g),f(x)}}n&&(a=setTimeout(()=>{m.abort("Request timeout")},n));try{s&&console.log(`
11
+ `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}};async function mi(o){try{return o.headers.get("content-type")?.includes("application/json")?await o.json():await o.clone().text()}catch(e){return`[ReadableStream - read failed: ${e.message}]`}}function wu(o,e){return Math.min(e.maxDelayMs,e.initialDelayMs*e.backoffFactor**o)*(.75+Math.random()*.5)}function Dd(o){if(!o)return;let e=Number(o);if(!Number.isNaN(e))return e*1e3;let t=Date.parse(o);if(!Number.isNaN(t)){let n=t-Date.now();return Math.max(0,n)}}function Ud(){return{startTime:Date.now(),retryCount:0}}function Ru(o){o.retryCount++,o.lastRetryTime=Date.now()}function vu(o,e,t,n){return t>=n.maxRetries?!1:e&&n.retryableStatusCodes.includes(e)?!0:o instanceof Je&&!(o instanceof Dt)}var tt=async(o,e)=>{if(o.localCall)return await o.localCall(e,o.stream);if(!o.url)throw new Error("API URL is required when localCall is not provided");let t={...$d,...o.retry},n=o.timeout,r=Ud(),s=o.verbose??!1,i=o.includeRequestBodyInErrors??!0,a,u=new URL(o.url),c=`${[u.pathname,o.name].filter(Boolean).join("/").replace(/\/+/g,"/")}${u.search}`,l=new URL(c,u);if(o.corsProxy){let m=l.href;l=new URL(`${o.corsProxy}?url=${encodeURIComponent(m)}`)}let p=Ze();if(o.validateRequest&&!await o.validateRequest(e))throw new Lt("Invalid request data",l.href,e,{validation:"request"},i);o.span?.setAttributes({"http.request.method":o.put?"PUT":"POST","url.full":l.href,"request.id":p,"request.startTime":r.startTime});let d=0;for(;;){let m=new AbortController;if(o.abortSignal){if(o.abortSignal.aborted)throw new Fe(l.href,o.abortSignal.reason,e,{metrics:r},i);let g=()=>{m.abort(o.abortSignal.reason||"User aborted request")};o.abortSignal.addEventListener("abort",g,{once:!0});let f=m.abort.bind(m);m.abort=x=>{o.abortSignal.removeEventListener("abort",g),f(x)}}n&&(a=setTimeout(()=>{m.abort("Request timeout")},n));try{s&&console.log(`
12
12
  --- [AxAI API Request] ---
13
13
  `,`URL: ${l.href}
14
14
  `,`Method: ${o.put?"PUT":"POST"}
15
15
  `,"Headers:",JSON.stringify({"Content-Type":"application/json","X-Request-ID":p,"X-Retry-Count":d.toString(),...o.headers},null,2),`
16
16
  Body:`,JSON.stringify(e,null,2),`
17
17
  ------------------------
18
- `);let g=await(o.fetch??fetch)(l,{method:o.put?"PUT":"POST",headers:{"Content-Type":"application/json","X-Request-ID":p,"X-Retry-Count":d.toString(),...o.headers},body:JSON.stringify(e),signal:m.signal});if(a&&clearTimeout(a),g.status===401||g.status===403){let T=await mi(g);throw new Ut(l.href,e,T,{metrics:r},i)}if(g.status===400){let T=await mi(g),C=T,R=!1;if(C?.error?.code==="context_length_exceeded")R=!0;else if(C?.type==="invalid_request_error"&&(C?.error?.message?.includes("prompt is too long")||C?.error?.message?.includes("max_tokens")||C?.error?.message?.includes("token limit")))R=!0;else if(C?.error?.code===400&&C?.error?.status==="INVALID_ARGUMENT"&&(C?.error?.message?.includes("token")||C?.error?.message?.includes("limit")))R=!0;else{let M=JSON.stringify(T).toLowerCase();(M.includes("token")&&M.includes("limit")||M.includes("context length")||M.includes("prompt is too long"))&&(R=!0)}if(R)throw new Ar(g.status,g.statusText,l.href,e,T,{metrics:r},i)}if(g.status>=400&&Iu(new Error,g.status,d,t)){let T=Tu(d,t),C=Nd(g.headers.get("Retry-After"));C!==void 0&&C<=t.maxDelayMs&&(T=C,s&&console.log(`[AxAI] Respecting Retry-After header: ${T}ms`)),d++,Cu(r),o.span?.addEvent("retry",{attempt:d,delay:T,status:g.status,"metrics.startTime":r.startTime,"metrics.retryCount":r.retryCount,"metrics.lastRetryTime":r.lastRetryTime}),await new Promise(R=>setTimeout(R,T));continue}if(g.status>=400){let T=await mi(g);throw new rt(g.status,g.statusText,l.href,e,T,{metrics:r},d>0?d:void 0,i)}if(!o.stream){let T=await g.json();if(s&&console.log(`
18
+ `);let g=await(o.fetch??fetch)(l,{method:o.put?"PUT":"POST",headers:{"Content-Type":"application/json","X-Request-ID":p,"X-Retry-Count":d.toString(),...o.headers},body:JSON.stringify(e),signal:m.signal});if(a&&clearTimeout(a),g.status===401||g.status===403){let C=await mi(g);throw new Dt(l.href,e,C,{metrics:r},i)}if(g.status===400){let C=await mi(g),I=C,R=!1;if(I?.error?.code==="context_length_exceeded")R=!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")))R=!0;else if(I?.error?.code===400&&I?.error?.status==="INVALID_ARGUMENT"&&(I?.error?.message?.includes("token")||I?.error?.message?.includes("limit")))R=!0;else{let M=JSON.stringify(C).toLowerCase();(M.includes("token")&&M.includes("limit")||M.includes("context length")||M.includes("prompt is too long"))&&(R=!0)}if(R)throw new yr(g.status,g.statusText,l.href,e,C,{metrics:r},i)}if(g.status>=400&&vu(new Error,g.status,d,t)){let C=wu(d,t),I=Dd(g.headers.get("Retry-After"));I!==void 0&&I<=t.maxDelayMs&&(C=I,s&&console.log(`[AxAI] Respecting Retry-After header: ${C}ms`)),d++,Ru(r),o.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(R=>setTimeout(R,C));continue}if(g.status>=400){let C=await mi(g);throw new rt(g.status,g.statusText,l.href,e,C,{metrics:r},d>0?d:void 0,i)}if(!o.stream){let C=await g.json();if(s&&console.log(`
19
19
  --- [AxAI API Response] ---
20
20
  `,`Status: ${g.status} ${g.statusText}
21
- `,"Body:",JSON.stringify(T,null,2),`
21
+ `,"Body:",JSON.stringify(C,null,2),`
22
22
  -------------------------
23
- `),o.validateResponse&&!await o.validateResponse(T))throw new Dt("Invalid response data",l.href,e,{validation:"response"},i);return o.span?.setAttributes({"response.time":Date.now()-r.startTime,"response.retries":r.retryCount}),T}if(s&&console.log(`
23
+ `),o.validateResponse&&!await o.validateResponse(C))throw new Lt("Invalid response data",l.href,e,{validation:"response"},i);return o.span?.setAttributes({"response.time":Date.now()-r.startTime,"response.retries":r.retryCount}),C}if(s&&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 Dt("Response body is null",l.href,e,{metrics:r},i);let f,x=0;if(typeof window<"u"&&typeof EventSource<"u")return new ReadableStream({start(T){let C=g.body.getReader(),R=new TextDecoder,M="";async function I(){try{for(;;){let{done:O,value:E}=await C.read();if(O){y=!0,T.close();break}M+=R.decode(E,{stream:!0});let $=M.split(`
28
+ `),!g.body)throw new Lt("Response body is null",l.href,e,{metrics:r},i);let f,x=0;if(typeof window<"u"&&typeof EventSource<"u")return new ReadableStream({start(C){let I=g.body.getReader(),R=new TextDecoder,M="";async function T(){try{for(;;){let{done:O,value:E}=await I.read();if(O){y=!0,C.close();break}M+=R.decode(E,{stream:!0});let $=M.split(`
29
29
 
30
30
  `);M=$.pop()||"";for(let N of $){if(!N.trim())continue;let S=N.split(`
31
- `),v="",F="message";for(let P of S)P.startsWith("data: ")?v=P.slice(6):P.startsWith("event: ")&&(F=P.slice(7));if(v){if(v==="[DONE]"){T.close();return}try{let P=JSON.parse(v);f=P,x++,r.streamChunks=x,r.lastChunkTime=Date.now(),T.enqueue(P),o.span?.addEvent("stream.chunk",{"stream.chunks":x,"stream.duration":Date.now()-r.startTime,"response.retries":r.retryCount,"sse.event.type":F})}catch(P){s&&console.warn("Skipping non-JSON SSE data:",v,P)}}}}}catch(O){let E=O,$={...r,streamDuration:Date.now()-r.startTime};E.name==="AbortError"||E.message?.includes("aborted")?T.error(new ht(l.href,e,f,{streamMetrics:$},i)):T.error(new Je(E,l.href,e,"[ReadableStream - consumed during streaming]",{streamMetrics:$},i))}finally{C.releaseLock()}}I()}});let h=new TransformStream({transform(T,C){f=T,x++,r.streamChunks=x,r.lastChunkTime=Date.now(),C.enqueue(T),o.span?.addEvent("stream.chunk",{"stream.chunks":x,"stream.duration":Date.now()-r.startTime,"response.retries":r.retryCount})}}),y=!1;return new ReadableStream({start(T){let C=g.body.pipeThrough(new _d).pipeThrough(new Co).pipeThrough(h).getReader();async function R(){try{for(;;){let{done:M,value:I}=await C.read();if(M){y||(y=!0,T.close());break}if(y)break;T.enqueue(I)}}catch(M){let I=M,O={...r,streamDuration:Date.now()-r.startTime};throw I.name==="AbortError"||I.message?.includes("aborted")?T.error(new ht(l.href,e,f,{streamMetrics:O},i)):I instanceof TypeError&&I.message.includes("cancelled")?T.error(new ht(l.href,e,f,{streamMetrics:O,cancelReason:"Stream cancelled by client"},i)):T.error(new Je(I,l.href,e,"[ReadableStream - consumed during streaming]",{streamMetrics:O},i)),I}finally{a&&clearTimeout(a),C.releaseLock()}}R()},cancel(){y=!0}})}catch(g){if(g instanceof Error&&g.name==="AbortError")throw o.abortSignal?.aborted?new Fe(l.href,o.abortSignal.reason,e,{metrics:r},i):new gt(l.href,n||0,e,{metrics:r},i);let f=g;if(!(g instanceof et)&&g instanceof Error&&(f=new Je(g,l.href,e,void 0,{metrics:r},i)),o.span?.isRecording()&&(o.span.recordException(f),o.span.setAttributes({"error.time":Date.now()-r.startTime,"error.retries":r.retryCount})),f instanceof Je&&Iu(f,void 0,d,t)){let x=Tu(d,t);d++,Cu(r),o.span?.addEvent("retry",{attempt:d,delay:x,error:f.message,"metrics.startTime":r.startTime,"metrics.retryCount":r.retryCount,"metrics.lastRetryTime":r.lastRetryTime}),await new Promise(A=>setTimeout(A,x));continue}throw f instanceof et&&(f.context.metrics=r),f}finally{a!==void 0&&clearTimeout(a)}}};var wu=typeof globalThis=="object"?globalThis:global;var Gt="1.9.0";var Ru=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function $d(o){var e=new Set([o]),t=new Set,n=o.match(Ru);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(u){return u===o};function s(a){return t.add(a),!1}function i(a){return e.add(a),!0}return function(u){if(e.has(u))return!0;if(t.has(u))return!1;var c=u.match(Ru);if(!c)return s(u);var l={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return l.prerelease!=null||r.major!==l.major?s(u):r.major===0?r.minor===l.minor&&r.patch<=l.patch?i(u):s(u):r.minor<=l.minor?i(u):s(u)}}var vu=$d(Gt);var Dd=Gt.split(".")[0],yr=Symbol.for("opentelemetry.js.api."+Dd),br=wu;function fn(o,e,t,n){var r;n===void 0&&(n=!1);var s=br[yr]=(r=br[yr])!==null&&r!==void 0?r:{version:Gt};if(!n&&s[o]){var i=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+o);return t.error(i.stack||i.message),!1}if(s.version!==Gt){var i=new Error("@opentelemetry/api: Registration of version v"+s.version+" for "+o+" does not match previously registered API v"+Gt);return t.error(i.stack||i.message),!1}return s[o]=e,t.debug("@opentelemetry/api: Registered a global for "+o+" v"+Gt+"."),!0}function Bt(o){var e,t,n=(e=br[yr])===null||e===void 0?void 0:e.version;if(!(!n||!vu(n)))return(t=br[yr])===null||t===void 0?void 0:t[o]}function hn(o,e){e.debug("@opentelemetry/api: Unregistering a global for "+o+" v"+Gt+".");var t=br[yr];t&&delete t[o]}var Ud=function(o,e){var t=typeof Symbol=="function"&&o[Symbol.iterator];if(!t)return o;var n=t.call(o),r,s=[],i;try{for(;(e===void 0||e-- >0)&&!(r=n.next()).done;)s.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 s},Gd=function(o,e,t){if(t||arguments.length===2)for(var n=0,r=e.length,s;n<r;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return o.concat(s||Array.prototype.slice.call(e))},Su=function(){function o(e){this._namespace=e.namespace||"DiagComponentLogger"}return o.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Tr("debug",this._namespace,e)},o.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Tr("error",this._namespace,e)},o.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Tr("info",this._namespace,e)},o.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Tr("warn",this._namespace,e)},o.prototype.verbose=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Tr("verbose",this._namespace,e)},o}();function Tr(o,e,t){var n=Bt("diag");if(n)return t.unshift(e),n[o].apply(n,Gd([],Ud(t),!1))}var ot;(function(o){o[o.NONE=0]="NONE",o[o.ERROR=30]="ERROR",o[o.WARN=50]="WARN",o[o.INFO=60]="INFO",o[o.DEBUG=70]="DEBUG",o[o.VERBOSE=80]="VERBOSE",o[o.ALL=9999]="ALL"})(ot||(ot={}));function ku(o,e){o<ot.NONE?o=ot.NONE:o>ot.ALL&&(o=ot.ALL),e=e||{};function t(n,r){var s=e[n];return typeof s=="function"&&o>=r?s.bind(e):function(){}}return{error:t("error",ot.ERROR),warn:t("warn",ot.WARN),info:t("info",ot.INFO),debug:t("debug",ot.DEBUG),verbose:t("verbose",ot.VERBOSE)}}var Bd=function(o,e){var t=typeof Symbol=="function"&&o[Symbol.iterator];if(!t)return o;var n=t.call(o),r,s=[],i;try{for(;(e===void 0||e-- >0)&&!(r=n.next()).done;)s.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 s},jd=function(o,e,t){if(t||arguments.length===2)for(var n=0,r=e.length,s;n<r;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return o.concat(s||Array.prototype.slice.call(e))},zd="diag",xn=function(){function o(){function e(r){return function(){for(var s=[],i=0;i<arguments.length;i++)s[i]=arguments[i];var a=Bt("diag");if(a)return a[r].apply(a,jd([],Bd(s),!1))}}var t=this,n=function(r,s){var i,a,u;if(s===void 0&&(s={logLevel:ot.INFO}),r===t){var c=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=c.stack)!==null&&i!==void 0?i:c.message),!1}typeof s=="number"&&(s={logLevel:s});var l=Bt("diag"),p=ku((a=s.logLevel)!==null&&a!==void 0?a:ot.INFO,r);if(l&&!s.suppressOverrideMessage){var d=(u=new Error().stack)!==null&&u!==void 0?u:"<failed to generate stacktrace>";l.warn("Current logger will be overwritten from "+d),p.warn("Current logger will overwrite one already registered from "+d)}return fn("diag",p,t,!0)};t.setLogger=n,t.disable=function(){hn(zd,t)},t.createComponentLogger=function(r){return new Su(r)},t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error")}return o.instance=function(){return this._instance||(this._instance=new o),this._instance},o}();function Ou(o){return Symbol.for(o)}var qd=function(){function o(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 s=new o(t._currentContext);return s._currentContext.set(n,r),s},t.deleteValue=function(n){var r=new o(t._currentContext);return r._currentContext.delete(n),r}}return o}(),Eu=new qd;var Hd=function(o,e){var t=typeof Symbol=="function"&&o[Symbol.iterator];if(!t)return o;var n=t.call(o),r,s=[],i;try{for(;(e===void 0||e-- >0)&&!(r=n.next()).done;)s.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 s},Wd=function(o,e,t){if(t||arguments.length===2)for(var n=0,r=e.length,s;n<r;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return o.concat(s||Array.prototype.slice.call(e))},Mu=function(){function o(){}return o.prototype.active=function(){return Eu},o.prototype.with=function(e,t,n){for(var r=[],s=3;s<arguments.length;s++)r[s-3]=arguments[s];return t.call.apply(t,Wd([n],Hd(r),!1))},o.prototype.bind=function(e,t){return t},o.prototype.enable=function(){return this},o.prototype.disable=function(){return this},o}();var Kd=function(o,e){var t=typeof Symbol=="function"&&o[Symbol.iterator];if(!t)return o;var n=t.call(o),r,s=[],i;try{for(;(e===void 0||e-- >0)&&!(r=n.next()).done;)s.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 s},Vd=function(o,e,t){if(t||arguments.length===2)for(var n=0,r=e.length,s;n<r;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return o.concat(s||Array.prototype.slice.call(e))},gi="context",Jd=new Mu,An=function(){function o(){}return o.getInstance=function(){return this._instance||(this._instance=new o),this._instance},o.prototype.setGlobalContextManager=function(e){return fn(gi,e,xn.instance())},o.prototype.active=function(){return this._getContextManager().active()},o.prototype.with=function(e,t,n){for(var r,s=[],i=3;i<arguments.length;i++)s[i-3]=arguments[i];return(r=this._getContextManager()).with.apply(r,Vd([e,t,n],Kd(s),!1))},o.prototype.bind=function(e,t){return this._getContextManager().bind(e,t)},o.prototype._getContextManager=function(){return Bt(gi)||Jd},o.prototype.disable=function(){this._getContextManager().disable(),hn(gi,xn.instance())},o}();var wo;(function(o){o[o.NONE=0]="NONE",o[o.SAMPLED=1]="SAMPLED"})(wo||(wo={}));var fi="0000000000000000",hi="00000000000000000000000000000000",Pu={traceId:hi,spanId:fi,traceFlags:wo.NONE};var zt=function(){function o(e){e===void 0&&(e=Pu),this._spanContext=e}return o.prototype.spanContext=function(){return this._spanContext},o.prototype.setAttribute=function(e,t){return this},o.prototype.setAttributes=function(e){return this},o.prototype.addEvent=function(e,t){return this},o.prototype.addLink=function(e){return this},o.prototype.addLinks=function(e){return this},o.prototype.setStatus=function(e){return this},o.prototype.updateName=function(e){return this},o.prototype.end=function(e){},o.prototype.isRecording=function(){return!1},o.prototype.recordException=function(e,t){},o}();var xi=Ou("OpenTelemetry Context Key SPAN");function Ro(o){return o.getValue(xi)||void 0}function Fu(){return Ro(An.getInstance().active())}function Cr(o,e){return o.setValue(xi,e)}function _u(o){return o.deleteValue(xi)}function Nu(o,e){return Cr(o,new zt(e))}function vo(o){var e;return(e=Ro(o))===null||e===void 0?void 0:e.spanContext()}var Qd=/^([0-9a-f]{32})$/i,Yd=/^[0-9a-f]{16}$/i;function Xd(o){return Qd.test(o)&&o!==hi}function Zd(o){return Yd.test(o)&&o!==fi}function So(o){return Xd(o.traceId)&&Zd(o.spanId)}function Lu(o){return new zt(o)}var Ai=An.getInstance(),ko=function(){function o(){}return o.prototype.startSpan=function(e,t,n){n===void 0&&(n=Ai.active());var r=!!t?.root;if(r)return new zt;var s=n&&vo(n);return em(s)&&So(s)?new zt(s):new zt},o.prototype.startActiveSpan=function(e,t,n,r){var s,i,a;if(!(arguments.length<2)){arguments.length===2?a=t:arguments.length===3?(s=t,a=n):(s=t,i=n,a=r);var u=i??Ai.active(),c=this.startSpan(e,s,u),l=Cr(u,c);return Ai.with(l,a,void 0,c)}},o}();function em(o){return typeof o=="object"&&typeof o.spanId=="string"&&typeof o.traceId=="string"&&typeof o.traceFlags=="number"}var tm=new ko,$u=function(){function o(e,t,n,r){this._provider=e,this.name=t,this.version=n,this.options=r}return o.prototype.startSpan=function(e,t,n){return this._getTracer().startSpan(e,t,n)},o.prototype.startActiveSpan=function(e,t,n,r){var s=this._getTracer();return Reflect.apply(s.startActiveSpan,s,arguments)},o.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):tm},o}();var Du=function(){function o(){}return o.prototype.getTracer=function(e,t,n){return new ko},o}();var nm=new Du,yi=function(){function o(){}return o.prototype.getTracer=function(e,t,n){var r;return(r=this.getDelegateTracer(e,t,n))!==null&&r!==void 0?r:new $u(this,e,t,n)},o.prototype.getDelegate=function(){var e;return(e=this._delegate)!==null&&e!==void 0?e:nm},o.prototype.setDelegate=function(e){this._delegate=e},o.prototype.getDelegateTracer=function(e,t,n){var r;return(r=this._delegate)===null||r===void 0?void 0:r.getTracer(e,t,n)},o}();var ct;(function(o){o[o.INTERNAL=0]="INTERNAL",o[o.SERVER=1]="SERVER",o[o.CLIENT=2]="CLIENT",o[o.PRODUCER=3]="PRODUCER",o[o.CONSUMER=4]="CONSUMER"})(ct||(ct={}));var qt=An.getInstance();var bi="trace",Uu=function(){function o(){this._proxyTracerProvider=new yi,this.wrapSpanContext=Lu,this.isSpanContextValid=So,this.deleteSpan=_u,this.getSpan=Ro,this.getActiveSpan=Fu,this.getSpanContext=vo,this.setSpan=Cr,this.setSpanContext=Nu}return o.getInstance=function(){return this._instance||(this._instance=new o),this._instance},o.prototype.setGlobalTracerProvider=function(e){var t=fn(bi,this._proxyTracerProvider,xn.instance());return t&&this._proxyTracerProvider.setDelegate(e),t},o.prototype.getTracerProvider=function(){return Bt(bi)||this._proxyTracerProvider},o.prototype.getTracer=function(e,t){return this.getTracerProvider().getTracer(e,t)},o.prototype.disable=function(){hn(bi,xn.instance()),this._proxyTracerProvider=new yi},o}();var Ir=Uu.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:o=>typeof o=="string"?o:o==null?"":JSON.stringify(o,null,2)};var st=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 AA=new st,Gu=o=>{console.log(o)},Bu=(o,e,t)=>{let n=(r,s)=>t&&s&&s in t?t[s](r):r;switch(o.role){case"system":return`${n("[ SYSTEM ]","magentaBright")}
31
+ `),v="",P="message";for(let F of S)F.startsWith("data: ")?v=F.slice(6):F.startsWith("event: ")&&(P=F.slice(7));if(v){if(v==="[DONE]"){C.close();return}try{let F=JSON.parse(v);f=F,x++,r.streamChunks=x,r.lastChunkTime=Date.now(),C.enqueue(F),o.span?.addEvent("stream.chunk",{"stream.chunks":x,"stream.duration":Date.now()-r.startTime,"response.retries":r.retryCount,"sse.event.type":P})}catch(F){s&&console.warn("Skipping non-JSON SSE data:",v,F)}}}}}catch(O){let E=O,$={...r,streamDuration:Date.now()-r.startTime};E.name==="AbortError"||E.message?.includes("aborted")?C.error(new ht(l.href,e,f,{streamMetrics:$},i)):C.error(new Je(E,l.href,e,"[ReadableStream - consumed during streaming]",{streamMetrics:$},i))}finally{I.releaseLock()}}T()}});let h=new TransformStream({transform(C,I){f=C,x++,r.streamChunks=x,r.lastChunkTime=Date.now(),I.enqueue(C),o.span?.addEvent("stream.chunk",{"stream.chunks":x,"stream.duration":Date.now()-r.startTime,"response.retries":r.retryCount})}}),y=!1;return new ReadableStream({start(C){let I=g.body.pipeThrough(new Ld).pipeThrough(new Co).pipeThrough(h).getReader();async function R(){try{for(;;){let{done:M,value:T}=await I.read();if(M){y||(y=!0,C.close());break}if(y)break;C.enqueue(T)}}catch(M){let T=M,O={...r,streamDuration:Date.now()-r.startTime};throw T.name==="AbortError"||T.message?.includes("aborted")?C.error(new ht(l.href,e,f,{streamMetrics:O},i)):T instanceof TypeError&&T.message.includes("cancelled")?C.error(new ht(l.href,e,f,{streamMetrics:O,cancelReason:"Stream cancelled by client"},i)):C.error(new Je(T,l.href,e,"[ReadableStream - consumed during streaming]",{streamMetrics:O},i)),T}finally{a&&clearTimeout(a),I.releaseLock()}}R()},cancel(){y=!0}})}catch(g){if(g instanceof Error&&g.name==="AbortError")throw o.abortSignal?.aborted?new Fe(l.href,o.abortSignal.reason,e,{metrics:r},i):new gt(l.href,n||0,e,{metrics:r},i);let f=g;if(!(g instanceof et)&&g instanceof Error&&(f=new Je(g,l.href,e,void 0,{metrics:r},i)),o.span?.isRecording()&&(o.span.recordException(f),o.span.setAttributes({"error.time":Date.now()-r.startTime,"error.retries":r.retryCount})),f instanceof Je&&vu(f,void 0,d,t)){let x=wu(d,t);d++,Ru(r),o.span?.addEvent("retry",{attempt:d,delay:x,error:f.message,"metrics.startTime":r.startTime,"metrics.retryCount":r.retryCount,"metrics.lastRetryTime":r.lastRetryTime}),await new Promise(A=>setTimeout(A,x));continue}throw f instanceof et&&(f.context.metrics=r),f}finally{a!==void 0&&clearTimeout(a)}}};var Su=typeof globalThis=="object"?globalThis:global;var Ut="1.9.0";var ku=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function Gd(o){var e=new Set([o]),t=new Set,n=o.match(ku);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(u){return u===o};function s(a){return t.add(a),!1}function i(a){return e.add(a),!0}return function(u){if(e.has(u))return!0;if(t.has(u))return!1;var c=u.match(ku);if(!c)return s(u);var l={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return l.prerelease!=null||r.major!==l.major?s(u):r.major===0?r.minor===l.minor&&r.patch<=l.patch?i(u):s(u):r.minor<=l.minor?i(u):s(u)}}var Ou=Gd(Ut);var jd=Ut.split(".")[0],br=Symbol.for("opentelemetry.js.api."+jd),Cr=Su;function xn(o,e,t,n){var r;n===void 0&&(n=!1);var s=Cr[br]=(r=Cr[br])!==null&&r!==void 0?r:{version:Ut};if(!n&&s[o]){var i=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+o);return t.error(i.stack||i.message),!1}if(s.version!==Ut){var i=new Error("@opentelemetry/api: Registration of version v"+s.version+" for "+o+" does not match previously registered API v"+Ut);return t.error(i.stack||i.message),!1}return s[o]=e,t.debug("@opentelemetry/api: Registered a global for "+o+" v"+Ut+"."),!0}function Gt(o){var e,t,n=(e=Cr[br])===null||e===void 0?void 0:e.version;if(!(!n||!Ou(n)))return(t=Cr[br])===null||t===void 0?void 0:t[o]}function An(o,e){e.debug("@opentelemetry/api: Unregistering a global for "+o+" v"+Ut+".");var t=Cr[br];t&&delete t[o]}var Bd=function(o,e){var t=typeof Symbol=="function"&&o[Symbol.iterator];if(!t)return o;var n=t.call(o),r,s=[],i;try{for(;(e===void 0||e-- >0)&&!(r=n.next()).done;)s.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 s},zd=function(o,e,t){if(t||arguments.length===2)for(var n=0,r=e.length,s;n<r;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return o.concat(s||Array.prototype.slice.call(e))},Eu=function(){function o(e){this._namespace=e.namespace||"DiagComponentLogger"}return o.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ir("debug",this._namespace,e)},o.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ir("error",this._namespace,e)},o.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ir("info",this._namespace,e)},o.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ir("warn",this._namespace,e)},o.prototype.verbose=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Ir("verbose",this._namespace,e)},o}();function Ir(o,e,t){var n=Gt("diag");if(n)return t.unshift(e),n[o].apply(n,zd([],Bd(t),!1))}var ot;(function(o){o[o.NONE=0]="NONE",o[o.ERROR=30]="ERROR",o[o.WARN=50]="WARN",o[o.INFO=60]="INFO",o[o.DEBUG=70]="DEBUG",o[o.VERBOSE=80]="VERBOSE",o[o.ALL=9999]="ALL"})(ot||(ot={}));function Mu(o,e){o<ot.NONE?o=ot.NONE:o>ot.ALL&&(o=ot.ALL),e=e||{};function t(n,r){var s=e[n];return typeof s=="function"&&o>=r?s.bind(e):function(){}}return{error:t("error",ot.ERROR),warn:t("warn",ot.WARN),info:t("info",ot.INFO),debug:t("debug",ot.DEBUG),verbose:t("verbose",ot.VERBOSE)}}var qd=function(o,e){var t=typeof Symbol=="function"&&o[Symbol.iterator];if(!t)return o;var n=t.call(o),r,s=[],i;try{for(;(e===void 0||e-- >0)&&!(r=n.next()).done;)s.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 s},Hd=function(o,e,t){if(t||arguments.length===2)for(var n=0,r=e.length,s;n<r;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return o.concat(s||Array.prototype.slice.call(e))},Kd="diag",yn=function(){function o(){function e(r){return function(){for(var s=[],i=0;i<arguments.length;i++)s[i]=arguments[i];var a=Gt("diag");if(a)return a[r].apply(a,Hd([],qd(s),!1))}}var t=this,n=function(r,s){var i,a,u;if(s===void 0&&(s={logLevel:ot.INFO}),r===t){var c=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=c.stack)!==null&&i!==void 0?i:c.message),!1}typeof s=="number"&&(s={logLevel:s});var l=Gt("diag"),p=Mu((a=s.logLevel)!==null&&a!==void 0?a:ot.INFO,r);if(l&&!s.suppressOverrideMessage){var d=(u=new Error().stack)!==null&&u!==void 0?u:"<failed to generate stacktrace>";l.warn("Current logger will be overwritten from "+d),p.warn("Current logger will overwrite one already registered from "+d)}return xn("diag",p,t,!0)};t.setLogger=n,t.disable=function(){An(Kd,t)},t.createComponentLogger=function(r){return new Eu(r)},t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error")}return o.instance=function(){return this._instance||(this._instance=new o),this._instance},o}();function Pu(o){return Symbol.for(o)}var Vd=function(){function o(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 s=new o(t._currentContext);return s._currentContext.set(n,r),s},t.deleteValue=function(n){var r=new o(t._currentContext);return r._currentContext.delete(n),r}}return o}(),Fu=new Vd;var Wd=function(o,e){var t=typeof Symbol=="function"&&o[Symbol.iterator];if(!t)return o;var n=t.call(o),r,s=[],i;try{for(;(e===void 0||e-- >0)&&!(r=n.next()).done;)s.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 s},Jd=function(o,e,t){if(t||arguments.length===2)for(var n=0,r=e.length,s;n<r;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return o.concat(s||Array.prototype.slice.call(e))},_u=function(){function o(){}return o.prototype.active=function(){return Fu},o.prototype.with=function(e,t,n){for(var r=[],s=3;s<arguments.length;s++)r[s-3]=arguments[s];return t.call.apply(t,Jd([n],Wd(r),!1))},o.prototype.bind=function(e,t){return t},o.prototype.enable=function(){return this},o.prototype.disable=function(){return this},o}();var Qd=function(o,e){var t=typeof Symbol=="function"&&o[Symbol.iterator];if(!t)return o;var n=t.call(o),r,s=[],i;try{for(;(e===void 0||e-- >0)&&!(r=n.next()).done;)s.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 s},Yd=function(o,e,t){if(t||arguments.length===2)for(var n=0,r=e.length,s;n<r;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return o.concat(s||Array.prototype.slice.call(e))},gi="context",Xd=new _u,bn=function(){function o(){}return o.getInstance=function(){return this._instance||(this._instance=new o),this._instance},o.prototype.setGlobalContextManager=function(e){return xn(gi,e,yn.instance())},o.prototype.active=function(){return this._getContextManager().active()},o.prototype.with=function(e,t,n){for(var r,s=[],i=3;i<arguments.length;i++)s[i-3]=arguments[i];return(r=this._getContextManager()).with.apply(r,Yd([e,t,n],Qd(s),!1))},o.prototype.bind=function(e,t){return this._getContextManager().bind(e,t)},o.prototype._getContextManager=function(){return Gt(gi)||Xd},o.prototype.disable=function(){this._getContextManager().disable(),An(gi,yn.instance())},o}();var To;(function(o){o[o.NONE=0]="NONE",o[o.SAMPLED=1]="SAMPLED"})(To||(To={}));var fi="0000000000000000",hi="00000000000000000000000000000000",Nu={traceId:hi,spanId:fi,traceFlags:To.NONE};var zt=function(){function o(e){e===void 0&&(e=Nu),this._spanContext=e}return o.prototype.spanContext=function(){return this._spanContext},o.prototype.setAttribute=function(e,t){return this},o.prototype.setAttributes=function(e){return this},o.prototype.addEvent=function(e,t){return this},o.prototype.addLink=function(e){return this},o.prototype.addLinks=function(e){return this},o.prototype.setStatus=function(e){return this},o.prototype.updateName=function(e){return this},o.prototype.end=function(e){},o.prototype.isRecording=function(){return!1},o.prototype.recordException=function(e,t){},o}();var xi=Pu("OpenTelemetry Context Key SPAN");function wo(o){return o.getValue(xi)||void 0}function $u(){return wo(bn.getInstance().active())}function Tr(o,e){return o.setValue(xi,e)}function Lu(o){return o.deleteValue(xi)}function Du(o,e){return Tr(o,new zt(e))}function Ro(o){var e;return(e=wo(o))===null||e===void 0?void 0:e.spanContext()}var Zd=/^([0-9a-f]{32})$/i,em=/^[0-9a-f]{16}$/i;function tm(o){return Zd.test(o)&&o!==hi}function nm(o){return em.test(o)&&o!==fi}function vo(o){return tm(o.traceId)&&nm(o.spanId)}function Uu(o){return new zt(o)}var Ai=bn.getInstance(),So=function(){function o(){}return o.prototype.startSpan=function(e,t,n){n===void 0&&(n=Ai.active());var r=!!t?.root;if(r)return new zt;var s=n&&Ro(n);return rm(s)&&vo(s)?new zt(s):new zt},o.prototype.startActiveSpan=function(e,t,n,r){var s,i,a;if(!(arguments.length<2)){arguments.length===2?a=t:arguments.length===3?(s=t,a=n):(s=t,i=n,a=r);var u=i??Ai.active(),c=this.startSpan(e,s,u),l=Tr(u,c);return Ai.with(l,a,void 0,c)}},o}();function rm(o){return typeof o=="object"&&typeof o.spanId=="string"&&typeof o.traceId=="string"&&typeof o.traceFlags=="number"}var om=new So,Gu=function(){function o(e,t,n,r){this._provider=e,this.name=t,this.version=n,this.options=r}return o.prototype.startSpan=function(e,t,n){return this._getTracer().startSpan(e,t,n)},o.prototype.startActiveSpan=function(e,t,n,r){var s=this._getTracer();return Reflect.apply(s.startActiveSpan,s,arguments)},o.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):om},o}();var ju=function(){function o(){}return o.prototype.getTracer=function(e,t,n){return new So},o}();var sm=new ju,yi=function(){function o(){}return o.prototype.getTracer=function(e,t,n){var r;return(r=this.getDelegateTracer(e,t,n))!==null&&r!==void 0?r:new Gu(this,e,t,n)},o.prototype.getDelegate=function(){var e;return(e=this._delegate)!==null&&e!==void 0?e:sm},o.prototype.setDelegate=function(e){this._delegate=e},o.prototype.getDelegateTracer=function(e,t,n){var r;return(r=this._delegate)===null||r===void 0?void 0:r.getTracer(e,t,n)},o}();var ct;(function(o){o[o.INTERNAL=0]="INTERNAL",o[o.SERVER=1]="SERVER",o[o.CLIENT=2]="CLIENT",o[o.PRODUCER=3]="PRODUCER",o[o.CONSUMER=4]="CONSUMER"})(ct||(ct={}));var qt=bn.getInstance();var bi="trace",Bu=function(){function o(){this._proxyTracerProvider=new yi,this.wrapSpanContext=Uu,this.isSpanContextValid=vo,this.deleteSpan=Lu,this.getSpan=wo,this.getActiveSpan=$u,this.getSpanContext=Ro,this.setSpan=Tr,this.setSpanContext=Du}return o.getInstance=function(){return this._instance||(this._instance=new o),this._instance},o.prototype.setGlobalTracerProvider=function(e){var t=xn(bi,this._proxyTracerProvider,yn.instance());return t&&this._proxyTracerProvider.setDelegate(e),t},o.prototype.getTracerProvider=function(){return Gt(bi)||this._proxyTracerProvider},o.prototype.getTracer=function(e,t){return this.getTracerProvider().getTracer(e,t)},o.prototype.disable=function(){An(bi,yn.instance()),this._proxyTracerProvider=new yi},o}();var wr=Bu.getInstance();var he={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:o=>typeof o=="string"?o:o==null?"":JSON.stringify(o,null,2)};var st=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 pA=new st,zu=o=>{console.log(o)},qu=(o,e,t)=>{let n=(r,s)=>t&&s&&s in t?t[s](r):r;switch(o.role){case"system":return`${n("[ SYSTEM ]","magentaBright")}
32
32
  ${n(o.content,"magenta")}`;case"function":return`${n("[ FUNCTION RESULT ]","yellow")}
33
33
  ${n(o.result??"[No result]","yellowDim")}`;case"user":{let r=`${n("[ USER ]","greenBright")}
34
34
  `;if(typeof o.content=="string")return r+n(o.content,"green");let s=o.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+s.join(`
@@ -38,11 +38,11 @@ ${n(o.result??"[No result]","yellowDim")}`;case"user":{let r=`${n("[ USER ]","gr
38
38
  `,o.functionCalls.forEach((i,a)=>{let u=typeof i.function.params=="string"?i.function.params:JSON.stringify(i.function.params,null,2);s+=n(`${a+1}. ${i.function.name}(${u}) [id: ${i.id}]`,"yellowDim"),a<(o.functionCalls?.length??0)-1&&(s+=`
39
39
  `)}),s+=`
40
40
  `),!o.content&&(!o.functionCalls||o.functionCalls.length===0)&&(s+=n("[No content]","gray")),s}default:return`${n("[ UNKNOWN ]","redBright")}
41
- ${n(JSON.stringify(o),"gray")}`}},Ti=(o=Gu)=>{let e=new st,t=e.gray(`${"\u2500".repeat(60)}
41
+ ${n(JSON.stringify(o),"gray")}`}},Ci=(o=zu)=>{let e=new st,t=e.gray(`${"\u2500".repeat(60)}
42
42
  `);return n=>{let r=n,s="";switch(r.name){case"ChatRequestChatPrompt":s=`
43
43
  ${e.blueBright(`[ CHAT REQUEST Step ${r.step} ]`)}
44
44
  ${t}
45
- `,r.value.forEach((i,a)=>{s+=Bu(i,void 0,e),a<r.value.length-1&&(s+=`
45
+ `,r.value.forEach((i,a)=>{s+=qu(i,void 0,e),a<r.value.length-1&&(s+=`
46
46
  ${t}
47
47
  `)}),s+=`
48
48
  ${t}`;break;case"FunctionResults":s=`
@@ -102,10 +102,10 @@ ${t}
102
102
  [ CHAT RESPONSE CITATIONS ]`)}
103
103
  `,r.value.forEach(i=>{s+=`${e.white("- ")}${e.cyan(i.title||i.url)}
104
104
  `,i.description&&(s+=` ${e.gray(i.description)}
105
- `)}),s+=t;break}default:s=e.gray(JSON.stringify(r,null,2))}o(s)}},ju=Ti(),zu=(o=Gu)=>{let e="\u2500".repeat(60);return t=>{let n=t,r="";switch(n.name){case"ChatRequestChatPrompt":r=`
105
+ `)}),s+=t;break}default:s=e.gray(JSON.stringify(r,null,2))}o(s)}},Hu=Ci(),Ku=(o=zu)=>{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((s,i)=>{r+=Bu(s),i<n.value.length-1&&(r+=`
108
+ `,n.value.forEach((s,i)=>{r+=qu(s),i<n.value.length-1&&(r+=`
109
109
  ${e}
110
110
  `)}),r+=`
111
111
  ${e}`;break;case"FunctionResults":r=`
@@ -164,19 +164,19 @@ ${e}
164
164
  `,n.value.forEach(s=>{r+=`- ${s.title||s.url}
165
165
  `,s.description&&(r+=` ${s.description}
166
166
  `)}),r+=`${e}
167
- `;break}default:r=JSON.stringify(n,null,2)}o(r)}};var ye={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"},vt={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"},Ci=(r=>(r.COMPLETION="completion",r.CHAT="chat",r.RERANK="rerank",r.UNKNOWN="unknown",r))(Ci||{}),Ii=(s=>(s.WORKFLOW="workflow",s.TASK="task",s.AGENT="agent",s.TOOL="tool",s.UNKNOWN="unknown",s))(Ii||{});var wi=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()}},Oo=class extends TransformStream{constructor(e,t){super(new wi(e,t))}};function Eo(o,e){for(let t of e){let n=o.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)):o.push(t)}}var qu=(o,e,t,n)=>{let r=n?o.filter(i=>i.role!=="system"):[...o];t({name:"ChatRequestChatPrompt",step:e,value:r})};var Hu=(o,e)=>{if(!o.results)return;let t={name:"ChatResponseResults",value:o.results};e(t)};function Wu(o,e){let t=new Map;for(let n of o)for(let r of n.results){if(!r)continue;let s=t.get(r.index);s?(r.content&&(s.content=(s.content??"")+r.content),r.thought&&(s.thought=(s.thought??"")+r.thought),r.finishReason&&(s.finishReason=r.finishReason),r.functionCalls&&(s.functionCalls?Eo(s.functionCalls,structuredClone(r.functionCalls)):s.functionCalls=structuredClone(r.functionCalls))):(s=structuredClone(r),t.set(r.index,s))}for(let n of t.values()){let r={name:"ChatResponseStreamingDoneResult",index:n.index,value:n};e(r)}}var Ku=(o,e)=>{e({name:"FunctionResults",value:o})},Ri=(o,e,t,n)=>{n({name:"FunctionError",index:e,fixingInstructions:t,error:o})},Vu=(o,e,t,n)=>{n({name:"ValidationError",index:e,fixingInstructions:t,error:o})},Ju=(o,e,t,n)=>{n({name:"AssertionError",index:e,fixingInstructions:t,error:o})},Qu=(o,e,t)=>{t({name:"RefusalError",index:e,error:o})};var Yu=(o,e,t)=>{t({name:"EmbedRequest",embedModel:e,value:o})},Xu=(o,e)=>{let t=o.slice(0,3).map(r=>({length:r.length,sample:r.slice(0,5),truncated:r.length>5})),n={name:"EmbedResponse",totalEmbeddings:o.length,value:t};e(n)},Zu=(o,e,t,n)=>{n({name:"ResultPickerUsed",sampleCount:o,selectedIndex:e,latency:t})};var Po=o=>{let e={};for(let[t,n]of Object.entries(o))if(n!=null){let r=String(n);e[t]=r.length>100?r.substring(0,100):r}return e},nn=(...o)=>{let e={};for(let t of o)t&&Object.assign(e,t);return e},Mo,ec=o=>{if(Mo)return Mo;if(o)return Mo=rm(o),Mo};var rm=o=>({latencyHistogram:o.createHistogram("ax_llm_request_duration_ms",{description:"Duration of LLM requests in milliseconds",unit:"ms"}),errorCounter:o.createCounter("ax_llm_errors_total",{description:"Total number of LLM request errors"}),requestCounter:o.createCounter("ax_llm_requests_total",{description:"Total number of LLM requests"}),tokenCounter:o.createCounter("ax_llm_tokens_total",{description:"Total number of LLM tokens consumed"}),inputTokenCounter:o.createCounter("ax_llm_input_tokens_total",{description:"Total number of input/prompt tokens consumed"}),outputTokenCounter:o.createCounter("ax_llm_output_tokens_total",{description:"Total number of output/completion tokens generated"}),errorRateGauge:o.createGauge("ax_llm_error_rate",{description:"Current error rate as a percentage (0-100)"}),meanLatencyGauge:o.createGauge("ax_llm_mean_latency_ms",{description:"Mean latency of LLM requests in milliseconds",unit:"ms"}),p95LatencyGauge:o.createGauge("ax_llm_p95_latency_ms",{description:"95th percentile latency of LLM requests in milliseconds",unit:"ms"}),p99LatencyGauge:o.createGauge("ax_llm_p99_latency_ms",{description:"99th percentile latency of LLM requests in milliseconds",unit:"ms"}),streamingRequestsCounter:o.createCounter("ax_llm_streaming_requests_total",{description:"Total number of streaming LLM requests"}),functionCallsCounter:o.createCounter("ax_llm_function_calls_total",{description:"Total number of function/tool calls made"}),functionCallLatencyHistogram:o.createHistogram("ax_llm_function_call_latency_ms",{description:"Latency of function calls in milliseconds",unit:"ms"}),requestSizeHistogram:o.createHistogram("ax_llm_request_size_bytes",{description:"Size of LLM request payloads in bytes",unit:"By"}),responseSizeHistogram:o.createHistogram("ax_llm_response_size_bytes",{description:"Size of LLM response payloads in bytes",unit:"By"}),temperatureGauge:o.createGauge("ax_llm_temperature_gauge",{description:"Temperature setting used for LLM requests"}),maxTokensGauge:o.createGauge("ax_llm_max_tokens_gauge",{description:"Maximum tokens setting used for LLM requests"}),estimatedCostCounter:o.createCounter("ax_llm_estimated_cost_total",{description:"Estimated cost of LLM requests in USD",unit:"$"}),promptLengthHistogram:o.createHistogram("ax_llm_prompt_length_chars",{description:"Length of prompts in characters"}),contextWindowUsageGauge:o.createGauge("ax_llm_context_window_usage_ratio",{description:"Context window utilization ratio (0-1)"}),timeoutsCounter:o.createCounter("ax_llm_timeouts_total",{description:"Total number of timed out LLM requests"}),abortsCounter:o.createCounter("ax_llm_aborts_total",{description:"Total number of aborted LLM requests"}),thinkingBudgetUsageCounter:o.createCounter("ax_llm_thinking_budget_usage_total",{description:"Total thinking budget tokens used"}),multimodalRequestsCounter:o.createCounter("ax_llm_multimodal_requests_total",{description:"Total number of multimodal requests (with images/audio)"}),cacheReadTokensCounter:o.createCounter("ax_llm_cache_read_tokens_total",{description:"Total number of tokens read from cache (prompt caching)"}),cacheWriteTokensCounter:o.createCounter("ax_llm_cache_write_tokens_total",{description:"Total number of tokens written to cache (prompt caching)"})}),tc=(o,e,t,n,r,s)=>{try{if(o.latencyHistogram){let i=Po({operation:e,ai_service:n,...r?{model:r}:{},...s});o.latencyHistogram.record(t,i)}}catch(i){console.warn("Failed to record latency metric:",i)}},nc=(o,e,t,n,r,s,i,a)=>{let u={operation:e,ai_service:s,...i?{model:i}:{},...a};o.meanLatencyGauge&&o.meanLatencyGauge.record(t,u),o.p95LatencyGauge&&o.p95LatencyGauge.record(n,u),o.p99LatencyGauge&&o.p99LatencyGauge.record(r,u)},rc=(o,e,t,n,r)=>{try{if(o.errorCounter){let s=Po({operation:e,ai_service:t,...n?{model:n}:{},...r});o.errorCounter.add(1,s)}}catch(s){console.warn("Failed to record error metric:",s)}},oc=(o,e,t,n,r,s)=>{o.errorRateGauge&&o.errorRateGauge.record(t*100,{operation:e,ai_service:n,...r?{model:r}:{},...s})},sc=(o,e,t,n,r)=>{o.requestCounter&&o.requestCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{},...r})},wr=(o,e,t,n,r,s)=>{try{let i=Po({ai_service:n,...r?{model:r}:{},...s});o.tokenCounter&&o.tokenCounter.add(t,{token_type:e,...i}),e==="input"&&o.inputTokenCounter&&o.inputTokenCounter.add(t,i),e==="output"&&o.outputTokenCounter&&o.outputTokenCounter.add(t,i)}catch(i){console.warn("Failed to record token metric:",i)}},ic=(o,e,t,n,r,s)=>{t&&o.streamingRequestsCounter&&o.streamingRequestsCounter.add(1,{operation:e,ai_service:n,...r?{model:r}:{},...s})},ac=(o,e,t,n,r,s)=>{let i={function_name:e,...n?{ai_service:n}:{},...r?{model:r}:{},...s};o.functionCallsCounter&&o.functionCallsCounter.add(1,i),t&&o.functionCallLatencyHistogram&&o.functionCallLatencyHistogram.record(t,i)},vi=(o,e,t,n,r,s)=>{o.requestSizeHistogram&&o.requestSizeHistogram.record(t,{operation:e,ai_service:n,...r?{model:r}:{},...s})},Si=(o,e,t,n,r,s)=>{o.responseSizeHistogram&&o.responseSizeHistogram.record(t,{operation:e,ai_service:n,...r?{model:r}:{},...s})},uc=(o,e,t,n,r,s)=>{let i={...n?{ai_service:n}:{},...r?{model:r}:{},...s};e!==void 0&&o.temperatureGauge&&o.temperatureGauge.record(e,i),t!==void 0&&o.maxTokensGauge&&o.maxTokensGauge.record(t,i)},ki=(o,e,t,n,r,s)=>{o.estimatedCostCounter&&o.estimatedCostCounter.add(t,{operation:e,ai_service:n,...r?{model:r}:{},...s})},cc=(o,e,t,n,r)=>{o.promptLengthHistogram&&o.promptLengthHistogram.record(e,{ai_service:t,...n?{model:n}:{},...r})},lc=(o,e,t,n,r)=>{o.contextWindowUsageGauge&&o.contextWindowUsageGauge.record(e,{ai_service:t,...n?{model:n}:{},...r})},pc=(o,e,t,n,r)=>{o.timeoutsCounter&&o.timeoutsCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{},...r})},dc=(o,e,t,n,r)=>{o.abortsCounter&&o.abortsCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{},...r})},mc=(o,e,t,n,r)=>{o.thinkingBudgetUsageCounter&&o.thinkingBudgetUsageCounter.add(e,{ai_service:t,...n?{model:n}:{},...r})},gc=(o,e,t,n,r,s)=>{(e||t)&&o.multimodalRequestsCounter&&o.multimodalRequestsCounter.add(1,{ai_service:n,has_images:e.toString(),has_audio:t.toString(),...r?{model:r}:{},...s})},Oi=(o,e,t,n,r,s)=>{try{if(t<=0)return;let i=Po({ai_service:n,...r?{model:r}:{},...s});e==="read"&&o.cacheReadTokensCounter&&o.cacheReadTokensCounter.add(t,i),e==="write"&&o.cacheWriteTokensCounter&&o.cacheWriteTokensCounter.add(t,i)}catch(i){console.warn("Failed to record cache token metric:",i)}};function fc(o){try{return JSON.stringify(o,null,2)}catch{return String(o)}}function St(o,e={}){let t=[o];throw e.fieldPath!==void 0&&t.push(`Field: ${e.fieldPath}`),e.value!==void 0&&t.push(`Value: ${fc(e.value)}`),e.note&&t.push(`Note: ${e.note}`),e.item!==void 0&&t.push(`Chat item: ${fc(e.item)}`),new Error(t.join(`
168
- `))}function yn(o){let e=n=>JSON.stringify(n,null,2);if(!o)throw new Error(`Chat request message item cannot be null or undefined, received: ${e(o)}`);let t=typeof o=="object"&&o!==null&&"role"in o&&typeof o.role=="string"?o.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 o=="object"&&o!==null&&"content"in o&&typeof o.content=="string"?o.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 o=="object"&&o!==null&&"content"in o?o.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 s=n[r];if(!s||typeof s!="object")throw new Error(`User message content item at index ${r} must be an object, received: ${e(s)}`);let i=typeof s=="object"&&s!==null&&"type"in s&&typeof s.type=="string"?s.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 s&&typeof s.text=="string"?s.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 s&&typeof s.image=="string"?s.image:void 0,u="mimeType"in s&&typeof s.mimeType=="string"?s.mimeType:void 0;if(!a||a.trim()==="")throw new Error(`User message image content at index ${r} cannot be empty, received: ${e(a)}`);if(!u||u.trim()==="")throw new Error(`User message image content at index ${r} must have a mimeType, received: ${e(u)}`);break}case"audio":{let a="data"in s&&typeof s.data=="string"?s.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 s&&typeof s.fileUri=="string",u="data"in s&&typeof s.data=="string";if(!a&&!u)throw new Error(`User message file content at index ${r} must have either 'data' or 'fileUri', received: ${e(s)}`);if(a&&u)throw new Error(`User message file content at index ${r} cannot have both 'data' and 'fileUri', received: ${e(s)}`);if(a){let l=s.fileUri;if(!l||l.trim()==="")throw new Error(`User message file content at index ${r} fileUri cannot be empty, received: ${e(l)}`)}if(u){let l=s.data;if(!l||l.trim()==="")throw new Error(`User message file content at index ${r} data cannot be empty, received: ${e(l)}`)}let c="mimeType"in s&&typeof s.mimeType=="string"?s.mimeType:null;if(!c||c.trim()==="")throw new Error(`User message file content at index ${r} must have a mimeType, received: ${e(c)}`);break}case"url":{let a="url"in s&&typeof s.url=="string"?s.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 o=="object"&&o!==null&&"content"in o?o.content:void 0,r=typeof o=="object"&&o!==null&&"functionCalls"in o?o.functionCalls:void 0,s=typeof o=="object"&&o!==null&&"thoughtBlocks"in o?o.thoughtBlocks:void 0,i=typeof n=="string"&&n.trim()!=="",a=Array.isArray(r)&&r.length>0,u=Array.isArray(s)&&s.length>0;if(!i&&!a&&!u&&St("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:s},item:o}),n!==void 0&&typeof n!="string"&&St("Assistant message content must be a string",{fieldPath:"content",value:n,item:o}),r!==void 0&&!Array.isArray(r)&&St("Assistant message functionCalls must be an array when provided",{fieldPath:"functionCalls",value:r,item:o}),Array.isArray(r))for(let c=0;c<r.length;c++){let l=r[c];if((!l||typeof l!="object")&&St("functionCalls entry must be an object",{fieldPath:`functionCalls[${c}]`,value:l,item:o}),(!("id"in l)||typeof l.id!="string"||l.id.trim()==="")&&St("functionCalls entry must include a non-empty string id",{fieldPath:`functionCalls[${c}].id`,value:l.id,item:o}),(!("type"in l)||l.type!=="function")&&St("functionCalls entry must have type 'function'",{fieldPath:`functionCalls[${c}].type`,value:l.type,item:o}),!("function"in l)||!l.function)St("functionCalls entry must include a function object",{fieldPath:`functionCalls[${c}].function`,value:l.function,item:o});else{let p=l.function;(!("name"in p)||typeof p.name!="string"||p.name.trim()==="")&&St("functionCalls entry must include a non-empty function name",{fieldPath:`functionCalls[${c}].function.name`,value:p?.name,item:o}),p.params!==void 0&&typeof p.params!="string"&&typeof p.params!="object"&&St("functionCalls entry params must be a string or object when provided",{fieldPath:`functionCalls[${c}].function.params`,value:p.params,item:o})}}if(o.name!==void 0){let c=o.name;(typeof c!="string"||c.trim()==="")&&St("Assistant message name must be a non-empty string when provided",{fieldPath:"name",value:c,item:o})}break}case"function":{let n=typeof o=="object"&&o!==null&&"functionId"in o&&typeof o.functionId=="string"?o.functionId:void 0,r=typeof o=="object"&&o!==null&&"result"in o?o.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)}`);o.isError!==void 0&&typeof o.isError!="boolean"&&St("Function message isError must be a boolean when provided",{fieldPath:"isError",value:o.isError,item:o});break}default:throw new Error(`Unsupported message role: ${e(t)}`)}}function Fo(o){let e=n=>JSON.stringify(n,null,2),t=Array.isArray(o)?o:[o];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 s=0;s<r.thoughtBlocks.length;s++){let i=r.thoughtBlocks[s];if(typeof i!="object"||i===null)throw new Error(`Chat response result thoughtBlocks[${s}] at index ${n} must be an object, received: ${e(i)}`);if(typeof i.data!="string")throw new Error(`Chat response result thoughtBlocks[${s}].data at index ${n} must be a string, received: ${e(i.data)}`);if(typeof i.encrypted!="boolean")throw new Error(`Chat response result thoughtBlocks[${s}].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[${s}].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 s=0;s<r.annotations.length;s++){let i=r.annotations[s];if(!i||typeof i!="object")throw new Error(`Chat response result annotation at index ${n}[${s}] must be an object, received: ${e(i)}`);if(i.type!=="url_citation")throw new Error(`Chat response result annotation at index ${n}[${s}] 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}[${s}] 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}[${s}] 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 s=0;s<r.functionCalls.length;s++){let i=r.functionCalls[s];if(!i)throw new Error(`Function call at index ${s} 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 ${s} 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 ${s} in result ${n} must have type 'function', received: ${e(i.type)}`);if(!i.function)throw new Error(`Function call at index ${s} 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 ${s} 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 ${s} in result ${n} must be a string or object, received: ${e(i.function.params)}`)}}if(r.finishReason!==void 0){let s=["stop","length","function_call","content_filter","error"];if(!s.includes(r.finishReason))throw new Error(`Chat response result finishReason at index ${n} must be one of: ${s.join(", ")}, received: ${e(r.finishReason)}`)}}}var Ei=new Map;function om(o){return`${o.providerName}:${o.contentHash}`}function sm(o,e){e.type==="text"?o.update(`text:${e.text}`):e.type==="image"?o.update(`image:${e.mimeType}:${e.image.slice(0,100)}`):e.type==="audio"?o.update(`audio:${e.format}:${e.data.slice(0,100)}`):e.type==="file"&&("fileUri"in e?o.update(`file:${e.mimeType}:${e.fileUri}`):o.update(`file:${e.mimeType}:${e.data.slice(0,100)}`))}function im(o){let e=mt("sha256"),t=-1;for(let n=o.length-1;n>=0;n--){let r=o[n];if("cache"in r&&r.cache){t=n;break}}for(let n=0;n<o.length;n++){let r=o[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 s of r.content)sm(e,s)}else r.role==="assistant"&&r.content&&e.update(`assistant:${r.content}`)}return e.digest("hex")}var Se=()=>structuredClone({temperature:0}),He=()=>structuredClone({temperature:.4,frequencyPenalty:.2}),Be=class{constructor(e,{name:t,apiURL:n,headers:r,modelInfo:s,defaults:i,options:a={},supportFor:u,models:c}){this.aiImpl=e;this.name=t,this.apiURL=n||"",this.headers=r,this.supportFor=u,this.tracer=a.tracer??fe.tracer,this.meter=a.meter??fe.meter,this.modelInfo=s,this.models=c,this.id=Ze();let l=this.getModel(i.model)??i.model,p=this.getEmbedModel(i.embedModel)??i.embedModel;if(this.defaults={model:l,embedModel:p},!i.model||typeof i.model!="string"||i.model==="")throw new Error("No model defined");this.setOptions(a),c&&am(c)}#e=!1;#t=!1;rt;fetch;tracer;meter;timeout;excludeContentFromTrace;models;abortSignal;logger=fe.logger??ju;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 ec(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 nn(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((s,i)=>s-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 s=this.getMetricsInstruments();if(s){let i=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel,a=this.getMergedCustomLabels(n);tc(s,e,t,this.name,i,a),nc(s,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 s=this.getMetricsInstruments();if(s){let i=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel,a=this.getMergedCustomLabels(n);sc(s,e,this.name,i,a),t&&rc(s,e,this.name,i,a),oc(s,e,r.rate,this.name,i,a)}}recordTokenUsage(e,t){let n=this.getMetricsInstruments();if(n&&e?.tokens){let{promptTokens:r,completionTokens:s,totalTokens:i,thoughtsTokens:a,cacheReadTokens:u,cacheCreationTokens:c}=e.tokens,l=this.getMergedCustomLabels(t);r&&wr(n,"input",r,this.name,e.model,l),s&&wr(n,"output",s,this.name,e.model,l),i&&wr(n,"total",i,this.name,e.model,l),a&&wr(n,"thoughts",a,this.name,e.model,l),u&&Oi(n,"read",u,this.name,e.model,l),c&&Oi(n,"write",c,this.name,e.model,l)}}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 s of r.content)s.type==="image"?t=!0:s.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(u=>u.name===e);if(!n||!n.promptTokenCostPer1M&&!n.completionTokenCostPer1M)return 0;let{promptTokens:r=0,completionTokens:s=0}=t.tokens,i=n.promptTokenCostPer1M||0,a=n.completionTokenCostPer1M||0;return r*i/1e6+s*a/1e6}estimateCostByName(e,t){if(!t?.tokens)return 0;let n=this.modelInfo.find(u=>u.name===e);if(!n||!n.promptTokenCostPer1M&&!n.completionTokenCostPer1M)return 0;let{promptTokens:r=0,completionTokens:s=0}=t.tokens,i=n.promptTokenCostPer1M||0,a=n.completionTokenCostPer1M||0;return r*i/1e6+s*a/1e6}recordFunctionCallMetrics(e,t,n){let r=this.getMetricsInstruments();if(!(!r||!e))for(let s of e)s&&typeof s=="object"&&"function"in s&&s.function&&typeof s.function=="object"&&"name"in s.function&&ac(r,s.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;pc(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;dc(n,e,this.name,r,this.getMergedCustomLabels(t))}}recordChatMetrics(e,t,n){let r=this.getMetricsInstruments();if(!r)return;let s=this.lastUsedChatModel,i=this.lastUsedModelConfig,a=this.getMergedCustomLabels(t?.customLabels),u=i?.stream??!1;ic(r,"chat",u,this.name,s,a);let{hasImages:c,hasAudio:l}=this.detectMultimodalContent(e);gc(r,c,l,this.name,s,a);let p=this.calculatePromptLength(e);cc(r,p,this.name,s,a),uc(r,i?.temperature,i?.maxTokens,this.name,s,a),t?.thinkingTokenBudget&&this.modelUsage?.tokens?.thoughtsTokens&&mc(r,this.modelUsage.tokens.thoughtsTokens,this.name,s,a);let d=this.calculateRequestSize(e);if(vi(r,"chat",d,this.name,s,a),n&&!u){let m=n,g=this.calculateResponseSize(m);if(Si(r,"chat",g,this.name,s,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&&lc(r,f,this.name,s,a);let x=this.estimateCost(this.lastUsedChatModel,m.modelUsage);x>0&&ki(r,"chat",x,this.name,s,a)}}recordEmbedMetrics(e,t,n){let r=this.getMetricsInstruments();if(!r)return;let s=this.lastUsedEmbedModel,i=this.getMergedCustomLabels(n?.customLabels),a=this.calculateRequestSize(e);vi(r,"embed",a,this.name,s,i);let u=this.calculateResponseSize(t);Si(r,"embed",u,this.name,s,i);let c=this.estimateCostByName(s,t.modelUsage);c>0&&ki(r,"embed",c,this.name,s,i)}getMetrics(){return structuredClone(this.metrics)}async chat(e,t){let n=performance.now(),r=!1,s,i=this.getModelByKey(e.model),a=i?i.thinkingTokenBudget:void 0,u={...i?{thinkingTokenBudget:a,showThoughts:i.showThoughts,stream:i.stream,debug:i.debug,useExpensiveModel:i.useExpensiveModel}:void 0,...Object.fromEntries(Object.entries(t??{}).filter(([,c])=>c!==void 0))};try{return s=await this._chat1(e,u),s}catch(c){throw r=!0,c instanceof Error&&(c.message.includes("timeout")||c.name==="TimeoutError"?this.recordTimeoutMetric("chat",u?.customLabels):(c.message.includes("abort")||c.name==="AbortError")&&this.recordAbortMetric("chat",u?.customLabels)),c}finally{let c=performance.now()-n;this.updateLatencyMetrics("chat",c,u?.customLabels),this.updateErrorMetrics("chat",r,u?.customLabels),r||this.recordChatMetrics(e,u,s)}}async _chat1(e,t){let n=this.getModel(e.model)??e.model??this.defaults.model;if(Array.isArray(e.chatPrompt))for(let c of e.chatPrompt)yn(c);let r=this.getModelByKey(e.model),s={...this.aiImpl.getModelConfig(),...r?r.modelConfig:void 0,...e.modelConfig},i=this.modelInfo.find(c=>c.name===n);if(i?.notSupported?.temperature&&"temperature"in s&&delete s.temperature,i?.notSupported?.topP&&"topP"in s&&delete s.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(c=>c.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 s.stream=(t?.stream!==void 0?t.stream:s.stream)??!0,this.getFeatures(n).streaming||(s.stream=!1),this.tracer?await this.tracer.startActiveSpan("AI Chat Request",{kind:ct.SERVER,attributes:{[ye.LLM_SYSTEM]:this.name,[ye.LLM_OPERATION_NAME]:"chat",[ye.LLM_REQUEST_MODEL]:n,[ye.LLM_REQUEST_MAX_TOKENS]:s.maxTokens??"Not set",[ye.LLM_REQUEST_TEMPERATURE]:s.temperature,[ye.LLM_REQUEST_TOP_P]:s.topP??"Not set",[ye.LLM_REQUEST_TOP_K]:s.topK??"Not set",[ye.LLM_REQUEST_FREQUENCY_PENALTY]:s.frequencyPenalty??"Not set",[ye.LLM_REQUEST_PRESENCE_PENALTY]:s.presencePenalty??"Not set",[ye.LLM_REQUEST_STOP_SEQUENCES]:s.stopSequences?.join(", ")??"Not set",[ye.LLM_REQUEST_LLM_IS_STREAMING]:s.stream??"Not set"}},t?.traceContext??qt.active(),async c=>await this._chat2(n,s,e,t,c)):await this._chat2(n,s,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,s){if(!this.aiImpl.createChatReq)throw new Error("createChatReq not implemented");let i=r?.debug??this.#e,a=r?.verbose??this.#t,u;n.functions&&n.functions.length>0&&(u=n.functions.map(y=>this.cleanupFunctionSchema(y)));let c={...n,model:e,functions:u,modelConfig:t};this.lastUsedChatModel=e,this.lastUsedModelConfig=t,i&&qu(c.chatPrompt,r?.stepIndex??0,r?.logger??this.logger,r?.debugHideSystemPrompt);let l=this.getFeatures(e).functions,p=r?.functionCallMode??"auto",m=p==="prompt"||p==="auto"&&!l?{...c,chatPrompt:c.chatPrompt.map(y=>{if(y.role==="assistant"){let{content:T,name:C,cache:R}=y;return{role:"assistant",content:T,name:C,cache:R}}return y.role==="function"?{role:"user",content:y.result}:y}),functions:[]}:c,g=await this.handleContextCaching(e,m,r,s),f=async()=>{if(g?.preparedRequest){let{apiConfig:R,request:M}=g.preparedRequest;return s?.isRecording()&&hc(n,s,this.excludeContentFromTrace),await tt({name:R.name,url:this.apiURL,localCall:R.localCall,headers:await this.buildHeaders(R.headers),stream:t.stream,timeout:this.timeout,verbose:a,fetch:this.fetch,span:s,abortSignal:r?.abortSignal??this.abortSignal,corsProxy:this.corsProxy,retry:r?.retry??this.retry},M)}let[y,T]=await this.aiImpl.createChatReq(m,r);return s?.isRecording()&&hc(n,s,this.excludeContentFromTrace),await tt({name:y.name,url:this.apiURL,localCall:y.localCall,headers:await this.buildHeaders(y.headers),stream:t.stream,timeout:this.timeout,verbose:a,fetch:this.fetch,span:s,abortSignal:r?.abortSignal??this.abortSignal,corsProxy:this.corsProxy,retry:r?.retry??this.retry},T)},x=r?.rateLimiter??this.rt,A=x?await x(f,{modelUsage:this.modelUsage}):await f();if(t.stream){if(!this.aiImpl.createChatStreamResp)throw new Error("createChatStreamResp not implemented");let y=this.aiImpl.createChatStreamResp.bind(this),T=I=>O=>{let E=y(O,I);if(E.sessionId=r?.sessionId,!E.modelUsage){let $=this.aiImpl.getTokenUsage();$&&(E.modelUsage={ai:this.name,model:e,tokens:$})}return this.modelUsage=E.modelUsage,this.recordTokenUsage(E.modelUsage,r?.customLabels),s?.isRecording()&&xc(E,s,this.excludeContentFromTrace),E},C=async I=>{s?.isRecording()&&s.end(),i&&Wu(I,r?.logger??this.logger)};if(typeof window<"u"){let I=A,O={},E=[],$=r?.abortSignal??this.abortSignal;return new ReadableStream({start:N=>{let S=I.getReader(),v=()=>{try{S.cancel().catch(()=>{})}catch{}try{this.recordAbortMetric("chat",r?.customLabels)}catch{}try{s?.isRecording()&&s.end()}catch{}try{N.error(new DOMException("Aborted","AbortError"))}catch{N.error(new Error("Aborted"))}};if($){if($.aborted){v();return}$.addEventListener("abort",v,{once:!0})}async function F(){try{for(;;){let{done:P,value:L}=await S.read();if(P){C&&await C(E),N.close();break}let D=T(O)(L);D&&(E.push(D),N.enqueue(D))}}catch(P){if(N.error(P),s?.isRecording())try{s.end()}catch{}}finally{if(S.releaseLock(),$)try{$.removeEventListener("abort",v)}catch{}}}F()}})}return A.pipeThrough(new Oo(T({}),C))}if(!this.aiImpl.createChatResp)throw new Error("createChatResp not implemented");let h=this.aiImpl.createChatResp(A);if(h.sessionId=r?.sessionId,!h.modelUsage){let y=this.aiImpl.getTokenUsage();y&&(h.modelUsage={ai:this.name,model:e,tokens:y})}return h.modelUsage&&(this.modelUsage=h.modelUsage,this.recordTokenUsage(h.modelUsage,r?.customLabels)),s?.isRecording()&&(xc(h,s,this.excludeContentFromTrace),s.end()),i&&Hu(h,r?.logger??this.logger),h}async embed(e,t){let n=performance.now(),r=!1,s,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 s=await this._embed1(e,a),s}catch(u){throw r=!0,u instanceof Error&&(u.message.includes("timeout")||u.name==="TimeoutError"?this.recordTimeoutMetric("embed",a?.customLabels):(u.message.includes("abort")||u.name==="AbortError")&&this.recordAbortMetric("embed",a?.customLabels)),u}finally{let u=performance.now()-n;this.updateLatencyMetrics("embed",u,a?.customLabels),this.updateErrorMetrics("embed",r,a?.customLabels),!r&&s&&this.recordEmbedMetrics(e,s,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:ct.SERVER,attributes:{[ye.LLM_SYSTEM]:this.name,[ye.LLM_OPERATION_NAME]:"embeddings",[ye.LLM_REQUEST_MODEL]:n}},t?.traceContext??qt.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 s=this.aiImpl.createEmbedReq.bind(this.aiImpl),i=n?.debug??this.#e,a=n?.verbose??this.#t,u={...t,embedModel:e};this.lastUsedEmbedModel=e,i&&Yu(u.texts??[],e,n?.logger??this.logger);let c=async()=>{let[m,g]=await s(u);return await tt({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)},l=n?.rateLimiter??this.rt,p=l?await l(c,{modelUsage:this.embedModelUsage}):await c(),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(vt.GEN_AI_USAGE,{[ye.LLM_USAGE_INPUT_TOKENS]:d.modelUsage.tokens.promptTokens,[ye.LLM_USAGE_OUTPUT_TOKENS]:d.modelUsage.tokens.completionTokens??0,[ye.LLM_USAGE_TOTAL_TOKENS]:d.modelUsage.tokens.totalTokens}),i&&Xu(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 s=n?.contextCache;if(!s)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 u=s.ttlSeconds??3600,c=s.refreshWindowSeconds??300,l=s.minTokens??2048;if(s.name)return this.useCacheByName(e,t,s.name,n,r);let p=im(t.chatPrompt);if(!p||p===mt("sha256").digest("hex"))return null;let d={providerName:this.getName(),contentHash:p},m=om(d),g=Date.now(),f=s.registry,x=f?await f.get(m):Ei.get(m);if(x&&x.expiresAt>g){if(x.expiresAt-g<c*1e3&&this.aiImpl.buildCacheUpdateTTLOp){await this.executeCacheOperation(this.aiImpl.buildCacheUpdateTTLOp(x.cacheName,u),n,r);let T={cacheName:x.cacheName,expiresAt:g+u*1e3,tokenCount:x.tokenCount};f?await f.set(m,T):Ei.set(m,{...T,contentHash:p,lastTouchedAt:g})}return this.useCacheByName(e,t,x.cacheName,n,r)}if(this.estimateCacheableTokens(t.chatPrompt)<l)return null;let h=this.aiImpl.buildCacheCreateOp?.(t,n);if(h){let y=await this.executeCacheOperation(h,n,r);if(y){let T={cacheName:y.name,expiresAt:new Date(y.expiresAt).getTime(),tokenCount:y.tokenCount};return f?await f.set(m,T):Ei.set(m,{...T,contentHash:p,lastTouchedAt:g}),this.useCacheByName(e,t,y.name,n,r)}}return null}async useCacheByName(e,t,n,r,s){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 s=await tt({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(s)}catch(s){n?.addEvent("context_cache.error",{type:e.type,error:s instanceof Error?s.message:String(s)});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 hc(o,e,t){let n=[];if(o.chatPrompt&&Array.isArray(o.chatPrompt)&&o.chatPrompt.length>0)for(let s of o.chatPrompt)switch(s.role){case"system":if(s.content){let i={};t||(i.content=s.content),e.addEvent(vt.GEN_AI_SYSTEM_MESSAGE,i)}break;case"user":if(typeof s.content=="string")n.push(s.content);else if(Array.isArray(s.content))for(let i of s.content)i.type==="text"&&n.push(i.text);break;case"assistant":{let i=s.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&&s.content&&(a.content=s.content),e.addEvent(vt.GEN_AI_ASSISTANT_MESSAGE,a)}else if(s.content){let a={};t||(a.content=s.content),e.addEvent(vt.GEN_AI_ASSISTANT_MESSAGE,a)}break}case"function":{let i={id:s.functionId};t||(i.content=s.result),e.addEvent(vt.GEN_AI_TOOL_MESSAGE,i);break}}let r={};t||(r.content=n.join(`
169
- `)),e.addEvent(vt.GEN_AI_USER_MESSAGE,r)}function xc(o,e,t){if(o.modelUsage?.tokens){let n=o.modelUsage.tokens.thoughtsTokens?{[ye.LLM_USAGE_THOUGHTS_TOKENS]:o.modelUsage.tokens.thoughtsTokens}:{};e.addEvent(vt.GEN_AI_USAGE,{[ye.LLM_USAGE_INPUT_TOKENS]:o.modelUsage.tokens.promptTokens,[ye.LLM_USAGE_OUTPUT_TOKENS]:o.modelUsage.tokens.completionTokens??0,[ye.LLM_USAGE_TOTAL_TOKENS]:o.modelUsage.tokens.totalTokens,...n})}if(o.results)for(let n=0;n<o.results.length;n++){let r=o.results[n];if(!r||!r.content&&!r.thought&&!r.functionCalls?.length&&!r.finishReason)continue;let s=r.functionCalls?.map(a=>({id:a.id,type:a.type,function:a.function.name,arguments:a.function.params})),i={};s&&s.length>0?(t||(i.content=r.content),i.tool_calls=s):t||(i.content=r.content??""),e.addEvent(vt.GEN_AI_CHOICE,{finish_reason:r.finishReason,index:n,message:JSON.stringify(i,null,2)})}}function Ac(o){let e=0;for(let t of o){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 am(o){let e=new Set;for(let t of o){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 Rr=(x=>(x.Claude46Opus="claude-opus-4-6",x.Claude46Sonnet="claude-sonnet-4-6",x.Claude45Opus="claude-opus-4-5-20251101",x.Claude41Opus="claude-opus-4-1-20250805",x.Claude4Opus="claude-opus-4-20250514",x.Claude4Sonnet="claude-sonnet-4-20250514",x.Claude45Sonnet="claude-sonnet-4-5-20250929",x.Claude45Haiku="claude-haiku-4-5",x.Claude37Sonnet="claude-3-7-sonnet-latest",x.Claude35Sonnet="claude-3-5-sonnet-latest",x.Claude35Haiku="claude-3-5-haiku-latest",x.Claude3Opus="claude-3-opus-latest",x.Claude3Sonnet="claude-3-sonnet-20240229",x.Claude3Haiku="claude-3-haiku-20240307",x.Claude21="claude-2.1",x.ClaudeInstant12="claude-instant-1.2",x))(Rr||{}),vr=(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))(vr||{});var Sr=[{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 Ht=o=>{if(!o||typeof o!="object")return o;let e={...o};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,Ht(r)]))),e.items&&(e.items=Ht(e.items)),Array.isArray(e.anyOf)&&(e.anyOf=e.anyOf.map(n=>Ht(n))),Array.isArray(e.allOf)&&(e.allOf=e.allOf.map(n=>Ht(n))),Array.isArray(e.oneOf)&&(e.oneOf=e.oneOf.map(n=>Ht(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"},...Se()}),bc=()=>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"},...Se()}),Mi=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,s;this.isVertex?s={name:r?`/models/${n}:streamRawPredict?alt=sse`:`/models/${n}:rawPredict`}:s={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(F=>"cache"in F&&F.cache)||e.functions?.some(F=>F.cache),u=e.chatPrompt.filter(F=>F.role==="system"),c=u.map((F,P)=>({type:"text",text:F.content,...F.cache||a&&P===u.length-1?{cache_control:{type:"ephemeral"}}:{}})),l=e.chatPrompt.filter(F=>F.role!=="system"),p=e.functions?.map((F,P,L)=>{let D={type:"object",properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]},j=F.parameters?Ht(F.parameters):void 0;return j===void 0||j&&typeof j=="object"&&Object.keys(j).length===0?j={...D}:j&&typeof j=="object"&&j.type==="object"&&(!("properties"in j)||!j.properties||Object.keys(j.properties).length===0)&&(j={...j,properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]}),{name:F.name,description:F.description,input_schema:j,...F.cache||a&&P===L.length-1?{cache_control:{type:"ephemeral"}}:{}}}),m=(this.config.tools??[]).map(F=>F&&typeof F=="object"&&"type"in F?F:{name:F.name,description:F.description,input_schema:F.input_schema?Ht(F.input_schema):void 0,...F.cache_control?{cache_control:F.cache_control}:{}}),g=[...p??[],...m];g.length===0&&(g=void 0);let f=e.modelConfig?.maxTokens??this.config.maxTokens,x=e.modelConfig?.stopSequences??this.config.stopSequences,A=e.modelConfig?.temperature,h=e.modelConfig?.topP,y=e.modelConfig?.topK??this.config.topK,T=e.modelConfig?.n??this.config.n;if(T&&T>1)throw new Error("Anthropic does not support sampling (n > 1)");let C=F=>F.includes("claude-opus-4-6"),R=F=>F.includes("claude-opus-4-5"),M,I,O=n;if(t?.thinkingTokenBudget){let F=this.config.thinkingTokenBudgetLevels,P=this.config.effortLevelMapping;if(t.thinkingTokenBudget==="none")M=void 0,I=void 0;else{let L=t.thinkingTokenBudget;if(C(O))M={type:"adaptive"},I={effort:P?.[L]??"medium"};else if(R(O)){M={type:"enabled",budget_tokens:F?.[L]??1e4};let j=P?.[L]??"medium";j==="max"&&(j="high"),I={effort:j}}else M={type:"enabled",budget_tokens:F?.[L]??1e4}}}let $=um(l,!!M);$.some(F=>F.role==="assistant"&&Array.isArray(F.content)&&F.content.length>0&&F.content[0]?.type==="tool_use")&&(M=void 0,I=void 0);let S;if(this.usedStructuredOutput=!1,e.responseFormat&&e.responseFormat.type==="json_schema"&&e.responseFormat.schema){let F=e.responseFormat.schema.schema||e.responseFormat.schema;S={type:"json_schema",schema:Ht(F)},this.usedStructuredOutput=!0}let v={...this.isVertex?{anthropic_version:"vertex-2023-10-16"}:{model:n},...f?{max_tokens:f}:{},...x&&x.length>0?{stop_sequences:x}:{},...A!==void 0&&!M?{temperature:A}:{},...h!==void 0&&(!M||h>=.95)?{top_p:h}:{},...y&&!M?{top_k:y}:{},...i,...g?{tools:g}:{},...r?{stream:!0}:{},...c?{system:c}:{},...M?{thinking:M}:{},...I?{output_config:I}:{},...S?{output_format:S}:{},messages:$};return[s,v]};createChatResp=e=>{if(e.type==="error")throw new Le(e.error.message,void 0,void 0);let t=yc(e.stop_reason),n=this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1,r="",s=[],i=[],a=[];for(let l of e.content)switch(l.type){case"text":if(r+=l.text??"",Array.isArray(l.citations))for(let p of l.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=l.thinking??"",d=l.signature;i.push({data:p,encrypted:!1,...typeof d=="string"?{signature:d}:{}})}break;case"redacted_thinking":if(n){let p=l.data??"",d=l.signature;i.push({data:p,encrypted:!0,...typeof d=="string"?{signature:d}:{}})}break;case"tool_use":s.push({id:l.id,type:"function",function:{name:l.name,params:l.input}});break}let u={index:0,id:e.id,finishReason:t};r&&(u.content=r),i.length>0&&(u.thoughtBlocks=i,u.thought=i.map(l=>l.data).join("")),s.length>0&&(u.functionCalls=s),a.length>0&&(u.citations=a);let c=[u];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:c,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:s}=e;throw new Le(s.message,void 0,void 0)}let r=0;if(e.type==="message_start"){let{message:s}=e,i=[{index:r,content:"",id:s.id}];return this.tokensUsed={promptTokens:s.usage?.input_tokens??0,completionTokens:s.usage?.output_tokens??0,totalTokens:(s.usage?.input_tokens??0)+(s.usage?.output_tokens??0)+(s.usage?.cache_creation_input_tokens??0)+(s.usage?.cache_read_input_tokens??0),cacheCreationTokens:s.usage?.cache_creation_input_tokens,cacheReadTokens:s.usage?.cache_read_input_tokens},{results:i}}if(e.type==="content_block_start"){let{content_block:s}=e;if(s.type==="text"){let i=[];if(Array.isArray(s.citations))for(let a of s.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:s.text,...i.length?{citations:i}:{}}]}}if(s.type==="thinking")return this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1?{results:[{index:r,thought:s.thinking,thoughtBlocks:[{data:s.thinking,encrypted:!1}]}]}:{results:[{index:r,content:""}]};if(s.type==="tool_use"&&typeof s.id=="string"&&typeof e.index=="number"&&!n.indexIdMap[e.index]){n.indexIdMap[e.index]=s.id;let i=[{id:s.id,type:"function",function:{name:s.name,params:""}}];return{results:[{index:r,functionCalls:i}]}}if(s.type==="web_search_tool_result"||s.type==="server_tool_use")return{results:[{index:r,content:""}]}}if(e.type==="content_block_delta"){let{delta:s}=e;if(s.type==="citations_delta"){let i=s.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(s.type==="text_delta"){let i=[];if(Array.isArray(s.citations))for(let a of s.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:s.text,...i.length?{citations:i}:{}}]}}if(s.type==="thinking_delta")return this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1?{results:[{index:r,thought:s.thinking,thoughtBlocks:[{data:s.thinking,encrypted:!1}]}]}:{results:[{index:r,content:""}]};if(s.type==="signature_delta")return{results:[{index:r,thoughtBlocks:[{data:"",encrypted:!1,signature:s.signature}]}]};if(s.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:s.partial_json}}];return{results:[{index:r,functionCalls:a}]}}}if(e.type==="message_delta"){let{delta:s,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:yc(s.stop_reason)}]}}return{results:[{index:r,content:""}]}};supportsImplicitCaching=()=>!0},bn=class o extends Be{static create(e){return new o(e)}constructor({apiKey:e,projectId:t,region:n,config:r,options:s,models:i}){let a=t!==void 0&&n!==void 0,u,c;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");u=`https://${n==="global"?"aiplatform":`${n}-aiplatform`}.googleapis.com/v1/projects/${t}/locations/${n}/publishers/anthropic/`,c=async()=>({Authorization:`Bearer ${await e()}`,"anthropic-beta":"web-search-2025-03-05"})}else{if(!e)throw new Error("Anthropic API key not set");u="https://api.anthropic.com/v1",c=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 l={...Pi(),...r},p=new Mi(l,a),d=g=>{let f=ft({model:g,modelInfo:Sr,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,x=f?.config;if(!x)return g;let A={};x.maxTokens!==void 0&&(A.maxTokens=x.maxTokens),x.temperature!==void 0&&(A.temperature=x.temperature),x.topP!==void 0&&(A.topP=x.topP),x.topK!==void 0&&(A.topK=x.topK),x.presencePenalty!==void 0&&(A.presencePenalty=x.presencePenalty),x.frequencyPenalty!==void 0&&(A.frequencyPenalty=x.frequencyPenalty),x.stopSequences!==void 0&&(A.stopSequences=x.stopSequences),x.endSequences!==void 0&&(A.endSequences=x.endSequences),x.stream!==void 0&&(A.stream=x.stream),x.n!==void 0&&(A.n=x.n);let h={...f};Object.keys(A).length>0&&(h.modelConfig={...f.modelConfig??{},...A});let y=x.thinking?.thinkingTokenBudget;if(typeof y=="number"){let T=l.thinkingTokenBudgetLevels,C=[["minimal",T?.minimal??1024],["low",T?.low??5e3],["medium",T?.medium??1e4],["high",T?.high??2e4],["highest",T?.highest??32e3]],R="minimal",M=Number.POSITIVE_INFINITY;for(let[I,O]of C){let E=Math.abs(y-O);E<M&&(M=E,R=I)}h.thinkingTokenBudget=R}return x.thinking?.includeThoughts!==void 0&&(h.showThoughts=!!x.thinking.includeThoughts),h});super(p,{name:"Anthropic",apiURL:u,headers:c,modelInfo:Sr,defaults:{model:l.model},options:s,supportFor:d,models:m??i})}};function um(o,e){let t=o.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 s="",i=[],a=r.thoughtBlocks;if(Array.isArray(a)&&a.length>0)for(let u of a)u.encrypted?i.push(u.signature?{type:"redacted_thinking",data:u.data,signature:u.signature}:{type:"redacted_thinking",data:u.data}):i.push(u.signature?{type:"thinking",thinking:u.data,signature:u.signature}:{type:"thinking",thinking:u.data});if(typeof r.content=="string"&&(i.length>0?s=[...i,{type:"text",text:r.content}]:s=r.content),typeof r.functionCalls<"u"&&(s=r.functionCalls.map(u=>{let c={};if(typeof u.function.params=="string"){let l=u.function.params;if(l.trim().length===0)c={};else try{c=JSON.parse(l)}catch{throw new Error(`Failed to parse function params JSON: ${l}`)}}else typeof u.function.params=="object"&&(c=u.function.params);return{type:"tool_use",id:u.id,name:u.function.name,input:c,...r.cache?{cache_control:{type:"ephemeral"}}:{}}}),Array.isArray(s)&&i.length>0&&(s=[...i,...s])),r.cache){if(typeof s=="string")s=[{type:"text",text:s,cache_control:{type:"ephemeral"}}];else if(Array.isArray(s)&&s.length>0){let u=s.length-1,c=s[u];c&&c.type==="text"&&(s[u]={...c,cache_control:{type:"ephemeral"}})}}return{role:"assistant",content:s}}default:throw new Error("Invalid role")}}),n=cm(t);return lm(n)}function cm(o){let e=[];for(let[t,n]of o.entries()){if(n.role!=="assistant"){e.push(n);continue}if(t>0&&o.at(t-1)?.role==="assistant"){let r=e.pop();e.push({...r||{},...n})}else e.push(n)}return e}function lm(o){return o.map(e=>e.role==="assistant"&&typeof e.content=="string"?{...e,content:e.content.replace(/\s+$/,"")}:e)}function yc(o){if(o)switch(o){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 kr=(D=>(D.GPT4="gpt-4",D.GPT41="gpt-4.1",D.GPT41Mini="gpt-4.1-mini",D.GPT41Nano="gpt-4.1-nano",D.GPT4O="gpt-4o",D.GPT4OMini="gpt-4o-mini",D.GPT4ChatGPT4O="chatgpt-4o-latest",D.GPT4Turbo="gpt-4-turbo",D.GPT35Turbo="gpt-3.5-turbo",D.GPT35TurboInstruct="gpt-3.5-turbo-instruct",D.GPT35TextDavinci002="text-davinci-002",D.GPT3TextBabbage002="text-babbage-002",D.GPT3TextAda001="text-ada-001",D.GPT5="gpt-5",D.GPT5Nano="gpt-5-nano",D.GPT5Mini="gpt-5-mini",D.GPT5Chat="gpt-5-chat",D.GPT5ChatLatest="gpt-5-chat-latest",D.GPT5Codex="gpt-5-codex",D.GPT5Pro="gpt-5-pro",D.GPT51="gpt-5.1",D.GPT51ChatLatest="gpt-5.1-chat-latest",D.GPT51Codex="gpt-5.1-codex",D.GPT51CodexMini="gpt-5.1-codex-mini",D.GPT51CodexMax="gpt-5.1-codex-max",D.GPT52="gpt-5.2",D.GPT52ChatLatest="gpt-5.2-chat-latest",D.GPT52Codex="gpt-5.2-codex",D.GPT52Pro="gpt-5.2-pro",D.O1="o1",D.O1Mini="o1-mini",D.O3="o3",D.O3Mini="o3-mini",D.O4Mini="o4-mini",D))(kr||{}),Tn=(n=>(n.TextEmbeddingAda002="text-embedding-ada-002",n.TextEmbedding3Small="text-embedding-3-small",n.TextEmbedding3Large="text-embedding-3-large",n))(Tn||{});var Cn=(G=>(G.GPT4="gpt-4",G.GPT41="gpt-4.1",G.GPT41Mini="gpt-4.1-mini",G.GPT41Nano="gpt-4.1-nano",G.GPT4O="gpt-4o",G.GPT4OMini="gpt-4o-mini",G.GPT4ChatGPT4O="chatgpt-4o-latest",G.GPT4Turbo="gpt-4-turbo",G.GPT35Turbo="gpt-3.5-turbo",G.GPT35TurboInstruct="gpt-3.5-turbo-instruct",G.GPT35TextDavinci002="text-davinci-002",G.GPT3TextBabbage002="text-babbage-002",G.GPT3TextAda001="text-ada-001",G.GPT5="gpt-5",G.GPT5Nano="gpt-5-nano",G.GPT5Mini="gpt-5-mini",G.GPT5Chat="gpt-5-chat",G.GPT5ChatLatest="gpt-5-chat-latest",G.GPT5Codex="gpt-5-codex",G.GPT5Pro="gpt-5-pro",G.GPT51="gpt-5.1",G.GPT51ChatLatest="gpt-5.1-chat-latest",G.GPT51Codex="gpt-5.1-codex",G.GPT51CodexMini="gpt-5.1-codex-mini",G.GPT51CodexMax="gpt-5.1-codex-max",G.GPT52="gpt-5.2",G.GPT52ChatLatest="gpt-5.2-chat-latest",G.GPT52Codex="gpt-5.2-codex",G.GPT52Pro="gpt-5.2-pro",G.O1Pro="o1-pro",G.O1="o1",G.O1Mini="o1-mini",G.O3Pro="o3-pro",G.O3="o3",G.O3Mini="o3-mini",G.O4Mini="o4-mini",G))(Cn||{});var In=[{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}],_o=[{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 pm=o=>{let e=["o1","o1-mini","o3","o3-mini","o4-mini","o1-pro","o3-pro"];return e.includes(o)||e.includes(o)},rn=()=>structuredClone({model:"gpt-5-mini",embedModel:"text-embedding-3-small",...Se()}),No=()=>structuredClone({...rn(),model:"gpt-5"}),Lo=()=>structuredClone({model:"gpt-5-mini",embedModel:"text-embedding-3-small",...He()}),$o=()=>({...rn(),model:"gpt-5-nano"}),Fi=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"},s=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=dm(e),u=e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,c=e.modelConfig?.stream??this.config.stream,l=this.config.store,p=pm(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}}:{},...s?{tools:s}:{},...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}:{},...u!==void 0?{frequency_penalty:u}:{}},...(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}:{},...c&&this.streamingUsage?{stream:!0,stream_options:{include_usage:!0}}:{},...l?{store:l}:{},...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:s}=e;if(s)throw s;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 Le(a.message.refusal,e.model,e.id);let u=Tc(a.finish_reason),c=a.message.tool_calls?.map(({id:l,function:{arguments:p,name:d}})=>({id:l,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(l=>l?.type==="url_citation"&&l.url_citation).map(l=>({url:l.url_citation?.url,title:l.url_citation?.title,description:l.url_citation?.description})),functionCalls:c,finishReason:u}}),remoteId:t}}createChatStreamResp(e,t){let{id:n,usage:r,choices:s}=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:s.map(({index:u,delta:{content:c,role:l,refusal:p,tool_calls:d,reasoning_content:m,annotations:g},finish_reason:f})=>{if(p)throw new Le(p,void 0,n);let x=Tc(f),A=d?.map(({id:h,index:y,function:{name:T,arguments:C}})=>{typeof h=="string"&&typeof y=="number"&&!i.indexIdMap[y]&&(i.indexIdMap[y]=h);let R=i.indexIdMap[y];return R?{id:R,type:"function",function:{name:T,params:C}}:null}).filter(h=>h!==null);return{index:u,content:c??void 0,role:l,thought:m,citations:g?.filter(h=>h?.type==="url_citation"&&h.url_citation).map(h=>({url:h.url_citation?.url,title:h.url_citation?.title,description:h.url_citation?.description})),functionCalls:A,finishReason:x,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)}}},Tc=o=>{switch(o){case"stop":return"stop";case"length":return"length";case"content_filter":return"error";case"tool_calls":return"function_call"}};function dm(o){return o.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 Ge=class extends Be{constructor({apiKey:e,config:t,options:n,apiURL:r,modelInfo:s,models:i,chatReqUpdater:a,supportFor:u}){if(!e||e==="")throw new Error("OpenAI API key not set");let c=new Fi(t,n?.streamingUsage??!0,a);super(c,{name:"OpenAI",apiURL:r||"https://api.openai.com/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:s,defaults:{model:t.model,embedModel:t.embedModel},options:n,supportFor:u,models:i})}},wn=class extends Ge{constructor({apiKey:e,apiURL:t,config:n,options:r,models:s,modelInfo:i}){if(!e||e==="")throw new Error("OpenAI API key not set");i=[...In,...i??[]];let a=c=>{let l=ft({model:c,modelInfo:i,models:s});return{functions:!0,streaming:!0,hasThinkingBudget:l?.supported?.thinkingBudget??!1,hasShowThoughts:l?.supported?.showThoughts??!1,structuredOutputs:l?.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:l?.supported?.thinkingBudget??!1,multiTurn:!0}},u=s?.map(c=>{let l=c,p=l?.config;if(!p)return c;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={...l};Object.keys(d).length>0&&(g.modelConfig={...l.modelConfig??{},...d});let f=p?.thinking?.thinkingTokenBudget;if(typeof f=="number"){let x=[["minimal",200],["low",800],["medium",5e3],["high",1e4],["highest",24500]],A="minimal",h=Number.POSITIVE_INFINITY;for(let[y,T]of x){let C=Math.abs(f-T);C<h&&(h=C,A=y)}g.thinkingTokenBudget=A}return p?.thinking?.includeThoughts!==void 0&&(g.showThoughts=!!p.thinking.includeThoughts),g});super({apiKey:e,apiURL:t,config:{...rn(),...n},options:r,modelInfo:i,models:u??s,supportFor:a}),super.setName("OpenAI")}};var mm=o=>{let e=o.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},gm=o=>{let e=o.match(/^(\d{4}-\d{2}-\d{2})/);return e?e[1]>="2024-08-01":!1},_i=rn,Cc=Lo,Ic=$o,wc=No,Rn=class extends Ge{constructor({apiKey:e,resourceName:t,deploymentName:n,version:r="api-version=2024-02-15-preview",config:s,options:i,models:a,modelInfo:u}){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 c={..._i(),...s},l=mm(r),p=gm(l);u=[...In,...u??[]];let d=g=>{let f=ft({model:g,modelInfo:u,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:c,options:i,models:a,modelInfo:u,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=${l}`,m).href),super.setHeaders(async()=>({"api-key":e}))}};var Do=class o{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.");fm(e),this.services=[...e].sort(t?.comparator??o.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 o(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,s=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 u=a.latency.chat.samples.length;u>0&&(t+=a.latency.chat.mean*u,n+=u);let c=a.latency.embed.samples.length;c>0&&(r+=a.latency.embed.mean*c,s+=c)}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),s>0&&(e.latency.embed.mean=r/s);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,s=Date.now()-r,i=Math.min(this.initialBackoffMs*2**n,this.maxBackoffMs);return s>=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,s=r?.requiresImages,i=r?.requiresAudio,a=this.services,u=e.model;if((n||s||i)&&(a=this.services.filter(p=>{let d=p.getFeatures(u);return!(n&&!d.structuredOutputs||s&&!d.media.images.supported||i&&!d.media.audio.supported)}),a.length===0)){let p=[];throw n&&p.push("structured outputs"),s&&p.push("images"),i&&p.push("audio"),new Error(`No services available that support required capabilities: ${p.join(", ")}.`)}let c=0,l=a[c];if(!l)throw new Error("No matching AI services available for request.");for(this.currentService=l;;){if(!this.canRetryService(l)){let p=this.getNextService(a,c);if(!p.service)throw new Error(`All candidate services exhausted (tried ${a.length} service(s))`);l=p.service,c=p.index,this.currentService=l;continue}try{let p=await l.chat(e,t);return this.handleSuccess(l),p}catch(p){if(!(p instanceof et))throw p;switch(p.constructor){case Ut:throw p;case rt:{if(![408,429,500,502,503,504].includes(p.status))throw p;break}case Je:break;case Dt:break;case ht:break;case gt:break;default:throw p}if(this.handleFailure(l,p),(this.serviceFailures.get(l.getId())?.retries??0)>=this.maxRetries){let m=this.getNextService(a,c);if(this.debug&&console.warn(`AxBalancer: Switching to service ${m.service?.getName()??"none"}`,p),!m.service)throw p;l=m.service,c=m.index,this.currentService=l}}}}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 et)||r instanceof rt&&![408,429,500,502,503,504].includes(r.status)||r instanceof Ut)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 fm(o){let e=o.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<o.length;r++){let s=o[r];if(!s)throw new Error(`Service at index ${r} is undefined`);let i=s.getModelList();if(!i)throw new Error(`Service at index ${r} (${s.getName()}) has no model list while another service does.`);let a=new Set(i.map(u=>u.key));for(let u of n)if(!a.has(u))throw new Error(`Service at index ${r} (${s.getName()}) is missing model "${u}"`);for(let u of a)if(!n.has(u))throw new Error(`Service at index ${r} (${s.getName()}) has extra model "${u}"`)}}function on(o){let e=!1,t=!1,n=!1,r=!1,s=!1,i=!1,a=!1,u=new Set,c=0;if(o.chatPrompt&&Array.isArray(o.chatPrompt))for(let l of o.chatPrompt){if(l.role==="user"&&Array.isArray(l.content))for(let p of l.content)switch(u.add(p.type),p.type){case"image":e=!0,p.cache&&(a=!0),c+=85;break;case"audio":t=!0,p.cache&&(a=!0),c+=p.duration||60;break;case"file":n=!0,p.cache&&(a=!0),c+=Math.ceil((p.extractedText?.length||1e3)/4);break;case"url":r=!0,p.cache&&(a=!0),c+=Math.ceil((p.cachedContent?.length||2e3)/4);break;case"text":p.cache&&(a=!0),c+=Math.ceil(p.text.length/4);break}else"content"in l&&typeof l.content=="string"&&(c+=Math.ceil(l.content.length/4));"cache"in l&&l.cache&&(a=!0)}return o.functions&&o.functions.length>0&&(s=!0),o.modelConfig?.stream===!0&&(i=!0),o.capabilities&&(o.capabilities.requiresImages&&(e=!0),o.capabilities.requiresAudio&&(t=!0),o.capabilities.requiresFiles&&(n=!0),o.capabilities.requiresWebSearch&&(r=!0)),{hasImages:e,hasAudio:t,hasFiles:n,hasUrls:r,requiresFunctions:s,requiresStreaming:i,requiresCaching:a,contentTypes:u,estimatedTokens:c}}function Ni(o,e){let t=o.getFeatures(),n=[],r=[],s=[];if(e.hasImages&&!t.media.images.supported&&(n.push("Image support"),s.push("Use altText for images or imageToText service")),e.hasAudio&&!t.media.audio.supported&&(n.push("Audio support"),s.push("Pre-transcribe audio or use transcription field")),e.hasFiles&&!t.media.files.supported&&(n.push("File support"),s.push("Pre-extract text content or use extractedText field")),e.hasUrls&&!t.media.urls.supported&&(n.push("URL/Web search support"),s.push("Pre-fetch content or use cachedContent field")),e.requiresFunctions&&!t.functions&&n.push("Function calling"),e.requiresStreaming&&!t.streaming&&(n.push("Streaming responses"),s.push("Use non-streaming mode")),e.requiresCaching&&!t.caching.supported&&(n.push("Content caching"),s.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:s}}function Uo(o,e){return o.map(t=>{let n=t.getFeatures(),r=Ni(t,e),s=0,i=[];return s+=10,e.hasImages&&n.media.images.supported&&(s+=25,i.push("Images"),n.media.images.detailLevels?.includes("high")&&(s+=5),n.media.images.maxSize&&n.media.images.maxSize>10*1024*1024&&(s+=3)),e.hasAudio&&n.media.audio.supported&&(s+=25,i.push("Audio"),n.media.audio.maxDuration&&n.media.audio.maxDuration>600&&(s+=5)),e.hasFiles&&n.media.files.supported&&(s+=25,i.push("Files"),n.media.files.uploadMethod==="cloud"&&(s+=3)),e.hasUrls&&n.media.urls.supported&&(s+=25,i.push("URLs"),n.media.urls.webSearch&&(s+=5)),e.requiresFunctions&&n.functions&&(s+=15,i.push("Functions"),n.functionCot&&(s+=3)),e.requiresStreaming&&n.streaming&&(s+=10,i.push("Streaming")),e.requiresCaching&&n.caching.supported&&(s+=8,i.push("Caching"),n.caching.types.includes("persistent")&&(s+=3)),n.thinking&&(s+=2),n.multiTurn&&(s+=2),n.hasThinkingBudget&&(s+=1),n.hasShowThoughts&&(s+=1),s-=r.missingCapabilities.length*10,{provider:t,score:s,missingCapabilities:r.missingCapabilities,supportedCapabilities:i}}).sort((t,n)=>n.score-t.score)}function Go(o,e,t={}){if(e.length===0)throw new Error("No providers available");let n=on(o),r=Uo(e,n);if(t.requireExactMatch){let s=r.filter(i=>i.missingCapabilities.length===0);if(s.length===0)throw new Error(`No providers fully support the request requirements: ${r[0]?.missingCapabilities.join(", ")||"unknown requirements"}`);return s[0].provider}if(!t.allowDegradation){let s=r[0];if(s.missingCapabilities.length>0)throw new Error(`Best available provider (${s.provider.getName()}) is missing: ${s.missingCapabilities.join(", ")}`)}return r[0].provider}function Rc(o,e){let t=on(o),n=Uo(e,t),r=n[0]?.provider||null,s=[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}/${s} requirements (${Math.round(i/Math.max(s,1)*100)}% compatibility)`:"No suitable providers found";return{requirements:t,providerScores:n,recommendedProvider:r,summary:a}}function vc(o,e){return o.filter(t=>t.getFeatures().media[e].supported)}function Sc(o,e){let t={};for(let n of o){let s=n.getFeatures().media[e];if(s.supported)for(let i of s.formats)t[i]||(t[i]=[]),t[i].push(n)}return t}var Or=(r=>(r.CommandRPlus="command-r-plus",r.CommandR="command-r",r.Command="command",r.CommandLight="command-light",r))(Or||{}),Er=(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))(Er||{});var Bo=[{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 hm(o){if(Array.isArray(o)){let t=["string","number","integer","boolean","object","array"].find(n=>o.includes(n));return t||(o.find(n=>n!=="null")??o[0]??"string")}return typeof o=="string"?o:"string"}var $i=()=>structuredClone({model:"command-r-plus",embedModel:"embed-english-v3.0",...Se()}),Oc=()=>structuredClone({model:"command-r",embedModel:"embed-english-v3.0",...He()}),Li=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),s;n&&n.role==="user"&&typeof n.content=="string"&&(s=n?.content);let i=xm(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:hm(g.type),required:p.parameters.required?.includes(m)??!1};return{name:p.name,description:p.description,parameter_definitions:d}}),u=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??""}]}}),c={name:"/chat"},l={message:s,model:t,tools:a,...u&&!s?{tool_results:u}:{},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[c,l]}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(s=>({id:s.name,type:"function",function:{name:s.name,params:s.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),s=r[0];if(!s)throw new Error("No result");return s.id=n.generation_id??"",{results:r}};createEmbedResp(e){return{remoteId:e.id,embeddings:e.embeddings}}},vn=class extends Be{constructor({apiKey:e,config:t,options:n,models:r}){if(!e||e==="")throw new Error("Cohere API key not set");let s={...$i(),...t},i=new Li(s),a=r?.map(u=>{let c=u,l=c?.config;if(!l)return u;let p={};l.maxTokens!==void 0&&(p.maxTokens=l.maxTokens),l.temperature!==void 0&&(p.temperature=l.temperature),l.topP!==void 0&&(p.topP=l.topP),l.topK!==void 0&&(p.topK=l.topK),l.presencePenalty!==void 0&&(p.presencePenalty=l.presencePenalty),l.frequencyPenalty!==void 0&&(p.frequencyPenalty=l.frequencyPenalty),l.stopSequences!==void 0&&(p.stopSequences=l.stopSequences),l.endSequences!==void 0&&(p.endSequences=l.endSequences),l.stream!==void 0&&(p.stream=l.stream),l.n!==void 0&&(p.n=l.n);let d={...c};return Object.keys(p).length>0&&(d.modelConfig={...c.modelConfig??{},...p}),d});super(i,{name:"Cohere",apiURL:"https://api.cohere.ai/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:Bo,defaults:{model:s.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 xm(o){return o.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=kc(e.functionCalls);return{role:"CHATBOT",message:t,tool_calls:n}}case"function":{let n=o.map(i=>{if(i.role==="assistant")return i.functionCalls?.find(a=>a.id===e.functionId)}).filter(i=>i!==void 0),r=kc(n)?.at(0);if(!r)throw new Error("Function call not found");let s=[{result:e.result}];return{role:"TOOL",tool_results:[{call:r,outputs:s}]}}default:throw new Error("Unknown role")}})}function kc(o){return o?.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 Mr=(n=>(n.DeepSeekChat="deepseek-chat",n.DeepSeekCoder="deepseek-coder",n.DeepSeekReasoner="deepseek-reasoner",n))(Mr||{});var jo=[{name:"deepseek-chat",currency:"USD",promptTokenCostPer1M:.27,completionTokenCostPer1M:1.1},{name:"deepseek-reasoner",currency:"USD",promptTokenCostPer1M:.55,completionTokenCostPer1M:2.19}];var Di=()=>structuredClone({model:"deepseek-chat",...Se()}),Ec=()=>structuredClone({model:"deepseek-coder",...He()}),Sn=class extends Ge{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:s}){if(!e||e==="")throw new Error("DeepSeek API key not set");let i={...Di(),...t};s=[...jo,...s??[]],super({apiKey:e,config:i,options:n,apiURL:"https://api.deepseek.com",modelInfo:s,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 Pr=(T=>(T.Gemini31Pro="gemini-3.1-pro-preview",T.Gemini3FlashLite="gemini-3.1-flash-lite-preview",T.Gemini3Flash="gemini-3-flash-preview",T.Gemini3Pro="gemini-3.1-pro-preview",T.Gemini3ProImage="gemini-3-pro-image-preview",T.Gemini25Pro="gemini-2.5-pro",T.Gemini25Flash="gemini-2.5-flash",T.Gemini25FlashLite="gemini-2.5-flash-lite",T.Gemini20Flash="gemini-2.0-flash",T.Gemini20FlashLite="gemini-2.0-flash-lite",T.Gemini20ProExp="gemini-2.0-pro-exp-02-05",T.Gemini20FlashThinkingExp="gemini-2.0-flash-thinking-exp-01-21",T.Gemini1Pro="gemini-1.0-pro",T.Gemini15Flash="gemini-1.5-flash",T.Gemini15Flash002="gemini-1.5-flash-002",T.Gemini15Flash8B="gemini-1.5-flash-8b",T.Gemini15Pro="gemini-1.5-pro",T.GeminiFlashLatest="gemini-flash-latest",T.GeminiFlashLiteLatest="gemini-flash-lite-latest",T.GeminiProLatest="gemini-pro-latest",T))(Pr||{}),zo=(s=>(s.GeminiEmbedding001="gemini-embedding-001",s.GeminiEmbedding="gemini-embedding-exp",s.TextEmbeddingLarge="text-embedding-large-exp-03-07",s.TextEmbedding004="text-embedding-004",s.TextEmbedding005="text-embedding-005",s))(zo||{}),qo=(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))(qo||{}),Ho=(s=>(s.BlockNone="BLOCK_NONE",s.BlockOnlyHigh="BLOCK_ONLY_HIGH",s.BlockMediumAndAbove="BLOCK_MEDIUM_AND_ABOVE",s.BlockLowAndAbove="BLOCK_LOW_AND_ABOVE",s.BlockDefault="HARM_BLOCK_THRESHOLD_UNSPECIFIED",s))(Ho||{}),Ui=(u=>(u.SemanticSimilarity="SEMANTIC_SIMILARITY",u.Classification="CLASSIFICATION",u.Clustering="CLUSTERING",u.RetrievalDocument="RETRIEVAL_DOCUMENT",u.RetrievalQuery="RETRIEVAL_QUERY",u.QuestionAnswering="QUESTION_ANSWERING",u.FactVerification="FACT_VERIFICATION",u.CodeRetrievalQuery="CODE_RETRIEVAL_QUERY",u))(Ui||{}),Mc=["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 sn=o=>o.includes("gemini-3"),Pc=o=>o.includes("gemini-3")&&o.includes("pro"),Ko=o=>{if(!o||typeof o!="object")return o;let e={...o};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,Ko(n)]))),e.items&&(e.items=Ko(e.items)),e},Fc=[{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:Fc,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},thinkingLevelMapping:{minimal:"minimal",low:"low",medium:"medium",high:"high",highest:"high"},...Se()}),_c=()=>structuredClone({model:"gemini-2.0-flash",embedModel:"text-embedding-005",safetySettings:Fc,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},thinkingLevelMapping:{minimal:"minimal",low:"low",medium:"medium",high:"high",highest:"high"},...He()}),Gi=class{constructor(e,t,n,r,s){this.config=e;this.isVertex=t;this.endpointId=n;this.apiKey=r;this.options=s;if(!this.isVertex&&this.config.autoTruncate)throw new Error("Auto truncate is not supported for GoogleGemini");let i=this.config.model;if(sn(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(Pc(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 s;if(this.endpointId?s={name:r?`/${this.endpointId}:streamGenerateContent?alt=sse`:`/${this.endpointId}:generateContent`}:s={name:r?`/models/${n}:streamGenerateContent?alt=sse`:`/models/${n}:generateContent`},!this.isVertex){let h=r?"&":"?",y=typeof this.apiKey=="function"?await this.apiKey():this.apiKey;s.name+=`${h}key=${y}`}let i=e.chatPrompt.filter(h=>h.role==="system").map(h=>h.content),a=i.length>0?{role:"user",parts:[{text:i.join(" ")}]}:void 0,u=[],c=e.chatPrompt.filter(h=>h.role!=="system");for(let h=0;h<c.length;h++){let y=c[h];switch(y.role){case"user":{let T=Array.isArray(y.content)?y.content.map((C,R)=>{switch(C.type){case"text":return{text:C.text};case"image":return{inlineData:{mimeType:C.mimeType,data:C.image}};case"audio":return{inlineData:{mimeType:`audio/${C.format??"mp3"}`,data:C.data}};case"file":return"fileUri"in C?{fileData:{mimeType:C.mimeType,fileUri:C.fileUri}}:{inlineData:{mimeType:C.mimeType,data:C.data}};default:throw new Error(`Chat prompt content type not supported (index: ${R})`)}}):[{text:y.content}];u.push({role:"user",parts:T});break}case"assistant":{let T=[],C=y.thoughtBlocks,R=y.functionCalls&&y.functionCalls.length>0,M=C?.[0],I=C?.map(E=>E.data).join("")??"",O=M?.signature;if(I&&T.push({...R?{}:{thought:!0},text:I,...O&&!R?{thought_signature:O}:{}}),y.functionCalls){let E=y.functionCalls.map(($,N)=>{let S;if(typeof $.function.params=="string"){let F=$.function.params;if(F.trim().length===0)S={};else try{S=JSON.parse(F)}catch{throw new Error(`Failed to parse function params JSON: ${F}`)}}else S=$.function.params;let v={functionCall:{name:$.function.name,args:S}};return O&&N===0&&(v.thought_signature=O),v});T.push(...E)}if(y.content&&T.push({text:y.content}),T.length===0)throw new Error("Assistant content is empty");u.push({role:"model",parts:T});break}case"function":{let T=[],C=y,R=h;for(;;){if(!("functionId"in C))throw new Error(`Chat prompt functionId is empty (index: ${R})`);if(T.push({functionResponse:{name:C.functionId,response:{result:C.result}}}),R+1<c.length&&c[R+1].role==="function")R++,C=c[R];else break}h=R,u.push({role:"user",parts:T});break}default:throw new Error(`Invalid role: ${JSON.stringify(y)} (index: ${h})`)}}let l=[];if(e.functions&&e.functions.length>0){let h=e.functions.map(y=>{let T={type:"object",properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]},C=y.parameters?Ko(y.parameters):void 0;return C===void 0||C&&typeof C=="object"&&Object.keys(C).length===0?C={...T}:C&&typeof C=="object"&&C.type==="object"&&(!("properties"in C)||!C.properties||Object.keys(C.properties).length===0)&&(C={...C,properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]}),{name:y.name,description:y.description,parameters:C}});l.push({function_declarations:h})}if(this.options?.codeExecution&&l.push({code_execution:{}}),this.options?.googleSearchRetrieval&&l.push({google_search_retrieval:{dynamic_retrieval_config:this.options.googleSearchRetrieval}}),this.options?.googleSearch&&l.push({google_search:{}}),this.options?.googleMaps){let h=this.options.googleMaps,y=h?.enableWidget!==void 0?{enableWidget:h.enableWidget}:{};l.push({google_maps:y})}this.options?.urlContext&&l.push({url_context:{}}),l.length===0&&(l=void 0);let p,d=Array.isArray(l)?l.some(h=>h&&Array.isArray(h.function_declarations)&&h.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 h=e.functionCall.function?.name?{allowedFunctionNames:[e.functionCall.function.name]}:{};p={function_calling_config:{mode:"ANY"},...h}}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&&sn(n)&&(m.thinkingLevel=this.config.thinking.thinkingLevel),t?.thinkingTokenBudget){let h=this.getEffectiveMappings(n),y=h.thinkingTokenBudgetLevels;if(sn(n)){let C=Pc(n),R=h.thinkingLevelMapping;if(t.thinkingTokenBudget==="none")m.thinkingLevel=R?.minimal??"minimal";else{let M=t.thinkingTokenBudget,I=R?.[M];I||(I=M==="highest"?"high":M),m.thinkingLevel=I}if(C&&m.thinkingLevel){let M=m.thinkingLevel;M!=="low"&&M!=="high"&&(m.thinkingLevel=M==="minimal"?"low":"high")}}else switch(t.thinkingTokenBudget){case"none":m.thinkingBudget=0,m.includeThoughts=!1,delete m.thinkingLevel;break;case"minimal":m.thinkingBudget=y?.minimal??200;break;case"low":m.thinkingBudget=y?.low??800;break;case"medium":m.thinkingBudget=y?.medium??5e3;break;case"high":m.thinkingBudget=y?.high??1e4;break;case"highest":m.thinkingBudget=y?.highest??24500;break}}m.thinkingLevel&&delete m.thinkingBudget,sn(n)||delete m.thinkingLevel,sn(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(sn(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 h=e.responseFormat.schema.schema||e.responseFormat.schema;f.responseSchema=Ko(h)}}else this.config.responseFormat&&this.config.responseFormat==="json_object"&&(f.responseMimeType="application/json");let x=this.config.safetySettings;return[s,{contents:u,tools:l,toolConfig:p,systemInstruction:a,generationConfig:f,safetySettings:x}]};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(s=>({content:s,...this.config.embedType&&{taskType:this.config.embedType}})),parameters:{autoTruncate:this.config.autoTruncate,outputDimensionality:this.config.dimensions}};else{let s=typeof this.apiKey=="function"?this.apiKey():this.apiKey;n={name:`/models/${t}:batchEmbedContents?key=${s}`},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(s=>{let i={index:0};switch(s.finishReason){case"MAX_TOKENS":i.finishReason="length";break;case"STOP":i.finishReason="stop";break;case"SAFETY":throw new Le("Content was blocked due to safety settings",void 0,void 0);case"RECITATION":throw new Le("Content was blocked due to recitation policy",void 0,void 0);case"MALFORMED_FUNCTION_CALL":throw new Le("Function call was malformed and blocked",void 0,void 0);case"UNEXPECTED_TOOL_CALL":throw new Le("Unexpected tool call",void 0,void 0);case"FINISH_REASON_UNSPECIFIED":throw new Le("Finish reason unspecified",void 0,void 0);case"BLOCKLIST":throw new Le("Content was blocked due to blocklist",void 0,void 0);case"PROHIBITED_CONTENT":throw new Le("Content was blocked due to prohibited content",void 0,void 0);case"SPII":throw new Le("Content was blocked due to SPII",void 0,void 0);case"OTHER":throw new Le("Other finish reason",void 0,void 0)}if(!s.content||!s.content.parts)return i;for(let c of s.content.parts){if("text"in c){if("thought"in c&&c.thought||c.thought===!0){i.thought=c.text;let l=c.thoughtSignature||c.thought_signature;i.thoughtBlocks||(i.thoughtBlocks=[]),i.thoughtBlocks.push({data:c.text,encrypted:!1,...l?{signature:l}:{}})}else i.content=c.text;continue}if("functionCall"in c){let l=c.thoughtSignature||c.thought_signature;if(l)if(!i.thoughtBlocks||i.thoughtBlocks.length===0)i.thoughtBlocks=[{data:"",encrypted:!1,signature:l}];else{let p=i.thoughtBlocks[i.thoughtBlocks.length-1];p&&!p.signature&&(p.signature=l)}i.functionCalls=[...i.functionCalls??[],{id:Ze(),type:"function",function:{name:c.functionCall.name,params:c.functionCall.args}}]}}let a=s.citationMetadata?.citations;if(Array.isArray(a)&&a.length){let c=l=>l?`${l.year}-${String(l.month).padStart(2,"0")}-${String(l.day).padStart(2,"0")}`:void 0;i.citations=a.filter(l=>typeof l?.uri=="string").map(l=>({url:l.uri,title:l.title,license:l.license,publicationDate:c(l.publicationDate)}))}let u=s.groundingMetadata;if(u){if(Array.isArray(u.groundingChunks)){let c=u.groundingChunks.map(l=>l?.maps).filter(l=>l&&typeof l.uri=="string").map(l=>({url:l.uri,title:l.title}));c.length&&(i.citations=[...i.citations??[],...c])}typeof u.googleMapsWidgetContextToken=="string"&&(t=u.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 Mc.some(n=>t.includes(n)||n.includes(t))};buildCacheCreateOp=(e,t)=>{let n=e.model,r=t.contextCache?.ttlSeconds??3600,{systemInstruction:s,contents:i}=this.extractCacheableContent(e.chatPrompt);if(!s&&(!i||i.length===0))return;let a={model:this.isVertex?n:`models/${n}`,ttl:`${r}s`,displayName:`ax-cache-${Date.now()}`};s&&(a.systemInstruction=s),i&&i.length>0&&(a.contents=i);let u;if(this.isVertex)u="/cachedContents";else{u="/cachedContents";let c=typeof this.apiKey=="function"?"ASYNC_KEY":this.apiKey;u+=`?key=${c}`}return{type:"create",apiConfig:{name:u},request:a,parseResponse:c=>{let l=c;if(l?.name)return{name:l.name,expiresAt:l.expireTime,tokenCount:l.usageMetadata?.totalTokenCount}}}};buildCacheUpdateTTLOp=(e,t)=>{let n={ttl:`${t}s`},r=`/${e}`;if(!this.isVertex&&this.apiKey){let s=typeof this.apiKey=="function"?"ASYNC_KEY":this.apiKey;r+=`?key=${s}`}return{type:"update",apiConfig:{name:r,headers:{"Content-Type":"application/json"}},request:n,parseResponse:s=>{let i=s;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,s=e.modelConfig?.stream??this.config.stream,{dynamicContents:i,dynamicSystemInstruction:a}=this.extractDynamicContent(e.chatPrompt),u;if(this.endpointId?u={name:s?`/${this.endpointId}:streamGenerateContent?alt=sse`:`/${this.endpointId}:generateContent`}:u={name:s?`/models/${r}:streamGenerateContent?alt=sse`:`/models/${r}:generateContent`},!this.isVertex){let d=s?"&":"?",m=typeof this.apiKey=="function"?await this.apiKey():this.apiKey;u.name+=`${d}key=${m}`}let c={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"};sn(r)&&(c.temperature===void 0||c.temperature<1)&&(c.temperature=1);let l=this.config.safetySettings,p={contents:i,cachedContent:n,generationConfig:c,safetySettings:l};return a&&(p.systemInstruction=a),{apiConfig:u,request:p}};extractCacheableContent(e){let t,n=[],r=-1;for(let s=e.length-1;s>=0;s--){let i=e[s];if("cache"in i&&i.cache){r=s;break}}for(let s=0;s<e.length;s++){let i=e[s];if(i.role==="system"){t={role:"user",parts:[{text:i.content}]};continue}if(r>=0&&s<=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 u of i.content)switch(u.type){case"text":a.push({text:u.text});break;case"image":a.push({inlineData:{mimeType:u.mimeType,data:u.image}});break;case"audio":a.push({inlineData:{mimeType:`audio/${u.format??"mp3"}`,data:u.data}});break;case"file":"fileUri"in u?a.push({fileData:{mimeType:u.mimeType,fileUri:u.fileUri}}):a.push({inlineData:{mimeType:u.mimeType,data:u.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 s=[];if(typeof r.content=="string")s.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":s.push({text:i.text});break;case"image":s.push({inlineData:{mimeType:i.mimeType,data:i.image}});break;case"audio":s.push({inlineData:{mimeType:`audio/${i.format??"mp3"}`,data:i.data}});break;case"file":"fileUri"in i?s.push({fileData:{mimeType:i.mimeType,fileUri:i.fileUri}}):s.push({inlineData:{mimeType:i.mimeType,data:i.data}});break}}s.length>0&&n.push({role:"user",parts:s})}else if(r.role==="assistant"){let s=[];if(r.content&&s.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??{};s.push({functionCall:{name:i.function.name,args:a}})}s.length>0&&n.push({role:"model",parts:s})}else r.role==="function"&&n.push({role:"user",parts:[{functionResponse:{name:r.functionId,response:{result:r.result}}}]});return{dynamicContents:n,dynamicSystemInstruction:void 0}}},kn=class o extends Be{static create(e){return new o(e)}constructor({apiKey:e,projectId:t,region:n,endpointId:r,config:s,options:i,models:a,modelInfo:u}){let c=t!==void 0&&n!==void 0,l,p;if(c){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 x;r?x="endpoints":x="publishers/google",l=`https://${n==="global"?"aiplatform":`${n}-aiplatform`}.googleapis.com/v1/projects/${t}/locations/${n}/${x}`,p=async()=>({Authorization:`Bearer ${typeof e=="function"?await e():e}`})}else{if(!e)throw new Error("GoogleGemini AI API key not set");l="https://generativelanguage.googleapis.com/v1beta",p=async()=>({})}let d={...Bi(),...s},m=new Gi(d,c,r,e,i);u=[...Wo,...u??[]];let g=x=>{let A=ft({model:x,modelInfo:u,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(x),types:["persistent"]},thinking:A?.supported?.thinkingBudget??!1,multiTurn:!0}},f=a?.map(x=>{let A=x,h=A?.config;if(!h)return x;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 T={...A};Object.keys(y).length>0&&(T.modelConfig={...A.modelConfig??{},...y});let C=h.thinking?.thinkingTokenBudget;if(typeof C=="number"){let R=d.thinkingTokenBudgetLevels,M=[["minimal",R?.minimal??200],["low",R?.low??800],["medium",R?.medium??5e3],["high",R?.high??1e4],["highest",R?.highest??24500]],I="minimal",O=Number.POSITIVE_INFINITY;for(let[E,$]of M){let N=Math.abs(C-$);N<O&&(O=N,I=E)}T.thinkingTokenBudget=I}return h.thinking?.includeThoughts!==void 0&&(T.showThoughts=!!h.thinking.includeThoughts),h.thinkingLevelMapping&&(T.thinkingLevelMapping=h.thinkingLevelMapping),h.thinkingTokenBudgetLevels&&(T.thinkingTokenBudgetLevels=h.thinkingTokenBudgetLevels),T});f?m.setModels(f):a&&m.setModels(a),super(m,{name:"GoogleGeminiAI",apiURL:l,headers:p,modelInfo:u,defaults:{model:d.model,embedModel:d.embedModel},options:i,supportFor:g,models:f??a})}};var Am=new st,On=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(Am.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 Fr=(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))(Fr||{});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 ym=()=>structuredClone({model:"llama-3.3-70b-versatile",...Se()}),En=class extends Ge{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:s}){if(!e||e==="")throw new Error("Groq API key not set");let i={...ym(),...t},a={...n,streamingUsage:!1};s=[...Vo,...s??[]];let 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};super({apiKey:e,config:i,options:a,modelInfo:s,apiURL:"https://api.groq.com/openai/v1",models:r,supportFor:u}),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 On(t,t/60,{debug:e?.debug});return async(s,i)=>{let a=i.modelUsage?.tokens?.totalTokens||0;return await n.acquire(a),await s()}}};var Jo=[];var Qo=(e=>(e.MetaLlama270BChatHF="meta-llama/Llama-2-70b-chat-hf",e))(Qo||{});var zi=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...Se()}),Nc=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...He()}),ji=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)}o(r)}};var be={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"},vt={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"},Ii=(r=>(r.COMPLETION="completion",r.CHAT="chat",r.RERANK="rerank",r.UNKNOWN="unknown",r))(Ii||{}),Ti=(s=>(s.WORKFLOW="workflow",s.TASK="task",s.AGENT="agent",s.TOOL="tool",s.UNKNOWN="unknown",s))(Ti||{});var wi=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()}},ko=class extends TransformStream{constructor(e,t){super(new wi(e,t))}};function Oo(o,e){for(let t of e){let n=o.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)):o.push(t)}}var Vu=(o,e,t,n)=>{let r=n?o.filter(i=>i.role!=="system"):[...o];t({name:"ChatRequestChatPrompt",step:e,value:r})};var Wu=(o,e)=>{if(!o.results)return;let t={name:"ChatResponseResults",value:o.results};e(t)};function Ju(o,e){let t=new Map;for(let n of o)for(let r of n.results){if(!r)continue;let s=t.get(r.index);s?(r.content&&(s.content=(s.content??"")+r.content),r.thought&&(s.thought=(s.thought??"")+r.thought),r.finishReason&&(s.finishReason=r.finishReason),r.functionCalls&&(s.functionCalls?Oo(s.functionCalls,structuredClone(r.functionCalls)):s.functionCalls=structuredClone(r.functionCalls))):(s=structuredClone(r),t.set(r.index,s))}for(let n of t.values()){let r={name:"ChatResponseStreamingDoneResult",index:n.index,value:n};e(r)}}var Qu=(o,e)=>{e({name:"FunctionResults",value:o})},Ri=(o,e,t,n)=>{n({name:"FunctionError",index:e,fixingInstructions:t,error:o})},Yu=(o,e,t,n)=>{n({name:"ValidationError",index:e,fixingInstructions:t,error:o})},Xu=(o,e,t,n)=>{n({name:"AssertionError",index:e,fixingInstructions:t,error:o})},Zu=(o,e,t)=>{t({name:"RefusalError",index:e,error:o})};var ec=(o,e,t)=>{t({name:"EmbedRequest",embedModel:e,value:o})},tc=(o,e)=>{let t=o.slice(0,3).map(r=>({length:r.length,sample:r.slice(0,5),truncated:r.length>5})),n={name:"EmbedResponse",totalEmbeddings:o.length,value:t};e(n)},nc=(o,e,t,n)=>{n({name:"ResultPickerUsed",sampleCount:o,selectedIndex:e,latency:t})};var Mo=o=>{let e={};for(let[t,n]of Object.entries(o))if(n!=null){let r=String(n);e[t]=r.length>100?r.substring(0,100):r}return e},rn=(...o)=>{let e={};for(let t of o)t&&Object.assign(e,t);return e},Eo,rc=o=>{if(Eo)return Eo;if(o)return Eo=im(o),Eo};var im=o=>({latencyHistogram:o.createHistogram("ax_llm_request_duration_ms",{description:"Duration of LLM requests in milliseconds",unit:"ms"}),errorCounter:o.createCounter("ax_llm_errors_total",{description:"Total number of LLM request errors"}),requestCounter:o.createCounter("ax_llm_requests_total",{description:"Total number of LLM requests"}),tokenCounter:o.createCounter("ax_llm_tokens_total",{description:"Total number of LLM tokens consumed"}),inputTokenCounter:o.createCounter("ax_llm_input_tokens_total",{description:"Total number of input/prompt tokens consumed"}),outputTokenCounter:o.createCounter("ax_llm_output_tokens_total",{description:"Total number of output/completion tokens generated"}),errorRateGauge:o.createGauge("ax_llm_error_rate",{description:"Current error rate as a percentage (0-100)"}),meanLatencyGauge:o.createGauge("ax_llm_mean_latency_ms",{description:"Mean latency of LLM requests in milliseconds",unit:"ms"}),p95LatencyGauge:o.createGauge("ax_llm_p95_latency_ms",{description:"95th percentile latency of LLM requests in milliseconds",unit:"ms"}),p99LatencyGauge:o.createGauge("ax_llm_p99_latency_ms",{description:"99th percentile latency of LLM requests in milliseconds",unit:"ms"}),streamingRequestsCounter:o.createCounter("ax_llm_streaming_requests_total",{description:"Total number of streaming LLM requests"}),functionCallsCounter:o.createCounter("ax_llm_function_calls_total",{description:"Total number of function/tool calls made"}),functionCallLatencyHistogram:o.createHistogram("ax_llm_function_call_latency_ms",{description:"Latency of function calls in milliseconds",unit:"ms"}),requestSizeHistogram:o.createHistogram("ax_llm_request_size_bytes",{description:"Size of LLM request payloads in bytes",unit:"By"}),responseSizeHistogram:o.createHistogram("ax_llm_response_size_bytes",{description:"Size of LLM response payloads in bytes",unit:"By"}),temperatureGauge:o.createGauge("ax_llm_temperature_gauge",{description:"Temperature setting used for LLM requests"}),maxTokensGauge:o.createGauge("ax_llm_max_tokens_gauge",{description:"Maximum tokens setting used for LLM requests"}),estimatedCostCounter:o.createCounter("ax_llm_estimated_cost_total",{description:"Estimated cost of LLM requests in USD",unit:"$"}),promptLengthHistogram:o.createHistogram("ax_llm_prompt_length_chars",{description:"Length of prompts in characters"}),contextWindowUsageGauge:o.createGauge("ax_llm_context_window_usage_ratio",{description:"Context window utilization ratio (0-1)"}),timeoutsCounter:o.createCounter("ax_llm_timeouts_total",{description:"Total number of timed out LLM requests"}),abortsCounter:o.createCounter("ax_llm_aborts_total",{description:"Total number of aborted LLM requests"}),thinkingBudgetUsageCounter:o.createCounter("ax_llm_thinking_budget_usage_total",{description:"Total thinking budget tokens used"}),multimodalRequestsCounter:o.createCounter("ax_llm_multimodal_requests_total",{description:"Total number of multimodal requests (with images/audio)"}),cacheReadTokensCounter:o.createCounter("ax_llm_cache_read_tokens_total",{description:"Total number of tokens read from cache (prompt caching)"}),cacheWriteTokensCounter:o.createCounter("ax_llm_cache_write_tokens_total",{description:"Total number of tokens written to cache (prompt caching)"})}),oc=(o,e,t,n,r,s)=>{try{if(o.latencyHistogram){let i=Mo({operation:e,ai_service:n,...r?{model:r}:{},...s});o.latencyHistogram.record(t,i)}}catch(i){console.warn("Failed to record latency metric:",i)}},sc=(o,e,t,n,r,s,i,a)=>{let u={operation:e,ai_service:s,...i?{model:i}:{},...a};o.meanLatencyGauge&&o.meanLatencyGauge.record(t,u),o.p95LatencyGauge&&o.p95LatencyGauge.record(n,u),o.p99LatencyGauge&&o.p99LatencyGauge.record(r,u)},ic=(o,e,t,n,r)=>{try{if(o.errorCounter){let s=Mo({operation:e,ai_service:t,...n?{model:n}:{},...r});o.errorCounter.add(1,s)}}catch(s){console.warn("Failed to record error metric:",s)}},ac=(o,e,t,n,r,s)=>{o.errorRateGauge&&o.errorRateGauge.record(t*100,{operation:e,ai_service:n,...r?{model:r}:{},...s})},uc=(o,e,t,n,r)=>{o.requestCounter&&o.requestCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{},...r})},Rr=(o,e,t,n,r,s)=>{try{let i=Mo({ai_service:n,...r?{model:r}:{},...s});o.tokenCounter&&o.tokenCounter.add(t,{token_type:e,...i}),e==="input"&&o.inputTokenCounter&&o.inputTokenCounter.add(t,i),e==="output"&&o.outputTokenCounter&&o.outputTokenCounter.add(t,i)}catch(i){console.warn("Failed to record token metric:",i)}},cc=(o,e,t,n,r,s)=>{t&&o.streamingRequestsCounter&&o.streamingRequestsCounter.add(1,{operation:e,ai_service:n,...r?{model:r}:{},...s})},lc=(o,e,t,n,r,s)=>{let i={function_name:e,...n?{ai_service:n}:{},...r?{model:r}:{},...s};o.functionCallsCounter&&o.functionCallsCounter.add(1,i),t&&o.functionCallLatencyHistogram&&o.functionCallLatencyHistogram.record(t,i)},vi=(o,e,t,n,r,s)=>{o.requestSizeHistogram&&o.requestSizeHistogram.record(t,{operation:e,ai_service:n,...r?{model:r}:{},...s})},Si=(o,e,t,n,r,s)=>{o.responseSizeHistogram&&o.responseSizeHistogram.record(t,{operation:e,ai_service:n,...r?{model:r}:{},...s})},pc=(o,e,t,n,r,s)=>{let i={...n?{ai_service:n}:{},...r?{model:r}:{},...s};e!==void 0&&o.temperatureGauge&&o.temperatureGauge.record(e,i),t!==void 0&&o.maxTokensGauge&&o.maxTokensGauge.record(t,i)},ki=(o,e,t,n,r,s)=>{o.estimatedCostCounter&&o.estimatedCostCounter.add(t,{operation:e,ai_service:n,...r?{model:r}:{},...s})},dc=(o,e,t,n,r)=>{o.promptLengthHistogram&&o.promptLengthHistogram.record(e,{ai_service:t,...n?{model:n}:{},...r})},mc=(o,e,t,n,r)=>{o.contextWindowUsageGauge&&o.contextWindowUsageGauge.record(e,{ai_service:t,...n?{model:n}:{},...r})},gc=(o,e,t,n,r)=>{o.timeoutsCounter&&o.timeoutsCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{},...r})},fc=(o,e,t,n,r)=>{o.abortsCounter&&o.abortsCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{},...r})},hc=(o,e,t,n,r)=>{o.thinkingBudgetUsageCounter&&o.thinkingBudgetUsageCounter.add(e,{ai_service:t,...n?{model:n}:{},...r})},xc=(o,e,t,n,r,s)=>{(e||t)&&o.multimodalRequestsCounter&&o.multimodalRequestsCounter.add(1,{ai_service:n,has_images:e.toString(),has_audio:t.toString(),...r?{model:r}:{},...s})},Oi=(o,e,t,n,r,s)=>{try{if(t<=0)return;let i=Mo({ai_service:n,...r?{model:r}:{},...s});e==="read"&&o.cacheReadTokensCounter&&o.cacheReadTokensCounter.add(t,i),e==="write"&&o.cacheWriteTokensCounter&&o.cacheWriteTokensCounter.add(t,i)}catch(i){console.warn("Failed to record cache token metric:",i)}};function Ac(o){try{return JSON.stringify(o,null,2)}catch{return String(o)}}function St(o,e={}){let t=[o];throw e.fieldPath!==void 0&&t.push(`Field: ${e.fieldPath}`),e.value!==void 0&&t.push(`Value: ${Ac(e.value)}`),e.note&&t.push(`Note: ${e.note}`),e.item!==void 0&&t.push(`Chat item: ${Ac(e.item)}`),new Error(t.join(`
168
+ `))}function Cn(o){let e=n=>JSON.stringify(n,null,2);if(!o)throw new Error(`Chat request message item cannot be null or undefined, received: ${e(o)}`);let t=typeof o=="object"&&o!==null&&"role"in o&&typeof o.role=="string"?o.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 o=="object"&&o!==null&&"content"in o&&typeof o.content=="string"?o.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 o=="object"&&o!==null&&"content"in o?o.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 s=n[r];if(!s||typeof s!="object")throw new Error(`User message content item at index ${r} must be an object, received: ${e(s)}`);let i=typeof s=="object"&&s!==null&&"type"in s&&typeof s.type=="string"?s.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 s&&typeof s.text=="string"?s.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 s&&typeof s.image=="string"?s.image:void 0,u="mimeType"in s&&typeof s.mimeType=="string"?s.mimeType:void 0;if(!a||a.trim()==="")throw new Error(`User message image content at index ${r} cannot be empty, received: ${e(a)}`);if(!u||u.trim()==="")throw new Error(`User message image content at index ${r} must have a mimeType, received: ${e(u)}`);break}case"audio":{let a="data"in s&&typeof s.data=="string"?s.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 s&&typeof s.fileUri=="string",u="data"in s&&typeof s.data=="string";if(!a&&!u)throw new Error(`User message file content at index ${r} must have either 'data' or 'fileUri', received: ${e(s)}`);if(a&&u)throw new Error(`User message file content at index ${r} cannot have both 'data' and 'fileUri', received: ${e(s)}`);if(a){let l=s.fileUri;if(!l||l.trim()==="")throw new Error(`User message file content at index ${r} fileUri cannot be empty, received: ${e(l)}`)}if(u){let l=s.data;if(!l||l.trim()==="")throw new Error(`User message file content at index ${r} data cannot be empty, received: ${e(l)}`)}let c="mimeType"in s&&typeof s.mimeType=="string"?s.mimeType:null;if(!c||c.trim()==="")throw new Error(`User message file content at index ${r} must have a mimeType, received: ${e(c)}`);break}case"url":{let a="url"in s&&typeof s.url=="string"?s.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 o=="object"&&o!==null&&"content"in o?o.content:void 0,r=typeof o=="object"&&o!==null&&"functionCalls"in o?o.functionCalls:void 0,s=typeof o=="object"&&o!==null&&"thoughtBlocks"in o?o.thoughtBlocks:void 0,i=typeof n=="string"&&n.trim()!=="",a=Array.isArray(r)&&r.length>0,u=Array.isArray(s)&&s.length>0;if(!i&&!a&&!u&&St("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:s},item:o}),n!==void 0&&typeof n!="string"&&St("Assistant message content must be a string",{fieldPath:"content",value:n,item:o}),r!==void 0&&!Array.isArray(r)&&St("Assistant message functionCalls must be an array when provided",{fieldPath:"functionCalls",value:r,item:o}),Array.isArray(r))for(let c=0;c<r.length;c++){let l=r[c];if((!l||typeof l!="object")&&St("functionCalls entry must be an object",{fieldPath:`functionCalls[${c}]`,value:l,item:o}),(!("id"in l)||typeof l.id!="string"||l.id.trim()==="")&&St("functionCalls entry must include a non-empty string id",{fieldPath:`functionCalls[${c}].id`,value:l.id,item:o}),(!("type"in l)||l.type!=="function")&&St("functionCalls entry must have type 'function'",{fieldPath:`functionCalls[${c}].type`,value:l.type,item:o}),!("function"in l)||!l.function)St("functionCalls entry must include a function object",{fieldPath:`functionCalls[${c}].function`,value:l.function,item:o});else{let p=l.function;(!("name"in p)||typeof p.name!="string"||p.name.trim()==="")&&St("functionCalls entry must include a non-empty function name",{fieldPath:`functionCalls[${c}].function.name`,value:p?.name,item:o}),p.params!==void 0&&typeof p.params!="string"&&typeof p.params!="object"&&St("functionCalls entry params must be a string or object when provided",{fieldPath:`functionCalls[${c}].function.params`,value:p.params,item:o})}}if(o.name!==void 0){let c=o.name;(typeof c!="string"||c.trim()==="")&&St("Assistant message name must be a non-empty string when provided",{fieldPath:"name",value:c,item:o})}break}case"function":{let n=typeof o=="object"&&o!==null&&"functionId"in o&&typeof o.functionId=="string"?o.functionId:void 0,r=typeof o=="object"&&o!==null&&"result"in o?o.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)}`);o.isError!==void 0&&typeof o.isError!="boolean"&&St("Function message isError must be a boolean when provided",{fieldPath:"isError",value:o.isError,item:o});break}default:throw new Error(`Unsupported message role: ${e(t)}`)}}function Po(o){let e=n=>JSON.stringify(n,null,2),t=Array.isArray(o)?o:[o];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 s=0;s<r.thoughtBlocks.length;s++){let i=r.thoughtBlocks[s];if(typeof i!="object"||i===null)throw new Error(`Chat response result thoughtBlocks[${s}] at index ${n} must be an object, received: ${e(i)}`);if(typeof i.data!="string")throw new Error(`Chat response result thoughtBlocks[${s}].data at index ${n} must be a string, received: ${e(i.data)}`);if(typeof i.encrypted!="boolean")throw new Error(`Chat response result thoughtBlocks[${s}].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[${s}].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 s=0;s<r.annotations.length;s++){let i=r.annotations[s];if(!i||typeof i!="object")throw new Error(`Chat response result annotation at index ${n}[${s}] must be an object, received: ${e(i)}`);if(i.type!=="url_citation")throw new Error(`Chat response result annotation at index ${n}[${s}] 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}[${s}] 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}[${s}] 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 s=0;s<r.functionCalls.length;s++){let i=r.functionCalls[s];if(!i)throw new Error(`Function call at index ${s} 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 ${s} 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 ${s} in result ${n} must have type 'function', received: ${e(i.type)}`);if(!i.function)throw new Error(`Function call at index ${s} 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 ${s} 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 ${s} in result ${n} must be a string or object, received: ${e(i.function.params)}`)}}if(r.finishReason!==void 0){let s=["stop","length","function_call","content_filter","error"];if(!s.includes(r.finishReason))throw new Error(`Chat response result finishReason at index ${n} must be one of: ${s.join(", ")}, received: ${e(r.finishReason)}`)}}}function Fo(o){if(!o||!Array.isArray(o))return 0;let e=0;for(let t of o)switch(t.role){case"system":case"assistant":typeof t.content=="string"&&(e+=t.content.length);break;case"user":if(typeof t.content=="string"){e+=t.content.length;break}if(Array.isArray(t.content))for(let n of t.content)n.type==="text"&&(e+=n.text.length);break;case"function":typeof t.result=="string"&&(e+=t.result.length);break}return e}var Ei=new Map;function am(o){return`${o.providerName}:${o.contentHash}`}function um(o,e){e.type==="text"?o.update(`text:${e.text}`):e.type==="image"?o.update(`image:${e.mimeType}:${e.image.slice(0,100)}`):e.type==="audio"?o.update(`audio:${e.format}:${e.data.slice(0,100)}`):e.type==="file"&&("fileUri"in e?o.update(`file:${e.mimeType}:${e.fileUri}`):o.update(`file:${e.mimeType}:${e.data.slice(0,100)}`))}function cm(o){let e=mt("sha256"),t=-1;for(let n=o.length-1;n>=0;n--){let r=o[n];if("cache"in r&&r.cache){t=n;break}}for(let n=0;n<o.length;n++){let r=o[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 s of r.content)um(e,s)}else r.role==="assistant"&&r.content&&e.update(`assistant:${r.content}`)}return e.digest("hex")}var ke=()=>structuredClone({temperature:0}),He=()=>structuredClone({temperature:.4,frequencyPenalty:.2}),je=class{constructor(e,{name:t,apiURL:n,headers:r,modelInfo:s,defaults:i,options:a={},supportFor:u,models:c}){this.aiImpl=e;this.name=t,this.apiURL=n||"",this.headers=r,this.supportFor=u,this.tracer=a.tracer??he.tracer,this.meter=a.meter??he.meter,this.modelInfo=s,this.models=c,this.id=Ze();let l=this.getModel(i.model)??i.model,p=this.getEmbedModel(i.embedModel)??i.embedModel;if(this.defaults={model:l,embedModel:p},!i.model||typeof i.model!="string"||i.model==="")throw new Error("No model defined");this.setOptions(a),c&&lm(c)}#e=!1;#t=!1;rt;fetch;tracer;meter;timeout;excludeContentFromTrace;models;abortSignal;logger=he.logger??Hu;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 rc(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??he.debug??!1,this.#t=e.verbose??!1,this.rt=e.rateLimiter,this.fetch=e.fetch,this.timeout=e.timeout,this.tracer=e.tracer??he.tracer,this.meter=e.meter??he.meter,this.excludeContentFromTrace=e.excludeContentFromTrace,this.abortSignal=e.abortSignal,this.logger=e.logger??he.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 rn(he.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((s,i)=>s-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 s=this.getMetricsInstruments();if(s){let i=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel,a=this.getMergedCustomLabels(n);oc(s,e,t,this.name,i,a),sc(s,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 s=this.getMetricsInstruments();if(s){let i=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel,a=this.getMergedCustomLabels(n);uc(s,e,this.name,i,a),t&&ic(s,e,this.name,i,a),ac(s,e,r.rate,this.name,i,a)}}recordTokenUsage(e,t){let n=this.getMetricsInstruments();if(n&&e?.tokens){let{promptTokens:r,completionTokens:s,totalTokens:i,thoughtsTokens:a,cacheReadTokens:u,cacheCreationTokens:c}=e.tokens,l=this.getMergedCustomLabels(t);r&&Rr(n,"input",r,this.name,e.model,l),s&&Rr(n,"output",s,this.name,e.model,l),i&&Rr(n,"total",i,this.name,e.model,l),a&&Rr(n,"thoughts",a,this.name,e.model,l),u&&Oi(n,"read",u,this.name,e.model,l),c&&Oi(n,"write",c,this.name,e.model,l)}}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 s of r.content)s.type==="image"?t=!0:s.type==="audio"&&(n=!0)}return{hasImages:t,hasAudio:n}}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(u=>u.name===e);if(!n||!n.promptTokenCostPer1M&&!n.completionTokenCostPer1M)return 0;let{promptTokens:r=0,completionTokens:s=0}=t.tokens,i=n.promptTokenCostPer1M||0,a=n.completionTokenCostPer1M||0;return r*i/1e6+s*a/1e6}estimateCostByName(e,t){if(!t?.tokens)return 0;let n=this.modelInfo.find(u=>u.name===e);if(!n||!n.promptTokenCostPer1M&&!n.completionTokenCostPer1M)return 0;let{promptTokens:r=0,completionTokens:s=0}=t.tokens,i=n.promptTokenCostPer1M||0,a=n.completionTokenCostPer1M||0;return r*i/1e6+s*a/1e6}recordFunctionCallMetrics(e,t,n){let r=this.getMetricsInstruments();if(!(!r||!e))for(let s of e)s&&typeof s=="object"&&"function"in s&&s.function&&typeof s.function=="object"&&"name"in s.function&&lc(r,s.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;gc(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;fc(n,e,this.name,r,this.getMergedCustomLabels(t))}}recordChatMetrics(e,t,n){let r=this.getMetricsInstruments();if(!r)return;let s=this.lastUsedChatModel,i=this.lastUsedModelConfig,a=this.getMergedCustomLabels(t?.customLabels),u=i?.stream??!1;cc(r,"chat",u,this.name,s,a);let{hasImages:c,hasAudio:l}=this.detectMultimodalContent(e);xc(r,c,l,this.name,s,a);let p=Fo(e.chatPrompt);dc(r,p,this.name,s,a),pc(r,i?.temperature,i?.maxTokens,this.name,s,a),t?.thinkingTokenBudget&&this.modelUsage?.tokens?.thoughtsTokens&&hc(r,this.modelUsage.tokens.thoughtsTokens,this.name,s,a);let d=this.calculateRequestSize(e);if(vi(r,"chat",d,this.name,s,a),n&&!u){let m=n,g=this.calculateResponseSize(m);if(Si(r,"chat",g,this.name,s,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&&mc(r,f,this.name,s,a);let x=this.estimateCost(this.lastUsedChatModel,m.modelUsage);x>0&&ki(r,"chat",x,this.name,s,a)}}recordEmbedMetrics(e,t,n){let r=this.getMetricsInstruments();if(!r)return;let s=this.lastUsedEmbedModel,i=this.getMergedCustomLabels(n?.customLabels),a=this.calculateRequestSize(e);vi(r,"embed",a,this.name,s,i);let u=this.calculateResponseSize(t);Si(r,"embed",u,this.name,s,i);let c=this.estimateCostByName(s,t.modelUsage);c>0&&ki(r,"embed",c,this.name,s,i)}getMetrics(){return structuredClone(this.metrics)}async chat(e,t){let n=performance.now(),r=!1,s,i=this.getModelByKey(e.model),a=i?i.thinkingTokenBudget:void 0,u={...i?{thinkingTokenBudget:a,showThoughts:i.showThoughts,stream:i.stream,debug:i.debug,useExpensiveModel:i.useExpensiveModel}:void 0,...Object.fromEntries(Object.entries(t??{}).filter(([,c])=>c!==void 0))};try{return s=await this._chat1(e,u),s}catch(c){throw r=!0,c instanceof Error&&(c.message.includes("timeout")||c.name==="TimeoutError"?this.recordTimeoutMetric("chat",u?.customLabels):(c.message.includes("abort")||c.name==="AbortError")&&this.recordAbortMetric("chat",u?.customLabels)),c}finally{let c=performance.now()-n;this.updateLatencyMetrics("chat",c,u?.customLabels),this.updateErrorMetrics("chat",r,u?.customLabels),r||this.recordChatMetrics(e,u,s)}}async _chat1(e,t){let n=this.getModel(e.model)??e.model??this.defaults.model;if(Array.isArray(e.chatPrompt))for(let c of e.chatPrompt)Cn(c);let r=this.getModelByKey(e.model),s={...this.aiImpl.getModelConfig(),...r?r.modelConfig:void 0,...e.modelConfig},i=this.modelInfo.find(c=>c.name===n);if(i?.notSupported?.temperature&&"temperature"in s&&delete s.temperature,i?.notSupported?.topP&&"topP"in s&&delete s.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(c=>c.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 s.stream=(t?.stream!==void 0?t.stream:s.stream)??!0,this.getFeatures(n).streaming||(s.stream=!1),this.tracer?await this.tracer.startActiveSpan("AI Chat Request",{kind:ct.SERVER,attributes:{[be.LLM_SYSTEM]:this.name,[be.LLM_OPERATION_NAME]:"chat",[be.LLM_REQUEST_MODEL]:n,[be.LLM_REQUEST_MAX_TOKENS]:s.maxTokens??"Not set",[be.LLM_REQUEST_TEMPERATURE]:s.temperature,[be.LLM_REQUEST_TOP_P]:s.topP??"Not set",[be.LLM_REQUEST_TOP_K]:s.topK??"Not set",[be.LLM_REQUEST_FREQUENCY_PENALTY]:s.frequencyPenalty??"Not set",[be.LLM_REQUEST_PRESENCE_PENALTY]:s.presencePenalty??"Not set",[be.LLM_REQUEST_STOP_SEQUENCES]:s.stopSequences?.join(", ")??"Not set",[be.LLM_REQUEST_LLM_IS_STREAMING]:s.stream??"Not set"}},t?.traceContext??qt.active(),async c=>await this._chat2(n,s,e,t,c)):await this._chat2(n,s,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,s){if(!this.aiImpl.createChatReq)throw new Error("createChatReq not implemented");let i=r?.debug??this.#e,a=r?.verbose??this.#t,u;n.functions&&n.functions.length>0&&(u=n.functions.map(y=>this.cleanupFunctionSchema(y)));let c={...n,model:e,functions:u,modelConfig:t};this.lastUsedChatModel=e,this.lastUsedModelConfig=t,i&&Vu(c.chatPrompt,r?.stepIndex??0,r?.logger??this.logger,r?.debugHideSystemPrompt);let l=this.getFeatures(e).functions,p=r?.functionCallMode??"auto",m=p==="prompt"||p==="auto"&&!l?{...c,chatPrompt:c.chatPrompt.map(y=>{if(y.role==="assistant"){let{content:C,name:I,cache:R}=y;return{role:"assistant",content:C,name:I,cache:R}}return y.role==="function"?{role:"user",content:y.result}:y}),functions:[]}:c,g=await this.handleContextCaching(e,m,r,s),f=async()=>{if(g?.preparedRequest){let{apiConfig:R,request:M}=g.preparedRequest;return s?.isRecording()&&yc(n,s,this.excludeContentFromTrace),await tt({name:R.name,url:this.apiURL,localCall:R.localCall,headers:await this.buildHeaders(R.headers),stream:t.stream,timeout:this.timeout,verbose:a,fetch:this.fetch,span:s,abortSignal:r?.abortSignal??this.abortSignal,corsProxy:this.corsProxy,retry:r?.retry??this.retry},M)}let[y,C]=await this.aiImpl.createChatReq(m,r);return s?.isRecording()&&yc(n,s,this.excludeContentFromTrace),await tt({name:y.name,url:this.apiURL,localCall:y.localCall,headers:await this.buildHeaders(y.headers),stream:t.stream,timeout:this.timeout,verbose:a,fetch:this.fetch,span:s,abortSignal:r?.abortSignal??this.abortSignal,corsProxy:this.corsProxy,retry:r?.retry??this.retry},C)},x=r?.rateLimiter??this.rt,A=x?await x(f,{modelUsage:this.modelUsage}):await f();if(t.stream){if(!this.aiImpl.createChatStreamResp)throw new Error("createChatStreamResp not implemented");let y=this.aiImpl.createChatStreamResp.bind(this),C=T=>O=>{let E=y(O,T);if(E.sessionId=r?.sessionId,!E.modelUsage){let $=this.aiImpl.getTokenUsage();$&&(E.modelUsage={ai:this.name,model:e,tokens:$})}return this.modelUsage=E.modelUsage,this.recordTokenUsage(E.modelUsage,r?.customLabels),s?.isRecording()&&bc(E,s,this.excludeContentFromTrace),E},I=async T=>{s?.isRecording()&&s.end(),i&&Ju(T,r?.logger??this.logger)};if(typeof window<"u"){let T=A,O={},E=[],$=r?.abortSignal??this.abortSignal;return new ReadableStream({start:N=>{let S=T.getReader(),v=()=>{try{S.cancel().catch(()=>{})}catch{}try{this.recordAbortMetric("chat",r?.customLabels)}catch{}try{s?.isRecording()&&s.end()}catch{}try{N.error(new DOMException("Aborted","AbortError"))}catch{N.error(new Error("Aborted"))}};if($){if($.aborted){v();return}$.addEventListener("abort",v,{once:!0})}async function P(){try{for(;;){let{done:F,value:U}=await S.read();if(F){I&&await I(E),N.close();break}let L=C(O)(U);L&&(E.push(L),N.enqueue(L))}}catch(F){if(N.error(F),s?.isRecording())try{s.end()}catch{}}finally{if(S.releaseLock(),$)try{$.removeEventListener("abort",v)}catch{}}}P()}})}return A.pipeThrough(new ko(C({}),I))}if(!this.aiImpl.createChatResp)throw new Error("createChatResp not implemented");let h=this.aiImpl.createChatResp(A);if(h.sessionId=r?.sessionId,!h.modelUsage){let y=this.aiImpl.getTokenUsage();y&&(h.modelUsage={ai:this.name,model:e,tokens:y})}return h.modelUsage&&(this.modelUsage=h.modelUsage,this.recordTokenUsage(h.modelUsage,r?.customLabels)),s?.isRecording()&&(bc(h,s,this.excludeContentFromTrace),s.end()),i&&Wu(h,r?.logger??this.logger),h}async embed(e,t){let n=performance.now(),r=!1,s,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 s=await this._embed1(e,a),s}catch(u){throw r=!0,u instanceof Error&&(u.message.includes("timeout")||u.name==="TimeoutError"?this.recordTimeoutMetric("embed",a?.customLabels):(u.message.includes("abort")||u.name==="AbortError")&&this.recordAbortMetric("embed",a?.customLabels)),u}finally{let u=performance.now()-n;this.updateLatencyMetrics("embed",u,a?.customLabels),this.updateErrorMetrics("embed",r,a?.customLabels),!r&&s&&this.recordEmbedMetrics(e,s,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:ct.SERVER,attributes:{[be.LLM_SYSTEM]:this.name,[be.LLM_OPERATION_NAME]:"embeddings",[be.LLM_REQUEST_MODEL]:n}},t?.traceContext??qt.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 s=this.aiImpl.createEmbedReq.bind(this.aiImpl),i=n?.debug??this.#e,a=n?.verbose??this.#t,u={...t,embedModel:e};this.lastUsedEmbedModel=e,i&&ec(u.texts??[],e,n?.logger??this.logger);let c=async()=>{let[m,g]=await s(u);return await tt({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)},l=n?.rateLimiter??this.rt,p=l?await l(c,{modelUsage:this.embedModelUsage}):await c(),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(vt.GEN_AI_USAGE,{[be.LLM_USAGE_INPUT_TOKENS]:d.modelUsage.tokens.promptTokens,[be.LLM_USAGE_OUTPUT_TOKENS]:d.modelUsage.tokens.completionTokens??0,[be.LLM_USAGE_TOTAL_TOKENS]:d.modelUsage.tokens.totalTokens}),i&&tc(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 s=n?.contextCache;if(!s)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 u=s.ttlSeconds??3600,c=s.refreshWindowSeconds??300,l=s.minTokens??2048;if(s.name)return this.useCacheByName(e,t,s.name,n,r);let p=cm(t.chatPrompt);if(!p||p===mt("sha256").digest("hex"))return null;let d={providerName:this.getName(),contentHash:p},m=am(d),g=Date.now(),f=s.registry,x=f?await f.get(m):Ei.get(m);if(x&&x.expiresAt>g){if(x.expiresAt-g<c*1e3&&this.aiImpl.buildCacheUpdateTTLOp){await this.executeCacheOperation(this.aiImpl.buildCacheUpdateTTLOp(x.cacheName,u),n,r);let C={cacheName:x.cacheName,expiresAt:g+u*1e3,tokenCount:x.tokenCount};f?await f.set(m,C):Ei.set(m,{...C,contentHash:p,lastTouchedAt:g})}return this.useCacheByName(e,t,x.cacheName,n,r)}if(this.estimateCacheableTokens(t.chatPrompt)<l)return null;let h=this.aiImpl.buildCacheCreateOp?.(t,n);if(h){let y=await this.executeCacheOperation(h,n,r);if(y){let C={cacheName:y.name,expiresAt:new Date(y.expiresAt).getTime(),tokenCount:y.tokenCount};return f?await f.set(m,C):Ei.set(m,{...C,contentHash:p,lastTouchedAt:g}),this.useCacheByName(e,t,y.name,n,r)}}return null}async useCacheByName(e,t,n,r,s){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 s=await tt({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(s)}catch(s){n?.addEvent("context_cache.error",{type:e.type,error:s instanceof Error?s.message:String(s)});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 yc(o,e,t){let n=[];if(o.chatPrompt&&Array.isArray(o.chatPrompt)&&o.chatPrompt.length>0)for(let s of o.chatPrompt)switch(s.role){case"system":if(s.content){let i={};t||(i.content=s.content),e.addEvent(vt.GEN_AI_SYSTEM_MESSAGE,i)}break;case"user":if(typeof s.content=="string")n.push(s.content);else if(Array.isArray(s.content))for(let i of s.content)i.type==="text"&&n.push(i.text);break;case"assistant":{let i=s.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&&s.content&&(a.content=s.content),e.addEvent(vt.GEN_AI_ASSISTANT_MESSAGE,a)}else if(s.content){let a={};t||(a.content=s.content),e.addEvent(vt.GEN_AI_ASSISTANT_MESSAGE,a)}break}case"function":{let i={id:s.functionId};t||(i.content=s.result),e.addEvent(vt.GEN_AI_TOOL_MESSAGE,i);break}}let r={};t||(r.content=n.join(`
169
+ `)),e.addEvent(vt.GEN_AI_USER_MESSAGE,r)}function bc(o,e,t){if(o.modelUsage?.tokens){let n=o.modelUsage.tokens.thoughtsTokens?{[be.LLM_USAGE_THOUGHTS_TOKENS]:o.modelUsage.tokens.thoughtsTokens}:{};e.addEvent(vt.GEN_AI_USAGE,{[be.LLM_USAGE_INPUT_TOKENS]:o.modelUsage.tokens.promptTokens,[be.LLM_USAGE_OUTPUT_TOKENS]:o.modelUsage.tokens.completionTokens??0,[be.LLM_USAGE_TOTAL_TOKENS]:o.modelUsage.tokens.totalTokens,...n})}if(o.results)for(let n=0;n<o.results.length;n++){let r=o.results[n];if(!r||!r.content&&!r.thought&&!r.functionCalls?.length&&!r.finishReason)continue;let s=r.functionCalls?.map(a=>({id:a.id,type:a.type,function:a.function.name,arguments:a.function.params})),i={};s&&s.length>0?(t||(i.content=r.content),i.tool_calls=s):t||(i.content=r.content??""),e.addEvent(vt.GEN_AI_CHOICE,{finish_reason:r.finishReason,index:n,message:JSON.stringify(i,null,2)})}}function Mi(o){let e=0;for(let t of o){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 lm(o){let e=new Set;for(let t of o){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 vr=(x=>(x.Claude46Opus="claude-opus-4-6",x.Claude46Sonnet="claude-sonnet-4-6",x.Claude45Opus="claude-opus-4-5-20251101",x.Claude41Opus="claude-opus-4-1-20250805",x.Claude4Opus="claude-opus-4-20250514",x.Claude4Sonnet="claude-sonnet-4-20250514",x.Claude45Sonnet="claude-sonnet-4-5-20250929",x.Claude45Haiku="claude-haiku-4-5",x.Claude37Sonnet="claude-3-7-sonnet-latest",x.Claude35Sonnet="claude-3-5-sonnet-latest",x.Claude35Haiku="claude-3-5-haiku-latest",x.Claude3Opus="claude-3-opus-latest",x.Claude3Sonnet="claude-3-sonnet-20240229",x.Claude3Haiku="claude-3-haiku-20240307",x.Claude21="claude-2.1",x.ClaudeInstant12="claude-instant-1.2",x))(vr||{}),Sr=(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))(Sr||{});var kr=[{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 Ht=o=>{if(!o||typeof o!="object")return o;let e={...o};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,Ht(r)]))),e.items&&(e.items=Ht(e.items)),Array.isArray(e.anyOf)&&(e.anyOf=e.anyOf.map(n=>Ht(n))),Array.isArray(e.allOf)&&(e.allOf=e.allOf.map(n=>Ht(n))),Array.isArray(e.oneOf)&&(e.oneOf=e.oneOf.map(n=>Ht(n))),e},Fi=()=>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"},...ke()}),Ic=()=>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"},...ke()}),Pi=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,s;this.isVertex?s={name:r?`/models/${n}:streamRawPredict?alt=sse`:`/models/${n}:rawPredict`}:s={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(P=>"cache"in P&&P.cache)||e.functions?.some(P=>P.cache),u=e.chatPrompt.filter(P=>P.role==="system"),c=u.map((P,F)=>({type:"text",text:P.content,...P.cache||a&&F===u.length-1?{cache_control:{type:"ephemeral"}}:{}})),l=e.chatPrompt.filter(P=>P.role!=="system"),p=e.functions?.map((P,F,U)=>{let L={type:"object",properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]},z=P.parameters?Ht(P.parameters):void 0;return z===void 0||z&&typeof z=="object"&&Object.keys(z).length===0?z={...L}:z&&typeof z=="object"&&z.type==="object"&&(!("properties"in z)||!z.properties||Object.keys(z.properties).length===0)&&(z={...z,properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]}),{name:P.name,description:P.description,input_schema:z,...P.cache||a&&F===U.length-1?{cache_control:{type:"ephemeral"}}:{}}}),m=(this.config.tools??[]).map(P=>P&&typeof P=="object"&&"type"in P?P:{name:P.name,description:P.description,input_schema:P.input_schema?Ht(P.input_schema):void 0,...P.cache_control?{cache_control:P.cache_control}:{}}),g=[...p??[],...m];g.length===0&&(g=void 0);let f=e.modelConfig?.maxTokens??this.config.maxTokens,x=e.modelConfig?.stopSequences??this.config.stopSequences,A=e.modelConfig?.temperature,h=e.modelConfig?.topP,y=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=P=>P.includes("claude-opus-4-6"),R=P=>P.includes("claude-opus-4-5"),M,T,O=n;if(t?.thinkingTokenBudget){let P=this.config.thinkingTokenBudgetLevels,F=this.config.effortLevelMapping;if(t.thinkingTokenBudget==="none")M=void 0,T=void 0;else{let U=t.thinkingTokenBudget;if(I(O))M={type:"adaptive"},T={effort:F?.[U]??"medium"};else if(R(O)){M={type:"enabled",budget_tokens:P?.[U]??1e4};let z=F?.[U]??"medium";z==="max"&&(z="high"),T={effort:z}}else M={type:"enabled",budget_tokens:P?.[U]??1e4}}}let $=pm(l,!!M);$.some(P=>P.role==="assistant"&&Array.isArray(P.content)&&P.content.length>0&&P.content[0]?.type==="tool_use")&&(M=void 0,T=void 0);let S;if(this.usedStructuredOutput=!1,e.responseFormat&&e.responseFormat.type==="json_schema"&&e.responseFormat.schema){let P=e.responseFormat.schema.schema||e.responseFormat.schema;S={type:"json_schema",schema:Ht(P)},this.usedStructuredOutput=!0}let v={...this.isVertex?{anthropic_version:"vertex-2023-10-16"}:{model:n},...f?{max_tokens:f}:{},...x&&x.length>0?{stop_sequences:x}:{},...A!==void 0&&!M?{temperature:A}:{},...h!==void 0&&(!M||h>=.95)?{top_p:h}:{},...y&&!M?{top_k:y}:{},...i,...g?{tools:g}:{},...r?{stream:!0}:{},...c?{system:c}:{},...M?{thinking:M}:{},...T?{output_config:T}:{},...S?{output_format:S}:{},messages:$};return[s,v]};createChatResp=e=>{if(e.type==="error")throw new $e(e.error.message,void 0,void 0);let t=Cc(e.stop_reason),n=this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1,r="",s=[],i=[],a=[];for(let l of e.content)switch(l.type){case"text":if(r+=l.text??"",Array.isArray(l.citations))for(let p of l.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=l.thinking??"",d=l.signature;i.push({data:p,encrypted:!1,...typeof d=="string"?{signature:d}:{}})}break;case"redacted_thinking":if(n){let p=l.data??"",d=l.signature;i.push({data:p,encrypted:!0,...typeof d=="string"?{signature:d}:{}})}break;case"tool_use":s.push({id:l.id,type:"function",function:{name:l.name,params:l.input}});break}let u={index:0,id:e.id,finishReason:t};r&&(u.content=r),i.length>0&&(u.thoughtBlocks=i,u.thought=i.map(l=>l.data).join("")),s.length>0&&(u.functionCalls=s),a.length>0&&(u.citations=a);let c=[u];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:c,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:s}=e;throw new $e(s.message,void 0,void 0)}let r=0;if(e.type==="message_start"){let{message:s}=e,i=[{index:r,content:"",id:s.id}];return this.tokensUsed={promptTokens:s.usage?.input_tokens??0,completionTokens:s.usage?.output_tokens??0,totalTokens:(s.usage?.input_tokens??0)+(s.usage?.output_tokens??0)+(s.usage?.cache_creation_input_tokens??0)+(s.usage?.cache_read_input_tokens??0),cacheCreationTokens:s.usage?.cache_creation_input_tokens,cacheReadTokens:s.usage?.cache_read_input_tokens},{results:i}}if(e.type==="content_block_start"){let{content_block:s}=e;if(s.type==="text"){let i=[];if(Array.isArray(s.citations))for(let a of s.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:s.text,...i.length?{citations:i}:{}}]}}if(s.type==="thinking")return this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1?{results:[{index:r,thought:s.thinking,thoughtBlocks:[{data:s.thinking,encrypted:!1}]}]}:{results:[{index:r,content:""}]};if(s.type==="tool_use"&&typeof s.id=="string"&&typeof e.index=="number"&&!n.indexIdMap[e.index]){n.indexIdMap[e.index]=s.id;let i=[{id:s.id,type:"function",function:{name:s.name,params:""}}];return{results:[{index:r,functionCalls:i}]}}if(s.type==="web_search_tool_result"||s.type==="server_tool_use")return{results:[{index:r,content:""}]}}if(e.type==="content_block_delta"){let{delta:s}=e;if(s.type==="citations_delta"){let i=s.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(s.type==="text_delta"){let i=[];if(Array.isArray(s.citations))for(let a of s.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:s.text,...i.length?{citations:i}:{}}]}}if(s.type==="thinking_delta")return this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1?{results:[{index:r,thought:s.thinking,thoughtBlocks:[{data:s.thinking,encrypted:!1}]}]}:{results:[{index:r,content:""}]};if(s.type==="signature_delta")return{results:[{index:r,thoughtBlocks:[{data:"",encrypted:!1,signature:s.signature}]}]};if(s.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:s.partial_json}}];return{results:[{index:r,functionCalls:a}]}}}if(e.type==="message_delta"){let{delta:s,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:Cc(s.stop_reason)}]}}return{results:[{index:r,content:""}]}};supportsImplicitCaching=()=>!0},In=class o extends je{static create(e){return new o(e)}constructor({apiKey:e,projectId:t,region:n,config:r,options:s,models:i}){let a=t!==void 0&&n!==void 0,u,c;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");u=`https://${n==="global"?"aiplatform":`${n}-aiplatform`}.googleapis.com/v1/projects/${t}/locations/${n}/publishers/anthropic/`,c=async()=>({Authorization:`Bearer ${await e()}`,"anthropic-beta":"web-search-2025-03-05"})}else{if(!e)throw new Error("Anthropic API key not set");u="https://api.anthropic.com/v1",c=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 l={...Fi(),...r},p=new Pi(l,a),d=g=>{let f=ft({model:g,modelInfo:kr,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,x=f?.config;if(!x)return g;let A={};x.maxTokens!==void 0&&(A.maxTokens=x.maxTokens),x.temperature!==void 0&&(A.temperature=x.temperature),x.topP!==void 0&&(A.topP=x.topP),x.topK!==void 0&&(A.topK=x.topK),x.presencePenalty!==void 0&&(A.presencePenalty=x.presencePenalty),x.frequencyPenalty!==void 0&&(A.frequencyPenalty=x.frequencyPenalty),x.stopSequences!==void 0&&(A.stopSequences=x.stopSequences),x.endSequences!==void 0&&(A.endSequences=x.endSequences),x.stream!==void 0&&(A.stream=x.stream),x.n!==void 0&&(A.n=x.n);let h={...f};Object.keys(A).length>0&&(h.modelConfig={...f.modelConfig??{},...A});let y=x.thinking?.thinkingTokenBudget;if(typeof y=="number"){let C=l.thinkingTokenBudgetLevels,I=[["minimal",C?.minimal??1024],["low",C?.low??5e3],["medium",C?.medium??1e4],["high",C?.high??2e4],["highest",C?.highest??32e3]],R="minimal",M=Number.POSITIVE_INFINITY;for(let[T,O]of I){let E=Math.abs(y-O);E<M&&(M=E,R=T)}h.thinkingTokenBudget=R}return x.thinking?.includeThoughts!==void 0&&(h.showThoughts=!!x.thinking.includeThoughts),h});super(p,{name:"Anthropic",apiURL:u,headers:c,modelInfo:kr,defaults:{model:l.model},options:s,supportFor:d,models:m??i})}};function pm(o,e){let t=o.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 s="",i=[],a=r.thoughtBlocks;if(Array.isArray(a)&&a.length>0)for(let u of a)u.encrypted?i.push(u.signature?{type:"redacted_thinking",data:u.data,signature:u.signature}:{type:"redacted_thinking",data:u.data}):i.push(u.signature?{type:"thinking",thinking:u.data,signature:u.signature}:{type:"thinking",thinking:u.data});if(typeof r.content=="string"&&(i.length>0?s=[...i,{type:"text",text:r.content}]:s=r.content),typeof r.functionCalls<"u"&&(s=r.functionCalls.map(u=>{let c={};if(typeof u.function.params=="string"){let l=u.function.params;if(l.trim().length===0)c={};else try{c=JSON.parse(l)}catch{throw new Error(`Failed to parse function params JSON: ${l}`)}}else typeof u.function.params=="object"&&(c=u.function.params);return{type:"tool_use",id:u.id,name:u.function.name,input:c,...r.cache?{cache_control:{type:"ephemeral"}}:{}}}),Array.isArray(s)&&i.length>0&&(s=[...i,...s])),r.cache){if(typeof s=="string")s=[{type:"text",text:s,cache_control:{type:"ephemeral"}}];else if(Array.isArray(s)&&s.length>0){let u=s.length-1,c=s[u];c&&c.type==="text"&&(s[u]={...c,cache_control:{type:"ephemeral"}})}}return{role:"assistant",content:s}}default:throw new Error("Invalid role")}}),n=dm(t);return mm(n)}function dm(o){let e=[];for(let[t,n]of o.entries()){if(n.role!=="assistant"){e.push(n);continue}if(t>0&&o.at(t-1)?.role==="assistant"){let r=e.pop();e.push({...r||{},...n})}else e.push(n)}return e}function mm(o){return o.map(e=>e.role==="assistant"&&typeof e.content=="string"?{...e,content:e.content.replace(/\s+$/,"")}:e)}function Cc(o){if(o)switch(o){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 Or=(L=>(L.GPT4="gpt-4",L.GPT41="gpt-4.1",L.GPT41Mini="gpt-4.1-mini",L.GPT41Nano="gpt-4.1-nano",L.GPT4O="gpt-4o",L.GPT4OMini="gpt-4o-mini",L.GPT4ChatGPT4O="chatgpt-4o-latest",L.GPT4Turbo="gpt-4-turbo",L.GPT35Turbo="gpt-3.5-turbo",L.GPT35TurboInstruct="gpt-3.5-turbo-instruct",L.GPT35TextDavinci002="text-davinci-002",L.GPT3TextBabbage002="text-babbage-002",L.GPT3TextAda001="text-ada-001",L.GPT5="gpt-5",L.GPT5Nano="gpt-5-nano",L.GPT5Mini="gpt-5-mini",L.GPT5Chat="gpt-5-chat",L.GPT5ChatLatest="gpt-5-chat-latest",L.GPT5Codex="gpt-5-codex",L.GPT5Pro="gpt-5-pro",L.GPT51="gpt-5.1",L.GPT51ChatLatest="gpt-5.1-chat-latest",L.GPT51Codex="gpt-5.1-codex",L.GPT51CodexMini="gpt-5.1-codex-mini",L.GPT51CodexMax="gpt-5.1-codex-max",L.GPT52="gpt-5.2",L.GPT52ChatLatest="gpt-5.2-chat-latest",L.GPT52Codex="gpt-5.2-codex",L.GPT52Pro="gpt-5.2-pro",L.O1="o1",L.O1Mini="o1-mini",L.O3="o3",L.O3Mini="o3-mini",L.O4Mini="o4-mini",L))(Or||{}),Tn=(n=>(n.TextEmbeddingAda002="text-embedding-ada-002",n.TextEmbedding3Small="text-embedding-3-small",n.TextEmbedding3Large="text-embedding-3-large",n))(Tn||{});var wn=(j=>(j.GPT4="gpt-4",j.GPT41="gpt-4.1",j.GPT41Mini="gpt-4.1-mini",j.GPT41Nano="gpt-4.1-nano",j.GPT4O="gpt-4o",j.GPT4OMini="gpt-4o-mini",j.GPT4ChatGPT4O="chatgpt-4o-latest",j.GPT4Turbo="gpt-4-turbo",j.GPT35Turbo="gpt-3.5-turbo",j.GPT35TurboInstruct="gpt-3.5-turbo-instruct",j.GPT35TextDavinci002="text-davinci-002",j.GPT3TextBabbage002="text-babbage-002",j.GPT3TextAda001="text-ada-001",j.GPT5="gpt-5",j.GPT5Nano="gpt-5-nano",j.GPT5Mini="gpt-5-mini",j.GPT5Chat="gpt-5-chat",j.GPT5ChatLatest="gpt-5-chat-latest",j.GPT5Codex="gpt-5-codex",j.GPT5Pro="gpt-5-pro",j.GPT51="gpt-5.1",j.GPT51ChatLatest="gpt-5.1-chat-latest",j.GPT51Codex="gpt-5.1-codex",j.GPT51CodexMini="gpt-5.1-codex-mini",j.GPT51CodexMax="gpt-5.1-codex-max",j.GPT52="gpt-5.2",j.GPT52ChatLatest="gpt-5.2-chat-latest",j.GPT52Codex="gpt-5.2-codex",j.GPT52Pro="gpt-5.2-pro",j.O1Pro="o1-pro",j.O1="o1",j.O1Mini="o1-mini",j.O3Pro="o3-pro",j.O3="o3",j.O3Mini="o3-mini",j.O4Mini="o4-mini",j))(wn||{});var Rn=[{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}],_o=[{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 gm=o=>{let e=["o1","o1-mini","o3","o3-mini","o4-mini","o1-pro","o3-pro"];return e.includes(o)||e.includes(o)},on=()=>structuredClone({model:"gpt-5-mini",embedModel:"text-embedding-3-small",...ke()}),No=()=>structuredClone({...on(),model:"gpt-5"}),$o=()=>structuredClone({model:"gpt-5-mini",embedModel:"text-embedding-3-small",...He()}),Lo=()=>({...on(),model:"gpt-5-nano"}),_i=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"},s=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=fm(e),u=e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,c=e.modelConfig?.stream??this.config.stream,l=this.config.store,p=gm(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}}:{},...s?{tools:s}:{},...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}:{},...u!==void 0?{frequency_penalty:u}:{}},...(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}:{},...c&&this.streamingUsage?{stream:!0,stream_options:{include_usage:!0}}:{},...l?{store:l}:{},...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:s}=e;if(s)throw s;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 $e(a.message.refusal,e.model,e.id);let u=Tc(a.finish_reason),c=a.message.tool_calls?.map(({id:l,function:{arguments:p,name:d}})=>({id:l,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(l=>l?.type==="url_citation"&&l.url_citation).map(l=>({url:l.url_citation?.url,title:l.url_citation?.title,description:l.url_citation?.description})),functionCalls:c,finishReason:u}}),remoteId:t}}createChatStreamResp(e,t){let{id:n,usage:r,choices:s}=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:s.map(({index:u,delta:{content:c,role:l,refusal:p,tool_calls:d,reasoning_content:m,annotations:g},finish_reason:f})=>{if(p)throw new $e(p,void 0,n);let x=Tc(f),A=d?.map(({id:h,index:y,function:{name:C,arguments:I}})=>{typeof h=="string"&&typeof y=="number"&&!i.indexIdMap[y]&&(i.indexIdMap[y]=h);let R=i.indexIdMap[y];return R?{id:R,type:"function",function:{name:C,params:I}}:null}).filter(h=>h!==null);return{index:u,content:c??void 0,role:l,thought:m,citations:g?.filter(h=>h?.type==="url_citation"&&h.url_citation).map(h=>({url:h.url_citation?.url,title:h.url_citation?.title,description:h.url_citation?.description})),functionCalls:A,finishReason:x,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)}}},Tc=o=>{switch(o){case"stop":return"stop";case"length":return"length";case"content_filter":return"error";case"tool_calls":return"function_call"}};function fm(o){return o.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 Ge=class extends je{constructor({apiKey:e,config:t,options:n,apiURL:r,modelInfo:s,models:i,chatReqUpdater:a,supportFor:u}){if(!e||e==="")throw new Error("OpenAI API key not set");let c=new _i(t,n?.streamingUsage??!0,a);super(c,{name:"OpenAI",apiURL:r||"https://api.openai.com/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:s,defaults:{model:t.model,embedModel:t.embedModel},options:n,supportFor:u,models:i})}},vn=class extends Ge{constructor({apiKey:e,apiURL:t,config:n,options:r,models:s,modelInfo:i}){if(!e||e==="")throw new Error("OpenAI API key not set");i=[...Rn,...i??[]];let a=c=>{let l=ft({model:c,modelInfo:i,models:s});return{functions:!0,streaming:!0,hasThinkingBudget:l?.supported?.thinkingBudget??!1,hasShowThoughts:l?.supported?.showThoughts??!1,structuredOutputs:l?.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:l?.supported?.thinkingBudget??!1,multiTurn:!0}},u=s?.map(c=>{let l=c,p=l?.config;if(!p)return c;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={...l};Object.keys(d).length>0&&(g.modelConfig={...l.modelConfig??{},...d});let f=p?.thinking?.thinkingTokenBudget;if(typeof f=="number"){let x=[["minimal",200],["low",800],["medium",5e3],["high",1e4],["highest",24500]],A="minimal",h=Number.POSITIVE_INFINITY;for(let[y,C]of x){let I=Math.abs(f-C);I<h&&(h=I,A=y)}g.thinkingTokenBudget=A}return p?.thinking?.includeThoughts!==void 0&&(g.showThoughts=!!p.thinking.includeThoughts),g});super({apiKey:e,apiURL:t,config:{...on(),...n},options:r,modelInfo:i,models:u??s,supportFor:a}),super.setName("OpenAI")}};var hm=o=>{let e=o.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},xm=o=>{let e=o.match(/^(\d{4}-\d{2}-\d{2})/);return e?e[1]>="2024-08-01":!1},Ni=on,wc=$o,Rc=Lo,vc=No,Sn=class extends Ge{constructor({apiKey:e,resourceName:t,deploymentName:n,version:r="api-version=2024-02-15-preview",config:s,options:i,models:a,modelInfo:u}){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 c={...Ni(),...s},l=hm(r),p=xm(l);u=[...Rn,...u??[]];let d=g=>{let f=ft({model:g,modelInfo:u,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:c,options:i,models:a,modelInfo:u,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=${l}`,m).href),super.setHeaders(async()=>({"api-key":e}))}};var Do=class o{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.");Am(e),this.services=[...e].sort(t?.comparator??o.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 o(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,s=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 u=a.latency.chat.samples.length;u>0&&(t+=a.latency.chat.mean*u,n+=u);let c=a.latency.embed.samples.length;c>0&&(r+=a.latency.embed.mean*c,s+=c)}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),s>0&&(e.latency.embed.mean=r/s);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,s=Date.now()-r,i=Math.min(this.initialBackoffMs*2**n,this.maxBackoffMs);return s>=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,s=r?.requiresImages,i=r?.requiresAudio,a=this.services,u=e.model;if((n||s||i)&&(a=this.services.filter(p=>{let d=p.getFeatures(u);return!(n&&!d.structuredOutputs||s&&!d.media.images.supported||i&&!d.media.audio.supported)}),a.length===0)){let p=[];throw n&&p.push("structured outputs"),s&&p.push("images"),i&&p.push("audio"),new Error(`No services available that support required capabilities: ${p.join(", ")}.`)}let c=0,l=a[c];if(!l)throw new Error("No matching AI services available for request.");for(this.currentService=l;;){if(!this.canRetryService(l)){let p=this.getNextService(a,c);if(!p.service)throw new Error(`All candidate services exhausted (tried ${a.length} service(s))`);l=p.service,c=p.index,this.currentService=l;continue}try{let p=await l.chat(e,t);return this.handleSuccess(l),p}catch(p){if(!(p instanceof et))throw p;switch(p.constructor){case Dt:throw p;case rt:{if(![408,429,500,502,503,504].includes(p.status))throw p;break}case Je:break;case Lt:break;case ht:break;case gt:break;default:throw p}if(this.handleFailure(l,p),(this.serviceFailures.get(l.getId())?.retries??0)>=this.maxRetries){let m=this.getNextService(a,c);if(this.debug&&console.warn(`AxBalancer: Switching to service ${m.service?.getName()??"none"}`,p),!m.service)throw p;l=m.service,c=m.index,this.currentService=l}}}}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 et)||r instanceof rt&&![408,429,500,502,503,504].includes(r.status)||r instanceof Dt)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 Am(o){let e=o.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<o.length;r++){let s=o[r];if(!s)throw new Error(`Service at index ${r} is undefined`);let i=s.getModelList();if(!i)throw new Error(`Service at index ${r} (${s.getName()}) has no model list while another service does.`);let a=new Set(i.map(u=>u.key));for(let u of n)if(!a.has(u))throw new Error(`Service at index ${r} (${s.getName()}) is missing model "${u}"`);for(let u of a)if(!n.has(u))throw new Error(`Service at index ${r} (${s.getName()}) has extra model "${u}"`)}}function sn(o){let e=!1,t=!1,n=!1,r=!1,s=!1,i=!1,a=!1,u=new Set,c=0;if(o.chatPrompt&&Array.isArray(o.chatPrompt))for(let l of o.chatPrompt){if(l.role==="user"&&Array.isArray(l.content))for(let p of l.content)switch(u.add(p.type),p.type){case"image":e=!0,p.cache&&(a=!0),c+=85;break;case"audio":t=!0,p.cache&&(a=!0),c+=p.duration||60;break;case"file":n=!0,p.cache&&(a=!0),c+=Math.ceil((p.extractedText?.length||1e3)/4);break;case"url":r=!0,p.cache&&(a=!0),c+=Math.ceil((p.cachedContent?.length||2e3)/4);break;case"text":p.cache&&(a=!0),c+=Math.ceil(p.text.length/4);break}else"content"in l&&typeof l.content=="string"&&(c+=Math.ceil(l.content.length/4));"cache"in l&&l.cache&&(a=!0)}return o.functions&&o.functions.length>0&&(s=!0),o.modelConfig?.stream===!0&&(i=!0),o.capabilities&&(o.capabilities.requiresImages&&(e=!0),o.capabilities.requiresAudio&&(t=!0),o.capabilities.requiresFiles&&(n=!0),o.capabilities.requiresWebSearch&&(r=!0)),{hasImages:e,hasAudio:t,hasFiles:n,hasUrls:r,requiresFunctions:s,requiresStreaming:i,requiresCaching:a,contentTypes:u,estimatedTokens:c}}function $i(o,e){let t=o.getFeatures(),n=[],r=[],s=[];if(e.hasImages&&!t.media.images.supported&&(n.push("Image support"),s.push("Use altText for images or imageToText service")),e.hasAudio&&!t.media.audio.supported&&(n.push("Audio support"),s.push("Pre-transcribe audio or use transcription field")),e.hasFiles&&!t.media.files.supported&&(n.push("File support"),s.push("Pre-extract text content or use extractedText field")),e.hasUrls&&!t.media.urls.supported&&(n.push("URL/Web search support"),s.push("Pre-fetch content or use cachedContent field")),e.requiresFunctions&&!t.functions&&n.push("Function calling"),e.requiresStreaming&&!t.streaming&&(n.push("Streaming responses"),s.push("Use non-streaming mode")),e.requiresCaching&&!t.caching.supported&&(n.push("Content caching"),s.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:s}}function Uo(o,e){return o.map(t=>{let n=t.getFeatures(),r=$i(t,e),s=0,i=[];return s+=10,e.hasImages&&n.media.images.supported&&(s+=25,i.push("Images"),n.media.images.detailLevels?.includes("high")&&(s+=5),n.media.images.maxSize&&n.media.images.maxSize>10*1024*1024&&(s+=3)),e.hasAudio&&n.media.audio.supported&&(s+=25,i.push("Audio"),n.media.audio.maxDuration&&n.media.audio.maxDuration>600&&(s+=5)),e.hasFiles&&n.media.files.supported&&(s+=25,i.push("Files"),n.media.files.uploadMethod==="cloud"&&(s+=3)),e.hasUrls&&n.media.urls.supported&&(s+=25,i.push("URLs"),n.media.urls.webSearch&&(s+=5)),e.requiresFunctions&&n.functions&&(s+=15,i.push("Functions"),n.functionCot&&(s+=3)),e.requiresStreaming&&n.streaming&&(s+=10,i.push("Streaming")),e.requiresCaching&&n.caching.supported&&(s+=8,i.push("Caching"),n.caching.types.includes("persistent")&&(s+=3)),n.thinking&&(s+=2),n.multiTurn&&(s+=2),n.hasThinkingBudget&&(s+=1),n.hasShowThoughts&&(s+=1),s-=r.missingCapabilities.length*10,{provider:t,score:s,missingCapabilities:r.missingCapabilities,supportedCapabilities:i}}).sort((t,n)=>n.score-t.score)}function Go(o,e,t={}){if(e.length===0)throw new Error("No providers available");let n=sn(o),r=Uo(e,n);if(t.requireExactMatch){let s=r.filter(i=>i.missingCapabilities.length===0);if(s.length===0)throw new Error(`No providers fully support the request requirements: ${r[0]?.missingCapabilities.join(", ")||"unknown requirements"}`);return s[0].provider}if(!t.allowDegradation){let s=r[0];if(s.missingCapabilities.length>0)throw new Error(`Best available provider (${s.provider.getName()}) is missing: ${s.missingCapabilities.join(", ")}`)}return r[0].provider}function Sc(o,e){let t=sn(o),n=Uo(e,t),r=n[0]?.provider||null,s=[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}/${s} requirements (${Math.round(i/Math.max(s,1)*100)}% compatibility)`:"No suitable providers found";return{requirements:t,providerScores:n,recommendedProvider:r,summary:a}}function kc(o,e){return o.filter(t=>t.getFeatures().media[e].supported)}function Oc(o,e){let t={};for(let n of o){let s=n.getFeatures().media[e];if(s.supported)for(let i of s.formats)t[i]||(t[i]=[]),t[i].push(n)}return t}var Er=(r=>(r.CommandRPlus="command-r-plus",r.CommandR="command-r",r.Command="command",r.CommandLight="command-light",r))(Er||{}),Mr=(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))(Mr||{});var jo=[{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 ym(o){if(Array.isArray(o)){let t=["string","number","integer","boolean","object","array"].find(n=>o.includes(n));return t||(o.find(n=>n!=="null")??o[0]??"string")}return typeof o=="string"?o:"string"}var Di=()=>structuredClone({model:"command-r-plus",embedModel:"embed-english-v3.0",...ke()}),Mc=()=>structuredClone({model:"command-r",embedModel:"embed-english-v3.0",...He()}),Li=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),s;n&&n.role==="user"&&typeof n.content=="string"&&(s=n?.content);let i=bm(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:ym(g.type),required:p.parameters.required?.includes(m)??!1};return{name:p.name,description:p.description,parameter_definitions:d}}),u=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??""}]}}),c={name:"/chat"},l={message:s,model:t,tools:a,...u&&!s?{tool_results:u}:{},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[c,l]}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(s=>({id:s.name,type:"function",function:{name:s.name,params:s.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),s=r[0];if(!s)throw new Error("No result");return s.id=n.generation_id??"",{results:r}};createEmbedResp(e){return{remoteId:e.id,embeddings:e.embeddings}}},kn=class extends je{constructor({apiKey:e,config:t,options:n,models:r}){if(!e||e==="")throw new Error("Cohere API key not set");let s={...Di(),...t},i=new Li(s),a=r?.map(u=>{let c=u,l=c?.config;if(!l)return u;let p={};l.maxTokens!==void 0&&(p.maxTokens=l.maxTokens),l.temperature!==void 0&&(p.temperature=l.temperature),l.topP!==void 0&&(p.topP=l.topP),l.topK!==void 0&&(p.topK=l.topK),l.presencePenalty!==void 0&&(p.presencePenalty=l.presencePenalty),l.frequencyPenalty!==void 0&&(p.frequencyPenalty=l.frequencyPenalty),l.stopSequences!==void 0&&(p.stopSequences=l.stopSequences),l.endSequences!==void 0&&(p.endSequences=l.endSequences),l.stream!==void 0&&(p.stream=l.stream),l.n!==void 0&&(p.n=l.n);let d={...c};return Object.keys(p).length>0&&(d.modelConfig={...c.modelConfig??{},...p}),d});super(i,{name:"Cohere",apiURL:"https://api.cohere.ai/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:jo,defaults:{model:s.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 bm(o){return o.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=Ec(e.functionCalls);return{role:"CHATBOT",message:t,tool_calls:n}}case"function":{let n=o.map(i=>{if(i.role==="assistant")return i.functionCalls?.find(a=>a.id===e.functionId)}).filter(i=>i!==void 0),r=Ec(n)?.at(0);if(!r)throw new Error("Function call not found");let s=[{result:e.result}];return{role:"TOOL",tool_results:[{call:r,outputs:s}]}}default:throw new Error("Unknown role")}})}function Ec(o){return o?.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 Pr=(n=>(n.DeepSeekChat="deepseek-chat",n.DeepSeekCoder="deepseek-coder",n.DeepSeekReasoner="deepseek-reasoner",n))(Pr||{});var Bo=[{name:"deepseek-chat",currency:"USD",promptTokenCostPer1M:.27,completionTokenCostPer1M:1.1},{name:"deepseek-reasoner",currency:"USD",promptTokenCostPer1M:.55,completionTokenCostPer1M:2.19}];var Ui=()=>structuredClone({model:"deepseek-chat",...ke()}),Pc=()=>structuredClone({model:"deepseek-coder",...He()}),On=class extends Ge{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:s}){if(!e||e==="")throw new Error("DeepSeek API key not set");let i={...Ui(),...t};s=[...Bo,...s??[]],super({apiKey:e,config:i,options:n,apiURL:"https://api.deepseek.com",modelInfo:s,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 Fr=(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))(Fr||{}),zo=(s=>(s.GeminiEmbedding001="gemini-embedding-001",s.GeminiEmbedding="gemini-embedding-exp",s.TextEmbeddingLarge="text-embedding-large-exp-03-07",s.TextEmbedding004="text-embedding-004",s.TextEmbedding005="text-embedding-005",s))(zo||{}),qo=(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))(qo||{}),Ho=(s=>(s.BlockNone="BLOCK_NONE",s.BlockOnlyHigh="BLOCK_ONLY_HIGH",s.BlockMediumAndAbove="BLOCK_MEDIUM_AND_ABOVE",s.BlockLowAndAbove="BLOCK_LOW_AND_ABOVE",s.BlockDefault="HARM_BLOCK_THRESHOLD_UNSPECIFIED",s))(Ho||{}),Gi=(u=>(u.SemanticSimilarity="SEMANTIC_SIMILARITY",u.Classification="CLASSIFICATION",u.Clustering="CLUSTERING",u.RetrievalDocument="RETRIEVAL_DOCUMENT",u.RetrievalQuery="RETRIEVAL_QUERY",u.QuestionAnswering="QUESTION_ANSWERING",u.FactVerification="FACT_VERIFICATION",u.CodeRetrievalQuery="CODE_RETRIEVAL_QUERY",u))(Gi||{}),Fc=["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 Ko=[{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 an=o=>o.includes("gemini-3"),_c=o=>o.includes("gemini-3")&&o.includes("pro"),Vo=o=>{if(!o||typeof o!="object")return o;let e={...o};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,Vo(n)]))),e.items&&(e.items=Vo(e.items)),e},Nc=[{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:Nc,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},thinkingLevelMapping:{minimal:"minimal",low:"low",medium:"medium",high:"high",highest:"high"},...ke()}),$c=()=>structuredClone({model:"gemini-2.0-flash",embedModel:"text-embedding-005",safetySettings:Nc,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},thinkingLevelMapping:{minimal:"minimal",low:"low",medium:"medium",high:"high",highest:"high"},...He()}),ji=class{constructor(e,t,n,r,s){this.config=e;this.isVertex=t;this.endpointId=n;this.apiKey=r;this.options=s;if(!this.isVertex&&this.config.autoTruncate)throw new Error("Auto truncate is not supported for GoogleGemini");let i=this.config.model;if(an(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(_c(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 s;if(this.endpointId?s={name:r?`/${this.endpointId}:streamGenerateContent?alt=sse`:`/${this.endpointId}:generateContent`}:s={name:r?`/models/${n}:streamGenerateContent?alt=sse`:`/models/${n}:generateContent`},!this.isVertex){let h=r?"&":"?",y=typeof this.apiKey=="function"?await this.apiKey():this.apiKey;s.name+=`${h}key=${y}`}let i=e.chatPrompt.filter(h=>h.role==="system").map(h=>h.content),a=i.length>0?{role:"user",parts:[{text:i.join(" ")}]}:void 0,u=[],c=e.chatPrompt.filter(h=>h.role!=="system");for(let h=0;h<c.length;h++){let y=c[h];switch(y.role){case"user":{let C=Array.isArray(y.content)?y.content.map((I,R)=>{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: ${R})`)}}):[{text:y.content}];u.push({role:"user",parts:C});break}case"assistant":{let C=[],I=y.thoughtBlocks,R=y.functionCalls&&y.functionCalls.length>0,M=I?.[0],T=I?.map(E=>E.data).join("")??"",O=M?.signature;if(T&&C.push({...R?{}:{thought:!0},text:T,...O&&!R?{thought_signature:O}:{}}),y.functionCalls){let E=y.functionCalls.map(($,N)=>{let S;if(typeof $.function.params=="string"){let P=$.function.params;if(P.trim().length===0)S={};else try{S=JSON.parse(P)}catch{throw new Error(`Failed to parse function params JSON: ${P}`)}}else S=$.function.params;let v={functionCall:{name:$.function.name,args:S}};return O&&N===0&&(v.thought_signature=O),v});C.push(...E)}if(y.content&&C.push({text:y.content}),C.length===0)throw new Error("Assistant content is empty");u.push({role:"model",parts:C});break}case"function":{let C=[],I=y,R=h;for(;;){if(!("functionId"in I))throw new Error(`Chat prompt functionId is empty (index: ${R})`);if(C.push({functionResponse:{name:I.functionId,response:{result:I.result}}}),R+1<c.length&&c[R+1].role==="function")R++,I=c[R];else break}h=R,u.push({role:"user",parts:C});break}default:throw new Error(`Invalid role: ${JSON.stringify(y)} (index: ${h})`)}}let l=[];if(e.functions&&e.functions.length>0){let h=e.functions.map(y=>{let C={type:"object",properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]},I=y.parameters?Vo(y.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:y.name,description:y.description,parameters:I}});l.push({function_declarations:h})}if(this.options?.codeExecution&&l.push({code_execution:{}}),this.options?.googleSearchRetrieval&&l.push({google_search_retrieval:{dynamic_retrieval_config:this.options.googleSearchRetrieval}}),this.options?.googleSearch&&l.push({google_search:{}}),this.options?.googleMaps){let h=this.options.googleMaps,y=h?.enableWidget!==void 0?{enableWidget:h.enableWidget}:{};l.push({google_maps:y})}this.options?.urlContext&&l.push({url_context:{}}),l.length===0&&(l=void 0);let p,d=Array.isArray(l)?l.some(h=>h&&Array.isArray(h.function_declarations)&&h.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 h=e.functionCall.function?.name?{allowedFunctionNames:[e.functionCall.function.name]}:{};p={function_calling_config:{mode:"ANY"},...h}}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&&an(n)&&(m.thinkingLevel=this.config.thinking.thinkingLevel),t?.thinkingTokenBudget){let h=this.getEffectiveMappings(n),y=h.thinkingTokenBudgetLevels;if(an(n)){let I=_c(n),R=h.thinkingLevelMapping;if(t.thinkingTokenBudget==="none")m.thinkingLevel=R?.minimal??"minimal";else{let M=t.thinkingTokenBudget,T=R?.[M];T||(T=M==="highest"?"high":M),m.thinkingLevel=T}if(I&&m.thinkingLevel){let M=m.thinkingLevel;M!=="low"&&M!=="high"&&(m.thinkingLevel=M==="minimal"?"low":"high")}}else switch(t.thinkingTokenBudget){case"none":m.thinkingBudget=0,m.includeThoughts=!1,delete m.thinkingLevel;break;case"minimal":m.thinkingBudget=y?.minimal??200;break;case"low":m.thinkingBudget=y?.low??800;break;case"medium":m.thinkingBudget=y?.medium??5e3;break;case"high":m.thinkingBudget=y?.high??1e4;break;case"highest":m.thinkingBudget=y?.highest??24500;break}}m.thinkingLevel&&delete m.thinkingBudget,an(n)||delete m.thinkingLevel,an(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(an(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 h=e.responseFormat.schema.schema||e.responseFormat.schema;f.responseSchema=Vo(h)}}else this.config.responseFormat&&this.config.responseFormat==="json_object"&&(f.responseMimeType="application/json");let x=this.config.safetySettings;return[s,{contents:u,tools:l,toolConfig:p,systemInstruction:a,generationConfig:f,safetySettings:x}]};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(s=>({content:s,...this.config.embedType&&{taskType:this.config.embedType}})),parameters:{autoTruncate:this.config.autoTruncate,outputDimensionality:this.config.dimensions}};else{let s=typeof this.apiKey=="function"?this.apiKey():this.apiKey;n={name:`/models/${t}:batchEmbedContents?key=${s}`},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(s=>{let i={index:0};switch(s.finishReason){case"MAX_TOKENS":i.finishReason="length";break;case"STOP":i.finishReason="stop";break;case"SAFETY":throw new $e("Content was blocked due to safety settings",void 0,void 0);case"RECITATION":throw new $e("Content was blocked due to recitation policy",void 0,void 0);case"MALFORMED_FUNCTION_CALL":throw new $e("Function call was malformed and blocked",void 0,void 0);case"UNEXPECTED_TOOL_CALL":throw new $e("Unexpected tool call",void 0,void 0);case"FINISH_REASON_UNSPECIFIED":throw new $e("Finish reason unspecified",void 0,void 0);case"BLOCKLIST":throw new $e("Content was blocked due to blocklist",void 0,void 0);case"PROHIBITED_CONTENT":throw new $e("Content was blocked due to prohibited content",void 0,void 0);case"SPII":throw new $e("Content was blocked due to SPII",void 0,void 0);case"OTHER":throw new $e("Other finish reason",void 0,void 0)}if(!s.content||!s.content.parts)return i;for(let c of s.content.parts){if("text"in c){if("thought"in c&&c.thought||c.thought===!0){i.thought=c.text;let l=c.thoughtSignature||c.thought_signature;i.thoughtBlocks||(i.thoughtBlocks=[]),i.thoughtBlocks.push({data:c.text,encrypted:!1,...l?{signature:l}:{}})}else i.content=c.text;continue}if("functionCall"in c){let l=c.thoughtSignature||c.thought_signature;if(l)if(!i.thoughtBlocks||i.thoughtBlocks.length===0)i.thoughtBlocks=[{data:"",encrypted:!1,signature:l}];else{let p=i.thoughtBlocks[i.thoughtBlocks.length-1];p&&!p.signature&&(p.signature=l)}i.functionCalls=[...i.functionCalls??[],{id:Ze(),type:"function",function:{name:c.functionCall.name,params:c.functionCall.args}}]}}let a=s.citationMetadata?.citations;if(Array.isArray(a)&&a.length){let c=l=>l?`${l.year}-${String(l.month).padStart(2,"0")}-${String(l.day).padStart(2,"0")}`:void 0;i.citations=a.filter(l=>typeof l?.uri=="string").map(l=>({url:l.uri,title:l.title,license:l.license,publicationDate:c(l.publicationDate)}))}let u=s.groundingMetadata;if(u){if(Array.isArray(u.groundingChunks)){let c=u.groundingChunks.map(l=>l?.maps).filter(l=>l&&typeof l.uri=="string").map(l=>({url:l.uri,title:l.title}));c.length&&(i.citations=[...i.citations??[],...c])}typeof u.googleMapsWidgetContextToken=="string"&&(t=u.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 Fc.some(n=>t.includes(n)||n.includes(t))};buildCacheCreateOp=(e,t)=>{let n=e.model,r=t.contextCache?.ttlSeconds??3600,{systemInstruction:s,contents:i}=this.extractCacheableContent(e.chatPrompt);if(!s&&(!i||i.length===0))return;let a={model:this.isVertex?n:`models/${n}`,ttl:`${r}s`,displayName:`ax-cache-${Date.now()}`};s&&(a.systemInstruction=s),i&&i.length>0&&(a.contents=i);let u;if(this.isVertex)u="/cachedContents";else{u="/cachedContents";let c=typeof this.apiKey=="function"?"ASYNC_KEY":this.apiKey;u+=`?key=${c}`}return{type:"create",apiConfig:{name:u},request:a,parseResponse:c=>{let l=c;if(l?.name)return{name:l.name,expiresAt:l.expireTime,tokenCount:l.usageMetadata?.totalTokenCount}}}};buildCacheUpdateTTLOp=(e,t)=>{let n={ttl:`${t}s`},r=`/${e}`;if(!this.isVertex&&this.apiKey){let s=typeof this.apiKey=="function"?"ASYNC_KEY":this.apiKey;r+=`?key=${s}`}return{type:"update",apiConfig:{name:r,headers:{"Content-Type":"application/json"}},request:n,parseResponse:s=>{let i=s;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,s=e.modelConfig?.stream??this.config.stream,{dynamicContents:i,dynamicSystemInstruction:a}=this.extractDynamicContent(e.chatPrompt),u;if(this.endpointId?u={name:s?`/${this.endpointId}:streamGenerateContent?alt=sse`:`/${this.endpointId}:generateContent`}:u={name:s?`/models/${r}:streamGenerateContent?alt=sse`:`/models/${r}:generateContent`},!this.isVertex){let d=s?"&":"?",m=typeof this.apiKey=="function"?await this.apiKey():this.apiKey;u.name+=`${d}key=${m}`}let c={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"};an(r)&&(c.temperature===void 0||c.temperature<1)&&(c.temperature=1);let l=this.config.safetySettings,p={contents:i,cachedContent:n,generationConfig:c,safetySettings:l};return a&&(p.systemInstruction=a),{apiConfig:u,request:p}};extractCacheableContent(e){let t,n=[],r=-1;for(let s=e.length-1;s>=0;s--){let i=e[s];if("cache"in i&&i.cache){r=s;break}}for(let s=0;s<e.length;s++){let i=e[s];if(i.role==="system"){t={role:"user",parts:[{text:i.content}]};continue}if(r>=0&&s<=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 u of i.content)switch(u.type){case"text":a.push({text:u.text});break;case"image":a.push({inlineData:{mimeType:u.mimeType,data:u.image}});break;case"audio":a.push({inlineData:{mimeType:`audio/${u.format??"mp3"}`,data:u.data}});break;case"file":"fileUri"in u?a.push({fileData:{mimeType:u.mimeType,fileUri:u.fileUri}}):a.push({inlineData:{mimeType:u.mimeType,data:u.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 s=[];if(typeof r.content=="string")s.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":s.push({text:i.text});break;case"image":s.push({inlineData:{mimeType:i.mimeType,data:i.image}});break;case"audio":s.push({inlineData:{mimeType:`audio/${i.format??"mp3"}`,data:i.data}});break;case"file":"fileUri"in i?s.push({fileData:{mimeType:i.mimeType,fileUri:i.fileUri}}):s.push({inlineData:{mimeType:i.mimeType,data:i.data}});break}}s.length>0&&n.push({role:"user",parts:s})}else if(r.role==="assistant"){let s=[];if(r.content&&s.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??{};s.push({functionCall:{name:i.function.name,args:a}})}s.length>0&&n.push({role:"model",parts:s})}else r.role==="function"&&n.push({role:"user",parts:[{functionResponse:{name:r.functionId,response:{result:r.result}}}]});return{dynamicContents:n,dynamicSystemInstruction:void 0}}},En=class o extends je{static create(e){return new o(e)}constructor({apiKey:e,projectId:t,region:n,endpointId:r,config:s,options:i,models:a,modelInfo:u}){let c=t!==void 0&&n!==void 0,l,p;if(c){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 x;r?x="endpoints":x="publishers/google",l=`https://${n==="global"?"aiplatform":`${n}-aiplatform`}.googleapis.com/v1/projects/${t}/locations/${n}/${x}`,p=async()=>({Authorization:`Bearer ${typeof e=="function"?await e():e}`})}else{if(!e)throw new Error("GoogleGemini AI API key not set");l="https://generativelanguage.googleapis.com/v1beta",p=async()=>({})}let d={...Bi(),...s},m=new ji(d,c,r,e,i);u=[...Ko,...u??[]];let g=x=>{let A=ft({model:x,modelInfo:u,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(x),types:["persistent"]},thinking:A?.supported?.thinkingBudget??!1,multiTurn:!0}},f=a?.map(x=>{let A=x,h=A?.config;if(!h)return x;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 C={...A};Object.keys(y).length>0&&(C.modelConfig={...A.modelConfig??{},...y});let I=h.thinking?.thinkingTokenBudget;if(typeof I=="number"){let R=d.thinkingTokenBudgetLevels,M=[["minimal",R?.minimal??200],["low",R?.low??800],["medium",R?.medium??5e3],["high",R?.high??1e4],["highest",R?.highest??24500]],T="minimal",O=Number.POSITIVE_INFINITY;for(let[E,$]of M){let N=Math.abs(I-$);N<O&&(O=N,T=E)}C.thinkingTokenBudget=T}return h.thinking?.includeThoughts!==void 0&&(C.showThoughts=!!h.thinking.includeThoughts),h.thinkingLevelMapping&&(C.thinkingLevelMapping=h.thinkingLevelMapping),h.thinkingTokenBudgetLevels&&(C.thinkingTokenBudgetLevels=h.thinkingTokenBudgetLevels),C});f?m.setModels(f):a&&m.setModels(a),super(m,{name:"GoogleGeminiAI",apiURL:l,headers:p,modelInfo:u,defaults:{model:d.model,embedModel:d.embedModel},options:i,supportFor:g,models:f??a})}};var Cm=new st,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(Cm.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 _r=(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))(_r||{});var Wo=[{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 Im=()=>structuredClone({model:"llama-3.3-70b-versatile",...ke()}),Pn=class extends Ge{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:s}){if(!e||e==="")throw new Error("Groq API key not set");let i={...Im(),...t},a={...n,streamingUsage:!1};s=[...Wo,...s??[]];let 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};super({apiKey:e,config:i,options:a,modelInfo:s,apiURL:"https://api.groq.com/openai/v1",models:r,supportFor:u}),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(s,i)=>{let a=i.modelUsage?.tokens?.totalTokens||0;return await n.acquire(a),await s()}}};var Jo=[];var Qo=(e=>(e.MetaLlama270BChatHF="meta-llama/Llama-2-70b-chat-hf",e))(Qo||{});var qi=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...ke()}),Lc=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...He()}),zi=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(u=>{switch(u.role){case"user":return`User: ${u.content}`;case"system":return`System: ${u.content}`;case"function":return`Function Result: ${u.result}`;case"assistant":{let c=u.functionCalls?.map(l=>{let p=typeof l.function.params=="string"?l.function.params:JSON.stringify(l.function.params);return`${l.function.name}(${p})`}).join(`
172
172
  `);return c?`Assistant: ${u.content}
173
173
  Functions:
174
174
  ${c}`:`Assistant: ${u.content}`}default:throw new Error("Unknown role")}}).join(`
175
- `),s=`${n} ${r}`.trim(),i={name:"/models"},a={model:t,inputs:s,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}]})},Mn=class extends Be{constructor({apiKey:e,config:t,options:n,models:r}){if(!e||e==="")throw new Error("HuggingFace API key not set");let s={...zi(),...t},i=new ji(s);super(i,{name:"HuggingFace",apiURL:"https://api-inference.huggingface.co",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:Jo,defaults:{model:s.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 _r=(u=>(u.Mistral7B="open-mistral-7b",u.Mistral8x7B="open-mixtral-8x7b",u.MistralSmall="mistral-small-latest",u.MistralNemo="mistral-nemo-latest",u.MistralLarge="mistral-large-latest",u.Codestral="codestral-latest",u.OpenCodestralMamba="open-codestral-mamba",u.OpenMistralNemo="open-mistral-nemo-latest",u))(_r||{}),qi=(e=>(e.MistralEmbed="mistral-embed",e))(qi||{});var Yo=[{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 Xo=()=>structuredClone({model:"mistral-small-latest",...Se(),topP:1}),Lc=()=>structuredClone({...Xo(),model:"mistral-large-latest"}),Pn=class extends Ge{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:s}){if(!e||e==="")throw new Error("Mistral API key not set");let i={...Xo(),...t};s=[...Yo,...s??[]];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},u=c=>{let{max_completion_tokens:l,messages:p,...d}=c;return{...d,messages:this.updateMessages(p),max_tokens:l}};super({apiKey:e,config:i,options:n,apiURL:"https://api.mistral.ai/v1",modelInfo:s,models:r,supportFor:a,chatReqUpdater:u}),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(s=>typeof s=="object"&&s!==null&&"image_url"in s?{type:"image_url",image_url:{url:s.image_url?.url}}:s);t.push({...n,content:r})}else t.push(n);return t}};var Zo=class{constructor(e={}){this.config=e;this.config.id=this.config.id??Ze()}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,s)=>r+s,0)/n.length,n.length>0){let r=[...n].sort((a,u)=>a-u),s=Math.max(0,Math.floor(r.length*.95)-1);this.metrics.latency[e].p95=r[s]??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 es=class o{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:s,description:i,isInternal:a}=n;this.services.set(n.key,{service:s,description:i,isInternal:a})}else{let s=n.getModelList();if(!s)throw new Error(`Service ${t} \`${n.getName()}\` has no model list.`);for(let i of s){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 o(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:s,...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:s,...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 Hi=()=>structuredClone({...Se(),model:"nous-hermes2",embedModel:"all-minilm"}),$c=()=>structuredClone({...He(),model:"nous-hermes2",embedModel:"all-minilm"}),Fn=class extends Ge{constructor({apiKey:e="not-set",url:t="http://localhost:11434/v1",config:n,options:r,models:s}){let i={...Hi(),...n};super({apiKey:e,options:r,config:i,apiURL:t,models:s,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 bm=o=>["o1","o1-mini","o1-pro","o3","o3-mini","o3-pro","o4-mini"].includes(o),_n=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 s=r;throw new Error(`Unsupported content part: ${JSON.stringify(s)}`)}return n}createResponsesReqInternalInput(e,t=!1){let n=[];for(let r of e){if(t&&r.role==="system")continue;let s;if(r.role==="system"||r.role==="user"||r.role==="assistant"&&r.content)if(typeof r.content=="string")r.role==="system"?s=r.content:r.role==="assistant"?s=[{type:"output_text",text:r.content}]:s=[{type:"input_text",text:r.content}];else if(Array.isArray(r.content))s=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}`);s=""}else r.role,s="";switch(r.role){case"system":n.push({type:"message",role:"system",content:s});break;case"user":n.push({type:"message",role:"user",content:s,name:r.name});break;case"assistant":if(r.content||r.functionCalls){let i={type:"message",role:"assistant",content:""};if(r.content&&(i.content=s),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"},s=null,i=!1;if(e.chatPrompt){for(let A of e.chatPrompt)if(A.role==="system"&&typeof A.content=="string"){s=A.content,i=!0;break}}let a=s??this.config.systemPrompt??null,u=e.functions?.map(A=>({type:"function",name:A.name,description:A.description,parameters:A.parameters??{}})),c=[],l=bm(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:u?.length?u: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,...l?{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:c.length>0?c: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 x=m;return this.responsesReqUpdater&&(x=this.responsesReqUpdater(x)),[r,x]}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 s={};for(let i of n??[])switch(i.type){case"message":s.id=i.id,s.content=Wi(i.content,t),s.finishReason=i.status==="completed"?"stop":"content_filter",s.citations=ts(i.content);break;case"reasoning":s.id=i.id,i.encrypted_content?s.thought=i.encrypted_content:s.thought=i.summary.map(a=>typeof a=="object"?JSON.stringify(a):a).join(`
176
- `);break;case"file_search_call":s.id=i.id,s.functionCalls=[{id:i.id,type:"function",function:{name:"file_search",params:{queries:i.queries,results:i.results}}}],s.finishReason="function_call";break;case"web_search_call":s.id=i.id,s.functionCalls=[{id:i.id,type:"function",function:{name:"web_search",params:{queries:i.queries}}}],s.finishReason="function_call";break;case"computer_call":s.id=i.id,s.functionCalls=[{id:i.id,type:"function",function:{name:"computer_use",params:{action:i.action}}}],s.finishReason="function_call";break;case"code_interpreter_call":s.id=i.id,s.functionCalls=[{id:i.id,type:"function",function:{name:"code_interpreter",params:{code:i.code,results:i.results}}}],s.finishReason="function_call";break;case"image_generation_call":s.id=i.id,s.functionCalls=[{id:i.id,type:"function",function:{name:"image_generation",params:{result:i.result}}}],s.finishReason="function_call";break;case"local_shell_call":s.id=i.id,s.functionCalls=[{id:i.id,type:"function",function:{name:"local_shell",params:{action:i.action}}}],s.finishReason="function_call";break;case"mcp_call":s.id=i.id,s.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}}}],s.finishReason="function_call";break;case"function_call":s.id=i.id,s.functionCalls=[{id:i.id,type:"function",function:{name:i.name,params:i.arguments}}],s.finishReason="function_call";break}return{results:[{...s,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=Wi(t.item.content,t.item.id),n.citations=ts(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 s=t.item;n.id=t.item.id,n.functionCalls=[{id:s.id,type:"function",function:{name:"file_search",params:{queries:s.queries||[],results:s.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 s=t.item;n.id=t.item.id,n.functionCalls=[{id:s.id,type:"function",function:{name:"web_search",params:{queries:s.queries||[]}}}]}break;case"computer_call":{let s=t.item;n.id=t.item.id,n.functionCalls=[{id:s.id,type:"function",function:{name:"computer_use",params:{action:s.action||{}}}}]}break;case"code_interpreter_call":{let s=t.item;n.id=t.item.id,n.functionCalls=[{id:s.id,type:"function",function:{name:"code_interpreter",params:{code:s.code||"",results:s.results}}}]}break;case"image_generation_call":{let s=t.item;n.id=t.item.id,n.functionCalls=[{id:s.id,type:"function",function:{name:"image_generation",params:{result:s.result}}}]}break;case"local_shell_call":{let s=t.item;n.id=t.item.id,n.functionCalls=[{id:s.id,type:"function",function:{name:"local_shell",params:{action:s.action||{}}}}]}break;case"mcp_call":{let s=t.item;n.id=t.item.id,n.functionCalls=[{id:s.id,type:"function",function:{name:"mcp",params:{name:s.name||"",args:s.args||"",serverLabel:s.server_label||"",output:s.output,error:s.error}}}]}break}break;case"response.content_part.added":n.id=t.item_id,n.content=Wi([t.part],t.item_id),n.citations=ts([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 s=ts(t.item.content||[]);s&&(n.citations=s)}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]}},Wi=(o,e)=>{let t=o.filter(n=>n.type==="refusal");if(t.length>0){let n=t.map(r=>r.refusal).join(`
177
- `);throw new Le(n,void 0,e)}return o.filter(n=>n.type==="output_text").map(n=>n.text).join(`
178
- `)};function ts(o){let e=[];for(let t of o??[])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 Lr=()=>({model:"gpt-4o",embedModel:"text-embedding-ada-002",temperature:.7,topP:1,stream:!0}),Dc=()=>({...Lr(),model:"gpt-4o",temperature:.5}),Uc=()=>({...Lr(),model:"gpt-4o",temperature:.9}),Nr=class extends Be{constructor({apiKey:e,config:t,options:n,apiURL:r,modelInfo:s=[],models:i,responsesReqUpdater:a,supportFor:u={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 c=new _n(t,n?.streamingUsage??!0,a),l=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 x={...d};Object.keys(g).length>0&&(x.modelConfig={...d.modelConfig??{},...g});let A=m?.thinking?.thinkingTokenBudget;if(typeof A=="number"){let h=[["minimal",200],["low",800],["medium",5e3],["high",1e4],["highest",24500]],y="minimal",T=Number.POSITIVE_INFINITY;for(let[C,R]of h){let M=Math.abs(A-R);M<T&&(T=M,y=C)}x.thinkingTokenBudget=y}return m?.thinking?.includeThoughts!==void 0&&(x.showThoughts=!!m.thinking.includeThoughts),x});super(c,{name:"OpenAI",apiURL:r||"https://api.openai.com/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:s,defaults:{model:t.model??"gpt-4o",embedModel:t.embedModel??"text-embedding-ada-002"},options:n,supportFor:u,models:l??i})}},Nn=class extends Nr{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:s}){if(!e||e==="")throw new Error("OpenAI API key not set");s=[..._o,...s??[]];let i=a=>{let u=ft({model:a,modelInfo:s,models:r});return{functions:!0,streaming:!0,hasThinkingBudget:u?.supported?.thinkingBudget??!1,hasShowThoughts:u?.supported?.showThoughts??!1,structuredOutputs:u?.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:{...Lr(),...t},options:n,modelInfo:s,models:r,supportFor:i})}};var Ki=()=>structuredClone({model:"openrouter/auto",...Se()}),Ln=class extends Ge{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:s,referer:i,title:a}){if(!e||e==="")throw new Error("OpenRouter API key not set");let u={...Ki(),...t},c={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=s??[];super({apiKey:e,config:u,options:n,apiURL:"https://openrouter.ai/api/v1",modelInfo:l,models:r,supportFor:c}),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 ns(o,e,t={}){if(typeof o=="string")return[{type:"text",text:o}];if(!Array.isArray(o))return[{type:"text",text:String(o)}];let n=e.getFeatures(),r=[];for(let s of o)try{switch(s.type){case"text":r.push({type:"text",text:s.text});break;case"image":if(n.media.images.supported)s.altText?r.push({type:"text",text:`[Image: ${s.altText}]`}):r.push({type:"text",text:"[Image content]"});else if(s.altText)r.push({type:"text",text:s.altText});else if(t.imageToText)try{let i=await t.imageToText(s.image);r.push({type:"text",text:i})}catch(i){throw new Rt(i,"image","vision analysis")}else switch(t.fallbackBehavior){case"error":throw new xt("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)s.transcription?r.push({type:"text",text:s.transcription}):r.push({type:"text",text:"[Audio content]"});else if(s.transcription)r.push({type:"text",text:s.transcription});else if(t.audioToText)try{let i=await t.audioToText(s.data,s.format);r.push({type:"text",text:i})}catch(i){throw new Rt(i,"audio","transcription")}else switch(t.fallbackBehavior){case"error":throw new xt("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)s.extractedText?r.push({type:"text",text:s.extractedText}):r.push({type:"text",text:`[File: ${s.filename}]`});else if(s.extractedText)r.push({type:"text",text:s.extractedText});else if(t.fileToText)try{let i=await t.fileToText(s.data,s.mimeType);r.push({type:"text",text:i})}catch(i){throw new Rt(i,"file","text extraction")}else switch(t.fallbackBehavior){case"error":throw new xt("Files",e.getName(),!1);case"skip":continue;default:r.push({type:"text",text:`[File: ${s.filename} - content not accessible by this provider]`})}break;case"url":if(n.media.urls.supported)s.cachedContent?r.push({type:"text",text:s.cachedContent}):r.push({type:"text",text:`[Link: ${s.url}${s.title?` - ${s.title}`:""}]`});else if(s.cachedContent)r.push({type:"text",text:s.cachedContent});else if(t.urlToText)try{let i=await t.urlToText(s.url);r.push({type:"text",text:i})}catch(i){throw new Rt(i,"url","content fetching")}else switch(t.fallbackBehavior){case"error":throw new xt("URLs",e.getName(),!1);case"skip":continue;case"degrade":r.push({type:"text",text:`[Link: ${s.url}${s.title?` - ${s.title}`:""}]`})}break;default:typeof s=="object"&&s.text?r.push({type:"text",text:s.text}):r.push({type:"text",text:String(s)})}}catch(i){throw i instanceof xt||i instanceof Rt?i:new Rt(i,s.type||"unknown","content processing")}return r}function Gc(o){let e=!1,t=!1,n=!1,r=!1;for(let s of o)if(s.role==="user"&&Array.isArray(s.content))for(let i of s.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 $r=(n=>(n.RekaCore="reka-core",n.RekaFlash="reka-flash",n.RekaEdge="reka-edge",n))($r||{});var rs=[{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 Dr=()=>structuredClone({model:"reka-core",...Se()}),jc=()=>structuredClone({...Dr(),model:"reka-core"}),zc=()=>structuredClone({model:"reka-core",...He()}),qc=()=>({...Dr(),model:"reka-flash"}),Vi=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=Tm(e),s=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,...s?{frequency_penalty:s}:{},...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 u=Bc(i.finish_reason),c;return typeof i.message.content=="string"?c=i.message.content:c=i.message.content.text,{index:a,id:`${t}`,content:c,finishReason:u}}),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 u=Bc(i.finish_reason),c;return typeof i.chunk.content=="string"?c=i.chunk.content:c=i.chunk.content.text,{index:a,id:`${t}`,content:c,finishReason:u}})}}},Bc=o=>{switch(o){case"stop":return"stop";case"context":return"length";case"length":return"length"}};function Tm(o){return o.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 $n=class extends Be{constructor({apiKey:e,config:t,options:n,apiURL:r,modelInfo:s=rs,models:i}){if(!e||e==="")throw new Error("Reka API key not set");let a={...Dr(),...t},u=new Vi(a);super(u,{name:"Reka",apiURL:r||"https://api.reka.ai/v1/chat",headers:async()=>({"X-Api-Key":e}),modelInfo:s,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 os=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(s){if(s instanceof xt&&t.fallbackProviders?.length)return await this.tryFallbackProviders(e,t.fallbackProviders,t);throw s}}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},s=[];for(let i of e.chatPrompt)if(i.role==="user"&&Array.isArray(i.content)){let a=await ns(i.content,t,r);a.every(c=>c.type==="text")&&a.length===1?s.push({...i,content:a[0].text}):s.push({...i,content:a.map(c=>({type:"text",text:c.text}))})}else s.push(i);return{...e,chatPrompt:s}}async selectProviderWithDegradation(e,t){let n=on(e),r=[],s=[],i=[];try{let a=Go(e,this.providers,{requireExactMatch:t.requireExactMatch??this.config.capability.requireExactMatch,allowDegradation:t.allowDegradation??this.config.capability.allowDegradation}),u=a.getFeatures();return n.hasImages&&!u.media.images.supported&&(s.push("Images will be converted to text descriptions"),r.push("Image-to-text conversion")),n.hasAudio&&!u.media.audio.supported&&(s.push("Audio will be transcribed to text"),r.push("Audio-to-text transcription")),n.hasFiles&&!u.media.files.supported&&(s.push("File content will be extracted to text"),r.push("File-to-text extraction")),n.hasUrls&&!u.media.urls.supported&&(s.push("URL content will be pre-fetched"),r.push("URL content fetching")),n.requiresStreaming&&!u.streaming&&i.push("Streaming not supported - will use non-streaming mode"),n.requiresCaching&&!u.caching.supported&&i.push("Content caching not supported"),{provider:a,processingApplied:r,degradations:s,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 s={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:s}}catch{}throw new Error("All fallback providers failed")}async getRoutingRecommendation(e){return await this.selectProviderWithDegradation(e,{})}async validateRequest(e){let t=on(e),n=[],r=[];try{let s=await this.selectProviderWithDegradation(e,{});return s.degradations.length>0&&(n.push(...s.degradations),r.push("Consider using a provider that natively supports all media types")),s.warnings.length>0&&n.push(...s.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||s.degradations.length>0,issues:n,recommendations:r}}catch(s){return{canHandle:!1,issues:[`Cannot route request: ${s instanceof Error?s.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 Ur=(h=>(h.KimiK25="moonshotai/Kimi-K2.5",h.KimiK2Instruct0905="moonshotai/Kimi-K2-Instruct-0905",h.KimiK2Thinking="moonshotai/Kimi-K2-Thinking",h.DeepSeekV31="deepseek-ai/DeepSeek-V3.1",h.DeepSeekR1="deepseek-ai/DeepSeek-R1",h.GPTOSS120B="openai/gpt-oss-120b",h.GPTOSS20B="openai/gpt-oss-20b",h.Qwen35_397B="Qwen/Qwen3.5-397B-A17B",h.Qwen3CoderNext="Qwen/Qwen3-Coder-Next-FP8",h.Qwen3Coder480B="Qwen/Qwen3-Coder-480B-A35B-Instruct-FP8",h.Qwen3_235BInstruct2507="Qwen/Qwen3-235B-A22B-Instruct-2507-tput",h.Qwen3_235BThinking2507="Qwen/Qwen3-235B-A22B-Thinking-2507",h.Qwen3Next80BInstruct="Qwen/Qwen3-Next-80B-A3B-Instruct",h.Qwen3Next80BThinking="Qwen/Qwen3-Next-80B-A3B-Thinking",h.GLM5="zai-org/GLM-5",h.GLM47="zai-org/GLM-4.7",h.Llama4Maverick="meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8",h.Llama33_70B="meta-llama/Llama-3.3-70B-Instruct-Turbo",h))(Ur||{});var ss=[{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 Ji=()=>structuredClone({model:"meta-llama/Llama-3.3-70B-Instruct-Turbo",...Se()}),Dn=class extends Ge{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:s}){if(!e||e==="")throw new Error("Together API key not set");let i={...Ji(),...t};s=[...ss,...s??[]];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:s,models:r,supportFor:a}),super.setName("Together")}};var Gr=(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))(Gr||{});var is=[{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 Yi=()=>structuredClone({model:"Llama-3.2-3B-Instruct-q4f32_1-MLC",...Se()}),Hc=()=>structuredClone({model:"Llama-3.2-3B-Instruct-q4f32_1-MLC",...He()}),Qi=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 u="";typeof a.content=="string"?u=a.content:Array.isArray(a.content)&&(u=a.content.filter(l=>l.type==="text").map(l=>l.text).join(`
179
- `));let c={role:a.role,content:u};return a.role==="assistant"&&a.functionCalls?.length?{...c,tool_calls:a.functionCalls.map(l=>({id:l.id,type:"function",function:{name:l.function.name,arguments:typeof l.function.params=="string"?l.function.params:JSON.stringify(l.function.params||{})}}))}:c}),r=e.functions?.map(a=>({type:"function",function:{name:a.name,description:a.description,parameters:a.parameters||{type:"object",properties:{}}}})),s={name:"/chat/completions",localCall:async(a,u)=>{try{let c=await this.engine.chat.completions.create({...a,stream:u||!1});return u?new ReadableStream({async start(l){try{for await(let p of c)l.enqueue(p);l.close()}catch(p){l.error(p)}}}):c}catch(c){throw new Error(`WebLLM API error: ${c}`)}}},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[s,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 s="stop";switch(n.finish_reason){case"stop":s="stop";break;case"length":s="length";break;case"tool_calls":s="function_call";break;case"content_filter":s="content_filter";break;default:s="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:s}}),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 u of r.delta.tool_calls){let c=n.toolCalls[u.index];c?u.function?.arguments&&(c.function.arguments=(c.function?.arguments||"")+u.function.arguments):n.toolCalls[u.index]={id:u.id,type:u.type,function:{name:u.function?.name,arguments:u.function?.arguments||""}}}}e.usage&&(this.tokensUsed={promptTokens:e.usage.prompt_tokens,completionTokens:e.usage.completion_tokens,totalTokens:e.usage.total_tokens});let s;if(r.finish_reason)switch(r.finish_reason){case"stop":s="stop";break;case"length":s="length";break;case"tool_calls":s="function_call";break;case"content_filter":s="content_filter";break;default:s="stop";break}let i=n.toolCalls?.map(u=>({id:u.id||"",type:"function",function:{name:u.function?.name||"",params:u.function?.arguments||""}}));return{results:[{index:0,id:e.id,content:n.content||"",functionCalls:i,finishReason:s}],remoteId:e.id}};createEmbedResp(e){throw new Error("WebLLM does not support embeddings")}},Un=class extends Be{constructor({engine:e,config:t,options:n,models:r}){if(!e)throw new Error("WebLLM engine instance is required");let s={...Yi(),...t},i=new Qi(s,e);super(i,{name:"WebLLM",apiURL:void 0,headers:async()=>({}),modelInfo:is,defaults:{model:s.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 Br=(r=>(r.Grok3="grok-3",r.Grok3Mini="grok-3-mini",r.Grok3Fast="grok-3-fast",r.Grok3MiniFast="grok-3-mini-fast",r))(Br||{}),Xi=(e=>(e.GrokEmbedSmall="grok-embed-small",e))(Xi||{});var as=[{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 us=()=>structuredClone({model:"grok-3-mini",...Se()}),Wc=()=>structuredClone({...us(),model:"grok-3"}),Gn=class extends Ge{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:s}){if(!e||e==="")throw new Error("Grok API key not set");let i={...us(),...t};s=[...as,...s??[]];let a=c=>{let l=ft({model:c,modelInfo:s,models:r});return{functions:!0,streaming:!0,hasThinkingBudget:l?.supported?.thinkingBudget??!1,hasShowThoughts:l?.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}},u=c=>{if(n?.searchParameters){let l=n.searchParameters;return{...c,search_parameters:{mode:l.mode,return_citations:l.returnCitations,from_date:l.fromDate,to_date:l.toDate,max_search_results:l.maxSearchResults,sources:l.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 c};super({apiKey:e,config:i,options:n,apiURL:"https://api.x.ai/v1",modelInfo:s,models:r,supportFor:a,chatReqUpdater:u}),super.setName("Grok")}};function Kc(o){return jr.create(o)}var jr=class o{ai;static create(e){return new o(e)}constructor(e){switch(e.name){case"openai":this.ai=new wn(e);break;case"openai-responses":this.ai=new Nn(e);break;case"azure-openai":this.ai=new Rn(e);break;case"grok":this.ai=new Gn(e);break;case"huggingface":this.ai=new Mn(e);break;case"groq":this.ai=new En(e);break;case"together":this.ai=new Dn(e);break;case"openrouter":this.ai=new Ln(e);break;case"cohere":this.ai=new vn(e);break;case"google-gemini":this.ai=new kn(e);break;case"anthropic":this.ai=new bn(e);break;case"mistral":this.ai=new Pn(e);break;case"deepseek":this.ai=new Sn(e);break;case"ollama":this.ai=new Fn(e);break;case"reka":this.ai=new $n(e);break;case"webllm":this.ai=new Un(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 At=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:ct.SERVER,attributes:{[ye.DB_SYSTEM]:this.name,[ye.DB_OPERATION_NAME]:"upsert",[ye.DB_TABLE]:e.table,[ye.DB_NAMESPACE]:e.namespace,[ye.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:ct.SERVER,attributes:{[ye.DB_SYSTEM]:this.name,[ye.DB_OPERATION_NAME]:"upsert",[ye.DB_TABLE]:e[0].table,[ye.DB_NAMESPACE]:e[0].namespace,[ye.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:ct.SERVER,attributes:{[ye.DB_SYSTEM]:this.name,[ye.DB_OPERATION_NAME]:"upsert",[ye.DB_TABLE]:e.table,[ye.DB_NAMESPACE]:e.namespace,[ye.DB_OPERATION_NAME]:"query"}},async t=>{try{return await this._query(e,{span:t})}finally{t.end()}}):await this._query(e)}};var Zi="https://api.cloudflare.com/client/v4/accounts/",Bn=class extends At{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 tt({url:new URL(`${this.accountId}/vectorize/indexes/${e.table}/upsert`,Zi),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:s})=>s).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,s=await tt({url:new URL(`${this.accountId}/vectorize/indexes/${r}/upsert`,Zi),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(s.errors)throw new Error(`Cloudflare batch upsert failed: ${s.errors.map(({message:i})=>i).join(", ")}`);return{ids:s.result.ids}};query=async(e,t)=>{let n=await tt({url:new URL(`${this.accountId}/vectorize/indexes/${e.table}/query`,Zi),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:s})=>s).join(", ")}`);return{matches:n.result.matches.map(({id:s,score:i,values:a,metadata:u})=>({id:s,score:i,values:a,metadata:u}))}}};var Wt=class extends At{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 s of e){let i=await this.upsert(s,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(([s,i])=>{if(e.values&&i.values){let a=Cm(e.values,i.values);r.push({id:s,score:a,metadata:i.metadata})}}),r.sort((s,i)=>s.score-i.score),e.limit&&(r.length=e.limit),{matches:r}};getDB=()=>structuredClone(this.state);setDB=e=>{this.state=structuredClone(e)};clearDB=()=>{this.state={}}},Cm=(o,e)=>{if(o.length!==e.length)throw new Error("Vectors must be of the same length.");let t=0,n=0,r=0,s=!0,i=!0,a=new Float64Array(o),u=new Float64Array(e);for(let d=0;d<a.length;d++)t+=a[d]*u[d],n+=a[d]*a[d],r+=u[d]*u[d],a[d]!==0&&(s=!1),u[d]!==0&&(i=!1);if(s||i)return 1;let c=Math.sqrt(n),l=Math.sqrt(r);return 1-t/(c*l)};var Im=o=>({namespace:o.namespace,topK:o.limit||10,filter:{},includeValues:!0,includeMetadata:!0,vector:o.values??[],id:o.id}),jn=class extends At{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 tt({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/vectors/upsert",fetch:this.fetch,span:n?.span},e.map(({id:r,values:s=[],metadata:i})=>({id:r,values:s,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 tt({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/query",fetch:this.fetch,span:t?.span},Im(e))).matches.map(({id:s,score:i,values:a,metadata:u})=>({id:s,score:i,metadata:u,values:a}))}}};var zn=class extends At{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 tt({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:s})=>s).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??{}})),s=await tt({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/v1/batch/objects",fetch:this.fetch,span:n?.span},{objects:r});if(s?.some(({result:i})=>i?.errors))throw new Error(`Weaviate batch upsert failed: ${s.map(({result:i})=>i?.errors?.error.map(({message:a})=>a).join(", ")).join(", ")}`);return{ids:s.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
+ `),s=`${n} ${r}`.trim(),i={name:"/models"},a={model:t,inputs:s,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 je{constructor({apiKey:e,config:t,options:n,models:r}){if(!e||e==="")throw new Error("HuggingFace API key not set");let s={...qi(),...t},i=new zi(s);super(i,{name:"HuggingFace",apiURL:"https://api-inference.huggingface.co",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:Jo,defaults:{model:s.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 Nr=(u=>(u.Mistral7B="open-mistral-7b",u.Mistral8x7B="open-mixtral-8x7b",u.MistralSmall="mistral-small-latest",u.MistralNemo="mistral-nemo-latest",u.MistralLarge="mistral-large-latest",u.Codestral="codestral-latest",u.OpenCodestralMamba="open-codestral-mamba",u.OpenMistralNemo="open-mistral-nemo-latest",u))(Nr||{}),Hi=(e=>(e.MistralEmbed="mistral-embed",e))(Hi||{});var Yo=[{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 Xo=()=>structuredClone({model:"mistral-small-latest",...ke(),topP:1}),Dc=()=>structuredClone({...Xo(),model:"mistral-large-latest"}),_n=class extends Ge{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:s}){if(!e||e==="")throw new Error("Mistral API key not set");let i={...Xo(),...t};s=[...Yo,...s??[]];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},u=c=>{let{max_completion_tokens:l,messages:p,...d}=c;return{...d,messages:this.updateMessages(p),max_tokens:l}};super({apiKey:e,config:i,options:n,apiURL:"https://api.mistral.ai/v1",modelInfo:s,models:r,supportFor:a,chatReqUpdater:u}),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(s=>typeof s=="object"&&s!==null&&"image_url"in s?{type:"image_url",image_url:{url:s.image_url?.url}}:s);t.push({...n,content:r})}else t.push(n);return t}};var Zo=class{constructor(e={}){this.config=e;this.config.id=this.config.id??Ze()}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,s)=>r+s,0)/n.length,n.length>0){let r=[...n].sort((a,u)=>a-u),s=Math.max(0,Math.floor(r.length*.95)-1);this.metrics.latency[e].p95=r[s]??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 es=class o{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:s,description:i,isInternal:a}=n;this.services.set(n.key,{service:s,description:i,isInternal:a})}else{let s=n.getModelList();if(!s)throw new Error(`Service ${t} \`${n.getName()}\` has no model list.`);for(let i of s){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 o(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:s,...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:s,...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 Ki=()=>structuredClone({...ke(),model:"nous-hermes2",embedModel:"all-minilm"}),Uc=()=>structuredClone({...He(),model:"nous-hermes2",embedModel:"all-minilm"}),Nn=class extends Ge{constructor({apiKey:e="not-set",url:t="http://localhost:11434/v1",config:n,options:r,models:s}){let i={...Ki(),...n};super({apiKey:e,options:r,config:i,apiURL:t,models:s,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 Tm=o=>["o1","o1-mini","o1-pro","o3","o3-mini","o3-pro","o4-mini"].includes(o),$n=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 s=r;throw new Error(`Unsupported content part: ${JSON.stringify(s)}`)}return n}createResponsesReqInternalInput(e,t=!1){let n=[];for(let r of e){if(t&&r.role==="system")continue;let s;if(r.role==="system"||r.role==="user"||r.role==="assistant"&&r.content)if(typeof r.content=="string")r.role==="system"?s=r.content:r.role==="assistant"?s=[{type:"output_text",text:r.content}]:s=[{type:"input_text",text:r.content}];else if(Array.isArray(r.content))s=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}`);s=""}else r.role,s="";switch(r.role){case"system":n.push({type:"message",role:"system",content:s});break;case"user":n.push({type:"message",role:"user",content:s,name:r.name});break;case"assistant":if(r.content||r.functionCalls){let i={type:"message",role:"assistant",content:""};if(r.content&&(i.content=s),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"},s=null,i=!1;if(e.chatPrompt){for(let A of e.chatPrompt)if(A.role==="system"&&typeof A.content=="string"){s=A.content,i=!0;break}}let a=s??this.config.systemPrompt??null,u=e.functions?.map(A=>({type:"function",name:A.name,description:A.description,parameters:A.parameters??{}})),c=[],l=Tm(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:u?.length?u: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,...l?{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:c.length>0?c: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 x=m;return this.responsesReqUpdater&&(x=this.responsesReqUpdater(x)),[r,x]}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 s={};for(let i of n??[])switch(i.type){case"message":s.id=i.id,s.content=Vi(i.content,t),s.finishReason=i.status==="completed"?"stop":"content_filter",s.citations=ts(i.content);break;case"reasoning":s.id=i.id,i.encrypted_content?s.thought=i.encrypted_content:s.thought=i.summary.map(a=>typeof a=="object"?JSON.stringify(a):a).join(`
176
+ `);break;case"file_search_call":s.id=i.id,s.functionCalls=[{id:i.id,type:"function",function:{name:"file_search",params:{queries:i.queries,results:i.results}}}],s.finishReason="function_call";break;case"web_search_call":s.id=i.id,s.functionCalls=[{id:i.id,type:"function",function:{name:"web_search",params:{queries:i.queries}}}],s.finishReason="function_call";break;case"computer_call":s.id=i.id,s.functionCalls=[{id:i.id,type:"function",function:{name:"computer_use",params:{action:i.action}}}],s.finishReason="function_call";break;case"code_interpreter_call":s.id=i.id,s.functionCalls=[{id:i.id,type:"function",function:{name:"code_interpreter",params:{code:i.code,results:i.results}}}],s.finishReason="function_call";break;case"image_generation_call":s.id=i.id,s.functionCalls=[{id:i.id,type:"function",function:{name:"image_generation",params:{result:i.result}}}],s.finishReason="function_call";break;case"local_shell_call":s.id=i.id,s.functionCalls=[{id:i.id,type:"function",function:{name:"local_shell",params:{action:i.action}}}],s.finishReason="function_call";break;case"mcp_call":s.id=i.id,s.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}}}],s.finishReason="function_call";break;case"function_call":s.id=i.id,s.functionCalls=[{id:i.id,type:"function",function:{name:i.name,params:i.arguments}}],s.finishReason="function_call";break}return{results:[{...s,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=Vi(t.item.content,t.item.id),n.citations=ts(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 s=t.item;n.id=t.item.id,n.functionCalls=[{id:s.id,type:"function",function:{name:"file_search",params:{queries:s.queries||[],results:s.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 s=t.item;n.id=t.item.id,n.functionCalls=[{id:s.id,type:"function",function:{name:"web_search",params:{queries:s.queries||[]}}}]}break;case"computer_call":{let s=t.item;n.id=t.item.id,n.functionCalls=[{id:s.id,type:"function",function:{name:"computer_use",params:{action:s.action||{}}}}]}break;case"code_interpreter_call":{let s=t.item;n.id=t.item.id,n.functionCalls=[{id:s.id,type:"function",function:{name:"code_interpreter",params:{code:s.code||"",results:s.results}}}]}break;case"image_generation_call":{let s=t.item;n.id=t.item.id,n.functionCalls=[{id:s.id,type:"function",function:{name:"image_generation",params:{result:s.result}}}]}break;case"local_shell_call":{let s=t.item;n.id=t.item.id,n.functionCalls=[{id:s.id,type:"function",function:{name:"local_shell",params:{action:s.action||{}}}}]}break;case"mcp_call":{let s=t.item;n.id=t.item.id,n.functionCalls=[{id:s.id,type:"function",function:{name:"mcp",params:{name:s.name||"",args:s.args||"",serverLabel:s.server_label||"",output:s.output,error:s.error}}}]}break}break;case"response.content_part.added":n.id=t.item_id,n.content=Vi([t.part],t.item_id),n.citations=ts([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 s=ts(t.item.content||[]);s&&(n.citations=s)}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]}},Vi=(o,e)=>{let t=o.filter(n=>n.type==="refusal");if(t.length>0){let n=t.map(r=>r.refusal).join(`
177
+ `);throw new $e(n,void 0,e)}return o.filter(n=>n.type==="output_text").map(n=>n.text).join(`
178
+ `)};function ts(o){let e=[];for(let t of o??[])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 Lr=()=>({model:"gpt-4o",embedModel:"text-embedding-ada-002",temperature:.7,topP:1,stream:!0}),Gc=()=>({...Lr(),model:"gpt-4o",temperature:.5}),jc=()=>({...Lr(),model:"gpt-4o",temperature:.9}),$r=class extends je{constructor({apiKey:e,config:t,options:n,apiURL:r,modelInfo:s=[],models:i,responsesReqUpdater:a,supportFor:u={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 c=new $n(t,n?.streamingUsage??!0,a),l=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 x={...d};Object.keys(g).length>0&&(x.modelConfig={...d.modelConfig??{},...g});let A=m?.thinking?.thinkingTokenBudget;if(typeof A=="number"){let h=[["minimal",200],["low",800],["medium",5e3],["high",1e4],["highest",24500]],y="minimal",C=Number.POSITIVE_INFINITY;for(let[I,R]of h){let M=Math.abs(A-R);M<C&&(C=M,y=I)}x.thinkingTokenBudget=y}return m?.thinking?.includeThoughts!==void 0&&(x.showThoughts=!!m.thinking.includeThoughts),x});super(c,{name:"OpenAI",apiURL:r||"https://api.openai.com/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:s,defaults:{model:t.model??"gpt-4o",embedModel:t.embedModel??"text-embedding-ada-002"},options:n,supportFor:u,models:l??i})}},Ln=class extends $r{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:s}){if(!e||e==="")throw new Error("OpenAI API key not set");s=[..._o,...s??[]];let i=a=>{let u=ft({model:a,modelInfo:s,models:r});return{functions:!0,streaming:!0,hasThinkingBudget:u?.supported?.thinkingBudget??!1,hasShowThoughts:u?.supported?.showThoughts??!1,structuredOutputs:u?.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:{...Lr(),...t},options:n,modelInfo:s,models:r,supportFor:i})}};var Wi=()=>structuredClone({model:"openrouter/auto",...ke()}),Dn=class extends Ge{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:s,referer:i,title:a}){if(!e||e==="")throw new Error("OpenRouter API key not set");let u={...Wi(),...t},c={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=s??[];super({apiKey:e,config:u,options:n,apiURL:"https://openrouter.ai/api/v1",modelInfo:l,models:r,supportFor:c}),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 ns(o,e,t={}){if(typeof o=="string")return[{type:"text",text:o}];if(!Array.isArray(o))return[{type:"text",text:String(o)}];let n=e.getFeatures(),r=[];for(let s of o)try{switch(s.type){case"text":r.push({type:"text",text:s.text});break;case"image":if(n.media.images.supported)s.altText?r.push({type:"text",text:`[Image: ${s.altText}]`}):r.push({type:"text",text:"[Image content]"});else if(s.altText)r.push({type:"text",text:s.altText});else if(t.imageToText)try{let i=await t.imageToText(s.image);r.push({type:"text",text:i})}catch(i){throw new Rt(i,"image","vision analysis")}else switch(t.fallbackBehavior){case"error":throw new xt("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)s.transcription?r.push({type:"text",text:s.transcription}):r.push({type:"text",text:"[Audio content]"});else if(s.transcription)r.push({type:"text",text:s.transcription});else if(t.audioToText)try{let i=await t.audioToText(s.data,s.format);r.push({type:"text",text:i})}catch(i){throw new Rt(i,"audio","transcription")}else switch(t.fallbackBehavior){case"error":throw new xt("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)s.extractedText?r.push({type:"text",text:s.extractedText}):r.push({type:"text",text:`[File: ${s.filename}]`});else if(s.extractedText)r.push({type:"text",text:s.extractedText});else if(t.fileToText)try{let i=await t.fileToText(s.data,s.mimeType);r.push({type:"text",text:i})}catch(i){throw new Rt(i,"file","text extraction")}else switch(t.fallbackBehavior){case"error":throw new xt("Files",e.getName(),!1);case"skip":continue;default:r.push({type:"text",text:`[File: ${s.filename} - content not accessible by this provider]`})}break;case"url":if(n.media.urls.supported)s.cachedContent?r.push({type:"text",text:s.cachedContent}):r.push({type:"text",text:`[Link: ${s.url}${s.title?` - ${s.title}`:""}]`});else if(s.cachedContent)r.push({type:"text",text:s.cachedContent});else if(t.urlToText)try{let i=await t.urlToText(s.url);r.push({type:"text",text:i})}catch(i){throw new Rt(i,"url","content fetching")}else switch(t.fallbackBehavior){case"error":throw new xt("URLs",e.getName(),!1);case"skip":continue;case"degrade":r.push({type:"text",text:`[Link: ${s.url}${s.title?` - ${s.title}`:""}]`})}break;default:typeof s=="object"&&s.text?r.push({type:"text",text:s.text}):r.push({type:"text",text:String(s)})}}catch(i){throw i instanceof xt||i instanceof Rt?i:new Rt(i,s.type||"unknown","content processing")}return r}function Bc(o){let e=!1,t=!1,n=!1,r=!1;for(let s of o)if(s.role==="user"&&Array.isArray(s.content))for(let i of s.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 Dr=(n=>(n.RekaCore="reka-core",n.RekaFlash="reka-flash",n.RekaEdge="reka-edge",n))(Dr||{});var rs=[{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 Ur=()=>structuredClone({model:"reka-core",...ke()}),qc=()=>structuredClone({...Ur(),model:"reka-core"}),Hc=()=>structuredClone({model:"reka-core",...He()}),Kc=()=>({...Ur(),model:"reka-flash"}),Ji=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=wm(e),s=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,...s?{frequency_penalty:s}:{},...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 u=zc(i.finish_reason),c;return typeof i.message.content=="string"?c=i.message.content:c=i.message.content.text,{index:a,id:`${t}`,content:c,finishReason:u}}),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 u=zc(i.finish_reason),c;return typeof i.chunk.content=="string"?c=i.chunk.content:c=i.chunk.content.text,{index:a,id:`${t}`,content:c,finishReason:u}})}}},zc=o=>{switch(o){case"stop":return"stop";case"context":return"length";case"length":return"length"}};function wm(o){return o.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 Un=class extends je{constructor({apiKey:e,config:t,options:n,apiURL:r,modelInfo:s=rs,models:i}){if(!e||e==="")throw new Error("Reka API key not set");let a={...Ur(),...t},u=new Ji(a);super(u,{name:"Reka",apiURL:r||"https://api.reka.ai/v1/chat",headers:async()=>({"X-Api-Key":e}),modelInfo:s,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 os=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(s){if(s instanceof xt&&t.fallbackProviders?.length)return await this.tryFallbackProviders(e,t.fallbackProviders,t);throw s}}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},s=[];for(let i of e.chatPrompt)if(i.role==="user"&&Array.isArray(i.content)){let a=await ns(i.content,t,r);a.every(c=>c.type==="text")&&a.length===1?s.push({...i,content:a[0].text}):s.push({...i,content:a.map(c=>({type:"text",text:c.text}))})}else s.push(i);return{...e,chatPrompt:s}}async selectProviderWithDegradation(e,t){let n=sn(e),r=[],s=[],i=[];try{let a=Go(e,this.providers,{requireExactMatch:t.requireExactMatch??this.config.capability.requireExactMatch,allowDegradation:t.allowDegradation??this.config.capability.allowDegradation}),u=a.getFeatures();return n.hasImages&&!u.media.images.supported&&(s.push("Images will be converted to text descriptions"),r.push("Image-to-text conversion")),n.hasAudio&&!u.media.audio.supported&&(s.push("Audio will be transcribed to text"),r.push("Audio-to-text transcription")),n.hasFiles&&!u.media.files.supported&&(s.push("File content will be extracted to text"),r.push("File-to-text extraction")),n.hasUrls&&!u.media.urls.supported&&(s.push("URL content will be pre-fetched"),r.push("URL content fetching")),n.requiresStreaming&&!u.streaming&&i.push("Streaming not supported - will use non-streaming mode"),n.requiresCaching&&!u.caching.supported&&i.push("Content caching not supported"),{provider:a,processingApplied:r,degradations:s,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 s={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:s}}catch{}throw new Error("All fallback providers failed")}async getRoutingRecommendation(e){return await this.selectProviderWithDegradation(e,{})}async validateRequest(e){let t=sn(e),n=[],r=[];try{let s=await this.selectProviderWithDegradation(e,{});return s.degradations.length>0&&(n.push(...s.degradations),r.push("Consider using a provider that natively supports all media types")),s.warnings.length>0&&n.push(...s.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||s.degradations.length>0,issues:n,recommendations:r}}catch(s){return{canHandle:!1,issues:[`Cannot route request: ${s instanceof Error?s.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 Gr=(h=>(h.KimiK25="moonshotai/Kimi-K2.5",h.KimiK2Instruct0905="moonshotai/Kimi-K2-Instruct-0905",h.KimiK2Thinking="moonshotai/Kimi-K2-Thinking",h.DeepSeekV31="deepseek-ai/DeepSeek-V3.1",h.DeepSeekR1="deepseek-ai/DeepSeek-R1",h.GPTOSS120B="openai/gpt-oss-120b",h.GPTOSS20B="openai/gpt-oss-20b",h.Qwen35_397B="Qwen/Qwen3.5-397B-A17B",h.Qwen3CoderNext="Qwen/Qwen3-Coder-Next-FP8",h.Qwen3Coder480B="Qwen/Qwen3-Coder-480B-A35B-Instruct-FP8",h.Qwen3_235BInstruct2507="Qwen/Qwen3-235B-A22B-Instruct-2507-tput",h.Qwen3_235BThinking2507="Qwen/Qwen3-235B-A22B-Thinking-2507",h.Qwen3Next80BInstruct="Qwen/Qwen3-Next-80B-A3B-Instruct",h.Qwen3Next80BThinking="Qwen/Qwen3-Next-80B-A3B-Thinking",h.GLM5="zai-org/GLM-5",h.GLM47="zai-org/GLM-4.7",h.Llama4Maverick="meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8",h.Llama33_70B="meta-llama/Llama-3.3-70B-Instruct-Turbo",h))(Gr||{});var ss=[{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 Qi=()=>structuredClone({model:"meta-llama/Llama-3.3-70B-Instruct-Turbo",...ke()}),Gn=class extends Ge{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:s}){if(!e||e==="")throw new Error("Together API key not set");let i={...Qi(),...t};s=[...ss,...s??[]];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:s,models:r,supportFor:a}),super.setName("Together")}};var jr=(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))(jr||{});var is=[{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 Xi=()=>structuredClone({model:"Llama-3.2-3B-Instruct-q4f32_1-MLC",...ke()}),Vc=()=>structuredClone({model:"Llama-3.2-3B-Instruct-q4f32_1-MLC",...He()}),Yi=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 u="";typeof a.content=="string"?u=a.content:Array.isArray(a.content)&&(u=a.content.filter(l=>l.type==="text").map(l=>l.text).join(`
179
+ `));let c={role:a.role,content:u};return a.role==="assistant"&&a.functionCalls?.length?{...c,tool_calls:a.functionCalls.map(l=>({id:l.id,type:"function",function:{name:l.function.name,arguments:typeof l.function.params=="string"?l.function.params:JSON.stringify(l.function.params||{})}}))}:c}),r=e.functions?.map(a=>({type:"function",function:{name:a.name,description:a.description,parameters:a.parameters||{type:"object",properties:{}}}})),s={name:"/chat/completions",localCall:async(a,u)=>{try{let c=await this.engine.chat.completions.create({...a,stream:u||!1});return u?new ReadableStream({async start(l){try{for await(let p of c)l.enqueue(p);l.close()}catch(p){l.error(p)}}}):c}catch(c){throw new Error(`WebLLM API error: ${c}`)}}},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[s,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 s="stop";switch(n.finish_reason){case"stop":s="stop";break;case"length":s="length";break;case"tool_calls":s="function_call";break;case"content_filter":s="content_filter";break;default:s="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:s}}),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 u of r.delta.tool_calls){let c=n.toolCalls[u.index];c?u.function?.arguments&&(c.function.arguments=(c.function?.arguments||"")+u.function.arguments):n.toolCalls[u.index]={id:u.id,type:u.type,function:{name:u.function?.name,arguments:u.function?.arguments||""}}}}e.usage&&(this.tokensUsed={promptTokens:e.usage.prompt_tokens,completionTokens:e.usage.completion_tokens,totalTokens:e.usage.total_tokens});let s;if(r.finish_reason)switch(r.finish_reason){case"stop":s="stop";break;case"length":s="length";break;case"tool_calls":s="function_call";break;case"content_filter":s="content_filter";break;default:s="stop";break}let i=n.toolCalls?.map(u=>({id:u.id||"",type:"function",function:{name:u.function?.name||"",params:u.function?.arguments||""}}));return{results:[{index:0,id:e.id,content:n.content||"",functionCalls:i,finishReason:s}],remoteId:e.id}};createEmbedResp(e){throw new Error("WebLLM does not support embeddings")}},jn=class extends je{constructor({engine:e,config:t,options:n,models:r}){if(!e)throw new Error("WebLLM engine instance is required");let s={...Xi(),...t},i=new Yi(s,e);super(i,{name:"WebLLM",apiURL:void 0,headers:async()=>({}),modelInfo:is,defaults:{model:s.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 Br=(r=>(r.Grok3="grok-3",r.Grok3Mini="grok-3-mini",r.Grok3Fast="grok-3-fast",r.Grok3MiniFast="grok-3-mini-fast",r))(Br||{}),Zi=(e=>(e.GrokEmbedSmall="grok-embed-small",e))(Zi||{});var as=[{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 us=()=>structuredClone({model:"grok-3-mini",...ke()}),Wc=()=>structuredClone({...us(),model:"grok-3"}),Bn=class extends Ge{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:s}){if(!e||e==="")throw new Error("Grok API key not set");let i={...us(),...t};s=[...as,...s??[]];let a=c=>{let l=ft({model:c,modelInfo:s,models:r});return{functions:!0,streaming:!0,hasThinkingBudget:l?.supported?.thinkingBudget??!1,hasShowThoughts:l?.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}},u=c=>{if(n?.searchParameters){let l=n.searchParameters;return{...c,search_parameters:{mode:l.mode,return_citations:l.returnCitations,from_date:l.fromDate,to_date:l.toDate,max_search_results:l.maxSearchResults,sources:l.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 c};super({apiKey:e,config:i,options:n,apiURL:"https://api.x.ai/v1",modelInfo:s,models:r,supportFor:a,chatReqUpdater:u}),super.setName("Grok")}};function Jc(o){return zr.create(o)}var zr=class o{ai;static create(e){return new o(e)}constructor(e){switch(e.name){case"openai":this.ai=new vn(e);break;case"openai-responses":this.ai=new Ln(e);break;case"azure-openai":this.ai=new Sn(e);break;case"grok":this.ai=new Bn(e);break;case"huggingface":this.ai=new Fn(e);break;case"groq":this.ai=new Pn(e);break;case"together":this.ai=new Gn(e);break;case"openrouter":this.ai=new Dn(e);break;case"cohere":this.ai=new kn(e);break;case"google-gemini":this.ai=new En(e);break;case"anthropic":this.ai=new In(e);break;case"mistral":this.ai=new _n(e);break;case"deepseek":this.ai=new On(e);break;case"ollama":this.ai=new Nn(e);break;case"reka":this.ai=new Un(e);break;case"webllm":this.ai=new jn(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 At=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:ct.SERVER,attributes:{[be.DB_SYSTEM]:this.name,[be.DB_OPERATION_NAME]:"upsert",[be.DB_TABLE]:e.table,[be.DB_NAMESPACE]:e.namespace,[be.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:ct.SERVER,attributes:{[be.DB_SYSTEM]:this.name,[be.DB_OPERATION_NAME]:"upsert",[be.DB_TABLE]:e[0].table,[be.DB_NAMESPACE]:e[0].namespace,[be.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:ct.SERVER,attributes:{[be.DB_SYSTEM]:this.name,[be.DB_OPERATION_NAME]:"upsert",[be.DB_TABLE]:e.table,[be.DB_NAMESPACE]:e.namespace,[be.DB_OPERATION_NAME]:"query"}},async t=>{try{return await this._query(e,{span:t})}finally{t.end()}}):await this._query(e)}};var ea="https://api.cloudflare.com/client/v4/accounts/",zn=class extends At{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 tt({url:new URL(`${this.accountId}/vectorize/indexes/${e.table}/upsert`,ea),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:s})=>s).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,s=await tt({url:new URL(`${this.accountId}/vectorize/indexes/${r}/upsert`,ea),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(s.errors)throw new Error(`Cloudflare batch upsert failed: ${s.errors.map(({message:i})=>i).join(", ")}`);return{ids:s.result.ids}};query=async(e,t)=>{let n=await tt({url:new URL(`${this.accountId}/vectorize/indexes/${e.table}/query`,ea),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:s})=>s).join(", ")}`);return{matches:n.result.matches.map(({id:s,score:i,values:a,metadata:u})=>({id:s,score:i,values:a,metadata:u}))}}};var Kt=class extends At{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 s of e){let i=await this.upsert(s,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(([s,i])=>{if(e.values&&i.values){let a=Rm(e.values,i.values);r.push({id:s,score:a,metadata:i.metadata})}}),r.sort((s,i)=>s.score-i.score),e.limit&&(r.length=e.limit),{matches:r}};getDB=()=>structuredClone(this.state);setDB=e=>{this.state=structuredClone(e)};clearDB=()=>{this.state={}}},Rm=(o,e)=>{if(o.length!==e.length)throw new Error("Vectors must be of the same length.");let t=0,n=0,r=0,s=!0,i=!0,a=new Float64Array(o),u=new Float64Array(e);for(let d=0;d<a.length;d++)t+=a[d]*u[d],n+=a[d]*a[d],r+=u[d]*u[d],a[d]!==0&&(s=!1),u[d]!==0&&(i=!1);if(s||i)return 1;let c=Math.sqrt(n),l=Math.sqrt(r);return 1-t/(c*l)};var vm=o=>({namespace:o.namespace,topK:o.limit||10,filter:{},includeValues:!0,includeMetadata:!0,vector:o.values??[],id:o.id}),qn=class extends At{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 tt({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/vectors/upsert",fetch:this.fetch,span:n?.span},e.map(({id:r,values:s=[],metadata:i})=>({id:r,values:s,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 tt({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/query",fetch:this.fetch,span:t?.span},vm(e))).matches.map(({id:s,score:i,values:a,metadata:u})=>({id:s,score:i,metadata:u,values:a}))}}};var Hn=class extends At{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 tt({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:s})=>s).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??{}})),s=await tt({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/v1/batch/objects",fetch:this.fetch,span:n?.span},{objects:r});if(s?.some(({result:i})=>i?.errors))throw new Error(`Weaviate batch upsert failed: ${s.map(({result:i})=>i?.errors?.error.map(({message:a})=>a).join(", ")).join(", ")}`);return{ids:s.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}'],
@@ -190,9 +190,9 @@ ${c}`:`Assistant: ${u.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 s=r.data.Get[e.table];return s?{matches:s.map(a=>({id:a.id,score:1,metadata:a}))}:{matches:[]}}};var cs=class{db;constructor(e){switch(e.name){case"weaviate":this.db=new zn(e);break;case"pinecone":this.db=new jn(e);break;case"cloudflare":this.db=new Bn(e);break;case"memory":this.db=new Wt(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 ea="_internal",ls=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 s=r.data.Get[e.table];return s?{matches:s.map(a=>({id:a.id,score:1,metadata:a}))}:{matches:[]}}};var cs=class{db;constructor(e){switch(e.name){case"weaviate":this.db=new Hn(e);break;case"pinecone":this.db=new qn(e);break;case"cloudflare":this.db=new zn(e);break;case"memory":this.db=new Kt(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 ta="_internal",ls=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(c=>c.length>0),s=t?.maxWordsPerChunk,i=t?.minWordsPerChunk,a=wm({initialChunks:r,minWordsPerChunk:i,maxWordsPerChunk:s}),u=t?.batchSize??10;for(let c=0;c<a.length;c+=u){let l=a.slice(c,c+u),d=(await this.ai.embed({texts:l},{abortSignal:t?.abortSignal})).embeddings.map((m,g)=>({id:`chunk_${Date.now()+g}`,table:ea,values:m,metadata:{text:l[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[u,c]of r.entries()){let{rewrittenQuery:l}=await this.rewriter.forward(this.ai,{query:c});r[u]=l}let s;typeof r[0]=="string"?s=(await this.ai.embed({texts:r},{abortSignal:n})).embeddings.map(c=>this.db.query({table:ea,values:c})):s=r.map(u=>this.db.query({table:ea,values:u}));let i=await Promise.all(s),a=[];for(let{matches:u}of i){let c=u.filter(d=>d.metadata?.text&&d.metadata?.text.length>0).map(({score:d,metadata:m})=>({score:d,text:m?.text??""})),l=t&&t>1?t/100:t,p=l?Rm(c,l):c;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}},wm=({initialChunks:o,maxWordsPerChunk:e=350,minWordsPerChunk:t=250})=>{let n=[],r="",s=0;return o.forEach(i=>{let a=i.split(/\s+/),u=a.length;if(s+u<=e)r+=`${i}
195
+ `):e,r=this.chunker(n).filter(c=>c.length>0),s=t?.maxWordsPerChunk,i=t?.minWordsPerChunk,a=Sm({initialChunks:r,minWordsPerChunk:i,maxWordsPerChunk:s}),u=t?.batchSize??10;for(let c=0;c<a.length;c+=u){let l=a.slice(c,c+u),d=(await this.ai.embed({texts:l},{abortSignal:t?.abortSignal})).embeddings.map((m,g)=>({id:`chunk_${Date.now()+g}`,table:ta,values:m,metadata:{text:l[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[u,c]of r.entries()){let{rewrittenQuery:l}=await this.rewriter.forward(this.ai,{query:c});r[u]=l}let s;typeof r[0]=="string"?s=(await this.ai.embed({texts:r},{abortSignal:n})).embeddings.map(c=>this.db.query({table:ta,values:c})):s=r.map(u=>this.db.query({table:ta,values:u}));let i=await Promise.all(s),a=[];for(let{matches:u}of i){let c=u.filter(d=>d.metadata?.text&&d.metadata?.text.length>0).map(({score:d,metadata:m})=>({score:d,text:m?.text??""})),l=t&&t>1?t/100:t,p=l?km(c,l):c;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}},Sm=({initialChunks:o,maxWordsPerChunk:e=350,minWordsPerChunk:t=250})=>{let n=[],r="",s=0;return o.forEach(i=>{let a=i.split(/\s+/),u=a.length;if(s+u<=e)r+=`${i}
196
196
 
197
197
  `,s+=u;else if(s>0&&s+u<=e*1.5)r+=`${i}
198
198
 
@@ -200,21 +200,21 @@ ${c}`:`Assistant: ${u.content}`}default:throw new Error("Unknown role")}}).join(
200
200
 
201
201
  `,s+=c.length)}else r=`${i}
202
202
 
203
- `,s=u}),(s>t||n.length===0)&&n.push(r.trim()),n},Rm=(o,e=.1)=>{let t=[...o].sort((r,s)=>r.score-s.score),n=Math.ceil(t.length*e);return t.slice(0,n)};var zr=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,...s})=>({index:r,value:structuredClone(s)})),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:s,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:s})}]});return}let u=a.chat.find(c=>c.index===i);if(!u){a.chat.push({index:i,value:structuredClone({content:e,name:t,functionCalls:n,thought:r,thoughtBlocks:s})});return}if(typeof e=="string"&&e.trim()!==""&&(u.value.content=e),typeof t=="string"&&t.trim()!==""&&(u.value.name=t),Array.isArray(n)&&n.length>0&&(u.value.functionCalls=n),typeof r=="string"&&r.trim()!==""){let c=u.value.thought;u.value.thought=typeof c=="string"?c+r:r}if(Array.isArray(s)&&s.length>0){let c=u.value.thoughtBlocks??[];for(let l of s){let p=c.length>0?c[c.length-1]:void 0;!l.signature&&l.data?p&&!p.signature?(p.data=(p.data??"")+l.data,l.encrypted&&(p.encrypted=!0)):c.push(structuredClone(l)):l.signature?p&&!p.signature?(p.data=(p.data??"")+l.data,p.signature=l.signature,l.encrypted&&(p.encrypted=!0)):c.push(structuredClone(l)):c.length===0&&c.push(structuredClone(l))}u.value.thoughtBlocks=c,c.length>0&&(u.value.thought=c.map(l=>l.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,s)=>(r.tags?.includes(e)&&n.push(s),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 s;n==="function"?s=r.filter(i=>i.index===e).map(i=>i.value):s=r.find(i=>i.index===e)?.value,Array.isArray(s)&&s.length>0?t.push(...s.map(i=>({...i,role:n}))):typeof s=="object"&&s!==null&&t.push({...s,role:n})}return t}getLast(){return this.data.at(-1)}reset(){this.data=[],this.seenTags=new Set}},qn=class{memories=new Map;defaultMemory;constructor(){this.defaultMemory=new zr}getMemory(e){return e?(this.memories.has(e)||this.memories.set(e,new zr),this.memories.get(e)):this.defaultMemory}addRequest(e,t){for(let n of e)yn(n);this.getMemory(t).addRequest(e,0)}addResponse(e,t){Fo(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 zr):this.defaultMemory.reset()}};function kt(o,e){if(!o&&!e)return;if(!o)return e;if(!e||o===e||o.aborted)return o;if(e.aborted)return e;if(typeof AbortSignal.any=="function")return AbortSignal.any([o,e]);let t=new AbortController,n=()=>{t.abort(o.aborted?o.reason:e.reason),r()},r=()=>{o.removeEventListener("abort",n),e.removeEventListener("abort",n)};return o.addEventListener("abort",n,{once:!0}),e.addEventListener("abort",n,{once:!0}),t.signal}var Pt=class extends Error{constructor({message:e}){super(e),this.name="AxAssertionError"}getFixingInstructions=()=>{let e=[],t=this.message.trim();return e.push({name:"error",title:"Follow these instructions",description:t+(t.endsWith(".")?"":".")}),e};toString(){return`${this.name}: ${this.message}`}[Symbol.for("nodejs.util.inspect.custom")](e,t){return this.toString()}},Hn=async(o,e)=>{for(let t of o){let{fn:n,message:r}=t,s=await n(e);if(s!==void 0){if(typeof s=="string")throw new Pt({message:s});if(!s)throw r?new Pt({message:r}):new Error("Assertion Failed: No message provided for assertion")}}},ta=async(o,e,t,n=!1)=>{if(!e.currField||e.s===-1||!o||o.length===0)return;let r=o.filter(i=>i.fieldName===e.currField?.name);if(r.length===0)return;let s=t.substring(e.s);for(let i of r){let{message:a,fn:u}=i,c=await u(s,n);if(c!==void 0){if(typeof c=="string")throw new Pt({message:c});if(!c&&a)throw new Pt({message:a})}}};var na={enabled:!0,enabledCategories:["generation","streaming","functions","errors","performance"],maxLabelLength:100,samplingRate:1},qr,ra=o=>{if(qr)return qr;let e=o??fe.meter;if(e)return qr=vm(e),qr};var Vc=()=>{let o=[];return fe.meter||o.push("Global meter not initialized"),!qr&&fe.meter&&o.push("Metrics instruments not created despite available meter"),{healthy:o.length===0,issues:o}},vm=o=>({generationLatencyHistogram:o.createHistogram("ax_gen_generation_duration_ms",{description:"End-to-end duration of AxGen generation requests",unit:"ms"}),generationRequestsCounter:o.createCounter("ax_gen_generation_requests_total",{description:"Total number of AxGen generation requests"}),generationErrorsCounter:o.createCounter("ax_gen_generation_errors_total",{description:"Total number of failed AxGen generations"}),multiStepGenerationsCounter:o.createCounter("ax_gen_multistep_generations_total",{description:"Total number of generations that required multiple steps"}),stepsPerGenerationHistogram:o.createHistogram("ax_gen_steps_per_generation",{description:"Number of steps taken per generation"}),maxStepsReachedCounter:o.createCounter("ax_gen_max_steps_reached_total",{description:"Total number of generations that hit max steps limit"}),validationErrorsCounter:o.createCounter("ax_gen_validation_errors_total",{description:"Total number of validation errors encountered"}),assertionErrorsCounter:o.createCounter("ax_gen_assertion_errors_total",{description:"Total number of assertion errors encountered"}),errorCorrectionAttemptsHistogram:o.createHistogram("ax_gen_error_correction_attempts",{description:"Number of error correction attempts per generation"}),errorCorrectionSuccessCounter:o.createCounter("ax_gen_error_correction_success_total",{description:"Total number of successful error corrections"}),errorCorrectionFailureCounter:o.createCounter("ax_gen_error_correction_failure_total",{description:"Total number of failed error corrections"}),maxRetriesReachedCounter:o.createCounter("ax_gen_max_retries_reached_total",{description:"Total number of generations that hit max retries limit"}),functionsEnabledGenerationsCounter:o.createCounter("ax_gen_functions_enabled_generations_total",{description:"Total number of generations with functions enabled"}),functionCallStepsCounter:o.createCounter("ax_gen_function_call_steps_total",{description:"Total number of steps that included function calls"}),functionsExecutedPerGenerationHistogram:o.createHistogram("ax_gen_functions_executed_per_generation",{description:"Number of unique functions executed per generation"}),functionErrorCorrectionCounter:o.createCounter("ax_gen_function_error_correction_total",{description:"Total number of function-related error corrections"}),fieldProcessorsExecutedCounter:o.createCounter("ax_gen_field_processors_executed_total",{description:"Total number of field processors executed"}),streamingFieldProcessorsExecutedCounter:o.createCounter("ax_gen_streaming_field_processors_executed_total",{description:"Total number of streaming field processors executed"}),streamingGenerationsCounter:o.createCounter("ax_gen_streaming_generations_total",{description:"Total number of streaming generations"}),streamingDeltasEmittedCounter:o.createCounter("ax_gen_streaming_deltas_emitted_total",{description:"Total number of streaming deltas emitted"}),streamingFinalizationLatencyHistogram:o.createHistogram("ax_gen_streaming_finalization_duration_ms",{description:"Duration of streaming response finalization",unit:"ms"}),samplesGeneratedHistogram:o.createHistogram("ax_gen_samples_generated",{description:"Number of samples generated per request"}),resultPickerUsageCounter:o.createCounter("ax_gen_result_picker_usage_total",{description:"Total number of times result picker was used"}),resultPickerLatencyHistogram:o.createHistogram("ax_gen_result_picker_duration_ms",{description:"Duration of result picker execution",unit:"ms"}),inputFieldsGauge:o.createGauge("ax_gen_input_fields",{description:"Number of input fields in signature"}),outputFieldsGauge:o.createGauge("ax_gen_output_fields",{description:"Number of output fields in signature"}),examplesUsedGauge:o.createGauge("ax_gen_examples_used",{description:"Number of examples used in generation"}),demosUsedGauge:o.createGauge("ax_gen_demos_used",{description:"Number of demos used in generation"}),promptRenderLatencyHistogram:o.createHistogram("ax_gen_prompt_render_duration_ms",{description:"Duration of prompt template rendering",unit:"ms"}),extractionLatencyHistogram:o.createHistogram("ax_gen_extraction_duration_ms",{description:"Duration of value extraction from responses",unit:"ms"}),assertionLatencyHistogram:o.createHistogram("ax_gen_assertion_duration_ms",{description:"Duration of assertion checking",unit:"ms"}),stateCreationLatencyHistogram:o.createHistogram("ax_gen_state_creation_duration_ms",{description:"Duration of state creation for multiple samples",unit:"ms"}),memoryUpdateLatencyHistogram:o.createHistogram("ax_gen_memory_update_duration_ms",{description:"Duration of memory updates during generation",unit:"ms"})}),ps=na,Jc=o=>{ps={...ps,...o}},Qc=()=>({...ps}),Ot=o=>{let e={};for(let[t,n]of Object.entries(o))if(n!=null){let r=String(n),s=ps.maxLabelLength;e[t]=r.length>s?r.substring(0,s):r}return e};var Yc=(o,e,t,n,r,s,i)=>{try{let a=Ot({success:t.toString(),...n?{signature:n}:{},...r?{ai_service:r}:{},...s?{model:s}:{},...i});o.generationLatencyHistogram&&o.generationLatencyHistogram.record(e,a),o.generationRequestsCounter&&o.generationRequestsCounter.add(1,a),!t&&o.generationErrorsCounter&&o.generationErrorsCounter.add(1,a)}catch(a){console.warn("Failed to record generation metric:",a)}},ds=(o,e,t,n,r)=>{try{let s=Ot({...n?{signature:n}:{},...r});e>1&&o.multiStepGenerationsCounter&&o.multiStepGenerationsCounter.add(1,s),o.stepsPerGenerationHistogram&&o.stepsPerGenerationHistogram.record(e,s),e>=t&&o.maxStepsReachedCounter&&o.maxStepsReachedCounter.add(1,s)}catch(s){console.warn("Failed to record multi-step metric:",s)}},oa=(o,e,t,n)=>{try{let r=Ot({error_type:e,...t?{signature:t}:{},...n});e==="validation"&&o.validationErrorsCounter&&o.validationErrorsCounter.add(1,r),e==="assertion"&&o.assertionErrorsCounter&&o.assertionErrorsCounter.add(1,r)}catch(r){console.warn("Failed to record validation error metric:",r)}},Xc=(o,e,t)=>{try{let n=Ot({error_type:"refusal",...e?{signature:e}:{},...t});o.validationErrorsCounter&&o.validationErrorsCounter.add(1,n)}catch(n){console.warn("Failed to record refusal error metric:",n)}},sa=(o,e,t,n,r,s)=>{try{let i=Ot({success:t.toString(),...r?{signature:r}:{},...s});o.errorCorrectionAttemptsHistogram&&o.errorCorrectionAttemptsHistogram.record(e,i),t&&o.errorCorrectionSuccessCounter&&o.errorCorrectionSuccessCounter.add(1,i),t||(o.errorCorrectionFailureCounter&&o.errorCorrectionFailureCounter.add(1,i),e>=n&&o.maxRetriesReachedCounter&&o.maxRetriesReachedCounter.add(1,i))}catch(i){console.warn("Failed to record error correction metric:",i)}},Zc=(o,e,t,n,r=!1,s,i)=>{try{let a=Ot({functions_enabled:e.toString(),had_function_calls:n.toString(),...s?{signature:s}:{},...i});e&&o.functionsEnabledGenerationsCounter&&o.functionsEnabledGenerationsCounter.add(1,a),n&&o.functionCallStepsCounter&&o.functionCallStepsCounter.add(1,a),t>0&&o.functionsExecutedPerGenerationHistogram&&o.functionsExecutedPerGenerationHistogram.record(t,a),r&&o.functionErrorCorrectionCounter&&o.functionErrorCorrectionCounter.add(1,a)}catch(a){console.warn("Failed to record function calling metric:",a)}},el=(o,e,t,n,r)=>{try{let s=Ot({...n?{signature:n}:{},...r});e>0&&o.fieldProcessorsExecutedCounter&&o.fieldProcessorsExecutedCounter.add(e,s),t>0&&o.streamingFieldProcessorsExecutedCounter&&o.streamingFieldProcessorsExecutedCounter.add(t,s)}catch(s){console.warn("Failed to record field processing metric:",s)}},tl=(o,e,t,n,r,s)=>{try{let i=Ot({is_streaming:e.toString(),...r?{signature:r}:{},...s});e&&o.streamingGenerationsCounter&&o.streamingGenerationsCounter.add(1,i),t>0&&o.streamingDeltasEmittedCounter&&o.streamingDeltasEmittedCounter.add(t,i),n&&o.streamingFinalizationLatencyHistogram&&o.streamingFinalizationLatencyHistogram.record(n,i)}catch(i){console.warn("Failed to record streaming metric:",i)}},nl=(o,e,t,n,r,s)=>{try{let i=Ot({result_picker_used:t.toString(),...r?{signature:r}:{},...s});o.samplesGeneratedHistogram&&o.samplesGeneratedHistogram.record(e,i),t&&o.resultPickerUsageCounter&&o.resultPickerUsageCounter.add(1,i),n&&o.resultPickerLatencyHistogram&&o.resultPickerLatencyHistogram.record(n,i)}catch(i){console.warn("Failed to record samples metric:",i)}},rl=(o,e,t,n,r,s,i)=>{try{let a=Ot({...s?{signature:s}:{},...i});o.inputFieldsGauge&&o.inputFieldsGauge.record(e,a),o.outputFieldsGauge&&o.outputFieldsGauge.record(t,a),o.examplesUsedGauge&&o.examplesUsedGauge.record(n,a),o.demosUsedGauge&&o.demosUsedGauge.record(r,a)}catch(a){console.warn("Failed to record signature complexity metrics:",a)}},ms=(o,e,t,n,r)=>{try{let s=Ot({metric_type:e,...n?{signature:n}:{},...r});switch(e){case"prompt_render":o.promptRenderLatencyHistogram&&o.promptRenderLatencyHistogram.record(t,s);break;case"extraction":o.extractionLatencyHistogram&&o.extractionLatencyHistogram.record(t,s);break;case"assertion":o.assertionLatencyHistogram&&o.assertionLatencyHistogram.record(t,s);break;case"state_creation":o.stateCreationLatencyHistogram&&o.stateCreationLatencyHistogram.record(t,s);break;case"memory_update":o.memoryUpdateLatencyHistogram&&o.memoryUpdateLatencyHistogram.record(t,s);break}}catch(s){console.warn("Failed to record performance metric:",s)}};var Wn=o=>{let e=(()=>{switch(o?.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 o?.isArray?`array of ${e}s`:e},Qe=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()}},ol=o=>{let t=o.map(n=>`'${n.title}' (${Wn(n.type)})`).join(", ");return new Qe(`Required field not found: ${t}. Add a line starting with the exact label followed by a colon (e.g., "${o[0]?.title}:") and then provide a valid ${Wn(o[0]?.type)} value. Keep the output concise and avoid unrelated text.`)},gs=o=>new Qe(`Expected (Required) field not found: '${o.title}'. Begin a new section with "${o.title}:" and then provide a valid ${Wn(o.type)} value directly after.`);var fs=o=>new Qe(`Required field is missing: '${o.title}'. After the "${o.title}:" label, provide a non-empty ${Wn(o.type)}. Do not use null, undefined, or leave it blank.`),sl=(o,e)=>new Qe(`Invalid JSON: ${e} in field '${o.title}'. Return only valid JSON. Prefer a fenced code block containing a single JSON object or array with no trailing text.`),il=(o,e)=>new Qe(`Invalid Array: ${e} for '${o.title}'. Provide a JSON array of ${Wn(o.type)} items (e.g., [ ... ]). Markdown lists are also accepted if each item is on its own line starting with a hyphen.`),al=(o,e,t)=>new Qe(`Field '${o.title}' has an invalid value '${e}': ${t}. Provide a ${Wn(o.type)}. Ensure formatting exactly matches the expected type.`),ul=(o,e,t)=>new Qe(`Invalid date for '${o.title}': ${t}. Use the exact format YYYY-MM-DD (e.g., 2024-05-09). You provided: ${e}.`),cl=(o,e,t)=>new Qe(`Invalid date/time for '${o.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}.`),ia=(o,e,t)=>new Qe(`Invalid URL for '${o.title}': ${t}. Use a valid URL format (e.g., https://example.com). You provided: ${e}.`),Kn=(o,e,t,n)=>{let r=`Field '${o.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 Qe(r)},aa=(o,e,t,n)=>{let r=`Field '${o.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 Qe(r)};var ll=({error:o,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:s,span:i,customLabels:a})=>{let u=o.getFixingInstructions();if(t&&n){let c=u?.map(l=>l.title).join(", ")??"";Vu(o,e,c,n)}return r&&oa(r,"validation",s,a),i&&i.addEvent("validation.error",{message:o.toString(),fixing_instructions:u?.map(c=>c.title).join(", ")??""}),u},pl=({error:o,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:s,span:i,customLabels:a})=>{let u=o.getFixingInstructions();if(t&&n){let c=u?.map(l=>l.title).join(", ")??"";Ju(o,e,c,n)}return r&&oa(r,"assertion",s,a),i&&i.addEvent("assertion.error",{message:o.toString(),fixing_instructions:u?.map(c=>c.title).join(", ")??""}),u},dl=({error:o,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:s,span:i,customLabels:a})=>{t&&n&&Qu(o,e,n),r&&Xc(r,s,a),i&&i.addEvent("refusal.error",{message:o.toString()})};var Kt=xr(ml(),1),xl=xr(gl(),1),Al=xr(fl(),1),yl=xr(hl(),1);Kt.default.extend(yl.default);Kt.default.extend(Al.default);Kt.default.extend(xl.default);function bl(o,e,t=!1){try{return Sm(e)}catch(n){if(o.isOptional&&!t)return;let r=n.message;throw ul(o,e,r)}}function Sm(o){if(!(0,Kt.default)(o,"YYYY-MM-DD",!0).isValid())throw new Error('Invalid date format. Please provide the date in "YYYY-MM-DD" format.');return Kt.default.utc(o,"YYYY-MM-DD").startOf("day").toDate()}function Tl(o,e,t=!1){try{return km(e)}catch(n){if(o.isOptional&&!t)return;let r=n.message;throw cl(o,e,r)}}function km(o){let e=/^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}(?::\d{2})?) (.+)$/,t=o.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 s=n.includes(":")&&n.split(":").length===3?"YYYY-MM-DD HH:mm:ss":"YYYY-MM-DD HH:mm",i=Kt.default.tz(n,s,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 Cl=o=>(0,Kt.default)(o).utc().format("YYYY-MM-DD HH:mm:ss [UTC]");var iC=new st,Hr=(o,e)=>{let t=o.type??{name:"string",isArray:!1},n=(c,l)=>{switch(c){case"class":return typeof l=="string";case"code":return typeof l=="string";case"string":return typeof l=="string";case"number":return typeof l=="number";case"boolean":return typeof l=="boolean";case"date":return l instanceof Date||typeof l=="string";case"datetime":return l instanceof Date||typeof l=="string";case"json":return typeof l=="object"||typeof l=="string";case"object":return typeof l=="object";default:return!1}},r=c=>!(!c||typeof c!="object"||!("mimeType"in c)||!("data"in c));if(o.type?.name==="image"){let c;if(Array.isArray(e)){for(let l of e)if(!r(l)){c="object ({ mimeType: string; data: string })";break}}else r(e)||(c="object ({ mimeType: string; data: string })");if(c)throw new Error(`Validation failed: Expected '${o.name}' to be type '${c}' instead got '${e}'`);return}let s=c=>!(!c||typeof c!="object"||!("data"in c));if(o.type?.name==="audio"){let c;if(Array.isArray(e)){for(let l of e)if(!s(l)){c="object ({ data: string; format?: string })";break}}else s(e)||(c="object ({ data: string; format?: string })");if(c)throw new Error(`Validation failed: Expected '${o.name}' to be type '${c}' instead got '${e}'`);return}let i=c=>{if(!c||typeof c!="object"||!("mimeType"in c))return!1;let l="data"in c,p="fileUri"in c;return!(!l&&!p||l&&p)};if(o.type?.name==="file"){let c;if(Array.isArray(e)){for(let l of e)if(!i(l)){c="object ({ mimeType: string; data: string } | { mimeType: string; fileUri: string })";break}}else i(e)||(c="object ({ mimeType: string; data: string } | { mimeType: string; fileUri: string })");if(c)throw new Error(`Validation failed: Expected '${o.name}' to be type '${c}' instead got '${e}'`);return}let a=c=>typeof c=="string"?!0:!(!c||typeof c!="object"||!("url"in c));if(o.type?.name==="url"){let c;if(Array.isArray(e)){for(let l of e)if(!a(l)){c="string or object ({ url: string; title?: string; description?: string })";break}}else a(e)||(c="string or object ({ url: string; title?: string; description?: string })");if(c)throw new Error(`Validation failed: Expected '${o.name}' to be type '${c}' instead got '${e}'`);return}let u=!0;if(t.isArray){if(!Array.isArray(e))u=!1;else for(let c of e)if(!n(t.name,c)){u=!1;break}}else u=n(t.name,e);if(!u){let c=Array.isArray(e)?"array":typeof e;throw new Error(`Validation failed: Expected '${o.name}' to be a ${o.type?.isArray?"an array of ":""}${t.name} instead got '${c}' (${JSON.stringify(e)})`)}};function Wr(o){let e={};for(let t of o){let n=`${t.ai}:${t.model}`;if(!e[n]){e[n]={...t};continue}let r=e[n];if(r){let s=r.tokens??{promptTokens:0,completionTokens:0,totalTokens:0};s.promptTokens+=t?.tokens?.promptTokens??0,s.completionTokens+=t?.tokens?.completionTokens??0,s.totalTokens+=t?.tokens?.totalTokens??0,r.tokens=s;let i=r.citations??[],a=t.citations??[];if(a.length){let u=new Set(i.map(c=>c.url));for(let c of a)c?.url&&!u.has(c.url)&&(i.push(c),u.add(c.url));r.citations=i}}}return Object.values(e)}var Il=o=>{if(!o.trim())return[];let e=new Set(["-","*","+"]),t=/^\d+[\s]*[.)\]]\s*/,n=o.split(`
204
- `),r=[];for(let s of n){let i=s.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 xa(o,e){let{index:t,delta:n,version:r}=e,s=o.find(a=>a.index===t)?.delta;if(!s)return o.push({index:t,delta:n,version:r}),o;for(let a of Object.keys(n)){let u=s[a],c=n[a];u===void 0&&Array.isArray(c)?s[a]=[...c]:Array.isArray(u)&&Array.isArray(c)?s[a]=[...u,...c]:(u===void 0||typeof u=="string")&&typeof c=="string"?s[a]=`${u??""}${c}`:s[a]=c}let i=o.find(a=>a.index===t);return i&&(i.version=r),o}var ha=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)}},Om=new ha(500);function wl(o,e,t=0,n=Om){if(/^```[a-zA-Z]*\s*$/.test(o))return-4;if(/^[\s`]*$/.test(o))return-3;let r=o.indexOf(e,t);if(r!==-1)return r;let s=n.get(e)??Array.from({length:e.length},(a,u)=>e.slice(0,u+1));n.get(e)||n.set(e,s);let i=-1;for(let a=s.length-1;a>=0;a--){let u=s[a];if(o.endsWith(u)){i=a;break}}return i>=0?-2:-1}function Vt(o,e){if(typeof o!="string")throw ia(e,String(o),"URL must be a string");try{new URL(o)}catch{throw ia(e,o,"Invalid URL format. Expected a valid URL like https://example.com")}}function yt(o,e){if(typeof o!="string")return;let t=e.type;if(t){if(t.minLength!==void 0&&o.length<t.minLength)throw Kn(e,o,"minLength",t.minLength);if(t.maxLength!==void 0&&o.length>t.maxLength)throw Kn(e,o,"maxLength",t.maxLength);if(t.pattern!==void 0&&!new RegExp(t.pattern).test(o))throw Kn(e,o,"pattern",t.pattern);if(t.format==="email"&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(o))throw Kn(e,o,"format","valid email address");if(t.format==="uri"||t.format==="url")try{new URL(o)}catch{throw Kn(e,o,"format","valid URL")}}}function bt(o,e){if(typeof o!="number")return;let t=e.type;if(t){if(t.minimum!==void 0&&o<t.minimum)throw aa(e,o,"minimum",t.minimum);if(t.maximum!==void 0&&o>t.maximum)throw aa(e,o,"maximum",t.maximum)}}var As=(o,e,t,n)=>{let r=n?.strictMode??!1,s=n?.treatAllFieldsOptional??!1,i=n?.treatAllFieldsOptional??!1,a={extractedFields:[],streamedIndex:{},s:-1};ba(o,e,a,t,{strictMode:r,skipEarlyFail:i,treatAllFieldsOptional:s}),Ta(o,e,a,t,{strictMode:r,treatAllFieldsOptional:s,forceFinalize:!0});for(let u of o.getOutputFields())u.isInternal&&delete e[u.name]},Aa=(o,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 ol(n)},ba=(o,e,t,n,{strictMode:r,skipEarlyFail:s}={})=>{let i=o.getOutputFields(),a;for(;;){let u=new Set;t.currFieldIndex!==void 0&&!t.inAssumedField&&u.add(t.currFieldIndex);let c=i.map((g,f)=>({field:g,index:f})).filter(({index:g})=>!u.has(g)),l,p,d=-1,m=0;for(let{index:g,field:f}of c){let A=`${(t.extractedFields.length===0?"":`
205
- `)+f.title}:`,h=wl(n,A,t.s);if(h===-2||h===-3)return!0;if(h===-4)return t.inBlock=!0,!0;h>=0&&(d===-1||h<d)&&(d=h,m=A.length,l=g,p=f)}if(d===-1){if(s)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 gs(g)}break}if(a&&p&&a.name!==p.name)throw gs(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=hs(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&&l!==void 0&&(t.currField=p,t.currFieldIndex=l),p&&!t.extractedFields.includes(p)&&t.extractedFields.push(p),p&&t.streamedIndex[p.name]===void 0&&(t.streamedIndex[p.name]=0)}},Ta=(o,e,t,n,r)=>{let s=r?.strictMode??!1,i=r?.treatAllFieldsOptional??!1,a=r?.deferRequiredCheckForStreaming??!1,u=r?.forceFinalize??!1;if(t.currField){let c=n.length,l=o.getOutputFields();for(let m of l){if(m.name===t.currField.name)continue;let g=`
206
- ${m.title}:`,f=n.indexOf(g,t.s);f!==-1&&f<c&&(c=f)}let p=n.substring(t.s,c).trim(),d=hs(t.currField,p);d!==void 0&&(e[t.currField.name]=d)}if(s&&!t.currField&&t.extractedFields.length===0&&n.trim()){let p=o.getOutputFields().find(d=>!d.isOptional);if(p)throw gs(p)}if(Em(o,e,n,t),!i){let c=t.currField!==void 0||(t.extractedFields?.length??0)>0;s||u?Aa(t,e,o.getOutputFields()):c||Aa(t,e,o.getOutputFields())}},Em=(o,e,t,n)=>{let r=o.getOutputFields();if(r.length===1){let i=r[0];if(i){let a=`${i.title}:`,u=t.indexOf(a);if(u!==-1){let c=u+a.length,l=`
203
+ `,s=u}),(s>t||n.length===0)&&n.push(r.trim()),n},km=(o,e=.1)=>{let t=[...o].sort((r,s)=>r.score-s.score),n=Math.ceil(t.length*e);return t.slice(0,n)};var qr=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,...s})=>({index:r,value:structuredClone(s)})),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:s,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:s})}]});return}let u=a.chat.find(c=>c.index===i);if(!u){a.chat.push({index:i,value:structuredClone({content:e,name:t,functionCalls:n,thought:r,thoughtBlocks:s})});return}if(typeof e=="string"&&e.trim()!==""&&(u.value.content=e),typeof t=="string"&&t.trim()!==""&&(u.value.name=t),Array.isArray(n)&&n.length>0&&(u.value.functionCalls=n),typeof r=="string"&&r.trim()!==""){let c=u.value.thought;u.value.thought=typeof c=="string"?c+r:r}if(Array.isArray(s)&&s.length>0){let c=u.value.thoughtBlocks??[];for(let l of s){let p=c.length>0?c[c.length-1]:void 0;!l.signature&&l.data?p&&!p.signature?(p.data=(p.data??"")+l.data,l.encrypted&&(p.encrypted=!0)):c.push(structuredClone(l)):l.signature?p&&!p.signature?(p.data=(p.data??"")+l.data,p.signature=l.signature,l.encrypted&&(p.encrypted=!0)):c.push(structuredClone(l)):c.length===0&&c.push(structuredClone(l))}u.value.thoughtBlocks=c,c.length>0&&(u.value.thought=c.map(l=>l.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,s)=>(r.tags?.includes(e)&&n.push(s),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 s;n==="function"?s=r.filter(i=>i.index===e).map(i=>i.value):s=r.find(i=>i.index===e)?.value,Array.isArray(s)&&s.length>0?t.push(...s.map(i=>({...i,role:n}))):typeof s=="object"&&s!==null&&t.push({...s,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 qr}getMemory(e){return e?(this.memories.has(e)||this.memories.set(e,new qr),this.memories.get(e)):this.defaultMemory}addRequest(e,t){for(let n of e)Cn(n);this.getMemory(t).addRequest(e,0)}addResponse(e,t){Po(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 qr):this.defaultMemory.reset()}};function kt(o,e){if(!o&&!e)return;if(!o)return e;if(!e||o===e||o.aborted)return o;if(e.aborted)return e;if(typeof AbortSignal.any=="function")return AbortSignal.any([o,e]);let t=new AbortController,n=()=>{t.abort(o.aborted?o.reason:e.reason),r()},r=()=>{o.removeEventListener("abort",n),e.removeEventListener("abort",n)};return o.addEventListener("abort",n,{once:!0}),e.addEventListener("abort",n,{once:!0}),t.signal}var Pt=class extends Error{constructor({message:e}){super(e),this.name="AxAssertionError"}getFixingInstructions=()=>{let e=[],t=this.message.trim();return e.push({name:"error",title:"Follow these instructions",description:t+(t.endsWith(".")?"":".")}),e};toString(){return`${this.name}: ${this.message}`}[Symbol.for("nodejs.util.inspect.custom")](e,t){return this.toString()}},Vn=async(o,e)=>{for(let t of o){let{fn:n,message:r}=t,s=await n(e);if(s!==void 0){if(typeof s=="string")throw new Pt({message:s});if(!s)throw r?new Pt({message:r}):new Error("Assertion Failed: No message provided for assertion")}}},na=async(o,e,t,n=!1)=>{if(!e.currField||e.s===-1||!o||o.length===0)return;let r=o.filter(i=>i.fieldName===e.currField?.name);if(r.length===0)return;let s=t.substring(e.s);for(let i of r){let{message:a,fn:u}=i,c=await u(s,n);if(c!==void 0){if(typeof c=="string")throw new Pt({message:c});if(!c&&a)throw new Pt({message:a})}}};var ra={enabled:!0,enabledCategories:["generation","streaming","functions","errors","performance"],maxLabelLength:100,samplingRate:1},Hr,oa=o=>{if(Hr)return Hr;let e=o??he.meter;if(e)return Hr=Om(e),Hr};var Qc=()=>{let o=[];return he.meter||o.push("Global meter not initialized"),!Hr&&he.meter&&o.push("Metrics instruments not created despite available meter"),{healthy:o.length===0,issues:o}},Om=o=>({generationLatencyHistogram:o.createHistogram("ax_gen_generation_duration_ms",{description:"End-to-end duration of AxGen generation requests",unit:"ms"}),generationRequestsCounter:o.createCounter("ax_gen_generation_requests_total",{description:"Total number of AxGen generation requests"}),generationErrorsCounter:o.createCounter("ax_gen_generation_errors_total",{description:"Total number of failed AxGen generations"}),multiStepGenerationsCounter:o.createCounter("ax_gen_multistep_generations_total",{description:"Total number of generations that required multiple steps"}),stepsPerGenerationHistogram:o.createHistogram("ax_gen_steps_per_generation",{description:"Number of steps taken per generation"}),maxStepsReachedCounter:o.createCounter("ax_gen_max_steps_reached_total",{description:"Total number of generations that hit max steps limit"}),validationErrorsCounter:o.createCounter("ax_gen_validation_errors_total",{description:"Total number of validation errors encountered"}),assertionErrorsCounter:o.createCounter("ax_gen_assertion_errors_total",{description:"Total number of assertion errors encountered"}),errorCorrectionAttemptsHistogram:o.createHistogram("ax_gen_error_correction_attempts",{description:"Number of error correction attempts per generation"}),errorCorrectionSuccessCounter:o.createCounter("ax_gen_error_correction_success_total",{description:"Total number of successful error corrections"}),errorCorrectionFailureCounter:o.createCounter("ax_gen_error_correction_failure_total",{description:"Total number of failed error corrections"}),maxRetriesReachedCounter:o.createCounter("ax_gen_max_retries_reached_total",{description:"Total number of generations that hit max retries limit"}),functionsEnabledGenerationsCounter:o.createCounter("ax_gen_functions_enabled_generations_total",{description:"Total number of generations with functions enabled"}),functionCallStepsCounter:o.createCounter("ax_gen_function_call_steps_total",{description:"Total number of steps that included function calls"}),functionsExecutedPerGenerationHistogram:o.createHistogram("ax_gen_functions_executed_per_generation",{description:"Number of unique functions executed per generation"}),functionErrorCorrectionCounter:o.createCounter("ax_gen_function_error_correction_total",{description:"Total number of function-related error corrections"}),fieldProcessorsExecutedCounter:o.createCounter("ax_gen_field_processors_executed_total",{description:"Total number of field processors executed"}),streamingFieldProcessorsExecutedCounter:o.createCounter("ax_gen_streaming_field_processors_executed_total",{description:"Total number of streaming field processors executed"}),streamingGenerationsCounter:o.createCounter("ax_gen_streaming_generations_total",{description:"Total number of streaming generations"}),streamingDeltasEmittedCounter:o.createCounter("ax_gen_streaming_deltas_emitted_total",{description:"Total number of streaming deltas emitted"}),streamingFinalizationLatencyHistogram:o.createHistogram("ax_gen_streaming_finalization_duration_ms",{description:"Duration of streaming response finalization",unit:"ms"}),samplesGeneratedHistogram:o.createHistogram("ax_gen_samples_generated",{description:"Number of samples generated per request"}),resultPickerUsageCounter:o.createCounter("ax_gen_result_picker_usage_total",{description:"Total number of times result picker was used"}),resultPickerLatencyHistogram:o.createHistogram("ax_gen_result_picker_duration_ms",{description:"Duration of result picker execution",unit:"ms"}),inputFieldsGauge:o.createGauge("ax_gen_input_fields",{description:"Number of input fields in signature"}),outputFieldsGauge:o.createGauge("ax_gen_output_fields",{description:"Number of output fields in signature"}),examplesUsedGauge:o.createGauge("ax_gen_examples_used",{description:"Number of examples used in generation"}),demosUsedGauge:o.createGauge("ax_gen_demos_used",{description:"Number of demos used in generation"}),promptRenderLatencyHistogram:o.createHistogram("ax_gen_prompt_render_duration_ms",{description:"Duration of prompt template rendering",unit:"ms"}),extractionLatencyHistogram:o.createHistogram("ax_gen_extraction_duration_ms",{description:"Duration of value extraction from responses",unit:"ms"}),assertionLatencyHistogram:o.createHistogram("ax_gen_assertion_duration_ms",{description:"Duration of assertion checking",unit:"ms"}),stateCreationLatencyHistogram:o.createHistogram("ax_gen_state_creation_duration_ms",{description:"Duration of state creation for multiple samples",unit:"ms"}),memoryUpdateLatencyHistogram:o.createHistogram("ax_gen_memory_update_duration_ms",{description:"Duration of memory updates during generation",unit:"ms"})}),ps=ra,Yc=o=>{ps={...ps,...o}},Xc=()=>({...ps}),Ot=o=>{let e={};for(let[t,n]of Object.entries(o))if(n!=null){let r=String(n),s=ps.maxLabelLength;e[t]=r.length>s?r.substring(0,s):r}return e};var Zc=(o,e,t,n,r,s,i)=>{try{let a=Ot({success:t.toString(),...n?{signature:n}:{},...r?{ai_service:r}:{},...s?{model:s}:{},...i});o.generationLatencyHistogram&&o.generationLatencyHistogram.record(e,a),o.generationRequestsCounter&&o.generationRequestsCounter.add(1,a),!t&&o.generationErrorsCounter&&o.generationErrorsCounter.add(1,a)}catch(a){console.warn("Failed to record generation metric:",a)}},ds=(o,e,t,n,r)=>{try{let s=Ot({...n?{signature:n}:{},...r});e>1&&o.multiStepGenerationsCounter&&o.multiStepGenerationsCounter.add(1,s),o.stepsPerGenerationHistogram&&o.stepsPerGenerationHistogram.record(e,s),e>=t&&o.maxStepsReachedCounter&&o.maxStepsReachedCounter.add(1,s)}catch(s){console.warn("Failed to record multi-step metric:",s)}},sa=(o,e,t,n)=>{try{let r=Ot({error_type:e,...t?{signature:t}:{},...n});e==="validation"&&o.validationErrorsCounter&&o.validationErrorsCounter.add(1,r),e==="assertion"&&o.assertionErrorsCounter&&o.assertionErrorsCounter.add(1,r)}catch(r){console.warn("Failed to record validation error metric:",r)}},el=(o,e,t)=>{try{let n=Ot({error_type:"refusal",...e?{signature:e}:{},...t});o.validationErrorsCounter&&o.validationErrorsCounter.add(1,n)}catch(n){console.warn("Failed to record refusal error metric:",n)}},ia=(o,e,t,n,r,s)=>{try{let i=Ot({success:t.toString(),...r?{signature:r}:{},...s});o.errorCorrectionAttemptsHistogram&&o.errorCorrectionAttemptsHistogram.record(e,i),t&&o.errorCorrectionSuccessCounter&&o.errorCorrectionSuccessCounter.add(1,i),t||(o.errorCorrectionFailureCounter&&o.errorCorrectionFailureCounter.add(1,i),e>=n&&o.maxRetriesReachedCounter&&o.maxRetriesReachedCounter.add(1,i))}catch(i){console.warn("Failed to record error correction metric:",i)}},tl=(o,e,t,n,r=!1,s,i)=>{try{let a=Ot({functions_enabled:e.toString(),had_function_calls:n.toString(),...s?{signature:s}:{},...i});e&&o.functionsEnabledGenerationsCounter&&o.functionsEnabledGenerationsCounter.add(1,a),n&&o.functionCallStepsCounter&&o.functionCallStepsCounter.add(1,a),t>0&&o.functionsExecutedPerGenerationHistogram&&o.functionsExecutedPerGenerationHistogram.record(t,a),r&&o.functionErrorCorrectionCounter&&o.functionErrorCorrectionCounter.add(1,a)}catch(a){console.warn("Failed to record function calling metric:",a)}},nl=(o,e,t,n,r)=>{try{let s=Ot({...n?{signature:n}:{},...r});e>0&&o.fieldProcessorsExecutedCounter&&o.fieldProcessorsExecutedCounter.add(e,s),t>0&&o.streamingFieldProcessorsExecutedCounter&&o.streamingFieldProcessorsExecutedCounter.add(t,s)}catch(s){console.warn("Failed to record field processing metric:",s)}},rl=(o,e,t,n,r,s)=>{try{let i=Ot({is_streaming:e.toString(),...r?{signature:r}:{},...s});e&&o.streamingGenerationsCounter&&o.streamingGenerationsCounter.add(1,i),t>0&&o.streamingDeltasEmittedCounter&&o.streamingDeltasEmittedCounter.add(t,i),n&&o.streamingFinalizationLatencyHistogram&&o.streamingFinalizationLatencyHistogram.record(n,i)}catch(i){console.warn("Failed to record streaming metric:",i)}},ol=(o,e,t,n,r,s)=>{try{let i=Ot({result_picker_used:t.toString(),...r?{signature:r}:{},...s});o.samplesGeneratedHistogram&&o.samplesGeneratedHistogram.record(e,i),t&&o.resultPickerUsageCounter&&o.resultPickerUsageCounter.add(1,i),n&&o.resultPickerLatencyHistogram&&o.resultPickerLatencyHistogram.record(n,i)}catch(i){console.warn("Failed to record samples metric:",i)}},sl=(o,e,t,n,r,s,i)=>{try{let a=Ot({...s?{signature:s}:{},...i});o.inputFieldsGauge&&o.inputFieldsGauge.record(e,a),o.outputFieldsGauge&&o.outputFieldsGauge.record(t,a),o.examplesUsedGauge&&o.examplesUsedGauge.record(n,a),o.demosUsedGauge&&o.demosUsedGauge.record(r,a)}catch(a){console.warn("Failed to record signature complexity metrics:",a)}},ms=(o,e,t,n,r)=>{try{let s=Ot({metric_type:e,...n?{signature:n}:{},...r});switch(e){case"prompt_render":o.promptRenderLatencyHistogram&&o.promptRenderLatencyHistogram.record(t,s);break;case"extraction":o.extractionLatencyHistogram&&o.extractionLatencyHistogram.record(t,s);break;case"assertion":o.assertionLatencyHistogram&&o.assertionLatencyHistogram.record(t,s);break;case"state_creation":o.stateCreationLatencyHistogram&&o.stateCreationLatencyHistogram.record(t,s);break;case"memory_update":o.memoryUpdateLatencyHistogram&&o.memoryUpdateLatencyHistogram.record(t,s);break}}catch(s){console.warn("Failed to record performance metric:",s)}};var Wn=o=>{let e=(()=>{switch(o?.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 o?.isArray?`array of ${e}s`:e},Qe=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()}},il=o=>{let t=o.map(n=>`'${n.title}' (${Wn(n.type)})`).join(", ");return new Qe(`Required field not found: ${t}. Add a line starting with the exact label followed by a colon (e.g., "${o[0]?.title}:") and then provide a valid ${Wn(o[0]?.type)} value. Keep the output concise and avoid unrelated text.`)},gs=o=>new Qe(`Expected (Required) field not found: '${o.title}'. Begin a new section with "${o.title}:" and then provide a valid ${Wn(o.type)} value directly after.`);var fs=o=>new Qe(`Required field is missing: '${o.title}'. After the "${o.title}:" label, provide a non-empty ${Wn(o.type)}. Do not use null, undefined, or leave it blank.`),al=(o,e)=>new Qe(`Invalid JSON: ${e} in field '${o.title}'. Return only valid JSON. Prefer a fenced code block containing a single JSON object or array with no trailing text.`),ul=(o,e)=>new Qe(`Invalid Array: ${e} for '${o.title}'. Provide a JSON array of ${Wn(o.type)} items (e.g., [ ... ]). Markdown lists are also accepted if each item is on its own line starting with a hyphen.`),cl=(o,e,t)=>new Qe(`Field '${o.title}' has an invalid value '${e}': ${t}. Provide a ${Wn(o.type)}. Ensure formatting exactly matches the expected type.`),ll=(o,e,t)=>new Qe(`Invalid date for '${o.title}': ${t}. Use the exact format YYYY-MM-DD (e.g., 2024-05-09). You provided: ${e}.`),pl=(o,e,t)=>new Qe(`Invalid date/time for '${o.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}.`),aa=(o,e,t)=>new Qe(`Invalid URL for '${o.title}': ${t}. Use a valid URL format (e.g., https://example.com). You provided: ${e}.`),Jn=(o,e,t,n)=>{let r=`Field '${o.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 Qe(r)},ua=(o,e,t,n)=>{let r=`Field '${o.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 Qe(r)};var dl=({error:o,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:s,span:i,customLabels:a})=>{let u=o.getFixingInstructions();if(t&&n){let c=u?.map(l=>l.title).join(", ")??"";Yu(o,e,c,n)}return r&&sa(r,"validation",s,a),i&&i.addEvent("validation.error",{message:o.toString(),fixing_instructions:u?.map(c=>c.title).join(", ")??""}),u},ml=({error:o,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:s,span:i,customLabels:a})=>{let u=o.getFixingInstructions();if(t&&n){let c=u?.map(l=>l.title).join(", ")??"";Xu(o,e,c,n)}return r&&sa(r,"assertion",s,a),i&&i.addEvent("assertion.error",{message:o.toString(),fixing_instructions:u?.map(c=>c.title).join(", ")??""}),u},gl=({error:o,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:s,span:i,customLabels:a})=>{t&&n&&Zu(o,e,n),r&&el(r,s,a),i&&i.addEvent("refusal.error",{message:o.toString()})};var Vt=Ar(fl(),1),yl=Ar(hl(),1),bl=Ar(xl(),1),Cl=Ar(Al(),1);Vt.default.extend(Cl.default);Vt.default.extend(bl.default);Vt.default.extend(yl.default);function Il(o,e,t=!1){try{return Em(e)}catch(n){if(o.isOptional&&!t)return;let r=n.message;throw ll(o,e,r)}}function Em(o){if(!(0,Vt.default)(o,"YYYY-MM-DD",!0).isValid())throw new Error('Invalid date format. Please provide the date in "YYYY-MM-DD" format.');return Vt.default.utc(o,"YYYY-MM-DD").startOf("day").toDate()}function Tl(o,e,t=!1){try{return Mm(e)}catch(n){if(o.isOptional&&!t)return;let r=n.message;throw pl(o,e,r)}}function Mm(o){let e=/^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}(?::\d{2})?) (.+)$/,t=o.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 s=n.includes(":")&&n.split(":").length===3?"YYYY-MM-DD HH:mm:ss":"YYYY-MM-DD HH:mm",i=Vt.default.tz(n,s,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 wl=o=>(0,Vt.default)(o).utc().format("YYYY-MM-DD HH:mm:ss [UTC]");var tI=new st,Kr=(o,e)=>{let t=o.type??{name:"string",isArray:!1},n=(c,l)=>{switch(c){case"class":return typeof l=="string";case"code":return typeof l=="string";case"string":return typeof l=="string";case"number":return typeof l=="number";case"boolean":return typeof l=="boolean";case"date":return l instanceof Date||typeof l=="string";case"datetime":return l instanceof Date||typeof l=="string";case"json":return typeof l=="object"||typeof l=="string";case"object":return typeof l=="object";default:return!1}},r=c=>!(!c||typeof c!="object"||!("mimeType"in c)||!("data"in c));if(o.type?.name==="image"){let c;if(Array.isArray(e)){for(let l of e)if(!r(l)){c="object ({ mimeType: string; data: string })";break}}else r(e)||(c="object ({ mimeType: string; data: string })");if(c)throw new Error(`Validation failed: Expected '${o.name}' to be type '${c}' instead got '${e}'`);return}let s=c=>!(!c||typeof c!="object"||!("data"in c));if(o.type?.name==="audio"){let c;if(Array.isArray(e)){for(let l of e)if(!s(l)){c="object ({ data: string; format?: string })";break}}else s(e)||(c="object ({ data: string; format?: string })");if(c)throw new Error(`Validation failed: Expected '${o.name}' to be type '${c}' instead got '${e}'`);return}let i=c=>{if(!c||typeof c!="object"||!("mimeType"in c))return!1;let l="data"in c,p="fileUri"in c;return!(!l&&!p||l&&p)};if(o.type?.name==="file"){let c;if(Array.isArray(e)){for(let l of e)if(!i(l)){c="object ({ mimeType: string; data: string } | { mimeType: string; fileUri: string })";break}}else i(e)||(c="object ({ mimeType: string; data: string } | { mimeType: string; fileUri: string })");if(c)throw new Error(`Validation failed: Expected '${o.name}' to be type '${c}' instead got '${e}'`);return}let a=c=>typeof c=="string"?!0:!(!c||typeof c!="object"||!("url"in c));if(o.type?.name==="url"){let c;if(Array.isArray(e)){for(let l of e)if(!a(l)){c="string or object ({ url: string; title?: string; description?: string })";break}}else a(e)||(c="string or object ({ url: string; title?: string; description?: string })");if(c)throw new Error(`Validation failed: Expected '${o.name}' to be type '${c}' instead got '${e}'`);return}let u=!0;if(t.isArray){if(!Array.isArray(e))u=!1;else for(let c of e)if(!n(t.name,c)){u=!1;break}}else u=n(t.name,e);if(!u){let c=Array.isArray(e)?"array":typeof e;throw new Error(`Validation failed: Expected '${o.name}' to be a ${o.type?.isArray?"an array of ":""}${t.name} instead got '${c}' (${JSON.stringify(e)})`)}};function Vr(o){let e={};for(let t of o){let n=`${t.ai}:${t.model}`;if(!e[n]){e[n]={...t};continue}let r=e[n];if(r){let s=r.tokens??{promptTokens:0,completionTokens:0,totalTokens:0};s.promptTokens+=t?.tokens?.promptTokens??0,s.completionTokens+=t?.tokens?.completionTokens??0,s.totalTokens+=t?.tokens?.totalTokens??0,r.tokens=s;let i=r.citations??[],a=t.citations??[];if(a.length){let u=new Set(i.map(c=>c.url));for(let c of a)c?.url&&!u.has(c.url)&&(i.push(c),u.add(c.url));r.citations=i}}}return Object.values(e)}var Rl=o=>{if(!o.trim())return[];let e=new Set(["-","*","+"]),t=/^\d+[\s]*[.)\]]\s*/,n=o.split(`
204
+ `),r=[];for(let s of n){let i=s.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 Aa(o,e){let{index:t,delta:n,version:r}=e,s=o.find(a=>a.index===t)?.delta;if(!s)return o.push({index:t,delta:n,version:r}),o;for(let a of Object.keys(n)){let u=s[a],c=n[a];u===void 0&&Array.isArray(c)?s[a]=[...c]:Array.isArray(u)&&Array.isArray(c)?s[a]=[...u,...c]:(u===void 0||typeof u=="string")&&typeof c=="string"?s[a]=`${u??""}${c}`:s[a]=c}let i=o.find(a=>a.index===t);return i&&(i.version=r),o}var xa=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)}},Pm=new xa(500);function vl(o,e,t=0,n=Pm){if(/^```[a-zA-Z]*\s*$/.test(o))return-4;if(/^[\s`]*$/.test(o))return-3;let r=o.indexOf(e,t);if(r!==-1)return r;let s=n.get(e)??Array.from({length:e.length},(a,u)=>e.slice(0,u+1));n.get(e)||n.set(e,s);let i=-1;for(let a=s.length-1;a>=0;a--){let u=s[a];if(o.endsWith(u)){i=a;break}}return i>=0?-2:-1}function Wt(o,e){if(typeof o!="string")throw aa(e,String(o),"URL must be a string");try{new URL(o)}catch{throw aa(e,o,"Invalid URL format. Expected a valid URL like https://example.com")}}function yt(o,e){if(typeof o!="string")return;let t=e.type;if(t){if(t.minLength!==void 0&&o.length<t.minLength)throw Jn(e,o,"minLength",t.minLength);if(t.maxLength!==void 0&&o.length>t.maxLength)throw Jn(e,o,"maxLength",t.maxLength);if(t.pattern!==void 0&&!new RegExp(t.pattern).test(o))throw Jn(e,o,"pattern",t.pattern);if(t.format==="email"&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(o))throw Jn(e,o,"format","valid email address");if(t.format==="uri"||t.format==="url")try{new URL(o)}catch{throw Jn(e,o,"format","valid URL")}}}function bt(o,e){if(typeof o!="number")return;let t=e.type;if(t){if(t.minimum!==void 0&&o<t.minimum)throw ua(e,o,"minimum",t.minimum);if(t.maximum!==void 0&&o>t.maximum)throw ua(e,o,"maximum",t.maximum)}}var As=(o,e,t,n)=>{let r=n?.strictMode??!1,s=n?.treatAllFieldsOptional??!1,i=n?.treatAllFieldsOptional??!1,a={extractedFields:[],streamedIndex:{},s:-1};Ca(o,e,a,t,{strictMode:r,skipEarlyFail:i,treatAllFieldsOptional:s}),Ia(o,e,a,t,{strictMode:r,treatAllFieldsOptional:s,forceFinalize:!0});for(let u of o.getOutputFields())u.isInternal&&delete e[u.name]},ya=(o,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 il(n)},Ca=(o,e,t,n,{strictMode:r,skipEarlyFail:s}={})=>{let i=o.getOutputFields(),a;for(;;){let u=new Set;t.currFieldIndex!==void 0&&!t.inAssumedField&&u.add(t.currFieldIndex);let c=i.map((g,f)=>({field:g,index:f})).filter(({index:g})=>!u.has(g)),l,p,d=-1,m=0;for(let{index:g,field:f}of c){let A=`${(t.extractedFields.length===0?"":`
205
+ `)+f.title}:`,h=vl(n,A,t.s);if(h===-2||h===-3)return!0;if(h===-4)return t.inBlock=!0,!0;h>=0&&(d===-1||h<d)&&(d=h,m=A.length,l=g,p=f)}if(d===-1){if(s)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 gs(g)}break}if(a&&p&&a.name!==p.name)throw gs(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=hs(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&&l!==void 0&&(t.currField=p,t.currFieldIndex=l),p&&!t.extractedFields.includes(p)&&t.extractedFields.push(p),p&&t.streamedIndex[p.name]===void 0&&(t.streamedIndex[p.name]=0)}},Ia=(o,e,t,n,r)=>{let s=r?.strictMode??!1,i=r?.treatAllFieldsOptional??!1,a=r?.deferRequiredCheckForStreaming??!1,u=r?.forceFinalize??!1;if(t.currField){let c=n.length,l=o.getOutputFields();for(let m of l){if(m.name===t.currField.name)continue;let g=`
206
+ ${m.title}:`,f=n.indexOf(g,t.s);f!==-1&&f<c&&(c=f)}let p=n.substring(t.s,c).trim(),d=hs(t.currField,p);d!==void 0&&(e[t.currField.name]=d)}if(s&&!t.currField&&t.extractedFields.length===0&&n.trim()){let p=o.getOutputFields().find(d=>!d.isOptional);if(p)throw gs(p)}if(Fm(o,e,n,t),!i){let c=t.currField!==void 0||(t.extractedFields?.length??0)>0;s||u?ya(t,e,o.getOutputFields()):c||ya(t,e,o.getOutputFields())}},Fm=(o,e,t,n)=>{let r=o.getOutputFields();if(r.length===1){let i=r[0];if(i){let a=`${i.title}:`,u=t.indexOf(a);if(u!==-1){let c=u+a.length,l=`
207
207
  ${i.title}:`,p=t.indexOf(l,c),d=t.substring(c,p===-1?t.length:p).trim();if(d)try{let m=hs(i,d);if(m!==void 0){e[i.name]=m;return}}catch{}}}}let s=t.split(`
208
- `);for(let i of r){if(i.name in e)continue;let a=`${i.title}:`;for(let u of s){let c=u.trim();if(c.startsWith(a)){let l=c.substring(a.length).trim();if(l)try{let p=hs(i,l);if(p!==void 0){e[i.name]=p;break}}catch(p){if(!i.isOptional)throw p}break}}}},Rl=(o,e,t=!1)=>{switch(o.type?.name){case"code":return ya(e);case"string":return e;case"number":{let n=Number(e);if(Number.isNaN(n)){if(o.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(o.isOptional&&!t)return;throw new Error("Invalid boolean")}case"date":return bl(o,e,t);case"datetime":return Tl(o,e,t);case"class":{let n=e;if(o.type.options&&!o.type.options.includes(n)){if(o.isOptional)return;throw new Error(`Invalid class '${e}', expected one of the following: ${o.type.options.join(", ")}`)}return n}default:return e}};function*vl(o,e,t,n,r,s){let{name:i,isInternal:a}=e,{isArray:u,name:c}=e.type??{};if(a||u||c&&c!=="string"&&c!=="code")return;let l=r.streamedIndex[i]??0,p=l===0,d=(t<0?0:t)+l,m=o.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:s,delta:{[i]:f}},r.streamedIndex[i]=l+g.length)}function*Ca(o,e,t,n,r){for(let i of n.prevFields??[]){let{field:a,s:u,e:c}=i;yield*vl(e,a,u,c,n,r)}if(n.prevFields=void 0,n.inAssumedField&&!(o.getOutputFields().filter(u=>!u.isInternal).length===1)||!n.currField||n.currField.isInternal)return;yield*vl(e,n.currField,n.s,e.length,n,r);let s=o.getOutputFields();for(let i of Object.keys(t)){let a=s.find(l=>l.name===i);if(!a||a.isInternal)continue;let u=t[i];if(Array.isArray(u)){let l=n.streamedIndex?.[i]??0,p=u.slice(l);p&&p.length>0&&(yield{index:r,delta:{[i]:p}},n.streamedIndex[i]=l+p.length);continue}let c=typeof u=="string"?u:void 0;if(!n.streamedIndex[i])yield{index:r,delta:{[i]:u}},n.streamedIndex[i]=c?c.length:1;else if(c){let l=n.streamedIndex[i];if(c.length>l){let p=c.substring(l);yield{index:r,delta:{[i]:p}},n.streamedIndex[i]=c.length}}}}function hs(o,e){if(!e||e===""||/^(null|undefined)\s*$/i.test(e)){if(o.isOptional)return;throw fs(o)}let t;if(o.type?.name==="json"&&!o.type?.isArray)try{let r=ya(e);return t=JSON.parse(r),t}catch(r){throw sl(o,r.message)}if(o.type?.isArray)try{try{t=JSON.parse(e)}catch{t=Il(e)}if(!Array.isArray(t))throw new Error("Expected an array")}catch(r){let s=r.message;if(s.includes("no valid list items found")||s==="Expected an array")t=[e];else throw il(o,s)}try{if(Array.isArray(t)){for(let[r,s]of t.entries())if(s!==void 0){let i=typeof s=="string"?s.trim():s;if(typeof i=="string"&&(o.type?.name==="object"||o.type?.name==="json"))try{let a=ya(i);i=JSON.parse(a)}catch{}t[r]=Rl(o,i,!0)}}else t=Rl(o,e)}catch(r){throw al(o,e,r.message)}if(typeof t=="string"&&t==="")return;let n=o.type;if(n&&t!==void 0&&(n.name==="url"&&Vt(t,o),(n.name==="string"||n.name==="code")&&yt(t,o),n.name==="number"&&bt(t,o),n.isArray&&Array.isArray(t)))for(let r of t)r!==void 0&&(n.name==="string"||n.name==="code"?yt(r,o):n.name==="number"&&bt(r,o));return t}function Vn(o,e,t){let n=o.getOutputFields();for(let r of n){let s=e[r.name];if(s==null){if(!r.isOptional&&!t?.allowMissingRequired)throw fs(r);continue}let i=r.type;if(i){if(i.name==="url"&&Vt(s,r),(i.name==="string"||i.name==="code")&&yt(s,r),i.name==="number"&&bt(s,r),i.isArray&&Array.isArray(s))for(let a of s)a!=null&&(i.name==="url"?Vt(a,r):i.name==="string"||i.name==="code"?yt(a,r):i.name==="number"&&bt(a,r));if(i.name==="object"&&i.fields&&typeof s=="object"&&!Array.isArray(s)&&xs(r,s,t),i.isArray&&i.fields&&Array.isArray(s)&&i.name==="object")for(let a of s)a&&typeof a=="object"&&xs(r,a,t)}}}function xs(o,e,t){let n=o.type?.fields;if(!(!n||typeof n!="object"))for(let[r,s]of Object.entries(n)){let i={name:r,title:r,description:s.description,type:{name:s.type,isArray:s.isArray,options:s.options,fields:s.fields,minLength:s.minLength,maxLength:s.maxLength,minimum:s.minimum,maximum:s.maximum,pattern:s.pattern,patternDescription:s.patternDescription,format:s.format},isOptional:s.isOptional??!1,isInternal:s.isInternal??!1},a=e[i.name];if(a==null){if(!i.isOptional&&!t?.allowMissingRequired)throw fs(i);continue}let u=i.type;if(u){if(u.name==="url"&&Vt(a,i),(u.name==="string"||u.name==="code")&&yt(a,i),u.name==="number"&&bt(a,i),u.isArray&&Array.isArray(a))for(let c of a)c!=null&&(u.name==="url"?Vt(c,i):u.name==="string"||u.name==="code"?yt(c,i):u.name==="number"&&bt(c,i));if(u.name==="object"&&u.fields&&typeof a=="object"&&!Array.isArray(a)&&xs(i,a,t),u.isArray&&u.fields&&Array.isArray(a)&&u.name==="object")for(let c of a)c&&typeof c=="object"&&xs(i,c,t)}}}var ya=o=>{let t=/```([A-Za-z]*)\s*([\s\S]*?)\s*```/g.exec(o);return t?t.length===3?t[2]:t.length===2?t[1]:o:o};async function Kr(o,e,t,n){for(let r of o){if(e[r.field.name]===void 0)continue;let s=r.process,i=await s(e[r.field.name],{sessionId:n,values:e,done:!0});Sl(r.field,t,i,n)}}async function Ia(o,e,t,n,r,s,i=!1){for(let a of o){if(t.currField?.name!==a.field.name)continue;let u=e.substring(t.s);t.currField?.type?.name==="code"&&(u=u.replace(/^[ ]*```[a-zA-Z0-9]*\n\s*/,""),u=u.replace(/\s*```\s*$/,""));let c=a.process,l=await c(u,{sessionId:s,values:r,done:i});Sl(t.currField,n,l,s)}}var Sl=(o,e,t,n)=>{if(t===void 0||typeof t=="string"&&(t===""||/^(null|undefined)\s*$/i.test(t)))return;let r=String(t),s=r;e.addRequest([{role:"user",content:[{type:"text",text:s}]}],n),e.addTag("processor",n)};function kl(o,e){if(!e)return o;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 o;let n=t.join(". ");return!o||o.trim().length===0?n:`${o.trim().endsWith(".")?o.trim():`${o.trim()}.`} ${n}`}function Jt(o,e="Schema"){if("name"in o&&"type"in o)return ys(o);let t={},n=[];for(let r of o){if(r.isInternal)continue;let s=ys(r);t[r.name]=s,r.isOptional||n.push(r.name)}return{type:"object",title:e,properties:t,required:n,additionalProperties:!1}}function ys(o,e=!1){let t=o.type,n=kl(o.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: ${o.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[s,i]of Object.entries(t.fields)){let a={name:s,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[s]=ys(a,!0),i.isOptional||r.items.required.push(s)}}else if(t.name==="class"&&t.options)r.items={type:"string",enum:t.options};else{let s=kl(t.description||o.description,t);r.items={type:Ol(t.name)},s&&(r.items.description=s),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[s,i]of Object.entries(t.fields)){let a={name:s,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[s]=ys(a,!0),i.isOptional||r.required.push(s)}}else t?.name==="class"&&t.options?(r.type="string",r.enum=t.options):(r.type=Ol(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 Ol(o){switch(o){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 bs(o){if(!o||typeof o!="object")throw new Error("Schema must be an object");if(o.type==="array"){if(!o.items)throw new Error('Array schema is missing an "items" definition (required by JSON Schema and all LLM providers for function tools)');bs(o.items)}else if(o.type==="object"&&o.properties)for(let e of Object.values(o.properties))bs(e)}var an=class extends Error{calls;constructor(e){super(`Stop function executed: ${e.map(t=>t.func.name).join(", ")}`),this.name="AxStopFunctionCallException",this.calls=e}},Vr=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()}},Jr=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}'
208
+ `);for(let i of r){if(i.name in e)continue;let a=`${i.title}:`;for(let u of s){let c=u.trim();if(c.startsWith(a)){let l=c.substring(a.length).trim();if(l)try{let p=hs(i,l);if(p!==void 0){e[i.name]=p;break}}catch(p){if(!i.isOptional)throw p}break}}}},Sl=(o,e,t=!1)=>{switch(o.type?.name){case"code":return ba(e);case"string":return e;case"number":{let n=Number(e);if(Number.isNaN(n)){if(o.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(o.isOptional&&!t)return;throw new Error("Invalid boolean")}case"date":return Il(o,e,t);case"datetime":return Tl(o,e,t);case"class":{let n=e;if(o.type.options&&!o.type.options.includes(n)){if(o.isOptional)return;throw new Error(`Invalid class '${e}', expected one of the following: ${o.type.options.join(", ")}`)}return n}default:return e}};function*kl(o,e,t,n,r,s){let{name:i,isInternal:a}=e,{isArray:u,name:c}=e.type??{};if(a||u||c&&c!=="string"&&c!=="code")return;let l=r.streamedIndex[i]??0,p=l===0,d=(t<0?0:t)+l,m=o.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:s,delta:{[i]:f}},r.streamedIndex[i]=l+g.length)}function*Ta(o,e,t,n,r){for(let i of n.prevFields??[]){let{field:a,s:u,e:c}=i;yield*kl(e,a,u,c,n,r)}if(n.prevFields=void 0,n.inAssumedField&&!(o.getOutputFields().filter(u=>!u.isInternal).length===1)||!n.currField||n.currField.isInternal)return;yield*kl(e,n.currField,n.s,e.length,n,r);let s=o.getOutputFields();for(let i of Object.keys(t)){let a=s.find(l=>l.name===i);if(!a||a.isInternal)continue;let u=t[i];if(Array.isArray(u)){let l=n.streamedIndex?.[i]??0,p=u.slice(l);p&&p.length>0&&(yield{index:r,delta:{[i]:p}},n.streamedIndex[i]=l+p.length);continue}let c=typeof u=="string"?u:void 0;if(!n.streamedIndex[i])yield{index:r,delta:{[i]:u}},n.streamedIndex[i]=c?c.length:1;else if(c){let l=n.streamedIndex[i];if(c.length>l){let p=c.substring(l);yield{index:r,delta:{[i]:p}},n.streamedIndex[i]=c.length}}}}function hs(o,e){if(!e||e===""||/^(null|undefined)\s*$/i.test(e)){if(o.isOptional)return;throw fs(o)}let t;if(o.type?.name==="json"&&!o.type?.isArray)try{let r=ba(e);return t=JSON.parse(r),t}catch(r){throw al(o,r.message)}if(o.type?.isArray)try{try{t=JSON.parse(e)}catch{t=Rl(e)}if(!Array.isArray(t))throw new Error("Expected an array")}catch(r){let s=r.message;if(s.includes("no valid list items found")||s==="Expected an array")t=[e];else throw ul(o,s)}try{if(Array.isArray(t)){for(let[r,s]of t.entries())if(s!==void 0){let i=typeof s=="string"?s.trim():s;if(typeof i=="string"&&(o.type?.name==="object"||o.type?.name==="json"))try{let a=ba(i);i=JSON.parse(a)}catch{}t[r]=Sl(o,i,!0)}}else t=Sl(o,e)}catch(r){throw cl(o,e,r.message)}if(typeof t=="string"&&t==="")return;let n=o.type;if(n&&t!==void 0&&(n.name==="url"&&Wt(t,o),(n.name==="string"||n.name==="code")&&yt(t,o),n.name==="number"&&bt(t,o),n.isArray&&Array.isArray(t)))for(let r of t)r!==void 0&&(n.name==="string"||n.name==="code"?yt(r,o):n.name==="number"&&bt(r,o));return t}function Qn(o,e,t){let n=o.getOutputFields();for(let r of n){let s=e[r.name];if(s==null){if(!r.isOptional&&!t?.allowMissingRequired)throw fs(r);continue}let i=r.type;if(i){if(i.name==="url"&&Wt(s,r),(i.name==="string"||i.name==="code")&&yt(s,r),i.name==="number"&&bt(s,r),i.isArray&&Array.isArray(s))for(let a of s)a!=null&&(i.name==="url"?Wt(a,r):i.name==="string"||i.name==="code"?yt(a,r):i.name==="number"&&bt(a,r));if(i.name==="object"&&i.fields&&typeof s=="object"&&!Array.isArray(s)&&xs(r,s,t),i.isArray&&i.fields&&Array.isArray(s)&&i.name==="object")for(let a of s)a&&typeof a=="object"&&xs(r,a,t)}}}function xs(o,e,t){let n=o.type?.fields;if(!(!n||typeof n!="object"))for(let[r,s]of Object.entries(n)){let i={name:r,title:r,description:s.description,type:{name:s.type,isArray:s.isArray,options:s.options,fields:s.fields,minLength:s.minLength,maxLength:s.maxLength,minimum:s.minimum,maximum:s.maximum,pattern:s.pattern,patternDescription:s.patternDescription,format:s.format},isOptional:s.isOptional??!1,isInternal:s.isInternal??!1},a=e[i.name];if(a==null){if(!i.isOptional&&!t?.allowMissingRequired)throw fs(i);continue}let u=i.type;if(u){if(u.name==="url"&&Wt(a,i),(u.name==="string"||u.name==="code")&&yt(a,i),u.name==="number"&&bt(a,i),u.isArray&&Array.isArray(a))for(let c of a)c!=null&&(u.name==="url"?Wt(c,i):u.name==="string"||u.name==="code"?yt(c,i):u.name==="number"&&bt(c,i));if(u.name==="object"&&u.fields&&typeof a=="object"&&!Array.isArray(a)&&xs(i,a,t),u.isArray&&u.fields&&Array.isArray(a)&&u.name==="object")for(let c of a)c&&typeof c=="object"&&xs(i,c,t)}}}var ba=o=>{let t=/```([A-Za-z]*)\s*([\s\S]*?)\s*```/g.exec(o);return t?t.length===3?t[2]:t.length===2?t[1]:o:o};async function Wr(o,e,t,n){for(let r of o){if(e[r.field.name]===void 0)continue;let s=r.process,i=await s(e[r.field.name],{sessionId:n,values:e,done:!0});Ol(r.field,t,i,n)}}async function wa(o,e,t,n,r,s,i=!1){for(let a of o){if(t.currField?.name!==a.field.name)continue;let u=e.substring(t.s);t.currField?.type?.name==="code"&&(u=u.replace(/^[ ]*```[a-zA-Z0-9]*\n\s*/,""),u=u.replace(/\s*```\s*$/,""));let c=a.process,l=await c(u,{sessionId:s,values:r,done:i});Ol(t.currField,n,l,s)}}var Ol=(o,e,t,n)=>{if(t===void 0||typeof t=="string"&&(t===""||/^(null|undefined)\s*$/i.test(t)))return;let r=String(t),s=r;e.addRequest([{role:"user",content:[{type:"text",text:s}]}],n),e.addTag("processor",n)};function El(o,e){if(!e)return o;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 o;let n=t.join(". ");return!o||o.trim().length===0?n:`${o.trim().endsWith(".")?o.trim():`${o.trim()}.`} ${n}`}function Jt(o,e="Schema"){if("name"in o&&"type"in o)return ys(o);let t={},n=[];for(let r of o){if(r.isInternal)continue;let s=ys(r);t[r.name]=s,r.isOptional||n.push(r.name)}return{type:"object",title:e,properties:t,required:n,additionalProperties:!1}}function ys(o,e=!1){let t=o.type,n=El(o.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: ${o.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[s,i]of Object.entries(t.fields)){let a={name:s,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[s]=ys(a,!0),i.isOptional||r.items.required.push(s)}}else if(t.name==="class"&&t.options)r.items={type:"string",enum:t.options};else{let s=El(t.description||o.description,t);r.items={type:Ml(t.name)},s&&(r.items.description=s),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[s,i]of Object.entries(t.fields)){let a={name:s,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[s]=ys(a,!0),i.isOptional||r.required.push(s)}}else t?.name==="class"&&t.options?(r.type="string",r.enum=t.options):(r.type=Ml(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 Ml(o){switch(o){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 bs(o){if(!o||typeof o!="object")throw new Error("Schema must be an object");if(o.type==="array"){if(!o.items)throw new Error('Array schema is missing an "items" definition (required by JSON Schema and all LLM providers for function tools)');bs(o.items)}else if(o.type==="object"&&o.properties)for(let e of Object.values(o.properties))bs(e)}var un=class extends Error{calls;constructor(e){super(`Stop function executed: ${e.map(t=>t.func.name).join(", ")}`),this.name="AxStopFunctionCallException",this.calls=e}},Jr=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()}},Qr=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()}},Qr=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(c){throw new Error(`Invalid function arguments: ${t.args}`,{cause:c})}else r=t.args;let s=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,s):await e.func(r):i=e.func.length===1?await e.func(s):await e.func();let u=(n?.functionResultFormatter??fe.functionResultFormatter)(i);return{formatted:String(u),rawResult:i,parsedArgs:r}};executeWithDetails=async(e,t)=>{let n=i=>i.replace(/[^a-zA-Z0-9]/g,"").toLowerCase(),r=n(e.name),s=this.funcList.find(i=>i.name===e.name);if(s||(s=this.funcList.find(i=>n(i.name)===r)),!s)throw new Error(`Function not found: ${e.name}`);if(!s.func)throw new Error(`No handler for function: ${e.name}`);try{return await this.executeFunction(s,e,t)}catch(i){throw i instanceof Vr?new Jr(i.getFields(),s,e.id):i}};execute=async(e,t)=>(await this.executeWithDetails(e,t)).formatted},un=(o,e)=>{if(o.length===0)return[...e??[]];let t=o.map(n=>"toFunction"in n?n.toFunction():n).flat();for(let n of t.filter(r=>r.parameters))if(n.parameters)try{bs(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()}},Yr=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(c){throw new Error(`Invalid function arguments: ${t.args}`,{cause:c})}else r=t.args;let s=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,s):await e.func(r):i=e.func.length===1?await e.func(s):await e.func();let u=(n?.functionResultFormatter??he.functionResultFormatter)(i);return{formatted:String(u),rawResult:i,parsedArgs:r}};executeWithDetails=async(e,t)=>{let n=i=>i.replace(/[^a-zA-Z0-9]/g,"").toLowerCase(),r=n(e.name),s=this.funcList.find(i=>i.name===e.name);if(s||(s=this.funcList.find(i=>n(i.name)===r)),!s)throw new Error(`Function not found: ${e.name}`);if(!s.func)throw new Error(`No handler for function: ${e.name}`);try{return await this.executeFunction(s,e,t)}catch(i){throw i instanceof Jr?new Qr(i.getFields(),s,e.id):i}};execute=async(e,t)=>(await this.executeWithDetails(e,t)).formatted},cn=(o,e)=>{if(o.length===0)return[...e??[]];let t=o.map(n=>"toFunction"in n?n.toFunction():n).flat();for(let n of t.filter(r=>r.parameters))if(n.parameters)try{bs(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]},Ts=async({ai:o,functionList:e,functionCalls:t,mem:n,sessionId:r,traceId:s,span:i,excludeContentFromTrace:a,index:u,functionResultFormatter:c,logger:l,debug:p,stopFunctionNames:d,step:m,abortSignal:g})=>{let f=new Qr(e),x=new Set,A=[],h=R=>{let M=E=>E.replace(/[^a-zA-Z0-9]/g,"").toLowerCase(),I=M(R),O=e.find(E=>E.name===R);return O||(O=e.find(E=>M(E.name)===I)),O},y=t.map(R=>{if(!R.id)throw new Error(`Function ${R.name} did not return an ID`);let M=o.getOptions().tracer??fe.tracer;return M?M.startActiveSpan(`Tool: ${R.name}`,async I=>{try{I?.setAttributes?.({"tool.name":R.name,"tool.mode":"native","function.id":R.id,"session.id":r??""});let{formatted:O,rawResult:E,parsedArgs:$}=await f.executeWithDetails(R,{sessionId:r,ai:o,functionResultFormatter:c,traceId:I?.spanContext?.().traceId??s,stopFunctionNames:d,step:m,abortSignal:g});if(x.add(R.name.toLowerCase()),m?._recordFunctionCall(R.name,$,E),d?.includes(R.name.toLowerCase())){let N=h(R.name);N&&A.push({func:N,args:$,result:E})}if(a?I.addEvent("gen_ai.tool.message",{name:R.name}):I.addEvent("gen_ai.tool.message",{name:R.name,args:R.args,result:O??""}),i){let N={name:R.name};a||(N.args=R.args,N.result=O??""),i.addEvent("function.call",N)}return{result:O??"",role:"function",functionId:R.id,index:u}}catch(O){if(I?.recordException?.(O),O instanceof Jr){let E=O.getFixingInstructions(),$={name:R.name,message:O.toString()};return a||($.args=R.args,$.fixing_instructions=E),I?.addEvent?.("function.error",$),p&&Ri(O,u,E,l),{functionId:R.id,isError:!0,index:u,result:E,role:"function"}}throw O}finally{I?.end?.()}}):f.executeWithDetails(R,{sessionId:r,ai:o,functionResultFormatter:c,traceId:s,stopFunctionNames:d,step:m,abortSignal:g}).then(({formatted:I,rawResult:O,parsedArgs:E})=>{if(x.add(R.name.toLowerCase()),m?._recordFunctionCall(R.name,E,O),d?.includes(R.name.toLowerCase())){let $=h(R.name);$&&A.push({func:$,args:E,result:O})}if(i){let $={name:R.name};a||($.args=R.args,$.result=I??""),i.addEvent("function.call",$)}return{result:I??"",role:"function",functionId:R.id,index:u}}).catch(I=>{if(!(I instanceof Jr))throw I;let O=I.getFixingInstructions();if(i){let E={name:R.name,message:I.toString()};a||(E.args=R.args,E.fixing_instructions=O),i.addEvent("function.error",E)}return p&&Ri(I,u,O,l),{functionId:R.id,isError:!0,index:u,result:O,role:"function"}})}),C=(await Promise.all(y)).map(R=>R.result===void 0||R.result===""?{...R,result:"done"}:R);if(n.addFunctionResults(C,r),p){let R=C.filter(M=>!M.isError);R.length>0&&Ku(R,l)}if(A.length>0)throw new an(A);return x};function wa(o,e,t,n){if(!e||e.length===0)return;if(!o.getFeatures(n).functions)throw new Error("Functions are not supported by the AI service");return e.map(s=>({id:s.id,name:s.function.name,args:s.function.params}))}function El(o,e,t,n){let r=e;return!t&&(r==="required"||typeof r=="function")?{functions:[],functionCall:void 0}:o?{functions:o.map(i=>"toFunction"in i?i.toFunction():i).flat(),functionCall:r}:{functions:[],functionCall:r}}function Mm(o){let e=0,t=!1,n=!1,r=!1,s=!1,i=[];for(let a=0;a<o.length;a++){let u=o[a];if(n){n=!1;continue}if(u==="\\"){n=!0;continue}if(u==='"'){t=!t;continue}t||(u==="{"?(i.push("{"),e++):u==="["?(i.push("["),e++):u==="}"?i.length>0&&i[i.length-1]==="{"&&(i.pop(),e--):u==="]"&&i.length>0&&i[i.length-1]==="["&&(i.pop(),e--))}if(i.length>0){let a=i[i.length-1];r=a==="[",s=a==="{"}return{nestingLevel:e,inString:t,inArray:r,inObject:s}}function Ml(o){if(!o.trim())return{parsed:null,partialMarker:null};try{return{parsed:JSON.parse(o),partialMarker:null}}catch{}let e=Mm(o),t=Pm(o);try{return{parsed:JSON.parse(t),partialMarker:e}}catch{return{parsed:null,partialMarker:e}}}function Pm(o){let e=o.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 s=0;s<e.length;s++){let i=e[s];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*Pl({res:o,usage:e,states:t,debug:n,stepContext:r,...s}){let i=(s.ai.getFeatures().functionCot??!1)&&s.functions!==void 0&&s.functions.length>0,a,u=[],c=o.getReader();try{for(;;){let{done:l,value:p}=await c.read();if(l)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&&u.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*Fm({...s,result:m,skipEarlyFail:i,state:g,debug:n})}}}finally{c.releaseLock()}for(let l of t)yield*_m({...s,state:l,debug:n,stepContext:r});if(a){if(u.length){let l=Array.from(new Map(u.filter(p=>p.url).map(p=>[p.url,p])).values());a.citations=l}if(e.push(a),n&&s.logger){let l=structuredClone(a);delete l.citations,s.logger({name:"ChatResponseUsage",value:l}),a.citations&&a.citations.length>0&&s.logger({name:"ChatResponseCitations",value:a.citations})}}}async function*Fm({result:o,mem:e,sessionId:t,strictMode:n,skipEarlyFail:r,treatAllFieldsOptional:s,state:i,signature:a,streamingFieldProcessors:u,thoughtFieldName:c,streamingAsserts:l,asserts:p}){if(o.functionCalls&&o.functionCalls.length>0)Eo(i.functionCalls,o.functionCalls),e.updateResult({name:o.name,content:o.content,functionCalls:i.functionCalls,thoughtBlocks:o.thoughtBlocks,delta:o.functionCalls?.[0]?.function?.params,index:o.index},t);else if(o.content&&o.content.length>0){o.thought&&o.thought.length>0&&(yield{index:o.index,delta:{[c]:o.thought}}),i.content+=o.content,e.updateResult({name:o.name,content:i.content,thoughtBlocks:o.thoughtBlocks,delta:o.content,index:o.index},t);let d=a.getOutputFields();if(a.hasComplexFields()){let{parsed:f,partialMarker:x}=Ml(i.content);if(f&&typeof f=="object"){let A={},h={};for(let y of Object.keys(f))if(d.some(T=>T.name===y)){let T=f[y],C=i.values[y];if(Array.isArray(T)&&T.length>0&&Nm(T,x)&&(T=T.slice(0,-1)),h[y]=T,typeof T=="string"&&typeof C=="string"&&T.startsWith(C)){let R=T.slice(C.length);R&&(A[y]=R)}else Array.isArray(T)&&Array.isArray(C)?T.length>C.length&&(A[y]=T.slice(C.length)):JSON.stringify(T)!==JSON.stringify(C)&&(Array.isArray(T)||(A[y]=T))}try{Vn(a,h,{allowMissingRequired:!0})}catch{}Object.assign(i.values,h),Object.keys(A).length>0&&(yield{index:o.index,delta:A});return}}if(ba(a,i.values,i.xstate,i.content,{strictMode:n,skipEarlyFail:r,treatAllFieldsOptional:s}))return;l.length!==0&&await ta(l,i.xstate,i.content),u.length!==0&&await Ia(u,i.content,i.xstate,e,i.values,t),yield*Ca(a,i.content,i.values,i.xstate,o.index),await Hn(p,i.values)}else o.thought&&o.thought.length>0?(i.values[c]=(i.values[c]??"")+o.thought,yield{index:o.index,delta:{[c]:o.thought}},e.updateResult({name:o.name,content:i.content,delta:"",index:o.index,thought:o.thought,thoughtBlocks:o.thoughtBlocks},t)):o.thoughtBlocks&&o.thoughtBlocks.length>0&&e.updateResult({name:o.name,content:i.content,delta:"",index:o.index,thoughtBlocks:o.thoughtBlocks},t);if(o.finishReason==="length")throw new Error(`Max tokens reached before completion
215
- Content: ${i.content}`)}async function*_m({state:o,signature:e,ai:t,model:n,functions:r,mem:s,sessionId:i,traceId:a,span:u,strictMode:c,excludeContentFromTrace:l,streamingAsserts:p,asserts:d,fieldProcessors:m,streamingFieldProcessors:g,functionResultFormatter:f,signatureToolCallingManager:x,logger:A,debug:h,stopFunctionNames:y,stepContext:T,abortSignal:C}){let R=x?void 0:wa(t,o.functionCalls,o.values,n);if(R){if(!r)throw new Error("Functions are not defined");let M=await Ts({ai:t,functionList:r,functionCalls:R,mem:s,sessionId:i,traceId:a,span:u,index:o.index,excludeContentFromTrace:l,functionResultFormatter:f,logger:A,debug:h,stopFunctionNames:y,step:T,abortSignal:C});o.functionsExecuted=new Set([...o.functionsExecuted,...M]),o.functionCalls=[]}else{let M=e.getOutputFields(),I=e.hasComplexFields(),O=!1;if(I)try{let E=JSON.parse(o.content),$={};for(let N of Object.keys(E))if(M.some(S=>S.name===N)){let S=E[N],v=o.values[N];if(typeof S=="string"&&typeof v=="string"&&S.startsWith(v)){let F=S.slice(v.length);F&&($[N]=F)}else Array.isArray(S)&&Array.isArray(v)?S.length>v.length&&($[N]=S.slice(v.length)):JSON.stringify(S)!==JSON.stringify(v)&&(Array.isArray(S)||($[N]=S))}try{Vn(e,$,{allowMissingRequired:!0})}catch(N){let S=(N.message||"").toLowerCase();if(S.includes("at least")||S.includes("at most")||S.includes("must match pattern")||S.includes("invalid url")||S.includes("required")||S.includes("missing")||S.includes("valid email")||S.includes("number must be"))throw N}for(let N of Object.keys(E))M.some(S=>S.name===N)&&(o.values[N]=E[N]);yield{index:o.index,delta:$},O=!0}catch(E){let $=(E.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 E}if(!O){let E=x!==void 0;Ta(e,o.values,o.xstate,o.content,{strictMode:c,treatAllFieldsOptional:E,deferRequiredCheckForStreaming:!0,forceFinalize:!0})}if(x){let E=await x.processResults(o.values);if(E&&E.length>0){if(!r)throw new Error("Functions are not defined");let $=await Ts({ai:t,functionList:r,functionCalls:E,mem:s,sessionId:i,traceId:a,span:u,index:o.index,excludeContentFromTrace:l,functionResultFormatter:f,logger:A,debug:h,stopFunctionNames:y,step:T,abortSignal:C});o.functionsExecuted=new Set([...o.functionsExecuted,...$]),s.updateResult({name:void 0,content:o.content,functionCalls:E.map(N=>({id:N.id,type:"function",function:{name:N.name,params:N.args}})),index:o.index},i);return}}await ta(p,o.xstate,o.content,!0),await Hn(d,o.values),m.length&&await Kr(m,o.values,s,i),g.length!==0&&await Ia(g,o.content,o.xstate,s,o.values,i,!0),yield*Ca(e,o.content,o.values,o.xstate,o.index)}}async function*Fl({ai:o,res:e,mem:t,sessionId:n,traceId:r,functions:s,span:i,strictMode:a,states:u,usage:c,excludeContentFromTrace:l,asserts:p,fieldProcessors:d,thoughtFieldName:m,signature:g,functionResultFormatter:f,logger:x,debug:A,signatureToolCallingManager:h,stopFunctionNames:y,disableMemoryCleanup:T,stepContext:C,abortSignal:R}){let M=e.results??[],I=h!==void 0;t.addResponse(M,n);let O=[];for(let S of M)if(Array.isArray(S?.citations))for(let v of S.citations)v?.url&&O.push({url:v.url,title:v.title,description:v.description,license:v.license,publicationDate:v.publicationDate,snippet:v.snippet});for(let S of M){let v=u[S.index];if(!v)throw new Error(`No state found for result (index: ${S.index})`);if(e.modelUsage){let F=Array.from(new Map(O.filter(L=>L.url).map(L=>[L.url,L])).values()),P={...e.modelUsage,...F.length?{citations:F}:{}};if(c.push(P),A&&x){let L=structuredClone(P);delete L.citations,x({name:"ChatResponseUsage",value:L}),P.citations&&P.citations.length>0&&x({name:"ChatResponseCitations",value:P.citations})}}if(h&&S.content){S.thought&&S.thought.length>0&&(v.values[m]=S.thought),As(g,v.values,S.content,{strictMode:a,treatAllFieldsOptional:I});let P=(await h.processResults(v.values))?.map(L=>({id:L.id,type:"function",function:{name:L.name,params:L.args}}));P&&P.length>0&&t.updateResult({name:S.name,content:S.content,functionCalls:P,index:S.index},n)}if(S.functionCalls?.length){let F=wa(o,S.functionCalls,v.values);if(F&&F.length>0){if(!s)throw new Error("Functions are not defined");let P;try{P=await Ts({ai:o,functionList:s,functionCalls:F,mem:t,sessionId:n,traceId:r,span:i,excludeContentFromTrace:l,index:S.index,functionResultFormatter:f,logger:x,debug:A,stopFunctionNames:y,step:C,abortSignal:R})}catch(L){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),L}v.functionsExecuted=new Set([...v.functionsExecuted,...P])}}else if(S.content){S.thought&&S.thought.length>0&&(v.values[m]=S.thought);let F=g.getOutputFields();if(g.hasComplexFields())try{let L=JSON.parse(S.content),D={};for(let j of Object.keys(L))F.some(G=>G.name===j)&&(D[j]=L[j]);Vn(g,D),Object.assign(v.values,D)}catch(L){let D=L instanceof SyntaxError;if((L.name?.includes("ValidationError")||L.name?.includes("Error"))&&!D){let G=(L.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 L}if(D)As(g,v.values,S.content,{strictMode:a,treatAllFieldsOptional:I});else throw L}else As(g,v.values,S.content,{strictMode:a,treatAllFieldsOptional:I})}if(await Hn(p,v.values),T||(t.removeByTag("correction",n),t.removeByTag("error",n)),d.length&&await Kr(d,v.values,t,n),S.finishReason==="length")throw new Error(`Max tokens reached before completion
216
- Content: ${S.content}`)}let E=u.map(S=>S.values);for(let S of E)for(let v of g.getOutputFields())v.isInternal&&delete S[v.name];let $=g.getOutputFields(),N=E.map((S,v)=>{let F={};for(let P of $)P.isInternal||(F[P.name]=S[P.name]);return S[m]!==void 0&&(F[m]=S[m]),{index:v,delta:F}});for(let S of N)yield S}function Nm(o,e){return e?!!(e.nestingLevel>0||e.inArray||e.inObject):!1}function _l(o,e,t,n){let r=o.getLast(n);if(!r)return!0;for(let[s,i]of t.entries()){let a=e?Array.from(e).some(p=>i.functionsExecuted.has(p)):!1;if(!r.chat[s])throw new Error(`No chat message found for result (index: ${s})`);let c=r.role==="function",l=r.tags?r.tags.some(p=>p==="processor"):!1;if(c&&e&&a||!(c||l))return!1}return!0}var Lm=["none","minimal","low","medium","high","highest"];function Ra(o,e,t){let n={};if(e.model!==!1){let a=o.getModelList();if(a&&a.length>0){let u=a.filter(c=>"model"in c);if(u.length>0){let c=u.map(p=>p.key),l=u.map(p=>`${p.key} (${p.description})`);n.model={type:"string",enum:c,description:`${t&&c.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: ${l.join(", ")}`}}}}e.thinkingBudget!==!1&&(n.thinkingBudget={type:"string",enum:[...Lm],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=un(e.functions);let a=r.map(c=>c.name),u=r.map(c=>`${c.name} (${c.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: ${u.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 s=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,u)=>{let c=u?.step;if(!c)return"Generation parameters adjusted for next response.";if(a?.model&&c.setModel(a.model),a?.thinkingBudget&&c.setThinkingBudget(a.thinkingBudget),a?.temperature!==void 0&&c.setTemperature(a.temperature),a?.addFunctions?.length&&s){let l=s.filter(p=>a.addFunctions.includes(p.name));l.length>0&&c.addFunctions(l)}return a?.removeFunctions?.length&&c.removeFunctions(...a.removeFunctions),"Generation parameters adjusted for next response."}}}var Jn=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,s){super(t);this.position=n;this.context=r;this.suggestion=s;this.name="SignatureValidationError"}},va=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),s=`${" ".repeat(n.length)}^`;return[`Position ${this.position} in signature:`,`"${n}${r}"`,` ${s}`].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 s=this.parseTypeNotClass(),i=this.match("[]");n={name:s,isArray:i}}catch(s){throw s instanceof he?s:new he(`Input field "${e}": ${s instanceof Error?s.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 u=a.split(/[,|]/).map(c=>c.trim()).filter(c=>c.length>0);if(u.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:u}}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 s=this.parseParsedString();return{name:e,desc:s?.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),s=`Invalid type "${n||"empty"}"`,i=r?`. Did you mean "${r}"?`:"",a=`${s}${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,s=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(s,Math.min(this.position,s+20));throw new he(`Unterminated string starting at position ${s}`,s,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 Nl(o){return new va(o).parse()}var Yr=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(([s,i])=>[s,Is(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(([s,i])=>[s,Is(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 Ne(e);return this._useStructuredOutputs&&(t._forceComplexFields=!0,t._hasComplexFields=void 0),t}},We=class o{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 o({...this,isOptional:!0})}array(e){return new o({...this,isArray:!0,description:e||this.description,itemDescription:e?this.description:void 0})}internal(){return new o({...this,isInternal:!0})}cache(){return new o({...this,isCached:!0})}min(e){return this.type==="string"?new o({...this,minLength:e}):this.type==="number"?new o({...this,minimum:e}):this}max(e){return this.type==="string"?new o({...this,maxLength:e}):this.type==="number"?new o({...this,maximum:e}):this}email(){return this.type==="string"?new o({...this,format:"email"}):this}url(){return this.type==="string"?new o({...this,format:"uri"}):this}regex(e,t){return this.type==="string"?new o({...this,pattern:e,patternDescription:t}):this}date(){return this.type==="string"?new o({...this,format:"date"}):this}datetime(){return this.type==="string"?new o({...this,format:"date-time"}):this}},ge=Object.assign(()=>new Yr,{string:o=>new We({type:"string",isArray:!1,description:o,isOptional:!1,isInternal:!1,isCached:!1}),number:o=>new We({type:"number",isArray:!1,description:o,isOptional:!1,isInternal:!1,isCached:!1}),boolean:o=>new We({type:"boolean",isArray:!1,description:o,isOptional:!1,isInternal:!1,isCached:!1}),json:o=>new We({type:"json",isArray:!1,description:o,isOptional:!1,isInternal:!1,isCached:!1}),datetime:o=>new We({type:"datetime",isArray:!1,description:o,isOptional:!1,isInternal:!1,isCached:!1}),date:o=>new We({type:"date",isArray:!1,description:o,isOptional:!1,isInternal:!1,isCached:!1}),class:(o,e)=>new We({type:"class",isArray:!1,options:o,description:e,isOptional:!1,isInternal:!1,isCached:!1}),image:o=>new We({type:"image",isArray:!1,description:o,isOptional:!1,isInternal:!1,isCached:!1}),audio:o=>new We({type:"audio",isArray:!1,description:o,isOptional:!1,isInternal:!1,isCached:!1}),file:o=>new We({type:"file",isArray:!1,description:o,isOptional:!1,isInternal:!1,isCached:!1}),url:o=>new We({type:"url",isArray:!1,description:o,isOptional:!1,isInternal:!1,isCached:!1}),email:o=>new We({type:"string",isArray:!1,description:o,isOptional:!1,isInternal:!1,isCached:!1,format:"email"}),code:(o,e)=>new We({type:"code",isArray:!1,description:e||o,isOptional:!1,isInternal:!1,isCached:!1}),object:(o,e)=>new We({type:"object",isArray:!1,fields:o,description:e,isOptional:!1,isInternal:!1,isCached:!1})});function Is(o){return{type:o.type,isArray:o.isArray,options:o.options,description:o.description,isOptional:o.isOptional,isInternal:o.isInternal,minLength:o.minLength,maxLength:o.maxLength,minimum:o.minimum,maximum:o.maximum,pattern:o.pattern,patternDescription:o.patternDescription,format:o.format,fields:o.fields?Object.fromEntries(Object.entries(o.fields).map(([e,t])=>[e,Is(t)])):void 0}}function Cs(o){return{type:{name:o.type,isArray:o.isArray,options:o.options?[...o.options]:void 0,fields:o.fields},description:o.description,isOptional:o.isOptional,isInternal:o.isInternal}}function Sa(o,e){return{name:o,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,Is(n)])):void 0},description:e.description,isOptional:e.isOptional||void 0,isInternal:e.isInternal||void 0,isCached:e.isCached||void 0}}function Ll(o){return o.length===0?{type:"object",properties:{}}:Jt(o,"Schema")}function $m(o){let e=Sa("__value",o);return Jt([e],"Schema").properties?.__value??{type:"json"}}var ka=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(Sa(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(Sa(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(s=>!s.code.trim()))throw new Error(`Function "${e}" examples must define non-empty code`);return{name:e,description:t,...n?{namespace:n}:{},parameters:Ll(this.argFields),...this.returnMode==="single"&&this.returnFieldType?{returns:$m(this.returnFieldType)}:this.returnMode==="fields"?{returns:Ll(this.returnFields)}:{},...this.fnExamples.length>0?{examples:this.fnExamples.map(s=>({...s}))}:{},func:this.fnHandler}}},Ul=o=>new ka(o),se=class extends Error{constructor(t,n,r){super(t);this.fieldName=n;this.suggestion=r;this.name="AxSignatureValidationError"}},Ne=class o{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=Nl(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 se(`Invalid Signature: ${n.message}`,void 0,r)}throw new se(`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 o)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 se("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 se("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 se?t:new se(`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 se("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 o(e)}parseParsedField=e=>{if(!e.name||e.name.length===0)throw new se("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 se("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 se("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);Ft(t,"input");for(let n of this.inputFields)if(n.name===t.name)throw new se(`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 se(`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 se?t:new se(`Failed to add input field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}};addOutputField=e=>{try{let t=this.parseField(e);Ft(t,"output");for(let n of this.outputFields)if(n.name===t.name)throw new se(`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 se(`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 se?t:new se(`Failed to add output field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}};setInputFields=e=>{if(!Array.isArray(e))throw new se("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 Ft(r,"input"),r});this.inputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof se?t:new se(`Failed to set input fields: ${t instanceof Error?t.message:"Unknown error"}`)}};setOutputFields=e=>{if(!Array.isArray(e))throw new se("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 Ft(r,"output"),r});this.outputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof se?t:new se(`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 o(this);return n.addInputField({name:e,...Cs(t)}),n};prependInputField=(e,t)=>{let n=new o(this),r={name:e,...Cs(t)},s=n.parseField(r);Ft(s,"input");for(let i of n.inputFields)if(i.name===s.name)throw new se(`Duplicate input field name: "${s.name}"`,s.name,"Each field name must be unique within the signature");for(let i of n.outputFields)if(i.name===s.name)throw new se(`Field name "${s.name}" appears in both inputs and outputs`,s.name,"Use different names for input and output fields to avoid confusion");return n.inputFields.unshift(s),n.invalidateValidationCache(),n.updateHashLight(),n};appendOutputField=(e,t)=>{let n=new o(this);return n.addOutputField({name:e,...Cs(t)}),n};prependOutputField=(e,t)=>{let n=new o(this),r={name:e,...Cs(t)},s=n.parseField(r);Ft(s,"output");for(let i of n.outputFields)if(i.name===s.name)throw new se(`Duplicate output field name: "${s.name}"`,s.name,"Each field name must be unique within the signature");for(let i of n.inputFields)if(i.name===s.name)throw new se(`Field name "${s.name}" appears in both inputs and outputs`,s.name,"Use different names for input and output fields to avoid confusion");return n.outputFields.unshift(s),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=>{Ft(e,"input")}),this.getOutputFields().forEach(e=>{Ft(e,"output")}),this.sigHash=mt("sha256").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=Dl(this.description,this.inputFields,this.outputFields),this._hasComplexFields=this.computeHasComplexFields(),[this.sigHash,this.sigString]}catch(e){throw e instanceof se?e:new se(`Signature validation failed: ${e instanceof Error?e.message:"Unknown error"}`)}};updateHash=()=>{try{return this.getInputFields().forEach(e=>{Ft(e,"input")}),this.getOutputFields().forEach(e=>{Ft(e,"output")}),this.validateSignatureConsistency(),this.sigHash=mt("sha256").update(this.description??"").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=Dl(this.description,this.inputFields,this.outputFields),this._hasComplexFields=this.computeHasComplexFields(),[this.sigHash,this.sigString]}catch(e){throw e instanceof se?e:new se(`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 se(`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 se(`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 se(`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 se("Signature must have at least one input field",void 0,'Add an input field. Example: "userInput:string -> ..."');if(this.outputFields.length===0)throw new se("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 Jt(e,this.description??"Schema")};toInputJSONSchema=()=>Jt(this.inputFields,this.description??"Schema")};function $l(o){let e=o.name;return o.isOptional&&(e+="?"),o.isInternal&&(e+="!"),o.type&&(e+=`:${o.type.name}`,o.type.isArray&&(e+="[]"),o.type.name==="class"&&o.type.options&&(e+=` "${o.type.options.join(" | ")}"`)),o.description&&o.type?.name!=="class"&&(e+=` "${o.description}"`),e}function Dl(o,e,t){let n=o?`"${o}" `:"",r=e.map($l).join(", "),s=t.map($l).join(", ");return`${n}${r} -> ${s}`}function Dm(o){let e=/^[a-z][a-zA-Z0-9]*$/,t=/^[a-z]+(_[a-z0-9]+)*$/;return e.test(o)||t.test(o)}function Ft(o,e){if(!o.name||o.name.length===0)throw new se("Field name cannot be blank",o.name,"Every field must have a descriptive name");if(!Dm(o.name))throw new se(`Invalid field name '${o.name}' - must be camelCase or snake_case`,o.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(o.name.toLowerCase())){let n=e==="input"?["userInput","questionText","documentContent","messageText","queryString"]:["responseText","analysisResult","categoryType","summaryText","outputData"];throw new se(`Field name '${o.name}' is too generic`,o.name,`Use a more descriptive name. Examples for ${e} fields: ${n.join(", ")}`)}if(o.name.length<2)throw new se(`Field name '${o.name}' is too short`,o.name,"Field names must be at least 2 characters long");if(o.name.length>50)throw new se(`Field name '${o.name}' is too long (${o.name.length} characters)`,o.name,"Field names should be 50 characters or less");o.type&&Um(o,e)}function Um(o,e){if(!o.type)return;let{type:t}=o;if((t.name==="image"||t.name==="audio"||t.name==="file")&&e==="output")throw new se(`${t.name} type is not supported in output fields`,o.name,`${t.name} types can only be used in input fields`);if(t.name==="class"){if(e==="input")throw new se("Class type is not supported in input fields",o.name,'Class types are only allowed on output fields. Use "string" type for input classifications');if(!t.options||t.options.length===0)throw new se("Class type requires options",o.name,'Provide class options. Example: class "positive, negative, neutral"');for(let r of t.options){if(!r||r.trim().length===0)throw new se("Empty class option found",o.name,"All class options must be non-empty strings");let s=r.trim();if(s.includes(",")||s.includes("|"))throw new se(`Invalid class option "${s}"`,o.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 se("Duplicate class options found",o.name,"Each class option must be unique (case-insensitive)")}if(t.name==="code"&&t.isArray)throw new se("Arrays of code are not commonly supported",o.name,"Consider using a single code field or an array of strings instead");if(o.isInternal&&e==="input")throw new se("Internal marker (!) is not allowed on input fields",o.name,"Internal markers are only allowed on output fields");t.name==="object"&&t.fields&&Oa(t.fields,o.name,e)}function Oa(o,e,t,n=1){for(let[r,s]of Object.entries(o)){let i=`${e}.${r}`;if(s.type==="image"||s.type==="audio"||s.type==="file")throw new se(`${s.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}.`);s.type==="object"&&s.fields&&Oa(s.fields,i,t,n+1),s.isArray&&s.fields&&Oa(s.fields,`${i}[]`,t,n+1)}}var Qt=class o{signature;sigHash;examples;examplesOptions;demos;trace;usage=[];traceLabel;key;children;childNames=new Map;childCount=0;constructor(e,t){this.signature=new Ne(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 Jn,this.key={id:"root"}}getSignature(){return new Ne(this.signature)}setSignature(e){this.signature=new Ne(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,s=[...r.getInputFields(),...r.getOutputFields()];this.examples=n.map(i=>{let a={};for(let u of s){let c=i[u.name];c!==void 0&&(Hr(u,c),a[u.name]=c)}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 Wr(e)}resetUsage(){this.usage=[];for(let e of Array.from(this.children))e?.resetUsage()}static _propagating=!1;setDemos(e,t){if(!o._propagating&&e.length>0){let c=new Set(this.namedPrograms().map(p=>p.id)),l=[...new Set(e.map(p=>p.programId))].filter(p=>!c.has(p));if(l.length>0){let p=[...c].join(", ");throw new Error(`Unknown program ID(s) in demos: ${l.join(", ")}. Valid IDs: ${p}. Use namedPrograms() to discover available IDs.`)}}let n=e.filter(c=>c.programId===this.key.id).map(c=>c.traces).flat(),r=this.signature,s=[...r.getInputFields(),...r.getOutputFields()],i=new Set(r.getInputFields().map(c=>c.name)),a=new Set(r.getOutputFields().map(c=>c.name));this.demos=n.map((c,l)=>{let p={};for(let g of s){let f=c[g.name];f!==void 0&&(Hr(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[${l}] for '${this.key.id}' has no output field values. Expected at least one of: ${[...a].join(", ")}`);if(!d)throw new Error(`Demo trace[${l}] 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 u=o._propagating;o._propagating=!0;try{for(let c of Array.from(this.children))c?.setDemos(e,t)}finally{o._propagating=u}}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}namedProgramInstances(){let e=[];[...this.signature.getInputFields(),...this.signature.getOutputFields()].length>0&&e.push({id:this.key.id,program:this,signature:this.signature.toString()});for(let n of Array.from(this.children))n&&"namedProgramInstances"in n&&typeof n.namedProgramInstances=="function"?e.push(...n.namedProgramInstances()):n&&e.push({id:n.getId(),program:n});return e}applyOptimization(e){let t=e.demos!==void 0,n=e.modelConfig!==void 0;(t||n)&&this.setDemos(e.demos??[],{modelConfig:e.modelConfig});let r=this;if(typeof r.setInstruction=="function"){let i=e.instructionMap?.[this.key.id],a=typeof i=="string"?i:e.instruction;typeof a=="string"&&a.length>0&&r.setInstruction(a)}let s={...e,...t?{demos:void 0}:{},...n?{modelConfig:void 0}:{}};for(let i of Array.from(this.children))i?.applyOptimization(s)}};var Gl={"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]},Cs=async({ai:o,functionList:e,functionCalls:t,mem:n,sessionId:r,traceId:s,span:i,excludeContentFromTrace:a,index:u,functionResultFormatter:c,logger:l,debug:p,stopFunctionNames:d,step:m,abortSignal:g})=>{let f=new Yr(e),x=new Set,A=[],h=R=>{let M=E=>E.replace(/[^a-zA-Z0-9]/g,"").toLowerCase(),T=M(R),O=e.find(E=>E.name===R);return O||(O=e.find(E=>M(E.name)===T)),O},y=t.map(R=>{if(!R.id)throw new Error(`Function ${R.name} did not return an ID`);let M=o.getOptions().tracer??he.tracer;return M?M.startActiveSpan(`Tool: ${R.name}`,async T=>{try{T?.setAttributes?.({"tool.name":R.name,"tool.mode":"native","function.id":R.id,"session.id":r??""});let{formatted:O,rawResult:E,parsedArgs:$}=await f.executeWithDetails(R,{sessionId:r,ai:o,functionResultFormatter:c,traceId:T?.spanContext?.().traceId??s,stopFunctionNames:d,step:m,abortSignal:g});if(x.add(R.name.toLowerCase()),m?._recordFunctionCall(R.name,$,E),d?.includes(R.name.toLowerCase())){let N=h(R.name);N&&A.push({func:N,args:$,result:E})}if(a?T.addEvent("gen_ai.tool.message",{name:R.name}):T.addEvent("gen_ai.tool.message",{name:R.name,args:R.args,result:O??""}),i){let N={name:R.name};a||(N.args=R.args,N.result=O??""),i.addEvent("function.call",N)}return{result:O??"",role:"function",functionId:R.id,index:u}}catch(O){if(T?.recordException?.(O),O instanceof Qr){let E=O.getFixingInstructions(),$={name:R.name,message:O.toString()};return a||($.args=R.args,$.fixing_instructions=E),T?.addEvent?.("function.error",$),p&&Ri(O,u,E,l),{functionId:R.id,isError:!0,index:u,result:E,role:"function"}}throw O}finally{T?.end?.()}}):f.executeWithDetails(R,{sessionId:r,ai:o,functionResultFormatter:c,traceId:s,stopFunctionNames:d,step:m,abortSignal:g}).then(({formatted:T,rawResult:O,parsedArgs:E})=>{if(x.add(R.name.toLowerCase()),m?._recordFunctionCall(R.name,E,O),d?.includes(R.name.toLowerCase())){let $=h(R.name);$&&A.push({func:$,args:E,result:O})}if(i){let $={name:R.name};a||($.args=R.args,$.result=T??""),i.addEvent("function.call",$)}return{result:T??"",role:"function",functionId:R.id,index:u}}).catch(T=>{if(!(T instanceof Qr))throw T;let O=T.getFixingInstructions();if(i){let E={name:R.name,message:T.toString()};a||(E.args=R.args,E.fixing_instructions=O),i.addEvent("function.error",E)}return p&&Ri(T,u,O,l),{functionId:R.id,isError:!0,index:u,result:O,role:"function"}})}),I=(await Promise.all(y)).map(R=>R.result===void 0||R.result===""?{...R,result:"done"}:R);if(n.addFunctionResults(I,r),p){let R=I.filter(M=>!M.isError);R.length>0&&Qu(R,l)}if(A.length>0)throw new un(A);return x};function Ra(o,e,t,n){if(!e||e.length===0)return;if(!o.getFeatures(n).functions)throw new Error("Functions are not supported by the AI service");return e.map(s=>({id:s.id,name:s.function.name,args:s.function.params}))}function Pl(o,e,t,n){let r=e;return!t&&(r==="required"||typeof r=="function")?{functions:[],functionCall:void 0}:o?{functions:o.map(i=>"toFunction"in i?i.toFunction():i).flat(),functionCall:r}:{functions:[],functionCall:r}}function _m(o){let e=0,t=!1,n=!1,r=!1,s=!1,i=[];for(let a=0;a<o.length;a++){let u=o[a];if(n){n=!1;continue}if(u==="\\"){n=!0;continue}if(u==='"'){t=!t;continue}t||(u==="{"?(i.push("{"),e++):u==="["?(i.push("["),e++):u==="}"?i.length>0&&i[i.length-1]==="{"&&(i.pop(),e--):u==="]"&&i.length>0&&i[i.length-1]==="["&&(i.pop(),e--))}if(i.length>0){let a=i[i.length-1];r=a==="[",s=a==="{"}return{nestingLevel:e,inString:t,inArray:r,inObject:s}}function Fl(o){if(!o.trim())return{parsed:null,partialMarker:null};try{return{parsed:JSON.parse(o),partialMarker:null}}catch{}let e=_m(o),t=Nm(o);try{return{parsed:JSON.parse(t),partialMarker:e}}catch{return{parsed:null,partialMarker:e}}}function Nm(o){let e=o.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 s=0;s<e.length;s++){let i=e[s];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*_l({res:o,usage:e,states:t,debug:n,stepContext:r,...s}){let i=(s.ai.getFeatures().functionCot??!1)&&s.functions!==void 0&&s.functions.length>0,a,u=[],c=o.getReader();try{for(;;){let{done:l,value:p}=await c.read();if(l)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&&u.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*$m({...s,result:m,skipEarlyFail:i,state:g,debug:n})}}}finally{c.releaseLock()}for(let l of t)yield*Lm({...s,state:l,debug:n,stepContext:r});if(a){if(u.length){let l=Array.from(new Map(u.filter(p=>p.url).map(p=>[p.url,p])).values());a.citations=l}if(e.push(a),n&&s.logger){let l=structuredClone(a);delete l.citations,s.logger({name:"ChatResponseUsage",value:l}),a.citations&&a.citations.length>0&&s.logger({name:"ChatResponseCitations",value:a.citations})}}}async function*$m({result:o,mem:e,sessionId:t,strictMode:n,skipEarlyFail:r,treatAllFieldsOptional:s,state:i,signature:a,streamingFieldProcessors:u,thoughtFieldName:c,streamingAsserts:l,asserts:p}){if(o.functionCalls&&o.functionCalls.length>0)Oo(i.functionCalls,o.functionCalls),e.updateResult({name:o.name,content:o.content,functionCalls:i.functionCalls,thoughtBlocks:o.thoughtBlocks,delta:o.functionCalls?.[0]?.function?.params,index:o.index},t);else if(o.content&&o.content.length>0){o.thought&&o.thought.length>0&&(yield{index:o.index,delta:{[c]:o.thought}}),i.content+=o.content,e.updateResult({name:o.name,content:i.content,thoughtBlocks:o.thoughtBlocks,delta:o.content,index:o.index},t);let d=a.getOutputFields();if(a.hasComplexFields()){let{parsed:f,partialMarker:x}=Fl(i.content);if(f&&typeof f=="object"){let A={},h={};for(let y of Object.keys(f))if(d.some(C=>C.name===y)){let C=f[y],I=i.values[y];if(Array.isArray(C)&&C.length>0&&Dm(C,x)&&(C=C.slice(0,-1)),h[y]=C,typeof C=="string"&&typeof I=="string"&&C.startsWith(I)){let R=C.slice(I.length);R&&(A[y]=R)}else Array.isArray(C)&&Array.isArray(I)?C.length>I.length&&(A[y]=C.slice(I.length)):JSON.stringify(C)!==JSON.stringify(I)&&(Array.isArray(C)||(A[y]=C))}try{Qn(a,h,{allowMissingRequired:!0})}catch{}Object.assign(i.values,h),Object.keys(A).length>0&&(yield{index:o.index,delta:A});return}}if(Ca(a,i.values,i.xstate,i.content,{strictMode:n,skipEarlyFail:r,treatAllFieldsOptional:s}))return;l.length!==0&&await na(l,i.xstate,i.content),u.length!==0&&await wa(u,i.content,i.xstate,e,i.values,t),yield*Ta(a,i.content,i.values,i.xstate,o.index),await Vn(p,i.values)}else o.thought&&o.thought.length>0?(i.values[c]=(i.values[c]??"")+o.thought,yield{index:o.index,delta:{[c]:o.thought}},e.updateResult({name:o.name,content:i.content,delta:"",index:o.index,thought:o.thought,thoughtBlocks:o.thoughtBlocks},t)):o.thoughtBlocks&&o.thoughtBlocks.length>0&&e.updateResult({name:o.name,content:i.content,delta:"",index:o.index,thoughtBlocks:o.thoughtBlocks},t);if(o.finishReason==="length")throw new Error(`Max tokens reached before completion
215
+ Content: ${i.content}`)}async function*Lm({state:o,signature:e,ai:t,model:n,functions:r,mem:s,sessionId:i,traceId:a,span:u,strictMode:c,excludeContentFromTrace:l,streamingAsserts:p,asserts:d,fieldProcessors:m,streamingFieldProcessors:g,functionResultFormatter:f,signatureToolCallingManager:x,logger:A,debug:h,stopFunctionNames:y,stepContext:C,abortSignal:I}){let R=x?void 0:Ra(t,o.functionCalls,o.values,n);if(R){if(!r)throw new Error("Functions are not defined");let M=await Cs({ai:t,functionList:r,functionCalls:R,mem:s,sessionId:i,traceId:a,span:u,index:o.index,excludeContentFromTrace:l,functionResultFormatter:f,logger:A,debug:h,stopFunctionNames:y,step:C,abortSignal:I});o.functionsExecuted=new Set([...o.functionsExecuted,...M]),o.functionCalls=[]}else{let M=e.getOutputFields(),T=e.hasComplexFields(),O=!1;if(T)try{let E=JSON.parse(o.content),$={};for(let N of Object.keys(E))if(M.some(S=>S.name===N)){let S=E[N],v=o.values[N];if(typeof S=="string"&&typeof v=="string"&&S.startsWith(v)){let P=S.slice(v.length);P&&($[N]=P)}else Array.isArray(S)&&Array.isArray(v)?S.length>v.length&&($[N]=S.slice(v.length)):JSON.stringify(S)!==JSON.stringify(v)&&(Array.isArray(S)||($[N]=S))}try{Qn(e,$,{allowMissingRequired:!0})}catch(N){let S=(N.message||"").toLowerCase();if(S.includes("at least")||S.includes("at most")||S.includes("must match pattern")||S.includes("invalid url")||S.includes("required")||S.includes("missing")||S.includes("valid email")||S.includes("number must be"))throw N}for(let N of Object.keys(E))M.some(S=>S.name===N)&&(o.values[N]=E[N]);yield{index:o.index,delta:$},O=!0}catch(E){let $=(E.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 E}if(!O){let E=x!==void 0;Ia(e,o.values,o.xstate,o.content,{strictMode:c,treatAllFieldsOptional:E,deferRequiredCheckForStreaming:!0,forceFinalize:!0})}if(x){let E=await x.processResults(o.values);if(E&&E.length>0){if(!r)throw new Error("Functions are not defined");let $=await Cs({ai:t,functionList:r,functionCalls:E,mem:s,sessionId:i,traceId:a,span:u,index:o.index,excludeContentFromTrace:l,functionResultFormatter:f,logger:A,debug:h,stopFunctionNames:y,step:C,abortSignal:I});o.functionsExecuted=new Set([...o.functionsExecuted,...$]),s.updateResult({name:void 0,content:o.content,functionCalls:E.map(N=>({id:N.id,type:"function",function:{name:N.name,params:N.args}})),index:o.index},i);return}}await na(p,o.xstate,o.content,!0),await Vn(d,o.values),m.length&&await Wr(m,o.values,s,i),g.length!==0&&await wa(g,o.content,o.xstate,s,o.values,i,!0),yield*Ta(e,o.content,o.values,o.xstate,o.index)}}async function*Nl({ai:o,res:e,mem:t,sessionId:n,traceId:r,functions:s,span:i,strictMode:a,states:u,usage:c,excludeContentFromTrace:l,asserts:p,fieldProcessors:d,thoughtFieldName:m,signature:g,functionResultFormatter:f,logger:x,debug:A,signatureToolCallingManager:h,stopFunctionNames:y,disableMemoryCleanup:C,stepContext:I,abortSignal:R}){let M=e.results??[],T=h!==void 0;t.addResponse(M,n);let O=[];for(let S of M)if(Array.isArray(S?.citations))for(let v of S.citations)v?.url&&O.push({url:v.url,title:v.title,description:v.description,license:v.license,publicationDate:v.publicationDate,snippet:v.snippet});for(let S of M){let v=u[S.index];if(!v)throw new Error(`No state found for result (index: ${S.index})`);if(e.modelUsage){let P=Array.from(new Map(O.filter(U=>U.url).map(U=>[U.url,U])).values()),F={...e.modelUsage,...P.length?{citations:P}:{}};if(c.push(F),A&&x){let U=structuredClone(F);delete U.citations,x({name:"ChatResponseUsage",value:U}),F.citations&&F.citations.length>0&&x({name:"ChatResponseCitations",value:F.citations})}}if(h&&S.content){S.thought&&S.thought.length>0&&(v.values[m]=S.thought),As(g,v.values,S.content,{strictMode:a,treatAllFieldsOptional:T});let F=(await h.processResults(v.values))?.map(U=>({id:U.id,type:"function",function:{name:U.name,params:U.args}}));F&&F.length>0&&t.updateResult({name:S.name,content:S.content,functionCalls:F,index:S.index},n)}if(S.functionCalls?.length){let P=Ra(o,S.functionCalls,v.values);if(P&&P.length>0){if(!s)throw new Error("Functions are not defined");let F;try{F=await Cs({ai:o,functionList:s,functionCalls:P,mem:t,sessionId:n,traceId:r,span:i,excludeContentFromTrace:l,index:S.index,functionResultFormatter:f,logger:x,debug:A,stopFunctionNames:y,step:I,abortSignal:R})}catch(U){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),U}v.functionsExecuted=new Set([...v.functionsExecuted,...F])}}else if(S.content){S.thought&&S.thought.length>0&&(v.values[m]=S.thought);let P=g.getOutputFields();if(g.hasComplexFields())try{let U=JSON.parse(S.content),L={};for(let z of Object.keys(U))P.some(j=>j.name===z)&&(L[z]=U[z]);Qn(g,L),Object.assign(v.values,L)}catch(U){let L=U instanceof SyntaxError;if((U.name?.includes("ValidationError")||U.name?.includes("Error"))&&!L){let j=(U.message||"").toLowerCase();if(j.includes("at least")||j.includes("at most")||j.includes("must match pattern")||j.includes("invalid url")||j.includes("required")||j.includes("missing")||j.includes("valid email")||j.includes("number must be"))throw U}if(L)As(g,v.values,S.content,{strictMode:a,treatAllFieldsOptional:T});else throw U}else As(g,v.values,S.content,{strictMode:a,treatAllFieldsOptional:T})}if(await Vn(p,v.values),C||(t.removeByTag("correction",n),t.removeByTag("error",n)),d.length&&await Wr(d,v.values,t,n),S.finishReason==="length")throw new Error(`Max tokens reached before completion
216
+ Content: ${S.content}`)}let E=u.map(S=>S.values);for(let S of E)for(let v of g.getOutputFields())v.isInternal&&delete S[v.name];let $=g.getOutputFields(),N=E.map((S,v)=>{let P={};for(let F of $)F.isInternal||(P[F.name]=S[F.name]);return S[m]!==void 0&&(P[m]=S[m]),{index:v,delta:P}});for(let S of N)yield S}function Dm(o,e){return e?!!(e.nestingLevel>0||e.inArray||e.inObject):!1}function $l(o,e,t,n){let r=o.getLast(n);if(!r)return!0;for(let[s,i]of t.entries()){let a=e?Array.from(e).some(p=>i.functionsExecuted.has(p)):!1;if(!r.chat[s])throw new Error(`No chat message found for result (index: ${s})`);let c=r.role==="function",l=r.tags?r.tags.some(p=>p==="processor"):!1;if(c&&e&&a||!(c||l))return!1}return!0}var Um=["none","minimal","low","medium","high","highest"];function va(o,e,t){let n={};if(e.model!==!1){let a=o.getModelList();if(a&&a.length>0){let u=a.filter(c=>"model"in c);if(u.length>0){let c=u.map(p=>p.key),l=u.map(p=>`${p.key} (${p.description})`);n.model={type:"string",enum:c,description:`${t&&c.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: ${l.join(", ")}`}}}}e.thinkingBudget!==!1&&(n.thinkingBudget={type:"string",enum:[...Um],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=cn(e.functions);let a=r.map(c=>c.name),u=r.map(c=>`${c.name} (${c.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: ${u.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 s=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,u)=>{let c=u?.step;if(!c)return"Generation parameters adjusted for next response.";if(a?.model&&c.setModel(a.model),a?.thinkingBudget&&c.setThinkingBudget(a.thinkingBudget),a?.temperature!==void 0&&c.setTemperature(a.temperature),a?.addFunctions?.length&&s){let l=s.filter(p=>a.addFunctions.includes(p.name));l.length>0&&c.addFunctions(l)}return a?.removeFunctions?.length&&c.removeFunctions(...a.removeFunctions),"Generation parameters adjusted for next response."}}}var Yn=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 xe=class extends Error{constructor(t,n,r,s){super(t);this.position=n;this.context=r;this.suggestion=s;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 xe("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 xe("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 xe('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 xe(`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 xe)throw e;let t=e instanceof Error?e.message:"Unknown error";throw new xe(t,this.position,this.getErrorContext())}}validateParsedSignature(e){let t=new Set;for(let r of e.inputs){if(t.has(r.name))throw new xe(`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 xe(`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 xe(`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 xe("Signature must have at least one input field",0,"",'Add an input field before "->". Example: "userInput:string -> ..."');if(e.outputs.length===0)throw new xe("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),s=`${" ".repeat(n.length)}^`;return[`Position ${this.position} in signature:`,`"${n}${r}"`,` ${s}`].join(`
217
+ `)}parseFieldList(e,t){let n=[];if(this.skipWhitespace(),this.position>=this.input.length)throw new xe(`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 xe?r:new xe(`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 xe(`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 xe?r:new xe(`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 xe(`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 xe(`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 s=this.parseTypeNotClass(),i=this.match("[]");n={name:s,isArray:i}}catch(s){throw s instanceof xe?s:new xe(`Input field "${e}": ${s instanceof Error?s.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 xe(`Output field "${e}": Missing class options after "class" type`,this.position,this.getErrorContext(),'Add class names in quotes. Example: class "positive, negative, neutral"');let u=a.split(/[,|]/).map(c=>c.trim()).filter(c=>c.length>0);if(u.length===0)throw new xe(`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:u}}else try{let i=this.parseTypeNotClass(),a=this.match("[]");if(r={name:i,isArray:a},i==="image"&&a)throw new xe(`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 xe(`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 xe(`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 xe(`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 xe?i:new xe(`Output field "${e}": ${i instanceof Error?i.message:"Unknown error"}`,this.position,this.getErrorContext())}this.skipWhitespace();let s=this.parseParsedString();return{name:e,desc:s?.trim(),type:r,isOptional:t,isInternal:n}}validateFieldName(e,t){if(he.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 xe(`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 xe(`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 xe(`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 xe(`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),s=`Invalid type "${n||"empty"}"`,i=r?`. Did you mean "${r}"?`:"",a=`${s}${i}`;throw new xe(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 xe("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 xe(`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 xe(`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,s=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(s,Math.min(this.position,s+20));throw new xe(`Unterminated string starting at position ${s}`,s,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 xe(`Expected "->" but found "${e}..."`,this.position,this.getErrorContext(),t)}}};function Ll(o){return new Sa(o).parse()}var Xr=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(([s,i])=>[s,Ts(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(([s,i])=>[s,Ts(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 _e(e);return this._useStructuredOutputs&&(t._forceComplexFields=!0,t._hasComplexFields=void 0),t}},Ke=class o{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 o({...this,isOptional:!0})}array(e){return new o({...this,isArray:!0,description:e||this.description,itemDescription:e?this.description:void 0})}internal(){return new o({...this,isInternal:!0})}cache(){return new o({...this,isCached:!0})}min(e){return this.type==="string"?new o({...this,minLength:e}):this.type==="number"?new o({...this,minimum:e}):this}max(e){return this.type==="string"?new o({...this,maxLength:e}):this.type==="number"?new o({...this,maximum:e}):this}email(){return this.type==="string"?new o({...this,format:"email"}):this}url(){return this.type==="string"?new o({...this,format:"uri"}):this}regex(e,t){return this.type==="string"?new o({...this,pattern:e,patternDescription:t}):this}date(){return this.type==="string"?new o({...this,format:"date"}):this}datetime(){return this.type==="string"?new o({...this,format:"date-time"}):this}},fe=Object.assign(()=>new Xr,{string:o=>new Ke({type:"string",isArray:!1,description:o,isOptional:!1,isInternal:!1,isCached:!1}),number:o=>new Ke({type:"number",isArray:!1,description:o,isOptional:!1,isInternal:!1,isCached:!1}),boolean:o=>new Ke({type:"boolean",isArray:!1,description:o,isOptional:!1,isInternal:!1,isCached:!1}),json:o=>new Ke({type:"json",isArray:!1,description:o,isOptional:!1,isInternal:!1,isCached:!1}),datetime:o=>new Ke({type:"datetime",isArray:!1,description:o,isOptional:!1,isInternal:!1,isCached:!1}),date:o=>new Ke({type:"date",isArray:!1,description:o,isOptional:!1,isInternal:!1,isCached:!1}),class:(o,e)=>new Ke({type:"class",isArray:!1,options:o,description:e,isOptional:!1,isInternal:!1,isCached:!1}),image:o=>new Ke({type:"image",isArray:!1,description:o,isOptional:!1,isInternal:!1,isCached:!1}),audio:o=>new Ke({type:"audio",isArray:!1,description:o,isOptional:!1,isInternal:!1,isCached:!1}),file:o=>new Ke({type:"file",isArray:!1,description:o,isOptional:!1,isInternal:!1,isCached:!1}),url:o=>new Ke({type:"url",isArray:!1,description:o,isOptional:!1,isInternal:!1,isCached:!1}),email:o=>new Ke({type:"string",isArray:!1,description:o,isOptional:!1,isInternal:!1,isCached:!1,format:"email"}),code:(o,e)=>new Ke({type:"code",isArray:!1,description:e||o,isOptional:!1,isInternal:!1,isCached:!1}),object:(o,e)=>new Ke({type:"object",isArray:!1,fields:o,description:e,isOptional:!1,isInternal:!1,isCached:!1})});function Ts(o){return{type:o.type,isArray:o.isArray,options:o.options,description:o.description,isOptional:o.isOptional,isInternal:o.isInternal,minLength:o.minLength,maxLength:o.maxLength,minimum:o.minimum,maximum:o.maximum,pattern:o.pattern,patternDescription:o.patternDescription,format:o.format,fields:o.fields?Object.fromEntries(Object.entries(o.fields).map(([e,t])=>[e,Ts(t)])):void 0}}function Is(o){return{type:{name:o.type,isArray:o.isArray,options:o.options?[...o.options]:void 0,fields:o.fields},description:o.description,isOptional:o.isOptional,isInternal:o.isInternal}}function ka(o,e){return{name:o,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,Ts(n)])):void 0},description:e.description,isOptional:e.isOptional||void 0,isInternal:e.isInternal||void 0,isCached:e.isCached||void 0}}function Dl(o){return o.length===0?{type:"object",properties:{}}:Jt(o,"Schema")}function Gm(o){let e=ka("__value",o);return Jt([e],"Schema").properties?.__value??{type:"json"}}var Oa=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(ka(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(ka(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(s=>!s.code.trim()))throw new Error(`Function "${e}" examples must define non-empty code`);return{name:e,description:t,...n?{namespace:n}:{},parameters:Dl(this.argFields),...this.returnMode==="single"&&this.returnFieldType?{returns:Gm(this.returnFieldType)}:this.returnMode==="fields"?{returns:Dl(this.returnFields)}:{},...this.fnExamples.length>0?{examples:this.fnExamples.map(s=>({...s}))}:{},func:this.fnHandler}}},jl=o=>new Oa(o),ce=class extends Error{constructor(t,n,r){super(t);this.fieldName=n;this.suggestion=r;this.name="AxSignatureValidationError"}},_e=class o{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=Ll(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 ce(`Invalid Signature: ${n.message}`,void 0,r)}throw new ce(`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 o)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 ce("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 ce("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 ce?t:new ce(`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 ce("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 o(e)}parseParsedField=e=>{if(!e.name||e.name.length===0)throw new ce("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 ce("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 ce("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);Ft(t,"input");for(let n of this.inputFields)if(n.name===t.name)throw new ce(`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 ce(`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 ce?t:new ce(`Failed to add input field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}};addOutputField=e=>{try{let t=this.parseField(e);Ft(t,"output");for(let n of this.outputFields)if(n.name===t.name)throw new ce(`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 ce(`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 ce?t:new ce(`Failed to add output field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}};setInputFields=e=>{if(!Array.isArray(e))throw new ce("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 Ft(r,"input"),r});this.inputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof ce?t:new ce(`Failed to set input fields: ${t instanceof Error?t.message:"Unknown error"}`)}};setOutputFields=e=>{if(!Array.isArray(e))throw new ce("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 Ft(r,"output"),r});this.outputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof ce?t:new ce(`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 o(this);return n.addInputField({name:e,...Is(t)}),n};prependInputField=(e,t)=>{let n=new o(this),r={name:e,...Is(t)},s=n.parseField(r);Ft(s,"input");for(let i of n.inputFields)if(i.name===s.name)throw new ce(`Duplicate input field name: "${s.name}"`,s.name,"Each field name must be unique within the signature");for(let i of n.outputFields)if(i.name===s.name)throw new ce(`Field name "${s.name}" appears in both inputs and outputs`,s.name,"Use different names for input and output fields to avoid confusion");return n.inputFields.unshift(s),n.invalidateValidationCache(),n.updateHashLight(),n};appendOutputField=(e,t)=>{let n=new o(this);return n.addOutputField({name:e,...Is(t)}),n};prependOutputField=(e,t)=>{let n=new o(this),r={name:e,...Is(t)},s=n.parseField(r);Ft(s,"output");for(let i of n.outputFields)if(i.name===s.name)throw new ce(`Duplicate output field name: "${s.name}"`,s.name,"Each field name must be unique within the signature");for(let i of n.inputFields)if(i.name===s.name)throw new ce(`Field name "${s.name}" appears in both inputs and outputs`,s.name,"Use different names for input and output fields to avoid confusion");return n.outputFields.unshift(s),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=>{Ft(e,"input")}),this.getOutputFields().forEach(e=>{Ft(e,"output")}),this.sigHash=mt("sha256").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=Gl(this.description,this.inputFields,this.outputFields),this._hasComplexFields=this.computeHasComplexFields(),[this.sigHash,this.sigString]}catch(e){throw e instanceof ce?e:new ce(`Signature validation failed: ${e instanceof Error?e.message:"Unknown error"}`)}};updateHash=()=>{try{return this.getInputFields().forEach(e=>{Ft(e,"input")}),this.getOutputFields().forEach(e=>{Ft(e,"output")}),this.validateSignatureConsistency(),this.sigHash=mt("sha256").update(this.description??"").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=Gl(this.description,this.inputFields,this.outputFields),this._hasComplexFields=this.computeHasComplexFields(),[this.sigHash,this.sigString]}catch(e){throw e instanceof ce?e:new ce(`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 ce(`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 ce(`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 ce(`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 ce("Signature must have at least one input field",void 0,'Add an input field. Example: "userInput:string -> ..."');if(this.outputFields.length===0)throw new ce("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 Jt(e,this.description??"Schema")};toInputJSONSchema=()=>Jt(this.inputFields,this.description??"Schema")};function Ul(o){let e=o.name;return o.isOptional&&(e+="?"),o.isInternal&&(e+="!"),o.type&&(e+=`:${o.type.name}`,o.type.isArray&&(e+="[]"),o.type.name==="class"&&o.type.options&&(e+=` "${o.type.options.join(" | ")}"`)),o.description&&o.type?.name!=="class"&&(e+=` "${o.description}"`),e}function Gl(o,e,t){let n=o?`"${o}" `:"",r=e.map(Ul).join(", "),s=t.map(Ul).join(", ");return`${n}${r} -> ${s}`}function jm(o){let e=/^[a-z][a-zA-Z0-9]*$/,t=/^[a-z]+(_[a-z0-9]+)*$/;return e.test(o)||t.test(o)}function Ft(o,e){if(!o.name||o.name.length===0)throw new ce("Field name cannot be blank",o.name,"Every field must have a descriptive name");if(!jm(o.name))throw new ce(`Invalid field name '${o.name}' - must be camelCase or snake_case`,o.name,'Use camelCase (e.g., "userInput") or snake_case (e.g., "user_input")');if(he.signatureStrict&&["text","object","image","string","number","boolean","json","array","datetime","date","time","type","class","input","output","data","value","result","response","request","item","element"].includes(o.name.toLowerCase())){let n=e==="input"?["userInput","questionText","documentContent","messageText","queryString"]:["responseText","analysisResult","categoryType","summaryText","outputData"];throw new ce(`Field name '${o.name}' is too generic`,o.name,`Use a more descriptive name. Examples for ${e} fields: ${n.join(", ")}`)}if(o.name.length<2)throw new ce(`Field name '${o.name}' is too short`,o.name,"Field names must be at least 2 characters long");if(o.name.length>50)throw new ce(`Field name '${o.name}' is too long (${o.name.length} characters)`,o.name,"Field names should be 50 characters or less");o.type&&Bm(o,e)}function Bm(o,e){if(!o.type)return;let{type:t}=o;if((t.name==="image"||t.name==="audio"||t.name==="file")&&e==="output")throw new ce(`${t.name} type is not supported in output fields`,o.name,`${t.name} types can only be used in input fields`);if(t.name==="class"){if(e==="input")throw new ce("Class type is not supported in input fields",o.name,'Class types are only allowed on output fields. Use "string" type for input classifications');if(!t.options||t.options.length===0)throw new ce("Class type requires options",o.name,'Provide class options. Example: class "positive, negative, neutral"');for(let r of t.options){if(!r||r.trim().length===0)throw new ce("Empty class option found",o.name,"All class options must be non-empty strings");let s=r.trim();if(s.includes(",")||s.includes("|"))throw new ce(`Invalid class option "${s}"`,o.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 ce("Duplicate class options found",o.name,"Each class option must be unique (case-insensitive)")}if(t.name==="code"&&t.isArray)throw new ce("Arrays of code are not commonly supported",o.name,"Consider using a single code field or an array of strings instead");if(o.isInternal&&e==="input")throw new ce("Internal marker (!) is not allowed on input fields",o.name,"Internal markers are only allowed on output fields");t.name==="object"&&t.fields&&Ea(t.fields,o.name,e)}function Ea(o,e,t,n=1){for(let[r,s]of Object.entries(o)){let i=`${e}.${r}`;if(s.type==="image"||s.type==="audio"||s.type==="file")throw new ce(`${s.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}.`);s.type==="object"&&s.fields&&Ea(s.fields,i,t,n+1),s.isArray&&s.fields&&Ea(s.fields,`${i}[]`,t,n+1)}}var Qt=class o{signature;sigHash;examples;examplesOptions;demos;trace;usage=[];traceLabel;key;children;childNames=new Map;childCount=0;constructor(e,t){this.signature=new _e(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 Yn,this.key={id:"root"}}getSignature(){return new _e(this.signature)}setSignature(e){this.signature=new _e(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,s=[...r.getInputFields(),...r.getOutputFields()];this.examples=n.map(i=>{let a={};for(let u of s){let c=i[u.name];c!==void 0&&(Kr(u,c),a[u.name]=c)}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 Vr(e)}resetUsage(){this.usage=[];for(let e of Array.from(this.children))e?.resetUsage()}static _propagating=!1;setDemos(e,t){if(!o._propagating&&e.length>0){let c=new Set(this.namedPrograms().map(p=>p.id)),l=[...new Set(e.map(p=>p.programId))].filter(p=>!c.has(p));if(l.length>0){let p=[...c].join(", ");throw new Error(`Unknown program ID(s) in demos: ${l.join(", ")}. Valid IDs: ${p}. Use namedPrograms() to discover available IDs.`)}}let n=e.filter(c=>c.programId===this.key.id).map(c=>c.traces).flat(),r=this.signature,s=[...r.getInputFields(),...r.getOutputFields()],i=new Set(r.getInputFields().map(c=>c.name)),a=new Set(r.getOutputFields().map(c=>c.name));this.demos=n.map((c,l)=>{let p={};for(let g of s){let f=c[g.name];f!==void 0&&(Kr(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[${l}] for '${this.key.id}' has no output field values. Expected at least one of: ${[...a].join(", ")}`);if(!d)throw new Error(`Demo trace[${l}] 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 u=o._propagating;o._propagating=!0;try{for(let c of Array.from(this.children))c?.setDemos(e,t)}finally{o._propagating=u}}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}namedProgramInstances(){let e=[];[...this.signature.getInputFields(),...this.signature.getOutputFields()].length>0&&e.push({id:this.key.id,program:this,signature:this.signature.toString()});for(let n of Array.from(this.children))n&&"namedProgramInstances"in n&&typeof n.namedProgramInstances=="function"?e.push(...n.namedProgramInstances()):n&&e.push({id:n.getId(),program:n});return e}applyOptimization(e){let t=e.demos!==void 0,n=e.modelConfig!==void 0;(t||n)&&this.setDemos(e.demos??[],{modelConfig:e.modelConfig});let r=this;if(typeof r.setInstruction=="function"){let i=e.instructionMap?.[this.key.id],a=typeof i=="string"?i:e.instruction;typeof a=="string"&&a.length>0&&r.setInstruction(a)}let s={...e,...t?{demos:void 0}:{},...n?{modelConfig:void 0}:{}};for(let i of Array.from(this.children))i?.applyOptimization(s)}};var Bl={"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.
@@ -711,12 +711,12 @@ You synthesize a final answer from the provided actorResult payload. In normal \
711
711
  1. Base your answer ONLY on evidence from actorResult payload arguments.
712
712
  2. If actorResult lacks sufficient information, provide the best possible answer from available evidence.
713
713
  3. If an internal or evaluation workflow provides \`actorResult.type = ask_clarification\`, ask for the missing information clearly in your output fields.
714
- `};var Ea=/{{\s*([^}]+?)\s*}}/g,Bl=/^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*$/,zl=/^([A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*)\s*===\s*(?:'([^']*)'|"([^"]*)")$/,jl=new Map;function _t(o,e,t,n){let s=e.slice(0,t).split(`
715
- `),i=s.length,a=(s.at(-1)?.length??0)+1;return`${o}:${i}:${a} ${n}`}function Gm(o){let e=[],t=0;Ea.lastIndex=0;let n=Ea.exec(o);for(;n;){let[r,s]=n,i=n.index;i>t&&e.push({type:"text",value:o.slice(t,i)}),e.push({type:"tag",value:s.trim(),index:i}),t=i+r.length,n=Ea.exec(o)}return t<o.length&&e.push({type:"text",value:o.slice(t)}),e}function Pa(o,e,t,n=0,r=new Set){let s=[],i=n;for(;i<o.length;){let a=o[i];if(a.type==="text"){s.push({type:"text",value:a.value}),i++;continue}let u=a.value;if(r.has(u))return{nodes:s,nextIndex:i,terminator:u};if(u.startsWith("if ")){let c=u.slice(3).trim();if(!Bl.test(c)&&!zl.test(c))throw new Error(_t(t,e,a.index,`Invalid if condition '${c}'`));let l=Pa(o,e,t,i+1,new Set(["else","/if"]));if(!l.terminator)throw new Error(_t(t,e,a.index,"Unclosed 'if' block"));let p=[],d=l.nextIndex+1;if(l.terminator==="else"){let m=Pa(o,e,t,l.nextIndex+1,new Set(["/if"]));if(m.terminator!=="/if")throw new Error(_t(t,e,a.index,"Unclosed 'if' block"));p=m.nodes,d=m.nextIndex+1}s.push({type:"if",condition:c,thenNodes:l.nodes,elseNodes:p,index:a.index}),i=d;continue}if(u==="else")throw new Error(_t(t,e,a.index,"Unexpected 'else'"));if(u==="/if")throw new Error(_t(t,e,a.index,"Unexpected '/if'"));if(u.startsWith("include "))throw new Error(_t(t,e,a.index,"Unexpected 'include' directive at runtime (includes must be compiled)"));if(!Bl.test(u))throw new Error(_t(t,e,a.index,`Invalid tag '${u}'`));s.push({type:"var",name:u,index:a.index}),i++}return{nodes:s,nextIndex:i}}function Ma(o,e,t,n,r){let s=e.split("."),i=o;for(let a of s){if(i===null||typeof i!="object"||!(a in i))throw new Error(_t(n,t,r,`Missing template variable '${e}'`));i=i[a]}return i}function Fa(o,e,t,n){let r="";for(let s of o){if(s.type==="text"){r+=s.value;continue}if(s.type==="var"){let u=Ma(e,s.name,t,n,s.index);if(typeof u!="string"&&typeof u!="number"&&typeof u!="boolean")throw new Error(_t(n,t,s.index,`Variable '${s.name}' must be string, number, or boolean`));r+=String(u);continue}let i,a=zl.exec(s.condition);if(a){let[,u,c,l]=a,p=c??l??"";i=Ma(e,u,t,n,s.index)===p}else{let u=Ma(e,s.condition,t,n,s.index);if(typeof u!="boolean")throw new Error(_t(n,t,s.index,`Condition '${s.condition}' must be boolean`));i=u}i?r+=Fa(s.thenNodes,e,t,n):r+=Fa(s.elseNodes,e,t,n)}return r}function Bm(o,e){let t=Gm(o),n=Pa(t,o,e);if(n.terminator)throw new Error(`Unexpected template terminator '${n.terminator}' in ${e}`);return n.nodes}function Tt(o,e={}){let t=Gl[o],n=`template:${o}`;if(!t)throw new Error(`Unknown template id: ${String(o)}`);let r=jl.get(o);return r||(r=Bm(t,n),jl.set(o,r)),Fa(r,e,t,n)}var ql=Tt("dsp/function-call-instructions.md"),jm=Tt("dsp/strict-output-formatting-rules.md"),zm=Tt("dsp/example-disclaimer.md"),Qn=Tt("dsp/example-separator.md"),ln=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=ws(this.sig.getInputFields()),r=ws(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(l=>"toFunction"in l?l.toFunction():l)?.flat()?.map(l=>`- \`${l.name}\`: ${Yn(l.description)}`).join(`
714
+ `};var Ma=/{{\s*([^}]+?)\s*}}/g,zl=/^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*$/,Hl=/^([A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*)\s*===\s*(?:'([^']*)'|"([^"]*)")$/,ql=new Map;function _t(o,e,t,n){let s=e.slice(0,t).split(`
715
+ `),i=s.length,a=(s.at(-1)?.length??0)+1;return`${o}:${i}:${a} ${n}`}function zm(o){let e=[],t=0;Ma.lastIndex=0;let n=Ma.exec(o);for(;n;){let[r,s]=n,i=n.index;i>t&&e.push({type:"text",value:o.slice(t,i)}),e.push({type:"tag",value:s.trim(),index:i}),t=i+r.length,n=Ma.exec(o)}return t<o.length&&e.push({type:"text",value:o.slice(t)}),e}function Fa(o,e,t,n=0,r=new Set){let s=[],i=n;for(;i<o.length;){let a=o[i];if(a.type==="text"){s.push({type:"text",value:a.value}),i++;continue}let u=a.value;if(r.has(u))return{nodes:s,nextIndex:i,terminator:u};if(u.startsWith("if ")){let c=u.slice(3).trim();if(!zl.test(c)&&!Hl.test(c))throw new Error(_t(t,e,a.index,`Invalid if condition '${c}'`));let l=Fa(o,e,t,i+1,new Set(["else","/if"]));if(!l.terminator)throw new Error(_t(t,e,a.index,"Unclosed 'if' block"));let p=[],d=l.nextIndex+1;if(l.terminator==="else"){let m=Fa(o,e,t,l.nextIndex+1,new Set(["/if"]));if(m.terminator!=="/if")throw new Error(_t(t,e,a.index,"Unclosed 'if' block"));p=m.nodes,d=m.nextIndex+1}s.push({type:"if",condition:c,thenNodes:l.nodes,elseNodes:p,index:a.index}),i=d;continue}if(u==="else")throw new Error(_t(t,e,a.index,"Unexpected 'else'"));if(u==="/if")throw new Error(_t(t,e,a.index,"Unexpected '/if'"));if(u.startsWith("include "))throw new Error(_t(t,e,a.index,"Unexpected 'include' directive at runtime (includes must be compiled)"));if(!zl.test(u))throw new Error(_t(t,e,a.index,`Invalid tag '${u}'`));s.push({type:"var",name:u,index:a.index}),i++}return{nodes:s,nextIndex:i}}function Pa(o,e,t,n,r){let s=e.split("."),i=o;for(let a of s){if(i===null||typeof i!="object"||!(a in i))throw new Error(_t(n,t,r,`Missing template variable '${e}'`));i=i[a]}return i}function _a(o,e,t,n){let r="";for(let s of o){if(s.type==="text"){r+=s.value;continue}if(s.type==="var"){let u=Pa(e,s.name,t,n,s.index);if(typeof u!="string"&&typeof u!="number"&&typeof u!="boolean")throw new Error(_t(n,t,s.index,`Variable '${s.name}' must be string, number, or boolean`));r+=String(u);continue}let i,a=Hl.exec(s.condition);if(a){let[,u,c,l]=a,p=c??l??"";i=Pa(e,u,t,n,s.index)===p}else{let u=Pa(e,s.condition,t,n,s.index);if(typeof u!="boolean")throw new Error(_t(n,t,s.index,`Condition '${s.condition}' must be boolean`));i=u}i?r+=_a(s.thenNodes,e,t,n):r+=_a(s.elseNodes,e,t,n)}return r}function qm(o,e){let t=zm(o),n=Fa(t,o,e);if(n.terminator)throw new Error(`Unexpected template terminator '${n.terminator}' in ${e}`);return n.nodes}function Ct(o,e={}){let t=Bl[o],n=`template:${o}`;if(!t)throw new Error(`Unknown template id: ${String(o)}`);let r=ql.get(o);return r||(r=qm(t,n),ql.set(o,r)),_a(r,e,t,n)}var Kl=Ct("dsp/function-call-instructions.md"),Hm=Ct("dsp/strict-output-formatting-rules.md"),Km=Ct("dsp/example-disclaimer.md"),Xn=Ct("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,he.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=ws(this.sig.getInputFields()),r=ws(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(l=>"toFunction"in l?l.toFunction():l)?.flat()?.map(l=>`- \`${l.name}\`: ${Zn(l.description)}`).join(`
716
716
  `);i&&i.length>0&&e.push(`## Available Functions
717
- ${i}`);let a=this.getFieldNameToTitleMap(),u=Hl(this.sig.getInputFields(),a);if(e.push(`## Input Fields
717
+ ${i}`);let a=this.getFieldNameToTitleMap(),u=Vl(this.sig.getInputFields(),a);if(e.push(`## Input Fields
718
718
  ${u}`),!t){let l=Wl(this.sig.getOutputFields(),a);e.push(`## Output Fields
719
- ${l}`)}i&&i.length>0&&e.push(ql.trim()),t&&this.structuredOutputFunctionName?e.push(Tt("dsp/legacy-formatting-rules-structured-function.md",{structuredOutputFunctionName:this.structuredOutputFunctionName}).trim()):t||e.push(jm.trim());let c=this.sig.getDescription();if(c){let l=Yn(c);l=Rs(l,a),e.push(l)}return{type:"text",text:e.join(`
719
+ ${l}`)}i&&i.length>0&&e.push(Kl.trim()),t&&this.structuredOutputFunctionName?e.push(Ct("dsp/legacy-formatting-rules-structured-function.md",{structuredOutputFunctionName:this.structuredOutputFunctionName}).trim()):t||e.push(Hm.trim());let c=this.sig.getDescription();if(c){let l=Zn(c);l=Rs(l,a),e.push(l)}return{type:"text",text:e.join(`
720
720
 
721
721
  `)}}buildStructuredPrompt(){let e=[],t=this.sig.hasComplexFields();e.push("<identity>"),e.push(this.buildIdentitySection()),e.push("</identity>");let n=this.buildTaskDefinitionSection();n&&(e.push(`
722
722
  <task_definition>`),e.push(n),e.push("</task_definition>"));let r=this.functions?.flatMap(s=>"toFunction"in s?s.toFunction():s);return r&&r.length>0&&(e.push(`
@@ -724,32 +724,32 @@ ${l}`)}i&&i.length>0&&e.push(ql.trim()),t&&this.structuredOutputFunctionName?e.p
724
724
  <input_fields>`),e.push(this.buildInputFieldsSection()),e.push("</input_fields>"),t||(e.push(`
725
725
  <output_fields>`),e.push(this.buildOutputFieldsSection()),e.push("</output_fields>")),e.push(`
726
726
  <formatting_rules>`),e.push(this.buildFormattingRulesSection()),e.push("</formatting_rules>"),{type:"text",text:e.join(`
727
- `)}}buildIdentitySection(){let e=ws(this.sig.getInputFields()),t=ws(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=Yn(e);return n=Rs(n,t),n}buildFunctionsSection(e){let t=[];t.push(`**Available Functions**: You can call the following functions to complete the task:
728
- `);let n=e.map(r=>`- \`${r.name}\`: ${Yn(r.description??"")}`).join(`
727
+ `)}}buildIdentitySection(){let e=ws(this.sig.getInputFields()),t=ws(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=Zn(e);return n=Rs(n,t),n}buildFunctionsSection(e){let t=[];t.push(`**Available Functions**: You can call the following functions to complete the task:
728
+ `);let n=e.map(r=>`- \`${r.name}\`: ${Zn(r.description??"")}`).join(`
729
729
  `);return t.push(n),t.push(`
730
- ${ql.trim()}`),t.join(`
730
+ ${Kl.trim()}`),t.join(`
731
731
  `)}buildInputFieldsSection(){let e=this.getFieldNameToTitleMap();return`**Input Fields**: The following fields will be provided to you:
732
732
 
733
- ${Hl(this.sig.getInputFields(),e)}`}buildOutputFieldsSection(){let e=this.getFieldNameToTitleMap();return`**Output Fields**: You must generate the following fields:
733
+ ${Vl(this.sig.getInputFields(),e)}`}buildOutputFieldsSection(){let e=this.getFieldNameToTitleMap();return`**Output Fields**: You must generate the following fields:
734
734
 
735
- ${Wl(this.sig.getOutputFields(),e)}`}buildFormattingRulesSection(){let e=this.sig.hasComplexFields();return e&&this.structuredOutputFunctionName?Tt("dsp/formatting-rules-structured-function.md",{structuredOutputFunctionName:this.structuredOutputFunctionName}).trim():e?Tt("dsp/formatting-rules-structured-json.md").trim():Tt("dsp/formatting-rules-plain-text.md").trim()}renderSingleValueUserContent=(e,t,n,r)=>{let s=this.renderInputFields(e),i;if(r)i=s;else{let u=[...t,...n];if(this.contextCache&&u.length>0){let c=u.length-1,l=u[c];l&&(u[c]={...l,cache:!0})}i=[...u,...s]}let a=i.filter(u=>u!==void 0);return a.every(u=>u.type==="text")?a.map(u=>u.text).join(`
736
- `):a.reduce(cn(`
735
+ ${Wl(this.sig.getOutputFields(),e)}`}buildFormattingRulesSection(){let e=this.sig.hasComplexFields();return e&&this.structuredOutputFunctionName?Ct("dsp/formatting-rules-structured-function.md",{structuredOutputFunctionName:this.structuredOutputFunctionName}).trim():e?Ct("dsp/formatting-rules-structured-json.md").trim():Ct("dsp/formatting-rules-plain-text.md").trim()}renderSingleValueUserContent=(e,t,n,r)=>{let s=this.renderInputFields(e),i;if(r)i=s;else{let u=[...t,...n];if(this.contextCache&&u.length>0){let c=u.length-1,l=u[c];l&&(u[c]={...l,cache:!0})}i=[...u,...s]}let a=i.filter(u=>u!==void 0);return a.every(u=>u.type==="text")?a.map(u=>u.text).join(`
736
+ `):a.reduce(ln(`
737
737
  `),[])};render=(e,{examples:t,demos:n})=>{if(!this.examplesInSystem)return this.renderWithMessagePairs(e,{examples:t,demos:n});let r=t?[{type:"text",text:`
738
738
 
739
739
  ## Examples
740
- `},...this.renderExamples(t)]:[],s=n?this.renderDemos(n):[],i=r.every(d=>d.type==="text"),a=s.every(d=>d.type==="text"),u=i&&a,c=this.task.text;if(u){let d=[{type:"text",text:c},...r,...s];d.reduce(cn(""),[]),d?.[0]&&(c=d[0].text)}let l={role:"system",content:c,cache:!!this.contextCache};if(Array.isArray(e)){let d=[],m=e,g=!0;for(let f of m){let x;if(g?(x=this.renderSingleValueUserContent(f.values,r,s,u),g=!1):x=this.renderSingleValueUserContent(f.values,[],[],!1),f.role==="user"){d.push({role:"user",content:x});continue}if(f.role!=="assistant")throw new Error("Invalid message role");if(typeof x!="string")throw new Error("Assistant message cannot contain non-text content like images, files,etc");d.push({role:"assistant",content:x})}return[l,...d]}let p=this.renderSingleValueUserContent(e,r,s,u);return[l,{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}
741
- ${zm}`:this.task.text,cache:!!this.contextCache},a=t?this.renderExamplesAsMessages(t):[],u=n?this.renderDemosAsMessages(n):[],c=[];for(let C of[...a,...u])c.push(C.userMessage),c.push(C.assistantMessage),C.functionResultMessage&&c.push(C.functionResultMessage);let l=this.contextCache?.cacheBreakpoint??"after-examples",p=this.ignoreBreakpoints||l==="after-examples";if(this.contextCache&&c.length>0&&p){let C=c.length-1,R=c[C];R?.role==="assistant"&&(c[C]={...R,cache:!0})}if(Array.isArray(e)){let C=[],R=e,M=!0;for(let I of R){let O=this.renderInputFields(I.values),E=O.every($=>$.type==="text")?O.map($=>$.text).join(`
742
- `):O.reduce(cn(`
743
- `),[]);if(I.role==="user"){M&&r&&(typeof E=="string"?E=Qn+E:E=[{type:"text",text:Qn},...E],M=!1),C.push({role:"user",content:E});continue}if(I.role!=="assistant")throw new Error("Invalid message role");if(typeof E!="string")throw new Error("Assistant message cannot contain non-text content like images, files, etc");C.push({role:"assistant",content:E})}return[i,...c,...C]}let d=this.sig.getInputFields(),m=d.filter(C=>C.isCached),g=d.filter(C=>!C.isCached),f=m.length>0;if(this.contextCache&&f&&(this.ignoreBreakpoints||l!=="system"&&l!=="after-functions")&&g.length>0){let C=m.map(O=>this.renderInField(O,e,void 0)).filter(O=>O!==void 0).flat();C.filter(O=>O.type==="text").forEach(O=>{O.text=`${O.text}
744
- `});let R=C.every(O=>O.type==="text")?C.map(O=>O.text).join(`
745
- `):C.reduce(cn(`
746
- `),[]);r&&(typeof R=="string"?R=Qn+R:R=[{type:"text",text:Qn},...R]);let M=g.map(O=>this.renderInField(O,e,void 0)).filter(O=>O!==void 0).flat();M.filter(O=>O.type==="text").forEach(O=>{O.text=`${O.text}
747
- `});let I=M.every(O=>O.type==="text")?M.map(O=>O.text).join(`
748
- `):M.reduce(cn(`
749
- `),[]);return[i,...c,{role:"user",content:R,cache:!0},{role:"user",content:I}]}let h=this.sortFieldsCachedFirst(d).map(C=>this.renderInField(C,e,void 0)).filter(C=>C!==void 0).flat();h.filter(C=>C.type==="text").forEach(C=>{C.text=`${C.text}
750
- `});let y=h.every(C=>C.type==="text")?h.map(C=>C.text).join(`
751
- `):h.reduce(cn(`
752
- `),[]);r&&(typeof y=="string"?y=Qn+y:y=[{type:"text",text:Qn},...y]);let T=f&&g.length===0&&this.contextCache;return[i,...c,{role:"user",content:y,...T?{cache:!0}:{}}]};renderExtraFields=e=>{let t=[];if(!e||e.length===0)return t;let n=e.reduce((i,a)=>{let u=a.title;return i[u]||(i[u]=[]),i[u].push(a),i},{}),r=this.sig.hasComplexFields();return Object.entries(n).map(([i,a])=>{if(a.length===1){let u=a[0];return u.type?.name==="object"||u.type?.isArray&&u.type.fields?{title:i,name:u.name,description:`${u.description}
740
+ `},...this.renderExamples(t)]:[],s=n?this.renderDemos(n):[],i=r.every(d=>d.type==="text"),a=s.every(d=>d.type==="text"),u=i&&a,c=this.task.text;if(u){let d=[{type:"text",text:c},...r,...s];d.reduce(ln(""),[]),d?.[0]&&(c=d[0].text)}let l={role:"system",content:c,cache:!!this.contextCache};if(Array.isArray(e)){let d=[],m=e,g=!0;for(let f of m){let x;if(g?(x=this.renderSingleValueUserContent(f.values,r,s,u),g=!1):x=this.renderSingleValueUserContent(f.values,[],[],!1),f.role==="user"){d.push({role:"user",content:x});continue}if(f.role!=="assistant")throw new Error("Invalid message role");if(typeof x!="string")throw new Error("Assistant message cannot contain non-text content like images, files,etc");d.push({role:"assistant",content:x})}return[l,...d]}let p=this.renderSingleValueUserContent(e,r,s,u);return[l,{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}
741
+ ${Km}`:this.task.text,cache:!!this.contextCache},a=t?this.renderExamplesAsMessages(t):[],u=n?this.renderDemosAsMessages(n):[],c=[];for(let I of[...a,...u])c.push(I.userMessage),c.push(I.assistantMessage),I.functionResultMessage&&c.push(I.functionResultMessage);let l=this.contextCache?.cacheBreakpoint??"after-examples",p=this.ignoreBreakpoints||l==="after-examples";if(this.contextCache&&c.length>0&&p){let I=c.length-1,R=c[I];R?.role==="assistant"&&(c[I]={...R,cache:!0})}if(Array.isArray(e)){let I=[],R=e,M=!0;for(let T of R){let O=this.renderInputFields(T.values),E=O.every($=>$.type==="text")?O.map($=>$.text).join(`
742
+ `):O.reduce(ln(`
743
+ `),[]);if(T.role==="user"){M&&r&&(typeof E=="string"?E=Xn+E:E=[{type:"text",text:Xn},...E],M=!1),I.push({role:"user",content:E});continue}if(T.role!=="assistant")throw new Error("Invalid message role");if(typeof E!="string")throw new Error("Assistant message cannot contain non-text content like images, files, etc");I.push({role:"assistant",content:E})}return[i,...c,...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||l!=="system"&&l!=="after-functions")&&g.length>0){let I=m.map(O=>this.renderInField(O,e,void 0)).filter(O=>O!==void 0).flat();I.filter(O=>O.type==="text").forEach(O=>{O.text=`${O.text}
744
+ `});let R=I.every(O=>O.type==="text")?I.map(O=>O.text).join(`
745
+ `):I.reduce(ln(`
746
+ `),[]);r&&(typeof R=="string"?R=Xn+R:R=[{type:"text",text:Xn},...R]);let M=g.map(O=>this.renderInField(O,e,void 0)).filter(O=>O!==void 0).flat();M.filter(O=>O.type==="text").forEach(O=>{O.text=`${O.text}
747
+ `});let T=M.every(O=>O.type==="text")?M.map(O=>O.text).join(`
748
+ `):M.reduce(ln(`
749
+ `),[]);return[i,...c,{role:"user",content:R,cache:!0},{role:"user",content:T}]}let h=this.sortFieldsCachedFirst(d).map(I=>this.renderInField(I,e,void 0)).filter(I=>I!==void 0).flat();h.filter(I=>I.type==="text").forEach(I=>{I.text=`${I.text}
750
+ `});let y=h.every(I=>I.type==="text")?h.map(I=>I.text).join(`
751
+ `):h.reduce(ln(`
752
+ `),[]);r&&(typeof y=="string"?y=Xn+y:y=[{type:"text",text:Xn},...y]);let C=f&&g.length===0&&this.contextCache;return[i,...c,{role:"user",content:y,...C?{cache:!0}:{}}]};renderExtraFields=e=>{let t=[];if(!e||e.length===0)return t;let n=e.reduce((i,a)=>{let u=a.title;return i[u]||(i[u]=[]),i[u].push(a),i},{}),r=this.sig.hasComplexFields();return Object.entries(n).map(([i,a])=>{if(a.length===1){let u=a[0];return u.type?.name==="object"||u.type?.isArray&&u.type.fields?{title:i,name:u.name,description:`${u.description}
753
753
  IMPORTANT: Provide the FULL JSON object for this field, matching the schema exactly.`}:{title:i,name:u.name,description:u.description}}if(a.length>1){let u=a.map(c=>`- ${c.description}`).join(`
754
754
  `);return{title:i,name:a[0].name,description:u}}}).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[s,i]of e.entries()){if(r){let l=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=[...l,{type:"text",text:`\`\`\`json
755
755
  ${m}
@@ -766,22 +766,22 @@ ${m}
766
766
  `}].slice(0,-1).forEach(f=>{"text"in f&&(f.text=`${f.text}
767
767
  `),t.push(f)});continue}let u=n.map(p=>this.renderInField(p,a,{...s,isInputField:!0})).filter(p=>p!==void 0).flat(),c=r.map(p=>this.renderInField(p,a,{...s,isInputField:!1})).filter(p=>p!==void 0).flat();[...u,...c].slice(0,-1).forEach(p=>{"text"in p&&(p.text=`${p.text}
768
768
  `),t.push(p)})}return t};renderExamplesAsMessages=e=>{let t=[],n={isExample:!0},r=this.sig.hasComplexFields();for(let s of e){let a=this.sortFieldsCachedFirst(this.sig.getInputFields()).map(d=>this.renderInField(d,s,{...n,isInputField:!0})).filter(d=>d!==void 0).flat(),u=a.every(d=>d.type==="text")?a.map(d=>d.text).join(`
769
- `):a.reduce(cn(`
769
+ `):a.reduce(ln(`
770
770
  `),[]);if(r&&this.structuredOutputFunctionName){let d={};for(let f of this.sig.getOutputFields())f.name in s&&(d[f.name]=s[f.name]);if(typeof u=="string"&&u.trim()===""||Array.isArray(u)&&u.length===0||Object.keys(d).length===0)continue;let g=`example-${t.length}`;t.push({userMessage:{role:"user",content:u},assistantMessage:{role:"assistant",functionCalls:[{id:g,type:"function",function:{name:this.structuredOutputFunctionName,params:d}}]},functionResultMessage:{role:"function",result:"done",functionId:g}});continue}let c;if(r){let d={};for(let m of this.sig.getOutputFields())m.name in s&&(d[m.name]=s[m.name]);c=JSON.stringify(d,null,2)}else c=this.sig.getOutputFields().map(m=>this.renderInField(m,s,{...n,isInputField:!1})).filter(m=>m!==void 0).flat().filter(m=>m.type==="text").map(m=>m.text).join(`
771
771
  `);let l=c.trim()==="";typeof u=="string"&&u.trim()===""||Array.isArray(u)&&u.length===0||l||t.push({userMessage:{role:"user",content:u},assistantMessage:{role:"assistant",content:c}})}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}
772
- `}),n};renderInField=(e,t,n)=>{let r=t[e.name];if(Wm(e,r,n))return;e.type&&Hr(e,r);let s=qm(e,r);return(this.fieldTemplates?.[e.name]??this.defaultRenderInField)(e,s)};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},s=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("Image field value must be an array.");s=s.concat(t.map(i=>{let a=r(i);return{type:"image",mimeType:a.mimeType,image:a.data}}))}else{let i=r(t);s.push({type:"image",mimeType:i.mimeType,image:i.data})}return s}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},s=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("Audio field value must be an array.");s=s.concat(t.map(i=>{let a=r(i);return{type:"audio",format:a.format??"wav",data:a.data}}))}else{let i=r(t);s.push({type:"audio",format:i.format??"wav",data:i.data})}return s}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,u="fileUri"in i;if(!a&&!u)throw new Error("File field must have either data or fileUri");if(a&&u)throw new Error("File field cannot have both data and fileUri");return i},s=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("File field value must be an array.");s=s.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);s.push("fileUri"in i?{type:"file",mimeType:i.mimeType,fileUri:i.fileUri}:{type:"file",mimeType:i.mimeType,data:i.data})}return s}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},s=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("URL field value must be an array.");s=s.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);s.push({type:"url",url:i.url,...i.title?{title:i.title}:{},...i.description?{description:i.description}:{}})}return s}let n=[e.title,": "];return Array.isArray(t)?(n.push(`
772
+ `}),n};renderInField=(e,t,n)=>{let r=t[e.name];if(Jm(e,r,n))return;e.type&&Kr(e,r);let s=Vm(e,r);return(this.fieldTemplates?.[e.name]??this.defaultRenderInField)(e,s)};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},s=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("Image field value must be an array.");s=s.concat(t.map(i=>{let a=r(i);return{type:"image",mimeType:a.mimeType,image:a.data}}))}else{let i=r(t);s.push({type:"image",mimeType:i.mimeType,image:i.data})}return s}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},s=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("Audio field value must be an array.");s=s.concat(t.map(i=>{let a=r(i);return{type:"audio",format:a.format??"wav",data:a.data}}))}else{let i=r(t);s.push({type:"audio",format:i.format??"wav",data:i.data})}return s}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,u="fileUri"in i;if(!a&&!u)throw new Error("File field must have either data or fileUri");if(a&&u)throw new Error("File field cannot have both data and fileUri");return i},s=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("File field value must be an array.");s=s.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);s.push("fileUri"in i?{type:"file",mimeType:i.mimeType,fileUri:i.fileUri}:{type:"file",mimeType:i.mimeType,data:i.data})}return s}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},s=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("URL field value must be an array.");s=s.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);s.push({type:"url",url:i.url,...i.title?{title:i.title}:{},...i.description?{description:i.description}:{}})}return s}let n=[e.title,": "];return Array.isArray(t)?(n.push(`
773
773
  `),n.push(t.map(r=>`- ${r}`).join(`
774
- `))):n.push(t),[{type:"text",text:n.join("")}]}},ws=o=>o.map(e=>`\`${e.title}\``).join(", "),Hl=(o,e)=>o.map(n=>{let r=n.title,s=n.type?.name?Xn(n.type):"string",i=n.isOptional?`This optional ${s} field may be omitted`:`${/^[aeiou]/i.test(s)?"An":"A"} ${s} field`,a="";if(n.description){let u=Yn(n.description);e&&(u=Rs(u,e)),a=` ${u}`}return`${r}: (${i})${a}`.trim()}).join(`
775
- `),Wl=(o,e)=>o.map(n=>{let r=n.title,s=n.type?.name?Xn(n.type):"string",i=n.isOptional?`Only include this ${s} field if its value is available`:`This ${s} field must be included`,a="";if(n.description&&n.description.length>0){let u=n.type?.name==="class"?n.description:Yn(n.description);e&&(u=Rs(u,e)),a=` ${u}`}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(`
776
- `),qm=(o,e)=>{if(o.type?.name==="date"&&e instanceof Date){let t=e.toISOString();return t.slice(0,t.indexOf("T"))}return o.type?.name==="datetime"&&e instanceof Date?Cl(e):o.type?.name==="image"&&typeof e=="object"||o.type?.name==="audio"&&typeof e=="object"||o.type?.name==="file"&&typeof e=="object"||o.type?.name==="url"&&(typeof e=="string"||typeof e=="object")||typeof e=="string"?e:JSON.stringify(e,null,2)};function Hm(o){return`{ ${Object.entries(o).map(([t,n])=>{let r=n.isOptional?"?":"",s=Xn({name:n.type,isArray:n.isArray,fields:n.fields,options:n.options});return`${t}${r}: ${s}`}).join(", ")} }`}var Xn=o=>{let e=(()=>{switch(o?.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 o?.fields?`object ${Hm(o.fields)}`:"object";default:return"string"}})();return o?.isArray?`json array of ${e} items`:e};function cn(o){return(e,t)=>{if(t.type==="text"){let n=e.length>0?e[e.length-1]:null;n&&n.type==="text"?n.text+=o+t.text:e.push(t)}else e.push(t);return e}}var Wm=(o,e,t)=>{if(typeof e=="boolean"||o?.type?.name==="number"&&typeof e=="number")return!1;if(!e||(Array.isArray(e)||typeof e=="string")&&e.length===0){if(t?.isExample||o.isOptional||o.isInternal)return!0;let n=t?.isInputField!==!1?"input":"output";throw new Error(`Value for ${n} field '${o.name}' is required.`)}return!1};function Yn(o){let e=o.trim();return e.length>0?`${e.charAt(0).toUpperCase()}${e.slice(1)}${e.endsWith(".")?"":"."}`:""}function Rs(o,e){if(e.size===0)return o;let t=o,n=Array.from(e.keys()).sort((r,s)=>s.length-r.length);for(let r of n){let s=e.get(r),i=new RegExp(`\`${r}\``,"g");t=t.replace(i,`\`${s}\``);let a=new RegExp(`"${r}"`,"g");t=t.replace(a,`"${s}"`);let u=new RegExp(`'${r}'`,"g");t=t.replace(u,`'${s}'`);let c=new RegExp(`\\[${r}\\]`,"g");t=t.replace(c,`[${s}]`);let l=new RegExp(`\\(${r}\\)`,"g");t=t.replace(l,`(${s})`);let p=new RegExp(`\\$${r}\\b`,"g");t=t.replace(p,`\`${s}\``)}return t}function Km(o,e){let t=o.history(0,e),n=t.some(s=>s.role==="function");return t.some(s=>s.role==="assistant"&&"functionCalls"in s&&Array.isArray(s.functionCalls)&&s.functionCalls.length>0)&&n}function Vm(o,e){let t=o.history(0,e),n=[],r=t.filter(i=>i.role==="assistant"&&"functionCalls"in i&&Array.isArray(i.functionCalls)&&i.functionCalls.length>0),s=t.filter(i=>i.role==="function");for(let i of r)if("functionCalls"in i&&i.functionCalls)for(let a of i.functionCalls){let u=s.find(c=>"functionId"in c&&c.functionId===a.id);u&&"result"in u&&"functionId"in u&&n.push({index:n.length,functionName:a.function.name,functionId:a.id,args:a.function.params||"",result:String(u.result),isError:"isError"in u?!!u.isError:!1})}return n}async function vs(o,e,t,n){if(!e?.resultPicker||o.length<=1)return 0;let r=e.resultPicker;if((t?Km(t,n):!1)&&t){let u=Vm(t,n),c=await r({type:"function",results:u});if(c<0||c>=u.length)throw new Error(`Result picker returned invalid index: ${c}. Must be between 0 and ${u.length-1}`);return c}let i=o.map((u,c)=>({index:c,sample:u.delta})),a=await r({type:"fields",results:i});if(a<0||a>=o.length)throw new Error(`Result picker returned invalid index: ${a}. Must be between 0 and ${o.length-1}`);return a}async function Kl(o,e,t){let n=o?.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 vs(r,t,o,e)}var Zn=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 Ss=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}=Jm(t);e.set(t.name,n)}else e.set(t.name,new Map);return e}async route(e,t){let n=[],r={},s=new Map,i=new Map;for(let[a,u]of this.tools.entries())i.set(a,this.buildSanitizedFieldMap(u));for(let[a,u]of Object.entries(e)){let c=this.tools.get(this.normalizeToolName(a));if(c){u!=null&&typeof u=="object"&&s.set(c.name,u);continue}r[a]=u}for(let[a,u]of Object.entries(e))for(let[c,l]of this.tools.entries()){let p=i.get(c);if(!p)continue;let d=p.get(a);if(!d)continue;let m=s.get(l.name)??{};this.setNested(m,d,u),s.set(l.name,m)}for(let[a,u]of this.tools.entries()){let c=s.get(u.name);if(!(!c||Object.keys(c).length===0)){if(u.parameters&&u.parameters.type==="object"){let p=(u.parameters.required||[]).filter(d=>c[d]===void 0);if(p.length>0)throw new Qe(`Missing required arguments for tool '${u.name}': ${p.join(", ")}`)}n.push({id:u.name,name:u.name,args:JSON.stringify(c)})}}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,s)=>{for(let[i,a]of Object.entries(r)){let u=[...s,i];if(a&&a.type==="object"&&a.properties)n(a.properties,u);else{let c=`${e.name}.${u.join(".")}`,l=this.sanitizeFieldName(c);t.set(l,u)}}};return n(e.parameters.properties??{},[]),t}setNested(e,t,n){let r=e;for(let s=0;s<t.length-1;s++){let i=t[s],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 Jm(o){let e=[],t=new Map;if(!o.parameters||!o.parameters.properties)return{fields:e,paramFieldMap:t};let n=o.parameters.properties,r=o.parameters.required||[],s=(i,a,u)=>{for(let[c,l]of Object.entries(i)){let p=a?`${a}.${c}`:c,d=`${o.name}.${p}`;if(l.type==="object"&&l.properties)s(l.properties,p,l.required||[]);else{let m=Qm(l);e.push({name:Xm(d),title:Ym(o.name,p),type:m,description:l.description||`${c} parameter for ${o.name}`,isOptional:!0}),t.set(d,e[e.length-1])}}};return s(n,"",r),{fields:e,paramFieldMap:t}}function Qm(o){switch(o.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=o.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 Ym(o,e){return`${o} ${e.replace(/\./g," ")}`}function Xm(o){return o.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}function Ql(o,e,t){let n=new Ne(e);if(t){let r=t.getToolParamFieldMap();for(let s of o){let i=r.get(s.name);if(i&&i.size>0)for(let a of i.values())n.getOutputFields().some(c=>c.name===a.name)||n.addOutputField(a);else{let a=_a(s.name),u=Jl(s.parameters);n.getOutputFields().some(l=>l.name===a)||n.addOutputField({name:a,title:Vl(s.name),type:u,description:s.description||`Parameters for ${s.name}`,isOptional:!0})}}return{signature:n,toolParamFieldMap:r}}else{let r=new Map;for(let s of o)if(s.parameters?.properties&&Object.keys(s.parameters.properties).length>0){let{fields:i,paramFieldMap:a}=Zm(s);r.set(s.name,a);for(let u of i)n.getOutputFields().some(l=>l.name===u.name)||n.addOutputField(u)}else{let i=_a(s.name),a=Jl(s.parameters);n.getOutputFields().some(c=>c.name===i)||n.addOutputField({name:i,title:Vl(s.name),type:a,description:s.description||`Parameters for ${s.name}`,isOptional:!0})}return{signature:n,toolParamFieldMap:r}}}function Zm(o){let e=[],t=new Map;if(!o.parameters||!o.parameters.properties)return{fields:e,paramFieldMap:t};let n=o.parameters.properties,r=o.parameters.required||[],s=(i,a,u)=>{for(let[c,l]of Object.entries(i)){let p=a?`${a}.${c}`:c,d=`${o.name}.${p}`;if(l.type==="object"&&l.properties)s(l.properties,p,l.required||[]);else{let m=eg(l),g={name:_a(d),title:tg(o.name,p),type:m,description:l.description||`${c} parameter for ${o.name}`,isOptional:!0};e.push(g),t.set(d,g)}}};return s(n,"",r),{fields:e,paramFieldMap:t}}function eg(o){switch(o.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=o.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 tg(o,e){return`${o} ${e.replace(/\./g," ")}`}function _a(o){return o.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}function Vl(o){return o.replace(/([A-Z])/g," $1").replace(/^./,e=>e.toUpperCase()).trim()}function Jl(o){return!o||!o.properties||Object.keys(o.properties).length===0?{name:"string",isArray:!1}:{name:"json",isArray:!1}}var Xr=class{tools;router;injectedToolFieldNames=new Set;constructor(e){this.tools=e,this.router=new Ss(e)}processSignature(e){let{signature:t}=Ql(this.tools,e),n=new Set(t.getOutputFields().map(s=>s.name)),r=new Set(e.getOutputFields().map(s=>s.name));return this.injectedToolFieldNames=new Set([...n].filter(s=>!r.has(s))),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 er="__finalResult",Me=class o extends Qt{clone=()=>new o(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??ln)(this.signature,n),this.asserts=this.options?.asserts??[],this.streamingAsserts=this.options?.streamingAsserts??[],this.excludeContentFromTrace=t?.excludeContentFromTrace??!1,this.functions=t?.functions?un(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 ra()}getMergedCustomLabels(e,t){return nn(fe.customLabels,e?.getOptions?.()?.customLabels,t?.customLabels)}updateMeter(e){ra(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 s=r.type?.name;if(!(!s||s==="string"||s==="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(s=>s.name===e);if(!r)throw new Error(`addFieldProcessor: field ${e} not found`);if(n){let s=r.type?.name;if(!(!s||s==="string"||s==="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:s,functionCall:i,stepIndex:a}){let{sessionId:u,model:c,rateLimiter:l,stream:p,thinkingTokenBudget:d,showThoughts:m}=n??{},g=await Kl(t,u,{resultPicker:n?.resultPicker}),f=t?.history(g,u)??[];if(f.length===0)throw new Error("No chat prompt found");let x={...n?.modelConfig,...n?.sampleCount?{n:n.sampleCount}:{},...n?.sampleCount&&n?.modelConfig?.temperature===1?{temperature:.8}:{}},A=this.isDebug(e,n),h=a===0,y=this.getLogger(e,n);s=this.signatureToolCallingManager?[]:s;let T,C=this.signature.getOutputFields();if(this.signature.hasComplexFields()&&!this.structuredOutputFunctionFallback){if(!e.getFeatures(c)?.structuredOutputs)throw new Error(`Complex structured outputs (object/array types) require a provider that supports structured outputs. Current provider/model (${c}) does not support this feature. Supported providers: OpenAI (GPT-4o, GPT-4.1+), Google Gemini, Anthropic (Sonnet/Opus).`);T={type:"json_schema",schema:{name:"output",strict:!0,schema:Jt(C)}}}let M=n?.contextCache?.cacheBreakpoint??"after-examples",I=e.getFeatures?.(c)?.caching?.cacheBreakpoints===!1,O=n?.contextCache&&(I||M==="after-functions"||M==="after-examples"),E=s?.length&&O?s.map((N,S)=>({...N,cache:S===s.length-1})):s;return await e.chat({chatPrompt:f,functions:E,functionCall:i,modelConfig:x,model:c,responseFormat:T},{sessionId:u,rateLimiter:l,stream:p,debug:A,debugHideSystemPrompt:n?.debugHideSystemPrompt??this.options?.debugHideSystemPrompt??!h,thinkingTokenBudget:d,showThoughts:m,traceContext:r,abortSignal:n?.abortSignal??fe.abortSignal,stepIndex:a,logger:y,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:s,traceContext:i,states:a,stopFunctionNames:u,stepContext:c}){let{sessionId:l,functions:p}=n??{},d=n?.functionResultFormatter??this.options?.functionResultFormatter,m=n?.functionCall??this.options?.functionCall,g=this.signatureToolCallingManager,f=n?.strictMode??!1,x=n.model,A=this.usage,h=r===0,y=this.isDebug(e,n),T=this.getLogger(e,n),{functions:C,functionCall:R}=El(p,m,h,n);this.structuredOutputFunctionFallback&&C.filter(O=>O.name!==er).length===0&&(R={type:"function",function:{name:er}});let M=await this.forwardSendRequest({ai:e,mem:t,options:n,traceContext:i,functions:C,functionCall:R,stepIndex:r});M instanceof ReadableStream?yield*Pl({ai:e,model:x,res:M,mem:t,sessionId:l,traceId:s?s.spanContext?.().traceId:void 0,functions:C,strictMode:f,span:s,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:T,debug:y,functionResultFormatter:d,signatureToolCallingManager:g,stopFunctionNames:u,disableMemoryCleanup:n.disableMemoryCleanup,stepContext:c,abortSignal:n.abortSignal}):yield*Fl({ai:e,model:x,res:M,mem:t,sessionId:l,traceId:s?s.spanContext?.().traceId:void 0,functions:C,span:s,strictMode:f,states:a,usage:A,asserts:this.asserts,fieldProcessors:this.fieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,logger:T,debug:y,functionResultFormatter:d,signatureToolCallingManager:g,stopFunctionNames:u,disableMemoryCleanup:n.disableMemoryCleanup,stepContext:c,abortSignal:n.abortSignal})}async*_forward2(e,t,n,r,s,i){this.signatureToolCallingManager=void 0;let a=r?.stopFunction??this.options?.stopFunction,u=Array.isArray(a)?a.map(H=>H.toLowerCase()):a?[a.toLowerCase()]:void 0,c=r.maxRetries??this.options?.maxRetries??3,l=r.maxSteps??this.options?.maxSteps??25,p=r.mem??this.options?.mem??new qn,d=r.functions?un(r.functions):[...this.functions],m=new Zn(l),g;if(r.selfTuning){if(g=r.selfTuning===!0?{model:!0,thinkingBudget:!0}:r.selfTuning,g.model!==!1){let le=e.getModelList()?.filter(B=>"model"in B);if(!le||le.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 H=Ra(e,g,r.model?String(r.model):void 0);d.push(H)}let f={...r},x=r.stepHooks,A=d&&d.length>0,h=r.functionCallMode??this.options?.functionCallMode??"auto";A&&h==="prompt"&&(this.signatureToolCallingManager=new Xr(d)),A&&h==="auto"&&!e.getFeatures(r.model).functions&&(this.signatureToolCallingManager=new Xr(d));let y,T,C=this.options?.promptTemplate??ln;this.signatureToolCallingManager&&(this.signature=this.signatureToolCallingManager.processSignature(this.signature),this.setSignature(this.signature));let R=this.signature.hasComplexFields(),M=e.getFeatures?.(r.model),I=r.structuredOutputMode??this.options?.structuredOutputMode??"auto";if(this.structuredOutputFunctionFallback=R&&(I==="function"||I==="auto"&&!M?.structuredOutputs),this.structuredOutputFunctionFallback){let H={name:er,description:"Return the final result. Call this function with the complete output data.",parameters:Jt(this.signature.getOutputFields()),func:async()=>"done"};d.push(H),u=[...u??[],er.toLowerCase()]}let O=e.getFeatures?.(r.model)?.caching?.cacheBreakpoints===!1,E={functions:this.signatureToolCallingManager?[]:d,thoughtFieldName:this.thoughtFieldName,contextCache:r.contextCache,examplesInSystem:r.examplesInSystem,ignoreBreakpoints:O,structuredOutputFunctionName:this.structuredOutputFunctionFallback?er:void 0};this.promptTemplate=new C(this.signature,E);let $,N=performance.now();Array.isArray(t)?(Ac(t),$=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos})):$=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos});let S=performance.now()-N,v=this.getMetricsInstruments(),F=this.getMergedCustomLabels(e,r);v&&ms(v,"prompt_render",S,this.getSignatureName(),F);let P=performance.now();p.addRequest($,r.sessionId);let L=performance.now()-P;v&&ms(v,"memory_update",L,this.getSignatureName(),F);let D=new Map;n.forEach(H=>{D.set(H.index,{})});let j=()=>{let H=m._consumePendingOptions();if(H){let{modelConfig:B,...V}=H;f={...f,...V},B&&(f.modelConfig={...f.modelConfig,...B})}let re=m._consumeFunctionsToAdd();if(re){let B=un(re);for(let V of B)d.some(Q=>Q.name===V.name)||d.push(V)}let le=m._consumeFunctionsToRemove();if(le){let B=new Set(le.map(V=>V.toLowerCase()));for(let V=d.length-1;V>=0;V--)B.has(d[V].name.toLowerCase())&&d.splice(V,1)}},G=r?.abortSignal??fe.abortSignal;e:for(let H=0;H<l;H++){if(m._beginStep(H),j(),g&&g.model!==!1){let le=d.findIndex(B=>B.name==="adjustGeneration");if(le!==-1){let B=f.model?String(f.model):void 0;d[le]=Ra(e,g,B)}}if(m._isStopRequested)break;if(G?.aborted)throw new Fe("between-steps",G.reason??"Aborted between steps");if(x?.beforeStep&&(await x.beforeStep(m),j(),m._isStopRequested))break;let re=c;for(let le=0;le<=re;le++)try{let B=c+1;for(let Q=0;Q<B;Q++){n.forEach(W=>{W.content="",W.values={},W.functionCalls=[],W.functionsExecuted=new Set,W.xstate={extractedFields:[],streamedIndex:{},s:-1}}),Q>0&&D.forEach((W,q)=>{D.set(q,{})});let ie=new Map;n.forEach(W=>{ie.set(W.index,{})});try{let W=this.forwardCore({options:{...f,functions:d},ai:e,mem:p,stepIndex:H,span:s,traceContext:i,states:n,stopFunctionNames:u,stepContext:m}),q=!1;try{for await(let ae of W)if(ae!==void 0){let ke=ae.index,ce=ae.delta,me=ie.get(ke)??{},be=D.get(ke)??{},ue={},xe=!1;for(let ve of Object.keys(ce)){let je=ce[ve],$e=me[ve],at;typeof je=="string"&&(typeof $e=="string"||$e===void 0)?at=($e??"")+je:Array.isArray(je)&&(Array.isArray($e)||$e===void 0)?at=[...$e??[],...je]:at=je,me[ve]=at;let Ee=at,ze=be[ve];if(typeof Ee=="string"&&typeof ze=="string")if(Ee.startsWith(ze)){let pe=Ee.slice(ze.length);pe&&(ue[ve]=pe,xe=!0,be[ve]=Ee)}else ze.startsWith(Ee)||Ee!==ze&&(ue[ve]=Ee,xe=!0,be[ve]=Ee);else if(Array.isArray(Ee)&&Array.isArray(ze)){if(Ee.length>ze.length){let pe=Ee.slice(ze.length);ue[ve]=pe,xe=!0,be[ve]=Ee}}else JSON.stringify(Ee)!==JSON.stringify(ze)&&(ue[ve]=Ee,xe=!0,be[ve]=Ee)}xe&&(yield{version:Q,index:ae.index,delta:ue})}}catch(ae){if(ae instanceof an){if(q=!0,this.structuredOutputFunctionFallback){let ke=ae.calls.find(ce=>ce.func.name===er);if(ke?.args){let ce=ke.args;Vn(this.signature,ce);let me=this.signature.getOutputFields();for(let be of n){let ue={};for(let xe of me)xe.name in ce&&!xe.isInternal&&(ue[xe.name]=ce[xe.name],be.values[xe.name]=ce[xe.name]);yield{version:Q,index:be.index,delta:ue}}for(let be of n)await Hn(this.asserts,be.values);if(this.fieldProcessors.length>0)for(let be of n)await Kr(this.fieldProcessors,be.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)&&x?.afterFunctionExecution&&(await x.afterFunctionExecution(m),j());let Ce=q||m._isStopRequested?!1:_l(p,u,n,f?.sessionId);if(x?.afterStep&&(await x.afterStep(m),j()),Ce&&!m._isStopRequested&&!G?.aborted){let ae=this.getMetricsInstruments();ae&&ds(ae,H+1,l,this.getSignatureName(),F);continue e}if(G?.aborted)throw new Fe("mid-step",G.reason??"Aborted");r?.disableMemoryCleanup||(p.removeByTag("invalid-assistant",r.sessionId),p.removeByTag("correction",r.sessionId),p.removeByTag("error",r.sessionId));let Re=this.getMetricsInstruments();if(Re){ds(Re,H+1,l,this.getSignatureName(),F);let ae=new Set;n.forEach(ke=>{ke.functionsExecuted.forEach(ce=>ae.add(ce))}),ae.size>0&&Zc(Re,!0,ae.size,!0,!1,this.getSignatureName(),F),el(Re,this.fieldProcessors.length,this.streamingFieldProcessors.length,this.getSignatureName(),F)}return}catch(W){if(W instanceof Fe)throw W;T=W;let q,oe=this.isDebug(e,r),Ce=this.getLogger(e,r),Re=this.getMetricsInstruments(),ae=this.getSignatureName(),ke={error:W,errCount:Q,logger:Ce,metricsInstruments:Re,signatureName:ae,span:s,debug:oe,customLabels:F};if(s?.recordException(W),W instanceof Qe)q=ll(ke),y=W;else if(W instanceof Pt)q=pl(ke),y=W;else if(W instanceof Le)dl(ke);else{if(W instanceof ht)throw W;{let ce=W,me=ce instanceof rt&&ce.status>=500&&ce.status<600,be=ce instanceof Je,ue=ce instanceof gt;throw me||be||ue?W:Na(W,e,this.signature)}}if(q&&(p.addTag("error",r.sessionId),p.addRequest([{role:"user",content:this.promptTemplate.renderExtraFields(q)}],r.sessionId),p.addTag("correction",r.sessionId),this.signature.hasComplexFields()))for(let me of n)me.content="",me.values={},me.xstate={extractedFields:[],streamedIndex:{},s:-1}}}let V=this.getMetricsInstruments();throw V&&sa(V,c,!1,c,this.getSignatureName(),F),Na(new Error(`Unable to fix validation error: ${(y??T)?.message??(y??T)?.toString()??"unknown error"}
774
+ `))):n.push(t),[{type:"text",text:n.join("")}]}},ws=o=>o.map(e=>`\`${e.title}\``).join(", "),Vl=(o,e)=>o.map(n=>{let r=n.title,s=n.type?.name?er(n.type):"string",i=n.isOptional?`This optional ${s} field may be omitted`:`${/^[aeiou]/i.test(s)?"An":"A"} ${s} field`,a="";if(n.description){let u=Zn(n.description);e&&(u=Rs(u,e)),a=` ${u}`}return`${r}: (${i})${a}`.trim()}).join(`
775
+ `),Wl=(o,e)=>o.map(n=>{let r=n.title,s=n.type?.name?er(n.type):"string",i=n.isOptional?`Only include this ${s} field if its value is available`:`This ${s} field must be included`,a="";if(n.description&&n.description.length>0){let u=n.type?.name==="class"?n.description:Zn(n.description);e&&(u=Rs(u,e)),a=` ${u}`}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(`
776
+ `),Vm=(o,e)=>{if(o.type?.name==="date"&&e instanceof Date){let t=e.toISOString();return t.slice(0,t.indexOf("T"))}return o.type?.name==="datetime"&&e instanceof Date?wl(e):o.type?.name==="image"&&typeof e=="object"||o.type?.name==="audio"&&typeof e=="object"||o.type?.name==="file"&&typeof e=="object"||o.type?.name==="url"&&(typeof e=="string"||typeof e=="object")||typeof e=="string"?e:JSON.stringify(e,null,2)};function Wm(o){return`{ ${Object.entries(o).map(([t,n])=>{let r=n.isOptional?"?":"",s=er({name:n.type,isArray:n.isArray,fields:n.fields,options:n.options});return`${t}${r}: ${s}`}).join(", ")} }`}var er=o=>{let e=(()=>{switch(o?.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 o?.fields?`object ${Wm(o.fields)}`:"object";default:return"string"}})();return o?.isArray?`json array of ${e} items`:e};function ln(o){return(e,t)=>{if(t.type==="text"){let n=e.length>0?e[e.length-1]:null;n&&n.type==="text"?n.text+=o+t.text:e.push(t)}else e.push(t);return e}}var Jm=(o,e,t)=>{if(typeof e=="boolean"||o?.type?.name==="number"&&typeof e=="number")return!1;if(!e||(Array.isArray(e)||typeof e=="string")&&e.length===0){if(t?.isExample||o.isOptional||o.isInternal)return!0;let n=t?.isInputField!==!1?"input":"output";throw new Error(`Value for ${n} field '${o.name}' is required.`)}return!1};function Zn(o){let e=o.trim();return e.length>0?`${e.charAt(0).toUpperCase()}${e.slice(1)}${e.endsWith(".")?"":"."}`:""}function Rs(o,e){if(e.size===0)return o;let t=o,n=Array.from(e.keys()).sort((r,s)=>s.length-r.length);for(let r of n){let s=e.get(r),i=new RegExp(`\`${r}\``,"g");t=t.replace(i,`\`${s}\``);let a=new RegExp(`"${r}"`,"g");t=t.replace(a,`"${s}"`);let u=new RegExp(`'${r}'`,"g");t=t.replace(u,`'${s}'`);let c=new RegExp(`\\[${r}\\]`,"g");t=t.replace(c,`[${s}]`);let l=new RegExp(`\\(${r}\\)`,"g");t=t.replace(l,`(${s})`);let p=new RegExp(`\\$${r}\\b`,"g");t=t.replace(p,`\`${s}\``)}return t}function Qm(o,e){let t=o.history(0,e),n=t.some(s=>s.role==="function");return t.some(s=>s.role==="assistant"&&"functionCalls"in s&&Array.isArray(s.functionCalls)&&s.functionCalls.length>0)&&n}function Ym(o,e){let t=o.history(0,e),n=[],r=t.filter(i=>i.role==="assistant"&&"functionCalls"in i&&Array.isArray(i.functionCalls)&&i.functionCalls.length>0),s=t.filter(i=>i.role==="function");for(let i of r)if("functionCalls"in i&&i.functionCalls)for(let a of i.functionCalls){let u=s.find(c=>"functionId"in c&&c.functionId===a.id);u&&"result"in u&&"functionId"in u&&n.push({index:n.length,functionName:a.function.name,functionId:a.id,args:a.function.params||"",result:String(u.result),isError:"isError"in u?!!u.isError:!1})}return n}async function vs(o,e,t,n){if(!e?.resultPicker||o.length<=1)return 0;let r=e.resultPicker;if((t?Qm(t,n):!1)&&t){let u=Ym(t,n),c=await r({type:"function",results:u});if(c<0||c>=u.length)throw new Error(`Result picker returned invalid index: ${c}. Must be between 0 and ${u.length-1}`);return c}let i=o.map((u,c)=>({index:c,sample:u.delta})),a=await r({type:"fields",results:i});if(a<0||a>=o.length)throw new Error(`Result picker returned invalid index: ${a}. Must be between 0 and ${o.length-1}`);return a}async function Na(o,e,t){let n=o?.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 vs(r,t,o,e)}var tr=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 Ss=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}=Xm(t);e.set(t.name,n)}else e.set(t.name,new Map);return e}async route(e,t){let n=[],r={},s=new Map,i=new Map;for(let[a,u]of this.tools.entries())i.set(a,this.buildSanitizedFieldMap(u));for(let[a,u]of Object.entries(e)){let c=this.tools.get(this.normalizeToolName(a));if(c){u!=null&&typeof u=="object"&&s.set(c.name,u);continue}r[a]=u}for(let[a,u]of Object.entries(e))for(let[c,l]of this.tools.entries()){let p=i.get(c);if(!p)continue;let d=p.get(a);if(!d)continue;let m=s.get(l.name)??{};this.setNested(m,d,u),s.set(l.name,m)}for(let[a,u]of this.tools.entries()){let c=s.get(u.name);if(!(!c||Object.keys(c).length===0)){if(u.parameters&&u.parameters.type==="object"){let p=(u.parameters.required||[]).filter(d=>c[d]===void 0);if(p.length>0)throw new Qe(`Missing required arguments for tool '${u.name}': ${p.join(", ")}`)}n.push({id:u.name,name:u.name,args:JSON.stringify(c)})}}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,s)=>{for(let[i,a]of Object.entries(r)){let u=[...s,i];if(a&&a.type==="object"&&a.properties)n(a.properties,u);else{let c=`${e.name}.${u.join(".")}`,l=this.sanitizeFieldName(c);t.set(l,u)}}};return n(e.parameters.properties??{},[]),t}setNested(e,t,n){let r=e;for(let s=0;s<t.length-1;s++){let i=t[s],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 Xm(o){let e=[],t=new Map;if(!o.parameters||!o.parameters.properties)return{fields:e,paramFieldMap:t};let n=o.parameters.properties,r=o.parameters.required||[],s=(i,a,u)=>{for(let[c,l]of Object.entries(i)){let p=a?`${a}.${c}`:c,d=`${o.name}.${p}`;if(l.type==="object"&&l.properties)s(l.properties,p,l.required||[]);else{let m=Zm(l);e.push({name:tg(d),title:eg(o.name,p),type:m,description:l.description||`${c} parameter for ${o.name}`,isOptional:!0}),t.set(d,e[e.length-1])}}};return s(n,"",r),{fields:e,paramFieldMap:t}}function Zm(o){switch(o.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=o.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 eg(o,e){return`${o} ${e.replace(/\./g," ")}`}function tg(o){return o.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}function Yl(o,e,t){let n=new _e(e);if(t){let r=t.getToolParamFieldMap();for(let s of o){let i=r.get(s.name);if(i&&i.size>0)for(let a of i.values())n.getOutputFields().some(c=>c.name===a.name)||n.addOutputField(a);else{let a=$a(s.name),u=Ql(s.parameters);n.getOutputFields().some(l=>l.name===a)||n.addOutputField({name:a,title:Jl(s.name),type:u,description:s.description||`Parameters for ${s.name}`,isOptional:!0})}}return{signature:n,toolParamFieldMap:r}}else{let r=new Map;for(let s of o)if(s.parameters?.properties&&Object.keys(s.parameters.properties).length>0){let{fields:i,paramFieldMap:a}=ng(s);r.set(s.name,a);for(let u of i)n.getOutputFields().some(l=>l.name===u.name)||n.addOutputField(u)}else{let i=$a(s.name),a=Ql(s.parameters);n.getOutputFields().some(c=>c.name===i)||n.addOutputField({name:i,title:Jl(s.name),type:a,description:s.description||`Parameters for ${s.name}`,isOptional:!0})}return{signature:n,toolParamFieldMap:r}}}function ng(o){let e=[],t=new Map;if(!o.parameters||!o.parameters.properties)return{fields:e,paramFieldMap:t};let n=o.parameters.properties,r=o.parameters.required||[],s=(i,a,u)=>{for(let[c,l]of Object.entries(i)){let p=a?`${a}.${c}`:c,d=`${o.name}.${p}`;if(l.type==="object"&&l.properties)s(l.properties,p,l.required||[]);else{let m=rg(l),g={name:$a(d),title:og(o.name,p),type:m,description:l.description||`${c} parameter for ${o.name}`,isOptional:!0};e.push(g),t.set(d,g)}}};return s(n,"",r),{fields:e,paramFieldMap:t}}function rg(o){switch(o.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=o.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 og(o,e){return`${o} ${e.replace(/\./g," ")}`}function $a(o){return o.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}function Jl(o){return o.replace(/([A-Z])/g," $1").replace(/^./,e=>e.toUpperCase()).trim()}function Ql(o){return!o||!o.properties||Object.keys(o.properties).length===0?{name:"string",isArray:!1}:{name:"json",isArray:!1}}var pn=class{tools;router;injectedToolFieldNames=new Set;constructor(e){this.tools=e,this.router=new Ss(e)}processSignature(e){let{signature:t}=Yl(this.tools,e),n=new Set(t.getOutputFields().map(s=>s.name)),r=new Set(e.getOutputFields().map(s=>s.name));return this.injectedToolFieldNames=new Set([...n].filter(s=>!r.has(s))),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",Me=class o extends Qt{clone=()=>new o(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?cn(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()}async renderPromptForInternalUse(e,t,n){let r=n?.promptTemplate??this.options?.promptTemplate??Yt,s=[...this.functions],i=n?.functionCallMode??this.options?.functionCallMode??"auto",a=s.length>0,u;a&&i==="prompt"&&(u=new pn(s)),a&&i==="auto"&&!e.getFeatures(n?.model).functions&&(u=new pn(s));let c=new _e(this.signature);u&&(c=u.processSignature(c));let l=c.hasComplexFields(),p=e.getFeatures?.(n?.model),d=n?.structuredOutputMode??this.options?.structuredOutputMode??"auto",m=l&&(d==="function"||d==="auto"&&!p?.structuredOutputs),g=e.getFeatures?.(n?.model)?.caching?.cacheBreakpoints===!1,f=new r(c,{functions:u?[]:s,thoughtFieldName:this.thoughtFieldName,contextCache:n?.contextCache,examplesInSystem:n?.examplesInSystem,ignoreBreakpoints:g,structuredOutputFunctionName:m?dn:void 0}),x=this.getInstruction();x!==void 0&&f.setInstruction(x),Array.isArray(t)&&Mi(t);let A=f.render(t,{examples:this.examples,demos:this.demos}),h=n?.mem??this.options?.mem;if(!h)return A;let y=await Na(h,n?.sessionId,{resultPicker:n?.resultPicker});return[...h.history(y,n?.sessionId),...A]}async _measurePromptCharsForInternalUse(e,t,n){return Fo(await this.renderPromptForInternalUse(e,t,n))}getSignatureName(){return this.signature.getDescription()||"unknown_signature"}getMetricsInstruments(){return oa()}getMergedCustomLabels(e,t){return rn(he.customLabels,e?.getOptions?.()?.customLabels,t?.customLabels)}updateMeter(e){oa(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 s=r.type?.name;if(!(!s||s==="string"||s==="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(s=>s.name===e);if(!r)throw new Error(`addFieldProcessor: field ${e} not found`);if(n){let s=r.type?.name;if(!(!s||s==="string"||s==="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:s,functionCall:i,stepIndex:a}){let{sessionId:u,model:c,rateLimiter:l,stream:p,thinkingTokenBudget:d,showThoughts:m}=n??{},g=await Na(t,u,{resultPicker:n?.resultPicker}),f=t?.history(g,u)??[];if(f.length===0)throw new Error("No chat prompt found");let x={...n?.modelConfig,...n?.sampleCount?{n:n.sampleCount}:{},...n?.sampleCount&&n?.modelConfig?.temperature===1?{temperature:.8}:{}},A=this.isDebug(e,n),h=a===0,y=this.getLogger(e,n);s=this.signatureToolCallingManager?[]:s;let C,I=this.signature.getOutputFields();if(this.signature.hasComplexFields()&&!this.structuredOutputFunctionFallback){if(!e.getFeatures(c)?.structuredOutputs)throw new Error(`Complex structured outputs (object/array types) require a provider that supports structured outputs. Current provider/model (${c}) 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:Jt(I)}}}let M=n?.contextCache?.cacheBreakpoint??"after-examples",T=e.getFeatures?.(c)?.caching?.cacheBreakpoints===!1,O=n?.contextCache&&(T||M==="after-functions"||M==="after-examples"),E=s?.length&&O?s.map((N,S)=>({...N,cache:S===s.length-1})):s;return await e.chat({chatPrompt:f,functions:E,functionCall:i,modelConfig:x,model:c,responseFormat:C},{sessionId:u,rateLimiter:l,stream:p,debug:A,debugHideSystemPrompt:n?.debugHideSystemPrompt??this.options?.debugHideSystemPrompt??!h,thinkingTokenBudget:d,showThoughts:m,traceContext:r,abortSignal:n?.abortSignal??he.abortSignal,stepIndex:a,logger:y,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:s,traceContext:i,states:a,stopFunctionNames:u,stepContext:c}){let{sessionId:l,functions:p}=n??{},d=n?.functionResultFormatter??this.options?.functionResultFormatter,m=n?.functionCall??this.options?.functionCall,g=this.signatureToolCallingManager,f=n?.strictMode??!1,x=n.model,A=this.usage,h=r===0,y=this.isDebug(e,n),C=this.getLogger(e,n),{functions:I,functionCall:R}=Pl(p,m,h,n);this.structuredOutputFunctionFallback&&I.filter(O=>O.name!==dn).length===0&&(R={type:"function",function:{name:dn}});let M=await this.forwardSendRequest({ai:e,mem:t,options:n,traceContext:i,functions:I,functionCall:R,stepIndex:r});M instanceof ReadableStream?yield*_l({ai:e,model:x,res:M,mem:t,sessionId:l,traceId:s?s.spanContext?.().traceId:void 0,functions:I,strictMode:f,span:s,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:y,functionResultFormatter:d,signatureToolCallingManager:g,stopFunctionNames:u,disableMemoryCleanup:n.disableMemoryCleanup,stepContext:c,abortSignal:n.abortSignal}):yield*Nl({ai:e,model:x,res:M,mem:t,sessionId:l,traceId:s?s.spanContext?.().traceId:void 0,functions:I,span:s,strictMode:f,states:a,usage:A,asserts:this.asserts,fieldProcessors:this.fieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,logger:C,debug:y,functionResultFormatter:d,signatureToolCallingManager:g,stopFunctionNames:u,disableMemoryCleanup:n.disableMemoryCleanup,stepContext:c,abortSignal:n.abortSignal})}async*_forward2(e,t,n,r,s,i){this.signatureToolCallingManager=void 0;let a=r?.stopFunction??this.options?.stopFunction,u=Array.isArray(a)?a.map(K=>K.toLowerCase()):a?[a.toLowerCase()]:void 0,c=r.maxRetries??this.options?.maxRetries??3,l=r.maxSteps??this.options?.maxSteps??25,p=r.mem??this.options?.mem??new Kn,d=r.functions?cn(r.functions):[...this.functions],m=new tr(l),g;if(r.selfTuning){if(g=r.selfTuning===!0?{model:!0,thinkingBudget:!0}:r.selfTuning,g.model!==!1){let pe=e.getModelList()?.filter(G=>"model"in G);if(!pe||pe.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 K=va(e,g,r.model?String(r.model):void 0);d.push(K)}let f={...r},x=r.stepHooks,A=d&&d.length>0,h=r.functionCallMode??this.options?.functionCallMode??"auto";A&&h==="prompt"&&(this.signatureToolCallingManager=new pn(d)),A&&h==="auto"&&!e.getFeatures(r.model).functions&&(this.signatureToolCallingManager=new pn(d));let y,C,I=this.options?.promptTemplate??Yt;this.signatureToolCallingManager&&(this.signature=this.signatureToolCallingManager.processSignature(this.signature),this.setSignature(this.signature));let R=this.signature.hasComplexFields(),M=e.getFeatures?.(r.model),T=r.structuredOutputMode??this.options?.structuredOutputMode??"auto";if(this.structuredOutputFunctionFallback=R&&(T==="function"||T==="auto"&&!M?.structuredOutputs),this.structuredOutputFunctionFallback){let K={name:dn,description:"Return the final result. Call this function with the complete output data.",parameters:Jt(this.signature.getOutputFields()),func:async()=>"done"};d.push(K),u=[...u??[],dn.toLowerCase()]}let O=e.getFeatures?.(r.model)?.caching?.cacheBreakpoints===!1,E={functions:this.signatureToolCallingManager?[]:d,thoughtFieldName:this.thoughtFieldName,contextCache:r.contextCache,examplesInSystem:r.examplesInSystem,ignoreBreakpoints:O,structuredOutputFunctionName:this.structuredOutputFunctionFallback?dn:void 0};this.promptTemplate=new I(this.signature,E);let $,N=performance.now();Array.isArray(t)?(Mi(t),$=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos})):$=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos});let S=performance.now()-N,v=this.getMetricsInstruments(),P=this.getMergedCustomLabels(e,r);v&&ms(v,"prompt_render",S,this.getSignatureName(),P);let F=performance.now();p.addRequest($,r.sessionId);let U=performance.now()-F;v&&ms(v,"memory_update",U,this.getSignatureName(),P);let L=new Map;n.forEach(K=>{L.set(K.index,{})});let z=()=>{let K=m._consumePendingOptions();if(K){let{modelConfig:G,...J}=K;f={...f,...J},G&&(f.modelConfig={...f.modelConfig,...G})}let W=m._consumeFunctionsToAdd();if(W){let G=cn(W);for(let J of G)d.some(Y=>Y.name===J.name)||d.push(J)}let pe=m._consumeFunctionsToRemove();if(pe){let G=new Set(pe.map(J=>J.toLowerCase()));for(let J=d.length-1;J>=0;J--)G.has(d[J].name.toLowerCase())&&d.splice(J,1)}},j=r?.abortSignal??he.abortSignal;e:for(let K=0;K<l;K++){if(m._beginStep(K),z(),g&&g.model!==!1){let pe=d.findIndex(G=>G.name==="adjustGeneration");if(pe!==-1){let G=f.model?String(f.model):void 0;d[pe]=va(e,g,G)}}if(m._isStopRequested)break;if(j?.aborted)throw new Fe("between-steps",j.reason??"Aborted between steps");if(x?.beforeStep&&(await x.beforeStep(m),z(),m._isStopRequested))break;let W=c;for(let pe=0;pe<=W;pe++)try{let G=c+1;for(let Y=0;Y<G;Y++){n.forEach(H=>{H.content="",H.values={},H.functionCalls=[],H.functionsExecuted=new Set,H.xstate={extractedFields:[],streamedIndex:{},s:-1}}),Y>0&&L.forEach((H,q)=>{L.set(q,{})});let le=new Map;n.forEach(H=>{le.set(H.index,{})});try{let H=this.forwardCore({options:{...f,functions:d},ai:e,mem:p,stepIndex:K,span:s,traceContext:i,states:n,stopFunctionNames:u,stepContext:m}),q=!1;try{for await(let ue of H)if(ue!==void 0){let Te=ue.index,ae=ue.delta,de=le.get(Te)??{},X=L.get(Te)??{},te={},Ae=!1;for(let Se of Object.keys(ae)){let Be=ae[Se],Le=de[Se],at;typeof Be=="string"&&(typeof Le=="string"||Le===void 0)?at=(Le??"")+Be:Array.isArray(Be)&&(Array.isArray(Le)||Le===void 0)?at=[...Le??[],...Be]:at=Be,de[Se]=at;let Ee=at,ze=X[Se];if(typeof Ee=="string"&&typeof ze=="string")if(Ee.startsWith(ze)){let me=Ee.slice(ze.length);me&&(te[Se]=me,Ae=!0,X[Se]=Ee)}else ze.startsWith(Ee)||Ee!==ze&&(te[Se]=Ee,Ae=!0,X[Se]=Ee);else if(Array.isArray(Ee)&&Array.isArray(ze)){if(Ee.length>ze.length){let me=Ee.slice(ze.length);te[Se]=me,Ae=!0,X[Se]=Ee}}else JSON.stringify(Ee)!==JSON.stringify(ze)&&(te[Se]=Ee,Ae=!0,X[Se]=Ee)}Ae&&(yield{version:Y,index:ue.index,delta:te})}}catch(ue){if(ue instanceof un){if(q=!0,this.structuredOutputFunctionFallback){let Te=ue.calls.find(ae=>ae.func.name===dn);if(Te?.args){let ae=Te.args;Qn(this.signature,ae);let de=this.signature.getOutputFields();for(let X of n){let te={};for(let Ae of de)Ae.name in ae&&!Ae.isInternal&&(te[Ae.name]=ae[Ae.name],X.values[Ae.name]=ae[Ae.name]);yield{version:Y,index:X.index,delta:te}}for(let X of n)await Vn(this.asserts,X.values);if(this.fieldProcessors.length>0)for(let X of n)await Wr(this.fieldProcessors,X.values,p,r.sessionId)}}}else throw ue}if(this.usage.length>0){let ue=this.usage[this.usage.length-1];ue?.tokens&&m._addUsage(ue.tokens.promptTokens??0,ue.tokens.completionTokens??0,ue.tokens.totalTokens??0)}n.some(ue=>ue.functionsExecuted.size>0)&&x?.afterFunctionExecution&&(await x.afterFunctionExecution(m),z());let Ce=q||m._isStopRequested?!1:$l(p,u,n,f?.sessionId);if(x?.afterStep&&(await x.afterStep(m),z()),Ce&&!m._isStopRequested&&!j?.aborted){let ue=this.getMetricsInstruments();ue&&ds(ue,K+1,l,this.getSignatureName(),P);continue e}if(j?.aborted)throw new Fe("mid-step",j.reason??"Aborted");r?.disableMemoryCleanup||(p.removeByTag("invalid-assistant",r.sessionId),p.removeByTag("correction",r.sessionId),p.removeByTag("error",r.sessionId));let we=this.getMetricsInstruments();if(we){ds(we,K+1,l,this.getSignatureName(),P);let ue=new Set;n.forEach(Te=>{Te.functionsExecuted.forEach(ae=>ue.add(ae))}),ue.size>0&&tl(we,!0,ue.size,!0,!1,this.getSignatureName(),P),nl(we,this.fieldProcessors.length,this.streamingFieldProcessors.length,this.getSignatureName(),P)}return}catch(H){if(H instanceof Fe)throw H;C=H;let q,re=this.isDebug(e,r),Ce=this.getLogger(e,r),we=this.getMetricsInstruments(),ue=this.getSignatureName(),Te={error:H,errCount:Y,logger:Ce,metricsInstruments:we,signatureName:ue,span:s,debug:re,customLabels:P};if(s?.recordException(H),H instanceof Qe)q=dl(Te),y=H;else if(H instanceof Pt)q=ml(Te),y=H;else if(H instanceof $e)gl(Te);else{if(H instanceof ht)throw H;{let ae=H,de=ae instanceof rt&&ae.status>=500&&ae.status<600,X=ae instanceof Je,te=ae instanceof gt;throw de||X||te?H:La(H,e,this.signature)}}if(q&&(p.addTag("error",r.sessionId),p.addRequest([{role:"user",content:this.promptTemplate.renderExtraFields(q)}],r.sessionId),p.addTag("correction",r.sessionId),this.signature.hasComplexFields()))for(let de of n)de.content="",de.values={},de.xstate={extractedFields:[],streamedIndex:{},s:-1}}}let J=this.getMetricsInstruments();throw J&&ia(J,c,!1,c,this.getSignatureName(),P),La(new Error(`Unable to fix validation error: ${(y??C)?.message??(y??C)?.toString()??"unknown error"}
777
777
 
778
778
  LLM Output:
779
- ${n.map(Q=>Q.content).join(`
779
+ ${n.map(Y=>Y.content).join(`
780
780
  ---
781
- `)}`),e,this.signature)}catch(B){let V=B,Q=V instanceof rt&&V.status>=500&&V.status<600,ie=V instanceof Je,W=V instanceof gt,q=V instanceof ht;if((Q||ie||W||q)&&le<re){let Ce=this.isDebug(e,r),Re=this.getLogger(e,r),ce=Math.min(6e4,1e3*Math.pow(2,le));Ce&&Re&&Re({name:"Notification",id:"infrastructure-retry",value:`Infrastructure error (attempt ${le+1}/${re+1}): ${V.message}. Retrying in ${ce}ms...`}),s?.addEvent("infrastructure.retry",{attempt:le+1,maxRetries:re,delay:ce,errorType:V instanceof rt?"status_error":V instanceof Je?"network_error":V instanceof gt?"timeout_error":"stream_terminated",errorMessage:V.message}),await new Promise((me,be)=>{let ue=!1,xe,ve=()=>{G&&xe&&G.removeEventListener("abort",xe)},$e=setTimeout(()=>{ue||(ue=!0,ve(),me())},ce);if(G){if(xe=()=>{ue||(ue=!0,clearTimeout($e),ve(),be(new Fe("infrastructure-retry-backoff",G.reason?String(G.reason):"Aborted during retry backoff")))},G.aborted){xe();return}G.addEventListener("abort",xe,{once:!0})}});continue}throw B}}throw v&&ds(v,l,l,this.getSignatureName(),F),Na(new Error(`Max steps reached: ${l}`),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 s=n.type;if(s&&(s.name==="url"&&Vt(r,n),s.name,s.name,(s.name==="string"||s.name==="code")&&yt(r,n),s.name==="number"&&bt(r,n),s.name==="object"&&s.fields&&typeof r=="object"&&r!==null&&this.validateObjectFields(r,s.fields,n.name),s.isArray&&Array.isArray(r)))for(let i=0;i<r.length;i++){let a=r[i];s.name==="string"||s.name==="code"?yt(a,n):s.name==="number"?bt(a,n):s.fields&&typeof a=="object"&&a!==null&&this.validateObjectFields(a,s.fields,`${n.name}[${i}]`)}}}validateObjectFields(e,t,n){for(let[r,s]of Object.entries(t)){let i=e[r];if(s.isOptional&&i===void 0)continue;let a={name:`${n}.${r}`,type:{name:s.type,isArray:s.isArray,options:s.options?[...s.options]:void 0,fields:s.fields,minLength:s.minLength,maxLength:s.maxLength,minimum:s.minimum,maximum:s.maximum,pattern:s.pattern,format:s.format},description:s.description,isOptional:s.isOptional};if(s.type==="string"||s.type==="code"?yt(i,a):s.type==="number"?bt(i,a):s.type==="object"&&s.fields&&typeof i=="object"&&i!==null&&this.validateObjectFields(i,s.fields,a.name),s.isArray&&Array.isArray(i))for(let u=0;u<i.length;u++){let c=i[u];s.type==="string"||s.type==="code"?yt(c,a):s.type==="number"?bt(c,a):s.fields&&typeof c=="object"&&c!==null&&this.validateObjectFields(c,s.fields,`${a.name}[${u}]`)}}}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 s=kt(r.signal,n?.abortSignal??fe.abortSignal),i=s?{...n,abortSignal:s}:n;try{let a=performance.now(),u=this.createStates(n.sampleCount??1),c=performance.now()-a,l=this.getMetricsInstruments(),p=this.getMergedCustomLabels(e,n);l&&ms(l,"state_creation",c,this.getSignatureName(),p);let d=n?.tracer??this.options?.tracer??e.getOptions().tracer,m=this.functions;if(n?.functions&&(m=un(n.functions,this.functions)),!d){yield*this._forward2(e,t,u,{...i,functions:m});return}let g=m?.map(C=>C.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}:{}},x=this.traceLabel&&n.traceLabel?`${this.traceLabel} > ${n.traceLabel}`:n.traceLabel??this.traceLabel,A=x?`AxGen > ${x}`:"AxGen",h=d.startSpan(A,{kind:ct.SERVER,attributes:f}),y=qt.active(),T=Ir.setSpan(y,h);try{if(this.excludeContentFromTrace||h.addEvent("input",{content:JSON.stringify(t,null,2)}),yield*this._forward2(e,t,u,{...i,functions:m},h,T),!this.excludeContentFromTrace){let C=u.map(M=>M.values),R=C.length===1?C[0]:C;h.addEvent("output",{content:JSON.stringify(R,null,2)})}}finally{h.end()}}finally{this.activeAbortControllers.delete(r),this._stopRequested=!1}}async forward(e,t,n){let r=n?.cachingFunction??this.options?.cachingFunction??fe.cachingFunction,s=(()=>{if(!r)return;let d=this.signature.getInputFields().map(m=>m.name);return this.computeCacheKey(t,d)})();if(r&&s){let d=await r(s);if(d!==void 0)return d}let i=performance.now(),a=this.getSignatureName(),u=n?.stream??!1,c=!1,l=0,p=!1;try{let d=this.getMetricsInstruments(),m=this.getMergedCustomLabels(e,n);d&&rl(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=[],x=0,A=0;for await(let I of g)I.version!==x&&(f=[]),x=I.version,f=xa(f,I),A++;l=x;let h=performance.now();p=!!n?.resultPicker;let y=await vs(f,{resultPicker:n?.resultPicker},n?.mem,n?.sessionId),T=performance.now()-h,R=f[y]?.delta??{},M=Array.isArray(t)?{}:t??{};if(this.trace={...M,...R},p&&this.isDebug(e,n)){let I=this.getLogger(e,n);Zu(f.length,y,T,I)}if(c=!0,d&&(nl(d,f.length,p,p?T:void 0,a,m),tl(d,u,A,void 0,a,m)),r&&s)try{await r(s,R)}catch{}return R}catch(d){throw c=!1,d}finally{let d=performance.now()-i,m=this.getMetricsInstruments(),g=this.getMergedCustomLabels(e,n);m&&(Yc(m,d,c,a,e.getName(),n?.model?String(n.model):void 0,g),l>0&&sa(m,l,c,n?.maxRetries??this.options?.maxRetries??3,a,g))}}async*streamingForward(e,t,n){let r=n?.cachingFunction??this.options?.cachingFunction??fe.cachingFunction,s=(()=>{if(!r)return;let p=this.signature.getInputFields().map(d=>d.name);return this.computeCacheKey(t,p)})();if(r&&s){let p;try{p=await r(s)}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=[],u=0;for await(let p of i)p.version!==u&&(a=[]),u=p.version,a=xa(a,p);let c=await vs(a,{resultPicker:n?.resultPicker},n?.mem,n?.sessionId),l=a[c];if(l){if(r&&s)try{await r(s,l.delta)}catch{}yield{version:u,index:c,delta:l.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=mt("sha256");n.update(this.signature.hash()??"");let r=s=>{let i=typeof s;if(n.update(`|${i}|`),s==null){n.update("null");return}if(i==="string"||i==="number"||i==="boolean"){n.update(String(s));return}if(Array.isArray(s)){n.update("[");for(let a of s)r(a);n.update("]");return}if(typeof s=="object"&&s!==null&&"mimeType"in s&&"data"in s){let a=s;n.update(a.mimeType??"");let u=mt("sha256").update(a.data??"").digest("hex");n.update(u);return}if(typeof s=="object"){let a=s,u=Object.keys(a).sort();for(let c of u)n.update(`{${c}}`),r(a[c]);return}n.update(String(s))};if(Array.isArray(e))for(let s of e){n.update(`role:${s.role}`);let i=t.map(a=>s.values?.[a]);for(let a of i)r(a)}else{let s=t.map(i=>e?.[i]);for(let i of s)r(i)}return n.digest("hex")}},Zr=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 Na(o,e,t){let n=o instanceof Error?o:new Error(String(o));if(n instanceof Fe)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(),u={model:i,maxTokens:a?.maxTokens,streaming:a?.stream??!1,signature:{input:t.getInputFields(),output:t.getOutputFields(),description:t.getDescription()}};return new Zr(`Generate failed: ${n.message}`,u,{cause:n})}var ng=o=>o.replace(/^\W+|\W+$/g,""),rg=(o,e)=>{let t=o.search(e);if(t===-1)return[o];let n=o.match(e);if(!n)throw new Error("Match failed unexpectedly.");let r=o.substring(0,t),s=o.substring(t+n[0].length);return[r,s]},og=o=>{let e=new Set,t=[];for(let n of o)e.has(n)||(e.add(n),t.push(n));return t},sg=o=>{let e=o.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}},ig=o=>{let e=o.match(/^(\d+)[.,\s]+(.*)$/);return e&&e[2]!==void 0?e[2].trim():o},ag=(o,e)=>{let t=[];for(let n=0;n<o.length;n+=e)t.push(o.slice(n,n+e));return t},ks={trimNonAlphaNum:ng,splitIntoTwo:rg,dedup:og,extractIdAndText:sg,extractIndexPrefixedText:ig,batchArray:ag};var Os=class extends Me{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."
782
- 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),s=r.map(a=>{let{id:u}=ks.extractIdAndText(a);return u});return{rankedItems:t.items.map((a,u)=>{let c=s[u];return c!==void 0?t.items[c]:void 0}).filter(a=>a!==void 0)}}};var Es=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 s=await(this.fetch??fetch)(this.tikaUrl,r);if(!s.ok)throw new Error(`Failed to upload file: ${s.statusText}`);return await s.text()}catch(r){throw new Error(`Error converting file: ${r}`)}}async convert(e,t){let n=[],r=t?.batchSize??10;for(let s=0;s<e.length;s+=r){let a=e.slice(s,s+r).map(c=>this._convert(c,{format:t?.format})),u=await Promise.all(a);n.push(...u)}return n}};var DI=new st,Ms=class{name;context;constructor(e,t){this.name=e,this.context=t}getName(){return this.name}getContext(){return this.context}},Ps=class{ai;db;debug;constructor(e){this.db=new Wt,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}),s=(await this.db.query({table:"classes",values:n[0]})).matches;if(typeof t?.cutoff=="number"){let{cutoff:a}=t;s=s.filter(u=>u.score<=a)}let i=s.at(0);return i?i.id:""}setOptions(e){typeof e.debug=="boolean"&&(this.debug=e.debug)}};var Yl=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 Xl(o,e){return o.filter(t=>!e.has(t))}function Zl(o){let e={};for(let t of o)e[t]=(e[t]||0)+1;return e}function pn(o){let e=o.normalize("NFD");return e=e.replace(/\b(a|an|the)\b/g," "),e=e.split(/\s+/).join(" "),e=e.replace(/[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]/g,""),e.toLowerCase()}function ug(o,e){return pn(o)===pn(e)?1:0}function cg(o,e){let t=pn(o).split(" "),n=pn(e).split(" "),r=Zl(t),s=Zl(n),i=0;for(let c in r){let l=r[c]??0,p=s[c]??0;i+=Math.min(l,p)}if(i===0)return 0;let a=i/t.length,u=i/n.length;return 2*a*u/(a+u)}function lg(o,e,t,n=!1){let r=pn(o).split(" "),s=pn(e).split(" "),i=pn(t).split(" "),a=new Set([...Yl,...r]);s=Xl(s,a),i=Xl(i,a);let u=0,c=u/s.length,l=u/i.length,p=2*c*l/(c+l);return n?l:p}var ep={emScore:ug,f1Score:cg,novelF1ScoreOptimized:lg};var Fs=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 u=await this.program.forward(this.ai,a,{maxRetries:1}),c=await e({prediction:u,example:a});r+=c}catch(u){console.warn(`Program evaluation failed for example ${i}: ${u instanceof Error?u.message:"Unknown error"}`)}}let s=n>0?r/n:0;this.ai.getOptions().debug&&console.log(`
781
+ `)}`),e,this.signature)}catch(G){let J=G,Y=J instanceof rt&&J.status>=500&&J.status<600,le=J instanceof Je,H=J instanceof gt,q=J instanceof ht;if((Y||le||H||q)&&pe<W){let Ce=this.isDebug(e,r),we=this.getLogger(e,r),ae=Math.min(6e4,1e3*Math.pow(2,pe));Ce&&we&&we({name:"Notification",id:"infrastructure-retry",value:`Infrastructure error (attempt ${pe+1}/${W+1}): ${J.message}. Retrying in ${ae}ms...`}),s?.addEvent("infrastructure.retry",{attempt:pe+1,maxRetries:W,delay:ae,errorType:J instanceof rt?"status_error":J instanceof Je?"network_error":J instanceof gt?"timeout_error":"stream_terminated",errorMessage:J.message}),await new Promise((de,X)=>{let te=!1,Ae,Se=()=>{j&&Ae&&j.removeEventListener("abort",Ae)},Le=setTimeout(()=>{te||(te=!0,Se(),de())},ae);if(j){if(Ae=()=>{te||(te=!0,clearTimeout(Le),Se(),X(new Fe("infrastructure-retry-backoff",j.reason?String(j.reason):"Aborted during retry backoff")))},j.aborted){Ae();return}j.addEventListener("abort",Ae,{once:!0})}});continue}throw G}}throw v&&ds(v,l,l,this.getSignatureName(),P),La(new Error(`Max steps reached: ${l}`),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 s=n.type;if(s&&(s.name==="url"&&Wt(r,n),s.name,s.name,(s.name==="string"||s.name==="code")&&yt(r,n),s.name==="number"&&bt(r,n),s.name==="object"&&s.fields&&typeof r=="object"&&r!==null&&this.validateObjectFields(r,s.fields,n.name),s.isArray&&Array.isArray(r)))for(let i=0;i<r.length;i++){let a=r[i];s.name==="string"||s.name==="code"?yt(a,n):s.name==="number"?bt(a,n):s.fields&&typeof a=="object"&&a!==null&&this.validateObjectFields(a,s.fields,`${n.name}[${i}]`)}}}validateObjectFields(e,t,n){for(let[r,s]of Object.entries(t)){let i=e[r];if(s.isOptional&&i===void 0)continue;let a={name:`${n}.${r}`,type:{name:s.type,isArray:s.isArray,options:s.options?[...s.options]:void 0,fields:s.fields,minLength:s.minLength,maxLength:s.maxLength,minimum:s.minimum,maximum:s.maximum,pattern:s.pattern,format:s.format},description:s.description,isOptional:s.isOptional};if(s.type==="string"||s.type==="code"?yt(i,a):s.type==="number"?bt(i,a):s.type==="object"&&s.fields&&typeof i=="object"&&i!==null&&this.validateObjectFields(i,s.fields,a.name),s.isArray&&Array.isArray(i))for(let u=0;u<i.length;u++){let c=i[u];s.type==="string"||s.type==="code"?yt(c,a):s.type==="number"?bt(c,a):s.fields&&typeof c=="object"&&c!==null&&this.validateObjectFields(c,s.fields,`${a.name}[${u}]`)}}}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 s=kt(r.signal,n?.abortSignal??he.abortSignal),i=s?{...n,abortSignal:s}:n;try{let a=performance.now(),u=this.createStates(n.sampleCount??1),c=performance.now()-a,l=this.getMetricsInstruments(),p=this.getMergedCustomLabels(e,n);l&&ms(l,"state_creation",c,this.getSignatureName(),p);let d=n?.tracer??this.options?.tracer??e.getOptions().tracer,m=this.functions;if(n?.functions&&(m=cn(n.functions,this.functions)),!d){yield*this._forward2(e,t,u,{...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}:{}},x=this.traceLabel&&n.traceLabel?`${this.traceLabel} > ${n.traceLabel}`:n.traceLabel??this.traceLabel,A=x?`AxGen > ${x}`:"AxGen",h=d.startSpan(A,{kind:ct.SERVER,attributes:f}),y=qt.active(),C=wr.setSpan(y,h);try{if(this.excludeContentFromTrace||h.addEvent("input",{content:JSON.stringify(t,null,2)}),yield*this._forward2(e,t,u,{...i,functions:m},h,C),!this.excludeContentFromTrace){let I=u.map(M=>M.values),R=I.length===1?I[0]:I;h.addEvent("output",{content:JSON.stringify(R,null,2)})}}finally{h.end()}}finally{this.activeAbortControllers.delete(r),this._stopRequested=!1}}async forward(e,t,n){let r=n?.cachingFunction??this.options?.cachingFunction??he.cachingFunction,s=(()=>{if(!r)return;let d=this.signature.getInputFields().map(m=>m.name);return this.computeCacheKey(t,d)})();if(r&&s){let d=await r(s);if(d!==void 0)return d}let i=performance.now(),a=this.getSignatureName(),u=n?.stream??!1,c=!1,l=0,p=!1;try{let d=this.getMetricsInstruments(),m=this.getMergedCustomLabels(e,n);d&&sl(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=[],x=0,A=0;for await(let T of g)T.version!==x&&(f=[]),x=T.version,f=Aa(f,T),A++;l=x;let h=performance.now();p=!!n?.resultPicker;let y=await vs(f,{resultPicker:n?.resultPicker},n?.mem,n?.sessionId),C=performance.now()-h,R=f[y]?.delta??{},M=Array.isArray(t)?{}:t??{};if(this.trace={...M,...R},p&&this.isDebug(e,n)){let T=this.getLogger(e,n);nc(f.length,y,C,T)}if(c=!0,d&&(ol(d,f.length,p,p?C:void 0,a,m),rl(d,u,A,void 0,a,m)),r&&s)try{await r(s,R)}catch{}return R}catch(d){throw c=!1,d}finally{let d=performance.now()-i,m=this.getMetricsInstruments(),g=this.getMergedCustomLabels(e,n);m&&(Zc(m,d,c,a,e.getName(),n?.model?String(n.model):void 0,g),l>0&&ia(m,l,c,n?.maxRetries??this.options?.maxRetries??3,a,g))}}async*streamingForward(e,t,n){let r=n?.cachingFunction??this.options?.cachingFunction??he.cachingFunction,s=(()=>{if(!r)return;let p=this.signature.getInputFields().map(d=>d.name);return this.computeCacheKey(t,p)})();if(r&&s){let p;try{p=await r(s)}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=[],u=0;for await(let p of i)p.version!==u&&(a=[]),u=p.version,a=Aa(a,p);let c=await vs(a,{resultPicker:n?.resultPicker},n?.mem,n?.sessionId),l=a[c];if(l){if(r&&s)try{await r(s,l.delta)}catch{}yield{version:u,index:c,delta:l.delta}}}setExamples(e,t){super.setExamples(e,t)}isDebug(e,t){return t?.debug??this.options?.debug??he.debug??e.getOptions().debug??!1}getLogger(e,t){return t?.logger??this.options?.logger??he.logger??e.getLogger()}computeCacheKey(e,t){let n=mt("sha256");n.update(this.signature.hash()??"");let r=s=>{let i=typeof s;if(n.update(`|${i}|`),s==null){n.update("null");return}if(i==="string"||i==="number"||i==="boolean"){n.update(String(s));return}if(Array.isArray(s)){n.update("[");for(let a of s)r(a);n.update("]");return}if(typeof s=="object"&&s!==null&&"mimeType"in s&&"data"in s){let a=s;n.update(a.mimeType??"");let u=mt("sha256").update(a.data??"").digest("hex");n.update(u);return}if(typeof s=="object"){let a=s,u=Object.keys(a).sort();for(let c of u)n.update(`{${c}}`),r(a[c]);return}n.update(String(s))};if(Array.isArray(e))for(let s of e){n.update(`role:${s.role}`);let i=t.map(a=>s.values?.[a]);for(let a of i)r(a)}else{let s=t.map(i=>e?.[i]);for(let i of s)r(i)}return n.digest("hex")}},Zr=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 La(o,e,t){let n=o instanceof Error?o:new Error(String(o));if(n instanceof Fe)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(),u={model:i,maxTokens:a?.maxTokens,streaming:a?.stream??!1,signature:{input:t.getInputFields(),output:t.getOutputFields(),description:t.getDescription()}};return new Zr(`Generate failed: ${n.message}`,u,{cause:n})}var sg=o=>o.replace(/^\W+|\W+$/g,""),ig=(o,e)=>{let t=o.search(e);if(t===-1)return[o];let n=o.match(e);if(!n)throw new Error("Match failed unexpectedly.");let r=o.substring(0,t),s=o.substring(t+n[0].length);return[r,s]},ag=o=>{let e=new Set,t=[];for(let n of o)e.has(n)||(e.add(n),t.push(n));return t},ug=o=>{let e=o.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}},cg=o=>{let e=o.match(/^(\d+)[.,\s]+(.*)$/);return e&&e[2]!==void 0?e[2].trim():o},lg=(o,e)=>{let t=[];for(let n=0;n<o.length;n+=e)t.push(o.slice(n,n+e));return t},ks={trimNonAlphaNum:sg,splitIntoTwo:ig,dedup:ag,extractIdAndText:ug,extractIndexPrefixedText:cg,batchArray:lg};var Os=class extends Me{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."
782
+ 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),s=r.map(a=>{let{id:u}=ks.extractIdAndText(a);return u});return{rankedItems:t.items.map((a,u)=>{let c=s[u];return c!==void 0?t.items[c]:void 0}).filter(a=>a!==void 0)}}};var Es=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 s=await(this.fetch??fetch)(this.tikaUrl,r);if(!s.ok)throw new Error(`Failed to upload file: ${s.statusText}`);return await s.text()}catch(r){throw new Error(`Error converting file: ${r}`)}}async convert(e,t){let n=[],r=t?.batchSize??10;for(let s=0;s<e.length;s+=r){let a=e.slice(s,s+r).map(c=>this._convert(c,{format:t?.format})),u=await Promise.all(a);n.push(...u)}return n}};var NT=new st,Ms=class{name;context;constructor(e,t){this.name=e,this.context=t}getName(){return this.name}getContext(){return this.context}},Ps=class{ai;db;debug;constructor(e){this.db=new Kt,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}),s=(await this.db.query({table:"classes",values:n[0]})).matches;if(typeof t?.cutoff=="number"){let{cutoff:a}=t;s=s.filter(u=>u.score<=a)}let i=s.at(0);return i?i.id:""}setOptions(e){typeof e.debug=="boolean"&&(this.debug=e.debug)}};var Xl=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 Zl(o,e){return o.filter(t=>!e.has(t))}function ep(o){let e={};for(let t of o)e[t]=(e[t]||0)+1;return e}function mn(o){let e=o.normalize("NFD");return e=e.replace(/\b(a|an|the)\b/g," "),e=e.split(/\s+/).join(" "),e=e.replace(/[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]/g,""),e.toLowerCase()}function pg(o,e){return mn(o)===mn(e)?1:0}function dg(o,e){let t=mn(o).split(" "),n=mn(e).split(" "),r=ep(t),s=ep(n),i=0;for(let c in r){let l=r[c]??0,p=s[c]??0;i+=Math.min(l,p)}if(i===0)return 0;let a=i/t.length,u=i/n.length;return 2*a*u/(a+u)}function mg(o,e,t,n=!1){let r=mn(o).split(" "),s=mn(e).split(" "),i=mn(t).split(" "),a=new Set([...Xl,...r]);s=Zl(s,a),i=Zl(i,a);let u=0,c=u/s.length,l=u/i.length,p=2*c*l/(c+l);return n?l:p}var tp={emScore:pg,f1Score:dg,novelF1ScoreOptimized:mg};var Fs=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 u=await this.program.forward(this.ai,a,{maxRetries:1}),c=await e({prediction:u,example:a});r+=c}catch(u){console.warn(`Program evaluation failed for example ${i}: ${u instanceof Error?u.message:"Unknown error"}`)}}let s=n>0?r/n:0;this.ai.getOptions().debug&&console.log(`
783
783
  Performance: `,r,"/",n,"Average Score: ",s,`
784
- `)}};function tp(){let o=Date.now().toString(36),e=Math.random().toString(36).substring(2,8);return`trace-${o}-${e}`}var tr=class o{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=tp(),s=new Date,i,a;try{let u=this.gen.streamingForward(e,t,n);for await(let c of u)c.partial?i=c.partial:c.delta,yield c}catch(u){throw a=u instanceof Error?u.message:String(u),u}finally{let u=new Date,c=u.getTime()-s.getTime(),l={type:"trace",id:r,name:this.options.name,input:this.options.logInputs?t:{},output:this.options.logOutputs&&i?i:{},startTime:s,endTime:u,durationMs:c,model:n?.model??void 0,metadata:this.options.metadata,error:a};this.saveTrace(l)}}async forward(e,t,n){let r=tp(),s=new Date,i,a;try{return i=await this.gen.forward(e,t,n),i}catch(u){throw a=u instanceof Error?u.message:String(u),u}finally{let u=new Date,c=u.getTime()-s.getTime(),l={type:"trace",id:r,name:this.options.name,input:this.options.logInputs?t:{},output:this.options.logOutputs&&i?i:{},startTime:s,endTime:u,durationMs:c,model:n?.model??void 0,metadata:this.options.metadata,error:a};this.saveTrace(l)}}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 o(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})}};function np(o){return Ne.create(o)}function it(o,e){let t=typeof o=="string"?Ne.create(o):o;return new Me(t,e)}var rp=o=>{console.log(o)},La=(o=rp)=>{let e=new st,t=e.gray("\u2500".repeat(50)),n=e.gray("\u2501".repeat(50));return r=>{let s="";switch(r.name){case"OptimizationStart":s=`
784
+ `)}};function np(){let o=Date.now().toString(36),e=Math.random().toString(36).substring(2,8);return`trace-${o}-${e}`}var nr=class o{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=np(),s=new Date,i,a;try{let u=this.gen.streamingForward(e,t,n);for await(let c of u)c.partial?i=c.partial:c.delta,yield c}catch(u){throw a=u instanceof Error?u.message:String(u),u}finally{let u=new Date,c=u.getTime()-s.getTime(),l={type:"trace",id:r,name:this.options.name,input:this.options.logInputs?t:{},output:this.options.logOutputs&&i?i:{},startTime:s,endTime:u,durationMs:c,model:n?.model??void 0,metadata:this.options.metadata,error:a};this.saveTrace(l)}}async forward(e,t,n){let r=np(),s=new Date,i,a;try{return i=await this.gen.forward(e,t,n),i}catch(u){throw a=u instanceof Error?u.message:String(u),u}finally{let u=new Date,c=u.getTime()-s.getTime(),l={type:"trace",id:r,name:this.options.name,input:this.options.logInputs?t:{},output:this.options.logOutputs&&i?i:{},startTime:s,endTime:u,durationMs:c,model:n?.model??void 0,metadata:this.options.metadata,error:a};this.saveTrace(l)}}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 o(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})}};function rp(o){return _e.create(o)}function it(o,e){let t=typeof o=="string"?_e.create(o):o;return new Me(t,e)}var op=o=>{console.log(o)},Da=(o=op)=>{let e=new st,t=e.gray("\u2500".repeat(50)),n=e.gray("\u2501".repeat(50));return r=>{let s="";switch(r.name){case"OptimizationStart":s=`
785
785
  ${e.blueBright("\u25CF ")}${e.whiteBright("Optimization Started")}
786
786
  ${t}
787
787
  ${e.white("Optimizer:")} ${e.cyan(r.value.optimizerType)}
@@ -824,7 +824,7 @@ ${t}
824
824
  ${e.white("Config:")} ${e.cyan(JSON.stringify(r.value.config).slice(0,80))}${JSON.stringify(r.value.config).length>80?"...":""}
825
825
  `;break;default:s=`${e.red("\u25CF ")}${e.whiteBright("Unknown Event")}
826
826
  ${e.white(JSON.stringify(r).slice(0,100))}${JSON.stringify(r).length>100?"...":""}
827
- `}o(s)}},op=(o=rp)=>{let e="\u2500".repeat(60);return t=>{let n="";switch(t.name){case"OptimizationStart":n=`[ OPTIMIZATION START: ${t.value.optimizerType} ]
827
+ `}o(s)}},sp=(o=op)=>{let e="\u2500".repeat(60);return t=>{let n="";switch(t.name){case"OptimizationStart":n=`[ OPTIMIZATION START: ${t.value.optimizerType} ]
828
828
  ${e}
829
829
  Config: ${JSON.stringify(t.value.config,null,2)}
830
830
  Examples: ${t.value.exampleCount}, Validation: ${t.value.validationCount}
@@ -850,7 +850,7 @@ Score: ${t.value.score.toFixed(3)}
850
850
  Config: ${JSON.stringify(t.value.config)}
851
851
  ${e}`;break;default:n=`[ UNKNOWN OPTIMIZER EVENT ]
852
852
  ${JSON.stringify(t)}
853
- ${e}`}o(n)}},eo=La();var $a={enabled:!0,enabledCategories:["optimization","convergence","resource_usage","teacher_student","checkpointing","pareto"],maxLabelLength:100,samplingRate:1},_s,pg=o=>{if(_s)return _s;if(o)return _s=dg(o),_s};var Ns=$a,sp=o=>{Ns={...Ns,...o}},ip=()=>({...Ns}),dg=o=>({optimizationLatencyHistogram:o.createHistogram("ax_optimizer_optimization_duration_ms",{description:"End-to-end duration of optimization runs",unit:"ms"}),optimizationRequestsCounter:o.createCounter("ax_optimizer_optimization_requests_total",{description:"Total number of optimization requests"}),optimizationErrorsCounter:o.createCounter("ax_optimizer_optimization_errors_total",{description:"Total number of failed optimizations"}),convergenceRoundsHistogram:o.createHistogram("ax_optimizer_convergence_rounds",{description:"Number of rounds until convergence"}),convergenceScoreGauge:o.createGauge("ax_optimizer_convergence_score",{description:"Current best score during optimization"}),convergenceImprovementGauge:o.createGauge("ax_optimizer_convergence_improvement",{description:"Improvement in score from baseline"}),stagnationRoundsGauge:o.createGauge("ax_optimizer_stagnation_rounds",{description:"Number of rounds without improvement"}),earlyStoppingCounter:o.createCounter("ax_optimizer_early_stopping_total",{description:"Total number of early stopping events"}),tokenUsageCounter:o.createCounter("ax_optimizer_token_usage_total",{description:"Total tokens used during optimization"}),costUsageCounter:o.createCounter("ax_optimizer_cost_usage_total",{description:"Total cost incurred during optimization",unit:"$"}),memoryUsageGauge:o.createGauge("ax_optimizer_memory_usage_bytes",{description:"Peak memory usage during optimization",unit:"By"}),optimizationDurationHistogram:o.createHistogram("ax_optimizer_duration_ms",{description:"Duration of optimization runs",unit:"ms"}),teacherStudentUsageCounter:o.createCounter("ax_optimizer_teacher_student_usage_total",{description:"Total number of teacher-student interactions"}),teacherStudentLatencyHistogram:o.createHistogram("ax_optimizer_teacher_student_latency_ms",{description:"Latency of teacher-student interactions",unit:"ms"}),teacherStudentScoreImprovementGauge:o.createGauge("ax_optimizer_teacher_student_score_improvement",{description:"Score improvement from teacher-student interactions"}),checkpointSaveCounter:o.createCounter("ax_optimizer_checkpoint_save_total",{description:"Total number of checkpoint saves"}),checkpointLoadCounter:o.createCounter("ax_optimizer_checkpoint_load_total",{description:"Total number of checkpoint loads"}),checkpointSaveLatencyHistogram:o.createHistogram("ax_optimizer_checkpoint_save_latency_ms",{description:"Latency of checkpoint save operations",unit:"ms"}),checkpointLoadLatencyHistogram:o.createHistogram("ax_optimizer_checkpoint_load_latency_ms",{description:"Latency of checkpoint load operations",unit:"ms"}),paretoOptimizationsCounter:o.createCounter("ax_optimizer_pareto_optimizations_total",{description:"Total number of Pareto optimizations"}),paretoFrontSizeHistogram:o.createHistogram("ax_optimizer_pareto_front_size",{description:"Size of Pareto frontier"}),paretoHypervolumeGauge:o.createGauge("ax_optimizer_pareto_hypervolume",{description:"Hypervolume of Pareto frontier"}),paretoSolutionsGeneratedHistogram:o.createHistogram("ax_optimizer_pareto_solutions_generated",{description:"Number of solutions generated for Pareto optimization"}),programInputFieldsGauge:o.createGauge("ax_optimizer_program_input_fields",{description:"Number of input fields in optimized program"}),programOutputFieldsGauge:o.createGauge("ax_optimizer_program_output_fields",{description:"Number of output fields in optimized program"}),examplesCountGauge:o.createGauge("ax_optimizer_examples_count",{description:"Number of training examples used"}),validationSetSizeGauge:o.createGauge("ax_optimizer_validation_set_size",{description:"Size of validation set used"}),evaluationLatencyHistogram:o.createHistogram("ax_optimizer_evaluation_latency_ms",{description:"Latency of program evaluations",unit:"ms"}),demoGenerationLatencyHistogram:o.createHistogram("ax_optimizer_demo_generation_latency_ms",{description:"Latency of demo generation",unit:"ms"}),metricComputationLatencyHistogram:o.createHistogram("ax_optimizer_metric_computation_latency_ms",{description:"Latency of metric computation",unit:"ms"}),optimizerTypeGauge:o.createGauge("ax_optimizer_type",{description:"Type of optimizer being used"}),targetScoreGauge:o.createGauge("ax_optimizer_target_score",{description:"Target score for optimization"}),maxRoundsGauge:o.createGauge("ax_optimizer_max_rounds",{description:"Maximum rounds for optimization"})}),Et=o=>{let e={};for(let[t,n]of Object.entries(o))if(n!=null){let r=String(n),s=Ns.maxLabelLength;e[t]=r.length>s?r.substring(0,s):r}return e},mg=(o,e,t,n,r,s)=>{try{let i=Et({success:t.toString(),optimizer_type:n,...r?{program_signature:r}:{},...s});o.optimizationLatencyHistogram&&o.optimizationLatencyHistogram.record(e,i),o.optimizationRequestsCounter&&o.optimizationRequestsCounter.add(1,i),!t&&o.optimizationErrorsCounter&&o.optimizationErrorsCounter.add(1,i)}catch(i){console.warn("Failed to record optimization metric:",i)}},gg=(o,e,t,n,r,s,i)=>{try{let a=Et({optimizer_type:s,...i});o.convergenceRoundsHistogram&&o.convergenceRoundsHistogram.record(e,a),o.convergenceScoreGauge&&o.convergenceScoreGauge.record(t,a),o.convergenceImprovementGauge&&o.convergenceImprovementGauge.record(n,a),o.stagnationRoundsGauge&&o.stagnationRoundsGauge.record(r,a)}catch(a){console.warn("Failed to record convergence metric:",a)}},fg=(o,e,t,n)=>{try{let r=Et({reason:e,optimizer_type:t,...n});o.earlyStoppingCounter&&o.earlyStoppingCounter.add(1,r)}catch(r){console.warn("Failed to record early stopping metric:",r)}},hg=(o,e,t,n,r,s)=>{try{let i=Et({optimizer_type:n,...s});o.tokenUsageCounter&&o.tokenUsageCounter.add(e,i),o.costUsageCounter&&o.costUsageCounter.add(t,i),r!==void 0&&o.memoryUsageGauge&&o.memoryUsageGauge.record(r,i)}catch(i){console.warn("Failed to record resource usage metric:",i)}},xg=(o,e,t,n)=>{try{let r=Et({optimizer_type:t,...n});o.optimizationDurationHistogram&&o.optimizationDurationHistogram.record(e,r)}catch(r){console.warn("Failed to record optimization duration metric:",r)}},Ag=(o,e,t,n,r)=>{try{let s=Et({optimizer_type:n,...r});o.teacherStudentUsageCounter&&o.teacherStudentUsageCounter.add(1,s),o.teacherStudentLatencyHistogram&&o.teacherStudentLatencyHistogram.record(e,s),o.teacherStudentScoreImprovementGauge&&o.teacherStudentScoreImprovementGauge.record(t,s)}catch(s){console.warn("Failed to record teacher-student metric:",s)}},yg=(o,e,t,n,r,s)=>{try{let i=Et({operation:e,success:n.toString(),optimizer_type:r,...s});e==="save"?(o.checkpointSaveCounter&&o.checkpointSaveCounter.add(1,i),o.checkpointSaveLatencyHistogram&&o.checkpointSaveLatencyHistogram.record(t,i)):(o.checkpointLoadCounter&&o.checkpointLoadCounter.add(1,i),o.checkpointLoadLatencyHistogram&&o.checkpointLoadLatencyHistogram.record(t,i))}catch(i){console.warn("Failed to record checkpoint metric:",i)}},bg=(o,e,t,n,r,s)=>{try{let i=Et({optimizer_type:n,...s});o.paretoOptimizationsCounter&&o.paretoOptimizationsCounter.add(1,i),o.paretoFrontSizeHistogram&&o.paretoFrontSizeHistogram.record(e,i),r!==void 0&&o.paretoHypervolumeGauge&&o.paretoHypervolumeGauge.record(r,i),o.paretoSolutionsGeneratedHistogram&&o.paretoSolutionsGeneratedHistogram.record(t,i)}catch(i){console.warn("Failed to record Pareto metric:",i)}},Tg=(o,e,t,n,r,s,i)=>{try{let a=Et({optimizer_type:s,...i});o.programInputFieldsGauge&&o.programInputFieldsGauge.record(e,a),o.programOutputFieldsGauge&&o.programOutputFieldsGauge.record(t,a),o.examplesCountGauge&&o.examplesCountGauge.record(n,a),o.validationSetSizeGauge&&o.validationSetSizeGauge.record(r,a)}catch(a){console.warn("Failed to record program complexity metric:",a)}},Cg=(o,e,t,n,r)=>{try{let s=Et({metric_type:e,optimizer_type:n,...r});switch(e){case"evaluation":o.evaluationLatencyHistogram&&o.evaluationLatencyHistogram.record(t,s);break;case"demo_generation":o.demoGenerationLatencyHistogram&&o.demoGenerationLatencyHistogram.record(t,s);break;case"metric_computation":o.metricComputationLatencyHistogram&&o.metricComputationLatencyHistogram.record(t,s);break}}catch(s){console.warn("Failed to record optimizer performance metric:",s)}},Ig=(o,e,t,n,r)=>{try{let s=Et({optimizer_type:e,...r});o.optimizerTypeGauge&&o.optimizerTypeGauge.record(1,s),t!==void 0&&o.targetScoreGauge&&o.targetScoreGauge.record(t,s),n!==void 0&&o.maxRoundsGauge&&o.maxRoundsGauge.record(n,s)}catch(s){console.warn("Failed to record optimizer configuration metric:",s)}},Ct=class{bestScore;stats;instruction;instructionMap;demos;examples;modelConfig;optimizerType;optimizationTime;totalRounds;converged;scoreHistory;configurationHistory;artifactFormatVersion;instructionSchema;constructor(e){this.bestScore=e.bestScore,this.stats=e.stats,this.instruction=e.instruction,this.instructionMap=e.instructionMap,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,this.artifactFormatVersion=e.artifactFormatVersion,this.instructionSchema=e.instructionSchema}applyTo(e){e.applyOptimization?.(this)}},to=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}},It=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 to({maxTokens:1e6});this.costTracker=e.costTracker??t,this.metricsInstruments=pg(fe.meter),this.stats=this.initializeStats(),this.debugOptimizer=e.debugOptimizer??!1,this.optimizerLogger=e.optimizerLogger??(this.verbose?eo:void 0),this.initializeResultExplainer()}getMergedCustomLabels(e){return nn(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 s=Date.now(),i=this.constructor.name,a=e.getSignature().toString();this.recordOptimizationStart(i,a,r);let u,c=(g,f,x,A,h,y,T,C={},R)=>{this.getOptimizerLogger(R)?.({name:"RoundProgress",value:{round:g,totalRounds:R?.maxIterations??0,currentScore:f,bestScore:y,configuration:x}}),this.updateOptimizationProgress(g,f,x,A,h,y,T,C,R)},l=(g,f)=>{u=g,this.triggerEarlyStopping(g,this.currentRound,r)},p=g=>{this.onProgress?.(g),c(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:l}),m=Date.now()-s;return this.recordOptimizationComplete(m,!0,i,a,r),u&&this.getLogger(r)?.({name:"Notification",id:"optimization_early_stop",value:`Optimization stopped early due to ${u}`}),{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 s=this.constructor.name,i=Date.now(),a=await this.generateWeightedSolutions(e,t,n,r),u=await this.generateConstraintSolutions(e,t,n,r),c=[...a,...u],l=this.findParetoFrontier(c),p=this.calculateHypervolume(l);this.updateResourceUsage(i),this.stats.convergenceInfo.converged=!0,this.recordParetoMetrics(l.length,c.length,"base_optimizer",p,r);let d=l.length>0?Math.max(...l.map(m=>Math.max(...Object.values(m.scores)))):0;return{demos:l.length>0?[...l[0].demos]:void 0,stats:this.stats,bestScore:d,paretoFront:l,hypervolume:p,paretoFrontSize:l.length,finalConfiguration:{paretoFrontSize:l.length,hypervolume:p,strategy:"weighted_combinations_and_constraints",numSolutions:c.length}}}async generateWeightedSolutions(e,t,n,r){let s=[];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),u=await n({prediction:a,example:i}),c=Object.keys(u),l=this.generateWeightCombinations(c);for(let p=0;p<l.length;p++){let d=l[p],m=async({prediction:g,example:f})=>{let x=await n({prediction:g,example:f}),A=0;for(let[h,y]of Object.entries(x))A+=y*(d[h]||0);return A};try{let g=await this.compile(e,t,m,{...r,verbose:!1}),f=await this.evaluateWithMultiObjective(e,g,n,t);s.push({scores:f,demos:g.demos,configuration:{...g.finalConfiguration,weights:d,strategy:"weighted_combination"}})}catch{}}return s}async generateConstraintSolutions(e,t,n,r){let s=[];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),u=await n({prediction:a,example:i}),c=Object.keys(u);for(let l of c){let p=async({prediction:d,example:m})=>{let g=await n({prediction:d,example:m}),f=g[l]||0,x=0;for(let[A,h]of Object.entries(g))A!==l&&h<.3&&(x+=(.3-h)*2);return f-x};try{let d=await this.compile(e,t,p,{...r,verbose:!1}),m=await this.evaluateWithMultiObjective(e,d,n,t);s.push({scores:m,demos:d.demos,configuration:{...d.finalConfiguration,primaryObjective:l,strategy:"constraint_based"}})}catch{}}return s}generateWeightCombinations(e){let t=[];for(let r of e){let s={};for(let i of e)s[i]=i===r?1:0;t.push(s)}let n={};for(let r of e)n[r]=1/e.length;if(t.push(n),e.length===2){let[r,s]=e;for(let i=.1;i<=.9;i+=.2){let a=1-i;t.push({[r]:i,[s]:a})}}if(e.length===3){let[r,s,i]=e;t.push({[r]:.5,[s]:.3,[i]:.2},{[r]:.3,[s]:.5,[i]:.2},{[r]:.2,[s]:.3,[i]:.5})}return t}async evaluateWithMultiObjective(e,t,n,r){let s=new Me(e.getSignature());t.demos&&s.setDemos(t.demos);let i=[],a=Math.max(1,Math.min(5,Math.floor(r.length*.2))),u=r.slice(-a),c={},l=u;for(let d of l)try{let m=await s.forward(this.studentAI,d),g=await n({prediction:m,example:d});for(let[f,x]of Object.entries(g))c[f]||(c[f]=[]),c[f].push(x)}catch{}let p={};for(let[d,m]of Object.entries(c))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],s=!1,i=0;for(let a=0;a<e.length;a++){if(n===a)continue;let u=e[a];if(this.dominates(u.scores,r.scores)){s=!0;break}this.dominates(r.scores,u.scores)&&i++}s||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,s=!1;for(let i of n){let a=e[i]||0,u=t[i]||0;if(a<u){r=!1;break}a>u&&(s=!0)}return r&&s}calculateHypervolume(e){if(e.length===0)return;let t=e[0],n=Object.keys(t.scores);if(n.length===2){let[r,s]=n,i=0,a=[...e].sort((c,l)=>(l.scores[r]||0)-(c.scores[r]||0)),u=0;for(let c of a){let l=c.scores[r]||0,p=c.scores[s]||0;i+=l*(p-u),u=Math.max(u,p)}return i}}async saveCheckpoint(e,t,n,r,s={},i){let a=i?.overrideCheckpointSave||this.checkpointSave;if(!a)return;let u=Date.now(),c=!1,l;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:s,examples:[]};l=await a(p),c=!0}catch(p){throw c=!1,p}finally{let p=Date.now()-u;this.recordCheckpointMetrics("save",p,c,e,i)}return l}async loadCheckpoint(e,t){let n=t?.overrideCheckpointLoad||this.checkpointLoad;if(!n)return null;let r=Date.now(),s=!1,i=null;try{i=await n(e),s=i!==null}catch(a){throw s=!1,a}finally{let a=Date.now()-r;this.recordCheckpointMetrics("load",a,s,"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,s,i,a,u={},c){this.currentRound=e,this.scoreHistory.push(t),this.configurationHistory.push(n),this.shouldSaveCheckpoint(e,c)&&await this.saveCheckpoint(r,s,i,a,u,c),this.getOptimizerLogger(c)?.({name:"RoundProgress",value:{round:e,totalRounds:c?.maxIterations??0,currentScore:t,bestScore:i,configuration:n}})}async saveFinalCheckpoint(e,t,n,r,s={},i){i?.saveCheckpointOnComplete!==!1&&await this.saveCheckpoint(e,t,n,r,{...s,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 s=(t.match(/input:/g)||[]).length,i=(t.match(/output:/g)||[]).length;Tg(this.metricsInstruments,s,i,0,0,e,r)}Ig(this.metricsInstruments,e,this.targetScore,void 0,r)}recordOptimizationComplete(e,t,n,r,s){if(!this.metricsInstruments)return;let i=this.getMergedCustomLabels(s);mg(this.metricsInstruments,e,t,n,r,i),xg(this.metricsInstruments,e,n,i);let a=this.costTracker?.getCurrentCost()??0,u=this.costTracker?.getTotalTokens()??0;hg(this.metricsInstruments,u,a,n,void 0,i)}recordConvergenceMetrics(e,t,n,r,s,i){if(!this.metricsInstruments)return;let a=this.getMergedCustomLabels(i);gg(this.metricsInstruments,e,t,n,r,s,a)}recordEarlyStoppingMetrics(e,t,n){if(!this.metricsInstruments)return;let r=this.getMergedCustomLabels(n);fg(this.metricsInstruments,e,t,r)}recordTeacherStudentMetrics(e,t,n,r){if(!this.metricsInstruments)return;let s=this.getMergedCustomLabels(r);Ag(this.metricsInstruments,e,t,n,s)}recordCheckpointMetrics(e,t,n,r,s){if(!this.metricsInstruments)return;let i=this.getMergedCustomLabels(s);yg(this.metricsInstruments,e,t,n,r,i)}recordParetoMetrics(e,t,n,r,s){if(!this.metricsInstruments)return;let i=this.getMergedCustomLabels(s);bg(this.metricsInstruments,e,t,n,r,i)}recordPerformanceMetrics(e,t,n,r){if(!this.metricsInstruments)return;let s=this.getMergedCustomLabels(r);Cg(this.metricsInstruments,e,t,n,s)}isOptimizerLoggingEnabled(e){return this.debugOptimizer||(e?.verbose??this.verbose??!1)}getOptimizerLogger(e){if(this.isOptimizerLoggingEnabled(e))return this.optimizerLogger??fe.optimizerLogger??eo}getStats(){return{...this.stats}}async explainOptimizationResults(e,t,n){let r=this.stats.convergenceInfo.converged,s=this.stats.totalCalls,i=s>0?this.stats.successfulDemos/s*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)}%.`,u=[];if(r||u.push("Increase numTrials or relax earlyStoppingTrials to allow further improvement."),typeof this.targetScore=="number"&&e<this.targetScore&&u.push("Tighten the metric or supply more/better-labeled examples to reach targetScore."),t&&"bootstrappedDemos"in t){let l=t.bootstrappedDemos;typeof l=="number"&&l===0&&u.push("Consider allowing a small number of bootstrapped demos to boost performance.")}u.length===0&&u.push("Re-run with more trials or different acquisition settings to explore more of the space.");let c=`Tokens used: ${this.stats.resourceUsage.totalTokens}, rounds: ${this.currentRound}, stagnationRounds: ${this.stats.convergenceInfo.stagnationRounds}.`;return{humanExplanation:a,recommendations:u,performanceAssessment:c}}async logOptimizationComplete(e,t,n,r,s){let i=this.getOptimizerLogger(r);i&&i(s?{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:s.humanExplanation,recommendations:s.recommendations,performanceAssessment:s.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=[]}};var ap=xr(Od("crypto"),1);function Ls(o){let e=new Date().toISOString();return{version:1,sections:{},stats:{bulletCount:0,helpfulCount:0,harmfulCount:0,tokenEstimate:0},updatedAt:e,description:o}}function Mt(o){return JSON.parse(JSON.stringify(o))}function wg(o){return Math.ceil(o.length/4)}function Da(o,e,t){let n=[],r=[],{maxSectionSize:s=Number.POSITIVE_INFINITY,allowDynamicSections:i=!0,enableAutoPrune:a=!1,protectedBulletIds:u}=t??{},c=new Date().toISOString(),l=u??new Set;for(let p of e){if(!p.section)continue;if(!o.sections[p.section]){if(!i)continue;o.sections[p.section]=[]}let d=o.sections[p.section];switch(p.type){case"ADD":{if(d.length>=s){if(!a)continue;let f=vg(d,l);if(!f)continue;n.push(f.id),r.push({type:"REMOVE",section:p.section,bulletId:f.id,metadata:{...f.metadata??{},autoPruned:!0,removedAt:c}})}let m=p.bulletId??Rg(p.section),g={id:m,section:p.section,content:p.content??"",helpfulCount:0,harmfulCount:0,createdAt:c,updatedAt:c,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=c,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(o),o.updatedAt=c,{updatedBulletIds:n,autoRemoved:r}}function Ua(o,e,t){for(let n of Object.values(o.sections)){let r=n.find(s=>s.id===e);if(r){t==="helpful"?r.helpfulCount+=1:t==="harmful"&&(r.harmfulCount+=1),r.updatedAt=new Date().toISOString(),Ba(o);return}}}function dn(o){let e=o.description?`## Context Playbook
853
+ ${e}`}o(n)}},eo=Da();var Ua={enabled:!0,enabledCategories:["optimization","convergence","resource_usage","teacher_student","checkpointing","pareto"],maxLabelLength:100,samplingRate:1},_s,gg=o=>{if(_s)return _s;if(o)return _s=fg(o),_s};var Ns=Ua,ip=o=>{Ns={...Ns,...o}},ap=()=>({...Ns}),fg=o=>({optimizationLatencyHistogram:o.createHistogram("ax_optimizer_optimization_duration_ms",{description:"End-to-end duration of optimization runs",unit:"ms"}),optimizationRequestsCounter:o.createCounter("ax_optimizer_optimization_requests_total",{description:"Total number of optimization requests"}),optimizationErrorsCounter:o.createCounter("ax_optimizer_optimization_errors_total",{description:"Total number of failed optimizations"}),convergenceRoundsHistogram:o.createHistogram("ax_optimizer_convergence_rounds",{description:"Number of rounds until convergence"}),convergenceScoreGauge:o.createGauge("ax_optimizer_convergence_score",{description:"Current best score during optimization"}),convergenceImprovementGauge:o.createGauge("ax_optimizer_convergence_improvement",{description:"Improvement in score from baseline"}),stagnationRoundsGauge:o.createGauge("ax_optimizer_stagnation_rounds",{description:"Number of rounds without improvement"}),earlyStoppingCounter:o.createCounter("ax_optimizer_early_stopping_total",{description:"Total number of early stopping events"}),tokenUsageCounter:o.createCounter("ax_optimizer_token_usage_total",{description:"Total tokens used during optimization"}),costUsageCounter:o.createCounter("ax_optimizer_cost_usage_total",{description:"Total cost incurred during optimization",unit:"$"}),memoryUsageGauge:o.createGauge("ax_optimizer_memory_usage_bytes",{description:"Peak memory usage during optimization",unit:"By"}),optimizationDurationHistogram:o.createHistogram("ax_optimizer_duration_ms",{description:"Duration of optimization runs",unit:"ms"}),teacherStudentUsageCounter:o.createCounter("ax_optimizer_teacher_student_usage_total",{description:"Total number of teacher-student interactions"}),teacherStudentLatencyHistogram:o.createHistogram("ax_optimizer_teacher_student_latency_ms",{description:"Latency of teacher-student interactions",unit:"ms"}),teacherStudentScoreImprovementGauge:o.createGauge("ax_optimizer_teacher_student_score_improvement",{description:"Score improvement from teacher-student interactions"}),checkpointSaveCounter:o.createCounter("ax_optimizer_checkpoint_save_total",{description:"Total number of checkpoint saves"}),checkpointLoadCounter:o.createCounter("ax_optimizer_checkpoint_load_total",{description:"Total number of checkpoint loads"}),checkpointSaveLatencyHistogram:o.createHistogram("ax_optimizer_checkpoint_save_latency_ms",{description:"Latency of checkpoint save operations",unit:"ms"}),checkpointLoadLatencyHistogram:o.createHistogram("ax_optimizer_checkpoint_load_latency_ms",{description:"Latency of checkpoint load operations",unit:"ms"}),paretoOptimizationsCounter:o.createCounter("ax_optimizer_pareto_optimizations_total",{description:"Total number of Pareto optimizations"}),paretoFrontSizeHistogram:o.createHistogram("ax_optimizer_pareto_front_size",{description:"Size of Pareto frontier"}),paretoHypervolumeGauge:o.createGauge("ax_optimizer_pareto_hypervolume",{description:"Hypervolume of Pareto frontier"}),paretoSolutionsGeneratedHistogram:o.createHistogram("ax_optimizer_pareto_solutions_generated",{description:"Number of solutions generated for Pareto optimization"}),programInputFieldsGauge:o.createGauge("ax_optimizer_program_input_fields",{description:"Number of input fields in optimized program"}),programOutputFieldsGauge:o.createGauge("ax_optimizer_program_output_fields",{description:"Number of output fields in optimized program"}),examplesCountGauge:o.createGauge("ax_optimizer_examples_count",{description:"Number of training examples used"}),validationSetSizeGauge:o.createGauge("ax_optimizer_validation_set_size",{description:"Size of validation set used"}),evaluationLatencyHistogram:o.createHistogram("ax_optimizer_evaluation_latency_ms",{description:"Latency of program evaluations",unit:"ms"}),demoGenerationLatencyHistogram:o.createHistogram("ax_optimizer_demo_generation_latency_ms",{description:"Latency of demo generation",unit:"ms"}),metricComputationLatencyHistogram:o.createHistogram("ax_optimizer_metric_computation_latency_ms",{description:"Latency of metric computation",unit:"ms"}),optimizerTypeGauge:o.createGauge("ax_optimizer_type",{description:"Type of optimizer being used"}),targetScoreGauge:o.createGauge("ax_optimizer_target_score",{description:"Target score for optimization"}),maxRoundsGauge:o.createGauge("ax_optimizer_max_rounds",{description:"Maximum rounds for optimization"})}),Et=o=>{let e={};for(let[t,n]of Object.entries(o))if(n!=null){let r=String(n),s=Ns.maxLabelLength;e[t]=r.length>s?r.substring(0,s):r}return e},hg=(o,e,t,n,r,s)=>{try{let i=Et({success:t.toString(),optimizer_type:n,...r?{program_signature:r}:{},...s});o.optimizationLatencyHistogram&&o.optimizationLatencyHistogram.record(e,i),o.optimizationRequestsCounter&&o.optimizationRequestsCounter.add(1,i),!t&&o.optimizationErrorsCounter&&o.optimizationErrorsCounter.add(1,i)}catch(i){console.warn("Failed to record optimization metric:",i)}},xg=(o,e,t,n,r,s,i)=>{try{let a=Et({optimizer_type:s,...i});o.convergenceRoundsHistogram&&o.convergenceRoundsHistogram.record(e,a),o.convergenceScoreGauge&&o.convergenceScoreGauge.record(t,a),o.convergenceImprovementGauge&&o.convergenceImprovementGauge.record(n,a),o.stagnationRoundsGauge&&o.stagnationRoundsGauge.record(r,a)}catch(a){console.warn("Failed to record convergence metric:",a)}},Ag=(o,e,t,n)=>{try{let r=Et({reason:e,optimizer_type:t,...n});o.earlyStoppingCounter&&o.earlyStoppingCounter.add(1,r)}catch(r){console.warn("Failed to record early stopping metric:",r)}},yg=(o,e,t,n,r,s)=>{try{let i=Et({optimizer_type:n,...s});o.tokenUsageCounter&&o.tokenUsageCounter.add(e,i),o.costUsageCounter&&o.costUsageCounter.add(t,i),r!==void 0&&o.memoryUsageGauge&&o.memoryUsageGauge.record(r,i)}catch(i){console.warn("Failed to record resource usage metric:",i)}},bg=(o,e,t,n)=>{try{let r=Et({optimizer_type:t,...n});o.optimizationDurationHistogram&&o.optimizationDurationHistogram.record(e,r)}catch(r){console.warn("Failed to record optimization duration metric:",r)}},Cg=(o,e,t,n,r)=>{try{let s=Et({optimizer_type:n,...r});o.teacherStudentUsageCounter&&o.teacherStudentUsageCounter.add(1,s),o.teacherStudentLatencyHistogram&&o.teacherStudentLatencyHistogram.record(e,s),o.teacherStudentScoreImprovementGauge&&o.teacherStudentScoreImprovementGauge.record(t,s)}catch(s){console.warn("Failed to record teacher-student metric:",s)}},Ig=(o,e,t,n,r,s)=>{try{let i=Et({operation:e,success:n.toString(),optimizer_type:r,...s});e==="save"?(o.checkpointSaveCounter&&o.checkpointSaveCounter.add(1,i),o.checkpointSaveLatencyHistogram&&o.checkpointSaveLatencyHistogram.record(t,i)):(o.checkpointLoadCounter&&o.checkpointLoadCounter.add(1,i),o.checkpointLoadLatencyHistogram&&o.checkpointLoadLatencyHistogram.record(t,i))}catch(i){console.warn("Failed to record checkpoint metric:",i)}},Tg=(o,e,t,n,r,s)=>{try{let i=Et({optimizer_type:n,...s});o.paretoOptimizationsCounter&&o.paretoOptimizationsCounter.add(1,i),o.paretoFrontSizeHistogram&&o.paretoFrontSizeHistogram.record(e,i),r!==void 0&&o.paretoHypervolumeGauge&&o.paretoHypervolumeGauge.record(r,i),o.paretoSolutionsGeneratedHistogram&&o.paretoSolutionsGeneratedHistogram.record(t,i)}catch(i){console.warn("Failed to record Pareto metric:",i)}},wg=(o,e,t,n,r,s,i)=>{try{let a=Et({optimizer_type:s,...i});o.programInputFieldsGauge&&o.programInputFieldsGauge.record(e,a),o.programOutputFieldsGauge&&o.programOutputFieldsGauge.record(t,a),o.examplesCountGauge&&o.examplesCountGauge.record(n,a),o.validationSetSizeGauge&&o.validationSetSizeGauge.record(r,a)}catch(a){console.warn("Failed to record program complexity metric:",a)}},Rg=(o,e,t,n,r)=>{try{let s=Et({metric_type:e,optimizer_type:n,...r});switch(e){case"evaluation":o.evaluationLatencyHistogram&&o.evaluationLatencyHistogram.record(t,s);break;case"demo_generation":o.demoGenerationLatencyHistogram&&o.demoGenerationLatencyHistogram.record(t,s);break;case"metric_computation":o.metricComputationLatencyHistogram&&o.metricComputationLatencyHistogram.record(t,s);break}}catch(s){console.warn("Failed to record optimizer performance metric:",s)}},vg=(o,e,t,n,r)=>{try{let s=Et({optimizer_type:e,...r});o.optimizerTypeGauge&&o.optimizerTypeGauge.record(1,s),t!==void 0&&o.targetScoreGauge&&o.targetScoreGauge.record(t,s),n!==void 0&&o.maxRoundsGauge&&o.maxRoundsGauge.record(n,s)}catch(s){console.warn("Failed to record optimizer configuration metric:",s)}},It=class{bestScore;stats;instruction;instructionMap;demos;examples;modelConfig;optimizerType;optimizationTime;totalRounds;converged;scoreHistory;configurationHistory;artifactFormatVersion;instructionSchema;constructor(e){this.bestScore=e.bestScore,this.stats=e.stats,this.instruction=e.instruction,this.instructionMap=e.instructionMap,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,this.artifactFormatVersion=e.artifactFormatVersion,this.instructionSchema=e.instructionSchema}applyTo(e){e.applyOptimization?.(this)}},to=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}},Tt=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 to({maxTokens:1e6});this.costTracker=e.costTracker??t,this.metricsInstruments=gg(he.meter),this.stats=this.initializeStats(),this.debugOptimizer=e.debugOptimizer??!1,this.optimizerLogger=e.optimizerLogger??(this.verbose?eo:void 0),this.initializeResultExplainer()}getMergedCustomLabels(e){return rn(he.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 s=Date.now(),i=this.constructor.name,a=e.getSignature().toString();this.recordOptimizationStart(i,a,r);let u,c=(g,f,x,A,h,y,C,I={},R)=>{this.getOptimizerLogger(R)?.({name:"RoundProgress",value:{round:g,totalRounds:R?.maxIterations??0,currentScore:f,bestScore:y,configuration:x}}),this.updateOptimizationProgress(g,f,x,A,h,y,C,I,R)},l=(g,f)=>{u=g,this.triggerEarlyStopping(g,this.currentRound,r)},p=g=>{this.onProgress?.(g),c(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:l}),m=Date.now()-s;return this.recordOptimizationComplete(m,!0,i,a,r),u&&this.getLogger(r)?.({name:"Notification",id:"optimization_early_stop",value:`Optimization stopped early due to ${u}`}),{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 s=this.constructor.name,i=Date.now(),a=await this.generateWeightedSolutions(e,t,n,r),u=await this.generateConstraintSolutions(e,t,n,r),c=[...a,...u],l=this.findParetoFrontier(c),p=this.calculateHypervolume(l);this.updateResourceUsage(i),this.stats.convergenceInfo.converged=!0,this.recordParetoMetrics(l.length,c.length,"base_optimizer",p,r);let d=l.length>0?Math.max(...l.map(m=>Math.max(...Object.values(m.scores)))):0;return{demos:l.length>0?[...l[0].demos]:void 0,stats:this.stats,bestScore:d,paretoFront:l,hypervolume:p,paretoFrontSize:l.length,finalConfiguration:{paretoFrontSize:l.length,hypervolume:p,strategy:"weighted_combinations_and_constraints",numSolutions:c.length}}}async generateWeightedSolutions(e,t,n,r){let s=[];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),u=await n({prediction:a,example:i}),c=Object.keys(u),l=this.generateWeightCombinations(c);for(let p=0;p<l.length;p++){let d=l[p],m=async({prediction:g,example:f})=>{let x=await n({prediction:g,example:f}),A=0;for(let[h,y]of Object.entries(x))A+=y*(d[h]||0);return A};try{let g=await this.compile(e,t,m,{...r,verbose:!1}),f=await this.evaluateWithMultiObjective(e,g,n,t);s.push({scores:f,demos:g.demos,configuration:{...g.finalConfiguration,weights:d,strategy:"weighted_combination"}})}catch{}}return s}async generateConstraintSolutions(e,t,n,r){let s=[];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),u=await n({prediction:a,example:i}),c=Object.keys(u);for(let l of c){let p=async({prediction:d,example:m})=>{let g=await n({prediction:d,example:m}),f=g[l]||0,x=0;for(let[A,h]of Object.entries(g))A!==l&&h<.3&&(x+=(.3-h)*2);return f-x};try{let d=await this.compile(e,t,p,{...r,verbose:!1}),m=await this.evaluateWithMultiObjective(e,d,n,t);s.push({scores:m,demos:d.demos,configuration:{...d.finalConfiguration,primaryObjective:l,strategy:"constraint_based"}})}catch{}}return s}generateWeightCombinations(e){let t=[];for(let r of e){let s={};for(let i of e)s[i]=i===r?1:0;t.push(s)}let n={};for(let r of e)n[r]=1/e.length;if(t.push(n),e.length===2){let[r,s]=e;for(let i=.1;i<=.9;i+=.2){let a=1-i;t.push({[r]:i,[s]:a})}}if(e.length===3){let[r,s,i]=e;t.push({[r]:.5,[s]:.3,[i]:.2},{[r]:.3,[s]:.5,[i]:.2},{[r]:.2,[s]:.3,[i]:.5})}return t}async evaluateWithMultiObjective(e,t,n,r){let s=new Me(e.getSignature());t.demos&&s.setDemos(t.demos);let i=[],a=Math.max(1,Math.min(5,Math.floor(r.length*.2))),u=r.slice(-a),c={},l=u;for(let d of l)try{let m=await s.forward(this.studentAI,d),g=await n({prediction:m,example:d});for(let[f,x]of Object.entries(g))c[f]||(c[f]=[]),c[f].push(x)}catch{}let p={};for(let[d,m]of Object.entries(c))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],s=!1,i=0;for(let a=0;a<e.length;a++){if(n===a)continue;let u=e[a];if(this.dominates(u.scores,r.scores)){s=!0;break}this.dominates(r.scores,u.scores)&&i++}s||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,s=!1;for(let i of n){let a=e[i]||0,u=t[i]||0;if(a<u){r=!1;break}a>u&&(s=!0)}return r&&s}calculateHypervolume(e){if(e.length===0)return;let t=e[0],n=Object.keys(t.scores);if(n.length===2){let[r,s]=n,i=0,a=[...e].sort((c,l)=>(l.scores[r]||0)-(c.scores[r]||0)),u=0;for(let c of a){let l=c.scores[r]||0,p=c.scores[s]||0;i+=l*(p-u),u=Math.max(u,p)}return i}}async saveCheckpoint(e,t,n,r,s={},i){let a=i?.overrideCheckpointSave||this.checkpointSave;if(!a)return;let u=Date.now(),c=!1,l;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:s,examples:[]};l=await a(p),c=!0}catch(p){throw c=!1,p}finally{let p=Date.now()-u;this.recordCheckpointMetrics("save",p,c,e,i)}return l}async loadCheckpoint(e,t){let n=t?.overrideCheckpointLoad||this.checkpointLoad;if(!n)return null;let r=Date.now(),s=!1,i=null;try{i=await n(e),s=i!==null}catch(a){throw s=!1,a}finally{let a=Date.now()-r;this.recordCheckpointMetrics("load",a,s,"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,s,i,a,u={},c){this.currentRound=e,this.scoreHistory.push(t),this.configurationHistory.push(n),this.shouldSaveCheckpoint(e,c)&&await this.saveCheckpoint(r,s,i,a,u,c),this.getOptimizerLogger(c)?.({name:"RoundProgress",value:{round:e,totalRounds:c?.maxIterations??0,currentScore:t,bestScore:i,configuration:n}})}async saveFinalCheckpoint(e,t,n,r,s={},i){i?.saveCheckpointOnComplete!==!1&&await this.saveCheckpoint(e,t,n,r,{...s,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 s=(t.match(/input:/g)||[]).length,i=(t.match(/output:/g)||[]).length;wg(this.metricsInstruments,s,i,0,0,e,r)}vg(this.metricsInstruments,e,this.targetScore,void 0,r)}recordOptimizationComplete(e,t,n,r,s){if(!this.metricsInstruments)return;let i=this.getMergedCustomLabels(s);hg(this.metricsInstruments,e,t,n,r,i),bg(this.metricsInstruments,e,n,i);let a=this.costTracker?.getCurrentCost()??0,u=this.costTracker?.getTotalTokens()??0;yg(this.metricsInstruments,u,a,n,void 0,i)}recordConvergenceMetrics(e,t,n,r,s,i){if(!this.metricsInstruments)return;let a=this.getMergedCustomLabels(i);xg(this.metricsInstruments,e,t,n,r,s,a)}recordEarlyStoppingMetrics(e,t,n){if(!this.metricsInstruments)return;let r=this.getMergedCustomLabels(n);Ag(this.metricsInstruments,e,t,r)}recordTeacherStudentMetrics(e,t,n,r){if(!this.metricsInstruments)return;let s=this.getMergedCustomLabels(r);Cg(this.metricsInstruments,e,t,n,s)}recordCheckpointMetrics(e,t,n,r,s){if(!this.metricsInstruments)return;let i=this.getMergedCustomLabels(s);Ig(this.metricsInstruments,e,t,n,r,i)}recordParetoMetrics(e,t,n,r,s){if(!this.metricsInstruments)return;let i=this.getMergedCustomLabels(s);Tg(this.metricsInstruments,e,t,n,r,i)}recordPerformanceMetrics(e,t,n,r){if(!this.metricsInstruments)return;let s=this.getMergedCustomLabels(r);Rg(this.metricsInstruments,e,t,n,s)}isOptimizerLoggingEnabled(e){return this.debugOptimizer||(e?.verbose??this.verbose??!1)}getOptimizerLogger(e){if(this.isOptimizerLoggingEnabled(e))return this.optimizerLogger??he.optimizerLogger??eo}getStats(){return{...this.stats}}async explainOptimizationResults(e,t,n){let r=this.stats.convergenceInfo.converged,s=this.stats.totalCalls,i=s>0?this.stats.successfulDemos/s*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)}%.`,u=[];if(r||u.push("Increase numTrials or relax earlyStoppingTrials to allow further improvement."),typeof this.targetScore=="number"&&e<this.targetScore&&u.push("Tighten the metric or supply more/better-labeled examples to reach targetScore."),t&&"bootstrappedDemos"in t){let l=t.bootstrappedDemos;typeof l=="number"&&l===0&&u.push("Consider allowing a small number of bootstrapped demos to boost performance.")}u.length===0&&u.push("Re-run with more trials or different acquisition settings to explore more of the space.");let c=`Tokens used: ${this.stats.resourceUsage.totalTokens}, rounds: ${this.currentRound}, stagnationRounds: ${this.stats.convergenceInfo.stagnationRounds}.`;return{humanExplanation:a,recommendations:u,performanceAssessment:c}}async logOptimizationComplete(e,t,n,r,s){let i=this.getOptimizerLogger(r);i&&i(s?{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:s.humanExplanation,recommendations:s.recommendations,performanceAssessment:s.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=[]}};var up=Ar(Pd("crypto"),1);function $s(o){let e=new Date().toISOString();return{version:1,sections:{},stats:{bulletCount:0,helpfulCount:0,harmfulCount:0,tokenEstimate:0},updatedAt:e,description:o}}function Mt(o){return JSON.parse(JSON.stringify(o))}function Sg(o){return Math.ceil(o.length/4)}function Ga(o,e,t){let n=[],r=[],{maxSectionSize:s=Number.POSITIVE_INFINITY,allowDynamicSections:i=!0,enableAutoPrune:a=!1,protectedBulletIds:u}=t??{},c=new Date().toISOString(),l=u??new Set;for(let p of e){if(!p.section)continue;if(!o.sections[p.section]){if(!i)continue;o.sections[p.section]=[]}let d=o.sections[p.section];switch(p.type){case"ADD":{if(d.length>=s){if(!a)continue;let f=Og(d,l);if(!f)continue;n.push(f.id),r.push({type:"REMOVE",section:p.section,bulletId:f.id,metadata:{...f.metadata??{},autoPruned:!0,removedAt:c}})}let m=p.bulletId??kg(p.section),g={id:m,section:p.section,content:p.content??"",helpfulCount:0,harmfulCount:0,createdAt:c,updatedAt:c,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=c,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 za(o),o.updatedAt=c,{updatedBulletIds:n,autoRemoved:r}}function ja(o,e,t){for(let n of Object.values(o.sections)){let r=n.find(s=>s.id===e);if(r){t==="helpful"?r.helpfulCount+=1:t==="harmful"&&(r.harmfulCount+=1),r.updatedAt=new Date().toISOString(),za(o);return}}}function gn(o){let e=o.description?`## Context Playbook
854
854
  ${o.description.trim()}
855
855
  `:`## Context Playbook
856
856
  `,t=Object.entries(o.sections).map(([n,r])=>{let s=r.map(i=>`- [${i.id}] ${i.content}`).join(`
@@ -859,45 +859,45 @@ ${s}`:`### ${n}
859
859
  _(empty)_`}).join(`
860
860
 
861
861
  `);return`${e}
862
- ${t}`.trim()}function Rg(o){let e=o.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,6),t=ap.default.randomBytes(4).toString("hex");return`${e||"ctx"}-${t}`}function vg(o,e){let t=-1,n;for(let s=0;s<o.length;s+=1){let i=o[s];if(e.has(i.id))continue;let a=i.helpfulCount??0,u=i.harmfulCount??0,c=a-u*2,l=Date.parse(i.updatedAt??i.createdAt),p=[c,a,Number.isFinite(l)?l:Number.POSITIVE_INFINITY];if(!n){t=s,n=p;continue}let d=o[t],m=d.helpfulCount??0,g=d.harmfulCount??0,f=m-g*2,x=Date.parse(d.updatedAt??d.createdAt),A=[f,m,Number.isFinite(x)?x: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=s,n=p)}if(t===-1)return;let[r]=o.splice(t,1);return r}function Ga(o,e=.95){for(let[t,n]of Object.entries(o.sections)){let r=new Map,s=[];for(let i of n){let a=i.content.trim().toLowerCase(),u=r.get(a);u?(u.helpfulCount+=i.helpfulCount,u.harmfulCount+=i.harmfulCount,u.updatedAt=i.updatedAt):(r.set(a,i),s.push(i))}o.sections[t]=s}Ba(o)}function Ba(o){let e=0,t=0,n=0,r=0;for(let s of Object.values(o.sections))for(let i of s)e+=1,t+=i.helpfulCount,n+=i.harmfulCount,r+=wg(i.content);o.stats={bulletCount:e,helpfulCount:t,harmfulCount:n,tokenEstimate:r}}var Sg={maxEpochs:1,maxReflectorRounds:2,maxSectionSize:25,similarityThreshold:.95,allowDynamicSections:!0},no=class extends Ct{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=Mt(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(),"",dn(this.playbook)].filter(s=>s&&s.trim().length>0).join(`
862
+ ${t}`.trim()}function kg(o){let e=o.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,6),t=up.default.randomBytes(4).toString("hex");return`${e||"ctx"}-${t}`}function Og(o,e){let t=-1,n;for(let s=0;s<o.length;s+=1){let i=o[s];if(e.has(i.id))continue;let a=i.helpfulCount??0,u=i.harmfulCount??0,c=a-u*2,l=Date.parse(i.updatedAt??i.createdAt),p=[c,a,Number.isFinite(l)?l:Number.POSITIVE_INFINITY];if(!n){t=s,n=p;continue}let d=o[t],m=d.helpfulCount??0,g=d.harmfulCount??0,f=m-g*2,x=Date.parse(d.updatedAt??d.createdAt),A=[f,m,Number.isFinite(x)?x: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=s,n=p)}if(t===-1)return;let[r]=o.splice(t,1);return r}function Ba(o,e=.95){for(let[t,n]of Object.entries(o.sections)){let r=new Map,s=[];for(let i of n){let a=i.content.trim().toLowerCase(),u=r.get(a);u?(u.helpfulCount+=i.helpfulCount,u.harmfulCount+=i.harmfulCount,u.updatedAt=i.updatedAt):(r.set(a,i),s.push(i))}o.sections[t]=s}za(o)}function za(o){let e=0,t=0,n=0,r=0;for(let s of Object.values(o.sections))for(let i of s)e+=1,t+=i.helpfulCount,n+=i.harmfulCount,r+=Sg(i.content);o.stats={bulletCount:e,helpfulCount:t,harmfulCount:n,tokenEstimate:r}}var Eg={maxEpochs:1,maxReflectorRounds:2,maxSectionSize:25,similarityThreshold:.95,allowDynamicSections:!0},no=class extends It{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=Mt(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(),"",gn(this.playbook)].filter(s=>s&&s.trim().length>0).join(`
863
863
 
864
- `);e.setDescription(r)}},nr=class extends It{aceConfig;playbook;baseInstruction;generatorHistory=[];deltaHistory=[];reflectorProgram;curatorProgram;program;constructor(e,t){super(e),this.aceConfig={...Sg,...t},this.playbook=t?.initialPlaybook!==void 0?Mt(t.initialPlaybook):Ls()}reset(){super.reset(),this.playbook=this.aceConfig.initialPlaybook!==void 0?Mt(this.aceConfig.initialPlaybook):Ls(),this.baseInstruction=void 0,this.generatorHistory=[],this.deltaHistory=[]}hydrate(e,t){this.program=e,this.baseInstruction=t?.baseInstruction??e.getSignature().getDescription()??void 0,this.playbook=t?.playbook!==void 0?Mt(t.playbook):this.aceConfig.initialPlaybook!==void 0?Mt(this.aceConfig.initialPlaybook):Ls(),this.generatorHistory=[...t?.artifact?.feedback??[]],this.deltaHistory=[...t?.artifact?.history??[]]}getPlaybook(){return Mt(this.playbook)}getBaseInstruction(){return this.baseInstruction}getArtifact(){return{playbook:Mt(this.playbook),feedback:[...this.generatorHistory],history:[...this.deltaHistory]}}applyCurrentState(e){let t=e??this.program;if(!t)throw new Error("AxACE: no program available to apply playbook state");let n=this.baseInstruction??t.getSignature().getDescription()??"";t.setDescription?.(this.composeInstruction(n,this.playbook))}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 s=r?.aceOptions;s&&(Object.assign(this.aceConfig,{maxEpochs:s.maxEpochs??this.aceConfig.maxEpochs,maxReflectorRounds:s.maxReflectorRounds??this.aceConfig.maxReflectorRounds,maxSectionSize:s.maxSectionSize??this.aceConfig.maxSectionSize,similarityThreshold:s.similarityThreshold??this.aceConfig.similarityThreshold,allowDynamicSections:s.allowDynamicSections??this.aceConfig.allowDynamicSections}),s.initialPlaybook&&(this.playbook=Mt(s.initialPlaybook)));let i=Date.now();this.validateExamples(t),this.program=e;let a=await this.extractProgramInstruction(e),u=e.getSignature().getDescription()??"";this.baseInstruction=a??u,this.generatorHistory=[],this.deltaHistory=[];let c=Number.NEGATIVE_INFINITY,l=0,p=Math.max(this.aceConfig.maxEpochs,1),d=p*t.length;try{for(let A=0;A<p;A++)for(let h=0;h<t.length;h++){let y=t[h],T=this.composeInstruction(a??u,this.playbook);e.setDescription?.(T);let C=await e.forward(this.studentAI,y);this.stats.totalCalls+=1;let R=await n({prediction:C,example:y});typeof R=="number"&&(this.stats.bestScore=Math.max(this.stats.bestScore,R),c=Math.max(c,R));let M=C?.severity,I=y?.severity,O=this.createGeneratorOutput(C,y),E=I&&M&&I!==M,$=await this.runReflectionRounds({example:y,generatorOutput:O,feedback:I&&M&&I!==M?`Expected severity "${I}" but model predicted "${M}".`:void 0}),N=await this.runCurator({program:e,example:y,reflection:$,playbook:this.playbook}),S=this.normalizeCuratorOperations(N?.operations);S.length===0&&E&&(S=this.inferOperationsFromReflection($)),S=this.resolveCuratorOperationTargets(S,this.playbook,$,O);let v=N||S.length>0?{...N??{},operations:S}:void 0,F=[];if(S.length>0){let G=this.collectProtectedBulletIds(S),H=Da(this.playbook,S,{maxSectionSize:this.aceConfig.maxSectionSize,allowDynamicSections:this.aceConfig.allowDynamicSections,enableAutoPrune:!0,protectedBulletIds:G});F=H.updatedBulletIds,H.autoRemoved.length>0&&(S.push(...H.autoRemoved),v&&(v.operations=S))}if($?.bulletTags)for(let G of $.bulletTags)Ua(this.playbook,G.id,G.tag);S.length>0&&F.length>0&&Ga(this.playbook,this.aceConfig.similarityThreshold);let P={example:y,prediction:C,score:typeof R=="number"?R:0,generatorOutput:O,reflection:$,curator:v,timestamp:new Date().toISOString()};this.generatorHistory.push(P),F.length>0&&v?.operations?.length&&this.deltaHistory.push({epoch:A,exampleIndex:h,operations:v.operations}),l+=1,this.currentRound=l;let L=typeof R=="number"&&Number.isFinite(R)?R:0,D=Number.isFinite(c)?c:L,j={...r??{},maxIterations:d};await this.updateOptimizationProgress(l,L,{epoch:A,exampleIndex:h,playbookBullets:this.playbook.stats.bulletCount},"ACE",{epochs:p,totalRounds:d},D,{playbookBullets:this.playbook.stats.bulletCount},void 0,j),this.stats.convergenceInfo.finalImprovement=Math.max(this.stats.convergenceInfo.finalImprovement,L)}}finally{e.setDescription?.(u)}let m=Date.now()-i;this.stats.resourceUsage.totalTime=m,this.stats.convergenceInfo.converged=!0,this.stats.bestScore=Number.isFinite(c)?c:0;let g={playbook:Mt(this.playbook),feedback:[...this.generatorHistory],history:[...this.deltaHistory]},f=new no({baseInstruction:a??u,playbook:this.playbook,artifact:g,bestScore:Number.isFinite(c)?c:0,stats:this.stats,optimizerType:"ACE",optimizationTime:m,totalRounds:l,converged:this.stats.convergenceInfo.converged});return{stats:this.stats,bestScore:Number.isFinite(c)?c:0,finalConfiguration:{strategy:"ace",epochs:p},optimizedProgram:f,playbook:Mt(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,s=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:s,playbook:this.playbook}),a=this.normalizeCuratorOperations(i?.operations),u=r&&n&&r!==n;a.length===0&&u&&(a=this.inferOperationsFromReflection(s)),a=this.resolveCuratorOperationTargets(a,this.playbook,s,t);let c=i||a.length>0?{...i??{},operations:a}:void 0;if(s?.bulletTags)for(let p of s.bulletTags)Ua(this.playbook,p.id,p.tag);if(a.length>0){let p=this.collectProtectedBulletIds(a),d=Da(this.playbook,a,{maxSectionSize:this.aceConfig.maxSectionSize,allowDynamicSections:this.aceConfig.allowDynamicSections,enableAutoPrune:!0,protectedBulletIds:p});d.autoRemoved.length>0&&(a.push(...d.autoRemoved),c&&(c.operations=a)),Ga(this.playbook,this.aceConfig.similarityThreshold)}let l={example:e.example,prediction:e.prediction,score:0,generatorOutput:t,reflection:s,curator:c,timestamp:new Date().toISOString()};return this.generatorHistory.push(l),c}composeInstruction(e,t){return[e.trim(),"",dn(t)].filter(r=>r.trim().length>0).join(`
864
+ `);e.setDescription(r)}},rr=class extends Tt{aceConfig;playbook;baseInstruction;generatorHistory=[];deltaHistory=[];reflectorProgram;curatorProgram;program;constructor(e,t){super(e),this.aceConfig={...Eg,...t},this.playbook=t?.initialPlaybook!==void 0?Mt(t.initialPlaybook):$s()}reset(){super.reset(),this.playbook=this.aceConfig.initialPlaybook!==void 0?Mt(this.aceConfig.initialPlaybook):$s(),this.baseInstruction=void 0,this.generatorHistory=[],this.deltaHistory=[]}hydrate(e,t){this.program=e,this.baseInstruction=t?.baseInstruction??e.getSignature().getDescription()??void 0,this.playbook=t?.playbook!==void 0?Mt(t.playbook):this.aceConfig.initialPlaybook!==void 0?Mt(this.aceConfig.initialPlaybook):$s(),this.generatorHistory=[...t?.artifact?.feedback??[]],this.deltaHistory=[...t?.artifact?.history??[]]}getPlaybook(){return Mt(this.playbook)}getBaseInstruction(){return this.baseInstruction}getArtifact(){return{playbook:Mt(this.playbook),feedback:[...this.generatorHistory],history:[...this.deltaHistory]}}applyCurrentState(e){let t=e??this.program;if(!t)throw new Error("AxACE: no program available to apply playbook state");let n=this.baseInstruction??t.getSignature().getDescription()??"";t.setDescription?.(this.composeInstruction(n,this.playbook))}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 s=r?.aceOptions;s&&(Object.assign(this.aceConfig,{maxEpochs:s.maxEpochs??this.aceConfig.maxEpochs,maxReflectorRounds:s.maxReflectorRounds??this.aceConfig.maxReflectorRounds,maxSectionSize:s.maxSectionSize??this.aceConfig.maxSectionSize,similarityThreshold:s.similarityThreshold??this.aceConfig.similarityThreshold,allowDynamicSections:s.allowDynamicSections??this.aceConfig.allowDynamicSections}),s.initialPlaybook&&(this.playbook=Mt(s.initialPlaybook)));let i=Date.now();this.validateExamples(t),this.program=e;let a=await this.extractProgramInstruction(e),u=e.getSignature().getDescription()??"";this.baseInstruction=a??u,this.generatorHistory=[],this.deltaHistory=[];let c=Number.NEGATIVE_INFINITY,l=0,p=Math.max(this.aceConfig.maxEpochs,1),d=p*t.length;try{for(let A=0;A<p;A++)for(let h=0;h<t.length;h++){let y=t[h],C=this.composeInstruction(a??u,this.playbook);e.setDescription?.(C);let I=await e.forward(this.studentAI,y);this.stats.totalCalls+=1;let R=await n({prediction:I,example:y});typeof R=="number"&&(this.stats.bestScore=Math.max(this.stats.bestScore,R),c=Math.max(c,R));let M=I?.severity,T=y?.severity,O=this.createGeneratorOutput(I,y),E=T&&M&&T!==M,$=await this.runReflectionRounds({example:y,generatorOutput:O,feedback:T&&M&&T!==M?`Expected severity "${T}" but model predicted "${M}".`:void 0}),N=await this.runCurator({program:e,example:y,reflection:$,playbook:this.playbook}),S=this.normalizeCuratorOperations(N?.operations);S.length===0&&E&&(S=this.inferOperationsFromReflection($)),S=this.resolveCuratorOperationTargets(S,this.playbook,$,O);let v=N||S.length>0?{...N??{},operations:S}:void 0,P=[];if(S.length>0){let j=this.collectProtectedBulletIds(S),K=Ga(this.playbook,S,{maxSectionSize:this.aceConfig.maxSectionSize,allowDynamicSections:this.aceConfig.allowDynamicSections,enableAutoPrune:!0,protectedBulletIds:j});P=K.updatedBulletIds,K.autoRemoved.length>0&&(S.push(...K.autoRemoved),v&&(v.operations=S))}if($?.bulletTags)for(let j of $.bulletTags)ja(this.playbook,j.id,j.tag);S.length>0&&P.length>0&&Ba(this.playbook,this.aceConfig.similarityThreshold);let F={example:y,prediction:I,score:typeof R=="number"?R:0,generatorOutput:O,reflection:$,curator:v,timestamp:new Date().toISOString()};this.generatorHistory.push(F),P.length>0&&v?.operations?.length&&this.deltaHistory.push({epoch:A,exampleIndex:h,operations:v.operations}),l+=1,this.currentRound=l;let U=typeof R=="number"&&Number.isFinite(R)?R:0,L=Number.isFinite(c)?c:U,z={...r??{},maxIterations:d};await this.updateOptimizationProgress(l,U,{epoch:A,exampleIndex:h,playbookBullets:this.playbook.stats.bulletCount},"ACE",{epochs:p,totalRounds:d},L,{playbookBullets:this.playbook.stats.bulletCount},void 0,z),this.stats.convergenceInfo.finalImprovement=Math.max(this.stats.convergenceInfo.finalImprovement,U)}}finally{e.setDescription?.(u)}let m=Date.now()-i;this.stats.resourceUsage.totalTime=m,this.stats.convergenceInfo.converged=!0,this.stats.bestScore=Number.isFinite(c)?c:0;let g={playbook:Mt(this.playbook),feedback:[...this.generatorHistory],history:[...this.deltaHistory]},f=new no({baseInstruction:a??u,playbook:this.playbook,artifact:g,bestScore:Number.isFinite(c)?c:0,stats:this.stats,optimizerType:"ACE",optimizationTime:m,totalRounds:l,converged:this.stats.convergenceInfo.converged});return{stats:this.stats,bestScore:Number.isFinite(c)?c:0,finalConfiguration:{strategy:"ace",epochs:p},optimizedProgram:f,playbook:Mt(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,s=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:s,playbook:this.playbook}),a=this.normalizeCuratorOperations(i?.operations),u=r&&n&&r!==n;a.length===0&&u&&(a=this.inferOperationsFromReflection(s)),a=this.resolveCuratorOperationTargets(a,this.playbook,s,t);let c=i||a.length>0?{...i??{},operations:a}:void 0;if(s?.bulletTags)for(let p of s.bulletTags)ja(this.playbook,p.id,p.tag);if(a.length>0){let p=this.collectProtectedBulletIds(a),d=Ga(this.playbook,a,{maxSectionSize:this.aceConfig.maxSectionSize,allowDynamicSections:this.aceConfig.allowDynamicSections,enableAutoPrune:!0,protectedBulletIds:p});d.autoRemoved.length>0&&(a.push(...d.autoRemoved),c&&(c.operations=a)),Ba(this.playbook,this.aceConfig.similarityThreshold)}let l={example:e.example,prediction:e.prediction,score:0,generatorOutput:t,reflection:s,curator:c,timestamp:new Date().toISOString()};return this.generatorHistory.push(l),c}composeInstruction(e,t){return[e.trim(),"",gn(t)].filter(r=>r.trim().length>0).join(`
865
865
 
866
- `)}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 s=[],i=new Set(e.map(l=>l.bulletId).filter(l=>typeof l=="string")),a=new Map,u=(l,p)=>{if(i.has(l))return;let d=this.locateBullet(t,l);if(!d)return;let m=a.get(d.section)??{harmful:[],primary:[],generator:[]};m[p].push(d.id),a.set(d.section,m)};for(let l of n?.bulletTags??[]){let p=l.tag==="harmful"?"harmful":"primary";u(l.id,p)}if(r?.bulletIds)for(let l of r.bulletIds)u(l,"generator");let c=l=>{let p=a.get(l);if(!p)return this.locateFallbackBullet(t,l,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,l,i)};for(let l of e){if((l.type==="UPDATE"||l.type==="REMOVE")&&!l.bulletId){let p=c(l.section);p&&(l.bulletId=p,i.add(p))}(l.type==="UPDATE"||l.type==="REMOVE")&&!l.bulletId||s.push(l)}return s}locateBullet(e,t){for(let n of Object.values(e.sections)){let r=n.find(s=>s.id===t);if(r)return r}}locateFallbackBullet(e,t,n){let r=e.sections[t]??[];for(let s of r)if(!n.has(s.id))return s.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 s=r.type??"ADD",i=typeof s=="string"?s.toUpperCase():"ADD",a=i==="UPDATE"?"UPDATE":i==="REMOVE"?"REMOVE":"ADD",u=r.section??"Guidelines",c=typeof u=="string"&&u.trim().length>0?u.trim():"Guidelines",l=r.content??"",p=typeof l=="string"?l.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,c,p,m??""].join(":");if(n.has(f))continue;n.add(f);let x={type:a,section:c};a!=="REMOVE"&&(x.content=p),m&&(x.bulletId=m);let A=r.metadata;A&&typeof A=="object"&&(x.metadata={...A}),t.push(x)}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=(s,i)=>{if(!i)return;let a=i.trim();if(!a||a.toLowerCase().startsWith("no error"))return;let c=`${s}:${a}`;n.has(c)||(n.add(c),t.push({type:"ADD",section:s,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),s;for(let i=0;i<r;i++){let a=await this.runReflector({example:e,generatorOutput:t,feedback:n,previousReflection:s});if(!a)break;s=a;let u=a.errorIdentification?.toLowerCase().trim()??"";if(a.metadata?.resolved===!0||u.length===0||u.startsWith("no error")||u.startsWith("resolved"))break}return s}async runReflector({example:e,generatorOutput:t,feedback:n,previousReflection:r}){let s=this.getOrCreateReflectorProgram(),i=this.teacherAI??this.studentAI;try{let a={severity:e?.severity,policyHint:e?.policyHint},l=(this.program?.getSignature()?.getInputFields()??[]).reduce((d,m)=>(m.name in e&&(d[m.name]=e[m.name]),d),{});return await s.forward(i,{question:JSON.stringify(l),generator_answer:JSON.stringify(t.answer),generator_reasoning:t.reasoning,playbook:JSON.stringify({markdown:dn(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 s=this.getOrCreateCuratorProgram(),i=this.teacherAI??this.studentAI,c=e.getSignature().getInputFields().reduce((l,p)=>(p.name in t&&(l[p.name]=t[p.name]),l),{});try{return await s.forward(i,{playbook:JSON.stringify({markdown:dn(r),structured:r}),reflection:JSON.stringify(n),question_context:JSON.stringify(c),token_budget:1024})}catch(l){this.verbose&&console.warn("[AxACE] Curator error:",l instanceof Error?l.message:l);return}}getOrCreateReflectorProgram(){if(!this.reflectorProgram){let e=ge().input("question",ge.string("Original task input serialized as JSON")).input("generator_answer",ge.string("Generator output serialized as JSON")).input("generator_reasoning",ge.string("Generator reasoning trace").optional()).input("playbook",ge.string("Current context playbook rendered as markdown")).input("expected_answer",ge.string("Expected output when ground truth is available").optional()).input("feedback",ge.string("External feedback or reward signal").optional()).input("previous_reflection",ge.string("Most recent reflection JSON when running multi-round refinement").optional()).output("reasoning",ge.string("Step-by-step analysis of generator performance")).output("errorIdentification",ge.string("Specific mistakes detected")).output("rootCauseAnalysis",ge.string("Underlying cause of the error")).output("correctApproach",ge.string("What the generator should do differently")).output("keyInsight",ge.string("Reusable insight to remember")).output("bulletTags",ge.json("Array of {id, tag} entries referencing playbook bullets")).build();this.reflectorProgram=it(e)}return this.reflectorProgram}getOrCreateCuratorProgram(){if(!this.curatorProgram){let e=ge().input("playbook",ge.string("Current playbook serialized as JSON")).input("reflection",ge.string("Latest reflection output serialized as JSON")).input("question_context",ge.string("Original task input serialized as JSON")).input("token_budget",ge.number("Approximate token budget for curator response").optional()).output("reasoning",ge.string("Justification for the proposed updates")).output("operations",ge.json("List of operations with type/section/content fields")).build();this.curatorProgram=it(e)}return this.curatorProgram}};function up(o,e,t=0){let n=new Set([...Object.keys(o),...Object.keys(e)]),r=!0,s=!1;for(let i of n){let a=o[i]??0,u=e[i]??0;if(a+t<u){r=!1;break}a>u+t&&(s=!0)}return r&&s}function ro(o,e=0){let t=[];for(let n=0;n<o.length;n++){let r=0,s=!1;for(let i=0;i<o.length;i++)if(n!==i){if(up(o[i].scores,o[n].scores,e)){s=!0;break}up(o[n].scores,o[i].scores,e)&&r++}s||t.push({idx:o[n].idx,scores:o[n].scores,dominated:r})}return t}function rr(o){if(o.length===0)return;let e=Object.keys(o[0]??{});if(e.length!==2)return;let[t,n]=e,r=[...o].sort((a,u)=>(u[t]??0)-(a[t]??0)),s=0,i=0;for(let a of r){let u=a[t]??0,c=a[n]??0,l=Math.max(c-i,0);s+=u*l,i=Math.max(i,c)}return s}function ja(o){if(o.length===0)return 0;let e=0;for(let t of o)e+=t;return e/o.length}function cp(o){let e={},t={};for(let r of o)for(let[s,i]of Object.entries(r))e[s]=(e[s]||0)+(typeof i=="number"?i:0),t[s]=(t[s]||0)+1;let n={};for(let[r,s]of Object.entries(e))n[r]=s/Math.max(t[r]||1,1);return n}function za(o,e){let t=new Set;for(let l of o)for(let p of l)t.add(p);let r=[...Array.from(t)].sort((l,p)=>(e[l]??0)-(e[p]??0)),s=new Set,i=(l,p)=>{for(let d of o){if(!d.has(l))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 l of r){if(s.has(l))continue;let p=new Set(r.filter(d=>d!==l&&!s.has(d)));if(i(l,p)){s.add(l),a=!0;break}}}let u=r.filter(l=>!s.has(l)),c=new Set(u);return o.map(l=>{let p=new Set;for(let d of l)c.has(d)&&p.add(d);return p})}function lp(o,e,t){let n=za(o,e),r={};for(let u of n)for(let c of u)r[c]=(r[c]||0)+1;let s=[];for(let[u,c]of Object.entries(r)){let l=Number(u);for(let p=0;p<c;p++)s.push(l)}if(s.length===0)return 0;let i=typeof t=="function"?t():Math.random(),a=Math.floor(i*s.length);return s[a]}function kg(o){return o.size===0?{score:0}:Object.fromEntries([...o].map(e=>[e,0]))}function $s(o,e=800){if(typeof o=="string"){let t=o.trim();return t.length<=e?t:`${t.slice(0,Math.max(0,e-3))}...`}try{let t=JSON.stringify(o,null,2).trim();return t.length<=e?t:`${t.slice(0,Math.max(0,e-3))}...`}catch{let t=String(o).trim();return t.length<=e?t:`${t.slice(0,Math.max(0,e-3))}...`}}var Yt=class o extends It{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 s=e?.crossoverEvery;this.crossoverEvery=Math.max(0,Math.floor(s??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 u=e?.mergeMax;this.mergeMax=Math.max(0,Math.floor(u??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 s=Date.now();this.validateExamples(t),r?.auto&&this.configureAuto(r.auto);let i=r?.maxMetricCalls;if(!Number.isFinite(i)||i<=0)throw new Error("AxGEPA: options.maxMetricCalls must be set to a positive integer");let a=Math.floor(i),u=r?.validationExamples,c=r?.feedbackExamples,l=(u&&u.length>0?u:t).slice(0,this.paretoSetSize),p=B=>{let V=Object.keys(B).sort().reduce((Q,ie)=>(Q[ie]=B[ie],Q),{});return JSON.stringify(V)},d=new Set(t.map(B=>p(B))),m=c&&c.length>0?c.filter(B=>d.has(p(B))):t,g=m.length>0?m:t,f=this.getInstructionTargets(e);if(f.length===0)throw new Error("AxGEPA: program has no instruction-bearing nodes to optimize");let x=f.map(B=>B.id),A=B=>{for(let V of f){let Q=B[V.id];typeof Q=="string"&&V.program.setInstruction?.(Q)}},h=async(B,V)=>{let Q=await n({prediction:B,example:V});if(typeof Q=="number")return Number.isFinite(Q)?{score:Q}:{};if(!Q||typeof Q!="object")return{};let ie={};for(let[W,q]of Object.entries(Q))typeof q=="number"&&Number.isFinite(q)&&(ie[W]=q);return ie},y=B=>{let V=r?.paretoMetricKey,Q=r?.paretoScalarize;if(typeof Q=="function")return Q(B);if(V)return Number.isFinite(B[V])?B[V]:0;let ie=Object.values(B);return ie.length?ie.reduce((W,q)=>W+q,0)/ie.length:0},T=this.getOptimizerLogger(r),C=r?.verbose??this.verbose?B=>console.log(`[GEPA] ${B}`):B=>{},R=new Set,M=async(B,V,Q,ie=!1)=>{let W=V.length;if(this.stats.totalCalls+W>a){if(ie)throw new Error(`AxGEPA: options.maxMetricCalls=${a} is too small to evaluate the initial Pareto set; need at least ${W} metric calls`);return}let q=[];C(`${Q}: evaluating ${V.length} example${V.length===1?"":"s"}`);for(let[oe,Ce]of V.entries()){A(B);let Re,ae;try{Re=await e.forward(this.studentAI,Ce,{sampleCount:this.sampleCount}),ae=await h(Re,Ce);for(let ce of Object.keys(ae))R.add(ce)}catch(ce){let me=ce instanceof Error?ce.message:String(ce);Re={error:me},ae=kg(R),C(`Evaluation failed during ${Q}; scoring this example as zero. Error: ${me}`)}this.stats.totalCalls+=1;let ke=y(ae);q.push({input:Ce,prediction:Re,scores:ae,scalar:ke}),C(`${Q}: completed ${oe+1}/${V.length} (score=${ke.toFixed(3)})`)}return{rows:q,avg:cp(q.map(oe=>oe.scores)),scalars:q.map(oe=>oe.scalar),sum:q.reduce((oe,Ce)=>oe+Ce.scalar,0)}},I={};for(let B of f)I[B.id]=await this.getBaseInstruction(B.program);let O=await M(I,l,"initial Pareto evaluation",!0),E=[{cfg:{...I},parent:void 0,scores:O.avg}],$=[O.scalars];T?.({name:"OptimizationStart",value:{optimizerType:"GEPA",exampleCount:t.length,validationCount:l.length,config:{numTrials:this.numTrials,minibatch:this.minibatch,mergeMax:this.mergeMax,tunableCount:f.length}}}),C(`Starting GEPA optimization: ${t.length} train, ${l.length} validation, maxCalls=${a}`);let N=0,S=new Set,v=ro(E.map((B,V)=>({idx:V,scores:B.scores})),this.tieEpsilon).map(B=>B.idx),F;for(let B=0;B<this.numTrials&&!(a!==void 0&&this.stats.totalCalls>=Math.max(1,Math.floor(a)));B++){let V=$[0]?.length??0,Q=[];for(let pe=0;pe<V;pe++){let De=Number.NEGATIVE_INFINITY,Ke=new Set;for(let Ye=0;Ye<$.length;Ye++){let ut=$[Ye][pe];ut>De+this.tieEpsilon?(De=ut,Ke.clear(),Ke.add(Ye)):Math.abs(ut-De)<=this.tieEpsilon&&Ke.add(Ye)}Q.push(Ke)}let ie=$.map(pe=>ja(pe));if(this.mergeMax>0&&this.mergesDue>0&&this.lastIterFoundNewProgram){let pe=k=>{let _=[],w=k;for(;w!==void 0;)_.push(w),w=E[w]?.parent;return _},De=k=>k.length?k[Math.floor(this.rand()*k.length)]:void 0,Ke=za(Q,ie),Ye=new Set;for(let k of Ke)for(let _ of k)Ye.add(_);let ut=Array.from(Ye),b;for(let k=0;k<10&&!b&&!(ut.length<2);k++){let _=De(ut),w=De(ut);if(_===w)continue;w<_&&([_,w]=[w,_]);let z=new Set(pe(_)),J=new Set(pe(w));if(z.has(w)||J.has(_))continue;let Z=[...z].filter(te=>J.has(te));if(Z.length===0)continue;let Y=[];for(let te of Z){let Ie=E[te].cfg,Ue=E[_].cfg,Te=E[w].cfg,qe=!1,_e=new Set([...Object.keys(Ie),...Object.keys(Ue),...Object.keys(Te)]);for(let nt of _e){let ee=Ie[nt],X=Ue[nt],Ae=Te[nt];if(X===ee&&Ae!==X||Ae===ee&&X!==Ae){qe=!0;break}}qe&&Y.push(te)}if(Y.length===0)continue;let U=Y.map(te=>Math.max(1e-9,ie[te])),K=this.rand()*U.reduce((te,Ie)=>te+Ie,0),ne=Y[Y.length-1];for(let te=0;te<Y.length;te++){if(K<U[te]){ne=Y[te];break}K-=U[te]}b={i:_,j:w,a:ne}}if(this.lastIterFoundNewProgram=!1,b){let k=!1,{i:_,j:w,a:z}=b,J=ie[z],Z=ie[_],Y=ie[w];if(J>Math.min(Z,Y))continue;let U=`${_}|${w}|${z}`;if(this.mergeAttemptKeys.has(U)||(this.mergeAttemptKeys.add(U),S.has(U)))continue;let{cfg:K,descSig:ne}=this.systemAwareMergeWithSig(E,_,w,(we,Xe)=>ie[we]>=ie[Xe]?we:Xe),te=`${Math.min(_,w)}|${Math.max(_,w)}|${ne}`;if(this.mergeCompositionKeys.has(te))continue;this.mergeCompositionKeys.add(te);let Ie=$[_],Ue=$[w],Te=Array.from({length:Ie.length},(we,Xe)=>Xe),qe=Te.filter(we=>(Ie[we]??0)>(Ue[we]??0)),_e=Te.filter(we=>(Ue[we]??0)>(Ie[we]??0)),nt=Te.filter(we=>!(qe.includes(we)||_e.includes(we))),ee=5,X=Math.ceil(ee/3),Ae=(we,Xe)=>{if(Xe<=0||we.length===0)return[];if(we.length<=Xe)return[...we];let hr=[],yo=new Set;for(;hr.length<Xe;){let wt=Math.floor(this.rand()*we.length);yo.has(wt)||(yo.add(wt),hr.push(we[wt]))}return hr},Oe=[];Oe.push(...Ae(qe,Math.min(X,qe.length))),Oe.push(...Ae(_e,Math.min(X,_e.length)));let Pe=ee-Oe.length;Oe.push(...Ae(nt,Math.max(0,Pe)));let Ve=ee-Oe.length;if(Ve>0){let we=Te.filter(Xe=>!Oe.includes(Xe));Oe.push(...Ae(we,Math.min(Ve,we.length)))}let Zt=Oe.slice(0,Math.min(ee,Te.length)),ci=Zt.map(we=>l[we]),en=await M(K,ci,"merge subsample");if(!en)break;let tn=en.sum,Ao=Zt.reduce((we,Xe)=>we+(Ie[Xe]??0),0),Au=Zt.reduce((we,Xe)=>we+(Ue[Xe]??0),0);if(tn>=Math.max(Ao,Au)+this.minImprovementThreshold){C(`Iteration ${B+1}: Merge accepted (programs ${_} + ${w} via ancestor ${z})`);let we=await M(K,l,"merge validation");if(!we)break;E.push({cfg:{...K},parent:z,scores:we.avg}),$.push(we.scalars);let Xe=v.length,hr=rr(v.map(wt=>E[wt].scores))??0;v=ro(E.map((wt,Id)=>({idx:Id,scores:wt.scores})),this.tieEpsilon).map(wt=>wt.idx);let yo=rr(v.map(wt=>E[wt].scores))??0;(v.length>Xe||yo>hr+1e-6)&&(N=0),this.mergesDue-=1,this.totalMergesTested+=1,S.add(U),k=!0}if(k)continue}}let W=lp(Q,ie,()=>this.rand());this.lastIterFoundNewProgram=!1;let q=this.minibatch?this.nextMinibatchIndices(g.length,B).map(pe=>g[pe]):g,oe=await M(E[W].cfg,q,"parent minibatch");if(!oe)break;if(r?.skipPerfectScore??!0){let pe=Number(r?.perfectScore??1);if(oe.scalars.length>0&&oe.scalars.every(De=>De>=pe))continue}let Ce={...E[W].cfg},Re="reflective_mutation",ae,ke,ce=f[B%f.length],me=E[W].cfg[ce.id],be=r?.gepaAdapter,ue,xe=oe.rows.map(pe=>({input:pe.input,prediction:pe.prediction,score:pe.scalar}));if(be)try{let pe=await be.evaluate(q,{...E[W].cfg},!0);ae=Array.isArray(pe?.scores)?pe.scores.reduce((ut,b)=>ut+(Number(b)||0),0):void 0;let De=be.make_reflective_dataset({...E[W].cfg},pe,[ce.id]),Ke=await be.propose_new_texts?.({...E[W].cfg},De,[ce.id]),Ye=Ke?.[ce.id]??(Ke?Object.values(Ke)[0]:void 0);typeof Ye=="string"&&Ye.length>0&&(ue=Ye)}catch{}if(ue||(ue=await this.reflectTargetInstruction(ce.id,me,e,A,{...E[W].cfg},q,async({prediction:pe,example:De})=>y(await h(pe,De)),r,xe)),Ce[ce.id]=ue,be&&ae!==void 0)try{let pe=await be.evaluate(q,Ce,!1);ke=Array.isArray(pe?.scores)?pe.scores.reduce((De,Ke)=>De+(Number(Ke)||0),0):void 0}catch{}let ve=await M(Ce,q,"child minibatch");if(!ve)break;if(this.currentRound=B+1,await this.updateOptimizationProgress(this.currentRound,ve.sum,{instructionLen:ue.length,target:ce.id,parent:W,totalRounds:this.numTrials},"GEPA",{strategy:Re,paretoSetSize:l.length,tunableCount:f.length},ve.sum,{instructionLen:me.length,idx:W},{...r??{},maxIterations:this.numTrials}),!(ve.sum>oe.sum+this.minImprovementThreshold&&(ae===void 0||ke===void 0||ke>ae+this.minImprovementThreshold))){if(C(`Iteration ${B+1}: Rejected (child=${ve.sum.toFixed(3)} <= parent=${oe.sum.toFixed(3)})`),++N>=this.earlyStoppingTrials){C(`Early stopping: ${N} iterations without improvement`);break}continue}C(`Iteration ${B+1}: Accepted (child=${ve.sum.toFixed(3)} > parent=${oe.sum.toFixed(3)})`);let $e=await M(Ce,l,"validation evaluation");if(!$e)break;E.push({cfg:{...Ce},parent:W,scores:$e.avg}),$.push($e.scalars);let at=v.length,Ee=rr(v.map(pe=>E[pe].scores))??0;v=ro(E.map((pe,De)=>({idx:De,scores:pe.scores})),this.tieEpsilon).map(pe=>pe.idx);let ze=rr(v.map(pe=>E[pe].scores))??0;if(v.length>at||ze>Ee+1e-6)N=0,C(`Iteration ${B+1}: Archive improved (size=${v.length}, hv=${ze.toFixed(4)})`);else if(N++,C(`Iteration ${B+1}: Archive unchanged (stagnation=${N}/${this.earlyStoppingTrials})`),N>=this.earlyStoppingTrials){C(`Early stopping: ${N} iterations without archive improvement`);break}this.lastIterFoundNewProgram=!0,this.mergeMax>0&&this.totalMergesTested<this.mergeMax&&(this.mergesDue+=1)}let P=ro(E.map((B,V)=>({idx:V,scores:B.scores})),this.tieEpsilon),L=P.length>0?Math.max(...P.map(B=>y(B.scores))):0,D;if(P.length>0){let B=Number.NEGATIVE_INFINITY;for(let V of P){let Q=y(V.scores);Q>B&&(B=Q,D=V.idx)}}let j=rr(P.map(B=>B.scores));this.stats.convergenceInfo.converged=!0;let G=this.getMergedCustomLabels(r);this.recordParetoMetrics(P.length,E.length,"GEPA",j,G);let H=Date.now()-s,re=typeof D=="number"?new Ct({bestScore:L,stats:this.stats,instruction:f.length===1?E[D].cfg[x[0]]:void 0,instructionMap:{...E[D].cfg},demos:[],examples:t,modelConfig:void 0,optimizerType:"GEPA",optimizationTime:H,totalRounds:this.numTrials,converged:this.stats.convergenceInfo.converged}):void 0,le=this.generateOptimizationReport(P,j,L,E.length);return{demos:[],stats:this.stats,bestScore:L,paretoFront:P.map(B=>({demos:[],scores:B.scores,configuration:{candidate:B.idx,instructionMap:{...E[B.idx].cfg},...f.length===1?{instruction:E[B.idx].cfg[x[0]]}:{}},dominatedSolutions:B.dominated})),paretoFrontSize:P.length,hypervolume:j,finalConfiguration:{strategy:"gepa",candidates:E.length,tunables:f.length},optimizedProgram:re,report:le}}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."}getInstructionTargets(e){let t=new Set,n=[],r=(s,i)=>{let a=i;!s||t.has(s)||typeof a?.setInstruction!="function"||(t.add(s),n.push({id:s,program:a,signature:a.getSignature?.()?.toString?.()}))};if("namedProgramInstances"in e&&typeof e.namedProgramInstances=="function"){let s=e.namedProgramInstances()??[];for(let i of s)r(i?.id,i?.program)}return r(e.getId?.(),e),n}async evaluateOnSet(e,t,n,r){let s=[];for(let i of n){let a=await this.evaluateOne(e,t,i,r);s.push(a)}return s}async evaluateAvg(e,t,n,r){let s=await this.evaluateOnSet(e,t,n,r);return s.length>0?ja(s):0}async evaluateOne(e,t,n,r){try{e.setInstruction?.(t);let s=await e.forward(this.studentAI,n,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let i=await r({prediction:s,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(s){return this.getLogger()?.({name:"Notification",id:"gepa_eval",value:String(s)}),0}}async reflectTargetInstruction(e,t,n,r,s,i,a,u,c){let l=c?[...c]:[];if(l.length===0)for(let h of i)try{s[e]=t,r(s);let y=await n.forward(this.studentAI,h,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let T=await a({prediction:y,example:h});l.push({input:h,prediction:y,score:typeof T=="number"?T:0})}catch{l.push({input:h,prediction:{},score:0})}let p=u?.overrideTeacherAI??this.teacherAI??this.studentAI,d=it('targetId:string "Target program ID", minibatch:json "Array of {input,prediction,score}", evalFeedback?:string[] "Evaluator feedback when available" -> feedbackSummary:string "Concise program-focused feedback"'),g=[...(u?.feedbackNotes??[]).filter(h=>typeof h=="string"&&h.trim().length>0)],f=u?.feedbackFn;if(typeof f=="function")for(let h of l){let y=f({prediction:h.prediction,example:h.input,componentId:e});y&&(Array.isArray(y)?g.push(...y):g.push(y))}let x="";try{x=(await d.forward(p,{targetId:e,minibatch:l,evalFeedback:g}))?.feedbackSummary?.trim()||""}catch{}let A=it('targetId:string "Target program ID", currentInstruction:string "Current instruction", feedbackSummary?:string "Summarized feedback", minibatch:json "Array of {input,prediction,score}" -> newInstruction:string "Improved instruction (1-6 sentences) for the target program"');try{let y=(await A.forward(p,{targetId:e,currentInstruction:t,feedbackSummary:x,minibatch:l}))?.newInstruction?.trim();if(y&&y.length>16)return y}catch{}return`${t.trim()} Focus on step-by-step, target-specific reasoning and factual grounding.`.slice(0,2e3)}async reflectInstruction(e,t,n,r,s,i){let a=i??[];if(a.length===0)for(let f of n)try{t.setInstruction?.(e);let x=await t.forward(this.studentAI,f,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let A=await r({prediction:x,example:f});a.push({input:f,prediction:x,score:typeof A=="number"?A:0})}catch{a.push({input:f,prediction:{},score:0})}let u=s?.overrideTeacherAI??this.teacherAI??this.studentAI,c=typeof t?.getId=="function"?t.getId():void 0,l=s?.feedbackFn,p=(s?.feedbackNotes??[]).filter(f=>typeof f=="string"&&f.trim().length>0),d=()=>{let f=[];for(let A=0;A<a.length;A++){let h=a[A],y=`# Example ${A+1}
866
+ `)}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 s=[],i=new Set(e.map(l=>l.bulletId).filter(l=>typeof l=="string")),a=new Map,u=(l,p)=>{if(i.has(l))return;let d=this.locateBullet(t,l);if(!d)return;let m=a.get(d.section)??{harmful:[],primary:[],generator:[]};m[p].push(d.id),a.set(d.section,m)};for(let l of n?.bulletTags??[]){let p=l.tag==="harmful"?"harmful":"primary";u(l.id,p)}if(r?.bulletIds)for(let l of r.bulletIds)u(l,"generator");let c=l=>{let p=a.get(l);if(!p)return this.locateFallbackBullet(t,l,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,l,i)};for(let l of e){if((l.type==="UPDATE"||l.type==="REMOVE")&&!l.bulletId){let p=c(l.section);p&&(l.bulletId=p,i.add(p))}(l.type==="UPDATE"||l.type==="REMOVE")&&!l.bulletId||s.push(l)}return s}locateBullet(e,t){for(let n of Object.values(e.sections)){let r=n.find(s=>s.id===t);if(r)return r}}locateFallbackBullet(e,t,n){let r=e.sections[t]??[];for(let s of r)if(!n.has(s.id))return s.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 s=r.type??"ADD",i=typeof s=="string"?s.toUpperCase():"ADD",a=i==="UPDATE"?"UPDATE":i==="REMOVE"?"REMOVE":"ADD",u=r.section??"Guidelines",c=typeof u=="string"&&u.trim().length>0?u.trim():"Guidelines",l=r.content??"",p=typeof l=="string"?l.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,c,p,m??""].join(":");if(n.has(f))continue;n.add(f);let x={type:a,section:c};a!=="REMOVE"&&(x.content=p),m&&(x.bulletId=m);let A=r.metadata;A&&typeof A=="object"&&(x.metadata={...A}),t.push(x)}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=(s,i)=>{if(!i)return;let a=i.trim();if(!a||a.toLowerCase().startsWith("no error"))return;let c=`${s}:${a}`;n.has(c)||(n.add(c),t.push({type:"ADD",section:s,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),s;for(let i=0;i<r;i++){let a=await this.runReflector({example:e,generatorOutput:t,feedback:n,previousReflection:s});if(!a)break;s=a;let u=a.errorIdentification?.toLowerCase().trim()??"";if(a.metadata?.resolved===!0||u.length===0||u.startsWith("no error")||u.startsWith("resolved"))break}return s}async runReflector({example:e,generatorOutput:t,feedback:n,previousReflection:r}){let s=this.getOrCreateReflectorProgram(),i=this.teacherAI??this.studentAI;try{let a={severity:e?.severity,policyHint:e?.policyHint},l=(this.program?.getSignature()?.getInputFields()??[]).reduce((d,m)=>(m.name in e&&(d[m.name]=e[m.name]),d),{});return await s.forward(i,{question:JSON.stringify(l),generator_answer:JSON.stringify(t.answer),generator_reasoning:t.reasoning,playbook:JSON.stringify({markdown:gn(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 s=this.getOrCreateCuratorProgram(),i=this.teacherAI??this.studentAI,c=e.getSignature().getInputFields().reduce((l,p)=>(p.name in t&&(l[p.name]=t[p.name]),l),{});try{return await s.forward(i,{playbook:JSON.stringify({markdown:gn(r),structured:r}),reflection:JSON.stringify(n),question_context:JSON.stringify(c),token_budget:1024})}catch(l){this.verbose&&console.warn("[AxACE] Curator error:",l instanceof Error?l.message:l);return}}getOrCreateReflectorProgram(){if(!this.reflectorProgram){let e=fe().input("question",fe.string("Original task input serialized as JSON")).input("generator_answer",fe.string("Generator output serialized as JSON")).input("generator_reasoning",fe.string("Generator reasoning trace").optional()).input("playbook",fe.string("Current context playbook rendered as markdown")).input("expected_answer",fe.string("Expected output when ground truth is available").optional()).input("feedback",fe.string("External feedback or reward signal").optional()).input("previous_reflection",fe.string("Most recent reflection JSON when running multi-round refinement").optional()).output("reasoning",fe.string("Step-by-step analysis of generator performance")).output("errorIdentification",fe.string("Specific mistakes detected")).output("rootCauseAnalysis",fe.string("Underlying cause of the error")).output("correctApproach",fe.string("What the generator should do differently")).output("keyInsight",fe.string("Reusable insight to remember")).output("bulletTags",fe.json("Array of {id, tag} entries referencing playbook bullets")).build();this.reflectorProgram=it(e)}return this.reflectorProgram}getOrCreateCuratorProgram(){if(!this.curatorProgram){let e=fe().input("playbook",fe.string("Current playbook serialized as JSON")).input("reflection",fe.string("Latest reflection output serialized as JSON")).input("question_context",fe.string("Original task input serialized as JSON")).input("token_budget",fe.number("Approximate token budget for curator response").optional()).output("reasoning",fe.string("Justification for the proposed updates")).output("operations",fe.json("List of operations with type/section/content fields")).build();this.curatorProgram=it(e)}return this.curatorProgram}};function cp(o,e,t=0){let n=new Set([...Object.keys(o),...Object.keys(e)]),r=!0,s=!1;for(let i of n){let a=o[i]??0,u=e[i]??0;if(a+t<u){r=!1;break}a>u+t&&(s=!0)}return r&&s}function ro(o,e=0){let t=[];for(let n=0;n<o.length;n++){let r=0,s=!1;for(let i=0;i<o.length;i++)if(n!==i){if(cp(o[i].scores,o[n].scores,e)){s=!0;break}cp(o[n].scores,o[i].scores,e)&&r++}s||t.push({idx:o[n].idx,scores:o[n].scores,dominated:r})}return t}function or(o){if(o.length===0)return;let e=Object.keys(o[0]??{});if(e.length!==2)return;let[t,n]=e,r=[...o].sort((a,u)=>(u[t]??0)-(a[t]??0)),s=0,i=0;for(let a of r){let u=a[t]??0,c=a[n]??0,l=Math.max(c-i,0);s+=u*l,i=Math.max(i,c)}return s}function qa(o){if(o.length===0)return 0;let e=0;for(let t of o)e+=t;return e/o.length}function lp(o){let e={},t={};for(let r of o)for(let[s,i]of Object.entries(r))e[s]=(e[s]||0)+(typeof i=="number"?i:0),t[s]=(t[s]||0)+1;let n={};for(let[r,s]of Object.entries(e))n[r]=s/Math.max(t[r]||1,1);return n}function Ha(o,e){let t=new Set;for(let l of o)for(let p of l)t.add(p);let r=[...Array.from(t)].sort((l,p)=>(e[l]??0)-(e[p]??0)),s=new Set,i=(l,p)=>{for(let d of o){if(!d.has(l))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 l of r){if(s.has(l))continue;let p=new Set(r.filter(d=>d!==l&&!s.has(d)));if(i(l,p)){s.add(l),a=!0;break}}}let u=r.filter(l=>!s.has(l)),c=new Set(u);return o.map(l=>{let p=new Set;for(let d of l)c.has(d)&&p.add(d);return p})}function pp(o,e,t){let n=Ha(o,e),r={};for(let u of n)for(let c of u)r[c]=(r[c]||0)+1;let s=[];for(let[u,c]of Object.entries(r)){let l=Number(u);for(let p=0;p<c;p++)s.push(l)}if(s.length===0)return 0;let i=typeof t=="function"?t():Math.random(),a=Math.floor(i*s.length);return s[a]}function Mg(o){return o.size===0?{score:0}:Object.fromEntries([...o].map(e=>[e,0]))}function Ls(o,e=800){if(typeof o=="string"){let t=o.trim();return t.length<=e?t:`${t.slice(0,Math.max(0,e-3))}...`}try{let t=JSON.stringify(o,null,2).trim();return t.length<=e?t:`${t.slice(0,Math.max(0,e-3))}...`}catch{let t=String(o).trim();return t.length<=e?t:`${t.slice(0,Math.max(0,e-3))}...`}}var Xt=class o extends Tt{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 s=e?.crossoverEvery;this.crossoverEvery=Math.max(0,Math.floor(s??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 u=e?.mergeMax;this.mergeMax=Math.max(0,Math.floor(u??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 s=Date.now();this.validateExamples(t),r?.auto&&this.configureAuto(r.auto);let i=r?.maxMetricCalls;if(!Number.isFinite(i)||i<=0)throw new Error("AxGEPA: options.maxMetricCalls must be set to a positive integer");let a=Math.floor(i),u=r?.validationExamples,c=r?.feedbackExamples,l=(u&&u.length>0?u:t).slice(0,this.paretoSetSize),p=G=>{let J=Object.keys(G).sort().reduce((Y,le)=>(Y[le]=G[le],Y),{});return JSON.stringify(J)},d=new Set(t.map(G=>p(G))),m=c&&c.length>0?c.filter(G=>d.has(p(G))):t,g=m.length>0?m:t,f=this.getInstructionTargets(e);if(f.length===0)throw new Error("AxGEPA: program has no instruction-bearing nodes to optimize");let x=f.map(G=>G.id),A=G=>{for(let J of f){let Y=G[J.id];typeof Y=="string"&&J.program.setInstruction?.(Y)}},h=async(G,J)=>{let Y=await n({prediction:G,example:J});if(typeof Y=="number")return Number.isFinite(Y)?{score:Y}:{};if(!Y||typeof Y!="object")return{};let le={};for(let[H,q]of Object.entries(Y))typeof q=="number"&&Number.isFinite(q)&&(le[H]=q);return le},y=G=>{let J=r?.paretoMetricKey,Y=r?.paretoScalarize;if(typeof Y=="function")return Y(G);if(J)return Number.isFinite(G[J])?G[J]:0;let le=Object.values(G);return le.length?le.reduce((H,q)=>H+q,0)/le.length:0},C=this.getOptimizerLogger(r),I=r?.verbose??this.verbose?G=>console.log(`[GEPA] ${G}`):G=>{},R=new Set,M=async(G,J,Y,le=!1)=>{let H=J.length;if(this.stats.totalCalls+H>a){if(le)throw new Error(`AxGEPA: options.maxMetricCalls=${a} is too small to evaluate the initial Pareto set; need at least ${H} metric calls`);return}let q=[];I(`${Y}: evaluating ${J.length} example${J.length===1?"":"s"}`);for(let[re,Ce]of J.entries()){A(G);let we,ue;try{we=await e.forward(this.studentAI,Ce,{sampleCount:this.sampleCount}),ue=await h(we,Ce);for(let ae of Object.keys(ue))R.add(ae)}catch(ae){let de=ae instanceof Error?ae.message:String(ae);we={error:de},ue=Mg(R),I(`Evaluation failed during ${Y}; scoring this example as zero. Error: ${de}`)}this.stats.totalCalls+=1;let Te=y(ue);q.push({input:Ce,prediction:we,scores:ue,scalar:Te}),I(`${Y}: completed ${re+1}/${J.length} (score=${Te.toFixed(3)})`)}return{rows:q,avg:lp(q.map(re=>re.scores)),scalars:q.map(re=>re.scalar),sum:q.reduce((re,Ce)=>re+Ce.scalar,0)}},T={};for(let G of f)T[G.id]=await this.getBaseInstruction(G.program);let O=await M(T,l,"initial Pareto evaluation",!0),E=[{cfg:{...T},parent:void 0,scores:O.avg}],$=[O.scalars];C?.({name:"OptimizationStart",value:{optimizerType:"GEPA",exampleCount:t.length,validationCount:l.length,config:{numTrials:this.numTrials,minibatch:this.minibatch,mergeMax:this.mergeMax,tunableCount:f.length}}}),I(`Starting GEPA optimization: ${t.length} train, ${l.length} validation, maxCalls=${a}`);let N=0,S=new Set,v=ro(E.map((G,J)=>({idx:J,scores:G.scores})),this.tieEpsilon).map(G=>G.idx),P;for(let G=0;G<this.numTrials&&!(a!==void 0&&this.stats.totalCalls>=Math.max(1,Math.floor(a)));G++){let J=$[0]?.length??0,Y=[];for(let me=0;me<J;me++){let De=Number.NEGATIVE_INFINITY,Ve=new Set;for(let Ye=0;Ye<$.length;Ye++){let ut=$[Ye][me];ut>De+this.tieEpsilon?(De=ut,Ve.clear(),Ve.add(Ye)):Math.abs(ut-De)<=this.tieEpsilon&&Ve.add(Ye)}Y.push(Ve)}let le=$.map(me=>qa(me));if(this.mergeMax>0&&this.mergesDue>0&&this.lastIterFoundNewProgram){let me=k=>{let _=[],w=k;for(;w!==void 0;)_.push(w),w=E[w]?.parent;return _},De=k=>k.length?k[Math.floor(this.rand()*k.length)]:void 0,Ve=Ha(Y,le),Ye=new Set;for(let k of Ve)for(let _ of k)Ye.add(_);let ut=Array.from(Ye),b;for(let k=0;k<10&&!b&&!(ut.length<2);k++){let _=De(ut),w=De(ut);if(_===w)continue;w<_&&([_,w]=[w,_]);let B=new Set(me(_)),Q=new Set(me(w));if(B.has(w)||Q.has(_))continue;let ne=[...B].filter(se=>Q.has(se));if(ne.length===0)continue;let Z=[];for(let se of ne){let Re=E[se].cfg,Ue=E[_].cfg,Ie=E[w].cfg,qe=!1,Ne=new Set([...Object.keys(Re),...Object.keys(Ue),...Object.keys(Ie)]);for(let nt of Ne){let oe=Re[nt],ee=Ue[nt],ye=Ie[nt];if(ee===oe&&ye!==ee||ye===oe&&ee!==ye){qe=!0;break}}qe&&Z.push(se)}if(Z.length===0)continue;let D=Z.map(se=>Math.max(1e-9,le[se])),V=this.rand()*D.reduce((se,Re)=>se+Re,0),ie=Z[Z.length-1];for(let se=0;se<Z.length;se++){if(V<D[se]){ie=Z[se];break}V-=D[se]}b={i:_,j:w,a:ie}}if(this.lastIterFoundNewProgram=!1,b){let k=!1,{i:_,j:w,a:B}=b,Q=le[B],ne=le[_],Z=le[w];if(Q>Math.min(ne,Z))continue;let D=`${_}|${w}|${B}`;if(this.mergeAttemptKeys.has(D)||(this.mergeAttemptKeys.add(D),S.has(D)))continue;let{cfg:V,descSig:ie}=this.systemAwareMergeWithSig(E,_,w,(ve,Xe)=>le[ve]>=le[Xe]?ve:Xe),se=`${Math.min(_,w)}|${Math.max(_,w)}|${ie}`;if(this.mergeCompositionKeys.has(se))continue;this.mergeCompositionKeys.add(se);let Re=$[_],Ue=$[w],Ie=Array.from({length:Re.length},(ve,Xe)=>Xe),qe=Ie.filter(ve=>(Re[ve]??0)>(Ue[ve]??0)),Ne=Ie.filter(ve=>(Ue[ve]??0)>(Re[ve]??0)),nt=Ie.filter(ve=>!(qe.includes(ve)||Ne.includes(ve))),oe=5,ee=Math.ceil(oe/3),ye=(ve,Xe)=>{if(Xe<=0||ve.length===0)return[];if(ve.length<=Xe)return[...ve];let xr=[],Ao=new Set;for(;xr.length<Xe;){let wt=Math.floor(this.rand()*ve.length);Ao.has(wt)||(Ao.add(wt),xr.push(ve[wt]))}return xr},Oe=[];Oe.push(...ye(qe,Math.min(ee,qe.length))),Oe.push(...ye(Ne,Math.min(ee,Ne.length)));let Pe=oe-Oe.length;Oe.push(...ye(nt,Math.max(0,Pe)));let We=oe-Oe.length;if(We>0){let ve=Ie.filter(Xe=>!Oe.includes(Xe));Oe.push(...ye(ve,Math.min(We,ve.length)))}let en=Oe.slice(0,Math.min(oe,Ie.length)),ci=en.map(ve=>l[ve]),tn=await M(V,ci,"merge subsample");if(!tn)break;let nn=tn.sum,xo=en.reduce((ve,Xe)=>ve+(Re[Xe]??0),0),Cu=en.reduce((ve,Xe)=>ve+(Ue[Xe]??0),0);if(nn>=Math.max(xo,Cu)+this.minImprovementThreshold){I(`Iteration ${G+1}: Merge accepted (programs ${_} + ${w} via ancestor ${B})`);let ve=await M(V,l,"merge validation");if(!ve)break;E.push({cfg:{...V},parent:B,scores:ve.avg}),$.push(ve.scalars);let Xe=v.length,xr=or(v.map(wt=>E[wt].scores))??0;v=ro(E.map((wt,vd)=>({idx:vd,scores:wt.scores})),this.tieEpsilon).map(wt=>wt.idx);let Ao=or(v.map(wt=>E[wt].scores))??0;(v.length>Xe||Ao>xr+1e-6)&&(N=0),this.mergesDue-=1,this.totalMergesTested+=1,S.add(D),k=!0}if(k)continue}}let H=pp(Y,le,()=>this.rand());this.lastIterFoundNewProgram=!1;let q=this.minibatch?this.nextMinibatchIndices(g.length,G).map(me=>g[me]):g,re=await M(E[H].cfg,q,"parent minibatch");if(!re)break;if(r?.skipPerfectScore??!0){let me=Number(r?.perfectScore??1);if(re.scalars.length>0&&re.scalars.every(De=>De>=me))continue}let Ce={...E[H].cfg},we="reflective_mutation",ue,Te,ae=f[G%f.length],de=E[H].cfg[ae.id],X=r?.gepaAdapter,te,Ae=re.rows.map(me=>({input:me.input,prediction:me.prediction,score:me.scalar}));if(X)try{let me=await X.evaluate(q,{...E[H].cfg},!0);ue=Array.isArray(me?.scores)?me.scores.reduce((ut,b)=>ut+(Number(b)||0),0):void 0;let De=X.make_reflective_dataset({...E[H].cfg},me,[ae.id]),Ve=await X.propose_new_texts?.({...E[H].cfg},De,[ae.id]),Ye=Ve?.[ae.id]??(Ve?Object.values(Ve)[0]:void 0);typeof Ye=="string"&&Ye.length>0&&(te=Ye)}catch{}if(te||(te=await this.reflectTargetInstruction(ae.id,de,e,A,{...E[H].cfg},q,async({prediction:me,example:De})=>y(await h(me,De)),r,Ae)),Ce[ae.id]=te,X&&ue!==void 0)try{let me=await X.evaluate(q,Ce,!1);Te=Array.isArray(me?.scores)?me.scores.reduce((De,Ve)=>De+(Number(Ve)||0),0):void 0}catch{}let Se=await M(Ce,q,"child minibatch");if(!Se)break;if(this.currentRound=G+1,await this.updateOptimizationProgress(this.currentRound,Se.sum,{instructionLen:te.length,target:ae.id,parent:H,totalRounds:this.numTrials},"GEPA",{strategy:we,paretoSetSize:l.length,tunableCount:f.length},Se.sum,{instructionLen:de.length,idx:H},{...r??{},maxIterations:this.numTrials}),!(Se.sum>re.sum+this.minImprovementThreshold&&(ue===void 0||Te===void 0||Te>ue+this.minImprovementThreshold))){if(I(`Iteration ${G+1}: Rejected (child=${Se.sum.toFixed(3)} <= parent=${re.sum.toFixed(3)})`),++N>=this.earlyStoppingTrials){I(`Early stopping: ${N} iterations without improvement`);break}continue}I(`Iteration ${G+1}: Accepted (child=${Se.sum.toFixed(3)} > parent=${re.sum.toFixed(3)})`);let Le=await M(Ce,l,"validation evaluation");if(!Le)break;E.push({cfg:{...Ce},parent:H,scores:Le.avg}),$.push(Le.scalars);let at=v.length,Ee=or(v.map(me=>E[me].scores))??0;v=ro(E.map((me,De)=>({idx:De,scores:me.scores})),this.tieEpsilon).map(me=>me.idx);let ze=or(v.map(me=>E[me].scores))??0;if(v.length>at||ze>Ee+1e-6)N=0,I(`Iteration ${G+1}: Archive improved (size=${v.length}, hv=${ze.toFixed(4)})`);else if(N++,I(`Iteration ${G+1}: Archive unchanged (stagnation=${N}/${this.earlyStoppingTrials})`),N>=this.earlyStoppingTrials){I(`Early stopping: ${N} iterations without archive improvement`);break}this.lastIterFoundNewProgram=!0,this.mergeMax>0&&this.totalMergesTested<this.mergeMax&&(this.mergesDue+=1)}let F=ro(E.map((G,J)=>({idx:J,scores:G.scores})),this.tieEpsilon),U=F.length>0?Math.max(...F.map(G=>y(G.scores))):0,L;if(F.length>0){let G=Number.NEGATIVE_INFINITY;for(let J of F){let Y=y(J.scores);Y>G&&(G=Y,L=J.idx)}}let z=or(F.map(G=>G.scores));this.stats.convergenceInfo.converged=!0;let j=this.getMergedCustomLabels(r);this.recordParetoMetrics(F.length,E.length,"GEPA",z,j);let K=Date.now()-s,W=typeof L=="number"?new It({bestScore:U,stats:this.stats,instruction:f.length===1?E[L].cfg[x[0]]:void 0,instructionMap:{...E[L].cfg},demos:[],examples:t,modelConfig:void 0,optimizerType:"GEPA",optimizationTime:K,totalRounds:this.numTrials,converged:this.stats.convergenceInfo.converged}):void 0,pe=this.generateOptimizationReport(F,z,U,E.length);return{demos:[],stats:this.stats,bestScore:U,paretoFront:F.map(G=>({demos:[],scores:G.scores,configuration:{candidate:G.idx,instructionMap:{...E[G.idx].cfg},...f.length===1?{instruction:E[G.idx].cfg[x[0]]}:{}},dominatedSolutions:G.dominated})),paretoFrontSize:F.length,hypervolume:z,finalConfiguration:{strategy:"gepa",candidates:E.length,tunables:f.length},optimizedProgram:W,report:pe}}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."}getInstructionTargets(e){let t=new Set,n=[],r=(s,i)=>{let a=i;!s||t.has(s)||typeof a?.setInstruction!="function"||(t.add(s),n.push({id:s,program:a,signature:a.getSignature?.()?.toString?.()}))};if("namedProgramInstances"in e&&typeof e.namedProgramInstances=="function"){let s=e.namedProgramInstances()??[];for(let i of s)r(i?.id,i?.program)}return r(e.getId?.(),e),n}async evaluateOnSet(e,t,n,r){let s=[];for(let i of n){let a=await this.evaluateOne(e,t,i,r);s.push(a)}return s}async evaluateAvg(e,t,n,r){let s=await this.evaluateOnSet(e,t,n,r);return s.length>0?qa(s):0}async evaluateOne(e,t,n,r){try{e.setInstruction?.(t);let s=await e.forward(this.studentAI,n,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let i=await r({prediction:s,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(s){return this.getLogger()?.({name:"Notification",id:"gepa_eval",value:String(s)}),0}}async reflectTargetInstruction(e,t,n,r,s,i,a,u,c){let l=c?[...c]:[];if(l.length===0)for(let h of i)try{s[e]=t,r(s);let y=await n.forward(this.studentAI,h,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let C=await a({prediction:y,example:h});l.push({input:h,prediction:y,score:typeof C=="number"?C:0})}catch{l.push({input:h,prediction:{},score:0})}let p=u?.overrideTeacherAI??this.teacherAI??this.studentAI,d=it('targetId:string "Target program ID", minibatch:json "Array of {input,prediction,score}", evalFeedback?:string[] "Evaluator feedback when available" -> feedbackSummary:string "Concise program-focused feedback"'),g=[...(u?.feedbackNotes??[]).filter(h=>typeof h=="string"&&h.trim().length>0)],f=u?.feedbackFn;if(typeof f=="function")for(let h of l){let y=f({prediction:h.prediction,example:h.input,componentId:e});y&&(Array.isArray(y)?g.push(...y):g.push(y))}let x="";try{x=(await d.forward(p,{targetId:e,minibatch:l,evalFeedback:g}))?.feedbackSummary?.trim()||""}catch{}let A=it('targetId:string "Target program ID", currentInstruction:string "Current instruction", feedbackSummary?:string "Summarized feedback", minibatch:json "Array of {input,prediction,score}" -> newInstruction:string "Improved instruction (1-6 sentences) for the target program"');try{let y=(await A.forward(p,{targetId:e,currentInstruction:t,feedbackSummary:x,minibatch:l}))?.newInstruction?.trim();if(y&&y.length>16)return y}catch{}return`${t.trim()} Focus on step-by-step, target-specific reasoning and factual grounding.`.slice(0,2e3)}async reflectInstruction(e,t,n,r,s,i){let a=i??[];if(a.length===0)for(let f of n)try{t.setInstruction?.(e);let x=await t.forward(this.studentAI,f,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let A=await r({prediction:x,example:f});a.push({input:f,prediction:x,score:typeof A=="number"?A:0})}catch{a.push({input:f,prediction:{},score:0})}let u=s?.overrideTeacherAI??this.teacherAI??this.studentAI,c=typeof t?.getId=="function"?t.getId():void 0,l=s?.feedbackFn,p=(s?.feedbackNotes??[]).filter(f=>typeof f=="string"&&f.trim().length>0),d=()=>{let f=[];for(let A=0;A<a.length;A++){let h=a[A],y=`# Example ${A+1}
867
867
  `;if(y+=`## Inputs
868
- `,typeof h.input=="object"&&h.input!==null)for(let[C,R]of Object.entries(h.input))y+=`### ${C}
869
- ${$s(R)}
868
+ `,typeof h.input=="object"&&h.input!==null)for(let[I,R]of Object.entries(h.input))y+=`### ${I}
869
+ ${Ls(R)}
870
870
 
871
- `;else y+=`${$s(h.input)}
871
+ `;else y+=`${Ls(h.input)}
872
872
 
873
873
  `;if(y+=`## Generated Outputs
874
- `,typeof h.prediction=="object"&&h.prediction!==null)for(let[C,R]of Object.entries(h.prediction))y+=`### ${C}
875
- ${$s(R)}
874
+ `,typeof h.prediction=="object"&&h.prediction!==null)for(let[I,R]of Object.entries(h.prediction))y+=`### ${I}
875
+ ${Ls(R)}
876
876
 
877
- `;else y+=`${$s(h.prediction)}
877
+ `;else y+=`${Ls(h.prediction)}
878
878
 
879
879
  `;y+=`## Feedback
880
- `;let T=`This trajectory got a score of ${h.score.toFixed(3)}.`;if(typeof l=="function")try{let C=l({prediction:h.prediction,example:h.input,componentId:c});C&&(T=Array.isArray(C)?C.join(`
881
- `):C)}catch{}y+=`${T}
880
+ `;let C=`This trajectory got a score of ${h.score.toFixed(3)}.`;if(typeof l=="function")try{let I=l({prediction:h.prediction,example:h.input,componentId:c});I&&(C=Array.isArray(I)?I.join(`
881
+ `):I)}catch{}y+=`${C}
882
882
  `,f.push(y)}return[...p.map((A,h)=>`# Additional Feedback ${h+1}
883
883
  ${A}`),...f].join(`
884
884
 
885
- `)},m=o.REFLECTION_PROMPT_TEMPLATE.replace("<curr_instructions>",e).replace("<inputs_outputs_feedback>",d());try{let f=await u.chat({chatPrompt:[{role:"user",content:m}],model:s?.reflectionModel},{stream:!1});if(typeof f.getReader=="function")throw new Error("Streaming response not expected for reflection");let A=f.results?.[0]?.content;if(typeof A=="string"){let h=this.extractInstructionFromBackticks(A);if(h&&h.length>16){let y=`Iteration feedback: ${a.map(T=>`score=${T.score.toFixed(2)}`).join(", ")}`;return this.feedbackMemory.unshift(y),this.feedbackMemory.length>this.feedbackMemorySize&&this.feedbackMemory.pop(),h}}}catch{}let g=it('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 x=(await g.forward(u,{currentInstruction:e,feedbackSummary:this.feedbackMemory[0]||"",recentFeedback:this.feedbackMemory,minibatch:a}))?.newInstruction?.trim();if(x&&x.length>16)return x}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),s=r.match(/^\S*\n/);return s&&(r=r.slice(s[0].length)),r.trim()}updateSamplerShuffled(e){let t=Array.from({length:e},(u,c)=>c);for(let u=t.length-1;u>0;u--){let c=Math.floor(this.rand()*(u+1));[t[u],t[c]]=[t[c],t[u]]}for(let u of t)this.samplerState.freq.set(u,(this.samplerState.freq.get(u)??0)+1);let n=this.minibatchSize,r=e%n,s=r===0?0:n-r,i=Array.from({length:e},(u,c)=>c).sort((u,c)=>(this.samplerState.freq.get(u)??0)-(this.samplerState.freq.get(c)??0)),a=[...t];for(let u=0;u<s;u++){let c=i[u%i.length];a.push(c),this.samplerState.freq.set(c,(this.samplerState.freq.get(c)??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)),s=Math.floor(t/r);for(;s>=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}systemAwareMergeWithSig(e,t,n,r){let s=x=>{let A=[],h=x;for(;h!==void 0;)A.push(h),h=e[h]?.parent;return A},i=s(t),a=s(n),c=i.find(x=>a.includes(x))??t,l=e[c].cfg,p=e[t].cfg,d=e[n].cfg,m={},g=[],f=Array.from(new Set([...Object.keys(l),...Object.keys(p),...Object.keys(d)])).sort();for(let x of f){let A=l[x],h=p[x],y=d[x];if(h===A&&y!==h)m[x]=y,g.push("j");else if(y===A&&h!==y)m[x]=h,g.push("i");else if(h!==y&&h!==A&&y!==A){let T=r(t,n);m[x]=T===t?h:y,g.push(T===t?"i":"j")}else m[x]=h??y??A,g.push("i")}return{cfg:m,descSig:g.join("|")}}generateOptimizationReport(e,t,n,r){let s=e.length>0?e.reduce((l,p)=>{let d=Object.values(l.scores).reduce((g,f)=>g+f,0);return Object.values(p.scores).reduce((g,f)=>g+f,0)>d?p:l}):void 0,i={};if(s)for(let[l,p]of Object.entries(s.scores))i[l]={value:p,percentage:p*100};let a=[];if(e.length>1){let l=[...e].sort((p,d)=>d.dominated-p.dominated).slice(0,3);for(let p of l)a.push({...p.scores})}let u="good",c=[];if(e.length===1)u="single",c.push("Increase numTrials (current seems low)"),c.push("Add more training examples"),c.push("Adjust earlyStoppingTrials");else if(e.length<3)u="limited",c.push("More optimization trials"),c.push("Larger validation set");else{u="good";let l=Object.keys(e[0]?.scores||{});for(let p of l)c.push(`High ${p}: Choose solution with best ${p} score`);c.push("Balanced: Use provided bestScore (average)")}return this.stats.totalCalls<50&&(c.push("Quick run detected - use numTrials: 30+ for production"),c.push("Provide 50+ training examples"),c.push("Use 20+ validation examples")),{summary:"GEPA Multi-Objective Optimization Complete",bestSolution:{overallScore:n??0,objectives:i},paretoFrontier:{solutionCount:e.length,objectiveSpaceCoverage:(t??0)*100,hypervolume:t??0,tradeoffs:a.length>0?a:void 0},statistics:{totalEvaluations:this.stats.totalCalls,candidatesExplored:r,converged:this.stats.convergenceInfo?.converged??!1},recommendations:{status:u,suggestions:c}}}async mergeInstructions(e,t,n){let r=n?.overrideTeacherAI??this.teacherAI??this.studentAI,s=it(`instructionA:string "Parent A instruction",
885
+ `)},m=o.REFLECTION_PROMPT_TEMPLATE.replace("<curr_instructions>",e).replace("<inputs_outputs_feedback>",d());try{let f=await u.chat({chatPrompt:[{role:"user",content:m}],model:s?.reflectionModel},{stream:!1});if(typeof f.getReader=="function")throw new Error("Streaming response not expected for reflection");let A=f.results?.[0]?.content;if(typeof A=="string"){let h=this.extractInstructionFromBackticks(A);if(h&&h.length>16){let y=`Iteration feedback: ${a.map(C=>`score=${C.score.toFixed(2)}`).join(", ")}`;return this.feedbackMemory.unshift(y),this.feedbackMemory.length>this.feedbackMemorySize&&this.feedbackMemory.pop(),h}}}catch{}let g=it('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 x=(await g.forward(u,{currentInstruction:e,feedbackSummary:this.feedbackMemory[0]||"",recentFeedback:this.feedbackMemory,minibatch:a}))?.newInstruction?.trim();if(x&&x.length>16)return x}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),s=r.match(/^\S*\n/);return s&&(r=r.slice(s[0].length)),r.trim()}updateSamplerShuffled(e){let t=Array.from({length:e},(u,c)=>c);for(let u=t.length-1;u>0;u--){let c=Math.floor(this.rand()*(u+1));[t[u],t[c]]=[t[c],t[u]]}for(let u of t)this.samplerState.freq.set(u,(this.samplerState.freq.get(u)??0)+1);let n=this.minibatchSize,r=e%n,s=r===0?0:n-r,i=Array.from({length:e},(u,c)=>c).sort((u,c)=>(this.samplerState.freq.get(u)??0)-(this.samplerState.freq.get(c)??0)),a=[...t];for(let u=0;u<s;u++){let c=i[u%i.length];a.push(c),this.samplerState.freq.set(c,(this.samplerState.freq.get(c)??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)),s=Math.floor(t/r);for(;s>=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}systemAwareMergeWithSig(e,t,n,r){let s=x=>{let A=[],h=x;for(;h!==void 0;)A.push(h),h=e[h]?.parent;return A},i=s(t),a=s(n),c=i.find(x=>a.includes(x))??t,l=e[c].cfg,p=e[t].cfg,d=e[n].cfg,m={},g=[],f=Array.from(new Set([...Object.keys(l),...Object.keys(p),...Object.keys(d)])).sort();for(let x of f){let A=l[x],h=p[x],y=d[x];if(h===A&&y!==h)m[x]=y,g.push("j");else if(y===A&&h!==y)m[x]=h,g.push("i");else if(h!==y&&h!==A&&y!==A){let C=r(t,n);m[x]=C===t?h:y,g.push(C===t?"i":"j")}else m[x]=h??y??A,g.push("i")}return{cfg:m,descSig:g.join("|")}}generateOptimizationReport(e,t,n,r){let s=e.length>0?e.reduce((l,p)=>{let d=Object.values(l.scores).reduce((g,f)=>g+f,0);return Object.values(p.scores).reduce((g,f)=>g+f,0)>d?p:l}):void 0,i={};if(s)for(let[l,p]of Object.entries(s.scores))i[l]={value:p,percentage:p*100};let a=[];if(e.length>1){let l=[...e].sort((p,d)=>d.dominated-p.dominated).slice(0,3);for(let p of l)a.push({...p.scores})}let u="good",c=[];if(e.length===1)u="single",c.push("Increase numTrials (current seems low)"),c.push("Add more training examples"),c.push("Adjust earlyStoppingTrials");else if(e.length<3)u="limited",c.push("More optimization trials"),c.push("Larger validation set");else{u="good";let l=Object.keys(e[0]?.scores||{});for(let p of l)c.push(`High ${p}: Choose solution with best ${p} score`);c.push("Balanced: Use provided bestScore (average)")}return this.stats.totalCalls<50&&(c.push("Quick run detected - use numTrials: 30+ for production"),c.push("Provide 50+ training examples"),c.push("Use 20+ validation examples")),{summary:"GEPA Multi-Objective Optimization Complete",bestSolution:{overallScore:n??0,objectives:i},paretoFrontier:{solutionCount:e.length,objectiveSpaceCoverage:(t??0)*100,hypervolume:t??0,tradeoffs:a.length>0?a:void 0},statistics:{totalEvaluations:this.stats.totalCalls,candidatesExplored:r,converged:this.stats.convergenceInfo?.converged??!1},recommendations:{status:u,suggestions:c}}}async mergeInstructions(e,t,n){let r=n?.overrideTeacherAI??this.teacherAI??this.studentAI,s=it(`instructionA:string "Parent A instruction",
886
886
  instructionB:string "Parent B instruction",
887
887
  recentFeedback?:string[] "Past feedback memory"
888
- -> mergedInstruction:string "Merged instruction (1-6 sentences) combining strengths, fixing weaknesses"`);try{let a=(await s.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 pp(o){return o.map(e=>{let t=e.type?.name??"string",n=e.type?.isArray?"[]":"",r=e.isOptional?" (optional)":"",s=e.description?`: ${e.description}`:"";return`- ${e.name}: ${t}${n}${r}${s}`}).join(`
889
- `)}function Og(o){return o.map(e=>{let t=e.type?.name??"string",n=e.type?.isArray?"[]":"",r=e.type?.options?` (options: ${e.type.options.join(", ")})`:"",s=e.description?`: ${e.description}`:"";return`- ${e.name}: ${t}${n}${r}${s}`}).join(`
890
- `)}var or=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),s=[],i=0,a=0;for(let u=0;u<e;u+=r){let c=Math.min(r,e-u),l=await this.generateInputs(c);for(let p of l){a++;try{let d=await this.labelInput(p);s.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 u=await this.generateEdgeCaseInputs(Math.ceil(e*.2));for(let c of u){a++;try{let l=await this.labelInput(c);s.push({input:c,expected:l,category:"edge_case"}),i++}catch(l){console.warn("AxSynth: Failed to label edge case input:",l)}}}return{examples:s,stats:{requested:e,generated:s.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(),s=`
888
+ -> mergedInstruction:string "Merged instruction (1-6 sentences) combining strengths, fixing weaknesses"`);try{let a=(await s.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 dp(o){return o.map(e=>{let t=e.type?.name??"string",n=e.type?.isArray?"[]":"",r=e.isOptional?" (optional)":"",s=e.description?`: ${e.description}`:"";return`- ${e.name}: ${t}${n}${r}${s}`}).join(`
889
+ `)}function Pg(o){return o.map(e=>{let t=e.type?.name??"string",n=e.type?.isArray?"[]":"",r=e.type?.options?` (options: ${e.type.options.join(", ")})`:"",s=e.description?`: ${e.description}`:"";return`- ${e.name}: ${t}${n}${r}${s}`}).join(`
890
+ `)}var sr=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),s=[],i=0,a=0;for(let u=0;u<e;u+=r){let c=Math.min(r,e-u),l=await this.generateInputs(c);for(let p of l){a++;try{let d=await this.labelInput(p);s.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 u=await this.generateEdgeCaseInputs(Math.ceil(e*.2));for(let c of u){a++;try{let l=await this.labelInput(c);s.push({input:c,expected:l,category:"edge_case"}),i++}catch(l){console.warn("AxSynth: Failed to label edge case input:",l)}}}return{examples:s,stats:{requested:e,generated:s.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(),s=`
891
891
  You are generating realistic input data for an AI system.
892
892
 
893
893
  ${r?`Task description: ${r}`:""}
894
894
  ${this.options.domain?`Domain: ${this.options.domain}`:""}
895
895
 
896
896
  The system expects these INPUT fields:
897
- ${pp(t)}
897
+ ${dp(t)}
898
898
 
899
899
  The system produces these OUTPUT fields:
900
- ${Og(n)}
900
+ ${Pg(n)}
901
901
 
902
902
  Generate ${e} diverse, realistic input examples as a JSON array.
903
903
  Each example should be an object with the input fields defined above.
@@ -908,7 +908,7 @@ Output ONLY the JSON array, no explanation.
908
908
  You are generating challenging edge case input data to test an AI system's robustness.
909
909
 
910
910
  The system expects these INPUT fields:
911
- ${pp(t)}
911
+ ${dp(t)}
912
912
 
913
913
  Generate ${e} edge case examples as a JSON array.
914
914
  Focus on these types of edge cases:
@@ -916,7 +916,7 @@ ${n.map(i=>`- ${i}`).join(`
916
916
  `)}
917
917
 
918
918
  Output ONLY the JSON array, no explanation.
919
- `.trim(),s=new Me("count:number -> examples:json");s.setInstruction(r);try{let i=await s.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 Me(this.signature).forward(this.options.teacher,e,{model:this.options.model})}getSignature(){return this.signature}getTeacher(){return this.options.teacher}};var Eg={excellent:1,good:.8,acceptable:.5,poor:.2,unacceptable:0};function Mg(o){let{ai:e,criteria:t,description:n,randomizeOrder:r,...s}=o;return{...s,maxSteps:1}}function Pg(o){if(o==null)return!1;if(typeof o=="string"||typeof o=="number"||typeof o=="boolean"||Array.isArray(o)&&o.every(e=>typeof e!="object"))return!0;if(typeof o=="object"){let e=Object.values(o);return e.length>0&&e.every(t=>t==null?!1:typeof t=="string"||typeof t=="number"||typeof t=="boolean"?!0:Array.isArray(t)?t.every(n=>typeof n!="object"):!1)}return!1}function Fg(o,e){return o===e?!0:typeof o!=typeof e?!1:typeof o=="object"&&o!==null&&e!==null?JSON.stringify(o)===JSON.stringify(e):!1}function _g(o,e,t){let n=o.getOutputFields(),r=0,s=0;for(let i of n){let a=e[i.name],u=t[i.name];u!==void 0&&(s+=1,Fg(a,u)&&(r+=1))}return s>0?r/s:0}function Ng(o,e){let t=new Me(`
919
+ `.trim(),s=new Me("count:number -> examples:json");s.setInstruction(r);try{let i=await s.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 Me(this.signature).forward(this.options.teacher,e,{model:this.options.model})}getSignature(){return this.signature}getTeacher(){return this.options.teacher}};var Fg={excellent:1,good:.8,acceptable:.5,poor:.2,unacceptable:0};function _g(o){let{ai:e,criteria:t,description:n,randomizeOrder:r,...s}=o;return{...s,maxSteps:1}}function Ng(o){if(o==null)return!1;if(typeof o=="string"||typeof o=="number"||typeof o=="boolean"||Array.isArray(o)&&o.every(e=>typeof e!="object"))return!0;if(typeof o=="object"){let e=Object.values(o);return e.length>0&&e.every(t=>t==null?!1:typeof t=="string"||typeof t=="number"||typeof t=="boolean"?!0:Array.isArray(t)?t.every(n=>typeof n!="object"):!1)}return!1}function $g(o,e){return o===e?!0:typeof o!=typeof e?!1:typeof o=="object"&&o!==null&&e!==null?JSON.stringify(o)===JSON.stringify(e):!1}function Lg(o,e,t){let n=o.getOutputFields(),r=0,s=0;for(let i of n){let a=e[i.name],u=t[i.name];u!==void 0&&(s+=1,$g(a,u)&&(r+=1))}return s>0?r/s:0}function Dg(o,e){let t=new Me(`
920
920
  task_input:string "The original task input encoded as JSON",
921
921
  task_description?:string "Optional task description from the program signature",
922
922
  criteria?:string "Optional evaluation guidance",
@@ -933,11 +933,11 @@ Output ONLY the JSON array, no explanation.
933
933
  ->
934
934
  reasoning:string "Short explanation of which output is better",
935
935
  winner:class "A, B, Tie" "Which output is better overall"
936
- `),r=e.description?.trim();r&&(t.setInstruction(r),n.setInstruction(r));let s=Mg(e),i=o.getDescription();return async({example:a,prediction:u})=>{let c={};for(let g of o.getInputFields())g.name in a&&(c[g.name]=a[g.name]);let l={},p=!1;for(let g of o.getOutputFields())g.name in a&&(l[g.name]=a[g.name],p=!0);let d=u;if(p&&Pg(l))return _g(o,d,l);if(p){let f=e.randomizeOrder??!0?Math.random()>.5:!0,A=(await n.forward(e.ai,{task_input:JSON.stringify(c),task_description:i,criteria:e.criteria,system_output_a:JSON.stringify(f?d:l),system_output_b:JSON.stringify(f?l:d)},s)).winner.toUpperCase();return A==="TIE"?.5:A==="A"?f?1:0:A==="B"?f?0:1:.5}let m=await t.forward(e.ai,{task_input:JSON.stringify(c),task_description:i,criteria:e.criteria,system_output:JSON.stringify(d)},s);return Eg[m.quality.toLowerCase()]??.5}}var Lg="batch",qa={feedbackWindowSize:25,maxRecentTraces:100,updateBudget:4},Ds=class o{gen;options;tracer;currentScore;currentState;readyPromise;playbookOptimizer;constructor(e,t){this.gen=e,this.options={...t,enableTracing:t.enableTracing??!0,mode:t.mode??Lg,continuousOptions:{feedbackWindowSize:t.continuousOptions?.feedbackWindowSize??qa.feedbackWindowSize,maxRecentTraces:t.continuousOptions?.maxRecentTraces??qa.maxRecentTraces,updateBudget:t.continuousOptions?.updateBudget??qa.updateBudget}},this.tracer=new tr(e,{name:this.options.name,storage:this.options.storage,metadata:this.options.metadata,onTrace:this.options.onTrace}),this.readyPromise=this.loadLatestCheckpoint()}async ready(){await this.readyPromise}async forward(e,t,n){return await this.ready(),this.options.enableTracing?this.tracer.forward(e,t,n):this.gen.forward(e,t,n)}async*streamingForward(e,t,n){await this.ready(),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.currentState?.mode==="playbook"||this.options.mode==="playbook"?this.currentState?.instruction??this.gen.getSignature().getDescription()??this.gen.getInstruction():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 o(this.gen.clone(),this.options)}async optimize(e={}){await this.ready();let t=this.mergeConfig(e);return t.mode==="playbook"?this.optimizePlaybook(t):(await this.runPromptOptimization(t)).result}async applyUpdate(e,t={}){await this.ready();let n=this.mergeConfig(t),r=n.mode==="continuous"?{...n,budget:t.budget??n.continuousOptions.updateBudget}:n;if(r.mode==="batch")throw new Error("AxLearn: applyUpdate() is only available in continuous or playbook modes");return r.mode==="playbook"?this.applyPlaybookUpdate(r,e):(await this.runPromptOptimization(r,e)).result}getGen(){return this.gen}getStorage(){return this.options.storage}async getTraces(e){return await this.ready(),this.options.storage.load(this.options.name,{type:"trace",...e})}async addFeedback(e,t){await this.ready();let r=(await this.options.storage.load(this.options.name,{type:"trace"})).find(s=>s.id===e);r&&(r.feedback={...r.feedback,...t},await this.options.storage.save(this.options.name,r))}createPromptOptimizer(e,t){return new Yt({studentAI:this.requireRuntimeAI(e.runtimeAI),teacherAI:e.teacher,numTrials:e.budget,minibatch:!0,minibatchSize:10,onProgress:this.createOptimizerProgressHandler(t,e.onProgress)})}createPlaybookOptimizer(e,t){return new nr({studentAI:this.requireRuntimeAI(e.runtimeAI),teacherAI:e.teacher,onProgress:this.createOptimizerProgressHandler(t,e.onProgress)},e.playbookOptions)}mergeConfig(e){return{runtimeAI:e.runtimeAI??this.options.runtimeAI,mode:this.options.mode,teacher:this.options.teacher,budget:e.budget??this.options.budget??20,metric:e.metric??this.options.metric,judgeOptions:e.judgeOptions??this.options.judgeOptions,criteria:e.criteria??this.options.criteria,examples:e.examples??this.options.examples,useTraces:e.useTraces??this.options.useTraces??!0,generateExamples:e.generateExamples??this.options.generateExamples??!1,synthCount:e.synthCount??this.options.synthCount,synthOptions:e.synthOptions??this.options.synthOptions,validationSplit:e.validationSplit??this.options.validationSplit??.2,continuousOptions:{feedbackWindowSize:e.continuousOptions?.feedbackWindowSize??this.options.continuousOptions.feedbackWindowSize,maxRecentTraces:e.continuousOptions?.maxRecentTraces??this.options.continuousOptions.maxRecentTraces,updateBudget:e.continuousOptions?.updateBudget??this.options.continuousOptions.updateBudget},playbookOptions:e.playbookOptions??this.options.playbookOptions,onProgress:e.onProgress??this.options.onProgress}}requireRuntimeAI(e){if(e)return e;throw new Error("AxLearn: runtimeAI is required for optimize()/applyUpdate(). Provide it in the constructor or per-call overrides.")}createOptimizerProgressHandler(e,t){if(t)return n=>{t({round:n.round,totalRounds:n.totalRounds,score:n.bestScore,improvement:n.bestScore-e})}}async resolveMetric(e){if(e.metric)return e.metric;let t={ai:e.teacher,criteria:e.criteria,...e.judgeOptions};return Ng(this.gen.getSignature(),t)}async runPromptOptimization(e,t){let n=Date.now(),r=this.currentScore??0,s=e.budget,i=await this.resolveMetric(e),a=await this.prepareDataset(e,t);if(a.examples.length<2)throw new Error("AxLearn: at least 2 usable examples are required after filtering traces/examples.");if(t!==void 0&&e.mode==="continuous"&&a.feedbackExamples.length===0)throw new Error("AxLearn: continuous updates require explicit feedback or stored feedback-bearing traces.");let{trainingExamples:u,validationExamples:c}=this.splitExamples(a.examples,a.feedbackScoredExamples,e.validationSplit,e.mode),p=await this.createPromptOptimizer({...e,budget:s},r).compile(this.gen,u,i,{validationExamples:c,feedbackExamples:a.feedbackExamples.length>0?a.feedbackExamples:void 0,feedbackFn:a.feedbackTextByKey.size>0?({example:A})=>a.feedbackTextByKey.get(this.exampleKey(A)):void 0,feedbackNotes:a.feedbackNotes.length>0?a.feedbackNotes:void 0,maxMetricCalls:this.computeMetricBudget(s,c.length)});if(!p.optimizedProgram)throw new Error("AxLearn: prompt optimization failed with no result");this.gen.applyOptimization?.(p.optimizedProgram),this.currentScore=p.optimizedProgram.bestScore,this.tracer=this.tracer.clone(this.gen);let d=this.createPromptState(e.mode,this.currentScore,a.feedbackExamples.length),m={feedbackExamples:a.feedbackExamples.length,lastUpdateAt:d.continuous?.lastUpdateAt},g={trainingExamples:u.length,validationExamples:c.length,feedbackExamples:a.feedbackExamples.length,durationMs:Date.now()-n},f=await this.saveCheckpoint({mode:e.mode,score:this.currentScore,state:d,stats:g,budget:s});return{result:{mode:e.mode,score:this.currentScore,improvement:this.currentScore-r,checkpointVersion:f,stats:{...g,mode:e.mode},state:d,artifact:m},optimizedProgram:p.optimizedProgram}}async optimizePlaybook(e){let t=Date.now();this.requireRuntimeAI(e.runtimeAI);let n=this.currentScore??0,r=await this.resolveMetric(e),s=await this.prepareDataset(e);if(s.examples.length<2)throw new Error("AxLearn: at least 2 usable examples are required for playbook mode.");let{trainingExamples:i,validationExamples:a}=this.splitExamples(s.examples,s.feedbackExamples,e.validationSplit,e.mode),u=this.createPlaybookOptimizer(e,n),c=await u.compile(this.gen,i,r,{aceOptions:e.playbookOptions});c.optimizedProgram?.applyTo(this.gen),this.playbookOptimizer=u,this.currentScore=c.bestScore,this.tracer=this.tracer.clone(this.gen);let l=c.playbook,p=c.artifact,d=this.summarizePlaybookArtifact(p),m=this.createPlaybookState(l,d,u.getBaseInstruction()),g={trainingExamples:i.length,validationExamples:a.length,feedbackExamples:s.feedbackExamples.length,durationMs:Date.now()-t},f=await this.saveCheckpoint({mode:"playbook",score:this.currentScore,state:m,stats:g,budget:e.budget});return{mode:"playbook",score:this.currentScore,improvement:this.currentScore-n,checkpointVersion:f,stats:{...g,mode:"playbook"},state:m,artifact:{playbook:l,playbookSummary:d,feedbackExamples:s.feedbackExamples.length}}}async applyPlaybookUpdate(e,t){let n=Date.now();this.requireRuntimeAI(e.runtimeAI);let r=this.currentScore??0,s=this.getOrCreatePlaybookOptimizer(e,r);await s.applyOnlineUpdate({example:t.example,prediction:t.prediction,feedback:this.feedbackToText(t.feedback)}),s.applyCurrentState(this.gen),this.tracer=this.tracer.clone(this.gen);let i=s.getArtifact(),a=s.getPlaybook(),u=this.summarizePlaybookArtifact(i),c=this.createPlaybookState(a,u,s.getBaseInstruction()),l=this.currentScore??r,p={trainingExamples:1,validationExamples:1,feedbackExamples:1,durationMs:Date.now()-n},d=await this.saveCheckpoint({mode:"playbook",score:l,state:c,stats:p,budget:e.playbookOptions?.maxEpochs});return e.onProgress?.({round:1,totalRounds:1,score:l,improvement:l-r}),{mode:"playbook",score:l,improvement:l-r,checkpointVersion:d,stats:{...p,mode:"playbook"},state:c,artifact:{playbook:a,playbookSummary:u,feedbackExamples:1}}}getOrCreatePlaybookOptimizer(e,t){return this.playbookOptimizer||(this.playbookOptimizer=this.createPlaybookOptimizer(e,t),this.playbookOptimizer.hydrate(this.gen,{baseInstruction:this.currentState?.baseInstruction??this.gen.getSignature().getDescription()??void 0,playbook:this.currentState?.playbook})),this.playbookOptimizer}async prepareDataset(e,t){let n=[],r=[],s=[],i=new Map,a=[],u=new Set,c=new Set,l=new Set,p=(d,m)=>{let g=this.normalizeExample(d);if(!g)return;let f=this.hasInputFields(g),x=this.hasOutputFields(g);if(!f||m?.requireOutput&&!x)return;let A=this.exampleKey(g);m?.includeInExamples!==!1&&!u.has(A)&&(u.add(A),n.push(g));let y=m?.feedback?.trim();if(y){let T=i.get(A);T?T!==y&&i.set(A,`${T}
937
- ${y}`):i.set(A,y),m?.includeInFeedbackSet!==!1&&!c.has(A)&&(r.push(g),c.add(A)),m?.feedbackEligibleForScoring&&!l.has(A)&&(s.push(g),l.add(A))}return g};for(let d of e.examples??[])p(d);if(e.useTraces){let d=await this.loadRelevantTraces(e);for(let m of d)p(m.example,{feedback:m.feedback,requireOutput:!0,feedbackEligibleForScoring:!0})}if(t){let d=this.feedbackToText(t.feedback),m=t.example,g=this.hasOutputFields(m),f=this.buildObservedUpdateExample(m,t.prediction);if(d&&f){p(f,{feedback:d,requireOutput:!0,includeInExamples:!1,feedbackEligibleForScoring:!1});let x=this.formatObservedUpdateFeedback(m,t.prediction,d);x&&a.push(x)}g&&p(m,{feedback:d,feedbackEligibleForScoring:!0})}if(e.generateExamples||n.length===0){let d=e.synthCount??20,g=await new or(this.gen.getSignature(),{teacher:e.teacher,...e.synthOptions}).generate(d);for(let f of g.examples)p({...f.input,...f.expected})}return e.mode==="continuous"&&s.length>0?{examples:[...s,...n.filter(m=>!s.some(g=>this.exampleKey(g)===this.exampleKey(m)))],feedbackExamples:r.slice(0,e.continuousOptions.feedbackWindowSize),feedbackScoredExamples:s.slice(0,e.continuousOptions.feedbackWindowSize),feedbackTextByKey:i,feedbackNotes:a}:{examples:n,feedbackExamples:r.slice(0,e.continuousOptions.feedbackWindowSize),feedbackScoredExamples:s.slice(0,e.continuousOptions.feedbackWindowSize),feedbackTextByKey:i,feedbackNotes:a}}async loadRelevantTraces(e){let n=[...await this.options.storage.load(this.options.name,{type:"trace"})].sort((i,a)=>{let u=new Date(i.endTime??i.startTime).getTime();return new Date(a.endTime??a.startTime).getTime()-u}),r=e.mode==="continuous"?n.slice(0,e.continuousOptions.maxRecentTraces):n,s=new Map;for(let i of r){if(i.error)continue;let a=this.normalizeExample({...i.input??{},...i.output??{}});if(!a||!this.hasOutputFields(a))continue;let u=this.exampleKey(a),c=this.feedbackToText(i.feedback),l=s.get(u);if(!l){s.set(u,{example:a,feedback:c});continue}!l.feedback&&c&&(l.feedback=c)}return[...s.values()]}normalizeExample(e){let t={},n=this.gen.getSignature(),r=[...n.getInputFields(),...n.getOutputFields()];for(let s of r)s.name in e&&e[s.name]!==void 0&&(t[s.name]=e[s.name]);if(Object.keys(t).length!==0)return t}buildObservedUpdateExample(e,t){return this.normalizeExample({...this.pickInputFields(e),...this.pickOutputFields(t)})}pickInputFields(e){let t={};for(let n of this.gen.getSignature().getInputFields())e[n.name]!==void 0&&(t[n.name]=e[n.name]);return t}pickOutputFields(e){let t={};for(let n of this.gen.getSignature().getOutputFields())e[n.name]!==void 0&&(t[n.name]=e[n.name]);return t}hasInputFields(e){return this.gen.getSignature().getInputFields().some(t=>e[t.name]!==void 0)}hasOutputFields(e){return this.gen.getSignature().getOutputFields().some(t=>e[t.name]!==void 0)}exampleKey(e){let t=this.gen.getSignature(),r=[...t.getInputFields(),...t.getOutputFields()].map(s=>s.name).reduce((s,i)=>(e[i]!==void 0&&(s[i]=e[i]),s),{});return JSON.stringify(r)}feedbackToText(e){if(!e)return;if(typeof e=="string")return e.trim()||void 0;let t=[];return typeof e.score=="number"&&t.push(`User score: ${e.score}.`),e.label&&t.push(`User label: ${e.label}.`),e.comment&&t.push(e.comment.trim()),t.join(" ").trim()||void 0}formatObservedUpdateFeedback(e,t,n){let r=this.pickInputFields(e),s=this.pickOutputFields(t);return["Observed continuous update event.",`Inputs: ${JSON.stringify(r)}`,`Observed output: ${JSON.stringify(s)}`,`User feedback: ${n}`].join(`
938
- `)}splitExamples(e,t,n,r){let s=this.shuffleExamples(e),i=Number.isFinite(n)?Math.min(Math.max(n,.05),.5):.2,a=Math.min(s.length-1,Math.max(1,Math.round(s.length*i)));if(r==="continuous"&&t.length>0){let u=new Set(t.map(p=>this.exampleKey(p))),c=[];for(let p of s)!u.has(this.exampleKey(p))&&c.length<a&&c.push(p);for(let p of s){if(c.length>=a)break;c.some(d=>this.exampleKey(d)===this.exampleKey(p))||c.push(p)}let l=new Set(c.map(p=>this.exampleKey(p)));return{trainingExamples:s.filter(p=>!l.has(this.exampleKey(p))),validationExamples:c}}return{trainingExamples:s.slice(0,s.length-a),validationExamples:s.slice(s.length-a)}}shuffleExamples(e){let t=[...e];for(let n=t.length-1;n>0;n-=1){let r=Math.floor(Math.random()*(n+1));[t[n],t[r]]=[t[r],t[n]]}return t}computeMetricBudget(e,t){let n=Math.max(e,1),r=Math.max(t,1);return Math.max(r*(n+2),20)}createPromptState(e,t,n){let r=this.gen.getInstruction(),s={mode:e,instruction:r,baseInstruction:r,score:t};return e==="continuous"&&(s.continuous={feedbackTraceCount:n,lastUpdateAt:new Date().toISOString()}),this.currentState=s,s}createPlaybookState(e,t,n){let r=this.gen.getSignature().getDescription()??this.gen.getInstruction(),s={mode:"playbook",instruction:r,baseInstruction:n??this.currentState?.baseInstruction??r,score:this.currentScore,playbook:e,artifactSummary:t};return this.currentState=s,s}summarizePlaybookArtifact(e){return{feedbackEvents:e.feedback.length,historyBatches:e.history.length,bulletCount:e.playbook.stats.bulletCount,updatedAt:e.playbook.updatedAt}}async saveCheckpoint(e){let r=(await this.options.storage.load(this.options.name,{type:"checkpoint"})).reduce((i,a)=>Math.max(i,a.version??0),0)+1,s={type:"checkpoint",name:this.options.name,version:r,createdAt:new Date,instruction:e.state.instruction??this.gen.getInstruction(),score:e.score,optimizerType:"learn",learnState:e.state,metadata:{mode:e.mode,budget:e.budget,trainingExamples:e.stats.trainingExamples,validationExamples:e.stats.validationExamples,feedbackExamples:e.stats.feedbackExamples,durationMs:e.stats.durationMs}};return await this.options.storage.save(this.options.name,s),this.currentScore=e.score,this.currentState=e.state,r}async loadLatestCheckpoint(){try{let e=await this.options.storage.load(this.options.name,{type:"checkpoint"});if(e.length===0)return;let t=[...e].sort((r,s)=>{let i=(s.version??0)-(r.version??0);return i!==0?i:new Date(s.createdAt).getTime()-new Date(r.createdAt).getTime()})[0];if(!t)return;let n=t.learnState?.instruction??t.instruction??void 0;t.learnState?.mode==="playbook"&&t.learnState.playbook?this.applyRestoredPlaybook(t.learnState.playbook,t.learnState.baseInstruction,n):n&&this.gen.setInstruction(n),this.currentScore=t.learnState?.score??t.score,this.currentState=t.learnState,t.learnState?.mode==="playbook"&&(this.playbookOptimizer=void 0),this.tracer=this.tracer.clone(this.gen)}catch{}}applyRestoredPlaybook(e,t,n){let s=[(t??this.gen.getSignature().getDescription()??n??"").trim(),"",dn(e)].filter(i=>i&&i.trim().length>0).join(`
936
+ `),r=e.description?.trim();r&&(t.setInstruction(r),n.setInstruction(r));let s=_g(e),i=o.getDescription();return async({example:a,prediction:u})=>{let c={};for(let g of o.getInputFields())g.name in a&&(c[g.name]=a[g.name]);let l={},p=!1;for(let g of o.getOutputFields())g.name in a&&(l[g.name]=a[g.name],p=!0);let d=u;if(p&&Ng(l))return Lg(o,d,l);if(p){let f=e.randomizeOrder??!0?Math.random()>.5:!0,A=(await n.forward(e.ai,{task_input:JSON.stringify(c),task_description:i,criteria:e.criteria,system_output_a:JSON.stringify(f?d:l),system_output_b:JSON.stringify(f?l:d)},s)).winner.toUpperCase();return A==="TIE"?.5:A==="A"?f?1:0:A==="B"?f?0:1:.5}let m=await t.forward(e.ai,{task_input:JSON.stringify(c),task_description:i,criteria:e.criteria,system_output:JSON.stringify(d)},s);return Fg[m.quality.toLowerCase()]??.5}}var Ug="batch",Ka={feedbackWindowSize:25,maxRecentTraces:100,updateBudget:4},Ds=class o{gen;options;tracer;currentScore;currentState;readyPromise;playbookOptimizer;constructor(e,t){this.gen=e,this.options={...t,enableTracing:t.enableTracing??!0,mode:t.mode??Ug,continuousOptions:{feedbackWindowSize:t.continuousOptions?.feedbackWindowSize??Ka.feedbackWindowSize,maxRecentTraces:t.continuousOptions?.maxRecentTraces??Ka.maxRecentTraces,updateBudget:t.continuousOptions?.updateBudget??Ka.updateBudget}},this.tracer=new nr(e,{name:this.options.name,storage:this.options.storage,metadata:this.options.metadata,onTrace:this.options.onTrace}),this.readyPromise=this.loadLatestCheckpoint()}async ready(){await this.readyPromise}async forward(e,t,n){return await this.ready(),this.options.enableTracing?this.tracer.forward(e,t,n):this.gen.forward(e,t,n)}async*streamingForward(e,t,n){await this.ready(),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.currentState?.mode==="playbook"||this.options.mode==="playbook"?this.currentState?.instruction??this.gen.getSignature().getDescription()??this.gen.getInstruction():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 o(this.gen.clone(),this.options)}async optimize(e={}){await this.ready();let t=this.mergeConfig(e);return t.mode==="playbook"?this.optimizePlaybook(t):(await this.runPromptOptimization(t)).result}async applyUpdate(e,t={}){await this.ready();let n=this.mergeConfig(t),r=n.mode==="continuous"?{...n,budget:t.budget??n.continuousOptions.updateBudget}:n;if(r.mode==="batch")throw new Error("AxLearn: applyUpdate() is only available in continuous or playbook modes");return r.mode==="playbook"?this.applyPlaybookUpdate(r,e):(await this.runPromptOptimization(r,e)).result}getGen(){return this.gen}getStorage(){return this.options.storage}async getTraces(e){return await this.ready(),this.options.storage.load(this.options.name,{type:"trace",...e})}async addFeedback(e,t){await this.ready();let r=(await this.options.storage.load(this.options.name,{type:"trace"})).find(s=>s.id===e);r&&(r.feedback={...r.feedback,...t},await this.options.storage.save(this.options.name,r))}createPromptOptimizer(e,t){return new Xt({studentAI:this.requireRuntimeAI(e.runtimeAI),teacherAI:e.teacher,numTrials:e.budget,minibatch:!0,minibatchSize:10,onProgress:this.createOptimizerProgressHandler(t,e.onProgress)})}createPlaybookOptimizer(e,t){return new rr({studentAI:this.requireRuntimeAI(e.runtimeAI),teacherAI:e.teacher,onProgress:this.createOptimizerProgressHandler(t,e.onProgress)},e.playbookOptions)}mergeConfig(e){return{runtimeAI:e.runtimeAI??this.options.runtimeAI,mode:this.options.mode,teacher:this.options.teacher,budget:e.budget??this.options.budget??20,metric:e.metric??this.options.metric,judgeOptions:e.judgeOptions??this.options.judgeOptions,criteria:e.criteria??this.options.criteria,examples:e.examples??this.options.examples,useTraces:e.useTraces??this.options.useTraces??!0,generateExamples:e.generateExamples??this.options.generateExamples??!1,synthCount:e.synthCount??this.options.synthCount,synthOptions:e.synthOptions??this.options.synthOptions,validationSplit:e.validationSplit??this.options.validationSplit??.2,continuousOptions:{feedbackWindowSize:e.continuousOptions?.feedbackWindowSize??this.options.continuousOptions.feedbackWindowSize,maxRecentTraces:e.continuousOptions?.maxRecentTraces??this.options.continuousOptions.maxRecentTraces,updateBudget:e.continuousOptions?.updateBudget??this.options.continuousOptions.updateBudget},playbookOptions:e.playbookOptions??this.options.playbookOptions,onProgress:e.onProgress??this.options.onProgress}}requireRuntimeAI(e){if(e)return e;throw new Error("AxLearn: runtimeAI is required for optimize()/applyUpdate(). Provide it in the constructor or per-call overrides.")}createOptimizerProgressHandler(e,t){if(t)return n=>{t({round:n.round,totalRounds:n.totalRounds,score:n.bestScore,improvement:n.bestScore-e})}}async resolveMetric(e){if(e.metric)return e.metric;let t={ai:e.teacher,criteria:e.criteria,...e.judgeOptions};return Dg(this.gen.getSignature(),t)}async runPromptOptimization(e,t){let n=Date.now(),r=this.currentScore??0,s=e.budget,i=await this.resolveMetric(e),a=await this.prepareDataset(e,t);if(a.examples.length<2)throw new Error("AxLearn: at least 2 usable examples are required after filtering traces/examples.");if(t!==void 0&&e.mode==="continuous"&&a.feedbackExamples.length===0)throw new Error("AxLearn: continuous updates require explicit feedback or stored feedback-bearing traces.");let{trainingExamples:u,validationExamples:c}=this.splitExamples(a.examples,a.feedbackScoredExamples,e.validationSplit,e.mode),p=await this.createPromptOptimizer({...e,budget:s},r).compile(this.gen,u,i,{validationExamples:c,feedbackExamples:a.feedbackExamples.length>0?a.feedbackExamples:void 0,feedbackFn:a.feedbackTextByKey.size>0?({example:A})=>a.feedbackTextByKey.get(this.exampleKey(A)):void 0,feedbackNotes:a.feedbackNotes.length>0?a.feedbackNotes:void 0,maxMetricCalls:this.computeMetricBudget(s,c.length)});if(!p.optimizedProgram)throw new Error("AxLearn: prompt optimization failed with no result");this.gen.applyOptimization?.(p.optimizedProgram),this.currentScore=p.optimizedProgram.bestScore,this.tracer=this.tracer.clone(this.gen);let d=this.createPromptState(e.mode,this.currentScore,a.feedbackExamples.length),m={feedbackExamples:a.feedbackExamples.length,lastUpdateAt:d.continuous?.lastUpdateAt},g={trainingExamples:u.length,validationExamples:c.length,feedbackExamples:a.feedbackExamples.length,durationMs:Date.now()-n},f=await this.saveCheckpoint({mode:e.mode,score:this.currentScore,state:d,stats:g,budget:s});return{result:{mode:e.mode,score:this.currentScore,improvement:this.currentScore-r,checkpointVersion:f,stats:{...g,mode:e.mode},state:d,artifact:m},optimizedProgram:p.optimizedProgram}}async optimizePlaybook(e){let t=Date.now();this.requireRuntimeAI(e.runtimeAI);let n=this.currentScore??0,r=await this.resolveMetric(e),s=await this.prepareDataset(e);if(s.examples.length<2)throw new Error("AxLearn: at least 2 usable examples are required for playbook mode.");let{trainingExamples:i,validationExamples:a}=this.splitExamples(s.examples,s.feedbackExamples,e.validationSplit,e.mode),u=this.createPlaybookOptimizer(e,n),c=await u.compile(this.gen,i,r,{aceOptions:e.playbookOptions});c.optimizedProgram?.applyTo(this.gen),this.playbookOptimizer=u,this.currentScore=c.bestScore,this.tracer=this.tracer.clone(this.gen);let l=c.playbook,p=c.artifact,d=this.summarizePlaybookArtifact(p),m=this.createPlaybookState(l,d,u.getBaseInstruction()),g={trainingExamples:i.length,validationExamples:a.length,feedbackExamples:s.feedbackExamples.length,durationMs:Date.now()-t},f=await this.saveCheckpoint({mode:"playbook",score:this.currentScore,state:m,stats:g,budget:e.budget});return{mode:"playbook",score:this.currentScore,improvement:this.currentScore-n,checkpointVersion:f,stats:{...g,mode:"playbook"},state:m,artifact:{playbook:l,playbookSummary:d,feedbackExamples:s.feedbackExamples.length}}}async applyPlaybookUpdate(e,t){let n=Date.now();this.requireRuntimeAI(e.runtimeAI);let r=this.currentScore??0,s=this.getOrCreatePlaybookOptimizer(e,r);await s.applyOnlineUpdate({example:t.example,prediction:t.prediction,feedback:this.feedbackToText(t.feedback)}),s.applyCurrentState(this.gen),this.tracer=this.tracer.clone(this.gen);let i=s.getArtifact(),a=s.getPlaybook(),u=this.summarizePlaybookArtifact(i),c=this.createPlaybookState(a,u,s.getBaseInstruction()),l=this.currentScore??r,p={trainingExamples:1,validationExamples:1,feedbackExamples:1,durationMs:Date.now()-n},d=await this.saveCheckpoint({mode:"playbook",score:l,state:c,stats:p,budget:e.playbookOptions?.maxEpochs});return e.onProgress?.({round:1,totalRounds:1,score:l,improvement:l-r}),{mode:"playbook",score:l,improvement:l-r,checkpointVersion:d,stats:{...p,mode:"playbook"},state:c,artifact:{playbook:a,playbookSummary:u,feedbackExamples:1}}}getOrCreatePlaybookOptimizer(e,t){return this.playbookOptimizer||(this.playbookOptimizer=this.createPlaybookOptimizer(e,t),this.playbookOptimizer.hydrate(this.gen,{baseInstruction:this.currentState?.baseInstruction??this.gen.getSignature().getDescription()??void 0,playbook:this.currentState?.playbook})),this.playbookOptimizer}async prepareDataset(e,t){let n=[],r=[],s=[],i=new Map,a=[],u=new Set,c=new Set,l=new Set,p=(d,m)=>{let g=this.normalizeExample(d);if(!g)return;let f=this.hasInputFields(g),x=this.hasOutputFields(g);if(!f||m?.requireOutput&&!x)return;let A=this.exampleKey(g);m?.includeInExamples!==!1&&!u.has(A)&&(u.add(A),n.push(g));let y=m?.feedback?.trim();if(y){let C=i.get(A);C?C!==y&&i.set(A,`${C}
937
+ ${y}`):i.set(A,y),m?.includeInFeedbackSet!==!1&&!c.has(A)&&(r.push(g),c.add(A)),m?.feedbackEligibleForScoring&&!l.has(A)&&(s.push(g),l.add(A))}return g};for(let d of e.examples??[])p(d);if(e.useTraces){let d=await this.loadRelevantTraces(e);for(let m of d)p(m.example,{feedback:m.feedback,requireOutput:!0,feedbackEligibleForScoring:!0})}if(t){let d=this.feedbackToText(t.feedback),m=t.example,g=this.hasOutputFields(m),f=this.buildObservedUpdateExample(m,t.prediction);if(d&&f){p(f,{feedback:d,requireOutput:!0,includeInExamples:!1,feedbackEligibleForScoring:!1});let x=this.formatObservedUpdateFeedback(m,t.prediction,d);x&&a.push(x)}g&&p(m,{feedback:d,feedbackEligibleForScoring:!0})}if(e.generateExamples||n.length===0){let d=e.synthCount??20,g=await new sr(this.gen.getSignature(),{teacher:e.teacher,...e.synthOptions}).generate(d);for(let f of g.examples)p({...f.input,...f.expected})}return e.mode==="continuous"&&s.length>0?{examples:[...s,...n.filter(m=>!s.some(g=>this.exampleKey(g)===this.exampleKey(m)))],feedbackExamples:r.slice(0,e.continuousOptions.feedbackWindowSize),feedbackScoredExamples:s.slice(0,e.continuousOptions.feedbackWindowSize),feedbackTextByKey:i,feedbackNotes:a}:{examples:n,feedbackExamples:r.slice(0,e.continuousOptions.feedbackWindowSize),feedbackScoredExamples:s.slice(0,e.continuousOptions.feedbackWindowSize),feedbackTextByKey:i,feedbackNotes:a}}async loadRelevantTraces(e){let n=[...await this.options.storage.load(this.options.name,{type:"trace"})].sort((i,a)=>{let u=new Date(i.endTime??i.startTime).getTime();return new Date(a.endTime??a.startTime).getTime()-u}),r=e.mode==="continuous"?n.slice(0,e.continuousOptions.maxRecentTraces):n,s=new Map;for(let i of r){if(i.error)continue;let a=this.normalizeExample({...i.input??{},...i.output??{}});if(!a||!this.hasOutputFields(a))continue;let u=this.exampleKey(a),c=this.feedbackToText(i.feedback),l=s.get(u);if(!l){s.set(u,{example:a,feedback:c});continue}!l.feedback&&c&&(l.feedback=c)}return[...s.values()]}normalizeExample(e){let t={},n=this.gen.getSignature(),r=[...n.getInputFields(),...n.getOutputFields()];for(let s of r)s.name in e&&e[s.name]!==void 0&&(t[s.name]=e[s.name]);if(Object.keys(t).length!==0)return t}buildObservedUpdateExample(e,t){return this.normalizeExample({...this.pickInputFields(e),...this.pickOutputFields(t)})}pickInputFields(e){let t={};for(let n of this.gen.getSignature().getInputFields())e[n.name]!==void 0&&(t[n.name]=e[n.name]);return t}pickOutputFields(e){let t={};for(let n of this.gen.getSignature().getOutputFields())e[n.name]!==void 0&&(t[n.name]=e[n.name]);return t}hasInputFields(e){return this.gen.getSignature().getInputFields().some(t=>e[t.name]!==void 0)}hasOutputFields(e){return this.gen.getSignature().getOutputFields().some(t=>e[t.name]!==void 0)}exampleKey(e){let t=this.gen.getSignature(),r=[...t.getInputFields(),...t.getOutputFields()].map(s=>s.name).reduce((s,i)=>(e[i]!==void 0&&(s[i]=e[i]),s),{});return JSON.stringify(r)}feedbackToText(e){if(!e)return;if(typeof e=="string")return e.trim()||void 0;let t=[];return typeof e.score=="number"&&t.push(`User score: ${e.score}.`),e.label&&t.push(`User label: ${e.label}.`),e.comment&&t.push(e.comment.trim()),t.join(" ").trim()||void 0}formatObservedUpdateFeedback(e,t,n){let r=this.pickInputFields(e),s=this.pickOutputFields(t);return["Observed continuous update event.",`Inputs: ${JSON.stringify(r)}`,`Observed output: ${JSON.stringify(s)}`,`User feedback: ${n}`].join(`
938
+ `)}splitExamples(e,t,n,r){let s=this.shuffleExamples(e),i=Number.isFinite(n)?Math.min(Math.max(n,.05),.5):.2,a=Math.min(s.length-1,Math.max(1,Math.round(s.length*i)));if(r==="continuous"&&t.length>0){let u=new Set(t.map(p=>this.exampleKey(p))),c=[];for(let p of s)!u.has(this.exampleKey(p))&&c.length<a&&c.push(p);for(let p of s){if(c.length>=a)break;c.some(d=>this.exampleKey(d)===this.exampleKey(p))||c.push(p)}let l=new Set(c.map(p=>this.exampleKey(p)));return{trainingExamples:s.filter(p=>!l.has(this.exampleKey(p))),validationExamples:c}}return{trainingExamples:s.slice(0,s.length-a),validationExamples:s.slice(s.length-a)}}shuffleExamples(e){let t=[...e];for(let n=t.length-1;n>0;n-=1){let r=Math.floor(Math.random()*(n+1));[t[n],t[r]]=[t[r],t[n]]}return t}computeMetricBudget(e,t){let n=Math.max(e,1),r=Math.max(t,1);return Math.max(r*(n+2),20)}createPromptState(e,t,n){let r=this.gen.getInstruction(),s={mode:e,instruction:r,baseInstruction:r,score:t};return e==="continuous"&&(s.continuous={feedbackTraceCount:n,lastUpdateAt:new Date().toISOString()}),this.currentState=s,s}createPlaybookState(e,t,n){let r=this.gen.getSignature().getDescription()??this.gen.getInstruction(),s={mode:"playbook",instruction:r,baseInstruction:n??this.currentState?.baseInstruction??r,score:this.currentScore,playbook:e,artifactSummary:t};return this.currentState=s,s}summarizePlaybookArtifact(e){return{feedbackEvents:e.feedback.length,historyBatches:e.history.length,bulletCount:e.playbook.stats.bulletCount,updatedAt:e.playbook.updatedAt}}async saveCheckpoint(e){let r=(await this.options.storage.load(this.options.name,{type:"checkpoint"})).reduce((i,a)=>Math.max(i,a.version??0),0)+1,s={type:"checkpoint",name:this.options.name,version:r,createdAt:new Date,instruction:e.state.instruction??this.gen.getInstruction(),score:e.score,optimizerType:"learn",learnState:e.state,metadata:{mode:e.mode,budget:e.budget,trainingExamples:e.stats.trainingExamples,validationExamples:e.stats.validationExamples,feedbackExamples:e.stats.feedbackExamples,durationMs:e.stats.durationMs}};return await this.options.storage.save(this.options.name,s),this.currentScore=e.score,this.currentState=e.state,r}async loadLatestCheckpoint(){try{let e=await this.options.storage.load(this.options.name,{type:"checkpoint"});if(e.length===0)return;let t=[...e].sort((r,s)=>{let i=(s.version??0)-(r.version??0);return i!==0?i:new Date(s.createdAt).getTime()-new Date(r.createdAt).getTime()})[0];if(!t)return;let n=t.learnState?.instruction??t.instruction??void 0;t.learnState?.mode==="playbook"&&t.learnState.playbook?this.applyRestoredPlaybook(t.learnState.playbook,t.learnState.baseInstruction,n):n&&this.gen.setInstruction(n),this.currentScore=t.learnState?.score??t.score,this.currentState=t.learnState,t.learnState?.mode==="playbook"&&(this.playbookOptimizer=void 0),this.tracer=this.tracer.clone(this.gen)}catch{}}applyRestoredPlaybook(e,t,n){let s=[(t??this.gen.getSignature().getDescription()??n??"").trim(),"",gn(e)].filter(i=>i&&i.trim().length>0).join(`
939
939
 
940
- `);if(typeof this.gen.setDescription=="function"){this.gen.setDescription(s);return}s&&this.gen.setInstruction(s)}};var Us=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(s=>{let i={};return t.forEach(a=>{let u=a.split("."),c=s.row;for(let p of u)Object.hasOwn(c,p)&&(c=c[p]);if(!c)return;let l=n&&a in n?n[a]:a;if(!l)throw new Error(`Invalid field name: ${a}`);i[l]=c}),i}).filter(s=>Object.keys(s).length!==0)}};var sr=class extends It{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,s){let i=Date.now(),a=s?.maxDemos??this.maxDemos,u={modelConfig:{temperature:.7}};this.maxTokensPerGeneration>0&&(u.modelConfig.max_tokens=this.maxTokensPerGeneration);let c=Dg([...t],this.maxExamples),l=this.traces.length,p=e.getId();for(let d=0;d<c.length;d+=this.batchSize){d>0&&(u.modelConfig.temperature=.7+.001*d);let m=c.slice(d,d+this.batchSize);for(let g of m){if(!g||typeof g!="object")continue;let f=t.filter(h=>h!==g);e.setDemos([{traces:f,programId:p}]);let x=this.getTeacherOrStudentAI();this.stats.totalCalls++;let A;try{let h={...u,maxRetries:1};A=await e.forward(x,g,h),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(h){(this.verboseMode||this.debugMode)&&console.warn(`Student model failed during bootstrap: ${h instanceof Error?h.message:"Unknown error"}`),A={}}if(this.traces.length>=a)return}}if(this.earlyStoppingPatience>0){let m=this.traces.length-l;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 s=r?.maxIterations??this.maxRounds;this.traces=[],this.reset();for(let u=0;u<s&&(await this.compileRound(e,t,u,n,r),!this.stats.earlyStopped);u++);if(this.traces.length===0)throw new Error("No demonstrations found. Either provide more examples or improve the existing ones.");let i=$g(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 $g(o){let e=new Map;for(let n of o)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 Dg=(o,e)=>{let t=[...o];for(let n=t.length-1;n>0;n--){let r=Math.floor(Math.random()*(n+1)),s=t[n],i=t[r];if(!s||!i)throw new Error("Invalid array elements");[t[n],t[r]]=[i,s]}return t.slice(0,e)};var Gs=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 s=await this.getJobStatus(e);if(["completed","failed","cancelled"].includes(s.status))return s;this.logger?.({name:"Notification",id:"job_status",value:`Job ${e} status: ${s.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 s=0;s<this.retryAttempts;s++)try{let i=new AbortController,a=setTimeout(()=>i.abort(),this.timeout),u=await fetch(n,{...t,signal:i.signal});return clearTimeout(a),u}catch(i){r=i,this.logger?.({name:"Notification",id:"retry_attempt",value:`Attempt ${s+1} failed: ${i}`}),s<this.retryAttempts-1&&await this.sleep(this.retryDelay*Math.pow(2,s))}throw new Error(`Request failed after ${this.retryAttempts} attempts: ${r?.message}`)}sleep(e){return new Promise(t=>setTimeout(t,e))}};var Bs=class extends It{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 Gs(t)}this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}defaultResultPicker=async e=>{if(e.type==="function"){let s=e.results.findIndex(i=>!i.isError);return s>=0?s:0}let t=new Map;for(let s of e.results){let i=JSON.stringify(s.sample??{}),a=t.get(i);a?a.count+=1:t.set(i,{count:1,firstIndex:s.index})}let n="",r={count:-1,firstIndex:0};for(let[s,i]of t.entries())i.count>r.count&&(r=i,n=s);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=`
940
+ `);if(typeof this.gen.setDescription=="function"){this.gen.setDescription(s);return}s&&this.gen.setInstruction(s)}};var Us=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(s=>{let i={};return t.forEach(a=>{let u=a.split("."),c=s.row;for(let p of u)Object.hasOwn(c,p)&&(c=c[p]);if(!c)return;let l=n&&a in n?n[a]:a;if(!l)throw new Error(`Invalid field name: ${a}`);i[l]=c}),i}).filter(s=>Object.keys(s).length!==0)}};var ir=class extends Tt{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,s){let i=Date.now(),a=s?.maxDemos??this.maxDemos,u={modelConfig:{temperature:.7}};this.maxTokensPerGeneration>0&&(u.modelConfig.max_tokens=this.maxTokensPerGeneration);let c=jg([...t],this.maxExamples),l=this.traces.length,p=e.getId();for(let d=0;d<c.length;d+=this.batchSize){d>0&&(u.modelConfig.temperature=.7+.001*d);let m=c.slice(d,d+this.batchSize);for(let g of m){if(!g||typeof g!="object")continue;let f=t.filter(h=>h!==g);e.setDemos([{traces:f,programId:p}]);let x=this.getTeacherOrStudentAI();this.stats.totalCalls++;let A;try{let h={...u,maxRetries:1};A=await e.forward(x,g,h),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(h){(this.verboseMode||this.debugMode)&&console.warn(`Student model failed during bootstrap: ${h instanceof Error?h.message:"Unknown error"}`),A={}}if(this.traces.length>=a)return}}if(this.earlyStoppingPatience>0){let m=this.traces.length-l;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 s=r?.maxIterations??this.maxRounds;this.traces=[],this.reset();for(let u=0;u<s&&(await this.compileRound(e,t,u,n,r),!this.stats.earlyStopped);u++);if(this.traces.length===0)throw new Error("No demonstrations found. Either provide more examples or improve the existing ones.");let i=Gg(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 Gg(o){let e=new Map;for(let n of o)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 jg=(o,e)=>{let t=[...o];for(let n=t.length-1;n>0;n--){let r=Math.floor(Math.random()*(n+1)),s=t[n],i=t[r];if(!s||!i)throw new Error("Invalid array elements");[t[n],t[r]]=[i,s]}return t.slice(0,e)};var Gs=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 s=await this.getJobStatus(e);if(["completed","failed","cancelled"].includes(s.status))return s;this.logger?.({name:"Notification",id:"job_status",value:`Job ${e} status: ${s.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 s=0;s<this.retryAttempts;s++)try{let i=new AbortController,a=setTimeout(()=>i.abort(),this.timeout),u=await fetch(n,{...t,signal:i.signal});return clearTimeout(a),u}catch(i){r=i,this.logger?.({name:"Notification",id:"retry_attempt",value:`Attempt ${s+1} failed: ${i}`}),s<this.retryAttempts-1&&await this.sleep(this.retryDelay*Math.pow(2,s))}throw new Error(`Request failed after ${this.retryAttempts} attempts: ${r?.message}`)}sleep(e){return new Promise(t=>setTimeout(t,e))}};var js=class extends Tt{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 Gs(t)}this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}defaultResultPicker=async e=>{if(e.type==="function"){let s=e.results.findIndex(i=>!i.isError);return s>=0?s:0}let t=new Map;for(let s of e.results){let i=JSON.stringify(s.sample??{}),a=t.get(i);a?a.count+=1:t.set(i,{count:1,firstIndex:s.index})}let n="",r={count:-1,firstIndex:0};for(let[s,i]of t.entries())i.count>r.count&&(r=i,n=s);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=`
941
941
  Analyze this language model program and provide a concise summary of its purpose and structure.
942
942
 
943
943
  Program Signature: ${e.getSignature()}
@@ -977,12 +977,12 @@ Requirements:
977
977
  5. Keep it concise but comprehensive
978
978
 
979
979
  Generate a single, well-crafted instruction:
980
- Instruction:`;try{let m=(await it('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:s??"",tip:e??""})).instructionText;if(m&&m.trim().length>10)return m.trim()}catch{}let c=["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."],l=c[t%c.length]||c[0];return e&&(l=`${l} ${e}`),l}async proposeInstructionCandidates(e,t,n=[]){let r=[],s=this.getTeacherOrStudentAI(t),i,a;this.programAwareProposer&&(i=await this.generateProgramSummary(e,s)),this.dataAwareProposer&&(a=await this.generateDatasetSummary([...n],s));let u=this.tipAwareProposer?this.generateTips():[];for(let c=0;c<this.numCandidates;c++){let l=u.length>0?c%u.length:-1,p=l>=0?u[l]:void 0,d=await this.generateInstruction({tip:p,candidateIndex:c,ai:s,programSummary:i,datasetSummary:a,previousInstructions:r});r.push(d)}return r}async bootstrapFewShotExamples(e,t,n){return(await new sr({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 s=e[r];s&&t.push(s)}}return t}applyConfigToProgram(e,t,n,r){if(e.setInstruction&&e.setInstruction(t.instruction),e.setDemos){let s=[...n.slice(0,t.bootstrappedDemos)];if(t.labeledExamples>0&&e.getId){let i=e.getId();s.push({traces:r.slice(0,t.labeledExamples),programId:i})}s.length>0&&e.setDemos(s)}}async compile(e,t,n,r){let s=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 s=[...n.slice(0,t.bootstrappedDemos)];if(t.labeledExamples>0){let i=e.getId();s.push({traces:r.slice(0,t.labeledExamples),programId:i})}s.length>0&&e.setDemos(s)}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 s=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)}`,u={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},c=await this.pythonClient.createOptimizationJob(u);this.getOptimizerLogger()?.({name:"OptimizationStart",value:{optimizerType:"MiPRO (Python)",exampleCount:t.length,validationCount:0,config:{jobId:c.job_id,numTrials:this.numTrials}}});let p=Number.NEGATIVE_INFINITY,d,m=0,g=0;for(let R=0;R<this.numTrials;R++)try{let M=await this.pythonClient.suggestParameters(a),I=M.params.temperature,O=M.params.bootstrappedDemos,E=M.params.instruction,$=M.params.labeledExamples,N=this.optimizeTopP?M.params.topP:void 0;if(I===void 0)throw new Error(`Missing temperature parameter in suggestion: ${JSON.stringify(M)}`);if(O===void 0)throw new Error(`Missing bootstrappedDemos parameter in suggestion: ${JSON.stringify(M)}`);if(E===void 0)throw new Error(`Missing instruction parameter in suggestion: ${JSON.stringify(M)}`);if($===void 0)throw new Error(`Missing labeledExamples parameter in suggestion: ${JSON.stringify(M)}`);let S=e.clone();S.setInstruction(E);let v=S.getId();S.setDemos([{traces:this.selectLabeledExamples(t).slice(0,$),programId:v}]);let P=!this.minibatch||this.minibatchFullEvalSteps>0&&R%this.minibatchFullEvalSteps===this.minibatchFullEvalSteps-1?[...t]:(()=>{let j=Math.min(this.minibatchSize,t.length),G=new Set;for(;G.size<j;)G.add(Math.floor(Math.random()*t.length));return Array.from(G).map(H=>t[H])})(),L=await this.evaluateConfiguration(S,n,{temperature:I,bootstrappedDemos:O,topP:N},P);m++,await this.pythonClient.evaluateTrial({study_name:a,trial_number:M.trial_number,value:L}),L>p+this.minImprovementThreshold?(p=L,d={temperature:I,bootstrappedDemos:O,...N!==void 0?{topP:N}:{},trialNumber:M.trial_number},g=0):g+=1,this.currentRound=R+1;let D={temperature:I,bootstrappedDemos:O,...N!==void 0?{topP:N}:{},trialNumber:M.trial_number};if(this.localScoreHistory.push(L),this.localConfigurationHistory.push(D),await this.updateOptimizationProgress(this.currentRound,L,D,"MiPRO (Python)",{sampler:"TPESampler"},p,d),this.onProgress?.({round:R+1,totalRounds:this.numTrials,currentScore:L,bestScore:p,tokensUsed:this.stats.estimatedTokenUsage,timeElapsed:Date.now()-s,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,x={},A=[];try{let R=await this.pythonClient.getStudyResults(a);if(f=R.best_value||p,x=R.best_params||{},x&&Object.keys(x).length>0){let M=x.bootstrappedDemos||0;M>0&&(A=await this.bootstrapFewShotExamples(e,n,t.slice(0,Math.floor(t.length*.8))),A=A.slice(0,M))}}catch{}let h;try{let M=await it('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:x||{}});h={humanExplanation:M.humanExplanation??"",recommendations:M.recommendations??[],performanceAssessment:M.performanceAssessment??""}}catch{}await this.logOptimizationComplete("MiPRO (Python)",f,x,r,h);try{await this.pythonClient.deleteStudy(a)}catch{}this.stats.bestScore=f;let y=new Me(e.getSignature());x.instruction&&y.setInstruction(x.instruction);let T=x.temperature?{temperature:x.temperature}:void 0;y.setDemos(A,{modelConfig:T});let C=new Ct({bestScore:f,stats:this.stats,instruction:x.instruction,demos:A,examples:[],modelConfig:{temperature:x.temperature},optimizerType:"MiPRO (Python)",optimizationTime:Date.now()-s,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:y,optimizedProgram:C,finalConfiguration:{temperature:x.temperature,bootstrappedDemos:x.bootstrappedDemos||0,...x}}}generateOptimizationReport(e,t){console.log(`
980
+ Instruction:`;try{let m=(await it('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:s??"",tip:e??""})).instructionText;if(m&&m.trim().length>10)return m.trim()}catch{}let c=["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."],l=c[t%c.length]||c[0];return e&&(l=`${l} ${e}`),l}async proposeInstructionCandidates(e,t,n=[]){let r=[],s=this.getTeacherOrStudentAI(t),i,a;this.programAwareProposer&&(i=await this.generateProgramSummary(e,s)),this.dataAwareProposer&&(a=await this.generateDatasetSummary([...n],s));let u=this.tipAwareProposer?this.generateTips():[];for(let c=0;c<this.numCandidates;c++){let l=u.length>0?c%u.length:-1,p=l>=0?u[l]:void 0,d=await this.generateInstruction({tip:p,candidateIndex:c,ai:s,programSummary:i,datasetSummary:a,previousInstructions:r});r.push(d)}return r}async bootstrapFewShotExamples(e,t,n){return(await new ir({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 s=e[r];s&&t.push(s)}}return t}applyConfigToProgram(e,t,n,r){if(e.setInstruction&&e.setInstruction(t.instruction),e.setDemos){let s=[...n.slice(0,t.bootstrappedDemos)];if(t.labeledExamples>0&&e.getId){let i=e.getId();s.push({traces:r.slice(0,t.labeledExamples),programId:i})}s.length>0&&e.setDemos(s)}}async compile(e,t,n,r){let s=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 s=[...n.slice(0,t.bootstrappedDemos)];if(t.labeledExamples>0){let i=e.getId();s.push({traces:r.slice(0,t.labeledExamples),programId:i})}s.length>0&&e.setDemos(s)}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 s=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)}`,u={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},c=await this.pythonClient.createOptimizationJob(u);this.getOptimizerLogger()?.({name:"OptimizationStart",value:{optimizerType:"MiPRO (Python)",exampleCount:t.length,validationCount:0,config:{jobId:c.job_id,numTrials:this.numTrials}}});let p=Number.NEGATIVE_INFINITY,d,m=0,g=0;for(let R=0;R<this.numTrials;R++)try{let M=await this.pythonClient.suggestParameters(a),T=M.params.temperature,O=M.params.bootstrappedDemos,E=M.params.instruction,$=M.params.labeledExamples,N=this.optimizeTopP?M.params.topP:void 0;if(T===void 0)throw new Error(`Missing temperature parameter in suggestion: ${JSON.stringify(M)}`);if(O===void 0)throw new Error(`Missing bootstrappedDemos parameter in suggestion: ${JSON.stringify(M)}`);if(E===void 0)throw new Error(`Missing instruction parameter in suggestion: ${JSON.stringify(M)}`);if($===void 0)throw new Error(`Missing labeledExamples parameter in suggestion: ${JSON.stringify(M)}`);let S=e.clone();S.setInstruction(E);let v=S.getId();S.setDemos([{traces:this.selectLabeledExamples(t).slice(0,$),programId:v}]);let F=!this.minibatch||this.minibatchFullEvalSteps>0&&R%this.minibatchFullEvalSteps===this.minibatchFullEvalSteps-1?[...t]:(()=>{let z=Math.min(this.minibatchSize,t.length),j=new Set;for(;j.size<z;)j.add(Math.floor(Math.random()*t.length));return Array.from(j).map(K=>t[K])})(),U=await this.evaluateConfiguration(S,n,{temperature:T,bootstrappedDemos:O,topP:N},F);m++,await this.pythonClient.evaluateTrial({study_name:a,trial_number:M.trial_number,value:U}),U>p+this.minImprovementThreshold?(p=U,d={temperature:T,bootstrappedDemos:O,...N!==void 0?{topP:N}:{},trialNumber:M.trial_number},g=0):g+=1,this.currentRound=R+1;let L={temperature:T,bootstrappedDemos:O,...N!==void 0?{topP:N}:{},trialNumber:M.trial_number};if(this.localScoreHistory.push(U),this.localConfigurationHistory.push(L),await this.updateOptimizationProgress(this.currentRound,U,L,"MiPRO (Python)",{sampler:"TPESampler"},p,d),this.onProgress?.({round:R+1,totalRounds:this.numTrials,currentScore:U,bestScore:p,tokensUsed:this.stats.estimatedTokenUsage,timeElapsed:Date.now()-s,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,x={},A=[];try{let R=await this.pythonClient.getStudyResults(a);if(f=R.best_value||p,x=R.best_params||{},x&&Object.keys(x).length>0){let M=x.bootstrappedDemos||0;M>0&&(A=await this.bootstrapFewShotExamples(e,n,t.slice(0,Math.floor(t.length*.8))),A=A.slice(0,M))}}catch{}let h;try{let M=await it('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:x||{}});h={humanExplanation:M.humanExplanation??"",recommendations:M.recommendations??[],performanceAssessment:M.performanceAssessment??""}}catch{}await this.logOptimizationComplete("MiPRO (Python)",f,x,r,h);try{await this.pythonClient.deleteStudy(a)}catch{}this.stats.bestScore=f;let y=new Me(e.getSignature());x.instruction&&y.setInstruction(x.instruction);let C=x.temperature?{temperature:x.temperature}:void 0;y.setDemos(A,{modelConfig:C});let I=new It({bestScore:f,stats:this.stats,instruction:x.instruction,demos:A,examples:[],modelConfig:{temperature:x.temperature},optimizerType:"MiPRO (Python)",optimizationTime:Date.now()-s,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:y,optimizedProgram:I,finalConfiguration:{temperature:x.temperature,bootstrappedDemos:x.bootstrappedDemos||0,...x}}}generateOptimizationReport(e,t){console.log(`
981
981
  \u{1F389} MiPRO Optimization Complete!
982
982
  `),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
983
983
  `),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
984
984
  `),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
985
- `),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 s=0,i=0,a=0,u=r;for(let c of u)try{let l=await e.forward(this.studentAI,c,{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:l,example:c});if(typeof p=="number"&&!Number.isNaN(p)){s+=p,i++;let d=typeof this.targetScore=="number"?this.targetScore:.5;p>=d&&a++}}catch(l){this.getLogger()?.({name:"Notification",id:"mipro_evaluate",value:typeof l=="string"?l:String(l)})}return this.stats.successfulDemos+=a,i>0?s/i:0}};var ir=class{analyzeMappingDependencies(e,t){if(!e||typeof e!="function")return[];let n=[];try{let r=e.toString(),s=Array.from(r.matchAll(/state\.(\w+)/g));for(let i of s)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,s){typeof s=="string"&&!t.includes(s)&&t.push(s);let i=r[s];return i&&typeof i=="object"?n.createTrackingProxy(i,t):i},has(r,s){return typeof s=="string"&&!t.includes(s)&&t.push(s),s 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 s=Array.from(e.matchAll(/\{\s*(\w+)(?:\s*,\s*(\w+))*\s*\}\s*=\s*state/g));for(let i of s)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 ar(o,e,t){if(!t||t<=0||t>=o.length){let r=o.map((s,i)=>e(s,i));return Promise.all(r)}let n=new Array(o.length);for(let r=0;r<o.length;r+=t){let i=o.slice(r,r+t).map((u,c)=>{let l=r+c;return e(u,l).then(p=>({result:p,originalIndex:l}))}),a=await Promise.all(i);for(let{result:u,originalIndex:c}of a)n[c]=u}return n}var ur=class{steps=[];parallelGroups=[];analyzer=new ir;initialFields=new Set;addExecutionStep(e,t,n,r,s,i,a){let u=[],c=[],l=r||"map";if(t&&n)l="execute",u=this.analyzer.analyzeMappingDependencies(n,t),c=[`${t}Result`];else if(l==="map"&&s)c=this.analyzeMapTransformation(s),u=this.getAllProducedFields();else if(l==="parallel-map"){if(Array.isArray(s)){let d=new Set;for(let m of s)this.analyzeMapTransformation(m).forEach(f=>d.add(f));c=Array.from(d)}else s?c=this.analyzeMapTransformation(s):c=["_parallelMapResult"];u=this.getAllProducedFields()}else if(l==="merge"){if(i?.resultKey)c=[i.resultKey];else{let m=this.analyzeBranchMergeFields();c=m.length>0?m:["_mergedResult"]}e.toString().includes("_parallelResults")?u=["_parallelResults"]:u=this.getAllProducedFields()}else if(l==="parallel")c=["_parallelResults"],u=this.getAllProducedFields();else if(l==="derive")if(a?.outputFieldName&&a?.inputFieldName){c=[a.outputFieldName];let d=s?this.analyzer.analyzeMappingDependencies(s,"derive"):[];u=[a.inputFieldName,...d].filter((m,g,f)=>f.indexOf(m)===g)}else c=["_deriveResult"],u=this.getAllProducedFields();else e.toString().includes("transform(")?(l="map",u=this.getAllProducedFields(),c=["_mapResult"]):e.toString().includes("_parallelResults")&&(c=["_parallelResults"],u=this.getAllProducedFields());for(let d of u)this.getAllProducedFields().includes(d)||this.initialFields.add(d);let p={type:l,nodeName:t,dependencies:u,produces:c,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),s=e(t,{mainAi:{getOptions:()=>({trace:!1}),forward:()=>Promise.resolve({text:"mock"})},mainOptions:void 0});if(s&&typeof s=="object"&&"then"in s)return this.analyzeStepFunctionSource(e);if(s&&typeof s=="object"&&!Array.isArray(s)){let a=Object.keys(s).filter(u=>!n.includes(u));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 s=n.map(i=>{let a=i.match(/(\w+)\s*:/);return a?a[1]:null}).filter(Boolean);if(s.length>0)return s}let r=t.match(/state\.(\w+)\s*=/g);if(r){let s=r.map(i=>{let a=i.match(/state\.(\w+)\s*=/);return a?a[1]:null}).filter(Boolean);if(s.length>0)return s}}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 s of this.steps){if(e.has(s.stepIndex))continue;if(s.dependencies.length===0||s.dependencies.every(a=>t.has(a))){if(s.type==="merge"&&r.length>0)continue;if(r.push(s),e.add(s.stepIndex),s.type==="merge")break}}if(r.length>0){for(let s of r)s.produces.forEach(i=>t.add(i));this.parallelGroups.push({level:n,steps:r}),n++}else{let s=this.steps.filter(i=>!e.has(i.stepIndex));if(s.length>0){let i=s[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(s,i)=>{let a=await ar(n.steps,async l=>await l.stepFunction(s,i),e);if(a.some(l=>l&&typeof l=="object"&&"_parallelResults"in l)){let l=a.find(p=>p&&typeof p=="object"&&"_parallelResults"in p);return l||s}let c=s;for(let l of a)c={...c,...l};return c};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 dp=o=>{console.log(o)},cr=(o,e=!1)=>{if(e)return"[State hidden]";let t={};for(let[n,r]of Object.entries(o))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 s=JSON.stringify(r);s.length>200?t[n]=`${s.substring(0,200)}...`:t[n]=r}else t[n]=r;return JSON.stringify(t,null,2)},lr=o=>o<1e3?`${o.toFixed(1)}ms`:o<6e4?`${(o/1e3).toFixed(2)}s`:`${(o/6e4).toFixed(2)}min`,oo=(o=dp)=>{let e=new st,t=e.gray(`${"\u2501".repeat(80)}
985
+ `),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 s=0,i=0,a=0,u=r;for(let c of u)try{let l=await e.forward(this.studentAI,c,{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:l,example:c});if(typeof p=="number"&&!Number.isNaN(p)){s+=p,i++;let d=typeof this.targetScore=="number"?this.targetScore:.5;p>=d&&a++}}catch(l){this.getLogger()?.({name:"Notification",id:"mipro_evaluate",value:typeof l=="string"?l:String(l)})}return this.stats.successfulDemos+=a,i>0?s/i:0}};var ar=class{analyzeMappingDependencies(e,t){if(!e||typeof e!="function")return[];let n=[];try{let r=e.toString(),s=Array.from(r.matchAll(/state\.(\w+)/g));for(let i of s)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,s){typeof s=="string"&&!t.includes(s)&&t.push(s);let i=r[s];return i&&typeof i=="object"?n.createTrackingProxy(i,t):i},has(r,s){return typeof s=="string"&&!t.includes(s)&&t.push(s),s 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 s=Array.from(e.matchAll(/\{\s*(\w+)(?:\s*,\s*(\w+))*\s*\}\s*=\s*state/g));for(let i of s)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 ur(o,e,t){if(!t||t<=0||t>=o.length){let r=o.map((s,i)=>e(s,i));return Promise.all(r)}let n=new Array(o.length);for(let r=0;r<o.length;r+=t){let i=o.slice(r,r+t).map((u,c)=>{let l=r+c;return e(u,l).then(p=>({result:p,originalIndex:l}))}),a=await Promise.all(i);for(let{result:u,originalIndex:c}of a)n[c]=u}return n}var cr=class{steps=[];parallelGroups=[];analyzer=new ar;initialFields=new Set;addExecutionStep(e,t,n,r,s,i,a){let u=[],c=[],l=r||"map";if(t&&n)l="execute",u=this.analyzer.analyzeMappingDependencies(n,t),c=[`${t}Result`];else if(l==="map"&&s)c=this.analyzeMapTransformation(s),u=this.getAllProducedFields();else if(l==="parallel-map"){if(Array.isArray(s)){let d=new Set;for(let m of s)this.analyzeMapTransformation(m).forEach(f=>d.add(f));c=Array.from(d)}else s?c=this.analyzeMapTransformation(s):c=["_parallelMapResult"];u=this.getAllProducedFields()}else if(l==="merge"){if(i?.resultKey)c=[i.resultKey];else{let m=this.analyzeBranchMergeFields();c=m.length>0?m:["_mergedResult"]}e.toString().includes("_parallelResults")?u=["_parallelResults"]:u=this.getAllProducedFields()}else if(l==="parallel")c=["_parallelResults"],u=this.getAllProducedFields();else if(l==="derive")if(a?.outputFieldName&&a?.inputFieldName){c=[a.outputFieldName];let d=s?this.analyzer.analyzeMappingDependencies(s,"derive"):[];u=[a.inputFieldName,...d].filter((m,g,f)=>f.indexOf(m)===g)}else c=["_deriveResult"],u=this.getAllProducedFields();else e.toString().includes("transform(")?(l="map",u=this.getAllProducedFields(),c=["_mapResult"]):e.toString().includes("_parallelResults")&&(c=["_parallelResults"],u=this.getAllProducedFields());for(let d of u)this.getAllProducedFields().includes(d)||this.initialFields.add(d);let p={type:l,nodeName:t,dependencies:u,produces:c,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),s=e(t,{mainAi:{getOptions:()=>({trace:!1}),forward:()=>Promise.resolve({text:"mock"})},mainOptions:void 0});if(s&&typeof s=="object"&&"then"in s)return this.analyzeStepFunctionSource(e);if(s&&typeof s=="object"&&!Array.isArray(s)){let a=Object.keys(s).filter(u=>!n.includes(u));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 s=n.map(i=>{let a=i.match(/(\w+)\s*:/);return a?a[1]:null}).filter(Boolean);if(s.length>0)return s}let r=t.match(/state\.(\w+)\s*=/g);if(r){let s=r.map(i=>{let a=i.match(/state\.(\w+)\s*=/);return a?a[1]:null}).filter(Boolean);if(s.length>0)return s}}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 s of this.steps){if(e.has(s.stepIndex))continue;if(s.dependencies.length===0||s.dependencies.every(a=>t.has(a))){if(s.type==="merge"&&r.length>0)continue;if(r.push(s),e.add(s.stepIndex),s.type==="merge")break}}if(r.length>0){for(let s of r)s.produces.forEach(i=>t.add(i));this.parallelGroups.push({level:n,steps:r}),n++}else{let s=this.steps.filter(i=>!e.has(i.stepIndex));if(s.length>0){let i=s[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(s,i)=>{let a=await ur(n.steps,async l=>await l.stepFunction(s,i),e);if(a.some(l=>l&&typeof l=="object"&&"_parallelResults"in l)){let l=a.find(p=>p&&typeof p=="object"&&"_parallelResults"in p);return l||s}let c=s;for(let l of a)c={...c,...l};return c};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 mp=o=>{console.log(o)},lr=(o,e=!1)=>{if(e)return"[State hidden]";let t={};for(let[n,r]of Object.entries(o))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 s=JSON.stringify(r);s.length>200?t[n]=`${s.substring(0,200)}...`:t[n]=r}else t[n]=r;return JSON.stringify(t,null,2)},pr=o=>o<1e3?`${o.toFixed(1)}ms`:o<6e4?`${(o/1e3).toFixed(2)}s`:`${(o/6e4).toFixed(2)}min`,oo=(o=mp)=>{let e=new st,t=e.gray(`${"\u2501".repeat(80)}
986
986
  `),n=e.gray(`${"\u2500".repeat(40)}
987
987
  `);return r=>{let s="";switch(r.name){case"FlowStart":s=`
988
988
  ${e.blueBright("\u{1F504} [ AXFLOW START ]")}
@@ -994,13 +994,13 @@ ${t}`,s+=`${e.white("Input Fields:")} ${e.cyan(r.inputFields.join(", "))}
994
994
  `,s+=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}";s=`${e.greenBright(`${i} [ STEP ${r.stepIndex} START ]`)} ${e.white(`(${r.stepType})`)}`,r.nodeName&&(s+=` ${e.cyanBright(`Node: ${r.nodeName}`)}`),s+=`
995
995
  `,r.dependencies.length>0&&(s+=`${e.white("Dependencies:")} ${e.gray(r.dependencies.join(", "))}
996
996
  `),r.produces.length>0&&(s+=`${e.white("Produces:")} ${e.cyan(r.produces.join(", "))}
997
- `),s+=`${e.white("State:")} ${e.gray(cr(r.state,!0))}
998
- `,s+=n;break}case"StepComplete":{let i=(r.stepType==="execute"||r.stepType==="map"||r.stepType==="merge"||r.stepType==="parallel","\u2705");s=`${e.greenBright(`${i} [ STEP ${r.stepIndex} COMPLETE ]`)} ${e.white(`(${r.stepType})`)}`,r.nodeName&&(s+=` ${e.cyanBright(`Node: ${r.nodeName}`)}`),s+=` ${e.magenta(`in ${lr(r.executionTime)}`)}
997
+ `),s+=`${e.white("State:")} ${e.gray(lr(r.state,!0))}
998
+ `,s+=n;break}case"StepComplete":{let i=(r.stepType==="execute"||r.stepType==="map"||r.stepType==="merge"||r.stepType==="parallel","\u2705");s=`${e.greenBright(`${i} [ STEP ${r.stepIndex} COMPLETE ]`)} ${e.white(`(${r.stepType})`)}`,r.nodeName&&(s+=` ${e.cyanBright(`Node: ${r.nodeName}`)}`),s+=` ${e.magenta(`in ${pr(r.executionTime)}`)}
999
999
  `,r.newFields&&r.newFields.length>0&&(s+=`${e.white("New Fields:")} ${e.green(r.newFields.join(", "))}
1000
1000
  `),r.result&&r.nodeName&&(s+=`${e.white("Result:")} ${e.yellow(JSON.stringify(r.result,null,2))}
1001
1001
  `),s+=n;break}case"ParallelGroupStart":s=`${e.blueBright("\u2696\uFE0F [ PARALLEL GROUP START ]")} ${e.white(`Level ${r.groupLevel}`)}
1002
1002
  `,s+=`${e.white("Steps:")} ${e.yellow(r.stepsCount.toString())} ${e.gray(`(${r.stepTypes.join(", ")})`)}
1003
- `,s+=n;break;case"ParallelGroupComplete":s=`${e.blueBright("\u2705 [ PARALLEL GROUP COMPLETE ]")} ${e.white(`Level ${r.groupLevel}`)}`,s+=` ${e.magenta(`in ${lr(r.executionTime)}`)}
1003
+ `,s+=n;break;case"ParallelGroupComplete":s=`${e.blueBright("\u2705 [ PARALLEL GROUP COMPLETE ]")} ${e.white(`Level ${r.groupLevel}`)}`,s+=` ${e.magenta(`in ${pr(r.executionTime)}`)}
1004
1004
  `,s+=`${e.white("Steps Executed:")} ${e.yellow(r.stepsCount.toString())}
1005
1005
  `,s+=n;break;case"BranchEvaluation":s=`${e.yellow("\u{1F500} [ BRANCH EVALUATION ]")}
1006
1006
  `,s+=`${e.white("Branch Value:")} ${e.cyan(JSON.stringify(r.branchValue))}
@@ -1008,16 +1008,16 @@ ${t}`,s+=`${e.white("Input Fields:")} ${e.cyan(r.inputFields.join(", "))}
1008
1008
  `,r.hasMatchingBranch&&(s+=`${e.white("Branch Steps:")} ${e.yellow(r.branchStepsCount.toString())}
1009
1009
  `),s+=n;break;case"FlowComplete":s=`
1010
1010
  ${e.greenBright("\u2705 [ AXFLOW COMPLETE ]")}
1011
- ${t}`,s+=`${e.white("Total Time:")} ${e.magenta(lr(r.totalExecutionTime))}
1011
+ ${t}`,s+=`${e.white("Total Time:")} ${e.magenta(pr(r.totalExecutionTime))}
1012
1012
  `,s+=`${e.white("Steps Executed:")} ${e.yellow(r.stepsExecuted.toString())}
1013
1013
  `,s+=`${e.white("Output Fields:")} ${e.green(r.outputFields.join(", "))}
1014
- `,s+=`${e.white("Final State:")} ${e.gray(cr(r.finalState,!0))}
1014
+ `,s+=`${e.white("Final State:")} ${e.gray(lr(r.finalState,!0))}
1015
1015
  `,s+=t;break;case"FlowError":s=`
1016
1016
  ${e.redBright("\u274C [ AXFLOW ERROR ]")}
1017
1017
  ${t}`,r.stepIndex!==void 0&&(s+=`${e.white("Step:")} ${e.yellow(r.stepIndex.toString())}`,r.stepType&&(s+=` ${e.gray(`(${r.stepType})`)}`),r.nodeName&&(s+=` ${e.cyan(`Node: ${r.nodeName}`)}`),s+=`
1018
1018
  `),s+=`${e.white("Error:")} ${e.red(r.error)}
1019
- `,r.state&&(s+=`${e.white("State:")} ${e.gray(cr(r.state,!0))}
1020
- `),s+=t;break;default:s=e.gray(JSON.stringify(r,null,2))}o(s)}},mp=(o=dp)=>{let e="=".repeat(80),t="-".repeat(40);return n=>{let r="";switch(n.name){case"FlowStart":r=`
1019
+ `,r.state&&(s+=`${e.white("State:")} ${e.gray(lr(r.state,!0))}
1020
+ `),s+=t;break;default:s=e.gray(JSON.stringify(r,null,2))}o(s)}},gp=(o=mp)=>{let e="=".repeat(80),t="-".repeat(40);return n=>{let r="";switch(n.name){case"FlowStart":r=`
1021
1021
  [ AXFLOW START ]
1022
1022
  ${e}
1023
1023
  `,r+=`Input Fields: ${n.inputFields.join(", ")}
@@ -1029,16 +1029,16 @@ ${e}
1029
1029
  `;break;case"StepStart":r=`[ STEP ${n.stepIndex} START ] (${n.stepType})`,n.nodeName&&(r+=` Node: ${n.nodeName}`),r+=`
1030
1030
  `,n.dependencies.length>0&&(r+=`Dependencies: ${n.dependencies.join(", ")}
1031
1031
  `),n.produces.length>0&&(r+=`Produces: ${n.produces.join(", ")}
1032
- `),r+=`State: ${cr(n.state,!0)}
1032
+ `),r+=`State: ${lr(n.state,!0)}
1033
1033
  `,r+=`${t}
1034
- `;break;case"StepComplete":r=`[ STEP ${n.stepIndex} COMPLETE ] (${n.stepType})`,n.nodeName&&(r+=` Node: ${n.nodeName}`),r+=` in ${lr(n.executionTime)}
1034
+ `;break;case"StepComplete":r=`[ STEP ${n.stepIndex} COMPLETE ] (${n.stepType})`,n.nodeName&&(r+=` Node: ${n.nodeName}`),r+=` in ${pr(n.executionTime)}
1035
1035
  `,n.newFields&&n.newFields.length>0&&(r+=`New Fields: ${n.newFields.join(", ")}
1036
1036
  `),n.result&&n.nodeName&&(r+=`Result: ${JSON.stringify(n.result,null,2)}
1037
1037
  `),r+=`${t}
1038
1038
  `;break;case"ParallelGroupStart":r=`[ PARALLEL GROUP START ] Level ${n.groupLevel}
1039
1039
  `,r+=`Steps: ${n.stepsCount} (${n.stepTypes.join(", ")})
1040
1040
  `,r+=`${t}
1041
- `;break;case"ParallelGroupComplete":r=`[ PARALLEL GROUP COMPLETE ] Level ${n.groupLevel} in ${lr(n.executionTime)}
1041
+ `;break;case"ParallelGroupComplete":r=`[ PARALLEL GROUP COMPLETE ] Level ${n.groupLevel} in ${pr(n.executionTime)}
1042
1042
  `,r+=`Steps Executed: ${n.stepsCount}
1043
1043
  `,r+=`${t}
1044
1044
  `;break;case"BranchEvaluation":r=`[ BRANCH EVALUATION ]
@@ -1049,21 +1049,21 @@ ${e}
1049
1049
  `;break;case"FlowComplete":r=`
1050
1050
  [ AXFLOW COMPLETE ]
1051
1051
  ${e}
1052
- `,r+=`Total Time: ${lr(n.totalExecutionTime)}
1052
+ `,r+=`Total Time: ${pr(n.totalExecutionTime)}
1053
1053
  `,r+=`Steps Executed: ${n.stepsExecuted}
1054
1054
  `,r+=`Output Fields: ${n.outputFields.join(", ")}
1055
- `,r+=`Final State: ${cr(n.finalState,!0)}
1055
+ `,r+=`Final State: ${lr(n.finalState,!0)}
1056
1056
  `,r+=`${e}
1057
1057
  `;break;case"FlowError":r=`
1058
1058
  [ AXFLOW ERROR ]
1059
1059
  ${e}
1060
1060
  `,n.stepIndex!==void 0&&(r+=`Step: ${n.stepIndex}`,n.stepType&&(r+=` (${n.stepType})`),n.nodeName&&(r+=` Node: ${n.nodeName}`),r+=`
1061
1061
  `),r+=`Error: ${n.error}
1062
- `,n.state&&(r+=`State: ${cr(n.state,!0)}
1062
+ `,n.state&&(r+=`State: ${lr(n.state,!0)}
1063
1063
  `),r+=`${e}
1064
- `;break;default:r=JSON.stringify(n,null,2)}o(r)}},gp=oo(),fp=o=>{let e=new Map;return{logger:o,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 pr=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(s,i)=>{let a=n?.ai??i.mainAi,u=n?.options??i.mainOptions,c=t(s),l=u?.traceLabel?`Node:${e} (${u.traceLabel})`:`Node:${e}`,p;if("forward"in r&&typeof r.forward=="function")p=await r.forward(a,c,{...u,traceLabel:l});else throw new Error(`Node program for '${e}' does not have a forward method`);return{...s,[`${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}},js=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(s,i)=>{let a=n?.ai??i.mainAi,u=n?.options??i.mainOptions,c=t(s),l=u?.traceLabel?`Node:${e} (${u.traceLabel})`:`Node:${e}`,p;if("forward"in r&&typeof r.forward=="function")p=await r.forward(a,c,{...u,traceLabel:l});else throw new Error(`Node program for '${e}' does not have a forward method`);return{...s,[`${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 so=class o{static _ctorWarned=!1;nodes=new Map;flowDefinition=[];nodeGenerators=new Map;loopStack=[];stepLabels=new Map;branchContext=null;autoParallelConfig;executionPlanner=new ur;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(u=>u.name),s=this.extractInputValues(e),i=mt("sha256");i.update(n.hash()??"");let a=u=>{let c=typeof u;if(i.update(`|${c}|`),u==null){i.update("null");return}if(c==="string"||c==="number"||c==="boolean"){i.update(String(u));return}if(Array.isArray(u)){i.update("[");for(let l of u)a(l);i.update("]");return}if(typeof u=="object"&&u!==null&&"mimeType"in u&&"data"in u){let l=u;i.update(l.mimeType??"");let p=mt("sha256").update(l.data??"").digest("hex");i.update(p);return}if(typeof u=="object"){let l=u,p=Object.keys(l).sort();for(let d of p)i.update(`{${d}}`),a(l[d]);return}i.update(String(u))};for(let u of r)a(s?.[u]);return i.digest("hex")}async executeStepsWithLogging(e,t,n,r){let s={...t},i=0;for(let a=0;a<e.length;a++){let u=e[a];if(!u)continue;let c=n.mainOptions?.abortSignal;if(c?.aborted)throw new Fe("flow-between-steps",c.reason??"Flow aborted between steps");let l=this.getStepType(u,a),p=this.getStepMetadata(u,a),d=Object.keys(s);this.flowLogger&&this.flowLogger({name:"StepStart",timestamp:Date.now(),stepIndex:a,stepType:l,nodeName:p.nodeName,dependencies:p.dependencies,produces:p.produces,state:{...s}});let m=Date.now();this.timingLogger?.startTiming(`step-${a}`);try{s=await u(s,n),i++;let f=this.timingLogger?.endTiming(`step-${a}`)??Date.now()-m,A=Object.keys(s).filter(y=>!d.includes(y)),h;if(l==="execute"&&p.nodeName&&A.length>0){let y=`${p.nodeName}Result`;h=s[y]}this.flowLogger&&this.flowLogger({name:"StepComplete",timestamp:Date.now(),stepIndex:a,stepType:l,nodeName:p.nodeName,executionTime:f,state:{...s},newFields:A,result:h})}catch(g){throw this.flowLogger&&this.flowLogger({name:"FlowError",timestamp:Date.now(),error:g instanceof Error?g.message:String(g),stepIndex:a,stepType:l,nodeName:p.nodeName,state:{...s}}),g}}return{finalState:s,stepsExecuted:i}}getStepType(e,t){let n=this.executionPlanner.getExecutionPlan().steps.find(s=>s.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 s=e.toString();return{nodeName:this.extractNodeNameFromSource(s),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 ge().input("userInput",ge.string("User input to the flow")).output("flowOutput",ge.string("Output from the flow")).build();let t=new Set,n=new Set;for(let l of e.steps)l.produces.forEach(p=>t.add(p)),l.dependencies.forEach(p=>n.add(p));let r=new Set;for(let l of Array.from(n))t.has(l)||r.add(l);let s=new Set,i=e.steps[e.steps.length-1];if(i&&(i.type==="map"||i.type==="merge")){if(i.produces.forEach(l=>{l.startsWith("_")||s.add(l)}),i.type==="merge"&&i.produces.includes("_mergedResult"))for(let l of e.steps)l.type==="execute"&&l.produces.length>0&&l.produces.forEach(p=>s.add(p))}else for(let l of Array.from(t)){let p=!1;for(let d of e.steps)if(d.dependencies.includes(l)){p=!0;break}if(!p)if(l.endsWith("Result")){let d=l.replace("Result",""),m=this.nodeGenerators.get(d);if(m){let f=m.getSignature().getOutputFields();for(let x of f)s.add(x.name)}else s.add(l)}else s.add(l)}if(r.size===0&&s.size===0){let l=[],p=[];for(let[m,g]of Array.from(this.nodeGenerators)){let f=g.getSignature();for(let x of f.getInputFields()){let A=this.toCamelCase(`${m}_${x.name}`);l.push({name:A,type:x.type,description:x.description,isOptional:x.isOptional,isInternal:x.isInternal})}for(let x of f.getOutputFields()){let A=this.toCamelCase(`${m}_${x.name}`);p.push({name:A,type:x.type,description:x.description,isOptional:x.isOptional,isInternal:x.isInternal})}}let d=new Ne;return l.length>0?d.setInputFields(l):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 Ne,u=[];for(let l of Array.from(r))u.push({name:l,type:{name:"string"},description:`Input field: ${l}`});u.length===0&&u.push({name:"userInput",type:{name:"string"},description:"User input to the flow"});let c=[];for(let l of Array.from(s))l.startsWith("_")||c.push({name:l,type:{name:"string"},description:`Output field: ${l}`});return c.length===0&&c.push({name:"flowOutput",type:{name:"string"},description:"Output from the flow"}),a.setInputFields(u),a.setOutputFields(c),a}constructor(e){o._ctorWarned||(console.warn("[AxFlow] new AxFlow() is deprecated. Use flow() factory instead."),o._ctorWarned=!0),this.autoParallelConfig={enabled:e?.autoParallel!==!1,batchSize:e?.batchSize||10},e?.logger?this.flowLogger=e.logger:e?.debug===!0?this.flowLogger=oo():this.flowLogger=void 0,this.timingLogger=this.flowLogger?fp(this.flowLogger):void 0,(e?.tracer||e?.meter)&&(this.defaultAIOptions={tracer:e.tracer,meter:e.meter})}static create(e){return new o(e)}ensureProgram(){let e=this.inferSignatureFromFlow();if(!this.program){this.program=new Qt(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()}namedProgramInstances(){return this.ensureProgram(),this.program.namedProgramInstances()}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(`
1064
+ `;break;default:r=JSON.stringify(n,null,2)}o(r)}},fp=oo(),hp=o=>{let e=new Map;return{logger:o,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 dr=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(s,i)=>{let a=n?.ai??i.mainAi,u=n?.options??i.mainOptions,c=t(s),l=u?.traceLabel?`Node:${e} (${u.traceLabel})`:`Node:${e}`,p;if("forward"in r&&typeof r.forward=="function")p=await r.forward(a,c,{...u,traceLabel:l});else throw new Error(`Node program for '${e}' does not have a forward method`);return{...s,[`${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}},Bs=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(s,i)=>{let a=n?.ai??i.mainAi,u=n?.options??i.mainOptions,c=t(s),l=u?.traceLabel?`Node:${e} (${u.traceLabel})`:`Node:${e}`,p;if("forward"in r&&typeof r.forward=="function")p=await r.forward(a,c,{...u,traceLabel:l});else throw new Error(`Node program for '${e}' does not have a forward method`);return{...s,[`${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 so=class o{static _ctorWarned=!1;nodes=new Map;flowDefinition=[];nodeGenerators=new Map;loopStack=[];stepLabels=new Map;branchContext=null;autoParallelConfig;executionPlanner=new cr;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(u=>u.name),s=this.extractInputValues(e),i=mt("sha256");i.update(n.hash()??"");let a=u=>{let c=typeof u;if(i.update(`|${c}|`),u==null){i.update("null");return}if(c==="string"||c==="number"||c==="boolean"){i.update(String(u));return}if(Array.isArray(u)){i.update("[");for(let l of u)a(l);i.update("]");return}if(typeof u=="object"&&u!==null&&"mimeType"in u&&"data"in u){let l=u;i.update(l.mimeType??"");let p=mt("sha256").update(l.data??"").digest("hex");i.update(p);return}if(typeof u=="object"){let l=u,p=Object.keys(l).sort();for(let d of p)i.update(`{${d}}`),a(l[d]);return}i.update(String(u))};for(let u of r)a(s?.[u]);return i.digest("hex")}async executeStepsWithLogging(e,t,n,r){let s={...t},i=0;for(let a=0;a<e.length;a++){let u=e[a];if(!u)continue;let c=n.mainOptions?.abortSignal;if(c?.aborted)throw new Fe("flow-between-steps",c.reason??"Flow aborted between steps");let l=this.getStepType(u,a),p=this.getStepMetadata(u,a),d=Object.keys(s);this.flowLogger&&this.flowLogger({name:"StepStart",timestamp:Date.now(),stepIndex:a,stepType:l,nodeName:p.nodeName,dependencies:p.dependencies,produces:p.produces,state:{...s}});let m=Date.now();this.timingLogger?.startTiming(`step-${a}`);try{s=await u(s,n),i++;let f=this.timingLogger?.endTiming(`step-${a}`)??Date.now()-m,A=Object.keys(s).filter(y=>!d.includes(y)),h;if(l==="execute"&&p.nodeName&&A.length>0){let y=`${p.nodeName}Result`;h=s[y]}this.flowLogger&&this.flowLogger({name:"StepComplete",timestamp:Date.now(),stepIndex:a,stepType:l,nodeName:p.nodeName,executionTime:f,state:{...s},newFields:A,result:h})}catch(g){throw this.flowLogger&&this.flowLogger({name:"FlowError",timestamp:Date.now(),error:g instanceof Error?g.message:String(g),stepIndex:a,stepType:l,nodeName:p.nodeName,state:{...s}}),g}}return{finalState:s,stepsExecuted:i}}getStepType(e,t){let n=this.executionPlanner.getExecutionPlan().steps.find(s=>s.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 s=e.toString();return{nodeName:this.extractNodeNameFromSource(s),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 fe().input("userInput",fe.string("User input to the flow")).output("flowOutput",fe.string("Output from the flow")).build();let t=new Set,n=new Set;for(let l of e.steps)l.produces.forEach(p=>t.add(p)),l.dependencies.forEach(p=>n.add(p));let r=new Set;for(let l of Array.from(n))t.has(l)||r.add(l);let s=new Set,i=e.steps[e.steps.length-1];if(i&&(i.type==="map"||i.type==="merge")){if(i.produces.forEach(l=>{l.startsWith("_")||s.add(l)}),i.type==="merge"&&i.produces.includes("_mergedResult"))for(let l of e.steps)l.type==="execute"&&l.produces.length>0&&l.produces.forEach(p=>s.add(p))}else for(let l of Array.from(t)){let p=!1;for(let d of e.steps)if(d.dependencies.includes(l)){p=!0;break}if(!p)if(l.endsWith("Result")){let d=l.replace("Result",""),m=this.nodeGenerators.get(d);if(m){let f=m.getSignature().getOutputFields();for(let x of f)s.add(x.name)}else s.add(l)}else s.add(l)}if(r.size===0&&s.size===0){let l=[],p=[];for(let[m,g]of Array.from(this.nodeGenerators)){let f=g.getSignature();for(let x of f.getInputFields()){let A=this.toCamelCase(`${m}_${x.name}`);l.push({name:A,type:x.type,description:x.description,isOptional:x.isOptional,isInternal:x.isInternal})}for(let x of f.getOutputFields()){let A=this.toCamelCase(`${m}_${x.name}`);p.push({name:A,type:x.type,description:x.description,isOptional:x.isOptional,isInternal:x.isInternal})}}let d=new _e;return l.length>0?d.setInputFields(l):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 _e,u=[];for(let l of Array.from(r))u.push({name:l,type:{name:"string"},description:`Input field: ${l}`});u.length===0&&u.push({name:"userInput",type:{name:"string"},description:"User input to the flow"});let c=[];for(let l of Array.from(s))l.startsWith("_")||c.push({name:l,type:{name:"string"},description:`Output field: ${l}`});return c.length===0&&c.push({name:"flowOutput",type:{name:"string"},description:"Output from the flow"}),a.setInputFields(u),a.setOutputFields(c),a}constructor(e){o._ctorWarned||(console.warn("[AxFlow] new AxFlow() is deprecated. Use flow() factory instead."),o._ctorWarned=!0),this.autoParallelConfig={enabled:e?.autoParallel!==!1,batchSize:e?.batchSize||10},e?.logger?this.flowLogger=e.logger:e?.debug===!0?this.flowLogger=oo():this.flowLogger=void 0,this.timingLogger=this.flowLogger?hp(this.flowLogger):void 0,(e?.tracer||e?.meter)&&(this.defaultAIOptions={tracer:e.tracer,meter:e.meter})}static create(e){return new o(e)}ensureProgram(){let e=this.inferSignatureFromFlow();if(!this.program){this.program=new Qt(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()}namedProgramInstances(){return this.ensureProgram(),this.program.namedProgramInstances()}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(`
1065
1065
  `)[0]||"axFlow")).replace(/\s+/g,"_"),r=this.toCamelCase(n),s=async(i,a)=>{let u=a?.ai;if(!u)throw new Error("AI service is required to run the flow");let c=await this.forward(u,i??{}),l=e.getOutputFields(),p=c??{};return Object.keys(p).map(d=>{let m=l.find(g=>g.name===d);return m&&m.title?`${m.title}: ${p[d]}`:`${d}: ${p[d]}`}).join(`
1066
- `)};return{name:r,description:e.getDescription()??"Execute this AxFlow",parameters:e.toJSONSchema(),func:s}}getUsage(){let e=[];for(let[t,n]of Array.from(this.nodeUsage))e.push(...n);return Wr(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]=Wr(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,s=this.getCacheKey(t,r);if(r&&s){let a;try{a=await r(s)}catch{}if(a!==void 0){yield{version:0,index:0,delta:a};return}}let i=await this.forward(e,t,n);if(r&&s)try{await r(s,i)}catch{}yield{version:1,index:0,delta:i}}async forward(e,t,n){let r=n?.cachingFunction??fe.cachingFunction,s=this.getCacheKey(t,r);if(r&&s){let l;try{l=await r(s)}catch{}if(l!==void 0)return l}let i=Date.now();this.timingLogger?.startTiming("flow-execution");let a={},u,c;try{this.resetUsage(),this.resetTraces();let l=this.extractInputValues(t);if(this.nodeGenerators.size>0&&this.ensureProgram(),a={...l},this.flowLogger){let y=this.getExecutionPlan();this.flowLogger({name:"FlowStart",timestamp:i,inputFields:Object.keys(l),totalSteps:y.totalSteps,parallelGroups:y.parallelGroups,maxParallelism:y.maxParallelism,autoParallelEnabled:y.autoParallelEnabled})}let p=n?.tracer??this.defaultAIOptions?.tracer,d=n?.traceContext,m=d;if(p){let y=this.getExecutionPlan(),T=n?.traceLabel?`AxFlow > ${n.traceLabel}`:"AxFlow";u=p.startSpan(T,{kind:ct.INTERNAL,attributes:{total_steps:y.totalSteps,parallel_groups:y.parallelGroups,max_parallelism:y.maxParallelism,auto_parallel_enabled:y.autoParallelEnabled}});let C=d??qt.active();m=Ir.setSpan(C,u)}c=new AbortController,this.activeAbortControllers.add(c),this._stopRequested&&c.abort("Stopped by user (pre-forward)");let g=kt(n?.abortSignal,n?.abortController?.signal),f=kt(c.signal,kt(g,fe.abortSignal)),x={mainAi:e,mainOptions:(()=>{let y={...this.defaultAIOptions??{},...n};return n?.model&&(y.model=String(n.model)),p&&(y.tracer=p),m&&(y.traceContext=m),f&&(y.abortSignal=f),Object.keys(y).length>0?y:void 0})()},A=n?.autoParallel!==!1&&this.autoParallelConfig.enabled,h=0;if(A){this.executionPlanner.setInitialFields(Object.keys(l));let y=this.executionPlanner.createOptimizedExecution(this.autoParallelConfig.batchSize),T=await this.executeStepsWithLogging(y,a,x,!0);a=T.finalState,h=T.stepsExecuted}else{let y=await this.executeStepsWithLogging(this.flowDefinition,a,x,!1);a=y.finalState,h=y.stepsExecuted}if(this.flowLogger){let y=this.timingLogger?.endTiming("flow-execution")??Date.now()-i;this.flowLogger({name:"FlowComplete",timestamp:Date.now(),totalExecutionTime:y,finalState:a,outputFields:Object.keys(a),stepsExecuted:h})}if(r&&s)try{await r(s,a)}catch{}return a}catch(l){throw this.flowLogger&&this.flowLogger({name:"FlowError",timestamp:Date.now(),error:l instanceof Error?l.message:String(l),state:a}),l}finally{u&&u.end(),c&&this.activeAbortControllers.delete(c),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 Ne){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=it(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 s=>(await ar(n,async(u,c)=>{let l=u(s);return Promise.resolve(l)},this.autoParallelConfig.batchSize)).reduce((u,c)=>({...u,...c}),s);if(this.branchContext?.currentBranchValue!==void 0){let s=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];s.push(r),this.branchContext.branches.set(this.branchContext.currentBranchValue,s)}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 s=e(r);return Promise.resolve(s)};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 s=async(i,a)=>{let u=n?.ai??a.mainAi,c={...a.mainOptions??{},...n?.options??{}},l=t(i),p=c?.traceLabel?`Node:${e} (${c.traceLabel})`:`Node:${e}`,d;if("forward"in r&&typeof r.forward=="function"){if(d=await r.forward(u,l,{...c,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(s),this.branchContext.branches.set(this.branchContext.currentBranchValue,i)}else this.flowDefinition.push(s),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(s,e,t);return this.ensureProgram(),this}applyOptimization(e){this.program&&"applyOptimization"in this.program&&this.program.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 s=e.predicate(n),i=e.branches.get(s);if(this.flowLogger&&this.flowLogger({name:"BranchEvaluation",timestamp:Date.now(),branchValue:s,hasMatchingBranch:!!i,branchStepsCount:i?.length??0}),!i)return n;let a=n;for(let u of i)a=await u(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 s=await ar(e,async(i,a)=>{let u=new pr(this.nodeGenerators);return await i(u).executeSteps(n,r)},this.autoParallelConfig.batchSize);return{...n,_parallelResults:s}};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 s=i=>{let a=i._parallelResults;if(!Array.isArray(a))throw new Error("No parallel results found for merge");let u=r(...a),c={...i};return delete c._parallelResults,c[n]=u,c};return this.flowDefinition.push(s),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(s,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),s=this.flowDefinition.length;return this.flowDefinition.push(async(i,a)=>{let u=i,c=1,l=`_feedback_${t}_iterations`;for(typeof u[l]!="number"&&(u={...u,[l]:1});e(u)&&c<n;){c++,u={...u,[l]:c};for(let p=r;p<s;p++){let d=this.flowDefinition[p];d&&(u=await d(u,a))}}return u}),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(s=>s,{_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,s=this.flowDefinition.splice(e+1);return this.flowDefinition[e]=async(i,a)=>{let u=i,c=0;for(;n(u)&&c<r;){c++;for(let l of s)u=await l(u,a)}if(c>=r&&n(u))throw new Error(`While loop exceeded maximum iterations (${r}). Consider increasing maxIterations or ensuring the loop condition eventually becomes false.`);return u},this.nodeGenerators.size>0&&this.ensureProgram(),this}end(){return this.endWhile()}derive(e,t,n,r){let s=async i=>{let a=i[t];if(a===void 0)throw new Error(`Input field '${t}' not found in state`);let u;if(Array.isArray(a))if(this.autoParallelConfig.enabled){let c=r?.batchSize||this.autoParallelConfig.batchSize;u=await ar(a,async(l,p)=>n(l,p,i),c)}else u=a.map((c,l)=>n(c,l,i));else u=n(a,void 0,i);return{...i,[e]:u}};if(this.branchContext?.currentBranchValue!==void 0){let i=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];i.push(s),this.branchContext.branches.set(this.branchContext.currentBranchValue,i)}else this.flowDefinition.push(s),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(s,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 s=typeof t=="string"?Ne.create(t):t;if(n.prependInputs)for(let i of n.prependInputs)s=s.prependInputField(i.name,i.type);if(n.appendInputs)for(let i of n.appendInputs)s=s.appendInputField(i.name,i.type);if(n.prependOutputs)for(let i of n.prependOutputs)s=s.prependOutputField(i.name,i.type);if(n.appendOutputs)for(let i of n.appendOutputs)s=s.appendOutputField(i.name,i.type);return this.node(e,s)}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 zs(o){return so.create(o)}var qs=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 s=t.map(c=>`${c.hostPath}:${c.containerPath}`);n||await this.pullImage(e);let i={Image:e,Tty:!0,OpenStdin:!1,AttachStdin:!1,AttachStdout:!1,AttachStderr:!1,HostConfig:{Binds:s},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 u=await a.json();return this.containerId=u.Id,u}async findOrCreateContainer({imageName:e,volumes:t=[],doNotPullImage:n,tag:r}){let i=(await this.listContainers(!0)).filter(u=>u.Labels&&u.Labels["com.example.tag"]===r);if(i&&i.length>0){let u=Math.floor(Math.random()*i.length),c=i[u];if(c)return await this.connectToContainer(c.Id),{Id:c.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=[],s=await this.listContainers(!0),i=e?s.filter(a=>a.Labels["com.example.tag"]===e):s;for(let a of i){if(a.State.Status==="running"){let u=await this.fetchDockerAPI(`/containers/${a.Id}/stop?t=${n}`,{method:"POST"});if(!u.ok){console.warn(`Failed to stop container ${a.Id}: ${u.statusText}`);continue}r.push({Id:a.Id,Action:"stopped"})}if(t){let u=await this.fetchDockerAPI(`/containers/${a.Id}`,{method:"DELETE"});if(!u.ok){console.warn(`Failed to remove container ${a.Id}: ${u.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(),s=await this.fetchDockerAPI(`/exec/${r.Id}/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({Detach:!1,Tty:!1})});if(!s.ok)throw new Error(`Failed to start exec instance: ${s.statusText}`);return await s.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(s=>setTimeout(s,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 Hs=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 mn(o){return!!o&&/[A-Za-z0-9_$]/.test(o)}function hp(o){return!!o&&/[A-Za-z_$]/.test(o)}function Nt(o){let e="",t=0,n="normal",r=!1;for(;t<o.length;){let s=o[t]??"",i=o[t+1]??"";if(n==="lineComment"){s===`
1066
+ `)};return{name:r,description:e.getDescription()??"Execute this AxFlow",parameters:e.toJSONSchema(),func:s}}getUsage(){let e=[];for(let[t,n]of Array.from(this.nodeUsage))e.push(...n);return Vr(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]=Vr(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??he.cachingFunction,s=this.getCacheKey(t,r);if(r&&s){let a;try{a=await r(s)}catch{}if(a!==void 0){yield{version:0,index:0,delta:a};return}}let i=await this.forward(e,t,n);if(r&&s)try{await r(s,i)}catch{}yield{version:1,index:0,delta:i}}async forward(e,t,n){let r=n?.cachingFunction??he.cachingFunction,s=this.getCacheKey(t,r);if(r&&s){let l;try{l=await r(s)}catch{}if(l!==void 0)return l}let i=Date.now();this.timingLogger?.startTiming("flow-execution");let a={},u,c;try{this.resetUsage(),this.resetTraces();let l=this.extractInputValues(t);if(this.nodeGenerators.size>0&&this.ensureProgram(),a={...l},this.flowLogger){let y=this.getExecutionPlan();this.flowLogger({name:"FlowStart",timestamp:i,inputFields:Object.keys(l),totalSteps:y.totalSteps,parallelGroups:y.parallelGroups,maxParallelism:y.maxParallelism,autoParallelEnabled:y.autoParallelEnabled})}let p=n?.tracer??this.defaultAIOptions?.tracer,d=n?.traceContext,m=d;if(p){let y=this.getExecutionPlan(),C=n?.traceLabel?`AxFlow > ${n.traceLabel}`:"AxFlow";u=p.startSpan(C,{kind:ct.INTERNAL,attributes:{total_steps:y.totalSteps,parallel_groups:y.parallelGroups,max_parallelism:y.maxParallelism,auto_parallel_enabled:y.autoParallelEnabled}});let I=d??qt.active();m=wr.setSpan(I,u)}c=new AbortController,this.activeAbortControllers.add(c),this._stopRequested&&c.abort("Stopped by user (pre-forward)");let g=kt(n?.abortSignal,n?.abortController?.signal),f=kt(c.signal,kt(g,he.abortSignal)),x={mainAi:e,mainOptions:(()=>{let y={...this.defaultAIOptions??{},...n};return n?.model&&(y.model=String(n.model)),p&&(y.tracer=p),m&&(y.traceContext=m),f&&(y.abortSignal=f),Object.keys(y).length>0?y:void 0})()},A=n?.autoParallel!==!1&&this.autoParallelConfig.enabled,h=0;if(A){this.executionPlanner.setInitialFields(Object.keys(l));let y=this.executionPlanner.createOptimizedExecution(this.autoParallelConfig.batchSize),C=await this.executeStepsWithLogging(y,a,x,!0);a=C.finalState,h=C.stepsExecuted}else{let y=await this.executeStepsWithLogging(this.flowDefinition,a,x,!1);a=y.finalState,h=y.stepsExecuted}if(this.flowLogger){let y=this.timingLogger?.endTiming("flow-execution")??Date.now()-i;this.flowLogger({name:"FlowComplete",timestamp:Date.now(),totalExecutionTime:y,finalState:a,outputFields:Object.keys(a),stepsExecuted:h})}if(r&&s)try{await r(s,a)}catch{}return a}catch(l){throw this.flowLogger&&this.flowLogger({name:"FlowError",timestamp:Date.now(),error:l instanceof Error?l.message:String(l),state:a}),l}finally{u&&u.end(),c&&this.activeAbortControllers.delete(c),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 _e){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=it(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 s=>(await ur(n,async(u,c)=>{let l=u(s);return Promise.resolve(l)},this.autoParallelConfig.batchSize)).reduce((u,c)=>({...u,...c}),s);if(this.branchContext?.currentBranchValue!==void 0){let s=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];s.push(r),this.branchContext.branches.set(this.branchContext.currentBranchValue,s)}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 s=e(r);return Promise.resolve(s)};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 s=async(i,a)=>{let u=n?.ai??a.mainAi,c={...a.mainOptions??{},...n?.options??{}},l=t(i),p=c?.traceLabel?`Node:${e} (${c.traceLabel})`:`Node:${e}`,d;if("forward"in r&&typeof r.forward=="function"){if(d=await r.forward(u,l,{...c,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(s),this.branchContext.branches.set(this.branchContext.currentBranchValue,i)}else this.flowDefinition.push(s),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(s,e,t);return this.ensureProgram(),this}applyOptimization(e){this.program&&"applyOptimization"in this.program&&this.program.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 s=e.predicate(n),i=e.branches.get(s);if(this.flowLogger&&this.flowLogger({name:"BranchEvaluation",timestamp:Date.now(),branchValue:s,hasMatchingBranch:!!i,branchStepsCount:i?.length??0}),!i)return n;let a=n;for(let u of i)a=await u(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 s=await ur(e,async(i,a)=>{let u=new dr(this.nodeGenerators);return await i(u).executeSteps(n,r)},this.autoParallelConfig.batchSize);return{...n,_parallelResults:s}};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 s=i=>{let a=i._parallelResults;if(!Array.isArray(a))throw new Error("No parallel results found for merge");let u=r(...a),c={...i};return delete c._parallelResults,c[n]=u,c};return this.flowDefinition.push(s),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(s,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),s=this.flowDefinition.length;return this.flowDefinition.push(async(i,a)=>{let u=i,c=1,l=`_feedback_${t}_iterations`;for(typeof u[l]!="number"&&(u={...u,[l]:1});e(u)&&c<n;){c++,u={...u,[l]:c};for(let p=r;p<s;p++){let d=this.flowDefinition[p];d&&(u=await d(u,a))}}return u}),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(s=>s,{_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,s=this.flowDefinition.splice(e+1);return this.flowDefinition[e]=async(i,a)=>{let u=i,c=0;for(;n(u)&&c<r;){c++;for(let l of s)u=await l(u,a)}if(c>=r&&n(u))throw new Error(`While loop exceeded maximum iterations (${r}). Consider increasing maxIterations or ensuring the loop condition eventually becomes false.`);return u},this.nodeGenerators.size>0&&this.ensureProgram(),this}end(){return this.endWhile()}derive(e,t,n,r){let s=async i=>{let a=i[t];if(a===void 0)throw new Error(`Input field '${t}' not found in state`);let u;if(Array.isArray(a))if(this.autoParallelConfig.enabled){let c=r?.batchSize||this.autoParallelConfig.batchSize;u=await ur(a,async(l,p)=>n(l,p,i),c)}else u=a.map((c,l)=>n(c,l,i));else u=n(a,void 0,i);return{...i,[e]:u}};if(this.branchContext?.currentBranchValue!==void 0){let i=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];i.push(s),this.branchContext.branches.set(this.branchContext.currentBranchValue,i)}else this.flowDefinition.push(s),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(s,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 s=typeof t=="string"?_e.create(t):t;if(n.prependInputs)for(let i of n.prependInputs)s=s.prependInputField(i.name,i.type);if(n.appendInputs)for(let i of n.appendInputs)s=s.appendInputField(i.name,i.type);if(n.prependOutputs)for(let i of n.prependOutputs)s=s.prependOutputField(i.name,i.type);if(n.appendOutputs)for(let i of n.appendOutputs)s=s.appendOutputField(i.name,i.type);return this.node(e,s)}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 zs(o){return so.create(o)}var qs=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 s=t.map(c=>`${c.hostPath}:${c.containerPath}`);n||await this.pullImage(e);let i={Image:e,Tty:!0,OpenStdin:!1,AttachStdin:!1,AttachStdout:!1,AttachStderr:!1,HostConfig:{Binds:s},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 u=await a.json();return this.containerId=u.Id,u}async findOrCreateContainer({imageName:e,volumes:t=[],doNotPullImage:n,tag:r}){let i=(await this.listContainers(!0)).filter(u=>u.Labels&&u.Labels["com.example.tag"]===r);if(i&&i.length>0){let u=Math.floor(Math.random()*i.length),c=i[u];if(c)return await this.connectToContainer(c.Id),{Id:c.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=[],s=await this.listContainers(!0),i=e?s.filter(a=>a.Labels["com.example.tag"]===e):s;for(let a of i){if(a.State.Status==="running"){let u=await this.fetchDockerAPI(`/containers/${a.Id}/stop?t=${n}`,{method:"POST"});if(!u.ok){console.warn(`Failed to stop container ${a.Id}: ${u.statusText}`);continue}r.push({Id:a.Id,Action:"stopped"})}if(t){let u=await this.fetchDockerAPI(`/containers/${a.Id}`,{method:"DELETE"});if(!u.ok){console.warn(`Failed to remove container ${a.Id}: ${u.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(),s=await this.fetchDockerAPI(`/exec/${r.Id}/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({Detach:!1,Tty:!1})});if(!s.ok)throw new Error(`Failed to start exec instance: ${s.statusText}`);return await s.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(s=>setTimeout(s,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 Hs=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 fn(o){return!!o&&/[A-Za-z0-9_$]/.test(o)}function xp(o){return!!o&&/[A-Za-z_$]/.test(o)}function jt(o){let e="",t=0,n="normal",r=!1;for(;t<o.length;){let s=o[t]??"",i=o[t+1]??"";if(n==="lineComment"){s===`
1067
1067
  `?(e+=`
1068
1068
  `,n="normal"):e+=" ",t++;continue}if(n==="blockComment"){s==="*"&&i==="/"?(e+=" ",t+=2,n="normal"):(e+=s===`
1069
1069
  `?`
@@ -1072,65 +1072,65 @@ ${e}
1072
1072
  `:" ",r=!1,t++;continue}if(s==="\\"){e+=" ",r=!0,t++;continue}if(s===a){e+=" ",n="normal",t++;continue}e+=s===`
1073
1073
  `?`
1074
1074
  `:" ",t++;continue}if(s==="/"&&i==="/"){e+=" ",t+=2,n="lineComment";continue}if(s==="/"&&i==="*"){e+=" ",t+=2,n="blockComment";continue}if(s==="'"){e+=" ",t++,n="single";continue}if(s==='"'){e+=" ",t++,n="double";continue}if(s==="`"){e+=" ",t++,n="template";continue}e+=s,t++}return e}function io(o){let e=[],t=o.length,n=0,r=0,s=0,i=A=>{if(n++,A==="`"){let h=0;for(;n<t;){let y=o[n];if(y==="\\"){n+=2;continue}if(h>0){y==="{"?h++:y==="}"&&h--,n++;continue}if(y==="$"&&n+1<t&&o[n+1]==="{"){h++,n+=2;continue}if(y==="`"){n++;return}n++}return}for(;n<t;){let h=o[n];if(h==="\\"){n+=2;continue}if(h===A){n++;return}n++}},a=()=>{for(n+=2;n<t&&o[n]!==`
1075
- `;)n++},u=()=>{for(n+=2;n<t;){if(o[n]==="*"&&n+1<t&&o[n+1]==="/"){n+=2;return}n++}},c=()=>{let A=n;for(;n<t&&mn(o[n]);)n++;return o.slice(A,n)},l=()=>{let A=n;for(;n<t;){let h=o[n];if(h===" "||h===" "||h===`
1076
- `||h==="\r"){n++;continue}if(h==="/"&&n+1<t){if(o[n+1]==="/"){a();continue}if(o[n+1]==="*"){u();continue}}break}return n>A},p=A=>{let h=1;for(;n<t&&h>0;){if(l(),n>=t)return;let y=o[n];if(y===A){h--,n++;continue}if(y==="{"||y==="["){let T=y==="{"?"}":"]";n++,p(T);continue}if(y==="."&&n+2<t&&o[n+1]==="."&&o[n+2]==="."){if(n+=3,l(),n<t&&mn(o[n])){let T=c();T&&e.push(T)}continue}if(y===","){n++;continue}if(y==="="){n++;let T=0;for(;n<t;){let C=o[n];if(C==="'"||C==='"'||C==="`"){i(C);continue}if(C==="("||C==="["||C==="{"){T++,n++;continue}if(C===")"||C==="]"||C==="}"){if(T>0){T--,n++;continue}break}if(C===","&&T===0)break;n++}continue}if(mn(y)){let T=c();if(l(),n<t&&o[n]===":"){if(n++,l(),n<t){let C=o[n];if(C==="{"||C==="["){let R=C==="{"?"}":"]";n++,p(R)}else if(mn(C)){let R=c();R&&e.push(R)}}}else T&&e.push(T);continue}n++}},d=()=>{let A=0;for(;n<t;){let h=o[n];if(h==="'"||h==='"'||h==="`"){i(h);continue}if(h==="/"&&n+1<t){if(o[n+1]==="/"){a();continue}if(o[n+1]==="*"){u();continue}}if(h==="("||h==="["||h==="{"){A++,n++;continue}if(h===")"||h==="]"||h==="}"){if(A>0){A--,n++;continue}return!1}if(h===","&&A===0)return n++,!0;if(h===";"&&A===0)return n++,!1;if(h===`
1077
- `&&A===0){let y=n;return n++,l(),n<t&&o[n]===","?(n++,!0):(n=y,!1)}n++}return!1},m=()=>{for(;n<t;){if(l(),n>=t)return;let A=o[n];if(A==="{"){if(n++,p("}"),!d())return;continue}if(A==="["){if(n++,p("]"),!d())return;continue}if(mn(A)){let h=c();if(h&&e.push(h),!d())return;continue}return}},g=A=>{if(A===0)return!0;let h=A-1;for(;h>=0;){let y=o[h];if(y===" "||y===" "||y==="\r"){h--;continue}return y===`
1078
- `||y===";"||y==="{"||y==="}"}return!0};for(;n<t;){let A=o[n];if(A==="'"||A==='"'||A==="`"){i(A);continue}if(A==="/"&&n+1<t){if(o[n+1]==="/"){a();continue}if(o[n+1]==="*"){u();continue}}if(A==="{"){r++,n++;continue}if(A==="}"){r--,n++;continue}if(A==="("){s++,n++;continue}if(A===")"){s--,n++;continue}if(r===0&&s===0&&mn(A)){let h=n,y=c();(y==="var"||y==="let"||y==="const")&&n<t&&(o[n]===" "||o[n]===" "||o[n]===`
1079
- `)&&g(h)&&m();continue}n++}let f=new Set,x=[];for(let A of e)f.has(A)||(f.add(A),x.push(A));return x}function xp(o){let e=new Set(io(o)),t=Nt(o),n=t.length,r=0,s=0,i=0,a=m=>{let g=m;for(;g<n&&/\s/.test(t[g]??"");)g++;return g},u=m=>{let g=m;for(;g>=0&&/\s/.test(t[g]??"");)g--;return g},c=m=>{let g=t.slice(m,m+3),f=t.slice(m,m+2);return g==="==="||f==="=="||f==="=>"?!1:t[m]==="="||["+=","-=","*=","/=","%=","&=","|=","^=","&&=","||=","??=","**=","<<=",">>=",">>>="].some(x=>t.startsWith(x,m))},l=m=>{let g=m;for(;g<n&&mn(t[g]);)g++;return{word:t.slice(m,g),nextIndex:g}},p=(m,g,f)=>{let x=u(g-1),A=x>=0?t[x]:void 0,h=a(f);if(A==="."||A==="?")return;let T=t.slice(Math.max(0,g-2),g)==="++"||t.slice(Math.max(0,g-2),g)==="--",C=t.startsWith("++",h)||t.startsWith("--",h);(T||C||c(h))&&e.add(m)},d=(m,g)=>{let f=a(g);if(t[f]!==".")return;let x=a(f+1);if(!hp(t[x]))return;let{word:A,nextIndex:h}=l(x),y=a(h),T=t.slice(Math.max(0,m-2),m)==="++"||t.slice(Math.max(0,m-2),m)==="--",C=t.startsWith("++",y)||t.startsWith("--",y);A&&(T||C||c(y))&&e.add(A)};for(;r<n;){let m=t[r];if(m==="{"){s++,r++;continue}if(m==="}"){s--,r++;continue}if(m==="("){i++,r++;continue}if(m===")"){i--,r++;continue}if(s===0&&i===0&&hp(m)){let g=r,{word:f,nextIndex:x}=l(r);if(r=x,!f)continue;if(f==="globalThis"){d(g,x);continue}p(f,g,x);continue}r++}return[...e]}function Ws(o){let e=typeof self<"u"?self:globalThis,t=[],n=Object.getPrototypeOf(async()=>{}).constructor,r=o.functionRefKey,s="return",i="stdout",a=/^(if|for|while|switch|try|catch|finally|function|class|import|export|throw|return|var|let|const|break|continue|debugger)\b/,u=/^\s*return\s+([^\n;]+?)\s*;?\s*$/,c={network:["fetch","XMLHttpRequest","WebSocket","EventSource"],storage:["indexedDB","caches"],"code-loading":["importScripts"],communication:["BroadcastChannel"],timing:["performance"],workers:["Worker","SharedWorker"]},l=()=>{let b;if(typeof process<"u"&&typeof process.getBuiltinModule=="function"&&(b=process.getBuiltinModule.bind(process)),!b)try{b=new Function('return typeof require==="function"?require:undefined')()}catch{b=void 0}if(!(typeof b=="function"&&typeof process<"u"&&!!process.versions?.node))return{isNodeWorker:!1,parentPort:null};try{return{isNodeWorker:!0,parentPort:b("node:worker_threads").parentPort??null}}catch{return{isNodeWorker:!0,parentPort:null}}},{isNodeWorker:p,parentPort:d}=l(),m=()=>{if(!d&&typeof e.postMessage!="function")throw new Error("Worker transport unavailable: no postMessage channel");return{send:_=>{if(d){d.postMessage(_);return}e.postMessage(_)},setOnMessage:_=>{if(d){d.on("message",w=>_({data:w}));return}e.onmessage=_}}},{send:g,setOnMessage:f}=m(),x=b=>b&&(/\r?\n$/.test(b)?b:`${b}
1075
+ `;)n++},u=()=>{for(n+=2;n<t;){if(o[n]==="*"&&n+1<t&&o[n+1]==="/"){n+=2;return}n++}},c=()=>{let A=n;for(;n<t&&fn(o[n]);)n++;return o.slice(A,n)},l=()=>{let A=n;for(;n<t;){let h=o[n];if(h===" "||h===" "||h===`
1076
+ `||h==="\r"){n++;continue}if(h==="/"&&n+1<t){if(o[n+1]==="/"){a();continue}if(o[n+1]==="*"){u();continue}}break}return n>A},p=A=>{let h=1;for(;n<t&&h>0;){if(l(),n>=t)return;let y=o[n];if(y===A){h--,n++;continue}if(y==="{"||y==="["){let C=y==="{"?"}":"]";n++,p(C);continue}if(y==="."&&n+2<t&&o[n+1]==="."&&o[n+2]==="."){if(n+=3,l(),n<t&&fn(o[n])){let C=c();C&&e.push(C)}continue}if(y===","){n++;continue}if(y==="="){n++;let C=0;for(;n<t;){let I=o[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(fn(y)){let C=c();if(l(),n<t&&o[n]===":"){if(n++,l(),n<t){let I=o[n];if(I==="{"||I==="["){let R=I==="{"?"}":"]";n++,p(R)}else if(fn(I)){let R=c();R&&e.push(R)}}}else C&&e.push(C);continue}n++}},d=()=>{let A=0;for(;n<t;){let h=o[n];if(h==="'"||h==='"'||h==="`"){i(h);continue}if(h==="/"&&n+1<t){if(o[n+1]==="/"){a();continue}if(o[n+1]==="*"){u();continue}}if(h==="("||h==="["||h==="{"){A++,n++;continue}if(h===")"||h==="]"||h==="}"){if(A>0){A--,n++;continue}return!1}if(h===","&&A===0)return n++,!0;if(h===";"&&A===0)return n++,!1;if(h===`
1077
+ `&&A===0){let y=n;return n++,l(),n<t&&o[n]===","?(n++,!0):(n=y,!1)}n++}return!1},m=()=>{for(;n<t;){if(l(),n>=t)return;let A=o[n];if(A==="{"){if(n++,p("}"),!d())return;continue}if(A==="["){if(n++,p("]"),!d())return;continue}if(fn(A)){let h=c();if(h&&e.push(h),!d())return;continue}return}},g=A=>{if(A===0)return!0;let h=A-1;for(;h>=0;){let y=o[h];if(y===" "||y===" "||y==="\r"){h--;continue}return y===`
1078
+ `||y===";"||y==="{"||y==="}"}return!0};for(;n<t;){let A=o[n];if(A==="'"||A==='"'||A==="`"){i(A);continue}if(A==="/"&&n+1<t){if(o[n+1]==="/"){a();continue}if(o[n+1]==="*"){u();continue}}if(A==="{"){r++,n++;continue}if(A==="}"){r--,n++;continue}if(A==="("){s++,n++;continue}if(A===")"){s--,n++;continue}if(r===0&&s===0&&fn(A)){let h=n,y=c();(y==="var"||y==="let"||y==="const")&&n<t&&(o[n]===" "||o[n]===" "||o[n]===`
1079
+ `)&&g(h)&&m();continue}n++}let f=new Set,x=[];for(let A of e)f.has(A)||(f.add(A),x.push(A));return x}function Ap(o){let e=new Set(io(o)),t=jt(o),n=t.length,r=0,s=0,i=0,a=m=>{let g=m;for(;g<n&&/\s/.test(t[g]??"");)g++;return g},u=m=>{let g=m;for(;g>=0&&/\s/.test(t[g]??"");)g--;return g},c=m=>{let g=t.slice(m,m+3),f=t.slice(m,m+2);return g==="==="||f==="=="||f==="=>"?!1:t[m]==="="||["+=","-=","*=","/=","%=","&=","|=","^=","&&=","||=","??=","**=","<<=",">>=",">>>="].some(x=>t.startsWith(x,m))},l=m=>{let g=m;for(;g<n&&fn(t[g]);)g++;return{word:t.slice(m,g),nextIndex:g}},p=(m,g,f)=>{let x=u(g-1),A=x>=0?t[x]:void 0,h=a(f);if(A==="."||A==="?")return;let C=t.slice(Math.max(0,g-2),g)==="++"||t.slice(Math.max(0,g-2),g)==="--",I=t.startsWith("++",h)||t.startsWith("--",h);(C||I||c(h))&&e.add(m)},d=(m,g)=>{let f=a(g);if(t[f]!==".")return;let x=a(f+1);if(!xp(t[x]))return;let{word:A,nextIndex:h}=l(x),y=a(h),C=t.slice(Math.max(0,m-2),m)==="++"||t.slice(Math.max(0,m-2),m)==="--",I=t.startsWith("++",y)||t.startsWith("--",y);A&&(C||I||c(y))&&e.add(A)};for(;r<n;){let m=t[r];if(m==="{"){s++,r++;continue}if(m==="}"){s--,r++;continue}if(m==="("){i++,r++;continue}if(m===")"){i--,r++;continue}if(s===0&&i===0&&xp(m)){let g=r,{word:f,nextIndex:x}=l(r);if(r=x,!f)continue;if(f==="globalThis"){d(g,x);continue}p(f,g,x);continue}r++}return[...e]}function Ks(o){let e=typeof self<"u"?self:globalThis,t=[],n=Object.getPrototypeOf(async()=>{}).constructor,r=o.functionRefKey,s="return",i="stdout",a=/^(if|for|while|switch|try|catch|finally|function|class|import|export|throw|return|var|let|const|break|continue|debugger)\b/,u=/^\s*return\s+([^\n;]+?)\s*;?\s*$/,c={network:["fetch","XMLHttpRequest","WebSocket","EventSource"],storage:["indexedDB","caches"],"code-loading":["importScripts"],communication:["BroadcastChannel"],timing:["performance"],workers:["Worker","SharedWorker"]},l=()=>{let b;if(typeof process<"u"&&typeof process.getBuiltinModule=="function"&&(b=process.getBuiltinModule.bind(process)),!b)try{b=new Function('return typeof require==="function"?require:undefined')()}catch{b=void 0}if(!(typeof b=="function"&&typeof process<"u"&&!!process.versions?.node))return{isNodeWorker:!1,parentPort:null};try{return{isNodeWorker:!0,parentPort:b("node:worker_threads").parentPort??null}}catch{return{isNodeWorker:!0,parentPort:null}}},{isNodeWorker:p,parentPort:d}=l(),m=()=>{if(!d&&typeof e.postMessage!="function")throw new Error("Worker transport unavailable: no postMessage channel");return{send:_=>{if(d){d.postMessage(_);return}e.postMessage(_)},setOnMessage:_=>{if(d){d.on("message",w=>_({data:w}));return}e.onmessage=_}}},{send:g,setOnMessage:f}=m(),x=b=>b&&(/\r?\n$/.test(b)?b:`${b}
1080
1080
  `),A=b=>{let k=b.trim();return k.startsWith("//")||k.startsWith("/*")||k.startsWith("*")},h=b=>{let k=b.length-1;for(;k>=0;){let _=b[k].trim();if(_&&!A(_))break;k-=1}return k},y=b=>{if(!b)return!0;let k=b.split(`
1081
- `).find(_=>_.trim().length>0)?.trim();return!k||a.test(k)?!0:k.startsWith("{")&&!k.startsWith("({")||k==="}"||k==="};"||A(k)},T=(b,k)=>{let _=b,w=k.trim().replace(/;\s*$/,"");if(!w)return null;let z=w.lastIndexOf(";");if(z!==-1){let J=w.slice(z+1).trim(),Z=w.slice(0,z).trim();J&&(J.startsWith("//")||J.startsWith("/*")?Z&&(w=Z):(Z&&(_=_?`${_}
1082
- ${Z};`:`${Z};`),w=J))}return y(w)?null:{head:_,expression:w}},C=(b,k,_)=>{let w=b.slice(0,k).join(`
1083
- `),z=b.slice(k,_+1).join(`
1084
- `).trim();if(!z)return null;if(!z.includes(`
1085
- `)){let J=T(w,z);return J?J.head?`${J.head}
1081
+ `).find(_=>_.trim().length>0)?.trim();return!k||a.test(k)?!0:k.startsWith("{")&&!k.startsWith("({")||k==="}"||k==="};"||A(k)},C=(b,k)=>{let _=b,w=k.trim().replace(/;\s*$/,"");if(!w)return null;let B=w.lastIndexOf(";");if(B!==-1){let Q=w.slice(B+1).trim(),ne=w.slice(0,B).trim();Q&&(Q.startsWith("//")||Q.startsWith("/*")?ne&&(w=ne):(ne&&(_=_?`${_}
1082
+ ${ne};`:`${ne};`),w=Q))}return y(w)?null:{head:_,expression:w}},I=(b,k,_)=>{let w=b.slice(0,k).join(`
1083
+ `),B=b.slice(k,_+1).join(`
1084
+ `).trim();if(!B)return null;if(!B.includes(`
1085
+ `)){let Q=C(w,B);return Q?Q.head?`${Q.head}
1086
1086
  return (
1087
- ${J.expression}
1087
+ ${Q.expression}
1088
1088
  );`:`return (
1089
- ${J.expression}
1090
- );`:null}return y(z)?null:w?`${w}
1089
+ ${Q.expression}
1090
+ );`:null}return y(B)?null:w?`${w}
1091
1091
  return (
1092
- ${z}
1092
+ ${B}
1093
1093
  );`:`return (
1094
- ${z}
1094
+ ${B}
1095
1095
  );`},R=b=>{try{return new n(b),!0}catch{return!1}},M=b=>{let k=b.split(`
1096
- `),_=h(k);if(_<0)return b;let w=new Set;for(let z=_;z>=0;z-=1){let J=k[z]??"";if(!J.trim()||A(J))continue;let Z=C(k,z,_);if(Z&&!w.has(Z)&&(w.add(Z),R(Z)))return Z}return b},I=b=>{let k=u.exec(b);return k&&(k[1]||"").trim()||b},O=b=>{let k=[],_=b.length,w=0,z=0,J=0,Z=ee=>ee>="a"&&ee<="z"||ee>="A"&&ee<="Z"||ee>="0"&&ee<="9"||ee==="_"||ee==="$",Y=ee=>{if(w++,ee==="`"){let X=0;for(;w<_;){let Ae=b[w];if(Ae==="\\"){w+=2;continue}if(X>0){Ae==="{"?X++:Ae==="}"&&X--,w++;continue}if(Ae==="$"&&w+1<_&&b[w+1]==="{"){X++,w+=2;continue}if(Ae==="`"){w++;return}w++}}else for(;w<_;){let X=b[w];if(X==="\\"){w+=2;continue}if(X===ee){w++;return}w++}},U=()=>{for(w+=2;w<_&&b[w]!==`
1097
- `;)w++},K=()=>{for(w+=2;w<_;){if(b[w]==="*"&&w+1<_&&b[w+1]==="/"){w+=2;return}w++}},ne=()=>{let ee=w;for(;w<_&&Z(b[w]);)w++;return b.slice(ee,w)},te=()=>{let ee=w;for(;w<_;){let X=b[w];if(X===" "||X===" "||X===`
1098
- `||X==="\r"){w++;continue}if(X==="/"&&w+1<_){if(b[w+1]==="/"){U();continue}if(b[w+1]==="*"){K();continue}}break}return w>ee},Ie=ee=>{let X=1;for(;w<_&&X>0;){if(te(),w>=_)return;let Ae=b[w];if(Ae===ee){X--,w++;continue}if(Ae==="{"||Ae==="["){let Oe=Ae==="{"?"}":"]";w++,X++,w--,X--,w++,Ie(Oe);continue}if(Ae==="."&&w+2<_&&b[w+1]==="."&&b[w+2]==="."){if(w+=3,te(),w<_&&Z(b[w])){let Oe=ne();Oe&&k.push(Oe)}continue}if(Ae===","){w++;continue}if(Ae==="="){w++;let Oe=0;for(;w<_;){let Pe=b[w];if(Pe==="'"||Pe==='"'||Pe==="`"){Y(Pe);continue}if(Pe==="("||Pe==="["||Pe==="{"){Oe++,w++;continue}if(Pe===")"||Pe==="]"||Pe==="}"){if(Oe>0){Oe--,w++;continue}break}if(Pe===","&&Oe===0)break;w++}continue}if(Z(Ae)){let Oe=ne();if(te(),w<_&&b[w]===":"){if(w++,te(),w<_){let Pe=b[w];if(Pe==="{"||Pe==="["){let Ve=Pe==="{"?"}":"]";w++,Ie(Ve)}else if(Z(Pe)){let Ve=ne();Ve&&k.push(Ve)}}}else Oe&&k.push(Oe);continue}w++}},Ue=()=>{let ee=0;for(;w<_;){let X=b[w];if(X==="'"||X==='"'||X==="`"){Y(X);continue}if(X==="/"&&w+1<_){if(b[w+1]==="/"){U();continue}if(b[w+1]==="*"){K();continue}}if(X==="("||X==="["||X==="{"){ee++,w++;continue}if(X===")"||X==="]"||X==="}"){if(ee>0){ee--,w++;continue}return!1}if(X===","&&ee===0)return w++,!0;if(X===";"&&ee===0)return w++,!1;if(X===`
1099
- `&&ee===0){let Ae=w;return w++,te(),w<_&&b[w]===","?(w++,!0):(w=Ae,!1)}w++}return!1},Te=()=>{for(;w<_;){if(te(),w>=_)return;let ee=b[w];if(ee==="{"){if(w++,Ie("}"),!Ue())return;continue}if(ee==="["){if(w++,Ie("]"),!Ue())return;continue}if(Z(ee)){let X=ne();if(X&&k.push(X),!Ue())return;continue}return}},qe=ee=>{if(ee===0)return!0;let X=ee-1;for(;X>=0;){let Ae=b[X];if(Ae===" "||Ae===" "||Ae==="\r"){X--;continue}return Ae===`
1100
- `||Ae===";"||Ae==="{"||Ae==="}"}return!0};for(;w<_;){let ee=b[w];if(ee==="'"||ee==='"'||ee==="`"){Y(ee);continue}if(ee==="/"&&w+1<_){if(b[w+1]==="/"){U();continue}if(b[w+1]==="*"){K();continue}}if(ee==="{"){z++,w++;continue}if(ee==="}"){z--,w++;continue}if(ee==="("){J++,w++;continue}if(ee===")"){J--,w++;continue}if(z===0&&J===0&&Z(ee)){let X=w,Ae=ne();if((Ae==="var"||Ae==="let"||Ae==="const")&&w<_&&(b[w]===" "||b[w]===" "||b[w]===`
1101
- `)&&qe(X)){Te();continue}continue}w++}let _e=new Set,nt=[];for(let ee of k)_e.has(ee)||(_e.add(ee),nt.push(ee));return nt},E=b=>b.length===0?"":`
1102
- try { ${b.map(_=>`globalThis[${JSON.stringify(_)}] = ${_};`).join(" ")} } catch (_ax_e) {} void 0;`,$=b=>{if(typeof b=="string")return b;try{return JSON.stringify(b,null,2)}catch{return String(b)}},N=(b,k)=>{let _=e.console&&typeof e.console=="object"?e.console:null,w=_?.[b],z=typeof w=="function"?(...Z)=>w.apply(_,Z):null,J=(...Z)=>{k.push(Z.map($).join(" "))};return(!e.console||typeof e.console!="object")&&(e.console={}),e.console[b]=J,()=>{if(!(!e.console||typeof e.console!="object")){if(z){e.console[b]=z;return}try{delete e.console[b]}catch{e.console[b]=void 0}}}},S=b=>{let k=[];return ie&&(k.push(N("log",b)),k.push(N("info",b)),k.push(N("warn",b)),k.push(N("error",b))),k},v=()=>{let b=[],k=S(b),_=e.print;return Q===i&&(e.print=(...z)=>{b.push(z.map($).join(" "))}),{output:b,cleanup:()=>{for(let z of k)try{z()}catch{}if(Q===i)if(_===void 0)try{delete e.print}catch{e.print=void 0}else e.print=_}}},F=b=>{for(let k of b)try{Object.defineProperty(e,k,{value:void 0,writable:!1,configurable:!1})}catch{}},P=b=>{let k=new Set(Array.isArray(b)?b:[]);for(let[_,w]of Object.entries(c))k.has(_)||F(w)},L=b=>{p&&!b&&F(["process","require"])},D=o.maxErrorCauseDepth,j=(b,k=0,_=new Set)=>{if(k>D)return{name:"Error",message:"[cause chain truncated]"};if(b&&typeof b=="object"){if(_.has(b))return{name:"Error",message:"[circular]"};_.add(b)}let w=b,z=w?.name!=null?String(w.name):"Error",J=w?.message!=null?String(w.message):re(b),Z=typeof w?.stack=="string"?w.stack:void 0,Y;if(typeof w?.cause<"u"&&k<D)try{let K=w.cause;K instanceof Error||K&&typeof K=="object"&&("message"in K||"name"in K)?Y=j(K,k+1,_):Y={name:"Error",message:re(K)}}catch{Y={name:"Error",message:re(w.cause)}}let U={name:z,message:J};if(Z!==void 0&&(U.stack=Z),Y!==void 0&&(U.cause=Y),typeof w?.data<"u")try{U.data=typeof structuredClone=="function"?structuredClone(w.data):w.data}catch{}return U},G=b=>{if(typeof b=="string")return new Error(b);if(!b||typeof b!="object")return new Error(String(b));let k=b,_=new Error(k.message!=null?String(k.message):"");return _.name=k.name!=null?String(k.name):"Error",typeof k.stack=="string"&&(_.stack=k.stack),k.cause!==void 0&&(_.cause=G(k.cause)),k.data!==void 0&&(_.data=k.data),_},H=b=>{let k=globalThis.AggregateError,_=typeof k=="function"&&b instanceof k;return b instanceof SyntaxError||b instanceof TypeError||b instanceof RangeError||b instanceof ReferenceError||_||b instanceof EvalError||b instanceof URIError},re=b=>{if(b==null||typeof b!="object")return String(b);try{return JSON.stringify(b,null,2)}catch{return String(b)}},le=(b,k,_=0)=>{let w=b,z=w?.name!=null?String(w.name):"Error",J=w?.message!=null?String(w.message):re(b),Z=[`${z}: ${J}`],Y;if(typeof w?.stack=="string"){let U=w.stack.match(/<anonymous>:(\d+):(\d+)/);U&&(Y=Math.max(1,Number(U[1])-_),Z.push(` at line ${Y}, column ${U[2]}`))}if(k&&Y!==void 0&&Y>=1&&Y<=k.split(`
1103
- `).length){let U=k.split(`
1104
- `),K=Math.max(0,Y-2),ne=Math.min(U.length,Y+1),Ie=U.slice(K,ne).map((Ue,Te)=>` ${String(K+Te+1).padStart(3)}| ${Ue}`).join(`
1105
- `);Z.push(`Source:
1106
- ${Ie}`)}if(w?.data!==void 0&&Z.push(`Data: ${re(w.data)}`),w?.cause!==void 0){let U=(K,ne)=>{if(ne>4)return"[cause chain truncated]";let te=K,Ie=te?.name!=null?String(te.name):"Error",Ue=te?.message!=null?String(te.message):re(K),Te=[`${Ie}: ${Ue}`];return te?.data!==void 0&&Te.push(`Data: ${re(te.data)}`),te?.cause!==void 0&&Te.push(`Caused by: ${U(te.cause,ne+1)}`),Te.join(`
1107
- `)};Z.push(`Caused by: ${U(w.cause,1)}`)}return Z.join(`
1108
- `)},B=new Map,V=0,Q=s,ie=!1,W=[],q=b=>{if(!b||typeof b!="object"||Array.isArray(b))return!1;let k=Object.getPrototypeOf(b);return k===Object.prototype||k===null},oe=b=>typeof b=="string"&&b.trim().length>0,Ce=b=>{if(!oe(b)){if(!q(b))throw new Error("ask_clarification() choice entries must be non-empty strings or objects with a non-empty label");if(!oe(b.label))throw new Error("ask_clarification() choice objects require a non-empty label");if(b.value!==void 0&&!oe(b.value))throw new Error("ask_clarification() choice object values must be non-empty strings")}},Re=b=>{if(oe(b))return;if(!q(b))throw new Error("ask_clarification() requires a non-empty string or an object payload");if(!oe(b.question))throw new Error("ask_clarification() object payload requires a non-empty question");let k=new Set(["text","number","date","single_choice","multiple_choice"]),_;if(b.type===void 0)_=Array.isArray(b.choices)&&b.choices.length>0?"single_choice":void 0;else{if(typeof b.type!="string"||!k.has(b.type))throw new Error("ask_clarification() object payload type must be one of: text, number, date, single_choice, multiple_choice");_=b.type}let w=_==="single_choice"||_==="multiple_choice",z=b.choices;if(z!==void 0){if(!Array.isArray(z)||z.length===0)throw new Error("ask_clarification() choices must be a non-empty array when provided");for(let J of z)Ce(J)}else if(w)throw new Error("ask_clarification() choice payloads require a non-empty choices array")},ae=(b,k)=>{if(b==="final"){if(k.length===0)throw new Error("final() requires at least one argument");return}if(b==="ask_clarification"){if(k.length!==1)throw new Error("ask_clarification() requires exactly one argument");Re(k[0])}},ke=b=>{if(b==="final"||b==="ask_clarification")return b;let _=/^fn_\d+_(.+)$/.exec(b)?.[1];if(_==="final"||_==="ask_clarification")return _},ce=b=>(...k)=>{let _=ke(b);_&&ae(_,k);let w=++V,z=!1,J=new Promise((te,Ie)=>{B.set(w,{resolve:te,reject:Ie}),g({type:"fn-call",id:w,name:b,args:k})}),Z=J.then.bind(J),Y=J.catch.bind(J),U=J.finally.bind(J),K=()=>{z=!0},ne=new Proxy(J,{get(te,Ie,Ue){return Ie==="then"?(...Te)=>(K(),Z(...Te)):Ie==="catch"?(...Te)=>(K(),Y(...Te)):Ie==="finally"?(...Te)=>(K(),U(...Te)):Reflect.get(te,Ie,Ue)}});return J.catch(te=>{z||W.push(te)}),ne},me=async()=>{for(let b=0;b<50&&B.size>0;b+=1)await new Promise(k=>{setTimeout(k,0)})},be=b=>{if(!b||typeof b!="object")return b;if(Array.isArray(b)){for(let _=0;_<b.length;_+=1)b[_]=be(b[_]);return b}let k=b;if(r in k){let _=k[r];return typeof _=="string"?ce(_):void 0}for(let[_,w]of Object.entries(k))k[_]=be(w);return b},ue=b=>{for(let[k,_]of Object.entries(b)){let w=be(_),z=e[k];if(q(z)&&q(w)){for(let J of Object.keys(z))Object.hasOwn(w,J)||delete z[J];for(let[J,Z]of Object.entries(w))z[J]=Z;continue}e[k]=w}},xe=b=>{if(b.globals&&typeof b.globals=="object"&&ue(b.globals),Array.isArray(b.fnNames))for(let k of b.fnNames)typeof k=="string"&&(e[k]=ce(k))},ve=async b=>{let k=x(b),_=[];try{_=O(b)}catch{_=[]}let w=E(_),z=k;try{z=M(k)}catch{z=k}let J=z;if(w){let U=z.lastIndexOf(`
1109
- return (`);U!==-1?J=z.slice(0,U)+w+z.slice(U):J=z+w}let Z=R(J)?J:R(z)?z:k;return await new n(Z)()},je=b=>{let k=I(b),_=[];try{_=O(b)}catch{_=[]}let w=E(_),z=w?k+w:k;return(0,eval)(z)},$e=(b,k)=>{if(Q!==i)return b;let _=k.join(`
1110
- `).trim();return _||b},at=(b,k)=>b.length<=k?b:`${b.slice(0,k-3)}...`,Ee=b=>{if(b===null)return"null";if(b===void 0)return"undefined";let k=typeof b;if(typeof b=="string")return JSON.stringify(at(b,40));if(k==="number"||k==="boolean"||k==="bigint"||k==="symbol")return String(b);if(k==="function")return`[function ${(b.name&&typeof b.name=="string"?b.name??"":"")||"anonymous"}]`;if(Array.isArray(b))return`[array(${b.length})]`;if(b instanceof Date)return Number.isFinite(b.getTime())?b.toISOString():String(b);if(b instanceof Error)return`${b.name||"Error"}: ${b.message||""}`;if(b instanceof Map)return`[map(${b.size})]`;if(b instanceof Set)return`[set(${b.size})]`;let _=b&&typeof b=="object"&&"constructor"in b&&b.constructor&&typeof b.constructor.name=="string"?b.constructor.name??"":"";return _&&_!=="Object"?`[${_}]`:"[object]"},ze=b=>{if(b===null)return{type:"null"};if(Array.isArray(b))return{type:"array",ctor:"Array"};if(b instanceof Map)return{type:"map",ctor:"Map"};if(b instanceof Set)return{type:"set",ctor:"Set"};if(b instanceof Date)return{type:"date",ctor:"Date"};if(b instanceof Error)return{type:"error",ctor:typeof b.name=="string"&&b.name.trim()?b.name:"Error"};let k=typeof b;return k!=="object"?{type:k}:{type:"object",ctor:b&&typeof b=="object"&&"constructor"in b&&b.constructor&&typeof b.constructor.name=="string"?b.constructor.name??void 0:void 0}},pe=(b,k)=>{if(k==="string")return`${b.length} chars`;if(k==="array")return`${b.length} items`;if(k==="map"||k==="set")return`${b.size} items`;if(k==="object"&&b&&typeof b=="object")return`${Object.keys(b).length} keys`},De=(b,k,_)=>{if(k==="array")return"["+b.slice(0,3).map(z=>Ee(z)).join(", ")+(b.length>3?", ...":"")+"]";if(k==="map"){let w=b,z=Array.from(w.entries()).slice(0,3).map(([J,Z])=>`${Ee(J)} => ${Ee(Z)}`);return"Map("+w.size+") {"+z.join(", ")+(w.size>3?", ...":"")+"}"}if(k==="set"){let w=b,z=Array.from(w.values()).slice(0,5).map(J=>Ee(J));return"Set("+w.size+") {"+z.join(", ")+(w.size>5?", ...":"")+"}"}if(k==="date"||k==="error"||k==="function")return Ee(b);if(k==="object"&&b&&typeof b=="object"){let w=Object.keys(b),z=w.slice(0,4);return(_&&_!=="Object"?`${_} `:"")+"{"+z.join(", ")+(w.length>z.length?", ...":"")+"}"}return Ee(b)},Ke=b=>{let k=new Set([...t,...b??[]]),_=Object.getOwnPropertyNames(e).filter(w=>!k.has(w)&&!w.startsWith("_")).sort().flatMap(w=>{try{let z=Object.getOwnPropertyDescriptor(e,w);if(!z)return[];if("get"in z&&typeof z.get=="function"&&!("value"in z))return[{name:w,type:"accessor",preview:"[getter omitted]"}];let J="value"in z?z.value:e[w],Z=ze(J),Y=pe(J,Z.type),U=De(J,Z.type,Z.ctor);return[{name:w,type:Z.type,...Z.ctor?{ctor:Z.ctor}:{},...Y?{size:Y}:{},...U?{preview:at(U,96)}:{}}]}catch{return[{name:w,type:"unknown",preview:"[unavailable]"}]}});return JSON.stringify({version:1,entries:_})},Ye=b=>{if(typeof structuredClone=="function")try{return structuredClone(b),!0}catch{return!1}try{return JSON.stringify(b),!0}catch{return!1}},ut=b=>{let k=new Set([...t,...b??[]]),_={};return{version:1,entries:Object.getOwnPropertyNames(e).filter(z=>!k.has(z)&&!z.startsWith("_")).sort().flatMap(z=>{try{let J=Object.getOwnPropertyDescriptor(e,z);if(!J)return[];if("get"in J&&typeof J.get=="function"&&!("value"in J))return[{name:z,type:"accessor",preview:"[getter omitted]",restorable:!1}];let Z="value"in J?J.value:e[z],Y=ze(Z),U=pe(Z,Y.type),K=De(Z,Y.type,Y.ctor),ne=Ye(Z);return ne&&(_[z]=typeof structuredClone=="function"?structuredClone(Z):Z),[{name:z,type:Y.type,...Y.ctor?{ctor:Y.ctor}:{},...U?{size:U}:{},...K?{preview:at(K,96)}:{},restorable:ne}]}catch{return[{name:z,type:"unknown",preview:"[unavailable]",restorable:!1}]}}),bindings:_}};f(async b=>{let k=b.data;if(!k||typeof k!="object"||typeof k.type!="string")return;if(k.type==="init"){Q=k.outputMode===i?i:s,ie=k.captureConsole!==void 0?!!k.captureConsole:Q===i;let Y=k.allowUnsafeNodeHostAccess===!0;xe(k),P(k.permissions),L(Y),t=Object.getOwnPropertyNames(e).sort();return}if(k.type==="fn-result"){if(typeof k.id!="number")return;let Y=B.get(k.id);Y&&(B.delete(k.id),k.error!==void 0?Y.reject(G(k.error)):Y.resolve(k.value));return}if(k.type==="update-globals"){if(typeof k.id!="number")return;try{k.globals&&typeof k.globals=="object"&&ue(k.globals),g({type:"result",id:k.id,value:void 0})}catch(Y){g({type:"result",id:k.id,error:j(Y)})}return}if(k.type==="inspect-globals"){if(typeof k.id!="number")return;try{let Y=Array.isArray(k.reservedNames)?k.reservedNames.filter(U=>typeof U=="string"):void 0;g({type:"result",id:k.id,value:Ke(Y)})}catch(Y){g({type:"result",id:k.id,error:j(Y)})}return}if(k.type==="snapshot-globals"){if(typeof k.id!="number")return;try{let Y=Array.isArray(k.reservedNames)?k.reservedNames.filter(U=>typeof U=="string"):void 0;g({type:"result",id:k.id,value:ut(Y)})}catch(Y){g({type:"result",id:k.id,error:j(Y)})}return}if(k.type!=="execute"||typeof k.id!="number"||typeof k.code!="string")return;let _=k.id,w=k.code,z=/\bawait\b/.test(w),{output:J,cleanup:Z}=v();try{W.length=0;let Y=z?await ve(w):je(w);if(B.size>0&&await me(),await Promise.resolve(),W.length>0)throw W[0];let U=$e(Y,J);try{g({type:"result",id:_,value:U})}catch{g({type:"result",id:_,value:String(U)})}}catch(Y){H(Y)?g({type:"result",id:_,value:le(Y,w,z?2:0)}):g({type:"result",id:_,error:j(Y)})}finally{Z()}})}var Ha=4,Ap=16,Wa="__ax_rlm_fn_ref__",Ka=16;function yp(){let o={functionRefKey:Wa,maxErrorCauseDepth:Ka},e=`(${Ws.toString()})(${JSON.stringify(o)});
1096
+ `),_=h(k);if(_<0)return b;let w=new Set;for(let B=_;B>=0;B-=1){let Q=k[B]??"";if(!Q.trim()||A(Q))continue;let ne=I(k,B,_);if(ne&&!w.has(ne)&&(w.add(ne),R(ne)))return ne}return b},T=b=>{let k=u.exec(b);return k&&(k[1]||"").trim()||b},O=b=>{let k=[],_=b.length,w=0,B=0,Q=0,ne=oe=>oe>="a"&&oe<="z"||oe>="A"&&oe<="Z"||oe>="0"&&oe<="9"||oe==="_"||oe==="$",Z=oe=>{if(w++,oe==="`"){let ee=0;for(;w<_;){let ye=b[w];if(ye==="\\"){w+=2;continue}if(ee>0){ye==="{"?ee++:ye==="}"&&ee--,w++;continue}if(ye==="$"&&w+1<_&&b[w+1]==="{"){ee++,w+=2;continue}if(ye==="`"){w++;return}w++}}else for(;w<_;){let ee=b[w];if(ee==="\\"){w+=2;continue}if(ee===oe){w++;return}w++}},D=()=>{for(w+=2;w<_&&b[w]!==`
1097
+ `;)w++},V=()=>{for(w+=2;w<_;){if(b[w]==="*"&&w+1<_&&b[w+1]==="/"){w+=2;return}w++}},ie=()=>{let oe=w;for(;w<_&&ne(b[w]);)w++;return b.slice(oe,w)},se=()=>{let oe=w;for(;w<_;){let ee=b[w];if(ee===" "||ee===" "||ee===`
1098
+ `||ee==="\r"){w++;continue}if(ee==="/"&&w+1<_){if(b[w+1]==="/"){D();continue}if(b[w+1]==="*"){V();continue}}break}return w>oe},Re=oe=>{let ee=1;for(;w<_&&ee>0;){if(se(),w>=_)return;let ye=b[w];if(ye===oe){ee--,w++;continue}if(ye==="{"||ye==="["){let Oe=ye==="{"?"}":"]";w++,ee++,w--,ee--,w++,Re(Oe);continue}if(ye==="."&&w+2<_&&b[w+1]==="."&&b[w+2]==="."){if(w+=3,se(),w<_&&ne(b[w])){let Oe=ie();Oe&&k.push(Oe)}continue}if(ye===","){w++;continue}if(ye==="="){w++;let Oe=0;for(;w<_;){let Pe=b[w];if(Pe==="'"||Pe==='"'||Pe==="`"){Z(Pe);continue}if(Pe==="("||Pe==="["||Pe==="{"){Oe++,w++;continue}if(Pe===")"||Pe==="]"||Pe==="}"){if(Oe>0){Oe--,w++;continue}break}if(Pe===","&&Oe===0)break;w++}continue}if(ne(ye)){let Oe=ie();if(se(),w<_&&b[w]===":"){if(w++,se(),w<_){let Pe=b[w];if(Pe==="{"||Pe==="["){let We=Pe==="{"?"}":"]";w++,Re(We)}else if(ne(Pe)){let We=ie();We&&k.push(We)}}}else Oe&&k.push(Oe);continue}w++}},Ue=()=>{let oe=0;for(;w<_;){let ee=b[w];if(ee==="'"||ee==='"'||ee==="`"){Z(ee);continue}if(ee==="/"&&w+1<_){if(b[w+1]==="/"){D();continue}if(b[w+1]==="*"){V();continue}}if(ee==="("||ee==="["||ee==="{"){oe++,w++;continue}if(ee===")"||ee==="]"||ee==="}"){if(oe>0){oe--,w++;continue}return!1}if(ee===","&&oe===0)return w++,!0;if(ee===";"&&oe===0)return w++,!1;if(ee===`
1099
+ `&&oe===0){let ye=w;return w++,se(),w<_&&b[w]===","?(w++,!0):(w=ye,!1)}w++}return!1},Ie=()=>{for(;w<_;){if(se(),w>=_)return;let oe=b[w];if(oe==="{"){if(w++,Re("}"),!Ue())return;continue}if(oe==="["){if(w++,Re("]"),!Ue())return;continue}if(ne(oe)){let ee=ie();if(ee&&k.push(ee),!Ue())return;continue}return}},qe=oe=>{if(oe===0)return!0;let ee=oe-1;for(;ee>=0;){let ye=b[ee];if(ye===" "||ye===" "||ye==="\r"){ee--;continue}return ye===`
1100
+ `||ye===";"||ye==="{"||ye==="}"}return!0};for(;w<_;){let oe=b[w];if(oe==="'"||oe==='"'||oe==="`"){Z(oe);continue}if(oe==="/"&&w+1<_){if(b[w+1]==="/"){D();continue}if(b[w+1]==="*"){V();continue}}if(oe==="{"){B++,w++;continue}if(oe==="}"){B--,w++;continue}if(oe==="("){Q++,w++;continue}if(oe===")"){Q--,w++;continue}if(B===0&&Q===0&&ne(oe)){let ee=w,ye=ie();if((ye==="var"||ye==="let"||ye==="const")&&w<_&&(b[w]===" "||b[w]===" "||b[w]===`
1101
+ `)&&qe(ee)){Ie();continue}continue}w++}let Ne=new Set,nt=[];for(let oe of k)Ne.has(oe)||(Ne.add(oe),nt.push(oe));return nt},E=b=>b.length===0?"":`
1102
+ try { ${b.map(_=>`globalThis[${JSON.stringify(_)}] = ${_};`).join(" ")} } catch (_ax_e) {} void 0;`,$=b=>{if(typeof b=="string")return b;try{return JSON.stringify(b,null,2)}catch{return String(b)}},N=(b,k)=>{let _=e.console&&typeof e.console=="object"?e.console:null,w=_?.[b],B=typeof w=="function"?(...ne)=>w.apply(_,ne):null,Q=(...ne)=>{k.push(ne.map($).join(" "))};return(!e.console||typeof e.console!="object")&&(e.console={}),e.console[b]=Q,()=>{if(!(!e.console||typeof e.console!="object")){if(B){e.console[b]=B;return}try{delete e.console[b]}catch{e.console[b]=void 0}}}},S=b=>{let k=[];return le&&(k.push(N("log",b)),k.push(N("info",b)),k.push(N("warn",b)),k.push(N("error",b))),k},v=()=>{let b=[],k=S(b),_=e.print;return Y===i&&(e.print=(...B)=>{b.push(B.map($).join(" "))}),{output:b,cleanup:()=>{for(let B of k)try{B()}catch{}if(Y===i)if(_===void 0)try{delete e.print}catch{e.print=void 0}else e.print=_}}},P=b=>{for(let k of b)try{Object.defineProperty(e,k,{value:void 0,writable:!1,configurable:!1})}catch{}},F=b=>{let k=new Set(Array.isArray(b)?b:[]);for(let[_,w]of Object.entries(c))k.has(_)||P(w)},U=b=>{p&&!b&&P(["process","require"])},L=o.maxErrorCauseDepth,z=(b,k=0,_=new Set)=>{if(k>L)return{name:"Error",message:"[cause chain truncated]"};if(b&&typeof b=="object"){if(_.has(b))return{name:"Error",message:"[circular]"};_.add(b)}let w=b,B=w?.name!=null?String(w.name):"Error",Q=w?.message!=null?String(w.message):W(b),ne=typeof w?.stack=="string"?w.stack:void 0,Z;if(typeof w?.cause<"u"&&k<L)try{let V=w.cause;V instanceof Error||V&&typeof V=="object"&&("message"in V||"name"in V)?Z=z(V,k+1,_):Z={name:"Error",message:W(V)}}catch{Z={name:"Error",message:W(w.cause)}}let D={name:B,message:Q};if(ne!==void 0&&(D.stack=ne),Z!==void 0&&(D.cause=Z),typeof w?.data<"u")try{D.data=typeof structuredClone=="function"?structuredClone(w.data):w.data}catch{}return D},j=b=>{if(typeof b=="string")return new Error(b);if(!b||typeof b!="object")return new Error(String(b));let k=b,_=new Error(k.message!=null?String(k.message):"");return _.name=k.name!=null?String(k.name):"Error",typeof k.stack=="string"&&(_.stack=k.stack),k.cause!==void 0&&(_.cause=j(k.cause)),k.data!==void 0&&(_.data=k.data),_},K=b=>{let k=globalThis.AggregateError,_=typeof k=="function"&&b instanceof k;return b instanceof SyntaxError||b instanceof TypeError||b instanceof RangeError||b instanceof ReferenceError||_||b instanceof EvalError||b instanceof URIError},W=b=>{if(b==null||typeof b!="object")return String(b);try{return JSON.stringify(b,null,2)}catch{return String(b)}},pe=(b,k,_=0)=>{let w=b,B=w?.name!=null?String(w.name):"Error",Q=w?.message!=null?String(w.message):W(b),ne=[`${B}: ${Q}`],Z;if(typeof w?.stack=="string"){let D=w.stack.match(/<anonymous>:(\d+):(\d+)/);D&&(Z=Math.max(1,Number(D[1])-_),ne.push(` at line ${Z}, column ${D[2]}`))}if(k&&Z!==void 0&&Z>=1&&Z<=k.split(`
1103
+ `).length){let D=k.split(`
1104
+ `),V=Math.max(0,Z-2),ie=Math.min(D.length,Z+1),Re=D.slice(V,ie).map((Ue,Ie)=>` ${String(V+Ie+1).padStart(3)}| ${Ue}`).join(`
1105
+ `);ne.push(`Source:
1106
+ ${Re}`)}if(w?.data!==void 0&&ne.push(`Data: ${W(w.data)}`),w?.cause!==void 0){let D=(V,ie)=>{if(ie>4)return"[cause chain truncated]";let se=V,Re=se?.name!=null?String(se.name):"Error",Ue=se?.message!=null?String(se.message):W(V),Ie=[`${Re}: ${Ue}`];return se?.data!==void 0&&Ie.push(`Data: ${W(se.data)}`),se?.cause!==void 0&&Ie.push(`Caused by: ${D(se.cause,ie+1)}`),Ie.join(`
1107
+ `)};ne.push(`Caused by: ${D(w.cause,1)}`)}return ne.join(`
1108
+ `)},G=new Map,J=0,Y=s,le=!1,H=[],q=b=>{if(!b||typeof b!="object"||Array.isArray(b))return!1;let k=Object.getPrototypeOf(b);return k===Object.prototype||k===null},re=b=>typeof b=="string"&&b.trim().length>0,Ce=b=>{if(!re(b)){if(!q(b))throw new Error("ask_clarification() choice entries must be non-empty strings or objects with a non-empty label");if(!re(b.label))throw new Error("ask_clarification() choice objects require a non-empty label");if(b.value!==void 0&&!re(b.value))throw new Error("ask_clarification() choice object values must be non-empty strings")}},we=b=>{if(re(b))return;if(!q(b))throw new Error("ask_clarification() requires a non-empty string or an object payload");if(!re(b.question))throw new Error("ask_clarification() object payload requires a non-empty question");let k=new Set(["text","number","date","single_choice","multiple_choice"]),_;if(b.type===void 0)_=Array.isArray(b.choices)&&b.choices.length>0?"single_choice":void 0;else{if(typeof b.type!="string"||!k.has(b.type))throw new Error("ask_clarification() object payload type must be one of: text, number, date, single_choice, multiple_choice");_=b.type}let w=_==="single_choice"||_==="multiple_choice",B=b.choices;if(B!==void 0){if(!Array.isArray(B)||B.length===0)throw new Error("ask_clarification() choices must be a non-empty array when provided");for(let Q of B)Ce(Q)}else if(w)throw new Error("ask_clarification() choice payloads require a non-empty choices array")},ue=(b,k)=>{if(b==="final"){if(k.length===0)throw new Error("final() requires at least one argument");return}if(b==="ask_clarification"){if(k.length!==1)throw new Error("ask_clarification() requires exactly one argument");we(k[0])}},Te=b=>{if(b==="final"||b==="ask_clarification")return b;let _=/^fn_\d+_(.+)$/.exec(b)?.[1];if(_==="final"||_==="ask_clarification")return _},ae=b=>(...k)=>{let _=Te(b);_&&ue(_,k);let w=++J,B=!1,Q=new Promise((se,Re)=>{G.set(w,{resolve:se,reject:Re}),g({type:"fn-call",id:w,name:b,args:k})}),ne=Q.then.bind(Q),Z=Q.catch.bind(Q),D=Q.finally.bind(Q),V=()=>{B=!0},ie=new Proxy(Q,{get(se,Re,Ue){return Re==="then"?(...Ie)=>(V(),ne(...Ie)):Re==="catch"?(...Ie)=>(V(),Z(...Ie)):Re==="finally"?(...Ie)=>(V(),D(...Ie)):Reflect.get(se,Re,Ue)}});return Q.catch(se=>{B||H.push(se)}),ie},de=async()=>{for(let b=0;b<50&&G.size>0;b+=1)await new Promise(k=>{setTimeout(k,0)})},X=b=>{if(!b||typeof b!="object")return b;if(Array.isArray(b)){for(let _=0;_<b.length;_+=1)b[_]=X(b[_]);return b}let k=b;if(r in k){let _=k[r];return typeof _=="string"?ae(_):void 0}for(let[_,w]of Object.entries(k))k[_]=X(w);return b},te=b=>{for(let[k,_]of Object.entries(b)){let w=X(_),B=e[k];if(q(B)&&q(w)){for(let Q of Object.keys(B))Object.hasOwn(w,Q)||delete B[Q];for(let[Q,ne]of Object.entries(w))B[Q]=ne;continue}e[k]=w}},Ae=b=>{if(b.globals&&typeof b.globals=="object"&&te(b.globals),Array.isArray(b.fnNames))for(let k of b.fnNames)typeof k=="string"&&(e[k]=ae(k))},Se=async b=>{let k=x(b),_=[];try{_=O(b)}catch{_=[]}let w=E(_),B=k;try{B=M(k)}catch{B=k}let Q=B;if(w){let D=B.lastIndexOf(`
1109
+ return (`);D!==-1?Q=B.slice(0,D)+w+B.slice(D):Q=B+w}let ne=R(Q)?Q:R(B)?B:k;return await new n(ne)()},Be=b=>{let k=T(b),_=[];try{_=O(b)}catch{_=[]}let w=E(_),B=w?k+w:k;return(0,eval)(B)},Le=(b,k)=>{if(Y!==i)return b;let _=k.join(`
1110
+ `).trim();return _||b},at=(b,k)=>b.length<=k?b:`${b.slice(0,k-3)}...`,Ee=b=>{if(b===null)return"null";if(b===void 0)return"undefined";let k=typeof b;if(typeof b=="string")return JSON.stringify(at(b,40));if(k==="number"||k==="boolean"||k==="bigint"||k==="symbol")return String(b);if(k==="function")return`[function ${(b.name&&typeof b.name=="string"?b.name??"":"")||"anonymous"}]`;if(Array.isArray(b))return`[array(${b.length})]`;if(b instanceof Date)return Number.isFinite(b.getTime())?b.toISOString():String(b);if(b instanceof Error)return`${b.name||"Error"}: ${b.message||""}`;if(b instanceof Map)return`[map(${b.size})]`;if(b instanceof Set)return`[set(${b.size})]`;let _=b&&typeof b=="object"&&"constructor"in b&&b.constructor&&typeof b.constructor.name=="string"?b.constructor.name??"":"";return _&&_!=="Object"?`[${_}]`:"[object]"},ze=b=>{if(b===null)return{type:"null"};if(Array.isArray(b))return{type:"array",ctor:"Array"};if(b instanceof Map)return{type:"map",ctor:"Map"};if(b instanceof Set)return{type:"set",ctor:"Set"};if(b instanceof Date)return{type:"date",ctor:"Date"};if(b instanceof Error)return{type:"error",ctor:typeof b.name=="string"&&b.name.trim()?b.name:"Error"};let k=typeof b;return k!=="object"?{type:k}:{type:"object",ctor:b&&typeof b=="object"&&"constructor"in b&&b.constructor&&typeof b.constructor.name=="string"?b.constructor.name??void 0:void 0}},me=(b,k)=>{if(k==="string")return`${b.length} chars`;if(k==="array")return`${b.length} items`;if(k==="map"||k==="set")return`${b.size} items`;if(k==="object"&&b&&typeof b=="object")return`${Object.keys(b).length} keys`},De=(b,k,_)=>{if(k==="array")return"["+b.slice(0,3).map(B=>Ee(B)).join(", ")+(b.length>3?", ...":"")+"]";if(k==="map"){let w=b,B=Array.from(w.entries()).slice(0,3).map(([Q,ne])=>`${Ee(Q)} => ${Ee(ne)}`);return"Map("+w.size+") {"+B.join(", ")+(w.size>3?", ...":"")+"}"}if(k==="set"){let w=b,B=Array.from(w.values()).slice(0,5).map(Q=>Ee(Q));return"Set("+w.size+") {"+B.join(", ")+(w.size>5?", ...":"")+"}"}if(k==="date"||k==="error"||k==="function")return Ee(b);if(k==="object"&&b&&typeof b=="object"){let w=Object.keys(b),B=w.slice(0,4);return(_&&_!=="Object"?`${_} `:"")+"{"+B.join(", ")+(w.length>B.length?", ...":"")+"}"}return Ee(b)},Ve=b=>{let k=new Set([...t,...b??[]]),_=Object.getOwnPropertyNames(e).filter(w=>!k.has(w)&&!w.startsWith("_")).sort().flatMap(w=>{try{let B=Object.getOwnPropertyDescriptor(e,w);if(!B)return[];if("get"in B&&typeof B.get=="function"&&!("value"in B))return[{name:w,type:"accessor",preview:"[getter omitted]"}];let Q="value"in B?B.value:e[w],ne=ze(Q),Z=me(Q,ne.type),D=De(Q,ne.type,ne.ctor);return[{name:w,type:ne.type,...ne.ctor?{ctor:ne.ctor}:{},...Z?{size:Z}:{},...D?{preview:at(D,96)}:{}}]}catch{return[{name:w,type:"unknown",preview:"[unavailable]"}]}});return JSON.stringify({version:1,entries:_})},Ye=b=>{if(typeof structuredClone=="function")try{return structuredClone(b),!0}catch{return!1}try{return JSON.stringify(b),!0}catch{return!1}},ut=b=>{let k=new Set([...t,...b??[]]),_={};return{version:1,entries:Object.getOwnPropertyNames(e).filter(B=>!k.has(B)&&!B.startsWith("_")).sort().flatMap(B=>{try{let Q=Object.getOwnPropertyDescriptor(e,B);if(!Q)return[];if("get"in Q&&typeof Q.get=="function"&&!("value"in Q))return[{name:B,type:"accessor",preview:"[getter omitted]",restorable:!1}];let ne="value"in Q?Q.value:e[B],Z=ze(ne),D=me(ne,Z.type),V=De(ne,Z.type,Z.ctor),ie=Ye(ne);return ie&&(_[B]=typeof structuredClone=="function"?structuredClone(ne):ne),[{name:B,type:Z.type,...Z.ctor?{ctor:Z.ctor}:{},...D?{size:D}:{},...V?{preview:at(V,96)}:{},restorable:ie}]}catch{return[{name:B,type:"unknown",preview:"[unavailable]",restorable:!1}]}}),bindings:_}};f(async b=>{let k=b.data;if(!k||typeof k!="object"||typeof k.type!="string")return;if(k.type==="init"){Y=k.outputMode===i?i:s,le=k.captureConsole!==void 0?!!k.captureConsole:Y===i;let Z=k.allowUnsafeNodeHostAccess===!0;Ae(k),F(k.permissions),U(Z),t=Object.getOwnPropertyNames(e).sort();return}if(k.type==="fn-result"){if(typeof k.id!="number")return;let Z=G.get(k.id);Z&&(G.delete(k.id),k.error!==void 0?Z.reject(j(k.error)):Z.resolve(k.value));return}if(k.type==="update-globals"){if(typeof k.id!="number")return;try{k.globals&&typeof k.globals=="object"&&te(k.globals),g({type:"result",id:k.id,value:void 0})}catch(Z){g({type:"result",id:k.id,error:z(Z)})}return}if(k.type==="inspect-globals"){if(typeof k.id!="number")return;try{let Z=Array.isArray(k.reservedNames)?k.reservedNames.filter(D=>typeof D=="string"):void 0;g({type:"result",id:k.id,value:Ve(Z)})}catch(Z){g({type:"result",id:k.id,error:z(Z)})}return}if(k.type==="snapshot-globals"){if(typeof k.id!="number")return;try{let Z=Array.isArray(k.reservedNames)?k.reservedNames.filter(D=>typeof D=="string"):void 0;g({type:"result",id:k.id,value:ut(Z)})}catch(Z){g({type:"result",id:k.id,error:z(Z)})}return}if(k.type!=="execute"||typeof k.id!="number"||typeof k.code!="string")return;let _=k.id,w=k.code,B=/\bawait\b/.test(w),{output:Q,cleanup:ne}=v();try{H.length=0;let Z=B?await Se(w):Be(w);if(G.size>0&&await de(),await Promise.resolve(),H.length>0)throw H[0];let D=Le(Z,Q);try{g({type:"result",id:_,value:D})}catch{g({type:"result",id:_,value:String(D)})}}catch(Z){K(Z)?g({type:"result",id:_,value:pe(Z,w,B?2:0)}):g({type:"result",id:_,error:z(Z)})}finally{ne()}})}var Va=4,yp=16,Wa="__ax_rlm_fn_ref__",Ja=16;function bp(){let o={functionRefKey:Wa,maxErrorCauseDepth:Ja},e=`(${Ks.toString()})(${JSON.stringify(o)});
1111
1111
  `,t="";return e.includes("__name")&&(t+=`var __name=(fn,_n)=>fn;
1112
- `),t?`${t}${e}`:e}var bp=()=>typeof Worker<"u"&&typeof Blob<"u"&&typeof URL<"u"&&typeof URL.createObjectURL=="function",Ks=()=>typeof process<"u"&&!!process.versions?.node,Ug=()=>!!globalThis.Deno?.version?.deno,Gg=()=>globalThis.Deno?.version?.deno??null,Bg=o=>{let e=/^(\d+)\.(\d+)\.(\d+)$/.exec(o.trim());return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3])}:null},Tp=o=>Number.isFinite(o)?Math.max(1,Math.min(Ap,Math.floor(o))):Ha,jg=()=>{if(!Ks())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},zg=o=>{if(o!==void 0)return Tp(o);let e=jg();return e?Tp(Math.ceil(e/2)):Ha},qg=o=>o?.debugNodeWorkerPool?!0:(globalThis.process?.env??{}).AX_RLM_DEBUG_NODE_POOL==="1",Hg=o=>{let e=new Set(o),t={};return e.has("network")&&(t.net=!0),Object.keys(t).length>0?t:"none"},Wg=(o,e)=>{let t=Gg(),n=t?Bg(t):null;if(n?n.major>=1:!0)try{return new Worker(o,{type:"module",deno:{permissions:Hg(e)}})}catch{}return new Worker(o,{type:"module"})},Cp=(o,e)=>{let t=new Blob([o],{type:"application/javascript"}),n=URL.createObjectURL(t),r=Ug()?Wg(n,e):new Worker(n),s=!1,i=()=>{s||(URL.revokeObjectURL(n),s=!0)},a={postMessage:u=>r.postMessage(u),terminate:()=>{r.terminate(),i()},onmessage:null,onerror:null};return r.onmessage=u=>{a.onmessage?.({data:u.data})},r.onerror=u=>{a.onerror?.(new Error(u.message||"Worker error"))},a},Ya=async o=>{let e="node:worker_threads",{Worker:t}=await import(e),n=new t(o,{eval:!0}),r=null,s=null,i=!1;n.on("error",u=>{s?s(u):r=u}),n.on("exit",u=>{if(i=!0,u!==0&&!r){let c=new Error(`Worker exited with code ${u}`);s?s(c):r=c}}),n.on("message",u=>{a.onmessage?.({data:u})});let a={postMessage:u=>n.postMessage(u),terminate:()=>{n.terminate()},onmessage:null,get onerror(){return s},set onerror(u){if(s=u,u&&r){let c=r;r=null,u(c)}},get exited(){return i}};return a},Xa=class{source;maxSize;idle=[];pendingCreates=0;constructor(e,t){this.source=e,this.maxSize=t}warm(){if(Ks())for(;this.idle.length+this.pendingCreates<this.maxSize;)this.pendingCreates+=1,Ya(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(),Ya(this.source)}release(e){e.onmessage=null,e.onerror=null,e.terminate(),this.warm()}},Ip=new Map,Kg=(o,e)=>`${e}:${o}`,Vg=(o,e)=>{let t=Kg(o,e),n=Ip.get(t);if(n)return n;let r=new Xa(o,e);return Ip.set(t,r),r},wp=(o,e)=>{let t={},n=new Map,r=0,s=new WeakMap,i=(a,u)=>{if(typeof a=="function"){let g=`fn_${e?.nextFnId?e.nextFnId():++r}_${u||"root"}`;return n.set(g,a),{[Wa]:g}}if(!a||typeof a!="object")return a;if(s.has(a))return s.get(a);if(Array.isArray(a)){let m=[];s.set(a,m);for(let g=0;g<a.length;g+=1)m[g]=i(a[g],`${u}[${g}]`);return m}let c=Object.getPrototypeOf(a);if(!(c===Object.prototype||c===null))return a;let p=a,d={};s.set(a,d);for(let[m,g]of Object.entries(p))d[m]=i(g,u?`${u}.${m}`:m);return d};if(o)for(let[a,u]of Object.entries(o))t[a]=i(u,a);return{serializableGlobals:t,fnMap:n}},Rp=o=>{if(typeof structuredClone=="function")try{structuredClone(o)}catch(e){let t=e instanceof Error?e.message:String(e);throw new Error(`RLM globals must be structured-cloneable: ${t}`)}},Va=o=>!!o&&/[A-Za-z0-9_$]/.test(o),Ja=o=>!!o&&/[A-Za-z_$]/.test(o),Jg=(o,e)=>{let t=new Set(e);for(let m of io(o))if(t.has(m))return m;let n=Nt(o),r=n.length,s=0,i=0,a=0,u=m=>{let g=m;for(;g<r&&/\s/.test(n[g]??"");)g++;return g},c=m=>{let g=m;for(;g>=0&&/\s/.test(n[g]??"");)g--;return g},l=m=>{let g=c(m-1);if(g<0)return!0;let f=n[g];return f===`
1113
- `||f===";"||f==="{"||f==="}"},p=()=>{let m=s;for(;s<r&&Va(n[s]);)s++;return n.slice(m,s)},d=m=>{let g=n.slice(m,m+2);return n.slice(m,m+3)==="==="||g==="=="||g==="=>"?!1:n[m]==="="||["+=","-=","*=","/=","%=","&=","|=","^=","&&=","||=","??=","**=","<<=",">>=",">>>="].some(x=>n.startsWith(x,m))};for(;s<r;){let m=n[s];if(m==="{"){i++,s++;continue}if(m==="}"){i--,s++;continue}if(m==="("){a++,s++;continue}if(m===")"){a--,s++;continue}if(i===0&&a===0&&Ja(m)){let g=s,f=p();if((f==="function"||f==="class")&&l(g)){let x=u(s);if(Ja(n[x])){let A=x+1;for(;A<r&&Va(n[A]);)A++;let h=n.slice(x,A);if(t.has(h))return h}continue}if(f==="async"&&l(g)){let x=u(s);if(n.startsWith("function",x)){let A=u(x+8);if(Ja(n[A])){let h=A+1;for(;h<r&&Va(n[h]);)h++;let y=n.slice(A,h);if(t.has(y))return y}}continue}if(t.has(f)){let x=c(g-1),A=x>=0?n[x]:void 0,h=u(s),y=A==="."||A==="?"||A==="["&&n[h]==="]",T=n.startsWith("++",h)||n.startsWith("--",h)||x>0&&(n.slice(x-1,x+1)==="++"||n.slice(x-1,x+1)==="--");if(!y&&(T||d(h)))return f}continue}s++}};function Qa(o){if(o==null||typeof o!="object")return String(o);try{return JSON.stringify(o,null,2)}catch{return String(o)}}function vp(o,e=Ka,t=0,n=new Set){if(t>e)return{name:"Error",message:"[cause chain truncated]"};if(o!==null&&typeof o=="object"){if(n.has(o))return{name:"Error",message:"[circular]"};n.add(o)}let r=o!==null&&typeof o=="object"&&o.name!=null?String(o.name):"Error",s=o!==null&&typeof o=="object"&&o.message!=null?String(o.message):Qa(o),i=o!==null&&typeof o=="object"&&typeof o.stack=="string"?o.stack:void 0,a,u=o;if(u&&typeof u=="object"&&u.cause!==void 0&&t<e)try{let p=u.cause;p instanceof Error||p!==null&&typeof p=="object"&&("message"in p||"name"in p)?a=vp(p,e,t+1,n):a={name:"Error",message:Qa(p)}}catch{a={name:"Error",message:Qa(u.cause)}}let c={name:r,message:s};i!==void 0&&(c.stack=i),a!==void 0&&(c.cause=a);let l=o;if(l&&typeof l=="object"&&"data"in l&&l.data!==void 0)try{typeof structuredClone=="function"?c.data=structuredClone(l.data):c.data=l.data}catch{}return c}function Sp(o){if(typeof o=="string")return new Error(o);if(!o||typeof o!="object")return new Error(String(o));let e=o.message!=null?String(o.message):"Unknown error",t=new Error(e);return t.name=o.name!=null?String(o.name):"Error",typeof o.stack=="string"&&(t.stack=o.stack),o.cause!==void 0&&(t.cause=Sp(o.cause)),o.data!==void 0&&(t.data=o.data),t}function Qg(o){if(!o||typeof o!="object")return!1;let e=o;return typeof e.name=="string"&&typeof e.type=="string"&&(e.ctor===void 0||typeof e.ctor=="string")&&(e.size===void 0||typeof e.size=="string")&&(e.preview===void 0||typeof e.preview=="string")&&(e.restorable===void 0||typeof e.restorable=="boolean")}function Yg(o){if(!o||typeof o!="object")return{version:1,entries:[],bindings:{}};let e=o,t=Array.isArray(e.entries)?e.entries:[],n=e.bindings&&typeof e.bindings=="object"?e.bindings:{};return{version:1,entries:t.filter(Qg),bindings:n}}var Za=(i=>(i.NETWORK="network",i.STORAGE="storage",i.CODE_LOADING="code-loading",i.COMMUNICATION="communication",i.TIMING="timing",i.WORKERS="workers",i))(Za||{}),gn=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=zg(e?.nodeWorkerPoolSize),this.debugNodeWorkerPool=qg(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(`
1114
- `)}createSession(e){let t=yp(),n=Ks()?Vg(t,this.nodeWorkerPoolSize):null;n&&this.debugNodeWorkerPool&&console.debug(`[AxJSRuntime] Node worker pool size: ${this.nodeWorkerPoolSize}`),n?.warm();let r=null,s=null,i=null,a=!1,u=this.timeout,c=0,{serializableGlobals:l,fnMap:p}=wp(e,{nextFnId:()=>++c});Rp(l);let d=new Map,m=0,g=[],f=null,x=I=>{let O=I.data;if(!O||typeof O!="object"||!("type"in O)||O.type===void 0)return;let E=O;if(E.type==="result"){if(typeof E.id!="number")return;let $=d.get(E.id);$&&(d.delete(E.id),E.error!==void 0?$.reject(Sp(E.error)):$.resolve(E.value));return}if(E.type==="fn-call"){if(typeof E.id!="number"||typeof E.name!="string")return;let $=p.get(E.name);if(!$){r?.postMessage({type:"fn-result",id:E.id,error:`Function "${E.name}" not found`});return}Promise.resolve().then(()=>$(...E.args??[])).then(N=>{r?.postMessage({type:"fn-result",id:E.id,value:N})}).catch(N=>{r?.postMessage({type:"fn-result",id:E.id,error:vp(N)})})}},A=()=>{r&&(s==="node"&&n?n.release(r):r.terminate(),r=null,s=null),i=null},h=()=>{a=!0,A();for(let I of g)!I.started&&!I.settled&&(I.settled=!0,I.signal&&I.onAbort&&I.signal.removeEventListener("abort",I.onAbort),I.reject(new Error("Worker terminated")));g.length=0;for(let I of d.values())I.reject(new Error("Worker terminated"));d.clear()},y=I=>{A();for(let O of d.values())O.reject(I);d.clear()},T=I=>{I.postMessage({type:"init",globals:l,fnNames:[...p.keys()],permissions:[...this.permissions],allowUnsafeNodeHostAccess:this.allowUnsafeNodeHostAccess,outputMode:this.outputMode,captureConsole:this.captureConsole})};if(bp()){r=Cp(t,this.permissions),s="browser",r.onmessage=x,r.onerror=y;try{T(r)}catch(I){throw h(),I}}let C=async()=>{if(!r){if(a)throw new Error("Session is closed");if(bp()){r=Cp(t,this.permissions),s="browser",r.onmessage=x,r.onerror=y;try{T(r)}catch(I){throw h(),I}return}if(!Ks())throw new Error("No worker runtime available: Web Worker is unavailable in this environment");i||(i=(n?n.acquire():Ya(t)).then(I=>{if(a)throw n?n.release(I):I.terminate(),new Error("Session is closed");r=I,s="node",r.onmessage=x,r.onerror=y;try{T(r)}catch(O){throw n?n.release(I):I.terminate(),r=null,s=null,O}})),await i}},R=(I,O)=>{if(a)return Promise.reject(new Error("Session is closed"));let E=O.signal;if(E?.aborted)return Promise.reject(new Error(`Aborted: ${E.reason??"execution aborted"}`));let $=++m;return new Promise((N,S)=>{let v=N,F=S,P,L=()=>{};if(d.set($,{resolve:D=>{P&&clearTimeout(P),L(),v(D)},reject:D=>{P&&clearTimeout(P),L(),F(D)}}),E){let D=()=>{clearTimeout(P),d.delete($),h(),F(new Error(`Aborted: ${E.reason??"execution aborted"}`))};E.addEventListener("abort",D,{once:!0}),L=()=>{E.removeEventListener("abort",D)}}C().then(()=>{if(!r)throw new Error("Worker unavailable");P=setTimeout(()=>{d.delete($),A();for(let D of d.values())D.reject(new Error("Worker terminated"));d.clear(),S(new Error(O.timeoutMessage))},u),r.postMessage({...I,id:$})}).catch(D=>{d.get($)&&(d.delete($),clearTimeout(P),L(),F(D))})})},M=(I,O)=>a?Promise.reject(new Error("Session is closed")):I?.aborted?Promise.reject(new Error(`Aborted: ${I.reason??"execution aborted"}`)):new Promise((E,$)=>{let N={started:!1,settled:!1,signal:I,resolve:E,reject:$,operation:O};if(I){let v=()=>{if(N.settled)return;N.settled=!0;let F=g.indexOf(N);F!==-1&&g.splice(F,1),I.removeEventListener("abort",v),$(new Error(`Aborted: ${I.reason??"execution aborted"}`))};N.onAbort=v,I.addEventListener("abort",v,{once:!0})}g.push(N);let S=()=>{if(f)return;let v=g.find(P=>!P.started&&!P.settled);if(!v)return;let F=()=>{f=null,S()};f=(async()=>{if(!v.settled){if(a){v.settled=!0,v.signal&&v.onAbort&&v.signal.removeEventListener("abort",v.onAbort),v.reject(new Error("Worker terminated"));return}if(v.signal?.aborted){v.settled=!0,v.onAbort&&v.signal.removeEventListener("abort",v.onAbort),v.reject(new Error(`Aborted: ${v.signal.reason??"execution aborted"}`));return}v.started=!0;try{let P=await v.operation();if(v.settled)return;v.settled=!0,v.signal&&v.onAbort&&v.signal.removeEventListener("abort",v.onAbort),v.resolve(P)}catch(P){if(v.settled)return;v.settled=!0,v.signal&&v.onAbort&&v.signal.removeEventListener("abort",v.onAbort),v.reject(P)}finally{let P=g.indexOf(v);P!==-1&&g.splice(P,1),F()}}})().catch(()=>{F()})};S()});return{execute(I,O){if(a)return Promise.reject(new Error("Session is closed"));if(/['"]use strict['"]/.test(I))return Promise.resolve('[ERROR] "use strict" is not allowed in the runtime session. Remove it and try again.');let E=O?.reservedNames;if(E){let $=Jg(I,E);if($)return Promise.resolve(`[ERROR] Cannot assign to, redeclare, or shadow reserved runtime variable '${$}'. Use a different local variable name (for example: \`ctx\`) or access the original via \`inputs.${$}\`.`)}return M(O?.signal,()=>R({type:"execute",code:I},{signal:O?.signal,timeoutMessage:"Execution timed out"}))},inspectGlobals(I){return a?Promise.reject(new Error("Session is closed")):M(I?.signal,()=>R({type:"inspect-globals",reservedNames:I?.reservedNames},{signal:I?.signal,timeoutMessage:"Global inspection timed out"}).then(O=>typeof O=="string"?O:O===void 0?"":JSON.stringify(O)))},snapshotGlobals(I){return a?Promise.reject(new Error("Session is closed")):M(I?.signal,()=>R({type:"snapshot-globals",reservedNames:I?.reservedNames},{signal:I?.signal,timeoutMessage:"Global snapshot timed out"}).then(Yg))},async patchGlobals(I,O){if(!I||typeof I!="object"||Array.isArray(I))throw new Error("patchGlobals expects an object");let{serializableGlobals:E,fnMap:$}=wp(I,{nextFnId:()=>++c});if(Rp(E),Object.keys(E).length!==0){await M(O?.signal,()=>R({type:"update-globals",globals:E},{signal:O?.signal,timeoutMessage:"Global patch timed out"}));for(let[N,S]of Object.entries(E))l[N]=S;for(let[N,S]of $.entries())p.set(N,S)}},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 kp(o){return new gn(o)}var Vs=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(s=>s.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 s=>{let{result:i}=await this.sendRequest("tools/call",{name:t.name,arguments:s});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(s=>s.name===t),r=e.arguments?.length?{type:"object",properties:Object.fromEntries(e.arguments.map(s=>[s.name,{type:"string",description:s.description??""}])),required:e.arguments.filter(s=>s.required).map(s=>s.name)}:void 0;return{name:n?.updates.name??t,description:n?.updates.description??e.description??`Get the ${e.name} prompt`,parameters:r,func:async s=>{let i=await this.getPrompt(e.name,s);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(s=>s.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(s=>[s,{type:"string",description:`Value for ${s}`}])),required:r}:void 0,func:async s=>{let i=this.expandUriTemplate(e.uriTemplate,s??{}),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(`
1112
+ `),t?`${t}${e}`:e}var Cp=()=>typeof Worker<"u"&&typeof Blob<"u"&&typeof URL<"u"&&typeof URL.createObjectURL=="function",Vs=()=>typeof process<"u"&&!!process.versions?.node,Bg=()=>!!globalThis.Deno?.version?.deno,zg=()=>globalThis.Deno?.version?.deno??null,qg=o=>{let e=/^(\d+)\.(\d+)\.(\d+)$/.exec(o.trim());return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3])}:null},Ip=o=>Number.isFinite(o)?Math.max(1,Math.min(yp,Math.floor(o))):Va,Hg=()=>{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},Kg=o=>{if(o!==void 0)return Ip(o);let e=Hg();return e?Ip(Math.ceil(e/2)):Va},Vg=o=>o?.debugNodeWorkerPool?!0:(globalThis.process?.env??{}).AX_RLM_DEBUG_NODE_POOL==="1",Wg=o=>{let e=new Set(o),t={};return e.has("network")&&(t.net=!0),Object.keys(t).length>0?t:"none"},Jg=(o,e)=>{let t=zg(),n=t?qg(t):null;if(n?n.major>=1:!0)try{return new Worker(o,{type:"module",deno:{permissions:Wg(e)}})}catch{}return new Worker(o,{type:"module"})},Tp=(o,e)=>{let t=new Blob([o],{type:"application/javascript"}),n=URL.createObjectURL(t),r=Bg()?Jg(n,e):new Worker(n),s=!1,i=()=>{s||(URL.revokeObjectURL(n),s=!0)},a={postMessage:u=>r.postMessage(u),terminate:()=>{r.terminate(),i()},onmessage:null,onerror:null};return r.onmessage=u=>{a.onmessage?.({data:u.data})},r.onerror=u=>{a.onerror?.(new Error(u.message||"Worker error"))},a},Za=async o=>{let e="node:worker_threads",{Worker:t}=await import(e),n=new t(o,{eval:!0}),r=null,s=null,i=!1;n.on("error",u=>{s?s(u):r=u}),n.on("exit",u=>{if(i=!0,u!==0&&!r){let c=new Error(`Worker exited with code ${u}`);s?s(c):r=c}}),n.on("message",u=>{a.onmessage?.({data:u})});let a={postMessage:u=>n.postMessage(u),terminate:()=>{n.terminate()},onmessage:null,get onerror(){return s},set onerror(u){if(s=u,u&&r){let c=r;r=null,u(c)}},get exited(){return i}};return a},eu=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,Za(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(),Za(this.source)}release(e){e.onmessage=null,e.onerror=null,e.terminate(),this.warm()}},wp=new Map,Qg=(o,e)=>`${e}:${o}`,Yg=(o,e)=>{let t=Qg(o,e),n=wp.get(t);if(n)return n;let r=new eu(o,e);return wp.set(t,r),r},Rp=(o,e)=>{let t={},n=new Map,r=0,s=new WeakMap,i=(a,u)=>{if(typeof a=="function"){let g=`fn_${e?.nextFnId?e.nextFnId():++r}_${u||"root"}`;return n.set(g,a),{[Wa]:g}}if(!a||typeof a!="object")return a;if(s.has(a))return s.get(a);if(Array.isArray(a)){let m=[];s.set(a,m);for(let g=0;g<a.length;g+=1)m[g]=i(a[g],`${u}[${g}]`);return m}let c=Object.getPrototypeOf(a);if(!(c===Object.prototype||c===null))return a;let p=a,d={};s.set(a,d);for(let[m,g]of Object.entries(p))d[m]=i(g,u?`${u}.${m}`:m);return d};if(o)for(let[a,u]of Object.entries(o))t[a]=i(u,a);return{serializableGlobals:t,fnMap:n}},vp=o=>{if(typeof structuredClone=="function")try{structuredClone(o)}catch(e){let t=e instanceof Error?e.message:String(e);throw new Error(`RLM globals must be structured-cloneable: ${t}`)}},Qa=o=>!!o&&/[A-Za-z0-9_$]/.test(o),Ya=o=>!!o&&/[A-Za-z_$]/.test(o),Xg=(o,e)=>{let t=new Set(e);for(let m of io(o))if(t.has(m))return m;let n=jt(o),r=n.length,s=0,i=0,a=0,u=m=>{let g=m;for(;g<r&&/\s/.test(n[g]??"");)g++;return g},c=m=>{let g=m;for(;g>=0&&/\s/.test(n[g]??"");)g--;return g},l=m=>{let g=c(m-1);if(g<0)return!0;let f=n[g];return f===`
1113
+ `||f===";"||f==="{"||f==="}"},p=()=>{let m=s;for(;s<r&&Qa(n[s]);)s++;return n.slice(m,s)},d=m=>{let g=n.slice(m,m+2);return n.slice(m,m+3)==="==="||g==="=="||g==="=>"?!1:n[m]==="="||["+=","-=","*=","/=","%=","&=","|=","^=","&&=","||=","??=","**=","<<=",">>=",">>>="].some(x=>n.startsWith(x,m))};for(;s<r;){let m=n[s];if(m==="{"){i++,s++;continue}if(m==="}"){i--,s++;continue}if(m==="("){a++,s++;continue}if(m===")"){a--,s++;continue}if(i===0&&a===0&&Ya(m)){let g=s,f=p();if((f==="function"||f==="class")&&l(g)){let x=u(s);if(Ya(n[x])){let A=x+1;for(;A<r&&Qa(n[A]);)A++;let h=n.slice(x,A);if(t.has(h))return h}continue}if(f==="async"&&l(g)){let x=u(s);if(n.startsWith("function",x)){let A=u(x+8);if(Ya(n[A])){let h=A+1;for(;h<r&&Qa(n[h]);)h++;let y=n.slice(A,h);if(t.has(y))return y}}continue}if(t.has(f)){let x=c(g-1),A=x>=0?n[x]:void 0,h=u(s),y=A==="."||A==="?"||A==="["&&n[h]==="]",C=n.startsWith("++",h)||n.startsWith("--",h)||x>0&&(n.slice(x-1,x+1)==="++"||n.slice(x-1,x+1)==="--");if(!y&&(C||d(h)))return f}continue}s++}};function Xa(o){if(o==null||typeof o!="object")return String(o);try{return JSON.stringify(o,null,2)}catch{return String(o)}}function Sp(o,e=Ja,t=0,n=new Set){if(t>e)return{name:"Error",message:"[cause chain truncated]"};if(o!==null&&typeof o=="object"){if(n.has(o))return{name:"Error",message:"[circular]"};n.add(o)}let r=o!==null&&typeof o=="object"&&o.name!=null?String(o.name):"Error",s=o!==null&&typeof o=="object"&&o.message!=null?String(o.message):Xa(o),i=o!==null&&typeof o=="object"&&typeof o.stack=="string"?o.stack:void 0,a,u=o;if(u&&typeof u=="object"&&u.cause!==void 0&&t<e)try{let p=u.cause;p instanceof Error||p!==null&&typeof p=="object"&&("message"in p||"name"in p)?a=Sp(p,e,t+1,n):a={name:"Error",message:Xa(p)}}catch{a={name:"Error",message:Xa(u.cause)}}let c={name:r,message:s};i!==void 0&&(c.stack=i),a!==void 0&&(c.cause=a);let l=o;if(l&&typeof l=="object"&&"data"in l&&l.data!==void 0)try{typeof structuredClone=="function"?c.data=structuredClone(l.data):c.data=l.data}catch{}return c}function kp(o){if(typeof o=="string")return new Error(o);if(!o||typeof o!="object")return new Error(String(o));let e=o.message!=null?String(o.message):"Unknown error",t=new Error(e);return t.name=o.name!=null?String(o.name):"Error",typeof o.stack=="string"&&(t.stack=o.stack),o.cause!==void 0&&(t.cause=kp(o.cause)),o.data!==void 0&&(t.data=o.data),t}function Zg(o){if(!o||typeof o!="object")return!1;let e=o;return typeof e.name=="string"&&typeof e.type=="string"&&(e.ctor===void 0||typeof e.ctor=="string")&&(e.size===void 0||typeof e.size=="string")&&(e.preview===void 0||typeof e.preview=="string")&&(e.restorable===void 0||typeof e.restorable=="boolean")}function ef(o){if(!o||typeof o!="object")return{version:1,entries:[],bindings:{}};let e=o,t=Array.isArray(e.entries)?e.entries:[],n=e.bindings&&typeof e.bindings=="object"?e.bindings:{};return{version:1,entries:t.filter(Zg),bindings:n}}var tu=(i=>(i.NETWORK="network",i.STORAGE="storage",i.CODE_LOADING="code-loading",i.COMMUNICATION="communication",i.TIMING="timing",i.WORKERS="workers",i))(tu||{}),hn=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=Kg(e?.nodeWorkerPoolSize),this.debugNodeWorkerPool=Vg(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(`
1114
+ `)}createSession(e){let t=bp(),n=Vs()?Yg(t,this.nodeWorkerPoolSize):null;n&&this.debugNodeWorkerPool&&console.debug(`[AxJSRuntime] Node worker pool size: ${this.nodeWorkerPoolSize}`),n?.warm();let r=null,s=null,i=null,a=!1,u=this.timeout,c=0,{serializableGlobals:l,fnMap:p}=Rp(e,{nextFnId:()=>++c});vp(l);let d=new Map,m=0,g=[],f=null,x=T=>{let O=T.data;if(!O||typeof O!="object"||!("type"in O)||O.type===void 0)return;let E=O;if(E.type==="result"){if(typeof E.id!="number")return;let $=d.get(E.id);$&&(d.delete(E.id),E.error!==void 0?$.reject(kp(E.error)):$.resolve(E.value));return}if(E.type==="fn-call"){if(typeof E.id!="number"||typeof E.name!="string")return;let $=p.get(E.name);if(!$){r?.postMessage({type:"fn-result",id:E.id,error:`Function "${E.name}" not found`});return}Promise.resolve().then(()=>$(...E.args??[])).then(N=>{r?.postMessage({type:"fn-result",id:E.id,value:N})}).catch(N=>{r?.postMessage({type:"fn-result",id:E.id,error:Sp(N)})})}},A=()=>{r&&(s==="node"&&n?n.release(r):r.terminate(),r=null,s=null),i=null},h=()=>{a=!0,A();for(let T of g)!T.started&&!T.settled&&(T.settled=!0,T.signal&&T.onAbort&&T.signal.removeEventListener("abort",T.onAbort),T.reject(new Error("Worker terminated")));g.length=0;for(let T of d.values())T.reject(new Error("Worker terminated"));d.clear()},y=T=>{A();for(let O of d.values())O.reject(T);d.clear()},C=T=>{T.postMessage({type:"init",globals:l,fnNames:[...p.keys()],permissions:[...this.permissions],allowUnsafeNodeHostAccess:this.allowUnsafeNodeHostAccess,outputMode:this.outputMode,captureConsole:this.captureConsole})};if(Cp()){r=Tp(t,this.permissions),s="browser",r.onmessage=x,r.onerror=y;try{C(r)}catch(T){throw h(),T}}let I=async()=>{if(!r){if(a)throw new Error("Session is closed");if(Cp()){r=Tp(t,this.permissions),s="browser",r.onmessage=x,r.onerror=y;try{C(r)}catch(T){throw h(),T}return}if(!Vs())throw new Error("No worker runtime available: Web Worker is unavailable in this environment");i||(i=(n?n.acquire():Za(t)).then(T=>{if(a)throw n?n.release(T):T.terminate(),new Error("Session is closed");r=T,s="node",r.onmessage=x,r.onerror=y;try{C(r)}catch(O){throw n?n.release(T):T.terminate(),r=null,s=null,O}})),await i}},R=(T,O)=>{if(a)return Promise.reject(new Error("Session is closed"));let E=O.signal;if(E?.aborted)return Promise.reject(new Error(`Aborted: ${E.reason??"execution aborted"}`));let $=++m;return new Promise((N,S)=>{let v=N,P=S,F,U=()=>{};if(d.set($,{resolve:L=>{F&&clearTimeout(F),U(),v(L)},reject:L=>{F&&clearTimeout(F),U(),P(L)}}),E){let L=()=>{clearTimeout(F),d.delete($),h(),P(new Error(`Aborted: ${E.reason??"execution aborted"}`))};E.addEventListener("abort",L,{once:!0}),U=()=>{E.removeEventListener("abort",L)}}I().then(()=>{if(!r)throw new Error("Worker unavailable");F=setTimeout(()=>{d.delete($),A();for(let L of d.values())L.reject(new Error("Worker terminated"));d.clear(),S(new Error(O.timeoutMessage))},u),r.postMessage({...T,id:$})}).catch(L=>{d.get($)&&(d.delete($),clearTimeout(F),U(),P(L))})})},M=(T,O)=>a?Promise.reject(new Error("Session is closed")):T?.aborted?Promise.reject(new Error(`Aborted: ${T.reason??"execution aborted"}`)):new Promise((E,$)=>{let N={started:!1,settled:!1,signal:T,resolve:E,reject:$,operation:O};if(T){let v=()=>{if(N.settled)return;N.settled=!0;let P=g.indexOf(N);P!==-1&&g.splice(P,1),T.removeEventListener("abort",v),$(new Error(`Aborted: ${T.reason??"execution aborted"}`))};N.onAbort=v,T.addEventListener("abort",v,{once:!0})}g.push(N);let S=()=>{if(f)return;let v=g.find(F=>!F.started&&!F.settled);if(!v)return;let P=()=>{f=null,S()};f=(async()=>{if(!v.settled){if(a){v.settled=!0,v.signal&&v.onAbort&&v.signal.removeEventListener("abort",v.onAbort),v.reject(new Error("Worker terminated"));return}if(v.signal?.aborted){v.settled=!0,v.onAbort&&v.signal.removeEventListener("abort",v.onAbort),v.reject(new Error(`Aborted: ${v.signal.reason??"execution aborted"}`));return}v.started=!0;try{let F=await v.operation();if(v.settled)return;v.settled=!0,v.signal&&v.onAbort&&v.signal.removeEventListener("abort",v.onAbort),v.resolve(F)}catch(F){if(v.settled)return;v.settled=!0,v.signal&&v.onAbort&&v.signal.removeEventListener("abort",v.onAbort),v.reject(F)}finally{let F=g.indexOf(v);F!==-1&&g.splice(F,1),P()}}})().catch(()=>{P()})};S()});return{execute(T,O){if(a)return Promise.reject(new Error("Session is closed"));if(/['"]use strict['"]/.test(T))return Promise.resolve('[ERROR] "use strict" is not allowed in the runtime session. Remove it and try again.');let E=O?.reservedNames;if(E){let $=Xg(T,E);if($)return Promise.resolve(`[ERROR] Cannot assign to, redeclare, or shadow reserved runtime variable '${$}'. Use a different local variable name (for example: \`ctx\`) or access the original via \`inputs.${$}\`.`)}return M(O?.signal,()=>R({type:"execute",code:T},{signal:O?.signal,timeoutMessage:"Execution timed out"}))},inspectGlobals(T){return a?Promise.reject(new Error("Session is closed")):M(T?.signal,()=>R({type:"inspect-globals",reservedNames:T?.reservedNames},{signal:T?.signal,timeoutMessage:"Global inspection timed out"}).then(O=>typeof O=="string"?O:O===void 0?"":JSON.stringify(O)))},snapshotGlobals(T){return a?Promise.reject(new Error("Session is closed")):M(T?.signal,()=>R({type:"snapshot-globals",reservedNames:T?.reservedNames},{signal:T?.signal,timeoutMessage:"Global snapshot timed out"}).then(ef))},async patchGlobals(T,O){if(!T||typeof T!="object"||Array.isArray(T))throw new Error("patchGlobals expects an object");let{serializableGlobals:E,fnMap:$}=Rp(T,{nextFnId:()=>++c});if(vp(E),Object.keys(E).length!==0){await M(O?.signal,()=>R({type:"update-globals",globals:E},{signal:O?.signal,timeoutMessage:"Global patch timed out"}));for(let[N,S]of Object.entries(E))l[N]=S;for(let[N,S]of $.entries())p.set(N,S)}},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 Op(o){return new hn(o)}var Ws=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(s=>s.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 s=>{let{result:i}=await this.sendRequest("tools/call",{name:t.name,arguments:s});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(s=>s.name===t),r=e.arguments?.length?{type:"object",properties:Object.fromEntries(e.arguments.map(s=>[s.name,{type:"string",description:s.description??""}])),required:e.arguments.filter(s=>s.required).map(s=>s.name)}:void 0;return{name:n?.updates.name??t,description:n?.updates.description??e.description??`Get the ${e.name} prompt`,parameters:r,func:async s=>{let i=await this.getPrompt(e.name,s);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(s=>s.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(s=>[s,{type:"string",description:`Value for ${s}`}])),required:r}:void 0,func:async s=>{let i=this.expandUriTemplate(e.uriTemplate,s??{}),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(`
1115
1115
 
1116
1116
  `)}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(`
1117
- `)}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:s}=r;if(typeof s!="object"||s===null||Object.keys(s).length!==0)throw new Error(`Unexpected ping response: ${JSON.stringify(s)}`)}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=Ze(),r={jsonrpc:"2.0",id:n,method:e,params:t},s=new Promise((a,u)=>{this.activeRequests.set(n,{reject:u}),this.transport.send(r).then(c=>{if(this.activeRequests.delete(n),c!==null&&typeof c=="object"&&"error"in c){let l=c;u(new Error(`RPC Error ${l.error.code}: ${l.error.message}`))}else c!==null&&typeof c=="object"&&"result"in c?a({result:c.result}):u(new Error("Invalid response no result or error"))}).catch(c=>{this.activeRequests.delete(n),u(c)})}),{result:i}=await s;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 s={name:"Notification",id:"mcp_notification",value:`Sending notification: ${JSON.stringify(n,null,2)}`};this.logger(s)}await this.transport.sendNotification(n)}};function Op(o){if(typeof Buffer<"u")return Buffer.from(o).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"");let e="";for(let n=0;n<o.length;n++)e+=String.fromCharCode(o[n]);return(typeof btoa=="function"?btoa(e):"").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function Ep(o){let t=new TextEncoder().encode(o),n=await bu().subtle.digest("SHA-256",t);return new Uint8Array(n)}async function eu(){return Op(await Ep(Ze()+Math.random().toString(36)))}async function Mp(o){return Op(await Ep(o))}async function Js(o,e){let t=await fetch(o,{headers:e});if(!t.ok)throw new Error(`HTTP ${t.status} fetching ${o}: ${t.statusText}`);return await t.json()}function Pp(o){let e=new URLSearchParams;for(let[t,n]of Object.entries(o))n!==void 0&&e.set(t,n);return e.toString()}function ao(o){return o.endsWith("/")?o.slice(0,-1):o}function Xg(o){if(!o)return null;let e=o.match(/resource_metadata\s*=\s*"([^"]+)"/i)||o.match(/resource_metadata\s*=\s*([^,\s]+)/i);return e?e[1]:null}async function Fp(o,e){let t=Xg(e);if(t){let a=await Js(t),u=ao(new URL(o).toString().split("?")[0]),c=ao(a.resource??"");if(!c||c!==u)throw new Error(`Protected resource metadata 'resource' mismatch. Expected ${u} but got ${c}`);let l=Array.isArray(a.authorization_servers)?a.authorization_servers:[];if(l.length===0)throw new Error("No authorization_servers advertised by protected resource");return{resource:u,issuers:l}}let n=new URL(o),r=n.pathname.replace(/\/+$/,""),s=[];r&&r!=="/"&&s.push({url:`${n.origin}/.well-known/oauth-protected-resource${r}`,expected:`${n.origin}${r}`}),s.push({url:`${n.origin}/.well-known/oauth-protected-resource`,expected:`${n.origin}`});let i;for(let a of s)try{let u=await Js(a.url),c=ao(u.resource??""),l=ao(a.expected);if(!c||c!==l)throw new Error(`Protected resource metadata 'resource' mismatch. Expected ${l} but got ${c}`);let p=Array.isArray(u.authorization_servers)?u.authorization_servers:[];if(p.length===0)throw new Error("No authorization_servers advertised by protected resource");return{resource:l,issuers:p}}catch(u){i=u}throw new Error(`Failed to resolve protected resource metadata via well-known endpoints. Last error: ${String(i)}`)}async function _p(o){let e=new URL(o),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 s of n)try{let i=await Js(s);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 ${o}: ${String(r)}`)}var dr=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 _p(e);return this.asMetaCache.set(e,t),t}async ensureAccessToken(e){if(!this.oauth)return null;let{resource:t,issuers:n}=await Fp(e.requestedUrl,e.wwwAuthenticate),r=this.oauth.selectAuthorizationServer?await this.oauth.selectAuthorizationServer(n,{}):n[0],s=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:s,resource:t};if(i?.refreshToken)try{let h=await this.refreshToken(i.refreshToken,t,r,s);return await this.setStoredToken(t,r,h),{token:h,issuer:r,asMeta:s,resource:t}}catch{await this.clearStoredToken(t,r)}let a=this.oauth.redirectUri??"http://localhost:8787/callback",u=this.oauth.clientId?{client_id:this.oauth.clientId,client_secret:this.oauth.clientSecret}:await this.dynamicClientRegistration(s,a),c=await eu(),l=await Mp(c),p=await eu(),d=this.oauth.scopes?.join(" "),m=`${s.authorization_endpoint}?${Pp({response_type:"code",client_id:u.client_id,redirect_uri:a,scope:d,state:p,code_challenge:l,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),x=f??a,A=await this.exchangeCodeForToken({asMeta:s,code:g,codeVerifier:c,client:u,redirectUri:x,resource:t});return await this.setStoredToken(t,r,A),{token:A,issuer:r,asMeta:s,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"},s=await fetch(e.registration_endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok)throw new Error(`Dynamic client registration failed: ${s.status} ${s.statusText}`);let i=await s.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 s=r.expires_in?Date.now()+r.expires_in*1e3:void 0;return{accessToken:r.access_token,refreshToken:r.refresh_token,expiresAt:s}}async refreshToken(e,t,n,r){let s=new URLSearchParams;s.set("grant_type","refresh_token"),s.set("refresh_token",e),s.set("resource",t),this.oauth?.clientId&&s.set("client_id",this.oauth.clientId),this.oauth?.clientSecret&&s.set("client_secret",this.oauth.clientSecret);let i=await fetch(r.token_endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s.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 u=a.expires_in?Date.now()+a.expires_in*1e3:void 0;return{accessToken:a.access_token,refreshToken:a.refresh_token??e,expiresAt:u}}};var Qs=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 dr(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=s=>{try{let i=JSON.parse(s.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"),u=await this.oauthHelper.ensureAccessToken({requestedUrl:this.mcpEndpoint,wwwAuthenticate:a,currentToken:null});if(!u)throw new Error("HTTP 401: Unauthorized");return this.customHeaders.Authorization=`Bearer ${u.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,s="",i=async()=>{try{let{done:a,value:u}=await n.read();if(a){n.releaseLock();return}s+=r.decode(u,{stream:!0});let c=s.split(`
1117
+ `)}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:s}=r;if(typeof s!="object"||s===null||Object.keys(s).length!==0)throw new Error(`Unexpected ping response: ${JSON.stringify(s)}`)}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=Ze(),r={jsonrpc:"2.0",id:n,method:e,params:t},s=new Promise((a,u)=>{this.activeRequests.set(n,{reject:u}),this.transport.send(r).then(c=>{if(this.activeRequests.delete(n),c!==null&&typeof c=="object"&&"error"in c){let l=c;u(new Error(`RPC Error ${l.error.code}: ${l.error.message}`))}else c!==null&&typeof c=="object"&&"result"in c?a({result:c.result}):u(new Error("Invalid response no result or error"))}).catch(c=>{this.activeRequests.delete(n),u(c)})}),{result:i}=await s;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 s={name:"Notification",id:"mcp_notification",value:`Sending notification: ${JSON.stringify(n,null,2)}`};this.logger(s)}await this.transport.sendNotification(n)}};function Ep(o){if(typeof Buffer<"u")return Buffer.from(o).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"");let e="";for(let n=0;n<o.length;n++)e+=String.fromCharCode(o[n]);return(typeof btoa=="function"?btoa(e):"").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function Mp(o){let t=new TextEncoder().encode(o),n=await Tu().subtle.digest("SHA-256",t);return new Uint8Array(n)}async function nu(){return Ep(await Mp(Ze()+Math.random().toString(36)))}async function Pp(o){return Ep(await Mp(o))}async function Js(o,e){let t=await fetch(o,{headers:e});if(!t.ok)throw new Error(`HTTP ${t.status} fetching ${o}: ${t.statusText}`);return await t.json()}function Fp(o){let e=new URLSearchParams;for(let[t,n]of Object.entries(o))n!==void 0&&e.set(t,n);return e.toString()}function ao(o){return o.endsWith("/")?o.slice(0,-1):o}function tf(o){if(!o)return null;let e=o.match(/resource_metadata\s*=\s*"([^"]+)"/i)||o.match(/resource_metadata\s*=\s*([^,\s]+)/i);return e?e[1]:null}async function _p(o,e){let t=tf(e);if(t){let a=await Js(t),u=ao(new URL(o).toString().split("?")[0]),c=ao(a.resource??"");if(!c||c!==u)throw new Error(`Protected resource metadata 'resource' mismatch. Expected ${u} but got ${c}`);let l=Array.isArray(a.authorization_servers)?a.authorization_servers:[];if(l.length===0)throw new Error("No authorization_servers advertised by protected resource");return{resource:u,issuers:l}}let n=new URL(o),r=n.pathname.replace(/\/+$/,""),s=[];r&&r!=="/"&&s.push({url:`${n.origin}/.well-known/oauth-protected-resource${r}`,expected:`${n.origin}${r}`}),s.push({url:`${n.origin}/.well-known/oauth-protected-resource`,expected:`${n.origin}`});let i;for(let a of s)try{let u=await Js(a.url),c=ao(u.resource??""),l=ao(a.expected);if(!c||c!==l)throw new Error(`Protected resource metadata 'resource' mismatch. Expected ${l} but got ${c}`);let p=Array.isArray(u.authorization_servers)?u.authorization_servers:[];if(p.length===0)throw new Error("No authorization_servers advertised by protected resource");return{resource:l,issuers:p}}catch(u){i=u}throw new Error(`Failed to resolve protected resource metadata via well-known endpoints. Last error: ${String(i)}`)}async function Np(o){let e=new URL(o),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 s of n)try{let i=await Js(s);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 ${o}: ${String(r)}`)}var mr=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 Np(e);return this.asMetaCache.set(e,t),t}async ensureAccessToken(e){if(!this.oauth)return null;let{resource:t,issuers:n}=await _p(e.requestedUrl,e.wwwAuthenticate),r=this.oauth.selectAuthorizationServer?await this.oauth.selectAuthorizationServer(n,{}):n[0],s=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:s,resource:t};if(i?.refreshToken)try{let h=await this.refreshToken(i.refreshToken,t,r,s);return await this.setStoredToken(t,r,h),{token:h,issuer:r,asMeta:s,resource:t}}catch{await this.clearStoredToken(t,r)}let a=this.oauth.redirectUri??"http://localhost:8787/callback",u=this.oauth.clientId?{client_id:this.oauth.clientId,client_secret:this.oauth.clientSecret}:await this.dynamicClientRegistration(s,a),c=await nu(),l=await Pp(c),p=await nu(),d=this.oauth.scopes?.join(" "),m=`${s.authorization_endpoint}?${Fp({response_type:"code",client_id:u.client_id,redirect_uri:a,scope:d,state:p,code_challenge:l,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),x=f??a,A=await this.exchangeCodeForToken({asMeta:s,code:g,codeVerifier:c,client:u,redirectUri:x,resource:t});return await this.setStoredToken(t,r,A),{token:A,issuer:r,asMeta:s,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"},s=await fetch(e.registration_endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok)throw new Error(`Dynamic client registration failed: ${s.status} ${s.statusText}`);let i=await s.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 s=r.expires_in?Date.now()+r.expires_in*1e3:void 0;return{accessToken:r.access_token,refreshToken:r.refresh_token,expiresAt:s}}async refreshToken(e,t,n,r){let s=new URLSearchParams;s.set("grant_type","refresh_token"),s.set("refresh_token",e),s.set("resource",t),this.oauth?.clientId&&s.set("client_id",this.oauth.clientId),this.oauth?.clientSecret&&s.set("client_secret",this.oauth.clientSecret);let i=await fetch(r.token_endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s.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 u=a.expires_in?Date.now()+a.expires_in*1e3:void 0;return{accessToken:a.access_token,refreshToken:a.refresh_token??e,expiresAt:u}}};var Qs=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 mr(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=s=>{try{let i=JSON.parse(s.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"),u=await this.oauthHelper.ensureAccessToken({requestedUrl:this.mcpEndpoint,wwwAuthenticate:a,currentToken:null});if(!u)throw new Error("HTTP 401: Unauthorized");return this.customHeaders.Authorization=`Bearer ${u.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,s="",i=async()=>{try{let{done:a,value:u}=await n.read();if(a){n.releaseLock();return}s+=r.decode(u,{stream:!0});let c=s.split(`
1118
1118
  `);s=c.pop()||"";for(let l of c)if(l.startsWith("data: ")){let p=l.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"),u=await this.oauthHelper.ensureAccessToken({requestedUrl:this.mcpEndpoint,wwwAuthenticate:a,currentToken:null});if(!u)throw new Error("HTTP 401: Unauthorized");this.customHeaders.Authorization=`Bearer ${u.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 s=r.headers.get("Mcp-Session-Id");s&&(this.sessionId=s);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 s=e.body?.getReader();if(!s){r(new Error("No response body reader available"));return}let i=new TextDecoder,a="",u=async()=>{try{let{done:c,value:l}=await s.read();if(c){s.releaseLock();return}a+=i.decode(l,{stream:!0});let p=a.split(`
1119
- `);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 u()}catch(c){s.releaseLock(),r(c)}};u().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 s=r.headers.get("WWW-Authenticate"),i=await this.oauthHelper.ensureAccessToken({requestedUrl:this.mcpEndpoint,wwwAuthenticate:s,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 Ys=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 dr(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 s=n.headers.get("WWW-Authenticate"),i=await this.oauthHelper.ensureAccessToken({requestedUrl:this.sseUrl,wwwAuthenticate:s,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="",s=null;for(;;){let{done:i,value:a}=await t.read();if(i)break;r+=n.decode(a,{stream:!0});let u=r.split(`
1120
- `);r=u.pop()||"";for(let c of u)if(c.startsWith("event: "))s=c.slice(7).trim();else if(c.startsWith("data: ")){let l=c.slice(6);if(s==="endpoint"){let p=l.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=l.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 c.trim()===""&&(s=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,u)=>{this.pendingRequests.set(e.id,{resolve:a,reject:u})}),s=await fetch(this.endpoint,{method:"POST",headers:t,body:n});if(s.status===401){let a=s.headers.get("WWW-Authenticate"),u=await this.oauthHelper.ensureAccessToken({requestedUrl:this.sseUrl,wwwAuthenticate:a,currentToken:null});if(!u)throw new Error("HTTP 401: Unauthorized");this.customHeaders.Authorization=`Bearer ${u.token.accessToken}`,s=await fetch(this.endpoint,{method:"POST",headers:this.buildHeaders({"Content-Type":"application/json"}),body:n})}if(!s.ok)throw this.pendingRequests.delete(e.id),new Error(`HTTP error ${s.status}: ${s.statusText}`);if(s.headers.get("Content-Type")?.includes("application/json")){let a=await s.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 s=r.headers.get("WWW-Authenticate"),i=await this.oauthHelper.ensureAccessToken({requestedUrl:this.sseUrl,wwwAuthenticate:s,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 tu(o){return o.match(/^(\w+Error:\s*.{0,60})/m)?.[1]??o.slice(0,80)}function Lp(o){return io(o)}function Zg(o){return xp(o)}var ef=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 $p(o){let e=Nt(o),t=/\b([a-zA-Z_$][a-zA-Z0-9_$]*)\b/g,n=new Set,r=t.exec(e);for(;r!==null;)r[1]&&!ef.has(r[1])&&n.add(r[1]),r=t.exec(e);return n}function Dp(o){let e=$p(o);for(let t of Lp(o))e.delete(t);return e}var tf=new Set(["dead-end","foundational","pivot","superseded"]);function Lt(o,e=120){let t=o.replace(/\s+/g," ").trim();return t.length<=e?t:`${t.slice(0,e-3)}...`}function nf(o){return/\b(final|ask_clarification)\s*\(/.test(o)}function rf(o){return o.tags.includes("error")?"error":nf(o.code)?"finalize":/\b(llmQuery|listModuleFunctions|getFunctionDefinitions)\s*\(/.test(o.code)?"query":(o.producedVars?.length??0)>0?"transform":"explore"}function of(o){let e=o.producedVars??[];if(e.length>0)return`Updated live runtime values: ${e.join(", ")}`;switch(o.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 ru(o){if(o.tombstone)return o.tombstone;let e=o.stepKind==="error"?"Error step":o.stepKind==="query"?"Query step":o.stepKind==="transform"?"Transform step":o.stepKind==="finalize"?"Finalize step":"Explore step",t=Lt(o.output||"(no output)"),n=Lt(o.actorFieldsOutput.replace(/^Actor fields:\s*/i,""),80),r=o.stateDelta??"No durable runtime state update",s=n?` Actor fields: ${n}.`:"";return`[SUMMARY]: ${e}. ${r}. Result: ${t}.${s}`}function sf(o){o.rank=void 0,o.tags=o.tags.filter(e=>!tf.has(e))}function jt(o){o.producedVars||(o.producedVars=Zg(o.code)),o.referencedVars||(o.referencedVars=[...$p(o.code)]),o.stepKind||(o.stepKind=rf(o)),o.stateDelta||(o.stateDelta=of(o)),o.summary||(o.summary=ru(o))}function Up(o,e){let t=[...o.matchAll(e)];return t.length===0?[]:t.map((n,r)=>{let s=n[1]?.trim(),i=n.index??0,a=t[r+1]?.index??o.length;if(s)return{key:s,text:o.slice(i,a).trim()}}).filter(n=>!!n)}function af(o){return/\blistModuleFunctions\s*\(/.test(o.code)?Up(o.output,/^### Module `([^`]+)`/gm).map(e=>({module:e.key,text:e.text})):[]}function uf(o){return/\bgetFunctionDefinitions\s*\(/.test(o.code)?Up(o.output,/^### `([^`]+)`/gm).map(e=>({qualifiedName:e.key,text:e.text})):[]}function cf(o){let e=Nt(o),t=new Set,n=/\b([a-zA-Z_$][a-zA-Z0-9_$]*)\.([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\(/g,r=n.exec(e);for(;r;){let s=r[1],i=r[2];s&&i&&t.add(`${s}.${i}`),r=n.exec(e)}return[...t]}function co(o){o._discoveryModuleSections||(o._discoveryModuleSections=af(o)),o._discoveryFunctionSections||(o._discoveryFunctionSections=uf(o)),o._directQualifiedCalls||(o._directQualifiedCalls=cf(o.code))}function lf(o){return co(o),o._directQualifiedCalls?.find(Boolean)}function Xs(o){let e=new Map;for(let t of o){let n=t;jt(n);let r=lf(n);for(let i of n.producedVars??[])e.set(i,{createdTurn:n.turn,stepKind:n.stepKind,source:r,code:n.code});let s=Dp(n.code);for(let i of s){let a=e.get(i);a&&(a.lastReadTurn=Math.max(a.lastReadTurn??a.createdTurn,n.turn))}}return e}function pf(o){let e=Array.from({length:o.length},()=>new Set),t=new Set;for(let n=o.length-1;n>=0;n--){e[n]=new Set(t);let r=o[n];if(!(!r||r.tags.includes("error"))){co(r);for(let s of r._directQualifiedCalls??[])t.add(s)}}return e}function df(o,e){let t=o;co(t);let n=t._discoveryFunctionSections??[];if(n.length>0){let s=n.filter(i=>!e.has(i.qualifiedName));return s.length===n.length?t:s.length===0?void 0:{...t,output:s.map(i=>i.text).join(`
1119
+ `);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 u()}catch(c){s.releaseLock(),r(c)}};u().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 s=r.headers.get("WWW-Authenticate"),i=await this.oauthHelper.ensureAccessToken({requestedUrl:this.mcpEndpoint,wwwAuthenticate:s,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 Ys=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 mr(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 s=n.headers.get("WWW-Authenticate"),i=await this.oauthHelper.ensureAccessToken({requestedUrl:this.sseUrl,wwwAuthenticate:s,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="",s=null;for(;;){let{done:i,value:a}=await t.read();if(i)break;r+=n.decode(a,{stream:!0});let u=r.split(`
1120
+ `);r=u.pop()||"";for(let c of u)if(c.startsWith("event: "))s=c.slice(7).trim();else if(c.startsWith("data: ")){let l=c.slice(6);if(s==="endpoint"){let p=l.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=l.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 c.trim()===""&&(s=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,u)=>{this.pendingRequests.set(e.id,{resolve:a,reject:u})}),s=await fetch(this.endpoint,{method:"POST",headers:t,body:n});if(s.status===401){let a=s.headers.get("WWW-Authenticate"),u=await this.oauthHelper.ensureAccessToken({requestedUrl:this.sseUrl,wwwAuthenticate:a,currentToken:null});if(!u)throw new Error("HTTP 401: Unauthorized");this.customHeaders.Authorization=`Bearer ${u.token.accessToken}`,s=await fetch(this.endpoint,{method:"POST",headers:this.buildHeaders({"Content-Type":"application/json"}),body:n})}if(!s.ok)throw this.pendingRequests.delete(e.id),new Error(`HTTP error ${s.status}: ${s.statusText}`);if(s.headers.get("Content-Type")?.includes("application/json")){let a=await s.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 s=r.headers.get("WWW-Authenticate"),i=await this.oauthHelper.ensureAccessToken({requestedUrl:this.sseUrl,wwwAuthenticate:s,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 ru(o){return o.match(/^(\w+Error:\s*.{0,60})/m)?.[1]??o.slice(0,80)}function Lp(o){return io(o)}function nf(o){return Ap(o)}var rf=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 Dp(o){let e=jt(o),t=/\b([a-zA-Z_$][a-zA-Z0-9_$]*)\b/g,n=new Set,r=t.exec(e);for(;r!==null;)r[1]&&!rf.has(r[1])&&n.add(r[1]),r=t.exec(e);return n}function Up(o){let e=Dp(o);for(let t of Lp(o))e.delete(t);return e}var of=new Set(["dead-end","foundational","pivot","superseded"]);function Nt(o,e=120){let t=o.replace(/\s+/g," ").trim();return t.length<=e?t:`${t.slice(0,e-3)}...`}function sf(o){return/\b(final|ask_clarification)\s*\(/.test(o)}function af(o){return o.tags.includes("error")?"error":sf(o.code)?"finalize":/\b(llmQuery|listModuleFunctions|getFunctionDefinitions)\s*\(/.test(o.code)?"query":(o.producedVars?.length??0)>0?"transform":"explore"}function uf(o){let e=o.producedVars??[];if(e.length>0)return`Updated live runtime values: ${e.join(", ")}`;switch(o.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 su(o){if(o.tombstone)return o.tombstone;let e=o.stepKind==="error"?"Error step":o.stepKind==="query"?"Query step":o.stepKind==="transform"?"Transform step":o.stepKind==="finalize"?"Finalize step":"Explore step",t=Nt(o.output||"(no output)"),n=Nt(o.actorFieldsOutput.replace(/^Actor fields:\s*/i,""),80),r=o.stateDelta??"No durable runtime state update",s=n?` Actor fields: ${n}.`:"";return`[SUMMARY]: ${e}. ${r}. Result: ${t}.${s}`}function cf(o){o.rank=void 0,o.tags=o.tags.filter(e=>!of.has(e))}function Bt(o){o.producedVars||(o.producedVars=nf(o.code)),o.referencedVars||(o.referencedVars=[...Dp(o.code)]),o.stepKind||(o.stepKind=af(o)),o.stateDelta||(o.stateDelta=uf(o)),o.summary||(o.summary=su(o))}function Gp(o,e){let t=[...o.matchAll(e)];return t.length===0?[]:t.map((n,r)=>{let s=n[1]?.trim(),i=n.index??0,a=t[r+1]?.index??o.length;if(s)return{key:s,text:o.slice(i,a).trim()}}).filter(n=>!!n)}function lf(o){return/\blistModuleFunctions\s*\(/.test(o.code)?Gp(o.output,/^### Module `([^`]+)`/gm).map(e=>({module:e.key,text:e.text})):[]}function pf(o){return/\bgetFunctionDefinitions\s*\(/.test(o.code)?Gp(o.output,/^### `([^`]+)`/gm).map(e=>({qualifiedName:e.key,text:e.text})):[]}function df(o){let e=jt(o),t=new Set,n=/\b([a-zA-Z_$][a-zA-Z0-9_$]*)\.([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\(/g,r=n.exec(e);for(;r;){let s=r[1],i=r[2];s&&i&&t.add(`${s}.${i}`),r=n.exec(e)}return[...t]}function co(o){o._discoveryModuleSections||(o._discoveryModuleSections=lf(o)),o._discoveryFunctionSections||(o._discoveryFunctionSections=pf(o)),o._directQualifiedCalls||(o._directQualifiedCalls=df(o.code))}function mf(o){return co(o),o._directQualifiedCalls?.find(Boolean)}function Xs(o){let e=new Map;for(let t of o){let n=t;Bt(n);let r=mf(n);for(let i of n.producedVars??[])e.set(i,{createdTurn:n.turn,stepKind:n.stepKind,source:r,code:n.code});let s=Up(n.code);for(let i of s){let a=e.get(i);a&&(a.lastReadTurn=Math.max(a.lastReadTurn??a.createdTurn,n.turn))}}return e}function gf(o){let e=Array.from({length:o.length},()=>new Set),t=new Set;for(let n=o.length-1;n>=0;n--){e[n]=new Set(t);let r=o[n];if(!(!r||r.tags.includes("error"))){co(r);for(let s of r._directQualifiedCalls??[])t.add(s)}}return e}function ff(o,e){let t=o;co(t);let n=t._discoveryFunctionSections??[];if(n.length>0){let s=n.filter(i=>!e.has(i.qualifiedName));return s.length===n.length?t:s.length===0?void 0:{...t,output:s.map(i=>i.text).join(`
1121
1121
 
1122
1122
  `),summary:void 0,_discoveryFunctionSections:s}}let r=t._discoveryModuleSections??[];if(r.length>0){let s=new Set([...e].map(a=>a.split(".")[0])),i=r.filter(a=>!s.has(a.module));return i.length===r.length?t:i.length===0?void 0:{...t,output:i.map(a=>a.text).join(`
1123
1123
 
1124
- `),summary:void 0,_discoveryModuleSections:i}}return t}function Zs(o,e){if(!e?.pruneUsedDocs||o.length===0)return[...o];let t=pf(o);return o.flatMap((n,r)=>{let s=df(n,t[r]??new Set);return s?[s]:[]})}function mf(o){let e=Array.from({length:o.length},()=>new Set),t=new Set;for(let n=o.length-1;n>=0;n--){e[n]=new Set(t);for(let r of o[n]?.referencedVars??[])t.add(r)}return e}function gf(o,e){let t=e.actionReplay??"full",n=Math.max(e.recentFullActions??1,0),r=t==="checkpointed"&&((e.checkpointTurns?.length??0)>0||!!e.checkpointSummary);for(let a of o)jt(a);let s=mf(o),i=Math.max(o.length-n,0);o.forEach((a,u)=>{if(a.tombstone){a.replayMode="full";return}if(t==="full"){a.replayMode="full";return}if(t==="checkpointed"&&!r){a.replayMode="full";return}let c=u>=i,l=a.tags.includes("error"),p=a.output.startsWith("[POLICY]"),d=s[u]??new Set,g=(a.producedVars??[]).some(f=>d.has(f));if(c||l||p){a.replayMode="full";return}if(t==="adaptive"&&g){a.replayMode="full";return}a.replayMode="omit"})}function ff(o,e){jt(o),jt(e),sf(o);let t=o.tags.includes("error"),n=e.tags.includes("error");if(t&&!n){o.rank=0,uo(o,"dead-end");return}if(t&&n){let r=tu(o.output),s=tu(e.output);r!==s?(o.rank=3,uo(o,"pivot")):(o.rank=0,uo(o,"dead-end"));return}if(!t&&!n){let r=o.producedVars??Lp(o.code);if(r.length===0||o.stepKind==="explore"||o.stepKind==="query")return;let s=Dp(e.code);if(r.filter(a=>s.has(a)).length>0){o.rank=5,uo(o,"foundational");return}o.stepKind==="transform"&&(o.rank=1,uo(o,"superseded"));return}}function uo(o,e){o.tags.includes(e)||o.tags.push(e)}function nu(o,e){let t=o.output.split(`
1124
+ `),summary:void 0,_discoveryModuleSections:i}}return t}function Zs(o,e){if(!e?.pruneUsedDocs||o.length===0)return[...o];let t=gf(o);return o.flatMap((n,r)=>{let s=ff(n,t[r]??new Set);return s?[s]:[]})}function hf(o){let e=Array.from({length:o.length},()=>new Set),t=new Set;for(let n=o.length-1;n>=0;n--){e[n]=new Set(t);for(let r of o[n]?.referencedVars??[])t.add(r)}return e}function xf(o,e){let t=e.actionReplay??"full",n=Math.max(e.recentFullActions??1,0),r=t==="checkpointed"&&((e.checkpointTurns?.length??0)>0||!!e.checkpointSummary);for(let a of o)Bt(a);let s=hf(o),i=Math.max(o.length-n,0);o.forEach((a,u)=>{if(a.tombstone){a.replayMode="full";return}if(t==="full"){a.replayMode="full";return}if(t==="checkpointed"&&!r){a.replayMode="full";return}let c=u>=i,l=a.tags.includes("error"),p=a.output.startsWith("[POLICY]"),d=s[u]??new Set,g=(a.producedVars??[]).some(f=>d.has(f));if(c||l||p){a.replayMode="full";return}if(t==="adaptive"&&g){a.replayMode="full";return}a.replayMode="omit"})}function Af(o,e){Bt(o),Bt(e),cf(o);let t=o.tags.includes("error"),n=e.tags.includes("error");if(t&&!n){o.rank=0,uo(o,"dead-end");return}if(t&&n){let r=ru(o.output),s=ru(e.output);r!==s?(o.rank=3,uo(o,"pivot")):(o.rank=0,uo(o,"dead-end"));return}if(!t&&!n){let r=o.producedVars??Lp(o.code);if(r.length===0||o.stepKind==="explore"||o.stepKind==="query")return;let s=Up(e.code);if(r.filter(a=>s.has(a)).length>0){o.rank=5,uo(o,"foundational");return}o.stepKind==="transform"&&(o.rank=1,uo(o,"superseded"));return}}function uo(o,e){o.tags.includes(e)||o.tags.push(e)}function ou(o,e){let t=o.output.split(`
1125
1125
  `).map(r=>r.trim()).filter(Boolean).find(r=>/\b\w+Error:/.test(r)&&!r.startsWith("["))??o.output.split(`
1126
- `).map(r=>r.trim()).filter(r=>!!r&&!r.startsWith("[")&&!r.startsWith("...")).at(-1)??tu(o.output);return`[TOMBSTONE]: Resolved ${Lt(t,96)} in turn ${e.turn}.`}function hf(o){return o.startsWith("[TOMBSTONE]: Resolved ")}var xf=`You are an internal AxAgent tombstone summarizer.
1126
+ `).map(r=>r.trim()).filter(r=>!!r&&!r.startsWith("[")&&!r.startsWith("...")).at(-1)??ru(o.output);return`[TOMBSTONE]: Resolved ${Nt(t,96)} in turn ${e.turn}.`}function yf(o){return o.startsWith("[TOMBSTONE]: Resolved ")}var bf=`You are an internal AxAgent tombstone summarizer.
1127
1127
 
1128
1128
  Write the output field \`tombstone\` as exactly one concise line.
1129
1129
  - Start with \`[TOMBSTONE]:\`
1130
1130
  - Summarize the resolved error and the successful fix.
1131
1131
  - Mention one failed approach to avoid when possible.
1132
1132
  - Do not include code fences, bullet points, or extra prose.
1133
- - Keep it roughly 20-40 tokens.`,Af=`You are an internal AxAgent checkpoint summarizer.
1133
+ - Keep it roughly 20-40 tokens.`,Cf=`You are an internal AxAgent checkpoint summarizer.
1134
1134
 
1135
1135
  Write the output field \`checkpointSummary\` as plain text with exactly these labels in this order:
1136
1136
  Objective:
@@ -1151,29 +1151,29 @@ Rules:
1151
1151
  - Use \`Failures to avoid:\` for exact retry hazards. Use \`none\` if there are no important failure patterns in the provided turns.
1152
1152
  - Do not restate raw code or quote large outputs.
1153
1153
  - Use "none" when a section has nothing worth preserving.
1154
- - Be concise and factual, but prefer slightly more detail over losing task-critical specifics.`;function Gp(o){let{mem:e,description:t,maxSteps:n,...r}=o??{};return r}function Bp(o,e,t){let n=Gp(t);return{...n,description:o,traceLabel:n.traceLabel??e,maxSteps:1}}function jp(o){return{...Gp(o),maxSteps:1}}async function yf(o,e,t,n,r){let s=new Me("errorCode:string, errorOutput:string, resolutionCode:string -> tombstone:string",{...Bp(xf,"ax-agent-tombstone-summary",e)});try{let i=await s.forward(o,{errorCode:n.code.slice(0,500),errorOutput:n.output.slice(0,300),resolutionCode:r.code.slice(0,500)},jp(t));return(typeof i.tombstone=="string"?i.tombstone.trim():String(i.tombstone).trim())||nu(n,r)}catch{return nu(n,r)}}function bf(o){return o.map(e=>{jt(e),co(e);let t=e.actorFieldsOutput.replace(/^Actor fields:\s*/i,"").trim(),n=(e._directQualifiedCalls??[]).join(", ")||"none",r=e.tags.includes("error")?Lt(e.output||"(no output)",200):"none";return[`Turn: ${e.turn}`,`Step kind: ${e.stepKind??"explore"}`,`Referenced inputs: ${(e.referencedVars??[]).join(", ")||"none"}`,`Durable values written: ${(e.producedVars??[]).join(", ")||"none"}`,`Direct callables: ${n}`,`State delta: ${e.stateDelta??"none"}`,`Observed result: ${Lt(e.output||"(no output)",360)}`,`Actor fields: ${t||"none"}`,`Failure cues: ${r}`,`Code excerpt: ${Lt(e.code||"(no code)",360)}`].join(`
1154
+ - Be concise and factual, but prefer slightly more detail over losing task-critical specifics.`;function jp(o){let{mem:e,description:t,maxSteps:n,...r}=o??{};return r}function Bp(o,e,t){let n=jp(t);return{...n,description:o,traceLabel:n.traceLabel??e,maxSteps:1}}function zp(o){return{...jp(o),maxSteps:1}}async function If(o,e,t,n,r){let s=new Me("errorCode:string, errorOutput:string, resolutionCode:string -> tombstone:string",{...Bp(bf,"ax-agent-tombstone-summary",e)});try{let i=await s.forward(o,{errorCode:n.code.slice(0,500),errorOutput:n.output.slice(0,300),resolutionCode:r.code.slice(0,500)},zp(t));return(typeof i.tombstone=="string"?i.tombstone.trim():String(i.tombstone).trim())||ou(n,r)}catch{return ou(n,r)}}function Tf(o){return o.map(e=>{Bt(e),co(e);let t=e.actorFieldsOutput.replace(/^Actor fields:\s*/i,"").trim(),n=(e._directQualifiedCalls??[]).join(", ")||"none",r=e.tags.includes("error")?Nt(e.output||"(no output)",200):"none";return[`Turn: ${e.turn}`,`Step kind: ${e.stepKind??"explore"}`,`Referenced inputs: ${(e.referencedVars??[]).join(", ")||"none"}`,`Durable values written: ${(e.producedVars??[]).join(", ")||"none"}`,`Direct callables: ${n}`,`State delta: ${e.stateDelta??"none"}`,`Observed result: ${Nt(e.output||"(no output)",360)}`,`Actor fields: ${t||"none"}`,`Failure cues: ${r}`,`Code excerpt: ${Nt(e.code||"(no code)",360)}`].join(`
1155
1155
  `)}).join(`
1156
1156
 
1157
- `)}function Np(o){let e=new Set,t=new Set,n=[],r=[],s=[],i=[],a="Continue from the latest live runtime state.";for(let u of o){jt(u),co(u),e.add(u.stepKind??"explore");for(let d of u.producedVars??[])t.add(d);let c=u._directQualifiedCalls??[];c.length>0?n.push(`Turn ${u.turn}: ${c.join(", ")} via ${Lt(u.code||"(no code)",140)}`):/\b(listModuleFunctions|getFunctionDefinitions)\s*\(/.test(u.code)&&n.push(`Turn ${u.turn}: ${Lt(u.code||"(no code)",140)}`);let l=Lt(u.output||"(no output)",200);r.push(`Turn ${u.turn}: ${l}`);let p=u.actorFieldsOutput.replace(/^Actor fields:\s*/i,"").trim();p&&s.push(`Turn ${u.turn}: ${p}`),u.tags.includes("error")&&i.push(`Turn ${u.turn}: ${Lt(u.output||"(no output)",160)}`),a=u.stepKind==="finalize"?"Complete the responder handoff.":"Continue from the latest live runtime state."}return[`Objective: ${[...e].join(", ")||"none"}`,`Durable state: ${[...t].join(", ")||"none"}`,`Exact callables and formats: ${n.join(" | ")||"none"}`,`Evidence: ${r.join(" | ")||"none"}`,"Conclusions: Preserve the durable state, exact callable usage, and evidence above. Confirmed execution facts should override inference.",`Actor fields: ${s.join(" | ")||"none"}`,`Failures to avoid: ${i.join(" | ")||"none"}`,`Next step: ${a}`].join(`
1158
- `)}async function zp(o,e,t,n){let r=new Me("turns:string -> checkpointSummary:string",{...Bp(Af,"ax-agent-checkpoint-summary",e)});try{let s=await r.forward(o,{turns:bf(n)},jp(t));return(typeof s.checkpointSummary=="string"?s.checkpointSummary.trim():String(s.checkpointSummary).trim())||Np(n)}catch{return Np(n)}}async function ou(o,e,t,n,r){let s=o[e];if(!s)return;jt(s);let i=s.tags.includes("error");if(t.hindsightEvaluation&&o.length>=2){let a=o[o.length-2];ff(a,s)}if(t.errorPruning||t.tombstoning)for(let a of o){if(!a.tags.includes("error"))continue;let u=o.indexOf(a),c=o[u+1];if(!c||c.tags.includes("error")||(t.errorPruning&&!a.tombstone&&(a.tombstone=nu(a,c)),!(!!t.tombstoning&&!!n&&!a._tombstonePromise&&(!a.tombstone||hf(a.tombstone)))||!n))continue;let p=typeof t.tombstoning=="object"?t.tombstoning:void 0;a._tombstonePromise=yf(n,p,r,a,c),a._tombstonePromise.then(d=>{a.tombstone=d}).catch(()=>{}).finally(()=>{a._tombstonePromise=void 0})}if(t.errorPruning&&!i){let a=o.filter(u=>!u.tags.includes("error")||u.tombstone!=null||u._tombstonePromise!=null);o.length=0,o.push(...a)}if(t.hindsightEvaluation){let a=o[o.length-1]?.turn??s.turn,u=o.filter((c,l)=>l===o.length-1||c.rank===void 0||!c.tags.includes("error")&&a-c.turn<t.rankPruneGraceTurns||c.rank>=t.pruneRank||c.tombstone!=null||c._tombstonePromise!=null);o.length=0,o.push(...u)}}function Tf(o,e){if(e.has(o.turn)&&!o.tags.includes("error")&&o.replayMode!=="full")return"";if(o.tombstone)return`Action ${o.turn}:
1159
- ${o.tombstone}`;switch(o.replayMode){case"omit":return jt(o),`Action ${o.turn}:
1160
- ${o.summary??ru(o)}`;default:return`Action ${o.turn}:
1157
+ `)}function $p(o){let e=new Set,t=new Set,n=[],r=[],s=[],i=[],a="Continue from the latest live runtime state.";for(let u of o){Bt(u),co(u),e.add(u.stepKind??"explore");for(let d of u.producedVars??[])t.add(d);let c=u._directQualifiedCalls??[];c.length>0?n.push(`Turn ${u.turn}: ${c.join(", ")} via ${Nt(u.code||"(no code)",140)}`):/\b(listModuleFunctions|getFunctionDefinitions)\s*\(/.test(u.code)&&n.push(`Turn ${u.turn}: ${Nt(u.code||"(no code)",140)}`);let l=Nt(u.output||"(no output)",200);r.push(`Turn ${u.turn}: ${l}`);let p=u.actorFieldsOutput.replace(/^Actor fields:\s*/i,"").trim();p&&s.push(`Turn ${u.turn}: ${p}`),u.tags.includes("error")&&i.push(`Turn ${u.turn}: ${Nt(u.output||"(no output)",160)}`),a=u.stepKind==="finalize"?"Complete the responder handoff.":"Continue from the latest live runtime state."}return[`Objective: ${[...e].join(", ")||"none"}`,`Durable state: ${[...t].join(", ")||"none"}`,`Exact callables and formats: ${n.join(" | ")||"none"}`,`Evidence: ${r.join(" | ")||"none"}`,"Conclusions: Preserve the durable state, exact callable usage, and evidence above. Confirmed execution facts should override inference.",`Actor fields: ${s.join(" | ")||"none"}`,`Failures to avoid: ${i.join(" | ")||"none"}`,`Next step: ${a}`].join(`
1158
+ `)}async function qp(o,e,t,n){let r=new Me("turns:string -> checkpointSummary:string",{...Bp(Cf,"ax-agent-checkpoint-summary",e)});try{let s=await r.forward(o,{turns:Tf(n)},zp(t));return(typeof s.checkpointSummary=="string"?s.checkpointSummary.trim():String(s.checkpointSummary).trim())||$p(n)}catch{return $p(n)}}async function iu(o,e,t,n,r){let s=o[e];if(!s)return;Bt(s);let i=s.tags.includes("error");if(t.hindsightEvaluation&&o.length>=2){let a=o[o.length-2];Af(a,s)}if(t.errorPruning||t.tombstoning)for(let a of o){if(!a.tags.includes("error"))continue;let u=o.indexOf(a),c=o[u+1];if(!c||c.tags.includes("error")||(t.errorPruning&&!a.tombstone&&(a.tombstone=ou(a,c)),!(!!t.tombstoning&&!!n&&!a._tombstonePromise&&(!a.tombstone||yf(a.tombstone)))||!n))continue;let p=typeof t.tombstoning=="object"?t.tombstoning:void 0;a._tombstonePromise=If(n,p,r,a,c),a._tombstonePromise.then(d=>{a.tombstone=d}).catch(()=>{}).finally(()=>{a._tombstonePromise=void 0})}if(t.errorPruning&&!i){let a=o.filter(u=>!u.tags.includes("error")||u.tombstone!=null||u._tombstonePromise!=null);o.length=0,o.push(...a)}if(t.hindsightEvaluation){let a=o[o.length-1]?.turn??s.turn,u=o.filter((c,l)=>l===o.length-1||c.rank===void 0||!c.tags.includes("error")&&a-c.turn<t.rankPruneGraceTurns||c.rank>=t.pruneRank||c.tombstone!=null||c._tombstonePromise!=null);o.length=0,o.push(...u)}}function wf(o,e){if(e.has(o.turn)&&!o.tags.includes("error")&&o.replayMode!=="full")return"";if(o.tombstone)return`Action ${o.turn}:
1159
+ ${o.tombstone}`;switch(o.replayMode){case"omit":return Bt(o),`Action ${o.turn}:
1160
+ ${o.summary??su(o)}`;default:return`Action ${o.turn}:
1161
1161
  \`\`\`javascript
1162
1162
  ${o.code}
1163
1163
  \`\`\`
1164
1164
  Result:
1165
- ${o.output}${o.actorFieldsOutput}`}}function lo(o,e){let t=Zs(o,{pruneUsedDocs:e.pruneUsedDocs});if(t.length===0)return{promptFacingEntries:t,checkpointEntries:[],historyText:"",historyChars:0};gf(t,e);let n=t.filter(i=>!i.tags.includes("error")&&i.replayMode!=="full"),r=new Set(e.checkpointTurns??[]),s=t.map(i=>Tf(i,r)).filter(Boolean).join(`
1165
+ ${o.output}${o.actorFieldsOutput}`}}function au(o,e){let t=Zs(o,{pruneUsedDocs:e.pruneUsedDocs});if(t.length===0)return{promptFacingEntries:t,checkpointEntries:[],historyText:"",historyChars:0};xf(t,e);let n=t.filter(i=>!i.tags.includes("error")&&i.replayMode!=="full"),r=new Set(e.checkpointTurns??[]),s=t.map(i=>wf(i,r)).filter(Boolean).join(`
1166
1166
 
1167
- `);return{promptFacingEntries:t,checkpointEntries:n,historyText:s,historyChars:s.length}}function qp(o,e){let t=lo(o,e);if(t.promptFacingEntries.length===0&&!e.delegatedContextSummary&&!e.stateSummary&&!e.checkpointSummary)return"";let n=[];return e.restoreNotice&&n.push(e.restoreNotice),e.delegatedContextSummary&&n.push(`Delegated Context (runtime-only \u2014 explore with code):
1167
+ `);return{promptFacingEntries:t,checkpointEntries:n,historyText:s,historyChars:s.length}}function Hp(o,e){let t=au(o,e);if(t.promptFacingEntries.length===0&&!e.delegatedContextSummary&&!e.stateSummary&&!e.checkpointSummary)return"";let n=[];return e.restoreNotice&&n.push(e.restoreNotice),e.delegatedContextSummary&&n.push(`Delegated Context (runtime-only \u2014 explore with code):
1168
1168
  ${e.delegatedContextSummary}`),e.stateSummary&&n.push(`Live Runtime State:
1169
1169
  ${e.stateSummary}`),t.historyText&&n.push(t.historyText),e.checkpointSummary&&n.push(`Checkpoint Summary:
1170
1170
  ${e.checkpointSummary}`),n.join(`
1171
1171
 
1172
- `)}function Hp(o,e){let t=Zs(o,{pruneUsedDocs:e?.pruneUsedDocs}),n=new Set(e?.checkpointTurns??[]),r=t.map(i=>{if(n.has(i.turn)&&!i.tags.includes("error"))return"";jt(i);let a=i.tombstone??i.summary??ru(i);return`- Action ${i.turn}: ${a}`}).filter(Boolean).join(`
1172
+ `)}function Kp(o,e){let t=Zs(o,{pruneUsedDocs:e?.pruneUsedDocs}),n=new Set(e?.checkpointTurns??[]),r=t.map(i=>{if(n.has(i.turn)&&!i.tags.includes("error"))return"";Bt(i);let a=i.tombstone??i.summary??su(i);return`- Action ${i.turn}: ${a}`}).filter(Boolean).join(`
1173
1173
  `),s=["Actor stopped without calling final(...). Evidence summary:"];return e?.checkpointSummary&&s.push(`Checkpoint summary:
1174
1174
  ${e.checkpointSummary}`),r?s.push(r):e?.checkpointSummary||s.push("- No actions were taken."),e?.stateSummary&&s.push(`Current runtime state:
1175
1175
  ${e.stateSummary}`),s.join(`
1176
- `)}function Wp(o,e=[]){return`(() => {
1176
+ `)}function Vp(o,e=[]){return`(() => {
1177
1177
  const skip = new Set([${[...o,...e].map(n=>`'${n}'`).join(",")}]);
1178
1178
  const truncate = (text, maxChars) =>
1179
1179
  text.length <= maxChars ? text : text.slice(0, maxChars - 3) + '...';
@@ -1294,21 +1294,21 @@ ${e.stateSummary}`),s.join(`
1294
1294
  }
1295
1295
  });
1296
1296
  return JSON.stringify({ version: 1, entries });
1297
- })()`}function Kp(){return"(() => JSON.stringify(Object.getOwnPropertyNames(globalThis).sort()))()"}function Cf(o){let e=o.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 If(o){let e=new Set(o);return e.has("object")&&e.has("array")&&e.has("string")&&e.has("number")&&e.has("boolean")&&e.has("null")}function su(o){if(o.enum)return o.enum.map(n=>`"${n}"`).join(" | ");let e=Cf(o);if(e.length===0)return"unknown";if(If(e))return"any";let t=[...new Set(e)].map(n=>{if(n==="array"){let r=o.items?su(o.items):"unknown";return r.includes(" | ")?`(${r})[]`:`${r}[]`}return n==="object"?o.properties&&Object.keys(o.properties).length>0?Jp(o):"object":n});return t.length>1?t.join(" | "):t[0]??"unknown"}function Jp(o,e){if(!o)return"{}";let t=!!o.properties&&Object.keys(o.properties).length>0,n=o.additionalProperties===!0;if(!t)return n?"{ [key: string]: unknown }":"{}";let r=new Set(o.required??[]),s=e?.respectRequired??!1,i=Object.entries(o.properties).map(([a,u])=>{let c=su(u),l=s&&!r.has(a)?"?":"";return`${a}${l}: ${c}`});return o?.additionalProperties===!0&&i.push("[key: string]: unknown"),`{ ${i.join(", ")} }`}function wf(o){return o?su(o):"unknown"}function Vp(o){let e=Jp(o.parameters,{respectRequired:!0}),t=o.returns?`: Promise<${wf(o.returns)}>`:"";return`- \`${o.qualifiedName}(args: ${e})${t}\``}function ei(o,e,t,n){let r=n.promptLevel??"detailed",s=e.length>0?e.map(m=>{let g=Xn(m.type),f=m.isOptional?"optional":"required",x=m.description?`: ${m.description}`:"";return`- \`${m.name}\` -> \`inputs.${m.name}\` (${g}, ${f})${x}`}).join(`
1298
- `):"(none)",i=t.map(m=>`\`${m.name}\``).join(", "),a=[...n.agents??[]].sort((m,g)=>m.name.localeCompare(g.name)),u=[...n.agentFunctions??[]].sort((m,g)=>m.namespace!==g.namespace?m.namespace.localeCompare(g.namespace):m.name.localeCompare(g.name)),c=n.agentModuleNamespace??"agents",l=!!n.discoveryMode,p=n.availableModules?[...n.availableModules].sort((m,g)=>m.namespace.localeCompare(g.namespace)):[...new Set([...u.map(m=>m.namespace),...a.length>0?[c]:[]])].sort((m,g)=>m.localeCompare(g)).map(m=>({namespace:m})),d=Tt("rlm/actor.md",{contextVarList:s,responderOutputFieldTitles:i,promptLevel:r,llmQueryPromptMode:n.llmQueryPromptMode??"simple",discoveryMode:l,hasInspectRuntime:!!n.hasInspectRuntime,hasAgentFunctions:!l&&a.length>0,agentModuleNamespace:c,agentFunctionsList:a.map(m=>Vp({qualifiedName:`${c}.${m.name}`,parameters:m.parameters})).join(`
1299
- `),hasFunctions:!l&&u.length>0,functionsList:u.map(m=>Vp({qualifiedName:`${m.namespace}.${m.name}`,parameters:m.parameters,returns:m.returns})).join(`
1297
+ })()`}function Wp(){return"(() => JSON.stringify(Object.getOwnPropertyNames(globalThis).sort()))()"}function Rf(o){let e=o.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 vf(o){let e=new Set(o);return e.has("object")&&e.has("array")&&e.has("string")&&e.has("number")&&e.has("boolean")&&e.has("null")}function uu(o){if(o.enum)return o.enum.map(n=>`"${n}"`).join(" | ");let e=Rf(o);if(e.length===0)return"unknown";if(vf(e))return"any";let t=[...new Set(e)].map(n=>{if(n==="array"){let r=o.items?uu(o.items):"unknown";return r.includes(" | ")?`(${r})[]`:`${r}[]`}return n==="object"?o.properties&&Object.keys(o.properties).length>0?Qp(o):"object":n});return t.length>1?t.join(" | "):t[0]??"unknown"}function Qp(o,e){if(!o)return"{}";let t=!!o.properties&&Object.keys(o.properties).length>0,n=o.additionalProperties===!0;if(!t)return n?"{ [key: string]: unknown }":"{}";let r=new Set(o.required??[]),s=e?.respectRequired??!1,i=Object.entries(o.properties).map(([a,u])=>{let c=uu(u),l=s&&!r.has(a)?"?":"";return`${a}${l}: ${c}`});return o?.additionalProperties===!0&&i.push("[key: string]: unknown"),`{ ${i.join(", ")} }`}function Sf(o){return o?uu(o):"unknown"}function Jp(o){let e=Qp(o.parameters,{respectRequired:!0}),t=o.returns?`: Promise<${Sf(o.returns)}>`:"";return`- \`${o.qualifiedName}(args: ${e})${t}\``}function ei(o,e,t,n){let r=n.promptLevel??"detailed",s=e.length>0?e.map(m=>{let g=er(m.type),f=m.isOptional?"optional":"required",x=m.description?`: ${m.description}`:"";return`- \`${m.name}\` -> \`inputs.${m.name}\` (${g}, ${f})${x}`}).join(`
1298
+ `):"(none)",i=t.map(m=>`\`${m.name}\``).join(", "),a=[...n.agents??[]].sort((m,g)=>m.name.localeCompare(g.name)),u=[...n.agentFunctions??[]].sort((m,g)=>m.namespace!==g.namespace?m.namespace.localeCompare(g.namespace):m.name.localeCompare(g.name)),c=n.agentModuleNamespace??"agents",l=!!n.discoveryMode,p=n.availableModules?[...n.availableModules].sort((m,g)=>m.namespace.localeCompare(g.namespace)):[...new Set([...u.map(m=>m.namespace),...a.length>0?[c]:[]])].sort((m,g)=>m.localeCompare(g)).map(m=>({namespace:m})),d=Ct("rlm/actor.md",{contextVarList:s,responderOutputFieldTitles:i,promptLevel:r,llmQueryPromptMode:n.llmQueryPromptMode??"simple",discoveryMode:l,hasInspectRuntime:!!n.hasInspectRuntime,hasAgentFunctions:!l&&a.length>0,agentModuleNamespace:c,agentFunctionsList:a.map(m=>Jp({qualifiedName:`${c}.${m.name}`,parameters:m.parameters})).join(`
1299
+ `),hasFunctions:!l&&u.length>0,functionsList:u.map(m=>Jp({qualifiedName:`${m.namespace}.${m.name}`,parameters:m.parameters,returns:m.returns})).join(`
1300
1300
  `),hasModules:l&&p.length>0,modulesList:p.map(m=>m.selectionCriteria?.trim()?`- \`${m.namespace}\` - ${m.selectionCriteria.trim()}`:`- \`${m.namespace}\``).join(`
1301
1301
  `),runtimeUsageInstructions:String(n.runtimeUsageInstructions),enforceIncrementalConsoleTurns:!!n.enforceIncrementalConsoleTurns,hasLiveRuntimeState:!!n.hasLiveRuntimeState,hasCompressedActionReplay:!!n.hasCompressedActionReplay}).replace(/\n{3,}/g,`
1302
1302
 
1303
1303
  `).trim();return o?`${d}
1304
1304
 
1305
- ${o}`:d}function ti(o,e){let t=e.length>0?e.map(r=>{let s=Xn(r.type),i=r.isOptional?"optional":"required";return`- \`${r.name}\` (${s}, ${i})`}).join(`
1306
- `):"(none)",n=Tt("rlm/responder.md",{contextVarSummary:t}).trim();return o?`${n}
1305
+ ${o}`:d}function ti(o,e){let t=e.length>0?e.map(r=>{let s=er(r.type),i=r.isOptional?"optional":"required";return`- \`${r.name}\` (${s}, ${i})`}).join(`
1306
+ `):"(none)",n=Ct("rlm/responder.md",{contextVarSummary:t}).trim();return o?`${n}
1307
1307
 
1308
- ${o}`:n}var po="ax-agent-recursive-slots-v1",de={shared:"root.actor.shared",root:"root.actor.root",recursive:"root.actor.recursive",terminal:"root.actor.terminal",responder:"root.responder"},Rf=()=>({promptTokens:0,completionTokens:0,totalTokens:0}),Xt=o=>{let e=Math.max(0,Math.floor(o?.promptTokens??0)),t=Math.max(0,Math.floor(o?.completionTokens??0)),n=Math.max(0,Math.floor(o?.totalTokens??0)),r=Math.max(n,e+t);return{promptTokens:e,completionTokens:t,totalTokens:r}},mo=(o,e)=>{let t=Xt(o),n=Xt(e);return{promptTokens:t.promptTokens+n.promptTokens,completionTokens:t.completionTokens+n.completionTokens,totalTokens:t.totalTokens+n.totalTokens}},Qp=(o,e)=>{let t=Xt(o),n=Xt(e);return Xt({promptTokens:Math.max(0,t.promptTokens-n.promptTokens),completionTokens:Math.max(0,t.completionTokens-n.completionTokens),totalTokens:Math.max(0,t.totalTokens-n.totalTokens)})},ni=o=>(o??[]).reduce((e,t)=>mo(e,{promptTokens:t.tokens?.promptTokens??0,completionTokens:t.tokens?.completionTokens??0,totalTokens:t.tokens?.totalTokens??0}),Rf()),$t=(o,e=240)=>{if(o===void 0)return;let t;if(typeof o=="string")t=o;else try{t=JSON.stringify(o)}catch{t=String(o)}let n=t.replace(/\s+/g," ").trim();if(n)return n.length<=e?n:`${n.slice(0,Math.max(0,e-3))}...`};var ri=(o,e)=>{let t=e?.maxCodeChars??220,n=e?.maxOutputChars??220,r=e?.maxTaskChars??220,s=e?.maxContextChars??220,i=e?.maxToolErrors??12,a=e?.maxFunctionCalls??12,u=e?.maxChildren??Number.POSITIVE_INFINITY,c=o.children.slice(0,u).map(d=>ri(d,e)),l=Xt(o.localUsage),p=c.reduce((d,m)=>mo(d,m.cumulativeUsage),l);return{nodeId:o.nodeId,parentId:o.parentId,depth:o.depth,role:o.role,taskDigest:$t(o.taskDigest,r),contextDigest:$t(o.contextDigest,s),completionType:o.completionType,turnCount:o.turnCount,childCount:c.length,actorTurns:o.actorTurns.map(d=>({turn:d.turn,code:$t(d.code,t)??"",output:$t(d.output,n)??"",isError:d.isError,thought:$t(d.thought,n)})),functionCalls:o.functionCalls.slice(0,a).map(d=>({qualifiedName:d.qualifiedName,name:d.name,error:$t(d.error,n)})),toolErrors:o.toolErrors.slice(0,i).map(d=>$t(d,n)??""),localUsage:l,cumulativeUsage:p,children:c}},iu=o=>{let e=0,t=0,n=0,r=0,s=0,i=0,a=0,u=0,c=0,l=[],p=d=>{e++,n=Math.max(n,d.depth),d.depth>0&&r++,d.children.length===0&&t++,d.children.length>1&&s++,d.completionType==="ask_clarification"&&i++,(d.toolErrors.length>0||d.functionCalls.some(g=>!!g.error)||d.actorTurns.some(g=>g.isError))&&a++,d.completionType==="final"&&(d.children.length>0?c++:u++),l.push({nodeId:d.nodeId,role:d.role,depth:d.depth,taskDigest:d.taskDigest,totalTokens:d.cumulativeUsage.totalTokens});for(let g of d.children)p(g)};return p(o),{nodeCount:e,leafCount:t,maxDepth:n,recursiveCallCount:r,batchedFanOutCount:s,clarificationCount:i,errorCount:a,directAnswerCount:u,delegatedAnswerCount:c,rootLocalUsage:Xt(o.localUsage),rootCumulativeUsage:Xt(o.cumulativeUsage),topExpensiveNodes:l.sort((d,m)=>m.totalTokens-d.totalTokens).slice(0,5)}},au=(o,e)=>{let t=[`Trace nodes=${e.nodeCount}, leaves=${e.leafCount}, maxDepth=${e.maxDepth}, recursiveCalls=${e.recursiveCallCount}, batchedFanOuts=${e.batchedFanOutCount}.`,`Final answers direct=${e.directAnswerCount}, delegated=${e.delegatedAnswerCount}, clarifications=${e.clarificationCount}, errorNodes=${e.errorCount}.`,`Root role=${o.role}, root local tokens=${e.rootLocalUsage.totalTokens}, root cumulative tokens=${e.rootCumulativeUsage.totalTokens}.`];if(e.topExpensiveNodes.length>0){let n=e.topExpensiveNodes.map(r=>{let s=r.taskDigest&&r.taskDigest.length>0?` (${r.taskDigest})`:"";return`${r.nodeId}:${r.totalTokens}${s}`}).join("; ");t.push(`Most expensive nodes: ${n}.`)}return t.join(`
1309
- `)},Yp=(o,e)=>{let t=new Map;for(let n of o.children){let r=n.taskDigest?.trim();r&&t.set(r,(t.get(r)??0)+1)}for(let[n,r]of t)r>1&&e.push(n);for(let n of o.children)Yp(n,e)},vf=o=>{let e=[],t=n=>{e.push(n);for(let r of n.children)t(r)};return t(o),e},Xp=o=>{let e=o.prediction.recursiveTrace,t=o.prediction.recursiveStats;if(!e||!t)return;let n=[],r=[];Yp(e,r);let s=vf(e),i=s.filter(c=>c.role==="recursive"),a=s.filter(c=>c.role==="terminal"),u=t.rootLocalUsage.totalTokens>0?t.rootCumulativeUsage.totalTokens/t.rootLocalUsage.totalTokens:t.rootCumulativeUsage.totalTokens>0?Number.POSITIVE_INFINITY:1;switch(o.componentId){case de.root:{e.childCount>=4&&n.push(`Root decomposition fanned out into ${e.childCount} subtasks. Delegate fewer, higher-leverage branches.`),e.childCount>0&&t.rootCumulativeUsage.totalTokens>=8e3&&u>=3&&n.push(`Root decomposition consumed ${t.rootCumulativeUsage.totalTokens} total tokens versus ${t.rootLocalUsage.totalTokens} local tokens. Prefer solving directly when a shallow answer is viable.`),r.length>0&&n.push(`Sibling subtasks overlap in scope (${[...new Set(r)].slice(0,2).join("; ")}). Make delegated tasks more distinct.`);break}case de.recursive:{let c=i.filter(p=>p.childCount===1&&p.cumulativeUsage.totalTokens>=2e3);c.length>0&&n.push(`Mid-tree branches repeatedly delegated one child at a time (${c.length} such nodes). Collapse serial delegation when the current branch can finish locally.`);let l=i.filter(p=>p.cumulativeUsage.totalTokens>=3e3).sort((p,d)=>d.cumulativeUsage.totalTokens-p.cumulativeUsage.totalTokens);l.length>0&&n.push(`Recursive branches are expensive (${l[0].cumulativeUsage.totalTokens} tokens on ${l[0].nodeId}). Narrow context and avoid redundant child work.`);break}case de.terminal:{let c=a.filter(p=>p.toolErrors.length>0||p.functionCalls.some(d=>!!d.error)||p.actorTurns.some(d=>d.isError));c.length>0&&n.push(`Terminal-depth nodes still hit avoidable errors (${c.length} nodes). Terminal instructions should prefer direct, minimal answers from already available context.`);let l=a.filter(p=>p.localUsage.totalTokens>=2e3||p.turnCount>=3);l.length>0&&n.push(`Terminal-depth nodes spent too much effort before answering (${l.length} nodes over budget). Encourage concise direct answers at max depth.`);break}case de.shared:{t.errorCount>0&&n.push(`The trace contains ${t.errorCount} error-producing nodes. Reinforce careful tool use, argument validation, and earlier stopping when the answer is already sufficient.`),t.rootCumulativeUsage.totalTokens>=1e4&&t.recursiveCallCount>=3&&n.push(`Tree-wide behavior is expensive (${t.rootCumulativeUsage.totalTokens} cumulative tokens across ${t.recursiveCallCount} recursive calls). Add stronger cost-awareness before delegating.`),t.delegatedAnswerCount>0&&t.directAnswerCount===0&&t.recursiveCallCount>=2&&n.push("The agent delegated every successful branch. Add a general rule to answer directly whenever the task can be completed without further recursion.");break}default:{t.errorCount>0&&n.push(`The recursive trace contains ${t.errorCount} error-producing nodes.`);break}}return n.length>0?n:void 0};var mr=o=>({[de.shared]:o?.trim()??"",[de.root]:"At the root, decide whether to solve directly or decompose. Delegate only when it clearly improves accuracy or reduces risk.",[de.recursive]:"Within recursive branches, avoid redundant delegation. Narrow context, keep sibling tasks distinct, and finish locally when further fan-out is unnecessary.",[de.terminal]:"At terminal depth, answer directly from the available context. Do not spend extra turns or imitate deeper delegation.",[de.responder]:""}),Zp=(o,e)=>{let t=[e[de.shared]?.trim(),o==="root"?e[de.root]?.trim():o==="recursive"?e[de.recursive]?.trim():e[de.terminal]?.trim()].filter(n=>!!n);if(t.length!==0)return t.join(`
1308
+ ${o}`:n}var lo="ax-agent-recursive-slots-v1",ge={shared:"root.actor.shared",root:"root.actor.root",recursive:"root.actor.recursive",terminal:"root.actor.terminal",responder:"root.responder"},kf=()=>({promptTokens:0,completionTokens:0,totalTokens:0}),Zt=o=>{let e=Math.max(0,Math.floor(o?.promptTokens??0)),t=Math.max(0,Math.floor(o?.completionTokens??0)),n=Math.max(0,Math.floor(o?.totalTokens??0)),r=Math.max(n,e+t);return{promptTokens:e,completionTokens:t,totalTokens:r}},po=(o,e)=>{let t=Zt(o),n=Zt(e);return{promptTokens:t.promptTokens+n.promptTokens,completionTokens:t.completionTokens+n.completionTokens,totalTokens:t.totalTokens+n.totalTokens}},Yp=(o,e)=>{let t=Zt(o),n=Zt(e);return Zt({promptTokens:Math.max(0,t.promptTokens-n.promptTokens),completionTokens:Math.max(0,t.completionTokens-n.completionTokens),totalTokens:Math.max(0,t.totalTokens-n.totalTokens)})},ni=o=>(o??[]).reduce((e,t)=>po(e,{promptTokens:t.tokens?.promptTokens??0,completionTokens:t.tokens?.completionTokens??0,totalTokens:t.tokens?.totalTokens??0}),kf()),$t=(o,e=240)=>{if(o===void 0)return;let t;if(typeof o=="string")t=o;else try{t=JSON.stringify(o)}catch{t=String(o)}let n=t.replace(/\s+/g," ").trim();if(n)return n.length<=e?n:`${n.slice(0,Math.max(0,e-3))}...`};var ri=(o,e)=>{let t=e?.maxCodeChars??220,n=e?.maxOutputChars??220,r=e?.maxTaskChars??220,s=e?.maxContextChars??220,i=e?.maxToolErrors??12,a=e?.maxFunctionCalls??12,u=e?.maxChildren??Number.POSITIVE_INFINITY,c=o.children.slice(0,u).map(d=>ri(d,e)),l=Zt(o.localUsage),p=c.reduce((d,m)=>po(d,m.cumulativeUsage),l);return{nodeId:o.nodeId,parentId:o.parentId,depth:o.depth,role:o.role,taskDigest:$t(o.taskDigest,r),contextDigest:$t(o.contextDigest,s),completionType:o.completionType,turnCount:o.turnCount,childCount:c.length,actorTurns:o.actorTurns.map(d=>({turn:d.turn,code:$t(d.code,t)??"",output:$t(d.output,n)??"",isError:d.isError,thought:$t(d.thought,n)})),functionCalls:o.functionCalls.slice(0,a).map(d=>({qualifiedName:d.qualifiedName,name:d.name,error:$t(d.error,n)})),toolErrors:o.toolErrors.slice(0,i).map(d=>$t(d,n)??""),localUsage:l,cumulativeUsage:p,children:c}},cu=o=>{let e=0,t=0,n=0,r=0,s=0,i=0,a=0,u=0,c=0,l=[],p=d=>{e++,n=Math.max(n,d.depth),d.depth>0&&r++,d.children.length===0&&t++,d.children.length>1&&s++,d.completionType==="ask_clarification"&&i++,(d.toolErrors.length>0||d.functionCalls.some(g=>!!g.error)||d.actorTurns.some(g=>g.isError))&&a++,d.completionType==="final"&&(d.children.length>0?c++:u++),l.push({nodeId:d.nodeId,role:d.role,depth:d.depth,taskDigest:d.taskDigest,totalTokens:d.cumulativeUsage.totalTokens});for(let g of d.children)p(g)};return p(o),{nodeCount:e,leafCount:t,maxDepth:n,recursiveCallCount:r,batchedFanOutCount:s,clarificationCount:i,errorCount:a,directAnswerCount:u,delegatedAnswerCount:c,rootLocalUsage:Zt(o.localUsage),rootCumulativeUsage:Zt(o.cumulativeUsage),topExpensiveNodes:l.sort((d,m)=>m.totalTokens-d.totalTokens).slice(0,5)}},lu=(o,e)=>{let t=[`Trace nodes=${e.nodeCount}, leaves=${e.leafCount}, maxDepth=${e.maxDepth}, recursiveCalls=${e.recursiveCallCount}, batchedFanOuts=${e.batchedFanOutCount}.`,`Final answers direct=${e.directAnswerCount}, delegated=${e.delegatedAnswerCount}, clarifications=${e.clarificationCount}, errorNodes=${e.errorCount}.`,`Root role=${o.role}, root local tokens=${e.rootLocalUsage.totalTokens}, root cumulative tokens=${e.rootCumulativeUsage.totalTokens}.`];if(e.topExpensiveNodes.length>0){let n=e.topExpensiveNodes.map(r=>{let s=r.taskDigest&&r.taskDigest.length>0?` (${r.taskDigest})`:"";return`${r.nodeId}:${r.totalTokens}${s}`}).join("; ");t.push(`Most expensive nodes: ${n}.`)}return t.join(`
1309
+ `)},Xp=(o,e)=>{let t=new Map;for(let n of o.children){let r=n.taskDigest?.trim();r&&t.set(r,(t.get(r)??0)+1)}for(let[n,r]of t)r>1&&e.push(n);for(let n of o.children)Xp(n,e)},Of=o=>{let e=[],t=n=>{e.push(n);for(let r of n.children)t(r)};return t(o),e},Zp=o=>{let e=o.prediction.recursiveTrace,t=o.prediction.recursiveStats;if(!e||!t)return;let n=[],r=[];Xp(e,r);let s=Of(e),i=s.filter(c=>c.role==="recursive"),a=s.filter(c=>c.role==="terminal"),u=t.rootLocalUsage.totalTokens>0?t.rootCumulativeUsage.totalTokens/t.rootLocalUsage.totalTokens:t.rootCumulativeUsage.totalTokens>0?Number.POSITIVE_INFINITY:1;switch(o.componentId){case ge.root:{e.childCount>=4&&n.push(`Root decomposition fanned out into ${e.childCount} subtasks. Delegate fewer, higher-leverage branches.`),e.childCount>0&&t.rootCumulativeUsage.totalTokens>=8e3&&u>=3&&n.push(`Root decomposition consumed ${t.rootCumulativeUsage.totalTokens} total tokens versus ${t.rootLocalUsage.totalTokens} local tokens. Prefer solving directly when a shallow answer is viable.`),r.length>0&&n.push(`Sibling subtasks overlap in scope (${[...new Set(r)].slice(0,2).join("; ")}). Make delegated tasks more distinct.`);break}case ge.recursive:{let c=i.filter(p=>p.childCount===1&&p.cumulativeUsage.totalTokens>=2e3);c.length>0&&n.push(`Mid-tree branches repeatedly delegated one child at a time (${c.length} such nodes). Collapse serial delegation when the current branch can finish locally.`);let l=i.filter(p=>p.cumulativeUsage.totalTokens>=3e3).sort((p,d)=>d.cumulativeUsage.totalTokens-p.cumulativeUsage.totalTokens);l.length>0&&n.push(`Recursive branches are expensive (${l[0].cumulativeUsage.totalTokens} tokens on ${l[0].nodeId}). Narrow context and avoid redundant child work.`);break}case ge.terminal:{let c=a.filter(p=>p.toolErrors.length>0||p.functionCalls.some(d=>!!d.error)||p.actorTurns.some(d=>d.isError));c.length>0&&n.push(`Terminal-depth nodes still hit avoidable errors (${c.length} nodes). Terminal instructions should prefer direct, minimal answers from already available context.`);let l=a.filter(p=>p.localUsage.totalTokens>=2e3||p.turnCount>=3);l.length>0&&n.push(`Terminal-depth nodes spent too much effort before answering (${l.length} nodes over budget). Encourage concise direct answers at max depth.`);break}case ge.shared:{t.errorCount>0&&n.push(`The trace contains ${t.errorCount} error-producing nodes. Reinforce careful tool use, argument validation, and earlier stopping when the answer is already sufficient.`),t.rootCumulativeUsage.totalTokens>=1e4&&t.recursiveCallCount>=3&&n.push(`Tree-wide behavior is expensive (${t.rootCumulativeUsage.totalTokens} cumulative tokens across ${t.recursiveCallCount} recursive calls). Add stronger cost-awareness before delegating.`),t.delegatedAnswerCount>0&&t.directAnswerCount===0&&t.recursiveCallCount>=2&&n.push("The agent delegated every successful branch. Add a general rule to answer directly whenever the task can be completed without further recursion.");break}default:{t.errorCount>0&&n.push(`The recursive trace contains ${t.errorCount} error-producing nodes.`);break}}return n.length>0?n:void 0};var gr=o=>({[ge.shared]:o?.trim()??"",[ge.root]:"At the root, decide whether to solve directly or decompose. Delegate only when it clearly improves accuracy or reduces risk.",[ge.recursive]:"Within recursive branches, avoid redundant delegation. Narrow context, keep sibling tasks distinct, and finish locally when further fan-out is unnecessary.",[ge.terminal]:"At terminal depth, answer directly from the available context. Do not spend extra turns or imitate deeper delegation.",[ge.responder]:""}),ed=(o,e)=>{let t=[e[ge.shared]?.trim(),o==="root"?e[ge.root]?.trim():o==="recursive"?e[ge.recursive]?.trim():e[ge.terminal]?.trim()].filter(n=>!!n);if(t.length!==0)return t.join(`
1310
1310
 
1311
- `)};var pt=class extends Error{question;clarification;stateSnapshot;stateErrorMessage;constructor(e,t){let n=xd(e);super(n.question),this.name="AxAgentClarificationError",this.question=n.question,this.clarification=n,this.stateSnapshot=t?.state?gr(t.state):void 0,this.stateErrorMessage=t?.stateError}getState(){if(this.stateErrorMessage)throw new Error(this.stateErrorMessage);return this.stateSnapshot?gr(this.stateSnapshot):void 0}},td=8,uu=5e3,Sf=8,nd=8,oi=2,kf=1200,si="agents",Of=2,Ef=14e3,Mf=1e4,Pf=4,Ff=2,_f=3,Nf=8e3,Lf=3,$f=3,Df=100,Uf=new Set(["console","Math","JSON","Object","Array","String","Number","Boolean","Date","Promise","Reflect","Map","Set","WeakMap","WeakSet","Symbol","Intl","URL","URLSearchParams"]),Gf=/^[$A-Z_a-z][$0-9A-Z_a-z]*$/,Bf=new Set(["context","__proto__","prototype","constructor","globalThis","global","self","window","console","JSON","Math","Reflect","Atomics","Array","Object","String","Number","Boolean","BigInt","Symbol","Date","RegExp","Error","EvalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError","AggregateError","Map","Set","WeakMap","WeakSet","Promise","Proxy","Function","Intl","URL","URLSearchParams","TextEncoder","TextDecoder","AbortController","AbortSignal","parseInt","parseFloat","isNaN","isFinite","eval","undefined","Infinity","NaN","await","break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","false","finally","for","function","if","import","in","instanceof","new","null","return","super","switch","this","throw","true","try","typeof","var","void","while","with","yield","let","static","implements","interface","package","private","protected","public"]),cu="listModuleFunctions",lu="getFunctionDefinitions",jf="AI service is required to use llmQuery(...) in AxAgent.test(). Pass options.ai or configure ai on the agent.",ui="[The JavaScript runtime was restarted; all global state was lost and must be recreated if needed.]",BR=new Ne(`
1311
+ `)};var pt=class extends Error{question;clarification;stateSnapshot;stateErrorMessage;constructor(e,t){let n=bd(e);super(n.question),this.name="AxAgentClarificationError",this.question=n.question,this.clarification=n,this.stateSnapshot=t?.state?fr(t.state):void 0,this.stateErrorMessage=t?.stateError}getState(){if(this.stateErrorMessage)throw new Error(this.stateErrorMessage);return this.stateSnapshot?fr(this.stateSnapshot):void 0}},nd=8,pu=5e3,Ef=8,rd=8,oi=2,Mf=1200,si="agents",Pf=2,Ff=100,od='actorModelPolicy now expects an ordered array of { model, abovePromptChars?, aboveErrorTurns? } entries. Example: actorModelPolicy: [{ model: "gpt-5.4-mini", abovePromptChars: 16000 }, { model: "gpt-5.4", aboveErrorTurns: 2 }]',_f=/^[$A-Z_a-z][$0-9A-Z_a-z]*$/,Nf=new Set(["context","__proto__","prototype","constructor","globalThis","global","self","window","console","JSON","Math","Reflect","Atomics","Array","Object","String","Number","Boolean","BigInt","Symbol","Date","RegExp","Error","EvalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError","AggregateError","Map","Set","WeakMap","WeakSet","Promise","Proxy","Function","Intl","URL","URLSearchParams","TextEncoder","TextDecoder","AbortController","AbortSignal","parseInt","parseFloat","isNaN","isFinite","eval","undefined","Infinity","NaN","await","break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","false","finally","for","function","if","import","in","instanceof","new","null","return","super","switch","this","throw","true","try","typeof","var","void","while","with","yield","let","static","implements","interface","package","private","protected","public"]),du="listModuleFunctions",mu="getFunctionDefinitions",$f="AI service is required to use llmQuery(...) in AxAgent.test(). Pass options.ai or configure ai on the agent.",ui="[The JavaScript runtime was restarted; all global state was lost and must be recreated if needed.]",DR=new _e(`
1312
1312
  taskInput:json "The structured task input passed to the agent",
1313
1313
  criteria:string "Task-specific success criteria",
1314
1314
  expectedOutput?:json "Optional expected final output",
@@ -1326,7 +1326,7 @@ ${o}`:n}var po="ax-agent-recursive-slots-v1",de={shared:"root.actor.shared",root
1326
1326
  usage?:json "Optional usage summary for the run",
1327
1327
  recursiveTrace?:json "Optional structured recursive trace projection for advanced recursive llmQuery runs",
1328
1328
  recursiveStats?:json "Optional deterministic recursive trace statistics for advanced recursive llmQuery runs"
1329
- `),zf=new Ne(`
1329
+ `),Lf=new _e(`
1330
1330
  taskInput:json "The structured task input passed to the agent",
1331
1331
  criteria:string "Task-specific success criteria",
1332
1332
  expectedOutput?:json "Optional expected final output",
@@ -1346,11 +1346,11 @@ ${o}`:n}var po="ax-agent-recursive-slots-v1",de={shared:"root.actor.shared",root
1346
1346
  ->
1347
1347
  reasoning:string "Short explanation of the run quality",
1348
1348
  quality:class "excellent, good, acceptable, poor, unacceptable" "Overall run quality tier"
1349
- `),qf=new Ne(`
1349
+ `),Df=new _e(`
1350
1350
  taskRecord:json "Full optimization task record, including the agent input and evaluation criteria"
1351
1351
  ->
1352
1352
  agentRunReport:json "Agent run report containing completion type, clarification or final output, action log, function calls, errors, and turn count"
1353
- `);function Hf(o){return"train"in o?{train:o.train,validation:o.validation}:{train:o}}function lt(o){if(o!==void 0){if(o===null)return null;if(typeof o=="string"||typeof o=="number"||typeof o=="boolean")return o;if(Array.isArray(o))try{return JSON.parse(JSON.stringify(o))}catch{return o.map(e=>lt(e))}if(typeof o=="object")try{return JSON.parse(JSON.stringify(o))}catch{return String(o)}return String(o)}}function Wf(o){let e=o.trim();for(;;){let t=e;if(e=e.replace(/^```(?:[A-Za-z0-9_-]+)?[ \t]*\r?\n/,""),e=e.replace(/\r?\n?```[ \t]*$/,""),e=e.trim(),e===t)return e}}function Kf(o){let e=`
1353
+ `);function Uf(o){return"train"in o?{train:o.train,validation:o.validation}:{train:o}}function lt(o){if(o!==void 0){if(o===null)return null;if(typeof o=="string"||typeof o=="number"||typeof o=="boolean")return o;if(Array.isArray(o))try{return JSON.parse(JSON.stringify(o))}catch{return o.map(e=>lt(e))}if(typeof o=="object")try{return JSON.parse(JSON.stringify(o))}catch{return String(o)}return String(o)}}function Gf(o){let e=o.trim();for(;;){let t=e;if(e=e.replace(/^```(?:[A-Za-z0-9_-]+)?[ \t]*\r?\n/,""),e=e.replace(/\r?\n?```[ \t]*$/,""),e=e.trim(),e===t)return e}}function jf(o){let e=`
1354
1354
  Use the input field named "criteria" as the task-specific rubric for success.
1355
1355
  - Reward actual task completion over polished wording.
1356
1356
  - Reward correct tool choice and correct arguments.
@@ -1365,42 +1365,42 @@ Use the input field named "criteria" as the task-specific rubric for success.
1365
1365
  `.trim(),t=o?.trim();return t?`${e}
1366
1366
 
1367
1367
  Additional Evaluation Guidance:
1368
- ${t}`:e}function Vf(o){let{criteria:e,description:t,randomizeOrder:n,...r}=o;return{...r,maxSteps:1}}function Jf(o){let e=o.toLowerCase();return e==="excellent"?1:e==="good"?.8:e==="acceptable"?.5:e==="poor"?.2:e==="unacceptable"?0:.5}function rd(o,e){return e.qualifiedName===o||e.name===o||e.qualifiedName.endsWith(`.${o}`)}function Qf(o,e,t){let n=Math.max(0,Math.min(1,o)),r=e.expectedActions??[];if(r.length>0){let i=r.filter(a=>t.functionCalls.some(u=>rd(a,u))).length;n*=.5+.5*(i/r.length)}return(e.forbiddenActions??[]).some(i=>t.functionCalls.some(a=>rd(i,a)))&&(n*=.2),Math.max(0,Math.min(1,n))}function Yf(o,e){let t=new Set(o.map(i=>i.id)),n=t.has(de.shared),r=[de.shared,de.root,de.recursive,de.terminal].filter(i=>t.has(i));if(e==="actor"){if(n){if(r.length===0)throw new Error("AxAgent.optimize(): recursive actor targets are not available");return r}if(!t.has("root.actor"))throw new Error("AxAgent.optimize(): root.actor is not available");return["root.actor"]}if(e==="responder"){if(!t.has("root.responder"))throw new Error("AxAgent.optimize(): root.responder is not available");return["root.responder"]}if(e==="all")return n?[...r,...t.has(de.responder)?[de.responder]:[]]:[...t];let s=[...e];for(let i of s)if(!t.has(i))throw new Error(`AxAgent.optimize(): unknown target program ID "${i}"`);return s}var fr=class extends Error{constructor(t){super(`AxAgent protocol completion: ${t}`);this.type=t;this.name="AxAgentProtocolCompletionSignal"}};function od(o){return{finalFunction:(...r)=>{o("final",r)},askClarificationFunction:(...r)=>{o("ask_clarification",r)},protocol:{final:(...r)=>{throw o("final",r),new fr("final")},askClarification:(...r)=>{throw o("ask_clarification",r),new fr("ask_clarification")}}}}function Xf(o,e,t){return{model:o?.model,modelConfig:o?.modelConfig,debug:e,verbose:o?.verbose,rateLimiter:o?.rateLimiter,fetch:o?.fetch,tracer:o?.tracer,meter:o?.meter,timeout:o?.timeout,excludeContentFromTrace:o?.excludeContentFromTrace,abortSignal:t,logger:o?.logger,sessionId:o?.sessionId,debugHideSystemPrompt:o?.debugHideSystemPrompt,traceContext:o?.traceContext,thinkingTokenBudget:o?.thinkingTokenBudget,showThoughts:o?.showThoughts,useExpensiveModel:o?.useExpensiveModel,corsProxy:o?.corsProxy,retry:o?.retry,contextCache:o?.contextCache,examplesInSystem:o?.examplesInSystem,customLabels:o?.customLabels}}function sd(o,e){if(typeof o!="string"||o.trim().length===0)throw new Error(`${e} must be a non-empty string`);return o.trim()}function Zf(o){if(o)return{escalatedModel:sd(o.escalatedModel,"actorModelPolicy.escalatedModel"),...o.baseModel!==void 0?{baseModel:sd(o.baseModel,"actorModelPolicy.baseModel")}:{},escalateAtPromptChars:Math.max(1,o.escalateAtPromptChars??Ef),escalateAtPromptCharsWhenCheckpointed:Math.max(1,o.escalateAtPromptCharsWhenCheckpointed??Mf),recentErrorWindowTurns:Math.max(1,o.recentErrorWindowTurns??Pf),recentErrorThreshold:Math.max(1,o.recentErrorThreshold??Ff),discoveryStallTurns:Math.max(1,o.discoveryStallTurns??_f),deescalateBelowPromptChars:Math.max(0,o.deescalateBelowPromptChars??Nf),stableTurnsBeforeDeescalate:Math.max(1,o.stableTurnsBeforeDeescalate??Lf),minEscalatedTurns:Math.max(0,o.minEscalatedTurns??$f)}}function id(o){let e=o?.preset??"full",t=eh(e),n=o?.expert?.rankPruning,r=n?.enabled??(n?.minRank!==void 0?!0:t.hindsight),s=o?.state?.summary??t.stateSummary,i=o?.state?.inspect??t.inspect,a=o?.checkpoints?.enabled??t.checkpointsEnabled;if(a&&!s&&!i)throw new Error("contextPolicy.checkpoints requires either state.summary or state.inspect to be enabled");return{preset:e,summarizerOptions:o?.summarizerOptions,pruneUsedDocs:o?.pruneUsedDocs??t.pruneUsedDocs,actionReplay:o?.expert?.replay??t.actionReplay,recentFullActions:Math.max(o?.expert?.recentFullActions??t.recentFullActions,0),errorPruning:o?.pruneErrors??t.errorPruning,hindsightEvaluation:r,pruneRank:n?.minRank??t.pruneRank,rankPruneGraceTurns:Of,tombstoning:o?.expert?.tombstones,stateSummary:{enabled:s,maxEntries:o?.state?.maxEntries??t.maxEntries,maxChars:o?.state?.maxChars??t.maxStateChars},stateInspection:{enabled:i,contextThreshold:o?.state?.inspectThresholdChars??t.inspectThreshold},checkpoints:{enabled:a,triggerChars:o?.checkpoints?.triggerChars??t.checkpointTriggerChars}}}function eh(o){switch(o){case"adaptive":return{actionReplay:"adaptive",recentFullActions:3,errorPruning:!0,hindsight:!1,pruneRank:2,pruneUsedDocs:!1,stateSummary:!0,inspect:!0,inspectThreshold:1e4,maxEntries:8,maxStateChars:1600,checkpointsEnabled:!0,checkpointTriggerChars:16e3};case"lean":return{actionReplay:"minimal",recentFullActions:1,errorPruning:!0,hindsight:!1,pruneRank:2,pruneUsedDocs:!0,stateSummary:!0,inspect:!0,inspectThreshold:6e3,maxEntries:4,maxStateChars:800,checkpointsEnabled:!0,checkpointTriggerChars:9e3};case"checkpointed":return{actionReplay:"checkpointed",recentFullActions:3,errorPruning:!1,hindsight:!1,pruneRank:2,pruneUsedDocs:!1,stateSummary:!0,inspect:!0,inspectThreshold:1e4,maxEntries:8,maxStateChars:1600,checkpointsEnabled:!0,checkpointTriggerChars:12e3};default:return{actionReplay:"full",recentFullActions:1,errorPruning:!1,hindsight:!1,pruneRank:2,pruneUsedDocs:!1,stateSummary:!1,inspect:!1,inspectThreshold:void 0,maxEntries:void 0,maxStateChars:void 0,checkpointsEnabled:!1,checkpointTriggerChars:void 0}}}function fd(o){let e=Nt(o),t=new Set,n=/\b([a-zA-Z_$][a-zA-Z0-9_$]*)\.([a-zA-Z_$][a-zA-Z0-9_$]*)\s*\(/g,r=n.exec(e);for(;r;){let s=r[1],i=r[2];s&&i&&!Uf.has(s)&&t.add(`${s}.${i}`),r=n.exec(e)}return[...t]}function th(o){return o.tags.includes("error")||!/\b(listModuleFunctions|getFunctionDefinitions)\s*\(/.test(o.code)?!1:fd(o.code).length===0}function nh(o,e){return o.slice(-e.recentErrorWindowTurns).filter(r=>r.tags.includes("error")).length>=e.recentErrorThreshold}function rh(o,e){if(o.length<e.discoveryStallTurns)return!1;let t=0;for(let n=o.length-1;n>=0;n--){let r=o[n];if(!r||r.tags.includes("error")||fd(r.code).length>0||!th(r))break;if(t+=1,t>=e.discoveryStallTurns)return!0}return!1}function oh(o,e,t,n){return{promptFacingChars:t,checkpointActive:n,recentErrorTrigger:nh(e,o),discoveryStallTrigger:rh(e,o)}}function sh(o,e,t){let n=t.checkpointActive?e.escalateAtPromptCharsWhenCheckpointed:e.escalateAtPromptChars,s=t.promptFacingChars>=n||t.recentErrorTrigger||t.discoveryStallTrigger,i=o?{...o}:{escalated:!1,escalatedTurns:0,stableBelowThresholdTurns:0};if(!i.escalated)return s?{escalated:!0,escalatedTurns:1,stableBelowThresholdTurns:0}:(i.escalatedTurns=0,i.stableBelowThresholdTurns=0,i);if(s)return{escalated:!0,escalatedTurns:i.escalatedTurns+1,stableBelowThresholdTurns:0};if(!(t.promptFacingChars<e.deescalateBelowPromptChars&&!t.recentErrorTrigger&&!t.discoveryStallTrigger&&i.escalatedTurns>=e.minEscalatedTurns))return{escalated:!0,escalatedTurns:i.escalatedTurns+1,stableBelowThresholdTurns:0};let u=i.stableBelowThresholdTurns+1;return u>=e.stableTurnsBeforeDeescalate?{escalated:!1,escalatedTurns:0,stableBelowThresholdTurns:0}:{escalated:!0,escalatedTurns:i.escalatedTurns+1,stableBelowThresholdTurns:u}}function ih(){let o=new Map,e={nextNodeOrdinal:1,nodesById:o,rootNode:void 0,createNode:({parentId:t,depth:n,role:r,taskDigest:s,contextDigest:i})=>{let a=`trace_${e.nextNodeOrdinal++}`,u={nodeId:a,parentId:t,depth:n,role:r,taskDigest:s,contextDigest:i,completionType:void 0,turnCount:0,actorTurns:[],functionCalls:[],toolErrors:[],localUsage:{promptTokens:0,completionTokens:0,totalTokens:0},children:[]};return o.set(a,u),t?o.get(t)?.children.push(u):e.rootNode=u,u}};return e}function du(o){let e=o.children.map(r=>du(r)),t=o.localUsage,n=e.reduce((r,s)=>({promptTokens:r.promptTokens+s.cumulativeUsage.promptTokens,completionTokens:r.completionTokens+s.cumulativeUsage.completionTokens,totalTokens:r.totalTokens+s.cumulativeUsage.totalTokens}),{...t});return{nodeId:o.nodeId,parentId:o.parentId,depth:o.depth,role:o.role,taskDigest:o.taskDigest,contextDigest:o.contextDigest,completionType:o.completionType,turnCount:o.turnCount,childCount:e.length,actorTurns:[...o.actorTurns],functionCalls:[...o.functionCalls],toolErrors:[...o.toolErrors],localUsage:{...t},cumulativeUsage:n,children:e}}var ho=class o{ai;judgeAI;program;actorProgram;responderProgram;agents;agentFunctions;agentFunctionModuleMetadata=new Map;debug;options;rlmConfig;runtime;actorFieldNames;localFieldNames;sharedFieldNames;globalSharedFieldNames;excludedSharedFields;excludedAgents;excludedAgentFunctions;actorDescription;actorPromptLevel;actorModelPolicy;responderDescription;judgeOptions;recursionForwardOptions;actorForwardOptions;responderForwardOptions;inputUpdateCallback;contextPromptConfigByField=new Map;agentModuleNamespace=si;functionDiscoveryEnabled=!1;runtimeUsageInstructions="";enforceIncrementalConsoleTurns=!1;activeAbortControllers=new Set;_stopRequested=!1;state;stateError;runtimeBootstrapContext=void 0;llmQueryBudgetState;recursiveInstructionSlots=mr();baseActorDefinition="";recursiveEvalContext;currentRecursiveTraceNodeId;recursiveInstructionRoleOverride;func;_parentSharedFields=new Set;_parentSharedAgents=new Set;_parentSharedAgentFunctions=new Set;_reservedAgentFunctionNamespaces(){return new Set(["inputs","llmQuery","final","ask_clarification","inspect_runtime",si,this.agentModuleNamespace,...this.functionDiscoveryEnabled?[cu,lu]:[]])}_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`)}}_supportsRecursiveActorSlotOptimization(){if((this.rlmConfig.mode??"simple")!=="advanced")return!1;let e=this.recursionForwardOptions?.maxDepth??oi;return!!this.recursiveInstructionRoleOverride||Math.max(0,e)>0}_getRecursiveActorRole(){if((this.rlmConfig.mode??"simple")!=="advanced")return;if(this.recursiveInstructionRoleOverride)return this.recursiveInstructionRoleOverride;let e=this.recursionForwardOptions?.maxDepth??oi;return Math.max(0,e)>0?"root":void 0}_applyRecursiveActorInstruction(){let e=this._getRecursiveActorRole();if(!e||!this.actorProgram)return;let t=Zp(e,this.recursiveInstructionSlots),n=[this.baseActorDefinition.trim(),t?.trim()].filter(r=>!!r).join(`
1368
+ ${t}`:e}function Bf(o){let{criteria:e,description:t,randomizeOrder:n,...r}=o;return{...r,maxSteps:1}}function zf(o){let e=o.toLowerCase();return e==="excellent"?1:e==="good"?.8:e==="acceptable"?.5:e==="poor"?.2:e==="unacceptable"?0:.5}function sd(o,e){return e.qualifiedName===o||e.name===o||e.qualifiedName.endsWith(`.${o}`)}function qf(o,e,t){let n=Math.max(0,Math.min(1,o)),r=e.expectedActions??[];if(r.length>0){let i=r.filter(a=>t.functionCalls.some(u=>sd(a,u))).length;n*=.5+.5*(i/r.length)}return(e.forbiddenActions??[]).some(i=>t.functionCalls.some(a=>sd(i,a)))&&(n*=.2),Math.max(0,Math.min(1,n))}function Hf(o,e){let t=new Set(o.map(i=>i.id)),n=t.has(ge.shared),r=[ge.shared,ge.root,ge.recursive,ge.terminal].filter(i=>t.has(i));if(e==="actor"){if(n){if(r.length===0)throw new Error("AxAgent.optimize(): recursive actor targets are not available");return r}if(!t.has("root.actor"))throw new Error("AxAgent.optimize(): root.actor is not available");return["root.actor"]}if(e==="responder"){if(!t.has("root.responder"))throw new Error("AxAgent.optimize(): root.responder is not available");return["root.responder"]}if(e==="all")return n?[...r,...t.has(ge.responder)?[ge.responder]:[]]:[...t];let s=[...e];for(let i of s)if(!t.has(i))throw new Error(`AxAgent.optimize(): unknown target program ID "${i}"`);return s}var hr=class extends Error{constructor(t){super(`AxAgent protocol completion: ${t}`);this.type=t;this.name="AxAgentProtocolCompletionSignal"}};function id(o){return{finalFunction:(...r)=>{o("final",r)},askClarificationFunction:(...r)=>{o("ask_clarification",r)},protocol:{final:(...r)=>{throw o("final",r),new hr("final")},askClarification:(...r)=>{throw o("ask_clarification",r),new hr("ask_clarification")}}}}function Kf(o,e,t){return{model:o?.model,modelConfig:o?.modelConfig,debug:e,verbose:o?.verbose,rateLimiter:o?.rateLimiter,fetch:o?.fetch,tracer:o?.tracer,meter:o?.meter,timeout:o?.timeout,excludeContentFromTrace:o?.excludeContentFromTrace,abortSignal:t,logger:o?.logger,sessionId:o?.sessionId,debugHideSystemPrompt:o?.debugHideSystemPrompt,traceContext:o?.traceContext,thinkingTokenBudget:o?.thinkingTokenBudget,showThoughts:o?.showThoughts,useExpensiveModel:o?.useExpensiveModel,corsProxy:o?.corsProxy,retry:o?.retry,contextCache:o?.contextCache,examplesInSystem:o?.examplesInSystem,customLabels:o?.customLabels}}function Vf(o,e){if(typeof o!="string"||o.trim().length===0)throw new Error(`${e} must be a non-empty string`);return o.trim()}function ad(o,e){if(o!==void 0){if(typeof o!="number"||!Number.isFinite(o)||o<0)throw new Error(`${e} must be a finite number >= 0`);return o}}function Wf(o){if(o!==void 0){if(!Array.isArray(o))throw new Error(od);if(o.length===0)throw new Error("actorModelPolicy must contain at least one entry");return o.map((e,t)=>{if(!e||typeof e!="object"||Array.isArray(e))throw new Error(`actorModelPolicy[${t}] must be an object`);let n=e;if("escalatedModel"in n||"baseModel"in n||"escalateAtPromptChars"in n||"escalateAtPromptCharsWhenCheckpointed"in n||"recentErrorWindowTurns"in n||"recentErrorThreshold"in n||"discoveryStallTurns"in n||"deescalateBelowPromptChars"in n||"stableTurnsBeforeDeescalate"in n||"minEscalatedTurns"in n)throw new Error(od);let r=ad(n.abovePromptChars,`actorModelPolicy[${t}].abovePromptChars`),s=ad(n.aboveErrorTurns,`actorModelPolicy[${t}].aboveErrorTurns`);if(s!==void 0&&!Number.isInteger(s))throw new Error(`actorModelPolicy[${t}].aboveErrorTurns must be an integer >= 0`);if(r===void 0&&s===void 0)throw new Error(`actorModelPolicy[${t}] must define at least one of abovePromptChars or aboveErrorTurns`);return{model:Vf(n.model,`actorModelPolicy[${t}].model`),...r!==void 0?{abovePromptChars:r}:{},...s!==void 0?{aboveErrorTurns:s}:{}}})}}function ud(o){let e=o?.preset??"full",t=Jf(e),n=o?.expert?.rankPruning,r=n?.enabled??(n?.minRank!==void 0?!0:t.hindsight),s=o?.state?.summary??t.stateSummary,i=o?.state?.inspect??t.inspect,a=o?.checkpoints?.enabled??t.checkpointsEnabled;if(a&&!s&&!i)throw new Error("contextPolicy.checkpoints requires either state.summary or state.inspect to be enabled");return{preset:e,summarizerOptions:o?.summarizerOptions,pruneUsedDocs:o?.pruneUsedDocs??t.pruneUsedDocs,actionReplay:o?.expert?.replay??t.actionReplay,recentFullActions:Math.max(o?.expert?.recentFullActions??t.recentFullActions,0),errorPruning:o?.pruneErrors??t.errorPruning,hindsightEvaluation:r,pruneRank:n?.minRank??t.pruneRank,rankPruneGraceTurns:Pf,tombstoning:o?.expert?.tombstones,stateSummary:{enabled:s,maxEntries:o?.state?.maxEntries??t.maxEntries,maxChars:o?.state?.maxChars??t.maxStateChars},stateInspection:{enabled:i,contextThreshold:o?.state?.inspectThresholdChars??t.inspectThreshold},checkpoints:{enabled:a,triggerChars:o?.checkpoints?.triggerChars??t.checkpointTriggerChars}}}function Jf(o){switch(o){case"adaptive":return{actionReplay:"adaptive",recentFullActions:3,errorPruning:!0,hindsight:!1,pruneRank:2,pruneUsedDocs:!1,stateSummary:!0,inspect:!0,inspectThreshold:16e3,maxEntries:8,maxStateChars:1600,checkpointsEnabled:!0,checkpointTriggerChars:22e3};case"lean":return{actionReplay:"minimal",recentFullActions:1,errorPruning:!0,hindsight:!1,pruneRank:2,pruneUsedDocs:!0,stateSummary:!0,inspect:!0,inspectThreshold:12e3,maxEntries:4,maxStateChars:800,checkpointsEnabled:!0,checkpointTriggerChars:15e3};case"checkpointed":return{actionReplay:"checkpointed",recentFullActions:3,errorPruning:!1,hindsight:!1,pruneRank:2,pruneUsedDocs:!1,stateSummary:!0,inspect:!0,inspectThreshold:16e3,maxEntries:8,maxStateChars:1600,checkpointsEnabled:!0,checkpointTriggerChars:18e3};default:return{actionReplay:"full",recentFullActions:1,errorPruning:!1,hindsight:!1,pruneRank:2,pruneUsedDocs:!1,stateSummary:!1,inspect:!1,inspectThreshold:void 0,maxEntries:void 0,maxStateChars:void 0,checkpointsEnabled:!1,checkpointTriggerChars:void 0}}}function xd(o){return o?.consecutiveErrorTurns??0}function Ad(){return{consecutiveErrorTurns:0}}function Qf(o){if(!o||typeof o!="object"||Array.isArray(o))return;let e=o,t=e.consecutiveErrorTurns;if(typeof t=="number"&&Number.isFinite(t)&&t>=0)return{consecutiveErrorTurns:Math.floor(t)};if("escalated"in e||"escalatedTurns"in e||"stableBelowThresholdTurns"in e)return Ad()}function Yf(o,e){return{consecutiveErrorTurns:e?xd(o)+1:0}}function Xf(o,e,t){let n;for(let r of o){let s=r.abovePromptChars!==void 0&&e>=r.abovePromptChars,i=r.aboveErrorTurns!==void 0&&t>=r.aboveErrorTurns;(s||i)&&(n=r.model)}return n}function Zf(){let o=new Map,e={nextNodeOrdinal:1,nodesById:o,rootNode:void 0,createNode:({parentId:t,depth:n,role:r,taskDigest:s,contextDigest:i})=>{let a=`trace_${e.nextNodeOrdinal++}`,u={nodeId:a,parentId:t,depth:n,role:r,taskDigest:s,contextDigest:i,completionType:void 0,turnCount:0,actorTurns:[],functionCalls:[],toolErrors:[],localUsage:{promptTokens:0,completionTokens:0,totalTokens:0},children:[]};return o.set(a,u),t?o.get(t)?.children.push(u):e.rootNode=u,u}};return e}function fu(o){let e=o.children.map(r=>fu(r)),t=o.localUsage,n=e.reduce((r,s)=>({promptTokens:r.promptTokens+s.cumulativeUsage.promptTokens,completionTokens:r.completionTokens+s.cumulativeUsage.completionTokens,totalTokens:r.totalTokens+s.cumulativeUsage.totalTokens}),{...t});return{nodeId:o.nodeId,parentId:o.parentId,depth:o.depth,role:o.role,taskDigest:o.taskDigest,contextDigest:o.contextDigest,completionType:o.completionType,turnCount:o.turnCount,childCount:e.length,actorTurns:[...o.actorTurns],functionCalls:[...o.functionCalls],toolErrors:[...o.toolErrors],localUsage:{...t},cumulativeUsage:n,children:e}}var fo=class o{ai;judgeAI;program;actorProgram;responderProgram;agents;agentFunctions;agentFunctionModuleMetadata=new Map;debug;options;rlmConfig;runtime;actorFieldNames;localFieldNames;sharedFieldNames;globalSharedFieldNames;excludedSharedFields;excludedAgents;excludedAgentFunctions;actorDescription;actorPromptLevel;actorModelPolicy;responderDescription;judgeOptions;recursionForwardOptions;actorForwardOptions;responderForwardOptions;inputUpdateCallback;contextPromptConfigByField=new Map;agentModuleNamespace=si;functionDiscoveryEnabled=!1;runtimeUsageInstructions="";enforceIncrementalConsoleTurns=!1;activeAbortControllers=new Set;_stopRequested=!1;state;stateError;runtimeBootstrapContext=void 0;llmQueryBudgetState;recursiveInstructionSlots=gr();baseActorDefinition="";recursiveEvalContext;currentRecursiveTraceNodeId;recursiveInstructionRoleOverride;func;_parentSharedFields=new Set;_parentSharedAgents=new Set;_parentSharedAgentFunctions=new Set;_reservedAgentFunctionNamespaces(){return new Set(["inputs","llmQuery","final","ask_clarification","inspect_runtime",si,this.agentModuleNamespace,...this.functionDiscoveryEnabled?[du,mu]:[]])}_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`)}}_supportsRecursiveActorSlotOptimization(){if((this.rlmConfig.mode??"simple")!=="advanced")return!1;let e=this.recursionForwardOptions?.maxDepth??oi;return!!this.recursiveInstructionRoleOverride||Math.max(0,e)>0}_getRecursiveActorRole(){if((this.rlmConfig.mode??"simple")!=="advanced")return;if(this.recursiveInstructionRoleOverride)return this.recursiveInstructionRoleOverride;let e=this.recursionForwardOptions?.maxDepth??oi;return Math.max(0,e)>0?"root":void 0}_applyRecursiveActorInstruction(){let e=this._getRecursiveActorRole();if(!e||!this.actorProgram)return;let t=ed(e,this.recursiveInstructionSlots),n=[this.baseActorDefinition.trim(),t?.trim()].filter(r=>!!r).join(`
1369
1369
 
1370
- `);this.actorProgram.setDescription(n),this.actorProgram.setInstruction(n)}_setRecursiveInstructionSlot(e,t){if(e===de.responder){this.responderProgram.setInstruction(t??"");return}this.recursiveInstructionSlots[e]=t??"",this._applyRecursiveActorInstruction()}_copyRecursiveOptimizationStateTo(e){e.recursiveInstructionSlots={...this.recursiveInstructionSlots},e.recursiveInstructionRoleOverride=e._supportsRecursiveActorSlotOptimization()?e.recursiveInstructionRoleOverride:void 0,e._applyRecursiveActorInstruction()}constructor({ai:e,judgeAI:t,agentIdentity:n,agentModuleNamespace:r,signature:s},i){let{debug:a,contextFields:u,runtime:c,maxSubAgentCalls:l,maxRuntimeChars:p,maxBatchedLlmQueryConcurrency:d,maxTurns:m,contextPolicy:g,actorFields:f,actorTurnCallback:x,mode:A,promptLevel:h,actorModelPolicy:y,recursionOptions:T,actorOptions:C,responderOptions:R,judgeOptions:M,inputUpdateCallback:I}=i;this.ai=e,this.judgeAI=t,this.agents=i.agents?.local,this.functionDiscoveryEnabled=i.functions?.discovery??!1,this.debug=a,this.options=i,this.runtime=c??new gn,this.runtimeUsageInstructions=this.runtime.getUsageInstructions(),this.enforceIncrementalConsoleTurns=$h(this.runtimeUsageInstructions);let O=r??n?.namespace??si;if(this.agentModuleNamespace=jh(O,{normalize:r===void 0}),new Set(["inputs","llmQuery","final","ask_clarification","inspect_runtime",cu,lu]).has(this.agentModuleNamespace))throw new Error(`Agent module namespace "${this.agentModuleNamespace}" is reserved`);let $=this._reservedAgentFunctionNamespaces(),N=pu(i.functions?.local,$),S=pu(i.functions?.shared,$),v=pu(i.functions?.globallyShared,$);this.agentFunctions=N.functions,this._mergeAgentFunctionModuleMetadata(N.moduleMetadata);let{agents:F,fields:P,functions:L,judgeOptions:D,inputUpdateCallback:j,promptLevel:G,actorModelPolicy:H,...re}=i;this.program=new Me(s,re);let le=this.program.getSignature().getInputFields(),B=_h(u,le,kf);this.contextPromptConfigByField=B.promptConfigByField,this.rlmConfig={contextFields:B.contextFieldNames,sharedFields:i.fields?.shared,runtime:this.runtime,maxSubAgentCalls:l,maxRuntimeChars:p,maxBatchedLlmQueryConcurrency:d,maxTurns:m,contextPolicy:g,actorFields:f,actorTurnCallback:x,mode:A},this.recursionForwardOptions=T;let{description:V,...Q}=C??{},{description:ie,...W}=R??{};this.actorDescription=V,this.actorPromptLevel=h??"detailed",this.actorModelPolicy=Zf(y),this.actorForwardOptions=Q,this.recursiveInstructionSlots=mr(V),this.responderDescription=ie,this.responderForwardOptions=W,this.judgeOptions=M?{...M}:void 0,this.inputUpdateCallback=I;let q=this.agents;for(let ue of q??[]){let xe=ue.getFunction().name;this.program.register(ue,xe)}n&&(this.func={name:Td(n.name),description:n.description,parameters:this._buildFuncParameters(),func:async()=>{throw new Error("Use getFunction() to get a callable wrapper")}});let oe=f??[];this.actorFieldNames=oe;let Ce=i.fields?.shared??[];this.sharedFieldNames=Ce,this.excludedSharedFields=i.fields?.excluded??[];let Re=i.fields?.globallyShared??[];this.globalSharedFieldNames=Re,this.localFieldNames=i.fields?.local??[];let ae=i.agents?.shared??[],ke=i.agents?.globallyShared??[];this.excludedAgents=i.agents?.excluded??[];let ce=S.functions,me=v.functions;this.excludedAgentFunctions=i.functions?.excluded??[];let be=[...this.agentFunctions,...ce,...me];for(let ue of be){if(!ue.parameters)throw new Error(`Agent function "${ue.name}" must define parameters schema for agent runtime usage.`);if(ue.examples){for(let[xe,ve]of ue.examples.entries())if(!ve.code.trim())throw new Error(`Agent function "${ue.name}" example at index ${xe} must define non-empty code`)}}if(this._validateConfiguredSignature(this.program.getSignature()),this._validateAgentFunctionNamespaces(be),Ce.length>0&&q){let ue=le.filter(xe=>Ce.includes(xe.name));for(let xe of q){if(!(xe instanceof o))continue;let ve=new Set(xe.getExcludedSharedFields()),je=ue.filter($e=>!ve.has($e.name));je.length!==0&&xe._extendForSharedFields(je,this.rlmConfig.contextFields)}}if(ae.length>0&&q)for(let ue of q)ue instanceof o&&ue._extendForSharedAgents(ae);if(Re.length>0&&q){let ue=le.filter(xe=>Re.includes(xe.name));for(let xe of q){if(!(xe instanceof o))continue;let ve=new Set(xe.getExcludedSharedFields()),je=ue.filter($e=>!ve.has($e.name));je.length!==0&&xe._extendForGlobalSharedFields(je,this.rlmConfig.contextFields)}}if(ke.length>0&&q)for(let ue of q)ue instanceof o&&ue._extendForGlobalSharedAgents(ke);if(ce.length>0&&q)for(let ue of q)ue instanceof o&&ue._extendForSharedAgentFunctions(S);if(me.length>0&&q)for(let ue of q)ue instanceof o&&ue._extendForGlobalSharedAgentFunctions(v);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)),s=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(),u=a.filter(I=>this.actorFieldNames.includes(I.name)),c=a.filter(I=>!this.actorFieldNames.includes(I.name)),l=ge().addInputFields(i).addInputFields(s).input("contextMetadata",ge.string("Metadata about pre-loaded context variables (type and size)")).input("actionLog",ge.string("Chronological trace of code executions or actions and their outputs so far")).output("javascriptCode",ge.code("JavaScript code to execute in runtime session"));u.length>0&&(l=l.addOutputFields(u));let p=l.build(),d=ge().addInputFields(i).input("contextData",ge.json("Context data to help synthesize the final answer.")).addOutputFields(c).build(),m=this.rlmConfig.maxSubAgentCalls??td,g=this.rlmConfig.maxTurns??nd,f=this.recursionForwardOptions?.maxDepth??oi,x=(this.rlmConfig.mode??"simple")==="advanced"?Math.max(0,f)>0?"advanced-recursive":"simple-at-terminal-depth":"simple",A=this.agents?.map(I=>{let O=I.getFunction();return{name:O.name,description:O.description,parameters:O.parameters}})??[],h=this.agentFunctions.map(I=>({name:I.name,description:I.description,parameters:I.parameters,returns:I.returns,namespace:I.namespace??"utils"})),y=new Set(h.map(I=>I.namespace??"utils"));A.length>0&&y.add(this.agentModuleNamespace);let T=[...y].sort((I,O)=>I.localeCompare(O)).map(I=>({namespace:I,selectionCriteria:this.agentFunctionModuleMetadata.get(I)?.selectionCriteria})),C=id(this.rlmConfig.contextPolicy),R=ei(this._supportsRecursiveActorSlotOptimization()?void 0:this.actorDescription,r,c,{runtimeUsageInstructions:this.runtimeUsageInstructions,promptLevel:this.actorPromptLevel,maxSubAgentCalls:m,maxTurns:g,hasInspectRuntime:C.stateInspection.enabled,hasLiveRuntimeState:C.stateSummary.enabled,hasCompressedActionReplay:C.actionReplay!=="full"||C.checkpoints.enabled||C.errorPruning||!!C.tombstoning||this.functionDiscoveryEnabled&&C.pruneUsedDocs,llmQueryPromptMode:x,enforceIncrementalConsoleTurns:this.enforceIncrementalConsoleTurns,agentModuleNamespace:this.agentModuleNamespace,discoveryMode:this.functionDiscoveryEnabled,availableModules:T,agents:A,agentFunctions:h});this.baseActorDefinition=R;let M=ti(this.responderDescription,r);this.actorProgram?(this.actorProgram.setSignature(p),this.actorProgram.setDescription(R)):this.actorProgram=new Me(p,{...this._genOptions,description:R}),this.responderProgram?(this.responderProgram.setSignature(d),this.responderProgram.setDescription(M)):this.responderProgram=new Me(d,{...this._genOptions,description:M}),this._applyRecursiveActorInstruction()}_extendForSharedFields(e,t){let n=this.program.getSignature(),r=n.getInputFields(),s=!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),s=!0}s&&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(s=>s.getFunction().name)),n=new Set(this.excludedAgents),r=[];for(let s of e){if(s===this)continue;let i=s.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(s)}}if(r.length!==0){this.agents=[...this.agents??[],...r];for(let s of r){let i=s.getFunction().name;this.program.register(s,i)}this._buildSplitPrograms()}}_extendForGlobalSharedFields(e,t){let n=this.program.getSignature(),r=n.getInputFields(),s=!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),s=!0}s&&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 o))continue;let a=new Set(i.getExcludedSharedFields()),u=e.filter(c=>!a.has(c.name));u.length!==0&&i._extendForGlobalSharedFields(u,t)}}_extendForGlobalSharedAgents(e){let t=this.agents?this.agents.filter(n=>n instanceof o):[];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=[],s=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&&!s||(r.length>0&&(this.agentFunctions=[...this.agentFunctions,...r]),this._buildSplitPrograms())}_extendForGlobalSharedAgentFunctions(e){let t=this.agents?this.agents.filter(n=>n instanceof o):[];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()}namedProgramInstances(){return this.program.namedProgramInstances()}getTraces(){return this.program.getTraces()}setDemos(e,t){this.program.setDemos(e,t)}getUsage(){return this.program.getUsage()}resetUsage(){this.program.resetUsage()}getState(){if(this.stateError)throw new Error(this.stateError);return this.state?gr(this.state):void 0}setState(e){if(e&&e.version!==1)throw new Error(`Unsupported AxAgentState version "${String(e.version)}"`);if(e){let t=this.runtime.createSession();try{if(typeof t.patchGlobals!="function")throw new Error("AxCodeSession.patchGlobals() is required to restore AxAgent state")}finally{try{t.close()}catch{}}}this.state=e?gr(e):void 0,this.stateError=void 0}_createRecursiveOptimizationProxy(e,t){return{id:e,signature:t,program:{getId:()=>e,setId:()=>{},getTraces:()=>[],setDemos:()=>{},applyOptimization:n=>{this.applyOptimization(n)},getInstruction:()=>e===de.responder?this.responderProgram.getInstruction():this.recursiveInstructionSlots[e],setInstruction:n=>{this._setRecursiveInstructionSlot(e,n)},getSignature:()=>({getDescription:()=>t})}}}_listOptimizationTargetDescriptors(){return this._supportsRecursiveActorSlotOptimization()?[this._createRecursiveOptimizationProxy(de.shared,"Shared recursive-actor guidance applied to every advanced recursive AxAgent actor invocation."),this._createRecursiveOptimizationProxy(de.root,"Root-only recursive-actor guidance for deciding whether to answer directly or decompose into subtasks."),this._createRecursiveOptimizationProxy(de.recursive,"Mid-tree recursive-actor guidance for branch orchestration, selective delegation, and efficient synthesis."),this._createRecursiveOptimizationProxy(de.terminal,"Terminal-depth recursive-actor guidance for direct answers when deeper recursion is no longer available."),{id:de.responder,signature:this.responderProgram.getSignature().toString(),program:this.responderProgram}]:this.namedProgramInstances().map(e=>({id:e.id,signature:e.signature,program:e.program}))}_beginRecursiveTraceCapture(e){let t=ni(this.getUsage()),n=this._getRecursiveActorRole();if(!this.recursiveEvalContext||!n)return{node:void 0,usageBefore:t};let r=this.recursiveEvalContext.collector.createNode({parentId:this.recursiveEvalContext.parentNodeId,depth:this.recursiveEvalContext.depth,role:n,taskDigest:$t(Array.isArray(e)?e.filter(s=>s.role==="user").map(s=>s.values):e),contextDigest:$t(this.runtimeBootstrapContext)});return this.currentRecursiveTraceNodeId=r.nodeId,{node:r,usageBefore:t}}_finalizeRecursiveTraceCapture(e,t,n,r,s){if(!e){this.currentRecursiveTraceNodeId=void 0;return}let i=ni(this.getUsage());e.localUsage=mo(e.localUsage,Qp(i,t)),e.turnCount=n.length,e.completionType=s.type,e.actorTurns=[...n],e.functionCalls=r.map(a=>({qualifiedName:a.qualifiedName,name:a.name,error:a.error})),e.toolErrors=r.filter(a=>!!a.error).map(a=>`${a.qualifiedName}: ${a.error??"unknown error"}`),this.currentRecursiveTraceNodeId=void 0}_recordEphemeralRecursiveUsage(e){if(!this.recursiveEvalContext||!this.currentRecursiveTraceNodeId||e.totalTokens<=0)return;let t=this.recursiveEvalContext.collector.nodesById.get(this.currentRecursiveTraceNodeId);t&&(t.localUsage=mo(t.localUsage,e))}async optimize(e,t){let n=Hf(e);if(n.train.length===0)throw new Error("AxAgent.optimize(): at least one training task is required.");let r=t?.studentAI??this.ai;if(!r)throw new Error("AxAgent.optimize(): studentAI is required when the agent has no default ai.");let s=t?.judgeAI??this.judgeAI??t?.teacherAI??this.ai??r,i={...this.judgeOptions??{},...t?.judgeOptions??{}},a=this._listOptimizationTargetDescriptors(),u=Yf(a,t?.target??"actor"),c=t?.metric??this._createAgentOptimizeMetric(s,i),l=this._createOptimizationProgram(u,a),p=Math.max(1,Math.floor(t?.maxMetricCalls??Math.max(Df,n.train.length*4))),m=await new Yt({studentAI:r,teacherAI:t?.teacherAI??s,numTrials:t?.numTrials,minibatch:t?.minibatch,minibatchSize:t?.minibatchSize,earlyStoppingTrials:t?.earlyStoppingTrials,minImprovementThreshold:t?.minImprovementThreshold,sampleCount:t?.sampleCount,seed:t?.seed,verbose:t?.verbose,debugOptimizer:t?.debugOptimizer,optimizerLogger:t?.optimizerLogger,onProgress:t?.onProgress,onEarlyStop:t?.onEarlyStop}).compile(l,n.train,c,{validationExamples:n.validation,maxMetricCalls:p,verbose:t?.verbose,feedbackFn:t?.metric?void 0:({prediction:f,example:x,componentId:A})=>Xp({componentId:A,prediction:f,example:x})}),g=m.optimizedProgram;return m.optimizedProgram&&this._supportsRecursiveActorSlotOptimization()&&(g=new Ct({...m.optimizedProgram,artifactFormatVersion:1,instructionSchema:po}),m.optimizedProgram=g),t?.apply!==!1&&g&&this.applyOptimization(g),m}_createOptimizationProgram(e,t){return{getId:()=>this.getId(),setId:n=>this.setId(n),getSignature:()=>qf,forward:async(n,r,s)=>this._forwardForEvaluation(n,r,s),streamingForward:async function*(n,r,s){yield{version:1,index:0,delta:await this.forward(n,r,s)}},getTraces:()=>this.getTraces(),namedProgramInstances:()=>t.filter(n=>e.includes(n.id)),setDemos:(n,r)=>this.setDemos(n,r),applyOptimization:n=>this.applyOptimization(n),getUsage:()=>this.getUsage(),resetUsage:()=>this.resetUsage()}}_createAgentOptimizeMetric(e,t){let n=Kf(t.criteria),r=new Me(zf),s=t.description?.trim();r.setInstruction(s?`${n}
1370
+ `);this.actorProgram.setDescription(n),this.actorProgram.setInstruction(n)}_setRecursiveInstructionSlot(e,t){if(e===ge.responder){this.responderProgram.setInstruction(t??"");return}this.recursiveInstructionSlots[e]=t??"",this._applyRecursiveActorInstruction()}_copyRecursiveOptimizationStateTo(e){e.recursiveInstructionSlots={...this.recursiveInstructionSlots},e.recursiveInstructionRoleOverride=e._supportsRecursiveActorSlotOptimization()?e.recursiveInstructionRoleOverride:void 0,e._applyRecursiveActorInstruction()}constructor({ai:e,judgeAI:t,agentIdentity:n,agentModuleNamespace:r,signature:s},i){let{debug:a,contextFields:u,runtime:c,maxSubAgentCalls:l,maxRuntimeChars:p,maxBatchedLlmQueryConcurrency:d,maxTurns:m,contextPolicy:g,actorFields:f,actorTurnCallback:x,mode:A,promptLevel:h,actorModelPolicy:y,recursionOptions:C,actorOptions:I,responderOptions:R,judgeOptions:M,inputUpdateCallback:T}=i;this.ai=e,this.judgeAI=t,this.agents=i.agents?.local,this.functionDiscoveryEnabled=i.functions?.discovery??!1,this.debug=a,this.options=i,this.runtime=c??new hn,this.runtimeUsageInstructions=this.runtime.getUsageInstructions(),this.enforceIncrementalConsoleTurns=Eh(this.runtimeUsageInstructions);let O=r??n?.namespace??si;if(this.agentModuleNamespace=Nh(O,{normalize:r===void 0}),new Set(["inputs","llmQuery","final","ask_clarification","inspect_runtime",du,mu]).has(this.agentModuleNamespace))throw new Error(`Agent module namespace "${this.agentModuleNamespace}" is reserved`);let $=this._reservedAgentFunctionNamespaces(),N=gu(i.functions?.local,$),S=gu(i.functions?.shared,$),v=gu(i.functions?.globallyShared,$);this.agentFunctions=N.functions,this._mergeAgentFunctionModuleMetadata(N.moduleMetadata);let{agents:P,fields:F,functions:U,judgeOptions:L,inputUpdateCallback:z,promptLevel:j,actorModelPolicy:K,...W}=i;this.program=new Me(s,W);let pe=this.program.getSignature().getInputFields(),G=Sh(u,pe,Mf);this.contextPromptConfigByField=G.promptConfigByField,this.rlmConfig={contextFields:G.contextFieldNames,sharedFields:i.fields?.shared,runtime:this.runtime,maxSubAgentCalls:l,maxRuntimeChars:p,maxBatchedLlmQueryConcurrency:d,maxTurns:m,contextPolicy:g,actorFields:f,actorTurnCallback:x,mode:A},this.recursionForwardOptions=C;let{description:J,...Y}=I??{},{description:le,...H}=R??{};this.actorDescription=J,this.actorPromptLevel=h??"detailed",this.actorModelPolicy=Wf(y),this.actorForwardOptions=Y,this.recursiveInstructionSlots=gr(J),this.responderDescription=le,this.responderForwardOptions=H,this.judgeOptions=M?{...M}:void 0,this.inputUpdateCallback=T;let q=this.agents;for(let te of q??[]){let Ae=te.getFunction().name;this.program.register(te,Ae)}n&&(this.func={name:wd(n.name),description:n.description,parameters:this._buildFuncParameters(),func:async()=>{throw new Error("Use getFunction() to get a callable wrapper")}});let re=f??[];this.actorFieldNames=re;let Ce=i.fields?.shared??[];this.sharedFieldNames=Ce,this.excludedSharedFields=i.fields?.excluded??[];let we=i.fields?.globallyShared??[];this.globalSharedFieldNames=we,this.localFieldNames=i.fields?.local??[];let ue=i.agents?.shared??[],Te=i.agents?.globallyShared??[];this.excludedAgents=i.agents?.excluded??[];let ae=S.functions,de=v.functions;this.excludedAgentFunctions=i.functions?.excluded??[];let X=[...this.agentFunctions,...ae,...de];for(let te of X){if(!te.parameters)throw new Error(`Agent function "${te.name}" must define parameters schema for agent runtime usage.`);if(te.examples){for(let[Ae,Se]of te.examples.entries())if(!Se.code.trim())throw new Error(`Agent function "${te.name}" example at index ${Ae} must define non-empty code`)}}if(this._validateConfiguredSignature(this.program.getSignature()),this._validateAgentFunctionNamespaces(X),Ce.length>0&&q){let te=pe.filter(Ae=>Ce.includes(Ae.name));for(let Ae of q){if(!(Ae instanceof o))continue;let Se=new Set(Ae.getExcludedSharedFields()),Be=te.filter(Le=>!Se.has(Le.name));Be.length!==0&&Ae._extendForSharedFields(Be,this.rlmConfig.contextFields)}}if(ue.length>0&&q)for(let te of q)te instanceof o&&te._extendForSharedAgents(ue);if(we.length>0&&q){let te=pe.filter(Ae=>we.includes(Ae.name));for(let Ae of q){if(!(Ae instanceof o))continue;let Se=new Set(Ae.getExcludedSharedFields()),Be=te.filter(Le=>!Se.has(Le.name));Be.length!==0&&Ae._extendForGlobalSharedFields(Be,this.rlmConfig.contextFields)}}if(Te.length>0&&q)for(let te of q)te instanceof o&&te._extendForGlobalSharedAgents(Te);if(ae.length>0&&q)for(let te of q)te instanceof o&&te._extendForSharedAgentFunctions(S);if(de.length>0&&q)for(let te of q)te instanceof o&&te._extendForGlobalSharedAgentFunctions(v);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(T=>t.includes(T.name)),s=r.filter(T=>this.contextPromptConfigByField.has(T.name)&&!n.has(T.name)).map(T=>({...T,isOptional:!0})),i=e.filter(T=>!t.includes(T.name)&&!n.has(T.name)),a=this.program.getSignature().getOutputFields(),u=a.filter(T=>this.actorFieldNames.includes(T.name)),c=a.filter(T=>!this.actorFieldNames.includes(T.name)),l=fe().addInputFields(i).addInputFields(s).input("contextMetadata",fe.string("Metadata about pre-loaded context variables (type and size)")).input("actionLog",fe.string("Chronological trace of code executions or actions and their outputs so far")).output("javascriptCode",fe.code("JavaScript code to execute in runtime session"));u.length>0&&(l=l.addOutputFields(u));let p=l.build(),d=fe().addInputFields(i).input("contextData",fe.json("Context data to help synthesize the final answer.")).addOutputFields(c).build(),m=this.rlmConfig.maxSubAgentCalls??nd,g=this.rlmConfig.maxTurns??rd,f=this.recursionForwardOptions?.maxDepth??oi,x=(this.rlmConfig.mode??"simple")==="advanced"?Math.max(0,f)>0?"advanced-recursive":"simple-at-terminal-depth":"simple",A=this.agents?.map(T=>{let O=T.getFunction();return{name:O.name,description:O.description,parameters:O.parameters}})??[],h=this.agentFunctions.map(T=>({name:T.name,description:T.description,parameters:T.parameters,returns:T.returns,namespace:T.namespace??"utils"})),y=new Set(h.map(T=>T.namespace??"utils"));A.length>0&&y.add(this.agentModuleNamespace);let C=[...y].sort((T,O)=>T.localeCompare(O)).map(T=>({namespace:T,selectionCriteria:this.agentFunctionModuleMetadata.get(T)?.selectionCriteria})),I=ud(this.rlmConfig.contextPolicy),R=ei(this._supportsRecursiveActorSlotOptimization()?void 0:this.actorDescription,r,c,{runtimeUsageInstructions:this.runtimeUsageInstructions,promptLevel:this.actorPromptLevel,maxSubAgentCalls:m,maxTurns:g,hasInspectRuntime:I.stateInspection.enabled,hasLiveRuntimeState:I.stateSummary.enabled,hasCompressedActionReplay:I.actionReplay!=="full"||I.checkpoints.enabled||I.errorPruning||!!I.tombstoning||this.functionDiscoveryEnabled&&I.pruneUsedDocs,llmQueryPromptMode:x,enforceIncrementalConsoleTurns:this.enforceIncrementalConsoleTurns,agentModuleNamespace:this.agentModuleNamespace,discoveryMode:this.functionDiscoveryEnabled,availableModules:C,agents:A,agentFunctions:h});this.baseActorDefinition=R;let M=ti(this.responderDescription,r);this.actorProgram?(this.actorProgram.setSignature(p),this.actorProgram.setDescription(R)):this.actorProgram=new Me(p,{...this._genOptions,description:R}),this.responderProgram?(this.responderProgram.setSignature(d),this.responderProgram.setDescription(M)):this.responderProgram=new Me(d,{...this._genOptions,description:M}),this._applyRecursiveActorInstruction()}_extendForSharedFields(e,t){let n=this.program.getSignature(),r=n.getInputFields(),s=!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),s=!0}s&&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(s=>s.getFunction().name)),n=new Set(this.excludedAgents),r=[];for(let s of e){if(s===this)continue;let i=s.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(s)}}if(r.length!==0){this.agents=[...this.agents??[],...r];for(let s of r){let i=s.getFunction().name;this.program.register(s,i)}this._buildSplitPrograms()}}_extendForGlobalSharedFields(e,t){let n=this.program.getSignature(),r=n.getInputFields(),s=!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),s=!0}s&&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 o))continue;let a=new Set(i.getExcludedSharedFields()),u=e.filter(c=>!a.has(c.name));u.length!==0&&i._extendForGlobalSharedFields(u,t)}}_extendForGlobalSharedAgents(e){let t=this.agents?this.agents.filter(n=>n instanceof o):[];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=[],s=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&&!s||(r.length>0&&(this.agentFunctions=[...this.agentFunctions,...r]),this._buildSplitPrograms())}_extendForGlobalSharedAgentFunctions(e){let t=this.agents?this.agents.filter(n=>n instanceof o):[];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()}namedProgramInstances(){return this.program.namedProgramInstances()}getTraces(){return this.program.getTraces()}setDemos(e,t){this.program.setDemos(e,t)}getUsage(){return this.program.getUsage()}resetUsage(){this.program.resetUsage()}getState(){if(this.stateError)throw new Error(this.stateError);return this.state?fr(this.state):void 0}setState(e){if(e&&e.version!==1)throw new Error(`Unsupported AxAgentState version "${String(e.version)}"`);if(e){let t=this.runtime.createSession();try{if(typeof t.patchGlobals!="function")throw new Error("AxCodeSession.patchGlobals() is required to restore AxAgent state")}finally{try{t.close()}catch{}}}this.state=e?fr(e):void 0,this.stateError=void 0}_createRecursiveOptimizationProxy(e,t){return{id:e,signature:t,program:{getId:()=>e,setId:()=>{},getTraces:()=>[],setDemos:()=>{},applyOptimization:n=>{this.applyOptimization(n)},getInstruction:()=>e===ge.responder?this.responderProgram.getInstruction():this.recursiveInstructionSlots[e],setInstruction:n=>{this._setRecursiveInstructionSlot(e,n)},getSignature:()=>({getDescription:()=>t})}}}_listOptimizationTargetDescriptors(){return this._supportsRecursiveActorSlotOptimization()?[this._createRecursiveOptimizationProxy(ge.shared,"Shared recursive-actor guidance applied to every advanced recursive AxAgent actor invocation."),this._createRecursiveOptimizationProxy(ge.root,"Root-only recursive-actor guidance for deciding whether to answer directly or decompose into subtasks."),this._createRecursiveOptimizationProxy(ge.recursive,"Mid-tree recursive-actor guidance for branch orchestration, selective delegation, and efficient synthesis."),this._createRecursiveOptimizationProxy(ge.terminal,"Terminal-depth recursive-actor guidance for direct answers when deeper recursion is no longer available."),{id:ge.responder,signature:this.responderProgram.getSignature().toString(),program:this.responderProgram}]:this.namedProgramInstances().map(e=>({id:e.id,signature:e.signature,program:e.program}))}_beginRecursiveTraceCapture(e){let t=ni(this.getUsage()),n=this._getRecursiveActorRole();if(!this.recursiveEvalContext||!n)return{node:void 0,usageBefore:t};let r=this.recursiveEvalContext.collector.createNode({parentId:this.recursiveEvalContext.parentNodeId,depth:this.recursiveEvalContext.depth,role:n,taskDigest:$t(Array.isArray(e)?e.filter(s=>s.role==="user").map(s=>s.values):e),contextDigest:$t(this.runtimeBootstrapContext)});return this.currentRecursiveTraceNodeId=r.nodeId,{node:r,usageBefore:t}}_finalizeRecursiveTraceCapture(e,t,n,r,s){if(!e){this.currentRecursiveTraceNodeId=void 0;return}let i=ni(this.getUsage());e.localUsage=po(e.localUsage,Yp(i,t)),e.turnCount=n.length,e.completionType=s.type,e.actorTurns=[...n],e.functionCalls=r.map(a=>({qualifiedName:a.qualifiedName,name:a.name,error:a.error})),e.toolErrors=r.filter(a=>!!a.error).map(a=>`${a.qualifiedName}: ${a.error??"unknown error"}`),this.currentRecursiveTraceNodeId=void 0}_recordEphemeralRecursiveUsage(e){if(!this.recursiveEvalContext||!this.currentRecursiveTraceNodeId||e.totalTokens<=0)return;let t=this.recursiveEvalContext.collector.nodesById.get(this.currentRecursiveTraceNodeId);t&&(t.localUsage=po(t.localUsage,e))}async optimize(e,t){let n=Uf(e);if(n.train.length===0)throw new Error("AxAgent.optimize(): at least one training task is required.");let r=t?.studentAI??this.ai;if(!r)throw new Error("AxAgent.optimize(): studentAI is required when the agent has no default ai.");let s=t?.judgeAI??this.judgeAI??t?.teacherAI??this.ai??r,i={...this.judgeOptions??{},...t?.judgeOptions??{}},a=this._listOptimizationTargetDescriptors(),u=Hf(a,t?.target??"actor"),c=t?.metric??this._createAgentOptimizeMetric(s,i),l=this._createOptimizationProgram(u,a),p=Math.max(1,Math.floor(t?.maxMetricCalls??Math.max(Ff,n.train.length*4))),m=await new Xt({studentAI:r,teacherAI:t?.teacherAI??s,numTrials:t?.numTrials,minibatch:t?.minibatch,minibatchSize:t?.minibatchSize,earlyStoppingTrials:t?.earlyStoppingTrials,minImprovementThreshold:t?.minImprovementThreshold,sampleCount:t?.sampleCount,seed:t?.seed,verbose:t?.verbose,debugOptimizer:t?.debugOptimizer,optimizerLogger:t?.optimizerLogger,onProgress:t?.onProgress,onEarlyStop:t?.onEarlyStop}).compile(l,n.train,c,{validationExamples:n.validation,maxMetricCalls:p,verbose:t?.verbose,feedbackFn:t?.metric?void 0:({prediction:f,example:x,componentId:A})=>Zp({componentId:A,prediction:f,example:x})}),g=m.optimizedProgram;return m.optimizedProgram&&this._supportsRecursiveActorSlotOptimization()&&(g=new It({...m.optimizedProgram,artifactFormatVersion:1,instructionSchema:lo}),m.optimizedProgram=g),t?.apply!==!1&&g&&this.applyOptimization(g),m}_createOptimizationProgram(e,t){return{getId:()=>this.getId(),setId:n=>this.setId(n),getSignature:()=>Df,forward:async(n,r,s)=>this._forwardForEvaluation(n,r,s),streamingForward:async function*(n,r,s){yield{version:1,index:0,delta:await this.forward(n,r,s)}},getTraces:()=>this.getTraces(),namedProgramInstances:()=>t.filter(n=>e.includes(n.id)),setDemos:(n,r)=>this.setDemos(n,r),applyOptimization:n=>this.applyOptimization(n),getUsage:()=>this.getUsage(),resetUsage:()=>this.resetUsage()}}_createAgentOptimizeMetric(e,t){let n=jf(t.criteria),r=new Me(Lf),s=t.description?.trim();r.setInstruction(s?`${n}
1371
1371
 
1372
1372
  Additional Judge Guidance:
1373
- ${s}`:n);let i=Vf(t);return async({example:a,prediction:u})=>{let c=a,l=u,p={taskInput:lt(c.input),criteria:c.criteria,expectedOutput:c.expectedOutput,expectedActions:c.expectedActions,forbiddenActions:c.forbiddenActions,metadata:c.metadata},d={completionType:l.completionType,clarification:lt(l.clarification),finalOutput:lt(l.output),actionLog:l.actionLog,functionCalls:lt(l.functionCalls),toolErrors:l.toolErrors,turnCount:l.turnCount,usage:lt(l.usage??[]),recursiveTrace:lt(l.recursiveTrace),recursiveStats:lt(l.recursiveStats)},m=await r.forward(e,{...p,...d},i);return Qf(Jf(m.quality),c,l)}}async _forwardForEvaluation(e,t,n){let r=this.state?gr(this.state):void 0,s=this.stateError;this.state=void 0,this.stateError=void 0;let i=new AbortController;this._stopRequested&&i.abort("Stopped by user (pre-forward)");let a=kt(i.signal,n?.abortSignal);this.activeAbortControllers.add(i);let u=this._ensureLlmQueryBudgetState(),c=this.recursiveEvalContext,l=this.currentRecursiveTraceNodeId,p=this._supportsRecursiveActorSlotOptimization()?ih():void 0;this.recursiveEvalContext=p?{collector:p,depth:0}:void 0,this.currentRecursiveTraceNodeId=void 0;try{let d=this.ai??e,m=n?.debug??this.debug??d?.getOptions()?.debug??!1,g=[],f=[],{node:x,usageBefore:A}=this._beginRecursiveTraceCapture(t.input),{nonContextValues:h,actorResult:y,actorFieldValues:T,actionLog:C,turnCount:R}=await this._runActorLoop(d,t.input,n,a,g,f),M=g.filter(S=>!!S.error).map(S=>`${S.qualifiedName}: ${S.error??"unknown error"}`);if(y.type==="ask_clarification"){this._finalizeRecursiveTraceCapture(x,A,f,g,y);let S=p?.rootNode?ri(du(p.rootNode)):void 0,v=S?iu(S):void 0,F=S&&v?au(S,v):void 0;return{completionType:"ask_clarification",clarification:xd(y.args[0]),actionLog:C,functionCalls:g,toolErrors:M,turnCount:R,recursiveTrace:S,recursiveStats:v,recursiveSummary:F}}let I={...this._genOptions,...this.responderForwardOptions,...n,debug:m,abortSignal:a,maxSteps:1},O=await this.responderProgram.forward(d,{...h,contextData:y},I);this._finalizeRecursiveTraceCapture(x,A,f,g,y);let E=p?.rootNode?ri(du(p.rootNode)):void 0,$=E?iu(E):void 0,N=E&&$?au(E,$):void 0;return{completionType:"final",output:{...O,...T},actionLog:C,functionCalls:g,toolErrors:M,turnCount:R,recursiveTrace:E,recursiveStats:$,recursiveSummary:N}}finally{this.state=r?gr(r):void 0,this.stateError=s,this.recursiveEvalContext=c,this.currentRecursiveTraceNodeId=l,u&&(this.llmQueryBudgetState=void 0),this.activeAbortControllers.delete(i),this._stopRequested=!1}}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,s)=>{let i=this.ai??s?.ai;if(!i)throw new Error("AI service is required to run the agent");let a=await e(i,r,s),c=this.program.getSignature().getOutputFields();return Object.keys(a).map(p=>{let d=c.find(m=>m.name===p);return d?`${d.title}: ${a[p]}`:`${p}: ${a[p]}`}).join(`
1374
- `)}}}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(x=>x.role==="user").reduce((x,A)=>({...x,...A.values}),{}):n=e;let r=t?.allowedFieldNames?new Set(t.allowedFieldNames):void 0;if(r&&t?.validateInputKeys){for(let x of Object.keys(n))if(!r.has(x))throw new Error(`AxAgent.test() only accepts context field values. "${x}" is not configured in contextFields.`)}let s={...n},i=r?new Set(r):new Set(this.program.getSignature().getInputFields().map(x=>x.name)),a=[...this.sharedFieldNames,...this.globalSharedFieldNames],u=this._getBypassedSharedFieldNames(),c={},l={},p={},d={},m="(none)",g=new Set(this.program.getSignature().getInputFields().filter(x=>this.rlmConfig.contextFields.includes(x.name)&&x.isOptional).map(x=>x.name));return{currentInputs:s,signatureInputFieldNames:i,sharedFieldValues:c,recomputeTurnInputs:x=>{let A={},h={};for(let[T,C]of Object.entries(s))this.rlmConfig.contextFields.includes(T)?A[T]=C:u.has(T)||(h[T]=C);if(x){for(let T of this.rlmConfig.contextFields)if(!g.has(T)&&(!(T in A)||A[T]===void 0))throw new Error(`RLM contextField "${T}" is missing from input values`)}let y={};for(let[T,C]of this.contextPromptConfigByField){if(u.has(T)||!(T in A))continue;let R=Mh(A[T],C);R!==void 0&&(y[T]=R)}l=A,p=h,d=y;for(let T of Object.keys(c))delete c[T];for(let T of a)T in s&&(c[T]=s[T]),T in l&&(c[T]=l[T]);m=Nh(l,{promptConfigByField:this.contextPromptConfigByField,inlinedFields:new Set(Object.keys(d))})||"(none)"},getNonContextValues:()=>p,getActorInlineContextValues:()=>d,getContextMetadata:()=>m}}_ensureLlmQueryBudgetState(){return this.llmQueryBudgetState?!1:(this.llmQueryBudgetState={used:0},!0)}_createRuntimeExecutionContext({ai:e,inputState:t,options:n,effectiveAbortSignal:r,debug:s,completionState:i,completionBindings:a,actionLogEntries:u,functionCallRecorder:c}){let l=this.rlmConfig,p=this.runtime,d=l.maxSubAgentCalls??td,m=l.maxRuntimeChars??uu,g=Math.max(1,l.maxBatchedLlmQueryConcurrency??Sf),f=this.recursionForwardOptions?.maxDepth??oi,x=Math.max(0,f),A=id(l.contextPolicy),h=this.llmQueryBudgetState??{used:0},y=new Set,T=Math.floor(d*.8),{maxDepth:C,...R}=this.recursionForwardOptions??{},{description:M,mem:I,sessionId:O,...E}=n??{},$={...this.recursionForwardOptions??{},maxDepth:Math.max(0,x-1)},N=ge().input("task",ge.string("Task for recursive analysis")).output("answer",ge.string("Answer from recursive analysis")).build(),S=ge().input("task",ge.string("Task for recursive analysis")).input("context",ge.json("Optional context for the recursive task")).output("answer",ge.string("Answer from recursive analysis")).build(),F=(l.mode??"simple")==="advanced"&&x>0,P=this.recursionForwardOptions?.promptLevel??this.actorPromptLevel,L=()=>(()=>{let U=new o({agentModuleNamespace:this.agentModuleNamespace,signature:N},{debug:s,...l,agents:{local:this.agents},functions:{local:this.agentFunctions,discovery:this.functionDiscoveryEnabled},contextFields:[],actorFields:void 0,promptLevel:P,actorModelPolicy:this.options?.actorModelPolicy,recursionOptions:$,actorOptions:{...this.actorForwardOptions},responderOptions:this.responderForwardOptions});return U.recursiveInstructionRoleOverride=$.maxDepth&&$.maxDepth>0?"recursive":"terminal",this._copyRecursiveOptimizationStateTo(U),U})(),D=U=>(U.llmQueryBudgetState=h,this.recursiveEvalContext&&(U.recursiveEvalContext={collector:this.recursiveEvalContext.collector,parentNodeId:this.currentRecursiveTraceNodeId,depth:this.recursiveEvalContext.depth+1}),U),j=()=>{for(let U of[...y])U.stop()},G=()=>new Me(S,$),H=async(U,K)=>{if(!Array.isArray(U)&&typeof U=="object"&&U!==null&&"query"in U)return H(U.query,U.context??K);if(r?.aborted)throw new Fe("rlm-llm-query",r.reason?String(r.reason):"Aborted");if(!e)throw new Error(jf);let ne=U,te=Te=>{if(Te==null)return"";if(typeof Te=="string")return dt(Te,m);try{return dt(JSON.stringify(Te),m)}catch{return dt(String(Te),m)}},Ie=async(Te,qe,_e=r)=>{if(_e?.aborted)throw new Fe("rlm-llm-query",_e.reason?String(_e.reason):"Aborted");let nt=qe===void 0?void 0:typeof qe=="string"?dt(qe,m):qe;if(h.used>=d)return`[ERROR] Sub-query budget exhausted (${d}/${d}). Complete the task using data already gathered or handle remaining work directly in JS.`;h.used++;let ee=3,X,Ae=Oe=>`[ERROR] ${Oe instanceof Error?Oe.message:String(Oe)}. Retry with a simpler query, handle in JS, or proceed with data already gathered.`;for(let Oe=0;Oe<ee;Oe++)try{if(!F){let Ve=G(),Zt=await Ve.forward(e,{task:Te,...nt!==void 0?{context:nt}:{}},{...E,...R,abortSignal:_e,debug:s});return this._recordEphemeralRecursiveUsage(ni(Ve.getUsage())),te(Zt.answer)}let Pe=await(()=>{let Ve=D(L());return y.add(Ve),Ve.runtimeBootstrapContext=nt,Ve.forward(e,{task:Te},{...E,...R,abortSignal:_e,debug:s}).finally(()=>{y.delete(Ve)})})();return te(Pe.answer)}catch(Pe){if(Pe instanceof Fe||Pe instanceof pt)throw Pe;if(X=Pe,!Ih(Pe)||Oe>=ee-1)return Ae(Pe);let Ve=Math.min(6e4,1e3*Math.pow(2,Oe));await new Promise((Zt,ci)=>{let en=!1,tn,Ao=()=>{_e&&tn&&_e.removeEventListener("abort",tn)},we=setTimeout(()=>{en||(en=!0,Ao(),Zt())},Ve);if(_e){if(tn=()=>{en||(en=!0,clearTimeout(we),Ao(),ci(new Fe("rlm-llm-query-retry-backoff",_e.reason?String(_e.reason):"Aborted during retry backoff")))},_e.aborted){tn();return}_e.addEventListener("abort",tn,{once:!0})}})}return Ae(X)};if(Array.isArray(U)){let Te=new AbortController,qe=kt(r,Te.signal)??Te.signal,_e,nt=()=>{j()};qe.addEventListener("abort",nt,{once:!0});try{return await Lh(U,g,async ee=>{try{return await Ie(ee.query,ee.context,qe)}catch(X){if(X instanceof Fe||X instanceof pt)throw(X instanceof pt||!_e)&&(_e=X),Te.signal.aborted||Te.abort(X instanceof pt?"Child clarification":X.message),_e;return`[ERROR] ${X instanceof Error?X.message:String(X)}`}},qe)}finally{qe.removeEventListener("abort",nt)}}let Ue=await Ie(ne,K);return h.used===T?`${Ue}
1375
- [WARNING] ${h.used}/${d} sub-queries used (${d-h.used} remaining). Consolidate remaining work.`:Ue},re=this.buildRuntimeGlobals(r,t.sharedFieldValues,e,a.protocol,c),le=[...new Set(this.agentFunctions.map(U=>U.namespace??"utils"))],B={...t.currentInputs},V=new Set(["inputs","llmQuery",si,this.agentModuleNamespace,"final","ask_clarification",...le,...A.stateInspection.enabled?["inspect_runtime"]:[],...Object.keys(re)]),Q=[...new Set([...Object.keys(B),...t.signatureInputFieldNames])].filter(U=>!V.has(U)),ie={};for(let U of Q)ie[U]=B[U];let W=()=>{for(let U of Object.keys(B))delete B[U];for(let[U,K]of Object.entries(t.currentInputs))B[U]=K;for(let U of Q)ie[U]=t.currentInputs[U]},q=[...V],oe=[...V,...Q],Ce=new Set(oe),Re=this.runtimeBootstrapContext;this.runtimeBootstrapContext=void 0;let ae=lh(Re,Ce),ke=new Set(Object.keys(ae)),ce=u??[],me,be,ue=U=>typeof U.inspectGlobals=="function"?U:void 0,xe=async()=>{try{let U=await me.execute(Kp(),{signal:r,reservedNames:oe});if(typeof U!="string")return[];let K=JSON.parse(U);return Array.isArray(K)?K.filter(ne=>typeof ne=="string"&&!ke.has(ne)):[]}catch{return[]}},ve=async()=>(be||(be=await xe()),be),je=async()=>{try{let U=ue(me);if(U?.inspectGlobals)return await U.inspectGlobals({signal:r,reservedNames:oe});let K=await ve(),ne=Wp(oe,K),te=await me.execute(ne,{signal:r,reservedNames:oe});return typeof te=="string"?te:String(te)}catch(U){return`[inspect_runtime error: ${U instanceof Error?U.message:String(U)}]`}},$e=(U,K)=>{let ne=Rh(U);if(!ne)return vh(U,K);let te=Xs(ce);return mu(ne,te,K)},at=A.stateInspection.enabled?async()=>$e(await je()):void 0,Ee=()=>(be=void 0,p.createSession({...ie,inputs:B,...ae,llmQuery:H,final:a.finalFunction,ask_clarification:a.askClarificationFunction,...at?{inspect_runtime:at}:{},...re}));me=Ee();let ze=()=>({maxEntries:A.stateSummary.maxEntries&&A.stateSummary.maxEntries>0?A.stateSummary.maxEntries:8,maxChars:A.stateSummary.maxChars&&A.stateSummary.maxChars>0?A.stateSummary.maxChars:void 0}),pe=()=>({maxEntries:A.stateSummary.maxEntries&&A.stateSummary.maxEntries>0?A.stateSummary.maxEntries:6,maxChars:A.stateSummary.maxChars&&A.stateSummary.maxChars>0?A.stateSummary.maxChars:Math.min(m,1200)}),De=Object.keys(ae).length>0?hh(ae,{...pe(),budgetRemaining:Math.max(0,d-h.used),budgetTotal:d}):void 0,Ke=async()=>{if(!i.payload)for(let U=0;U<3&&!i.payload;U++)await new Promise(K=>{setTimeout(K,0)})},Ye=async()=>{if(!A.stateSummary.enabled)return;let U=await je();return $e(U,ze())||"(no user variables)"},ut=U=>{if(typeof U.patchGlobals!="function")throw new Error("AxCodeSession.patchGlobals() is required when restoring AxAgent state or using inputUpdateCallback");return U},b=U=>{if(typeof U.snapshotGlobals!="function")throw new Error("AxCodeSession.snapshotGlobals() is required to export AxAgent state");return U},k=U=>{let K=new Set(oe),ne={};for(let[Ie,Ue]of Object.entries(U.runtimeBindings??{}))K.has(Ie)||(ne[Ie]=Ue);let te=(U.runtimeEntries??[]).filter(Ie=>!K.has(Ie.name));return{runtimeBindings:ne,runtimeEntries:te,actionLogEntries:Ah(U.actionLogEntries),checkpointState:U.checkpointState,provenance:{...U.provenance??{}},actorModelState:U.actorModelState?{escalated:U.actorModelState.escalated,escalatedTurns:U.actorModelState.escalatedTurns,stableBelowThresholdTurns:U.actorModelState.stableBelowThresholdTurns}:void 0}};return{effectiveContextConfig:A,bootstrapContextSummary:De,applyBootstrapRuntimeContext:async()=>{if(Object.keys(ae).length===0||!A.stateSummary.enabled)return;let U=await je();return $e(U,ze())||"(no user variables)"},captureRuntimeStateSummary:Ye,exportRuntimeState:async()=>{let K=await b(me).snapshotGlobals({signal:r,reservedNames:oe}),ne=Xs(ce);return{version:1,runtimeBindings:K.bindings,runtimeEntries:K.entries,actionLogEntries:xh(ce),provenance:yh(ne)}},restoreRuntimeState:async U=>{let K=k(U);return await ut(me).patchGlobals(K.runtimeBindings,{signal:r}),K},syncRuntimeInputsToSession:async()=>{W();let U=async K=>{await ut(K).patchGlobals({inputs:{...B},...ie},{signal:r})};try{await U(me)}catch(K){if(r?.aborted)throw new Fe("rlm-session",r.reason??"Aborted");if(K instanceof Error&&(K.name==="AbortError"||K.message.startsWith("Aborted")))throw K;if(dd(K)){me=Ee(),await U(me);return}throw new Error(`Failed to sync runtime inputs: ${ai(K,m)}`)}},executeActorCode:async U=>{let K={result:void 0,output:ii(void 0,m),isError:!1};try{let ne=await me.execute(U,{signal:r,reservedNames:q});return i.payload||ld(U)&&pd(ne)&&(await Ke(),i.payload)?K:{result:ne,output:ii(ne,m),isError:!1}}catch(ne){if(ne instanceof fr||i.payload)return K;if(ne instanceof pt||ne instanceof Fe)throw ne;if(r?.aborted)throw new Fe("rlm-session",r.reason??"Aborted");if(ne instanceof Error&&(ne.name==="AbortError"||ne.message.startsWith("Aborted")))throw ne;if(Oh(ne))return{result:void 0,output:dt(`${ui}
1376
- ${ai(ne,m)}`,m),isError:!0};if(dd(ne))try{me=Ee(),i.payload=void 0;let te=await me.execute(U,{signal:r,reservedNames:q});return{result:te,output:dt(`${ui}
1377
- ${ii(te,m)}`,m),isError:!1}}catch(te){if(te instanceof pt||te instanceof Fe)throw te;return{result:void 0,output:dt(`${ui}
1378
- ${ai(te,m)}`,m),isError:!0}}return{result:void 0,output:dt(ai(ne,m),m),isError:!0}}},executeTestCode:async U=>{try{let K=await me.execute(U,{signal:r,reservedNames:q});if(ld(U)&&pd(K)&&await Ke(),i.payload)return i.payload;let ne=ii(K,m);if(Eh(ne))throw new Error(ne);return ne}catch(K){if((K instanceof fr||i.payload)&&i.payload)return i.payload;throw K}},close:()=>{me.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,s=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},u=od((p,d)=>{a.payload=ad(p,d)}),c=this._ensureLlmQueryBudgetState(),l=this._createRuntimeExecutionContext({ai:r,inputState:i,options:void 0,effectiveAbortSignal:n?.abortSignal,debug:s,completionState:a,completionBindings:u,actionLogEntries:[]});try{return await l.executeTestCode(e)}finally{this.currentRecursiveTraceNodeId=void 0,c&&(this.llmQueryBudgetState=void 0),l.close()}}setSignature(e){let t=new Ne(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){let t=e?.instructionSchema,n=e?.artifactFormatVersion;if(t&&t!==po)throw new Error(`AxAgent.applyOptimization(): unsupported instruction schema "${t}".`);if(t===po&&n!==void 0&&n!==1)throw new Error(`AxAgent.applyOptimization(): unsupported recursive artifact format version "${String(n)}".`);let r=e?.instructionMap??{},s=[de.shared,de.root,de.recursive,de.terminal].some(i=>typeof r[i]=="string");if(t===po){if(!this._supportsRecursiveActorSlotOptimization())throw new Error('AxAgent.applyOptimization(): recursive-slot artifacts require mode "advanced" with recursion enabled.');(e?.demos||e?.modelConfig)&&this.program.setDemos(e.demos??[],{modelConfig:e.modelConfig}),this.recursiveInstructionSlots=mr(this.actorDescription);for(let a of[de.shared,de.root,de.recursive,de.terminal])typeof r[a]=="string"&&(this.recursiveInstructionSlots[a]=r[a]??"");this._applyRecursiveActorInstruction();let i=r[de.responder];typeof i=="string"&&this.responderProgram.setInstruction(i);return}if(this._supportsRecursiveActorSlotOptimization()&&!s){(e?.demos||e?.modelConfig)&&this.program.setDemos(e.demos??[],{modelConfig:e.modelConfig}),this.recursiveInstructionSlots=mr(this.actorDescription);let i=r["root.actor"]??e?.instruction;typeof i=="string"&&(this.recursiveInstructionSlots[de.shared]=i),this._applyRecursiveActorInstruction();let a=r["root.responder"];typeof a=="string"?this.responderProgram.setInstruction(a):typeof e?.instruction=="string"&&this.responderProgram.setInstruction(e.instruction);return}if(s){if(!this._supportsRecursiveActorSlotOptimization())throw new Error('AxAgent.applyOptimization(): recursive-slot instruction maps require mode "advanced" with recursion enabled.');this.recursiveInstructionSlots=mr(this.actorDescription);for(let a of[de.shared,de.root,de.recursive,de.terminal])typeof r[a]=="string"&&(this.recursiveInstructionSlots[a]=r[a]??"");this._applyRecursiveActorInstruction();let i=r[de.responder];typeof i=="string"&&this.responderProgram.setInstruction(i),(e?.demos||e?.modelConfig)&&this.program.setDemos(e.demos??[],{modelConfig:e.modelConfig});return}this.program.applyOptimization?.(e)}async _runActorLoop(e,t,n,r,s,i){let a=this.rlmConfig,u=n?.debug??this.debug??e?.getOptions()?.debug??!1,c=a.maxTurns??nd,l=this._createRuntimeInputState(t);l.recomputeTurnInputs(!1);let p={payload:void 0},d=od((P,L)=>{p.payload=ad(P,L)}),m=[],g,f=this._createRuntimeExecutionContext({ai:e,inputState:l,options:n,effectiveAbortSignal:r,debug:u,completionState:p,completionBindings:d,actionLogEntries:m,functionCallRecorder:s?P=>{s.push(P)}:void 0}),x=f.effectiveContextConfig.stateSummary.enabled?void 0:f.bootstrapContextSummary,A=async()=>{if(!this.inputUpdateCallback)return;let P=await this.inputUpdateCallback({...l.currentInputs});if(P!==void 0){if(!P||typeof P!="object"||Array.isArray(P))throw new Error("inputUpdateCallback must return an object patch or undefined");for(let[L,D]of Object.entries(P))l.signatureInputFieldNames.has(L)&&(l.currentInputs[L]=D)}},h={...this._genOptions,...this.actorForwardOptions,...n,debug:u,abortSignal:r},y={},T=f.effectiveContextConfig.stateInspection.enabled?f.effectiveContextConfig.stateInspection.contextThreshold:void 0,C=Xf(n,u,r),R=this.functionDiscoveryEnabled&&f.effectiveContextConfig.pruneUsedDocs,M,I,O,E=f.effectiveContextConfig.actionReplay==="checkpointed"?"minimal":f.effectiveContextConfig.actionReplay,$=f.effectiveContextConfig.actionReplay==="checkpointed"?"full":f.effectiveContextConfig.actionReplay,N=()=>Zs(m,{pruneUsedDocs:R}),S=()=>qp(N(),{actionReplay:f.effectiveContextConfig.actionReplay,recentFullActions:f.effectiveContextConfig.recentFullActions,restoreNotice:O,delegatedContextSummary:x,stateSummary:g,checkpointSummary:M?.summary,checkpointTurns:M?.turns})||"(no actions yet)",v=async()=>{if(!f.effectiveContextConfig.checkpoints.enabled){M=void 0;return}let P=lo(m,{actionReplay:$,recentFullActions:f.effectiveContextConfig.recentFullActions,pruneUsedDocs:R}),L=f.effectiveContextConfig.checkpoints.triggerChars;if(!L||P.historyChars<=L){M=void 0;return}let j=lo(m,{actionReplay:E,recentFullActions:f.effectiveContextConfig.recentFullActions,pruneUsedDocs:R}).checkpointEntries;if(j.length===0){M=void 0;return}let G=JSON.stringify(j.map(H=>({turn:H.turn,code:H.code,output:H.output,actorFieldsOutput:H.actorFieldsOutput,tags:H.tags,tombstone:H.tombstone})));M?.fingerprint!==G&&(M={fingerprint:G,turns:j.map(H=>H.turn),summary:await zp(e,f.effectiveContextConfig.summarizerOptions,C,j)})};try{if(this.state){let L=await f.restoreRuntimeState(this.state),D=f.effectiveContextConfig.stateSummary.enabled;m.push(...L.actionLogEntries),M=L.checkpointState?{fingerprint:L.checkpointState.fingerprint,turns:[...L.checkpointState.turns],summary:L.checkpointState.summary}:void 0,I=L.actorModelState?{escalated:L.actorModelState.escalated,escalatedTurns:L.actorModelState.escalatedTurns,stableBelowThresholdTurns:L.actorModelState.stableBelowThresholdTurns}:void 0;let j=Ch(Xs(m),Th(L.provenance));g=D?mu(L.runtimeEntries,j,{maxEntries:f.effectiveContextConfig.stateSummary.maxEntries&&f.effectiveContextConfig.stateSummary.maxEntries>0?f.effectiveContextConfig.stateSummary.maxEntries:8,maxChars:f.effectiveContextConfig.stateSummary.maxChars&&f.effectiveContextConfig.stateSummary.maxChars>0?f.effectiveContextConfig.stateSummary.maxChars:1200})||"(no user variables)":void 0,O=bh(L.runtimeEntries,{includeLiveRuntimeState:D})}let P=await f.applyBootstrapRuntimeContext();P!==void 0&&(g=P);for(let L=0;L<c;L++){await A(),l.recomputeTurnInputs(!0),await v();let D=S(),j=lo(m,{actionReplay:f.effectiveContextConfig.actionReplay,recentFullActions:f.effectiveContextConfig.recentFullActions,pruneUsedDocs:R,checkpointTurns:M?.turns});T&&j.historyChars>T&&(D+="\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 G=h;if(this.actorModelPolicy){let oe=(this.actorProgram.getSignature().getDescription()?.length??0)+l.getContextMetadata().length+D.length,Ce=oh(this.actorModelPolicy,m,oe,!!M?.summary);I=sh(I,this.actorModelPolicy,Ce);let Re=I.escalated?this.actorModelPolicy.escalatedModel:this.actorModelPolicy.baseModel??h.model;G=Re!==void 0?{...h,model:Re}:{...h}}let H=await this.actorProgram.forward(e,{...l.getNonContextValues(),...l.getActorInlineContextValues(),contextMetadata:l.getContextMetadata(),actionLog:D},G);L===0&&(h.debugHideSystemPrompt=!0,O=void 0);let re=H.javascriptCode,le=re?.trim();if(!re||!le)break;re=Wf(le),H.javascriptCode=re;for(let q of this.actorFieldNames)q in H&&(y[q]=H[q]);let B="";if(this.actorFieldNames.length>0){let q=this.actorFieldNames.filter(oe=>oe in H).map(oe=>`${oe}: ${H[oe]}`).join(`
1379
- `);q&&(B=`
1373
+ ${s}`:n);let i=Bf(t);return async({example:a,prediction:u})=>{let c=a,l=u,p={taskInput:lt(c.input),criteria:c.criteria,expectedOutput:c.expectedOutput,expectedActions:c.expectedActions,forbiddenActions:c.forbiddenActions,metadata:c.metadata},d={completionType:l.completionType,clarification:lt(l.clarification),finalOutput:lt(l.output),actionLog:l.actionLog,functionCalls:lt(l.functionCalls),toolErrors:l.toolErrors,turnCount:l.turnCount,usage:lt(l.usage??[]),recursiveTrace:lt(l.recursiveTrace),recursiveStats:lt(l.recursiveStats)},m=await r.forward(e,{...p,...d},i);return qf(zf(m.quality),c,l)}}async _forwardForEvaluation(e,t,n){let r=this.state?fr(this.state):void 0,s=this.stateError;this.state=void 0,this.stateError=void 0;let i=new AbortController;this._stopRequested&&i.abort("Stopped by user (pre-forward)");let a=kt(i.signal,n?.abortSignal);this.activeAbortControllers.add(i);let u=this._ensureLlmQueryBudgetState(),c=this.recursiveEvalContext,l=this.currentRecursiveTraceNodeId,p=this._supportsRecursiveActorSlotOptimization()?Zf():void 0;this.recursiveEvalContext=p?{collector:p,depth:0}:void 0,this.currentRecursiveTraceNodeId=void 0;try{let d=this.ai??e,m=n?.debug??this.debug??d?.getOptions()?.debug??!1,g=[],f=[],{node:x,usageBefore:A}=this._beginRecursiveTraceCapture(t.input),{nonContextValues:h,actorResult:y,actorFieldValues:C,actionLog:I,turnCount:R}=await this._runActorLoop(d,t.input,n,a,g,f),M=g.filter(S=>!!S.error).map(S=>`${S.qualifiedName}: ${S.error??"unknown error"}`);if(y.type==="ask_clarification"){this._finalizeRecursiveTraceCapture(x,A,f,g,y);let S=p?.rootNode?ri(fu(p.rootNode)):void 0,v=S?cu(S):void 0,P=S&&v?lu(S,v):void 0;return{completionType:"ask_clarification",clarification:bd(y.args[0]),actionLog:I,functionCalls:g,toolErrors:M,turnCount:R,recursiveTrace:S,recursiveStats:v,recursiveSummary:P}}let T={...this._genOptions,...this.responderForwardOptions,...n,debug:m,abortSignal:a,maxSteps:1},O=await this.responderProgram.forward(d,{...h,contextData:y},T);this._finalizeRecursiveTraceCapture(x,A,f,g,y);let E=p?.rootNode?ri(fu(p.rootNode)):void 0,$=E?cu(E):void 0,N=E&&$?lu(E,$):void 0;return{completionType:"final",output:{...O,...C},actionLog:I,functionCalls:g,toolErrors:M,turnCount:R,recursiveTrace:E,recursiveStats:$,recursiveSummary:N}}finally{this.state=r?fr(r):void 0,this.stateError=s,this.recursiveEvalContext=c,this.currentRecursiveTraceNodeId=l,u&&(this.llmQueryBudgetState=void 0),this.activeAbortControllers.delete(i),this._stopRequested=!1}}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,s)=>{let i=this.ai??s?.ai;if(!i)throw new Error("AI service is required to run the agent");let a=await e(i,r,s),c=this.program.getSignature().getOutputFields();return Object.keys(a).map(p=>{let d=c.find(m=>m.name===p);return d?`${d.title}: ${a[p]}`:`${p}: ${a[p]}`}).join(`
1374
+ `)}}}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(x=>x.role==="user").reduce((x,A)=>({...x,...A.values}),{}):n=e;let r=t?.allowedFieldNames?new Set(t.allowedFieldNames):void 0;if(r&&t?.validateInputKeys){for(let x of Object.keys(n))if(!r.has(x))throw new Error(`AxAgent.test() only accepts context field values. "${x}" is not configured in contextFields.`)}let s={...n},i=r?new Set(r):new Set(this.program.getSignature().getInputFields().map(x=>x.name)),a=[...this.sharedFieldNames,...this.globalSharedFieldNames],u=this._getBypassedSharedFieldNames(),c={},l={},p={},d={},m="(none)",g=new Set(this.program.getSignature().getInputFields().filter(x=>this.rlmConfig.contextFields.includes(x.name)&&x.isOptional).map(x=>x.name));return{currentInputs:s,signatureInputFieldNames:i,sharedFieldValues:c,recomputeTurnInputs:x=>{let A={},h={};for(let[C,I]of Object.entries(s))this.rlmConfig.contextFields.includes(C)?A[C]=I:u.has(C)||(h[C]=I);if(x){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 y={};for(let[C,I]of this.contextPromptConfigByField){if(u.has(C)||!(C in A))continue;let R=wh(A[C],I);R!==void 0&&(y[C]=R)}l=A,p=h,d=y;for(let C of Object.keys(c))delete c[C];for(let C of a)C in s&&(c[C]=s[C]),C in l&&(c[C]=l[C]);m=kh(l,{promptConfigByField:this.contextPromptConfigByField,inlinedFields:new Set(Object.keys(d))})||"(none)"},getNonContextValues:()=>p,getActorInlineContextValues:()=>d,getContextMetadata:()=>m}}_ensureLlmQueryBudgetState(){return this.llmQueryBudgetState?!1:(this.llmQueryBudgetState={used:0},!0)}_createRuntimeExecutionContext({ai:e,inputState:t,options:n,effectiveAbortSignal:r,debug:s,completionState:i,completionBindings:a,actionLogEntries:u,functionCallRecorder:c}){let l=this.rlmConfig,p=this.runtime,d=l.maxSubAgentCalls??nd,m=l.maxRuntimeChars??pu,g=Math.max(1,l.maxBatchedLlmQueryConcurrency??Ef),f=this.recursionForwardOptions?.maxDepth??oi,x=Math.max(0,f),A=ud(l.contextPolicy),h=this.llmQueryBudgetState??{used:0},y=new Set,C=Math.floor(d*.8),{maxDepth:I,...R}=this.recursionForwardOptions??{},{description:M,mem:T,sessionId:O,...E}=n??{},$={...this.recursionForwardOptions??{},maxDepth:Math.max(0,x-1)},N=fe().input("task",fe.string("Task for recursive analysis")).output("answer",fe.string("Answer from recursive analysis")).build(),S=fe().input("task",fe.string("Task for recursive analysis")).input("context",fe.json("Optional context for the recursive task")).output("answer",fe.string("Answer from recursive analysis")).build(),P=(l.mode??"simple")==="advanced"&&x>0,F=this.recursionForwardOptions?.promptLevel??this.actorPromptLevel,U=()=>(()=>{let D=new o({agentModuleNamespace:this.agentModuleNamespace,signature:N},{debug:s,...l,agents:{local:this.agents},functions:{local:this.agentFunctions,discovery:this.functionDiscoveryEnabled},contextFields:[],actorFields:void 0,promptLevel:F,actorModelPolicy:this.options?.actorModelPolicy,recursionOptions:$,actorOptions:{...this.actorForwardOptions},responderOptions:this.responderForwardOptions});return D.recursiveInstructionRoleOverride=$.maxDepth&&$.maxDepth>0?"recursive":"terminal",this._copyRecursiveOptimizationStateTo(D),D})(),L=D=>(D.llmQueryBudgetState=h,this.recursiveEvalContext&&(D.recursiveEvalContext={collector:this.recursiveEvalContext.collector,parentNodeId:this.currentRecursiveTraceNodeId,depth:this.recursiveEvalContext.depth+1}),D),z=()=>{for(let D of[...y])D.stop()},j=()=>new Me(S,$),K=async(D,V)=>{if(!Array.isArray(D)&&typeof D=="object"&&D!==null&&"query"in D)return K(D.query,D.context??V);if(r?.aborted)throw new Fe("rlm-llm-query",r.reason?String(r.reason):"Aborted");if(!e)throw new Error($f);let ie=D,se=Ie=>{if(Ie==null)return"";if(typeof Ie=="string")return dt(Ie,m);try{return dt(JSON.stringify(Ie),m)}catch{return dt(String(Ie),m)}},Re=async(Ie,qe,Ne=r)=>{if(Ne?.aborted)throw new Fe("rlm-llm-query",Ne.reason?String(Ne.reason):"Aborted");let nt=qe===void 0?void 0:typeof qe=="string"?dt(qe,m):qe;if(h.used>=d)return`[ERROR] Sub-query budget exhausted (${d}/${d}). Complete the task using data already gathered or handle remaining work directly in JS.`;h.used++;let oe=3,ee,ye=Oe=>`[ERROR] ${Oe instanceof Error?Oe.message:String(Oe)}. Retry with a simpler query, handle in JS, or proceed with data already gathered.`;for(let Oe=0;Oe<oe;Oe++)try{if(!P){let We=j(),en=await We.forward(e,{task:Ie,...nt!==void 0?{context:nt}:{}},{...E,...R,abortSignal:Ne,debug:s});return this._recordEphemeralRecursiveUsage(ni(We.getUsage())),se(en.answer)}let Pe=await(()=>{let We=L(U());return y.add(We),We.runtimeBootstrapContext=nt,We.forward(e,{task:Ie},{...E,...R,abortSignal:Ne,debug:s}).finally(()=>{y.delete(We)})})();return se(Pe.answer)}catch(Pe){if(Pe instanceof Fe||Pe instanceof pt)throw Pe;if(ee=Pe,!hh(Pe)||Oe>=oe-1)return ye(Pe);let We=Math.min(6e4,1e3*Math.pow(2,Oe));await new Promise((en,ci)=>{let tn=!1,nn,xo=()=>{Ne&&nn&&Ne.removeEventListener("abort",nn)},ve=setTimeout(()=>{tn||(tn=!0,xo(),en())},We);if(Ne){if(nn=()=>{tn||(tn=!0,clearTimeout(ve),xo(),ci(new Fe("rlm-llm-query-retry-backoff",Ne.reason?String(Ne.reason):"Aborted during retry backoff")))},Ne.aborted){nn();return}Ne.addEventListener("abort",nn,{once:!0})}})}return ye(ee)};if(Array.isArray(D)){let Ie=new AbortController,qe=kt(r,Ie.signal)??Ie.signal,Ne,nt=()=>{z()};qe.addEventListener("abort",nt,{once:!0});try{return await Oh(D,g,async oe=>{try{return await Re(oe.query,oe.context,qe)}catch(ee){if(ee instanceof Fe||ee instanceof pt)throw(ee instanceof pt||!Ne)&&(Ne=ee),Ie.signal.aborted||Ie.abort(ee instanceof pt?"Child clarification":ee.message),Ne;return`[ERROR] ${ee instanceof Error?ee.message:String(ee)}`}},qe)}finally{qe.removeEventListener("abort",nt)}}let Ue=await Re(ie,V);return h.used===C?`${Ue}
1375
+ [WARNING] ${h.used}/${d} sub-queries used (${d-h.used} remaining). Consolidate remaining work.`:Ue},W=this.buildRuntimeGlobals(r,t.sharedFieldValues,e,a.protocol,c),pe=[...new Set(this.agentFunctions.map(D=>D.namespace??"utils"))],G={...t.currentInputs},J=new Set(["inputs","llmQuery",si,this.agentModuleNamespace,"final","ask_clarification",...pe,...A.stateInspection.enabled?["inspect_runtime"]:[],...Object.keys(W)]),Y=[...new Set([...Object.keys(G),...t.signatureInputFieldNames])].filter(D=>!J.has(D)),le={};for(let D of Y)le[D]=G[D];let H=()=>{for(let D of Object.keys(G))delete G[D];for(let[D,V]of Object.entries(t.currentInputs))G[D]=V;for(let D of Y)le[D]=t.currentInputs[D]},q=[...J],re=[...J,...Y],Ce=new Set(re),we=this.runtimeBootstrapContext;this.runtimeBootstrapContext=void 0;let ue=rh(we,Ce),Te=new Set(Object.keys(ue)),ae=u??[],de,X,te=D=>typeof D.inspectGlobals=="function"?D:void 0,Ae=async()=>{try{let D=await de.execute(Wp(),{signal:r,reservedNames:re});if(typeof D!="string")return[];let V=JSON.parse(D);return Array.isArray(V)?V.filter(ie=>typeof ie=="string"&&!Te.has(ie)):[]}catch{return[]}},Se=async()=>(X||(X=await Ae()),X),Be=async()=>{try{let D=te(de);if(D?.inspectGlobals)return await D.inspectGlobals({signal:r,reservedNames:re});let V=await Se(),ie=Vp(re,V),se=await de.execute(ie,{signal:r,reservedNames:re});return typeof se=="string"?se:String(se)}catch(D){return`[inspect_runtime error: ${D instanceof Error?D.message:String(D)}]`}},Le=(D,V)=>{let ie=Ah(D);if(!ie)return yh(D,V);let se=Xs(ae);return hu(ie,se,V)},at=A.stateInspection.enabled?async()=>Le(await Be()):void 0,Ee=()=>(X=void 0,p.createSession({...le,inputs:G,...ue,llmQuery:K,final:a.finalFunction,ask_clarification:a.askClarificationFunction,...at?{inspect_runtime:at}:{},...W}));de=Ee();let ze=()=>({maxEntries:A.stateSummary.maxEntries&&A.stateSummary.maxEntries>0?A.stateSummary.maxEntries:8,maxChars:A.stateSummary.maxChars&&A.stateSummary.maxChars>0?A.stateSummary.maxChars:void 0}),me=()=>({maxEntries:A.stateSummary.maxEntries&&A.stateSummary.maxEntries>0?A.stateSummary.maxEntries:6,maxChars:A.stateSummary.maxChars&&A.stateSummary.maxChars>0?A.stateSummary.maxChars:Math.min(m,1200)}),De=Object.keys(ue).length>0?ch(ue,{...me(),budgetRemaining:Math.max(0,d-h.used),budgetTotal:d}):void 0,Ve=async()=>{if(!i.payload)for(let D=0;D<3&&!i.payload;D++)await new Promise(V=>{setTimeout(V,0)})},Ye=async()=>{if(!A.stateSummary.enabled)return;let D=await Be();return Le(D,ze())||"(no user variables)"},ut=D=>{if(typeof D.patchGlobals!="function")throw new Error("AxCodeSession.patchGlobals() is required when restoring AxAgent state or using inputUpdateCallback");return D},b=D=>{if(typeof D.snapshotGlobals!="function")throw new Error("AxCodeSession.snapshotGlobals() is required to export AxAgent state");return D},k=D=>{let V=new Set(re),ie={};for(let[Re,Ue]of Object.entries(D.runtimeBindings??{}))V.has(Re)||(ie[Re]=Ue);let se=(D.runtimeEntries??[]).filter(Re=>!V.has(Re.name));return{runtimeBindings:ie,runtimeEntries:se,actionLogEntries:ph(D.actionLogEntries),checkpointState:D.checkpointState,provenance:{...D.provenance??{}},actorModelState:Qf(D.actorModelState)}};return{effectiveContextConfig:A,bootstrapContextSummary:De,applyBootstrapRuntimeContext:async()=>{if(Object.keys(ue).length===0||!A.stateSummary.enabled)return;let D=await Be();return Le(D,ze())||"(no user variables)"},captureRuntimeStateSummary:Ye,exportRuntimeState:async()=>{let V=await b(de).snapshotGlobals({signal:r,reservedNames:re}),ie=Xs(ae);return{version:1,runtimeBindings:V.bindings,runtimeEntries:V.entries,actionLogEntries:lh(ae),provenance:dh(ie)}},restoreRuntimeState:async D=>{let V=k(D);return await ut(de).patchGlobals(V.runtimeBindings,{signal:r}),V},syncRuntimeInputsToSession:async()=>{H();let D=async V=>{await ut(V).patchGlobals({inputs:{...G},...le},{signal:r})};try{await D(de)}catch(V){if(r?.aborted)throw new Fe("rlm-session",r.reason??"Aborted");if(V instanceof Error&&(V.name==="AbortError"||V.message.startsWith("Aborted")))throw V;if(gd(V)){de=Ee(),await D(de);return}throw new Error(`Failed to sync runtime inputs: ${ai(V,m)}`)}},executeActorCode:async D=>{let V={result:void 0,output:ii(void 0,m),isError:!1};try{let ie=await de.execute(D,{signal:r,reservedNames:q});return i.payload||dd(D)&&md(ie)&&(await Ve(),i.payload)?V:{result:ie,output:ii(ie,m),isError:!1}}catch(ie){if(ie instanceof hr||i.payload)return V;if(ie instanceof pt||ie instanceof Fe)throw ie;if(r?.aborted)throw new Fe("rlm-session",r.reason??"Aborted");if(ie instanceof Error&&(ie.name==="AbortError"||ie.message.startsWith("Aborted")))throw ie;if(Ih(ie))return{result:void 0,output:dt(`${ui}
1376
+ ${ai(ie,m)}`,m),isError:!0};if(gd(ie))try{de=Ee(),i.payload=void 0;let se=await de.execute(D,{signal:r,reservedNames:q});return{result:se,output:dt(`${ui}
1377
+ ${ii(se,m)}`,m),isError:!1}}catch(se){if(se instanceof pt||se instanceof Fe)throw se;return{result:void 0,output:dt(`${ui}
1378
+ ${ai(se,m)}`,m),isError:!0}}return{result:void 0,output:dt(ai(ie,m),m),isError:!0}}},executeTestCode:async D=>{try{let V=await de.execute(D,{signal:r,reservedNames:q});if(dd(D)&&md(V)&&await Ve(),i.payload)return i.payload;let ie=ii(V,m);if(Th(ie))throw new Error(ie);return ie}catch(V){if((V instanceof hr||i.payload)&&i.payload)return i.payload;throw V}},close:()=>{de.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,s=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},u=id((p,d)=>{a.payload=cd(p,d)}),c=this._ensureLlmQueryBudgetState(),l=this._createRuntimeExecutionContext({ai:r,inputState:i,options:void 0,effectiveAbortSignal:n?.abortSignal,debug:s,completionState:a,completionBindings:u,actionLogEntries:[]});try{return await l.executeTestCode(e)}finally{this.currentRecursiveTraceNodeId=void 0,c&&(this.llmQueryBudgetState=void 0),l.close()}}setSignature(e){let t=new _e(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){let t=e?.instructionSchema,n=e?.artifactFormatVersion;if(t&&t!==lo)throw new Error(`AxAgent.applyOptimization(): unsupported instruction schema "${t}".`);if(t===lo&&n!==void 0&&n!==1)throw new Error(`AxAgent.applyOptimization(): unsupported recursive artifact format version "${String(n)}".`);let r=e?.instructionMap??{},s=[ge.shared,ge.root,ge.recursive,ge.terminal].some(i=>typeof r[i]=="string");if(t===lo){if(!this._supportsRecursiveActorSlotOptimization())throw new Error('AxAgent.applyOptimization(): recursive-slot artifacts require mode "advanced" with recursion enabled.');(e?.demos||e?.modelConfig)&&this.program.setDemos(e.demos??[],{modelConfig:e.modelConfig}),this.recursiveInstructionSlots=gr(this.actorDescription);for(let a of[ge.shared,ge.root,ge.recursive,ge.terminal])typeof r[a]=="string"&&(this.recursiveInstructionSlots[a]=r[a]??"");this._applyRecursiveActorInstruction();let i=r[ge.responder];typeof i=="string"&&this.responderProgram.setInstruction(i);return}if(this._supportsRecursiveActorSlotOptimization()&&!s){(e?.demos||e?.modelConfig)&&this.program.setDemos(e.demos??[],{modelConfig:e.modelConfig}),this.recursiveInstructionSlots=gr(this.actorDescription);let i=r["root.actor"]??e?.instruction;typeof i=="string"&&(this.recursiveInstructionSlots[ge.shared]=i),this._applyRecursiveActorInstruction();let a=r["root.responder"];typeof a=="string"?this.responderProgram.setInstruction(a):typeof e?.instruction=="string"&&this.responderProgram.setInstruction(e.instruction);return}if(s){if(!this._supportsRecursiveActorSlotOptimization())throw new Error('AxAgent.applyOptimization(): recursive-slot instruction maps require mode "advanced" with recursion enabled.');this.recursiveInstructionSlots=gr(this.actorDescription);for(let a of[ge.shared,ge.root,ge.recursive,ge.terminal])typeof r[a]=="string"&&(this.recursiveInstructionSlots[a]=r[a]??"");this._applyRecursiveActorInstruction();let i=r[ge.responder];typeof i=="string"&&this.responderProgram.setInstruction(i),(e?.demos||e?.modelConfig)&&this.program.setDemos(e.demos??[],{modelConfig:e.modelConfig});return}this.program.applyOptimization?.(e)}async _runActorLoop(e,t,n,r,s,i){let a=this.rlmConfig,u=n?.debug??this.debug??e?.getOptions()?.debug??!1,c=a.maxTurns??rd,l=this._createRuntimeInputState(t);l.recomputeTurnInputs(!1);let p={payload:void 0},d=id((K,W)=>{p.payload=cd(K,W)}),m=[],g,f=this._createRuntimeExecutionContext({ai:e,inputState:l,options:n,effectiveAbortSignal:r,debug:u,completionState:p,completionBindings:d,actionLogEntries:m,functionCallRecorder:s?K=>{s.push(K)}:void 0}),x=f.effectiveContextConfig.stateSummary.enabled?void 0:f.bootstrapContextSummary,A=async()=>{if(!this.inputUpdateCallback)return;let K=await this.inputUpdateCallback({...l.currentInputs});if(K!==void 0){if(!K||typeof K!="object"||Array.isArray(K))throw new Error("inputUpdateCallback must return an object patch or undefined");for(let[W,pe]of Object.entries(K))l.signatureInputFieldNames.has(W)&&(l.currentInputs[W]=pe)}},h={...this._genOptions,...this.actorForwardOptions,...n,debug:u,abortSignal:r},y={},C=f.effectiveContextConfig.stateInspection.enabled?f.effectiveContextConfig.stateInspection.contextThreshold:void 0,I=Kf(n,u,r),R=this.functionDiscoveryEnabled&&f.effectiveContextConfig.pruneUsedDocs,M,T,O,E=f.effectiveContextConfig.actionReplay==="checkpointed"?"minimal":f.effectiveContextConfig.actionReplay,$=f.effectiveContextConfig.actionReplay==="checkpointed"?"full":f.effectiveContextConfig.actionReplay,N=()=>Zs(m,{pruneUsedDocs:R}),S=K=>({...l.getNonContextValues(),...l.getActorInlineContextValues(),contextMetadata:l.getContextMetadata(),actionLog:K}),v=K=>this.actorProgram._measurePromptCharsForInternalUse(e,S(K),h),P=(K,W,pe)=>Hp(N(),{actionReplay:K,recentFullActions:f.effectiveContextConfig.recentFullActions,restoreNotice:O,delegatedContextSummary:x,stateSummary:g,checkpointSummary:W,checkpointTurns:pe})||"(no actions yet)",F=()=>P(f.effectiveContextConfig.actionReplay,M?.summary,M?.turns),U=()=>{!this.actorModelPolicy&&!T||(T=Ad())},L=K=>{!this.actorModelPolicy&&!T||(T=Yf(T,K))},z=async()=>{let K=H=>{let q=(M?.fingerprint??null)!==(H?.fingerprint??null);return M=H,q};if(!f.effectiveContextConfig.checkpoints.enabled)return K(void 0);let W=f.effectiveContextConfig.checkpoints.triggerChars,pe=P($),G=await v(pe);if(!W||G<=W)return K(void 0);let Y=au(m,{actionReplay:E,recentFullActions:f.effectiveContextConfig.recentFullActions,pruneUsedDocs:R}).checkpointEntries;if(Y.length===0)return K(void 0);let le=JSON.stringify(Y.map(H=>({turn:H.turn,code:H.code,output:H.output,actorFieldsOutput:H.actorFieldsOutput,tags:H.tags,tombstone:H.tombstone})));return M?.fingerprint===le?!1:K({fingerprint:le,turns:Y.map(H=>H.turn),summary:await qp(e,f.effectiveContextConfig.summarizerOptions,I,Y)})};try{if(this.state){let W=await f.restoreRuntimeState(this.state),pe=f.effectiveContextConfig.stateSummary.enabled;m.push(...W.actionLogEntries),M=W.checkpointState?{fingerprint:W.checkpointState.fingerprint,turns:[...W.checkpointState.turns],summary:W.checkpointState.summary}:void 0,T=W.actorModelState?{consecutiveErrorTurns:W.actorModelState.consecutiveErrorTurns}:void 0;let G=fh(Xs(m),gh(W.provenance));g=pe?hu(W.runtimeEntries,G,{maxEntries:f.effectiveContextConfig.stateSummary.maxEntries&&f.effectiveContextConfig.stateSummary.maxEntries>0?f.effectiveContextConfig.stateSummary.maxEntries:8,maxChars:f.effectiveContextConfig.stateSummary.maxChars&&f.effectiveContextConfig.stateSummary.maxChars>0?f.effectiveContextConfig.stateSummary.maxChars:1200})||"(no user variables)":void 0,O=mh(W.runtimeEntries,{includeLiveRuntimeState:pe})}let K=await f.applyBootstrapRuntimeContext();K!==void 0&&(g=K);for(let W=0;W<c;W++){await A(),l.recomputeTurnInputs(!0),await z()&&U();let G=F(),J=await v(G),Y=!1;C&&J>C&&(Y=!0,G+="\n\n[HINT: Actor prompt is large. Call `const state = await inspect_runtime()` for a compact snapshot of current variables instead of re-reading old outputs.]");let le=Y?await v(G):J,H=h;if(this.actorModelPolicy){let X=Xf(this.actorModelPolicy,le,xd(T));H=X!==void 0?{...h,model:X}:h}let q=await this.actorProgram.forward(e,S(G),H);W===0&&(h.debugHideSystemPrompt=!0,O=void 0);let re=q.javascriptCode,Ce=re?.trim();if(!re||!Ce)break;re=Gf(Ce),q.javascriptCode=re;for(let X of this.actorFieldNames)X in q&&(y[X]=q[X]);let we="";if(this.actorFieldNames.length>0){let X=this.actorFieldNames.filter(te=>te in q).map(te=>`${te}: ${q[te]}`).join(`
1379
+ `);X&&(we=`
1380
1380
  Actor fields:
1381
- ${q}`)}if(p.payload=void 0,this.enforceIncrementalConsoleTurns){let q=Dh(re);if(q){let oe=m.length+1;m.push({turn:oe,code:re,output:q,actorFieldsOutput:B,tags:["error"]}),i?.push({turn:oe,code:re,output:q,isError:!0,thought:typeof H.thought=="string"?H.thought:void 0}),a.actorTurnCallback&&await a.actorTurnCallback({turn:oe,actorResult:H,code:re,result:void 0,output:q,isError:!0,thought:typeof H.thought=="string"?H.thought:void 0}),await ou(m,m.length-1,f.effectiveContextConfig,e,C),await v();continue}}this.inputUpdateCallback&&await f.syncRuntimeInputsToSession();let V,Q,ie;try{let q=await f.executeActorCode(re);V=q.result,Q=q.output,ie=q.isError}catch(q){throw(q instanceof pt||q instanceof Fe)&&(i?.push({turn:m.length+1,code:re,output:ud(q,a.maxRuntimeChars??uu),isError:q instanceof Fe,thought:typeof H.thought=="string"?H.thought:void 0}),a.actorTurnCallback&&await a.actorTurnCallback({turn:m.length+1,actorResult:H,code:re,result:void 0,output:ud(q,a.maxRuntimeChars??uu),isError:q instanceof Fe,thought:typeof H.thought=="string"?H.thought:void 0})),q}let W=m.length+1;if(m.push({turn:W,code:re,output:Q,actorFieldsOutput:B,tags:ie?["error"]:[]}),i?.push({turn:W,code:re,output:Q,isError:ie,thought:typeof H.thought=="string"?H.thought:void 0}),a.actorTurnCallback&&await a.actorTurnCallback({turn:W,actorResult:H,code:re,result:V,output:Q,isError:ie,thought:typeof H.thought=="string"?H.thought:void 0}),await ou(m,m.length-1,f.effectiveContextConfig,e,C),ie||(g=await f.captureRuntimeStateSummary()),await v(),p.payload)break}await v();try{let L=await f.exportRuntimeState();L.checkpointState=M?{fingerprint:M.fingerprint,turns:[...M.turns],summary:M.summary}:void 0,L.actorModelState=I?{escalated:I.escalated,escalatedTurns:I.escalatedTurns,stableBelowThresholdTurns:I.stableBelowThresholdTurns}:void 0,this.state=L,this.stateError=void 0}catch(L){this.state=void 0,this.stateError=L instanceof Error?L.message:`Failed to export AxAgent state: ${String(L)}`}}finally{try{f.close()}catch{}}let F=p.payload??{type:"final",args:[Hp(m,{stateSummary:g,checkpointSummary:M?.summary,checkpointTurns:M?.turns,pruneUsedDocs:R})]};return{nonContextValues:l.getNonContextValues(),contextMetadata:l.getContextMetadata(),actionLog:S(),actorResult:F,actorFieldValues:y,turnCount:m.length}}async forward(e,t,n){let r=new AbortController;this._stopRequested&&r.abort("Stopped by user (pre-forward)");let s=kt(r.signal,n?.abortSignal);this.activeAbortControllers.add(r);let i=this._ensureLlmQueryBudgetState();try{let a=this.ai??e,u=n?.debug??this.debug??a?.getOptions()?.debug??!1,c=[],l=[],{node:p,usageBefore:d}=this._beginRecursiveTraceCapture(t),{nonContextValues:m,actorResult:g,actorFieldValues:f}=await this._runActorLoop(a,t,n,s,c,l);if(g.type==="ask_clarification")throw this._finalizeRecursiveTraceCapture(p,d,l,c,g),new pt(g.args[0],{state:this.state,stateError:this.stateError});let x={...this._genOptions,...this.responderForwardOptions,...n,debug:u,abortSignal:s,maxSteps:1},A=await this.responderProgram.forward(a,{...m,contextData:g},x);return this._finalizeRecursiveTraceCapture(p,d,l,c,g),{...A,...f}}finally{i&&(this.llmQueryBudgetState=void 0),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 s=kt(r.signal,n?.abortSignal);this.activeAbortControllers.add(r);let i=this._ensureLlmQueryBudgetState();try{let a=this.ai??e,u=n?.debug??this.debug??a?.getOptions()?.debug??!1,{nonContextValues:c,actorResult:l,actorFieldValues:p}=await this._runActorLoop(a,t,n,s);if(l.type==="ask_clarification")throw new pt(l.args[0],{state:this.state,stateError:this.stateError});let d={...this._genOptions,...this.responderForwardOptions,...n,debug:u,abortSignal:s,maxSteps:1};for await(let m of this.responderProgram.streamingForward(a,{...c,contextData:l},d))yield m;Object.keys(p).length>0&&(yield{version:1,index:0,delta:p})}finally{i&&(this.llmQueryBudgetState=void 0),this.activeAbortControllers.delete(r),this._stopRequested=!1}}static wrapFunction(e,t,n,r,s,i){return async(...a)=>{let u;if(a.length===1&&typeof a[0]=="object"&&a[0]!==null&&!Array.isArray(a[0]))u=a[0];else{let c=e.parameters?.properties?Object.keys(e.parameters.properties):[];u={},c.forEach((l,p)=>{p<a.length&&(u[l]=a[p])})}try{let c=await e.func(u,{abortSignal:t,ai:n,protocol:r});return i?.({qualifiedName:s??e.name,name:e.name,arguments:lt(u),result:lt(c)}),c}catch(c){throw i?.({qualifiedName:s??e.name,name:e.name,arguments:lt(u),error:c instanceof Error?c.message:String(c)}),c}}}static wrapFunctionWithSharedFields(e,t,n,r,s,i,a){return typeof n!="function"&&(!n||Object.keys(n).length===0)?o.wrapFunction(e,t,r,s,i,a):async(...u)=>{let c;if(u.length===1&&typeof u[0]=="object"&&u[0]!==null&&!Array.isArray(u[0]))c=u[0];else{let d=e.parameters?.properties?Object.keys(e.parameters.properties):[];c={},d.forEach((m,g)=>{g<u.length&&(c[m]=u[g])})}let l=typeof n=="function"?n():n,p=l?{...l,...c}:c;try{let d=await e.func(p,{abortSignal:t,ai:r,protocol:s});return a?.({qualifiedName:i??e.name,name:e.name,arguments:lt(p),result:lt(d)}),d}catch(d){throw a?.({qualifiedName:i??e.name,name:e.name,arguments:lt(p),error:d instanceof Error?d.message:String(d)}),d}}}buildRuntimeGlobals(e,t,n,r,s){let i={},a=new Map,u=new Map,c=new Map;for(let[p,d]of this.agentFunctionModuleMetadata)c.set(p,d);let l=(p,d)=>{a.set(d,p),u.has(p.module)||u.set(p.module,[]),u.get(p.module)?.push(d)};for(let p of this.agentFunctions){let d=p.namespace??"utils";(!i[d]||typeof i[d]!="object")&&(i[d]={});let m=`${d}.${p.name}`;i[d][p.name]=o.wrapFunction(p,e,n,r,m,s),l({module:d,name:p.name,description:p.description,parameters:p.parameters,returns:p.returns,examples:p.examples},m)}if(this.agents&&this.agents.length>0){let p={};for(let d of this.agents){let m=d.getFunction(),g=new Set(d.getExcludedSharedFields?.()??[]),f=()=>{let A={};if(t)for(let[h,y]of Object.entries(t))g.has(h)||(A[h]=y);return A},x=`${this.agentModuleNamespace}.${m.name}`;p[m.name]=o.wrapFunctionWithSharedFields(m,e,f,n,r,x,s),l({module:this.agentModuleNamespace,name:m.name,description:m.description,parameters:m.parameters},x)}i[this.agentModuleNamespace]=p}return this.functionDiscoveryEnabled&&(i[cu]=async p=>{let d=gd(p,"modules");return Kh(d,u,c)},i[lu]=async p=>{let d=gd(p,"functions");return Vh(d,a)}),i}get _genOptions(){if(!this.options)return{};let{agents:e,fields:t,functions:n,judgeOptions:r,inputUpdateCallback:s,...i}=this.options;return i}_buildFuncParameters(){let e=this.program.getSignature().toInputJSONSchema();return this._parentSharedFields.size>0?Bh(e,this._parentSharedFields):e}};function ad(o,e){if(e.length===0)throw new Error(`${o}() requires at least one argument`);if(o==="ask_clarification"){if(e.length!==1)throw new Error("ask_clarification() requires exactly one argument");return{type:o,args:[hd(e[0])]}}return{type:o,args:e}}function hu(o){return!!o&&typeof o=="object"&&!Array.isArray(o)&&Object.getPrototypeOf(o)===Object.prototype}function fo(o){return typeof o=="string"&&o.trim().length>0}function ah(o){if(fo(o))return o;if(!hu(o))throw new Error("ask_clarification() choice entries must be non-empty strings or objects with a non-empty label");if(!fo(o.label))throw new Error("ask_clarification() choice objects require a non-empty label");if(o.value!==void 0&&!fo(o.value))throw new Error("ask_clarification() choice object values must be non-empty strings");return{label:o.label,...o.value!==void 0?{value:o.value}:{}}}function hd(o){if(fo(o))return o;if(!hu(o))throw new Error("ask_clarification() requires a non-empty string or an object payload");if(!fo(o.question))throw new Error("ask_clarification() object payload requires a non-empty question");let e=new Set(["text","number","date","single_choice","multiple_choice"]),t;if(o.type===void 0)t=Array.isArray(o.choices)&&o.choices.length>0?"single_choice":void 0;else{if(typeof o.type!="string"||!e.has(o.type))throw new Error("ask_clarification() object payload type must be one of: text, number, date, single_choice, multiple_choice");t=o.type}let n=t==="single_choice"||t==="multiple_choice",r=o.choices;if(r!==void 0){if(!Array.isArray(r)||r.length===0)throw new Error("ask_clarification() choices must be a non-empty array when provided")}else if(n)throw new Error("ask_clarification() choice payloads require a non-empty choices array");return{...o,question:o.question,...t?{type:t}:{},...r?{choices:r.map(ah)}:{}}}function xd(o){let e=hd(o);return typeof e=="string"?{question:e,type:"text"}:{...e,type:e.type??(e.choices&&e.choices.length>0?"single_choice":"text")}}function uh(o){return typeof structuredClone=="function"?structuredClone(o):JSON.parse(JSON.stringify(o))}function ch(o,e){return!e.has(o)&&!Bf.has(o)&&Gf.test(o)}function lh(o,e){if(o===void 0)return{};let t={context:o};if(!hu(o))return t;for(let[n,r]of Object.entries(o))ch(n,e)&&(t[n]=r);return t}function ph(o){if(o===null)return{type:"null"};if(Array.isArray(o))return{type:"array",ctor:"Array"};if(o instanceof Map)return{type:"map",ctor:"Map"};if(o instanceof Set)return{type:"set",ctor:"Set"};if(o instanceof Date)return{type:"date",ctor:"Date"};if(o instanceof Error)return{type:"error",ctor:typeof o.name=="string"&&o.name.trim()?o.name:"Error"};let e=typeof o;return e!=="object"?{type:e}:{type:"object",ctor:o&&o.constructor&&typeof o.constructor?.name=="string"?o.constructor?.name:void 0}}function go(o){if(o===null)return"null";if(o===void 0)return"undefined";let e=typeof o;if(e==="string")return JSON.stringify(xu(o,40));if(e==="number"||e==="boolean"||e==="bigint"||e==="symbol")return String(o);if(e==="function")return`[function ${o.name||"anonymous"}]`;if(Array.isArray(o))return`[array(${o.length})]`;if(o instanceof Date)return Number.isFinite(o.getTime())?o.toISOString():String(o);if(o instanceof Error)return`${o.name||"Error"}: ${o.message||""}`;if(o instanceof Map)return`[map(${o.size})]`;if(o instanceof Set)return`[set(${o.size})]`;let t=o&&o.constructor&&typeof o.constructor?.name=="string"?o.constructor?.name:"";return t&&t!=="Object"?`[${t}]`:"[object]"}function dh(o,e,t){if(e==="array"&&Array.isArray(o))return`[${o.slice(0,3).map(r=>go(r)).join(", ")}${o.length>3?", ...":""}]`;if(e==="map"&&o instanceof Map){let n=[...o.entries()].slice(0,3).map(([r,s])=>`${go(r)} => ${go(s)}`);return`Map(${o.size}) {${n.join(", ")}${o.size>3?", ...":""}}`}if(e==="set"&&o instanceof Set){let n=[...o.values()].slice(0,5).map(r=>go(r));return`Set(${o.size}) {${n.join(", ")}${o.size>5?", ...":""}}`}if(e==="object"&&o&&typeof o=="object"){let n=Object.keys(o),r=n.slice(0,4);return`${t&&t!=="Object"?`${t} `:""}{${r.join(", ")}${n.length>r.length?", ...":""}}`}return go(o)}function mh(o,e){if(e==="string"&&typeof o=="string")return`${o.length} chars`;if(e==="array"&&Array.isArray(o))return`${o.length} items`;if((e==="map"||e==="set")&&o instanceof Map)return`${o.size} items`;if((e==="map"||e==="set")&&o instanceof Set)return`${o.size} items`;if(e==="object"&&o&&typeof o=="object")return`${Object.keys(o).length} keys`}function gh(o){if(o.length===0)return;let e=o[0];if(e&&typeof e=="object"&&!Array.isArray(e)){let t=Object.keys(e).slice(0,8);if(t.length>0)return t.join(", ")}}function fh(o){return Object.entries(o).map(([e,t])=>{try{let n=ph(t),r=mh(t,n.type),s=dh(t,n.type,n.ctor),i;n.type==="array"&&Array.isArray(t)&&(i=gh(t));let a=s?xu(s,40):void 0,u=i?a?`${a} \u2014 element keys: ${i}`:`element keys: ${i}`:a;return{name:e,type:n.type,...n.ctor?{ctor:n.ctor}:{},...r?{size:r}:{},...u?{preview:u}:{}}}catch{return{name:e,type:"unknown",preview:"[unavailable]"}}})}function hh(o,e){let t=fh(o),n=mu(t,new Map,e),r=e?.budgetRemaining!==void 0&&e?.budgetTotal!==void 0?`
1381
+ ${X}`)}if(p.payload=void 0,this.enforceIncrementalConsoleTurns){let X=Mh(re);if(X){let te=m.length+1;m.push({turn:te,code:re,output:X,actorFieldsOutput:we,tags:["error"]}),i?.push({turn:te,code:re,output:X,isError:!0,thought:typeof q.thought=="string"?q.thought:void 0}),a.actorTurnCallback&&await a.actorTurnCallback({turn:te,actorResult:q,code:re,result:void 0,output:X,isError:!0,thought:typeof q.thought=="string"?q.thought:void 0}),await iu(m,m.length-1,f.effectiveContextConfig,e,I),L(!0),await z()&&U();continue}}this.inputUpdateCallback&&await f.syncRuntimeInputsToSession();let ue,Te,ae;try{let X=await f.executeActorCode(re);ue=X.result,Te=X.output,ae=X.isError}catch(X){throw(X instanceof pt||X instanceof Fe)&&(i?.push({turn:m.length+1,code:re,output:ld(X,a.maxRuntimeChars??pu),isError:X instanceof Fe,thought:typeof q.thought=="string"?q.thought:void 0}),a.actorTurnCallback&&await a.actorTurnCallback({turn:m.length+1,actorResult:q,code:re,result:void 0,output:ld(X,a.maxRuntimeChars??pu),isError:X instanceof Fe,thought:typeof q.thought=="string"?q.thought:void 0})),X}let de=m.length+1;if(m.push({turn:de,code:re,output:Te,actorFieldsOutput:we,tags:ae?["error"]:[]}),i?.push({turn:de,code:re,output:Te,isError:ae,thought:typeof q.thought=="string"?q.thought:void 0}),a.actorTurnCallback&&await a.actorTurnCallback({turn:de,actorResult:q,code:re,result:ue,output:Te,isError:ae,thought:typeof q.thought=="string"?q.thought:void 0}),await iu(m,m.length-1,f.effectiveContextConfig,e,I),ae||(g=await f.captureRuntimeStateSummary()),L(ae),await z()&&U(),p.payload)break}await z()&&U();try{let W=await f.exportRuntimeState();W.checkpointState=M?{fingerprint:M.fingerprint,turns:[...M.turns],summary:M.summary}:void 0,W.actorModelState=T?{consecutiveErrorTurns:T.consecutiveErrorTurns}:void 0,this.state=W,this.stateError=void 0}catch(W){this.state=void 0,this.stateError=W instanceof Error?W.message:`Failed to export AxAgent state: ${String(W)}`}}finally{try{f.close()}catch{}}let j=p.payload??{type:"final",args:[Kp(m,{stateSummary:g,checkpointSummary:M?.summary,checkpointTurns:M?.turns,pruneUsedDocs:R})]};return{nonContextValues:l.getNonContextValues(),contextMetadata:l.getContextMetadata(),actionLog:F(),actorResult:j,actorFieldValues:y,turnCount:m.length}}async forward(e,t,n){let r=new AbortController;this._stopRequested&&r.abort("Stopped by user (pre-forward)");let s=kt(r.signal,n?.abortSignal);this.activeAbortControllers.add(r);let i=this._ensureLlmQueryBudgetState();try{let a=this.ai??e,u=n?.debug??this.debug??a?.getOptions()?.debug??!1,c=[],l=[],{node:p,usageBefore:d}=this._beginRecursiveTraceCapture(t),{nonContextValues:m,actorResult:g,actorFieldValues:f}=await this._runActorLoop(a,t,n,s,c,l);if(g.type==="ask_clarification")throw this._finalizeRecursiveTraceCapture(p,d,l,c,g),new pt(g.args[0],{state:this.state,stateError:this.stateError});let x={...this._genOptions,...this.responderForwardOptions,...n,debug:u,abortSignal:s,maxSteps:1},A=await this.responderProgram.forward(a,{...m,contextData:g},x);return this._finalizeRecursiveTraceCapture(p,d,l,c,g),{...A,...f}}finally{i&&(this.llmQueryBudgetState=void 0),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 s=kt(r.signal,n?.abortSignal);this.activeAbortControllers.add(r);let i=this._ensureLlmQueryBudgetState();try{let a=this.ai??e,u=n?.debug??this.debug??a?.getOptions()?.debug??!1,{nonContextValues:c,actorResult:l,actorFieldValues:p}=await this._runActorLoop(a,t,n,s);if(l.type==="ask_clarification")throw new pt(l.args[0],{state:this.state,stateError:this.stateError});let d={...this._genOptions,...this.responderForwardOptions,...n,debug:u,abortSignal:s,maxSteps:1};for await(let m of this.responderProgram.streamingForward(a,{...c,contextData:l},d))yield m;Object.keys(p).length>0&&(yield{version:1,index:0,delta:p})}finally{i&&(this.llmQueryBudgetState=void 0),this.activeAbortControllers.delete(r),this._stopRequested=!1}}static wrapFunction(e,t,n,r,s,i){return async(...a)=>{let u;if(a.length===1&&typeof a[0]=="object"&&a[0]!==null&&!Array.isArray(a[0]))u=a[0];else{let c=e.parameters?.properties?Object.keys(e.parameters.properties):[];u={},c.forEach((l,p)=>{p<a.length&&(u[l]=a[p])})}try{let c=await e.func(u,{abortSignal:t,ai:n,protocol:r});return i?.({qualifiedName:s??e.name,name:e.name,arguments:lt(u),result:lt(c)}),c}catch(c){throw i?.({qualifiedName:s??e.name,name:e.name,arguments:lt(u),error:c instanceof Error?c.message:String(c)}),c}}}static wrapFunctionWithSharedFields(e,t,n,r,s,i,a){return typeof n!="function"&&(!n||Object.keys(n).length===0)?o.wrapFunction(e,t,r,s,i,a):async(...u)=>{let c;if(u.length===1&&typeof u[0]=="object"&&u[0]!==null&&!Array.isArray(u[0]))c=u[0];else{let d=e.parameters?.properties?Object.keys(e.parameters.properties):[];c={},d.forEach((m,g)=>{g<u.length&&(c[m]=u[g])})}let l=typeof n=="function"?n():n,p=l?{...l,...c}:c;try{let d=await e.func(p,{abortSignal:t,ai:r,protocol:s});return a?.({qualifiedName:i??e.name,name:e.name,arguments:lt(p),result:lt(d)}),d}catch(d){throw a?.({qualifiedName:i??e.name,name:e.name,arguments:lt(p),error:d instanceof Error?d.message:String(d)}),d}}}buildRuntimeGlobals(e,t,n,r,s){let i={},a=new Map,u=new Map,c=new Map;for(let[p,d]of this.agentFunctionModuleMetadata)c.set(p,d);let l=(p,d)=>{a.set(d,p),u.has(p.module)||u.set(p.module,[]),u.get(p.module)?.push(d)};for(let p of this.agentFunctions){let d=p.namespace??"utils";(!i[d]||typeof i[d]!="object")&&(i[d]={});let m=`${d}.${p.name}`;i[d][p.name]=o.wrapFunction(p,e,n,r,m,s),l({module:d,name:p.name,description:p.description,parameters:p.parameters,returns:p.returns,examples:p.examples},m)}if(this.agents&&this.agents.length>0){let p={};for(let d of this.agents){let m=d.getFunction(),g=new Set(d.getExcludedSharedFields?.()??[]),f=()=>{let A={};if(t)for(let[h,y]of Object.entries(t))g.has(h)||(A[h]=y);return A},x=`${this.agentModuleNamespace}.${m.name}`;p[m.name]=o.wrapFunctionWithSharedFields(m,e,f,n,r,x,s),l({module:this.agentModuleNamespace,name:m.name,description:m.description,parameters:m.parameters},x)}i[this.agentModuleNamespace]=p}return this.functionDiscoveryEnabled&&(i[du]=async p=>{let d=hd(p,"modules");return Gh(d,u,c)},i[mu]=async p=>{let d=hd(p,"functions");return jh(d,a)}),i}get _genOptions(){if(!this.options)return{};let{agents:e,fields:t,functions:n,judgeOptions:r,inputUpdateCallback:s,...i}=this.options;return i}_buildFuncParameters(){let e=this.program.getSignature().toInputJSONSchema();return this._parentSharedFields.size>0?_h(e,this._parentSharedFields):e}};function cd(o,e){if(e.length===0)throw new Error(`${o}() requires at least one argument`);if(o==="ask_clarification"){if(e.length!==1)throw new Error("ask_clarification() requires exactly one argument");return{type:o,args:[yd(e[0])]}}return{type:o,args:e}}function yu(o){return!!o&&typeof o=="object"&&!Array.isArray(o)&&Object.getPrototypeOf(o)===Object.prototype}function go(o){return typeof o=="string"&&o.trim().length>0}function eh(o){if(go(o))return o;if(!yu(o))throw new Error("ask_clarification() choice entries must be non-empty strings or objects with a non-empty label");if(!go(o.label))throw new Error("ask_clarification() choice objects require a non-empty label");if(o.value!==void 0&&!go(o.value))throw new Error("ask_clarification() choice object values must be non-empty strings");return{label:o.label,...o.value!==void 0?{value:o.value}:{}}}function yd(o){if(go(o))return o;if(!yu(o))throw new Error("ask_clarification() requires a non-empty string or an object payload");if(!go(o.question))throw new Error("ask_clarification() object payload requires a non-empty question");let e=new Set(["text","number","date","single_choice","multiple_choice"]),t;if(o.type===void 0)t=Array.isArray(o.choices)&&o.choices.length>0?"single_choice":void 0;else{if(typeof o.type!="string"||!e.has(o.type))throw new Error("ask_clarification() object payload type must be one of: text, number, date, single_choice, multiple_choice");t=o.type}let n=t==="single_choice"||t==="multiple_choice",r=o.choices;if(r!==void 0){if(!Array.isArray(r)||r.length===0)throw new Error("ask_clarification() choices must be a non-empty array when provided")}else if(n)throw new Error("ask_clarification() choice payloads require a non-empty choices array");return{...o,question:o.question,...t?{type:t}:{},...r?{choices:r.map(eh)}:{}}}function bd(o){let e=yd(o);return typeof e=="string"?{question:e,type:"text"}:{...e,type:e.type??(e.choices&&e.choices.length>0?"single_choice":"text")}}function th(o){return typeof structuredClone=="function"?structuredClone(o):JSON.parse(JSON.stringify(o))}function nh(o,e){return!e.has(o)&&!Nf.has(o)&&_f.test(o)}function rh(o,e){if(o===void 0)return{};let t={context:o};if(!yu(o))return t;for(let[n,r]of Object.entries(o))nh(n,e)&&(t[n]=r);return t}function oh(o){if(o===null)return{type:"null"};if(Array.isArray(o))return{type:"array",ctor:"Array"};if(o instanceof Map)return{type:"map",ctor:"Map"};if(o instanceof Set)return{type:"set",ctor:"Set"};if(o instanceof Date)return{type:"date",ctor:"Date"};if(o instanceof Error)return{type:"error",ctor:typeof o.name=="string"&&o.name.trim()?o.name:"Error"};let e=typeof o;return e!=="object"?{type:e}:{type:"object",ctor:o&&o.constructor&&typeof o.constructor?.name=="string"?o.constructor?.name:void 0}}function mo(o){if(o===null)return"null";if(o===void 0)return"undefined";let e=typeof o;if(e==="string")return JSON.stringify(bu(o,40));if(e==="number"||e==="boolean"||e==="bigint"||e==="symbol")return String(o);if(e==="function")return`[function ${o.name||"anonymous"}]`;if(Array.isArray(o))return`[array(${o.length})]`;if(o instanceof Date)return Number.isFinite(o.getTime())?o.toISOString():String(o);if(o instanceof Error)return`${o.name||"Error"}: ${o.message||""}`;if(o instanceof Map)return`[map(${o.size})]`;if(o instanceof Set)return`[set(${o.size})]`;let t=o&&o.constructor&&typeof o.constructor?.name=="string"?o.constructor?.name:"";return t&&t!=="Object"?`[${t}]`:"[object]"}function sh(o,e,t){if(e==="array"&&Array.isArray(o))return`[${o.slice(0,3).map(r=>mo(r)).join(", ")}${o.length>3?", ...":""}]`;if(e==="map"&&o instanceof Map){let n=[...o.entries()].slice(0,3).map(([r,s])=>`${mo(r)} => ${mo(s)}`);return`Map(${o.size}) {${n.join(", ")}${o.size>3?", ...":""}}`}if(e==="set"&&o instanceof Set){let n=[...o.values()].slice(0,5).map(r=>mo(r));return`Set(${o.size}) {${n.join(", ")}${o.size>5?", ...":""}}`}if(e==="object"&&o&&typeof o=="object"){let n=Object.keys(o),r=n.slice(0,4);return`${t&&t!=="Object"?`${t} `:""}{${r.join(", ")}${n.length>r.length?", ...":""}}`}return mo(o)}function ih(o,e){if(e==="string"&&typeof o=="string")return`${o.length} chars`;if(e==="array"&&Array.isArray(o))return`${o.length} items`;if((e==="map"||e==="set")&&o instanceof Map)return`${o.size} items`;if((e==="map"||e==="set")&&o instanceof Set)return`${o.size} items`;if(e==="object"&&o&&typeof o=="object")return`${Object.keys(o).length} keys`}function ah(o){if(o.length===0)return;let e=o[0];if(e&&typeof e=="object"&&!Array.isArray(e)){let t=Object.keys(e).slice(0,8);if(t.length>0)return t.join(", ")}}function uh(o){return Object.entries(o).map(([e,t])=>{try{let n=oh(t),r=ih(t,n.type),s=sh(t,n.type,n.ctor),i;n.type==="array"&&Array.isArray(t)&&(i=ah(t));let a=s?bu(s,40):void 0,u=i?a?`${a} \u2014 element keys: ${i}`:`element keys: ${i}`:a;return{name:e,type:n.type,...n.ctor?{ctor:n.ctor}:{},...r?{size:r}:{},...u?{preview:u}:{}}}catch{return{name:e,type:"unknown",preview:"[unavailable]"}}})}function ch(o,e){let t=uh(o),n=hu(t,new Map,e),r=e?.budgetRemaining!==void 0&&e?.budgetTotal!==void 0?`
1382
1382
  Sub-query budget: ${e.budgetRemaining}/${e.budgetTotal} remaining`:"";return`Explore with code \u2014 do not assume values from these previews.
1383
- ${n}${r}`}function ud(o,e){return o instanceof pt?dt(`[CLARIFICATION] ${o.question}`,e):dt(`[ABORTED] ${o.message}`,e)}function gr(o){return uh(o)}function xh(o){return o.map(e=>({turn:e.turn,code:e.code,output:e.output,actorFieldsOutput:e.actorFieldsOutput,tags:[...e.tags],...e.summary?{summary:e.summary}:{},...e.producedVars?{producedVars:[...e.producedVars]}:{},...e.referencedVars?{referencedVars:[...e.referencedVars]}:{},...e.stateDelta?{stateDelta:e.stateDelta}:{},...e.stepKind?{stepKind:e.stepKind}:{},...e.replayMode?{replayMode:e.replayMode}:{},...e.rank!==void 0?{rank:e.rank}:{},...e.tombstone?{tombstone:e.tombstone}:{}}))}function Ah(o){return(o??[]).map(e=>({turn:e.turn,code:e.code,output:e.output,actorFieldsOutput:e.actorFieldsOutput,tags:[...e.tags],...e.summary?{summary:e.summary}:{},...e.producedVars?{producedVars:[...e.producedVars]}:{},...e.referencedVars?{referencedVars:[...e.referencedVars]}:{},...e.stateDelta?{stateDelta:e.stateDelta}:{},...e.stepKind?{stepKind:e.stepKind}:{},...e.replayMode?{replayMode:e.replayMode}:{},...e.rank!==void 0?{rank:e.rank}:{},...e.tombstone?{tombstone:e.tombstone}:{}}))}function yh(o){return Object.fromEntries([...o.entries()].map(([e,t])=>[e,{...t}]))}function bh(o,e){let t=o.filter(r=>r.restorable===!1).length,n=["Runtime Restore:","- Runtime state was restored from a previous call.","- Continue from restored values unless recomputation is actually needed."];return e?.includeLiveRuntimeState!==!1?n.splice(2,0,"- Live Runtime State below reflects the restored bindings."):n.splice(2,0,"- Live Runtime State rendering is disabled for this run, but the restored bindings are available in the runtime session."),t>0&&n.push(`- ${t} prior value${t===1?" was":"s were"} snapshot-only and could not be restored.`),n.join(`
1384
- `)}function Th(o){return new Map(Object.entries(o??{}).map(([e,t])=>[e,{...t}]))}function Ch(o,e){let t=new Map;for(let[n,r]of e.entries())t.set(n,{...r});for(let[n,r]of o.entries())t.set(n,{...r});return t}function Ad(o,e){let t=typeof o=="string"?Ne.create(o):o,{ai:n,judgeAI:r,agentIdentity:s,...i}=e;return new ho({ai:n,judgeAI:r,agentIdentity:s,signature:t},i)}function Ih(o){return o instanceof rt&&o.status>=500&&o.status<600?!0:o instanceof Je||o instanceof gt}function dt(o,e){return o.length<=e?o:`${o.slice(0,e)}
1385
- ...[truncated ${o.length-e} chars]`}function xu(o,e){return e<=0?"":o.length<=e?o:e<=3?o.slice(0,e):`${o.slice(0,e-3)}...`}function wh(o){if(!o||typeof o!="object")return!1;let e=o;return typeof e.name=="string"&&typeof e.type=="string"&&(e.ctor===void 0||typeof e.ctor=="string")&&(e.size===void 0||typeof e.size=="string")&&(e.preview===void 0||typeof e.preview=="string")&&(e.restorable===void 0||typeof e.restorable=="boolean")}function Rh(o){let e=o.trim();if(!(!e||e[0]!=="{"&&e[0]!=="["))try{let t=JSON.parse(e),n=Array.isArray(t)?t:t&&typeof t=="object"&&Array.isArray(t.entries)?t.entries:void 0;return n?n.filter(wh):void 0}catch{return}}function yd(o,e){let t=e?.maxEntries&&e.maxEntries>0?e.maxEntries:void 0,n=e?.maxChars&&e.maxChars>0?e.maxChars:void 0,r=t?o.slice(0,t):[...o];if(!n)return r.join(`
1386
- `);let s=[],i=0;for(let a of r){let u=s.length>0?1:0,c=n-i-u;if(c<=0)break;if(a.length<=c){s.push(a),i+=u+a.length;continue}s.push(xu(a,c)),i=n;break}return s.join(`
1387
- `)}function vh(o,e){let t=o.split(`
1388
- `).map(n=>n.trim()).filter(Boolean);return yd(t,e)}function cd(o,e){let t=0;return e&&(t+=1e6,t+=e.createdTurn*100,t+=(e.lastReadTurn??e.createdTurn)*1e4,e.source&&(t+=25)),o.type==="accessor"?t-=100:o.type==="function"&&(t-=10),t}function Sh(o){let e=o.type;return o.type==="object"&&o.ctor&&o.ctor!=="Object"?e=`object<${o.ctor}>`:o.type==="error"&&o.ctor&&o.ctor!=="Error"&&(e=`error<${o.ctor}>`),o.size&&(e+=` (${o.size})`),e}function kh(o){if(!o)return"";let e=[`from t${o.createdTurn}${o.source?` via ${o.source}`:""}`];return o.lastReadTurn!==void 0&&o.lastReadTurn>o.createdTurn&&e.push(`read t${o.lastReadTurn}`),` [${e.join("; ")}]`}function mu(o,e,t){let n=[...o].sort((r,s)=>{let i=cd(r,e.get(r.name));return cd(s,e.get(s.name))-i||r.name.localeCompare(s.name)}).map(r=>{let s=r.preview?` = ${r.preview}`:"",i=kh(e.get(r.name)),a="restorable"in r&&r.restorable===!1?" [snapshot only]":"";return`${r.name}: ${Sh(r)}${s}${i}${a}`});return n.length===0?"(no user variables)":yd(n,t)}function ii(o,e){if(o===void 0)return"(no output)";if(typeof o=="string")return dt(o||"(no output)",e);try{return dt(JSON.stringify(o,null,2),e)}catch{return dt(String(o),e)}}function ai(o,e){let t=o,n=t?.name??"Error",r=t?.message??String(o),s=[`${n}: ${r}`];if(t?.data!==void 0)try{s.push(`Data: ${JSON.stringify(t.data,null,2)}`)}catch{s.push(`Data: ${String(t.data)}`)}if(t?.cause!==void 0){let i=(a,u)=>{if(u>4)return"[cause chain truncated]";let c=a,l=c?.name??"Error",p=c?.message??String(a),d=[`${l}: ${p}`];if(c?.data!==void 0)try{d.push(`Data: ${JSON.stringify(c.data,null,2)}`)}catch{d.push(`Data: ${String(c.data)}`)}return c?.cause!==void 0&&d.push(`Caused by: ${i(c.cause,u+1)}`),d.join(`
1383
+ ${n}${r}`}function ld(o,e){return o instanceof pt?dt(`[CLARIFICATION] ${o.question}`,e):dt(`[ABORTED] ${o.message}`,e)}function fr(o){return th(o)}function lh(o){return o.map(e=>({turn:e.turn,code:e.code,output:e.output,actorFieldsOutput:e.actorFieldsOutput,tags:[...e.tags],...e.summary?{summary:e.summary}:{},...e.producedVars?{producedVars:[...e.producedVars]}:{},...e.referencedVars?{referencedVars:[...e.referencedVars]}:{},...e.stateDelta?{stateDelta:e.stateDelta}:{},...e.stepKind?{stepKind:e.stepKind}:{},...e.replayMode?{replayMode:e.replayMode}:{},...e.rank!==void 0?{rank:e.rank}:{},...e.tombstone?{tombstone:e.tombstone}:{}}))}function ph(o){return(o??[]).map(e=>({turn:e.turn,code:e.code,output:e.output,actorFieldsOutput:e.actorFieldsOutput,tags:[...e.tags],...e.summary?{summary:e.summary}:{},...e.producedVars?{producedVars:[...e.producedVars]}:{},...e.referencedVars?{referencedVars:[...e.referencedVars]}:{},...e.stateDelta?{stateDelta:e.stateDelta}:{},...e.stepKind?{stepKind:e.stepKind}:{},...e.replayMode?{replayMode:e.replayMode}:{},...e.rank!==void 0?{rank:e.rank}:{},...e.tombstone?{tombstone:e.tombstone}:{}}))}function dh(o){return Object.fromEntries([...o.entries()].map(([e,t])=>[e,{...t}]))}function mh(o,e){let t=o.filter(r=>r.restorable===!1).length,n=["Runtime Restore:","- Runtime state was restored from a previous call.","- Continue from restored values unless recomputation is actually needed."];return e?.includeLiveRuntimeState!==!1?n.splice(2,0,"- Live Runtime State below reflects the restored bindings."):n.splice(2,0,"- Live Runtime State rendering is disabled for this run, but the restored bindings are available in the runtime session."),t>0&&n.push(`- ${t} prior value${t===1?" was":"s were"} snapshot-only and could not be restored.`),n.join(`
1384
+ `)}function gh(o){return new Map(Object.entries(o??{}).map(([e,t])=>[e,{...t}]))}function fh(o,e){let t=new Map;for(let[n,r]of e.entries())t.set(n,{...r});for(let[n,r]of o.entries())t.set(n,{...r});return t}function Cd(o,e){let t=typeof o=="string"?_e.create(o):o,{ai:n,judgeAI:r,agentIdentity:s,...i}=e;return new fo({ai:n,judgeAI:r,agentIdentity:s,signature:t},i)}function hh(o){return o instanceof rt&&o.status>=500&&o.status<600?!0:o instanceof Je||o instanceof gt}function dt(o,e){return o.length<=e?o:`${o.slice(0,e)}
1385
+ ...[truncated ${o.length-e} chars]`}function bu(o,e){return e<=0?"":o.length<=e?o:e<=3?o.slice(0,e):`${o.slice(0,e-3)}...`}function xh(o){if(!o||typeof o!="object")return!1;let e=o;return typeof e.name=="string"&&typeof e.type=="string"&&(e.ctor===void 0||typeof e.ctor=="string")&&(e.size===void 0||typeof e.size=="string")&&(e.preview===void 0||typeof e.preview=="string")&&(e.restorable===void 0||typeof e.restorable=="boolean")}function Ah(o){let e=o.trim();if(!(!e||e[0]!=="{"&&e[0]!=="["))try{let t=JSON.parse(e),n=Array.isArray(t)?t:t&&typeof t=="object"&&Array.isArray(t.entries)?t.entries:void 0;return n?n.filter(xh):void 0}catch{return}}function Id(o,e){let t=e?.maxEntries&&e.maxEntries>0?e.maxEntries:void 0,n=e?.maxChars&&e.maxChars>0?e.maxChars:void 0,r=t?o.slice(0,t):[...o];if(!n)return r.join(`
1386
+ `);let s=[],i=0;for(let a of r){let u=s.length>0?1:0,c=n-i-u;if(c<=0)break;if(a.length<=c){s.push(a),i+=u+a.length;continue}s.push(bu(a,c)),i=n;break}return s.join(`
1387
+ `)}function yh(o,e){let t=o.split(`
1388
+ `).map(n=>n.trim()).filter(Boolean);return Id(t,e)}function pd(o,e){let t=0;return e&&(t+=1e6,t+=e.createdTurn*100,t+=(e.lastReadTurn??e.createdTurn)*1e4,e.source&&(t+=25)),o.type==="accessor"?t-=100:o.type==="function"&&(t-=10),t}function bh(o){let e=o.type;return o.type==="object"&&o.ctor&&o.ctor!=="Object"?e=`object<${o.ctor}>`:o.type==="error"&&o.ctor&&o.ctor!=="Error"&&(e=`error<${o.ctor}>`),o.size&&(e+=` (${o.size})`),e}function Ch(o){if(!o)return"";let e=[`from t${o.createdTurn}${o.source?` via ${o.source}`:""}`];return o.lastReadTurn!==void 0&&o.lastReadTurn>o.createdTurn&&e.push(`read t${o.lastReadTurn}`),` [${e.join("; ")}]`}function hu(o,e,t){let n=[...o].sort((r,s)=>{let i=pd(r,e.get(r.name));return pd(s,e.get(s.name))-i||r.name.localeCompare(s.name)}).map(r=>{let s=r.preview?` = ${r.preview}`:"",i=Ch(e.get(r.name)),a="restorable"in r&&r.restorable===!1?" [snapshot only]":"";return`${r.name}: ${bh(r)}${s}${i}${a}`});return n.length===0?"(no user variables)":Id(n,t)}function ii(o,e){if(o===void 0)return"(no output)";if(typeof o=="string")return dt(o||"(no output)",e);try{return dt(JSON.stringify(o,null,2),e)}catch{return dt(String(o),e)}}function ai(o,e){let t=o,n=t?.name??"Error",r=t?.message??String(o),s=[`${n}: ${r}`];if(t?.data!==void 0)try{s.push(`Data: ${JSON.stringify(t.data,null,2)}`)}catch{s.push(`Data: ${String(t.data)}`)}if(t?.cause!==void 0){let i=(a,u)=>{if(u>4)return"[cause chain truncated]";let c=a,l=c?.name??"Error",p=c?.message??String(a),d=[`${l}: ${p}`];if(c?.data!==void 0)try{d.push(`Data: ${JSON.stringify(c.data,null,2)}`)}catch{d.push(`Data: ${String(c.data)}`)}return c?.cause!==void 0&&d.push(`Caused by: ${i(c.cause,u+1)}`),d.join(`
1389
1389
  `)};s.push(`Caused by: ${i(t.cause,1)}`)}return dt(s.join(`
1390
- `),e)}function ld(o){let e=Nt(o);return/\bfinal\s*\(/.test(e)||/\bask_clarification\s*\(/.test(e)}function pd(o){return o&&(typeof o=="object"||typeof o=="function")&&"then"in o&&typeof o.then=="function"?!0:typeof o=="string"&&o.trim()==="[object Promise]"}function dd(o){return o instanceof Error&&o.message==="Session is closed"}function Oh(o){return o instanceof Error&&o.message==="Execution timed out"}function Eh(o){return o.startsWith("[ERROR]")||o.startsWith(ui)?!0:/^(AggregateError|Error|EvalError|RangeError|ReferenceError|SyntaxError|TypeError|URIError): /.test(o)}function Mh(o,e){if(e.kind==="threshold")return Fh(o)<=e.promptMaxChars?o:void 0;if(typeof o!="string")return;let t=e.keepInPromptChars;if(o.length<=t)return o;let n=o.length-t;if(e.reverseTruncate){let s=t>0?o.slice(-t):"";return`[truncated ${n} chars]...${s}`}return`${t>0?o.slice(0,t):""}...[truncated ${n} chars]`}function Ph(o,e,t){return e.kind==="threshold"?t?`inline (<=${e.promptMaxChars} chars)`:`runtime-only (>${e.promptMaxChars} chars)`:typeof o!="string"?"runtime-only (keepInPromptChars requires string)":t?o.length<=e.keepInPromptChars?`inline (<=${e.keepInPromptChars} chars)`:e.reverseTruncate?`inline-truncated(last ${e.keepInPromptChars} chars of ${o.length})`:`inline-truncated(first ${e.keepInPromptChars} chars of ${o.length})`:"runtime-only"}function Fh(o){if(typeof o=="string")return o.length;try{return JSON.stringify(o).length}catch{return String(o).length}}function _h(o,e,t){let n=new Set(e.map(a=>a.name)),r=new Set,s=[],i=new Map;for(let a of o){let u=typeof a=="string"?a:a.field;if(!n.has(u))throw new Error(`RLM contextField "${u}" not found in signature`);if(r.has(u))throw new Error(`Duplicate contextField "${u}"`);if(r.add(u),s.push(u),typeof a!="string"){let c=a.keepInPromptChars!==void 0,l=a.promptMaxChars!==void 0;if(c&&l)throw new Error(`contextField "${u}" cannot set both promptMaxChars and keepInPromptChars`);if("reverseTruncate"in a&&!c)throw new Error(`contextField "${u}" reverseTruncate requires keepInPromptChars`);if(c){let d=a.keepInPromptChars;if(!Number.isFinite(d)||d===void 0||d<0)throw new Error(`contextField "${u}" keepInPromptChars must be a finite number >= 0`);i.set(u,{kind:"truncate",keepInPromptChars:d,reverseTruncate:a.reverseTruncate===!0});continue}let p=a.promptMaxChars??t;if(!Number.isFinite(p)||p<0)throw new Error(`contextField "${u}" promptMaxChars must be a finite number >= 0`);i.set(u,{kind:"threshold",promptMaxChars:p})}}return{contextFieldNames:s,promptConfigByField:i}}function Nh(o,e){let t=[];for(let[n,r]of Object.entries(o)){let s=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),u=a===void 0?"runtime-only":Ph(r,a,e?.inlinedFields?.has(n)===!0);t.push(`- ${n}: type=${s}, size=${i}, prompt=${u}`)}return t.join(`
1391
- `)}async function Lh(o,e,t,n){if(o.length===0)return[];let r=new Array(o.length),s=0,i=Math.max(1,Math.min(e,o.length)),a=Array.from({length:i},async()=>{for(;;){if(n?.aborted)return;let u=s++;if(u>=o.length)return;let c=o[u];if(c===void 0)return;r[u]=await t(c,u)}});return await Promise.all(a),r}function $h(o){return o.includes("console.log")}function Dh(o){let e=Nt(o),t=/\bfinal\s*\(/.test(e),n=/\bask_clarification\s*\(/.test(e),r=Number(t)+Number(n),s=Uh(e);if(r>1)return"[POLICY] Use exactly one completion signal per turn: either final(...) or ask_clarification(...), not both.";if(r===1)return s.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(s.length===0)return"[POLICY] Non-final turns must include exactly one console.log(...) so the next turn can reason from its output.";if(s.length>1)return"[POLICY] Use exactly one console.log(...) per non-final turn, then stop.";let i=s[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 Uh(o){let e=o.matchAll(/\bconsole\s*\.\s*log\s*\(/g),t=[];for(let n of e){let r=n[0];if(r===void 0)continue;let s=n.index??-1;if(s<0)continue;let i=r.lastIndexOf("("),a=s+i,u=Gh(o,a);t.push({closeParenIndex:u})}return t}function Gh(o,e){if(e<0||o[e]!=="(")return;let t=0;for(let n=e;n<o.length;n++){let r=o[n];if(r==="(")t++;else if(r===")"&&(t--,t===0))return n}}function Bh(o,e){if(!o.properties||e.size===0)return o;let t=Object.fromEntries(Object.entries(o.properties).filter(([r])=>!e.has(r))),n=o.required?.filter(r=>!e.has(r));return{...o,properties:t,...n!==void 0?{required:n}:{}}}function jh(o,e){let t=o.trim(),r=e?.normalize??!0?Td(t):t;if(!r)throw new Error("Agent module namespace must contain letters or numbers");return r}function md(o){return Array.isArray(o.functions)}function pu(o,e){if(!o||o.length===0)return{functions:[],moduleMetadata:[]};let t=o.every(a=>md(a)),n=o.every(a=>!md(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:[...o],moduleMetadata:[]};let r=new Set,s=[],i=[];for(let a of o){let u=a.namespace.trim(),c=a.title.trim(),l=a.selectionCriteria?.trim()||void 0,p=a.description?.trim()||void 0;if(!u)throw new Error("Agent function group namespace must be a non-empty string");if(!c)throw new Error(`Agent function group "${u}" must define a non-empty title`);if(e.has(u))throw new Error(`Agent function namespace "${u}" conflicts with an AxAgent runtime global and is reserved`);if(r.has(u))throw new Error(`Duplicate agent function group namespace "${u}"`);if(a.functions.length===0)throw new Error(`Agent function group "${u}" must contain at least one function`);r.add(u),s.push({namespace:u,title:c,selectionCriteria:l,description:p});for(let d of a.functions){if("namespace"in d&&d.namespace!==void 0)throw new Error(`Grouped agent function "${u}.${d.name}" must not define namespace; use the parent group namespace instead`);i.push({...d,namespace:u})}}return{functions:i,moduleMetadata:s}}function gd(o,e){if(typeof o=="string"){let n=o.trim();if(n.length===0)throw new Error(`${e} must be a non-empty string`);return[n]}if(!Array.isArray(o))throw new Error(`${e} must be a string or string[]`);if(!o.every(n=>typeof n=="string"))throw new Error(`${e} must contain only strings`);let t=o.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 gu(o){let e=o.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 zh(o){let e=new Set(o);return e.has("object")&&e.has("array")&&e.has("string")&&e.has("number")&&e.has("boolean")&&e.has("null")}function xo(o){if(o.enum)return o.enum.map(n=>`"${n}"`).join(" | ");let e=gu(o);if(e.length===0)return"unknown";if(zh(e))return"any";let t=[...new Set(e)].map(n=>{if(n==="array"){let r=o.items?xo(o.items):"unknown";return r.includes(" | ")?`(${r})[]`:`${r}[]`}return n==="object"?o.properties&&Object.keys(o.properties).length>0?bd(o):"object":n});return t.length>1?t.join(" | "):t[0]??"unknown"}function bd(o,e){if(!o)return"{}";let t=!!o.properties&&Object.keys(o.properties).length>0,n=o.additionalProperties===!0;if(!t)return n?"{ [key: string]: unknown }":"{}";let r=new Set(o.required??[]),s=e?.respectRequired??!1,i=Object.entries(o.properties).map(([a,u])=>{let c=xo(u),l=s&&!r.has(a)?"?":"";return`${a}${l}: ${c}`});return o.additionalProperties===!0&&i.push("[key: string]: unknown"),`{ ${i.join(", ")} }`}function qh(o){let e=bd(o.parameters,{respectRequired:!0}),t=o.returns?`: Promise<${xo(o.returns)}>`:"";return`- \`${o.qualifiedName}(args: ${e})${t}\``}function fu(o,e="",t=!0){if(!o?.properties)return[];let n=new Set(o.required??[]),r=[];for(let[s,i]of Object.entries(o.properties)){let a=e?`${e}.${s}`:s,u=i.description?.trim();u&&r.push({name:a,type:xo(i),required:t?n.has(s):void 0,description:u});let c=gu(i);if(c.includes("object")&&i.properties&&r.push(...fu(i,a,!1)),c.includes("array")&&i.items){let l=i.items.description?.trim(),p=`${a}[]`;l&&r.push({name:p,type:xo(i.items),description:l}),gu(i.items).includes("object")&&i.items.properties&&r.push(...fu(i.items,p,!1))}}return r}function Hh(o){let e=fu(o);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(`
1392
- `)}function Wh(o){return!o||o.length===0?void 0:["#### Examples",o.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(`
1390
+ `),e)}function dd(o){let e=jt(o);return/\bfinal\s*\(/.test(e)||/\bask_clarification\s*\(/.test(e)}function md(o){return o&&(typeof o=="object"||typeof o=="function")&&"then"in o&&typeof o.then=="function"?!0:typeof o=="string"&&o.trim()==="[object Promise]"}function gd(o){return o instanceof Error&&o.message==="Session is closed"}function Ih(o){return o instanceof Error&&o.message==="Execution timed out"}function Th(o){return o.startsWith("[ERROR]")||o.startsWith(ui)?!0:/^(AggregateError|Error|EvalError|RangeError|ReferenceError|SyntaxError|TypeError|URIError): /.test(o)}function wh(o,e){if(e.kind==="threshold")return vh(o)<=e.promptMaxChars?o:void 0;if(typeof o!="string")return;let t=e.keepInPromptChars;if(o.length<=t)return o;let n=o.length-t;if(e.reverseTruncate){let s=t>0?o.slice(-t):"";return`[truncated ${n} chars]...${s}`}return`${t>0?o.slice(0,t):""}...[truncated ${n} chars]`}function Rh(o,e,t){return e.kind==="threshold"?t?`inline (<=${e.promptMaxChars} chars)`:`runtime-only (>${e.promptMaxChars} chars)`:typeof o!="string"?"runtime-only (keepInPromptChars requires string)":t?o.length<=e.keepInPromptChars?`inline (<=${e.keepInPromptChars} chars)`:e.reverseTruncate?`inline-truncated(last ${e.keepInPromptChars} chars of ${o.length})`:`inline-truncated(first ${e.keepInPromptChars} chars of ${o.length})`:"runtime-only"}function vh(o){if(typeof o=="string")return o.length;try{return JSON.stringify(o).length}catch{return String(o).length}}function Sh(o,e,t){let n=new Set(e.map(a=>a.name)),r=new Set,s=[],i=new Map;for(let a of o){let u=typeof a=="string"?a:a.field;if(!n.has(u))throw new Error(`RLM contextField "${u}" not found in signature`);if(r.has(u))throw new Error(`Duplicate contextField "${u}"`);if(r.add(u),s.push(u),typeof a!="string"){let c=a.keepInPromptChars!==void 0,l=a.promptMaxChars!==void 0;if(c&&l)throw new Error(`contextField "${u}" cannot set both promptMaxChars and keepInPromptChars`);if("reverseTruncate"in a&&!c)throw new Error(`contextField "${u}" reverseTruncate requires keepInPromptChars`);if(c){let d=a.keepInPromptChars;if(!Number.isFinite(d)||d===void 0||d<0)throw new Error(`contextField "${u}" keepInPromptChars must be a finite number >= 0`);i.set(u,{kind:"truncate",keepInPromptChars:d,reverseTruncate:a.reverseTruncate===!0});continue}let p=a.promptMaxChars??t;if(!Number.isFinite(p)||p<0)throw new Error(`contextField "${u}" promptMaxChars must be a finite number >= 0`);i.set(u,{kind:"threshold",promptMaxChars:p})}}return{contextFieldNames:s,promptConfigByField:i}}function kh(o,e){let t=[];for(let[n,r]of Object.entries(o)){let s=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),u=a===void 0?"runtime-only":Rh(r,a,e?.inlinedFields?.has(n)===!0);t.push(`- ${n}: type=${s}, size=${i}, prompt=${u}`)}return t.join(`
1391
+ `)}async function Oh(o,e,t,n){if(o.length===0)return[];let r=new Array(o.length),s=0,i=Math.max(1,Math.min(e,o.length)),a=Array.from({length:i},async()=>{for(;;){if(n?.aborted)return;let u=s++;if(u>=o.length)return;let c=o[u];if(c===void 0)return;r[u]=await t(c,u)}});return await Promise.all(a),r}function Eh(o){return o.includes("console.log")}function Mh(o){let e=jt(o),t=/\bfinal\s*\(/.test(e),n=/\bask_clarification\s*\(/.test(e),r=Number(t)+Number(n),s=Ph(e);if(r>1)return"[POLICY] Use exactly one completion signal per turn: either final(...) or ask_clarification(...), not both.";if(r===1)return s.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(s.length===0)return"[POLICY] Non-final turns must include exactly one console.log(...) so the next turn can reason from its output.";if(s.length>1)return"[POLICY] Use exactly one console.log(...) per non-final turn, then stop.";let i=s[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 Ph(o){let e=o.matchAll(/\bconsole\s*\.\s*log\s*\(/g),t=[];for(let n of e){let r=n[0];if(r===void 0)continue;let s=n.index??-1;if(s<0)continue;let i=r.lastIndexOf("("),a=s+i,u=Fh(o,a);t.push({closeParenIndex:u})}return t}function Fh(o,e){if(e<0||o[e]!=="(")return;let t=0;for(let n=e;n<o.length;n++){let r=o[n];if(r==="(")t++;else if(r===")"&&(t--,t===0))return n}}function _h(o,e){if(!o.properties||e.size===0)return o;let t=Object.fromEntries(Object.entries(o.properties).filter(([r])=>!e.has(r))),n=o.required?.filter(r=>!e.has(r));return{...o,properties:t,...n!==void 0?{required:n}:{}}}function Nh(o,e){let t=o.trim(),r=e?.normalize??!0?wd(t):t;if(!r)throw new Error("Agent module namespace must contain letters or numbers");return r}function fd(o){return Array.isArray(o.functions)}function gu(o,e){if(!o||o.length===0)return{functions:[],moduleMetadata:[]};let t=o.every(a=>fd(a)),n=o.every(a=>!fd(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:[...o],moduleMetadata:[]};let r=new Set,s=[],i=[];for(let a of o){let u=a.namespace.trim(),c=a.title.trim(),l=a.selectionCriteria?.trim()||void 0,p=a.description?.trim()||void 0;if(!u)throw new Error("Agent function group namespace must be a non-empty string");if(!c)throw new Error(`Agent function group "${u}" must define a non-empty title`);if(e.has(u))throw new Error(`Agent function namespace "${u}" conflicts with an AxAgent runtime global and is reserved`);if(r.has(u))throw new Error(`Duplicate agent function group namespace "${u}"`);if(a.functions.length===0)throw new Error(`Agent function group "${u}" must contain at least one function`);r.add(u),s.push({namespace:u,title:c,selectionCriteria:l,description:p});for(let d of a.functions){if("namespace"in d&&d.namespace!==void 0)throw new Error(`Grouped agent function "${u}.${d.name}" must not define namespace; use the parent group namespace instead`);i.push({...d,namespace:u})}}return{functions:i,moduleMetadata:s}}function hd(o,e){if(typeof o=="string"){let n=o.trim();if(n.length===0)throw new Error(`${e} must be a non-empty string`);return[n]}if(!Array.isArray(o))throw new Error(`${e} must be a string or string[]`);if(!o.every(n=>typeof n=="string"))throw new Error(`${e} must contain only strings`);let t=o.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 xu(o){let e=o.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 $h(o){let e=new Set(o);return e.has("object")&&e.has("array")&&e.has("string")&&e.has("number")&&e.has("boolean")&&e.has("null")}function ho(o){if(o.enum)return o.enum.map(n=>`"${n}"`).join(" | ");let e=xu(o);if(e.length===0)return"unknown";if($h(e))return"any";let t=[...new Set(e)].map(n=>{if(n==="array"){let r=o.items?ho(o.items):"unknown";return r.includes(" | ")?`(${r})[]`:`${r}[]`}return n==="object"?o.properties&&Object.keys(o.properties).length>0?Td(o):"object":n});return t.length>1?t.join(" | "):t[0]??"unknown"}function Td(o,e){if(!o)return"{}";let t=!!o.properties&&Object.keys(o.properties).length>0,n=o.additionalProperties===!0;if(!t)return n?"{ [key: string]: unknown }":"{}";let r=new Set(o.required??[]),s=e?.respectRequired??!1,i=Object.entries(o.properties).map(([a,u])=>{let c=ho(u),l=s&&!r.has(a)?"?":"";return`${a}${l}: ${c}`});return o.additionalProperties===!0&&i.push("[key: string]: unknown"),`{ ${i.join(", ")} }`}function Lh(o){let e=Td(o.parameters,{respectRequired:!0}),t=o.returns?`: Promise<${ho(o.returns)}>`:"";return`- \`${o.qualifiedName}(args: ${e})${t}\``}function Au(o,e="",t=!0){if(!o?.properties)return[];let n=new Set(o.required??[]),r=[];for(let[s,i]of Object.entries(o.properties)){let a=e?`${e}.${s}`:s,u=i.description?.trim();u&&r.push({name:a,type:ho(i),required:t?n.has(s):void 0,description:u});let c=xu(i);if(c.includes("object")&&i.properties&&r.push(...Au(i,a,!1)),c.includes("array")&&i.items){let l=i.items.description?.trim(),p=`${a}[]`;l&&r.push({name:p,type:ho(i.items),description:l}),xu(i.items).includes("object")&&i.items.properties&&r.push(...Au(i.items,p,!1))}}return r}function Dh(o){let e=Au(o);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(`
1392
+ `)}function Uh(o){return!o||o.length===0?void 0:["#### Examples",o.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(`
1393
1393
  `)}).join(`
1394
1394
 
1395
1395
  `)].join(`
1396
- `)}function Kh(o,e,t){return o.map(n=>{let r=[...e.get(n)??[]].map(c=>c.split(".").pop()??c).sort((c,l)=>c.localeCompare(l)),s=r.length>0,i=s?t.get(n):void 0,a=s?r.map(c=>`- \`${c}\``).join(`
1396
+ `)}function Gh(o,e,t){return o.map(n=>{let r=[...e.get(n)??[]].map(c=>c.split(".").pop()??c).sort((c,l)=>c.localeCompare(l)),s=r.length>0,i=s?t.get(n):void 0,a=s?r.map(c=>`- \`${c}\``).join(`
1397
1397
  `):`- Error: module \`${n}\` does not exist.`,u=[`### Module \`${n}\``];return i&&(u.push(`**${i.title}**`),i.description&&u.push(i.description)),u.push(a),u.join(`
1398
1398
  `)}).join(`
1399
1399
 
1400
- `)}function Vh(o,e){return o.map(t=>{let n=t.includes(".")?t:`utils.${t}`,r=e.get(n);return r?[`### \`${n}\``,r.description,qh({qualifiedName:n,parameters:r.parameters,returns:r.returns}),Hh(r.parameters),Wh(r.examples)].filter(s=>!!s).join(`
1400
+ `)}function jh(o,e){return o.map(t=>{let n=t.includes(".")?t:`utils.${t}`,r=e.get(n);return r?[`### \`${n}\``,r.description,Lh({qualifiedName:n,parameters:r.parameters,returns:r.returns}),Dh(r.parameters),Uh(r.examples)].filter(s=>!!s).join(`
1401
1401
  `):`### \`${n}\`
1402
1402
  - Not found.`}).join(`
1403
1403
 
1404
- `)}function Td(o){return o.split(/[^a-zA-Z0-9]/).map((n,r)=>{let s=n.toLowerCase();return r>0&&s&&s[0]?s[0].toUpperCase()+s.slice(1):s}).join("")}var Cd=(o,e)=>{let t=e?.maxHops??3,n=e?.qualityThreshold??.8,r=e?.maxIterations??2,s=e?.qualityTarget??.85,i=e?.disableQualityHealing??!1;return zs({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:s,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 u=a.queryGeneratorResult?.searchQuery||a.searchQuery||a.originalQuestion,c=await o(u);return{...a,retrievalResult:{retrievedDocument:c,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 u=a.currentQueries||[],c=u.length>0?await Promise.all(u.filter(Boolean).map(l=>o(l))):[];return{...a,retrievalResults:c}}).execute("evidenceSynthesizer",a=>{let u=Array.isArray(a.allEvidence)?a.allEvidence:[],c=Array.isArray(a.retrievalResults)?a.retrievalResults:[],l=[...u,...c].filter(Boolean);return{collectedEvidence:l.length>0?l:["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 u=(a.accumulatedContext||"").toString().trim();if(u.length>0)return u;let c=(a.synthesizedEvidence||"").toString().trim();if(c.length>0)return c;let p=(Array.isArray(a.allEvidence)?a.allEvidence.filter(Boolean).join(`
1405
- `):"").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 u=a.currentIssues||[],c=u.length>0?`${a.originalQuestion} addressing issues: ${u.join(", ")}`:`${a.originalQuestion} quality improvement`,l=await o(c);return{...a,healingResult:{healingDocument:l}}}).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 Md(Jh);})();
1404
+ `)}function wd(o){return o.split(/[^a-zA-Z0-9]/).map((n,r)=>{let s=n.toLowerCase();return r>0&&s&&s[0]?s[0].toUpperCase()+s.slice(1):s}).join("")}var Rd=(o,e)=>{let t=e?.maxHops??3,n=e?.qualityThreshold??.8,r=e?.maxIterations??2,s=e?.qualityTarget??.85,i=e?.disableQualityHealing??!1;return zs({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:s,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 u=a.queryGeneratorResult?.searchQuery||a.searchQuery||a.originalQuestion,c=await o(u);return{...a,retrievalResult:{retrievedDocument:c,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 u=a.currentQueries||[],c=u.length>0?await Promise.all(u.filter(Boolean).map(l=>o(l))):[];return{...a,retrievalResults:c}}).execute("evidenceSynthesizer",a=>{let u=Array.isArray(a.allEvidence)?a.allEvidence:[],c=Array.isArray(a.retrievalResults)?a.retrievalResults:[],l=[...u,...c].filter(Boolean);return{collectedEvidence:l.length>0?l:["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 u=(a.accumulatedContext||"").toString().trim();if(u.length>0)return u;let c=(a.synthesizedEvidence||"").toString().trim();if(c.length>0)return c;let p=(Array.isArray(a.allEvidence)?a.allEvidence.filter(Boolean).join(`
1405
+ `):"").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 u=a.currentIssues||[],c=u.length>0?`${a.originalQuestion} addressing issues: ${u.join(", ")}`:`${a.originalQuestion} quality improvement`,l=await o(c);return{...a,healingResult:{healingDocument:l}}}).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 _d(Bh);})();
1406
1406
  //# sourceMappingURL=index.global.js.map