@ax-llm/ax 19.0.18 → 19.0.19

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.cjs CHANGED
@@ -712,7 +712,7 @@ ${Ie}`)}if(T?.data!==void 0&&W.push(`Data: ${he(T.data)}`),T?.cause!==void 0){le
712
712
  `)};W.push(`Caused by: ${Y(T.cause,1)}`)}return W.join(`
713
713
  `)},G=new Map,j=0,ee=o,re=!1,V=[],pe=A=>{if(!A||typeof A!="object"||Array.isArray(A))return!1;let w=Object.getPrototypeOf(A);return w===Object.prototype||w===null},be=A=>typeof A=="string"&&A.trim().length>0,ve=A=>{if(!be(A)){if(!pe(A))throw new Error("ask_clarification() choice entries must be non-empty strings or objects with a non-empty label");if(!be(A.label))throw new Error("ask_clarification() choice objects require a non-empty label");if(A.value!==void 0&&!be(A.value))throw new Error("ask_clarification() choice object values must be non-empty strings")}},Oe=A=>{if(be(A))return;if(!pe(A))throw new Error("ask_clarification() requires a non-empty string or an object payload");if(!be(A.question))throw new Error("ask_clarification() object payload requires a non-empty question");let w=new Set(["text","number","date","single_choice","multiple_choice"]),S;if(A.type===void 0)S=Array.isArray(A.choices)&&A.choices.length>0?"single_choice":void 0;else{if(typeof A.type!="string"||!w.has(A.type))throw new Error("ask_clarification() object payload type must be one of: text, number, date, single_choice, multiple_choice");S=A.type}let T=S==="single_choice"||S==="multiple_choice",$=A.choices;if($!==void 0){if(!Array.isArray($)||$.length===0)throw new Error("ask_clarification() choices must be a non-empty array when provided");for(let q of $)ve(q)}else if(T)throw new Error("ask_clarification() choice payloads require a non-empty choices array")},se=(A,w)=>{if(A==="final"){if(w.length===0)throw new Error("final() requires at least one argument");return}if(A==="ask_clarification"){if(w.length!==1)throw new Error("ask_clarification() requires exactly one argument");Oe(w[0])}},te=A=>{if(A==="final"||A==="ask_clarification")return A;let S=/^fn_\d+_(.+)$/.exec(A)?.[1];if(S==="final"||S==="ask_clarification")return S},Q=A=>(...w)=>{let S=te(A);S&&se(S,w);let T=++j,$=!1,q=new Promise((ae,Ie)=>{G.set(T,{resolve:ae,reject:Ie}),g({type:"fn-call",id:T,name:A,args:w})}),W=q.then.bind(q),z=q.catch.bind(q),Y=q.finally.bind(q),fe=()=>{$=!0},_e=new Proxy(q,{get(ae,Ie,Ne){return Ie==="then"?(...ke)=>(fe(),W(...ke)):Ie==="catch"?(...ke)=>(fe(),z(...ke)):Ie==="finally"?(...ke)=>(fe(),Y(...ke)):Reflect.get(ae,Ie,Ne)}});return q.catch(ae=>{$||V.push(ae)}),_e},Ce=async()=>{for(let A=0;A<50&&G.size>0;A+=1)await new Promise(w=>{setTimeout(w,0)})},ge=A=>{if(!A||typeof A!="object")return A;if(Array.isArray(A)){for(let S=0;S<A.length;S+=1)A[S]=ge(A[S]);return A}let w=A;if(r in w){let S=w[r];return typeof S=="string"?Q(S):void 0}for(let[S,T]of Object.entries(w))w[S]=ge(T);return A},xe=A=>{for(let[w,S]of Object.entries(A)){let T=ge(S),$=e[w];if(pe($)&&pe(T)){for(let q of Object.keys($))Object.hasOwn(T,q)||delete $[q];for(let[q,W]of Object.entries(T))$[q]=W;continue}e[w]=T}},Ee=A=>{if(A.globals&&typeof A.globals=="object"&&xe(A.globals),Array.isArray(A.fnNames))for(let w of A.fnNames)typeof w=="string"&&(e[w]=Q(w))},Re=async A=>{let w=x(A),S=[];try{S=E(A)}catch{S=[]}let T=k(S),$=w;try{$=M(w)}catch{$=w}let q=$;if(T){let Y=$.lastIndexOf(`
714
714
  return (`);Y!==-1?q=$.slice(0,Y)+T+$.slice(Y):q=$+T}let W=R(q)?q:R($)?$:w;return await new n(W)()},It=A=>{let w=v(A),S=[];try{S=E(A)}catch{S=[]}let T=k(S),$=T?w+T:w;return(0,eval)($)},Ye=(A,w)=>{if(ee!==i)return A;let S=w.join(`
715
- `).trim();return S||A},rt=(A,w)=>A.length<=w?A:`${A.slice(0,w-3)}...`,Se=A=>{if(A===null)return"null";if(A===void 0)return"undefined";let w=typeof A;if(typeof A=="string")return JSON.stringify(rt(A,40));if(w==="number"||w==="boolean"||w==="bigint"||w==="symbol")return String(A);if(w==="function")return`[function ${(A.name&&typeof A.name=="string"?A.name??"":"")||"anonymous"}]`;if(Array.isArray(A))return`[array(${A.length})]`;if(A instanceof Date)return Number.isFinite(A.getTime())?A.toISOString():String(A);if(A instanceof Error)return`${A.name||"Error"}: ${A.message||""}`;if(A instanceof Map)return`[map(${A.size})]`;if(A instanceof Set)return`[set(${A.size})]`;let S=A&&typeof A=="object"&&"constructor"in A&&A.constructor&&typeof A.constructor.name=="string"?A.constructor.name??"":"";return S&&S!=="Object"?`[${S}]`:"[object]"},Ke=A=>{if(A===null)return{type:"null"};if(Array.isArray(A))return{type:"array",ctor:"Array"};if(A instanceof Map)return{type:"map",ctor:"Map"};if(A instanceof Set)return{type:"set",ctor:"Set"};if(A instanceof Date)return{type:"date",ctor:"Date"};if(A instanceof Error)return{type:"error",ctor:typeof A.name=="string"&&A.name.trim()?A.name:"Error"};let w=typeof A;return w!=="object"?{type:w}:{type:"object",ctor:A&&typeof A=="object"&&"constructor"in A&&A.constructor&&typeof A.constructor.name=="string"?A.constructor.name??void 0:void 0}},N=(A,w)=>{if(w==="string")return`${A.length} chars`;if(w==="array")return`${A.length} items`;if(w==="map"||w==="set")return`${A.size} items`;if(w==="object"&&A&&typeof A=="object")return`${Object.keys(A).length} keys`},K=(A,w,S)=>{if(w==="array")return"["+A.slice(0,3).map($=>Se($)).join(", ")+(A.length>3?", ...":"")+"]";if(w==="map"){let T=A,$=Array.from(T.entries()).slice(0,3).map(([q,W])=>`${Se(q)} => ${Se(W)}`);return"Map("+T.size+") {"+$.join(", ")+(T.size>3?", ...":"")+"}"}if(w==="set"){let T=A,$=Array.from(T.values()).slice(0,5).map(q=>Se(q));return"Set("+T.size+") {"+$.join(", ")+(T.size>5?", ...":"")+"}"}if(w==="date"||w==="error"||w==="function")return Se(A);if(w==="object"&&A&&typeof A=="object"){let T=Object.keys(A),$=T.slice(0,4);return(S&&S!=="Object"?`${S} `:"")+"{"+$.join(", ")+(T.length>$.length?", ...":"")+"}"}return Se(A)},oe=A=>{let w=new Set([...t,...A??[]]),S=Object.getOwnPropertyNames(e).filter(T=>!w.has(T)&&!T.startsWith("_")).sort().flatMap(T=>{try{let $=Object.getOwnPropertyDescriptor(e,T);if(!$)return[];if("get"in $&&typeof $.get=="function"&&!("value"in $))return[{name:T,type:"accessor",preview:"[getter omitted]"}];let q="value"in $?$.value:e[T],W=Ke(q),z=N(q,W.type),Y=K(q,W.type,W.ctor);return[{name:T,type:W.type,...W.ctor?{ctor:W.ctor}:{},...z?{size:z}:{},...Y?{preview:rt(Y,96)}:{}}]}catch{return[{name:T,type:"unknown",preview:"[unavailable]"}]}});return JSON.stringify({version:1,entries:S})},Te=A=>{if(typeof structuredClone=="function")try{return structuredClone(A),!0}catch{return!1}try{return JSON.stringify(A),!0}catch{return!1}},ze=A=>{let w=new Set([...t,...A??[]]),S={};return{version:1,entries:Object.getOwnPropertyNames(e).filter($=>!w.has($)&&!$.startsWith("_")).sort().flatMap($=>{try{let q=Object.getOwnPropertyDescriptor(e,$);if(!q)return[];if("get"in q&&typeof q.get=="function"&&!("value"in q))return[{name:$,type:"accessor",preview:"[getter omitted]",restorable:!1}];let W="value"in q?q.value:e[$],z=Ke(W),Y=N(W,z.type),fe=K(W,z.type,z.ctor),_e=Te(W);return _e&&(S[$]=typeof structuredClone=="function"?structuredClone(W):W),[{name:$,type:z.type,...z.ctor?{ctor:z.ctor}:{},...Y?{size:Y}:{},...fe?{preview:rt(fe,96)}:{},restorable:_e}]}catch{return[{name:$,type:"unknown",preview:"[unavailable]",restorable:!1}]}}),bindings:S}};f(async A=>{let w=A.data;if(!w||typeof w!="object"||typeof w.type!="string")return;if(w.type==="init"){ee=w.outputMode===i?i:o,re=w.captureConsole!==void 0?!!w.captureConsole:ee===i;let z=w.allowUnsafeNodeHostAccess===!0;Ee(w),t=Object.getOwnPropertyNames(e).sort(),B(w.permissions),H(z);return}if(w.type==="fn-result"){if(typeof w.id!="number")return;let z=G.get(w.id);z&&(G.delete(w.id),w.error!==void 0?z.reject(U(w.error)):z.resolve(w.value));return}if(w.type==="update-globals"){if(typeof w.id!="number")return;try{w.globals&&typeof w.globals=="object"&&xe(w.globals),g({type:"result",id:w.id,value:void 0})}catch(z){g({type:"result",id:w.id,error:J(z)})}return}if(w.type==="inspect-globals"){if(typeof w.id!="number")return;try{let z=Array.isArray(w.reservedNames)?w.reservedNames.filter(Y=>typeof Y=="string"):void 0;g({type:"result",id:w.id,value:oe(z)})}catch(z){g({type:"result",id:w.id,error:J(z)})}return}if(w.type==="snapshot-globals"){if(typeof w.id!="number")return;try{let z=Array.isArray(w.reservedNames)?w.reservedNames.filter(Y=>typeof Y=="string"):void 0;g({type:"result",id:w.id,value:ze(z)})}catch(z){g({type:"result",id:w.id,error:J(z)})}return}if(w.type!=="execute"||typeof w.id!="number"||typeof w.code!="string")return;let S=w.id,T=w.code,$=/\bawait\b/.test(T),{output:q,cleanup:W}=P();try{V.length=0;let z=$?await Re(T):It(T);if(G.size>0&&await Ce(),await Promise.resolve(),V.length>0)throw V[0];let Y=Ye(z,q);try{g({type:"result",id:S,value:Y})}catch{g({type:"result",id:S,value:String(Y)})}}catch(z){ie(z)?g({type:"result",id:S,value:Fe(z,T,$?2:0)}):g({type:"result",id:S,error:J(z)})}finally{W()}})}var Xi=4,Zl=16,Zi="__ax_rlm_fn_ref__",ea=16;function ec(){let s={functionRefKey:Zi,maxErrorCauseDepth:ea},e=`(${xs.toString()})(${JSON.stringify(s)});
715
+ `).trim();return S||A},rt=(A,w)=>A.length<=w?A:`${A.slice(0,w-3)}...`,Se=A=>{if(A===null)return"null";if(A===void 0)return"undefined";let w=typeof A;if(typeof A=="string")return JSON.stringify(rt(A,40));if(w==="number"||w==="boolean"||w==="bigint"||w==="symbol")return String(A);if(w==="function")return`[function ${(A.name&&typeof A.name=="string"?A.name??"":"")||"anonymous"}]`;if(Array.isArray(A))return`[array(${A.length})]`;if(A instanceof Date)return Number.isFinite(A.getTime())?A.toISOString():String(A);if(A instanceof Error)return`${A.name||"Error"}: ${A.message||""}`;if(A instanceof Map)return`[map(${A.size})]`;if(A instanceof Set)return`[set(${A.size})]`;let S=A&&typeof A=="object"&&"constructor"in A&&A.constructor&&typeof A.constructor.name=="string"?A.constructor.name??"":"";return S&&S!=="Object"?`[${S}]`:"[object]"},Ke=A=>{if(A===null)return{type:"null"};if(Array.isArray(A))return{type:"array",ctor:"Array"};if(A instanceof Map)return{type:"map",ctor:"Map"};if(A instanceof Set)return{type:"set",ctor:"Set"};if(A instanceof Date)return{type:"date",ctor:"Date"};if(A instanceof Error)return{type:"error",ctor:typeof A.name=="string"&&A.name.trim()?A.name:"Error"};let w=typeof A;return w!=="object"?{type:w}:{type:"object",ctor:A&&typeof A=="object"&&"constructor"in A&&A.constructor&&typeof A.constructor.name=="string"?A.constructor.name??void 0:void 0}},N=(A,w)=>{if(w==="string")return`${A.length} chars`;if(w==="array")return`${A.length} items`;if(w==="map"||w==="set")return`${A.size} items`;if(w==="object"&&A&&typeof A=="object")return`${Object.keys(A).length} keys`},K=(A,w,S)=>{if(w==="array")return"["+A.slice(0,3).map($=>Se($)).join(", ")+(A.length>3?", ...":"")+"]";if(w==="map"){let T=A,$=Array.from(T.entries()).slice(0,3).map(([q,W])=>`${Se(q)} => ${Se(W)}`);return"Map("+T.size+") {"+$.join(", ")+(T.size>3?", ...":"")+"}"}if(w==="set"){let T=A,$=Array.from(T.values()).slice(0,5).map(q=>Se(q));return"Set("+T.size+") {"+$.join(", ")+(T.size>5?", ...":"")+"}"}if(w==="date"||w==="error"||w==="function")return Se(A);if(w==="object"&&A&&typeof A=="object"){let T=Object.keys(A),$=T.slice(0,4);return(S&&S!=="Object"?`${S} `:"")+"{"+$.join(", ")+(T.length>$.length?", ...":"")+"}"}return Se(A)},oe=A=>{let w=new Set([...t,...A??[]]),S=Object.getOwnPropertyNames(e).filter(T=>!w.has(T)&&!T.startsWith("_")).sort().flatMap(T=>{try{let $=Object.getOwnPropertyDescriptor(e,T);if(!$)return[];if("get"in $&&typeof $.get=="function"&&!("value"in $))return[{name:T,type:"accessor",preview:"[getter omitted]"}];let q="value"in $?$.value:e[T],W=Ke(q),z=N(q,W.type),Y=K(q,W.type,W.ctor);return[{name:T,type:W.type,...W.ctor?{ctor:W.ctor}:{},...z?{size:z}:{},...Y?{preview:rt(Y,96)}:{}}]}catch{return[{name:T,type:"unknown",preview:"[unavailable]"}]}});return JSON.stringify({version:1,entries:S})},Te=A=>{if(typeof structuredClone=="function")try{return structuredClone(A),!0}catch{return!1}try{return JSON.stringify(A),!0}catch{return!1}},ze=A=>{let w=new Set([...t,...A??[]]),S={};return{version:1,entries:Object.getOwnPropertyNames(e).filter($=>!w.has($)&&!$.startsWith("_")).sort().flatMap($=>{try{let q=Object.getOwnPropertyDescriptor(e,$);if(!q)return[];if("get"in q&&typeof q.get=="function"&&!("value"in q))return[{name:$,type:"accessor",preview:"[getter omitted]",restorable:!1}];let W="value"in q?q.value:e[$],z=Ke(W),Y=N(W,z.type),fe=K(W,z.type,z.ctor),_e=Te(W);return _e&&(S[$]=typeof structuredClone=="function"?structuredClone(W):W),[{name:$,type:z.type,...z.ctor?{ctor:z.ctor}:{},...Y?{size:Y}:{},...fe?{preview:rt(fe,96)}:{},restorable:_e}]}catch{return[{name:$,type:"unknown",preview:"[unavailable]",restorable:!1}]}}),bindings:S}};f(async A=>{let w=A.data;if(!w||typeof w!="object"||typeof w.type!="string")return;if(w.type==="init"){ee=w.outputMode===i?i:o,re=w.captureConsole!==void 0?!!w.captureConsole:ee===i;let z=w.allowUnsafeNodeHostAccess===!0;Ee(w),B(w.permissions),H(z),t=Object.getOwnPropertyNames(e).sort();return}if(w.type==="fn-result"){if(typeof w.id!="number")return;let z=G.get(w.id);z&&(G.delete(w.id),w.error!==void 0?z.reject(U(w.error)):z.resolve(w.value));return}if(w.type==="update-globals"){if(typeof w.id!="number")return;try{w.globals&&typeof w.globals=="object"&&xe(w.globals),g({type:"result",id:w.id,value:void 0})}catch(z){g({type:"result",id:w.id,error:J(z)})}return}if(w.type==="inspect-globals"){if(typeof w.id!="number")return;try{let z=Array.isArray(w.reservedNames)?w.reservedNames.filter(Y=>typeof Y=="string"):void 0;g({type:"result",id:w.id,value:oe(z)})}catch(z){g({type:"result",id:w.id,error:J(z)})}return}if(w.type==="snapshot-globals"){if(typeof w.id!="number")return;try{let z=Array.isArray(w.reservedNames)?w.reservedNames.filter(Y=>typeof Y=="string"):void 0;g({type:"result",id:w.id,value:ze(z)})}catch(z){g({type:"result",id:w.id,error:J(z)})}return}if(w.type!=="execute"||typeof w.id!="number"||typeof w.code!="string")return;let S=w.id,T=w.code,$=/\bawait\b/.test(T),{output:q,cleanup:W}=P();try{V.length=0;let z=$?await Re(T):It(T);if(G.size>0&&await Ce(),await Promise.resolve(),V.length>0)throw V[0];let Y=Ye(z,q);try{g({type:"result",id:S,value:Y})}catch{g({type:"result",id:S,value:String(Y)})}}catch(z){ie(z)?g({type:"result",id:S,value:Fe(z,T,$?2:0)}):g({type:"result",id:S,error:J(z)})}finally{W()}})}var Xi=4,Zl=16,Zi="__ax_rlm_fn_ref__",ea=16;function ec(){let s={functionRefKey:Zi,maxErrorCauseDepth:ea},e=`(${xs.toString()})(${JSON.stringify(s)});
716
716
  `,t="";return e.includes("__name")&&(t+=`var __name=(fn,_n)=>fn;
717
717
  `),t?`${t}${e}`:e}var tc=()=>typeof Worker<"u"&&typeof Blob<"u"&&typeof URL<"u"&&typeof URL.createObjectURL=="function",As=()=>typeof process<"u"&&!!process.versions?.node,Vd=()=>!!globalThis.Deno?.version?.deno,Jd=()=>globalThis.Deno?.version?.deno??null,Qd=s=>{let e=/^(\d+)\.(\d+)\.(\d+)$/.exec(s.trim());return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3])}:null},nc=s=>Number.isFinite(s)?Math.max(1,Math.min(Zl,Math.floor(s))):Xi,Yd=()=>{if(!As())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},Xd=s=>{if(s!==void 0)return nc(s);let e=Yd();return e?nc(Math.ceil(e/2)):Xi},Zd=s=>s?.debugNodeWorkerPool?!0:(globalThis.process?.env??{}).AX_RLM_DEBUG_NODE_POOL==="1",em=s=>{let e=new Set(s),t={};return e.has("network")&&(t.net=!0),Object.keys(t).length>0?t:"none"},tm=(s,e)=>{let t=Jd(),n=t?Qd(t):null;if(n?n.major>=1:!0)try{return new Worker(s,{type:"module",deno:{permissions:em(e)}})}catch{}return new Worker(s,{type:"module"})},rc=(s,e)=>{let t=new Blob([s],{type:"application/javascript"}),n=URL.createObjectURL(t),r=Vd()?tm(n,e):new Worker(n),o=!1,i=()=>{o||(URL.revokeObjectURL(n),o=!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},oa=async s=>{let e="node:worker_threads",{Worker:t}=await import(e),n=new t(s,{eval:!0}),r=null,o=null,i=!1;n.on("error",u=>{o?o(u):r=u}),n.on("exit",u=>{if(i=!0,u!==0&&!r){let l=new Error(`Worker exited with code ${u}`);o?o(l):r=l}}),n.on("message",u=>{a.onmessage?.({data:u})});let a={postMessage:u=>n.postMessage(u),terminate:()=>{n.terminate()},onmessage:null,get onerror(){return o},set onerror(u){if(o=u,u&&r){let l=r;r=null,u(l)}},get exited(){return i}};return a},sa=class{source;maxSize;idle=[];pendingCreates=0;constructor(e,t){this.source=e,this.maxSize=t}warm(){if(As())for(;this.idle.length+this.pendingCreates<this.maxSize;)this.pendingCreates+=1,oa(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(),oa(this.source)}release(e){e.onmessage=null,e.onerror=null,e.terminate(),this.warm()}},oc=new Map,nm=(s,e)=>`${e}:${s}`,rm=(s,e)=>{let t=nm(s,e),n=oc.get(t);if(n)return n;let r=new sa(s,e);return oc.set(t,r),r},sc=(s,e)=>{let t={},n=new Map,r=0,o=new WeakMap,i=(a,u)=>{if(typeof a=="function"){let g=`fn_${e?.nextFnId?e.nextFnId():++r}_${u||"root"}`;return n.set(g,a),{[Zi]:g}}if(!a||typeof a!="object")return a;if(o.has(a))return o.get(a);if(Array.isArray(a)){let m=[];o.set(a,m);for(let g=0;g<a.length;g+=1)m[g]=i(a[g],`${u}[${g}]`);return m}let l=Object.getPrototypeOf(a);if(!(l===Object.prototype||l===null))return a;let p=a,d={};o.set(a,d);for(let[m,g]of Object.entries(p))d[m]=i(g,u?`${u}.${m}`:m);return d};if(s)for(let[a,u]of Object.entries(s))t[a]=i(u,a);return{serializableGlobals:t,fnMap:n}},ic=s=>{if(typeof structuredClone=="function")try{structuredClone(s)}catch(e){let t=e instanceof Error?e.message:String(e);throw new Error(`RLM globals must be structured-cloneable: ${t}`)}},ta=s=>!!s&&/[A-Za-z0-9_$]/.test(s),na=s=>!!s&&/[A-Za-z_$]/.test(s),om=(s,e)=>{let t=new Set(e);for(let m of jr(s))if(t.has(m))return m;let n=Yn(s),r=n.length,o=0,i=0,a=0,u=m=>{let g=m;for(;g<r&&/\s/.test(n[g]??"");)g++;return g},l=m=>{let g=m;for(;g>=0&&/\s/.test(n[g]??"");)g--;return g},c=m=>{let g=l(m-1);if(g<0)return!0;let f=n[g];return f===`
718
718
  `||f===";"||f==="{"||f==="}"},p=()=>{let m=o;for(;o<r&&ta(n[o]);)o++;return n.slice(m,o)},d=m=>{let g=n.slice(m,m+2);return n.slice(m,m+3)==="==="||g==="=="||g==="=>"?!1:n[m]==="="||["+=","-=","*=","/=","%=","&=","|=","^=","&&=","||=","??=","**=","<<=",">>=",">>>="].some(x=>n.startsWith(x,m))};for(;o<r;){let m=n[o];if(m==="{"){i++,o++;continue}if(m==="}"){i--,o++;continue}if(m==="("){a++,o++;continue}if(m===")"){a--,o++;continue}if(i===0&&a===0&&na(m)){let g=o,f=p();if((f==="function"||f==="class")&&c(g)){let x=u(o);if(na(n[x])){let b=x+1;for(;b<r&&ta(n[b]);)b++;let h=n.slice(x,b);if(t.has(h))return h}continue}if(f==="async"&&c(g)){let x=u(o);if(n.startsWith("function",x)){let b=u(x+8);if(na(n[b])){let h=b+1;for(;h<r&&ta(n[h]);)h++;let y=n.slice(b,h);if(t.has(y))return y}}continue}if(t.has(f)){let x=l(g-1),b=x>=0?n[x]:void 0,h=u(o),y=b==="."||b==="?"||b==="["&&n[h]==="]",I=n.startsWith("++",h)||n.startsWith("--",h)||x>0&&(n.slice(x-1,x+1)==="++"||n.slice(x-1,x+1)==="--");if(!y&&(I||d(h)))return f}continue}o++}};function ra(s){if(s==null||typeof s!="object")return String(s);try{return JSON.stringify(s,null,2)}catch{return String(s)}}function ac(s,e=ea,t=0,n=new Set){if(t>e)return{name:"Error",message:"[cause chain truncated]"};if(s!==null&&typeof s=="object"){if(n.has(s))return{name:"Error",message:"[circular]"};n.add(s)}let r=s!==null&&typeof s=="object"&&s.name!=null?String(s.name):"Error",o=s!==null&&typeof s=="object"&&s.message!=null?String(s.message):ra(s),i=s!==null&&typeof s=="object"&&typeof s.stack=="string"?s.stack:void 0,a,u=s;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=ac(p,e,t+1,n):a={name:"Error",message:ra(p)}}catch{a={name:"Error",message:ra(u.cause)}}let l={name:r,message:o};i!==void 0&&(l.stack=i),a!==void 0&&(l.cause=a);let c=s;if(c&&typeof c=="object"&&"data"in c&&c.data!==void 0)try{typeof structuredClone=="function"?l.data=structuredClone(c.data):l.data=c.data}catch{}return l}function uc(s){if(typeof s=="string")return new Error(s);if(!s||typeof s!="object")return new Error(String(s));let e=s.message!=null?String(s.message):"Unknown error",t=new Error(e);return t.name=s.name!=null?String(s.name):"Error",typeof s.stack=="string"&&(t.stack=s.stack),s.cause!==void 0&&(t.cause=uc(s.cause)),s.data!==void 0&&(t.data=s.data),t}function sm(s){if(!s||typeof s!="object")return!1;let e=s;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 im(s){if(!s||typeof s!="object")return{version:1,entries:[],bindings:{}};let e=s,t=Array.isArray(e.entries)?e.entries:[],n=e.bindings&&typeof e.bindings=="object"?e.bindings:{};return{version:1,entries:t.filter(sm),bindings:n}}var ia=(i=>(i.NETWORK="network",i.STORAGE="storage",i.CODE_LOADING="code-loading",i.COMMUNICATION="communication",i.TIMING="timing",i.WORKERS="workers",i))(ia||{}),Zt=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=Xd(e?.nodeWorkerPoolSize),this.debugNodeWorkerPool=Zd(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(`
@@ -936,7 +936,7 @@ Use the input field named "criteria" as the task-specific rubric for success.
936
936
  `.trim(),t=s?.trim();return t?`${e}
937
937
 
938
938
  Additional Evaluation Guidance:
939
- ${t}`:e}function Fc(s,e){return e.qualifiedName===s||e.name===s||e.qualifiedName.endsWith(`.${s}`)}function Hm(s,e,t){let n=Math.max(0,Math.min(1,s)),r=e.expectedActions??[];if(r.length>0){let i=r.filter(a=>t.functionCalls.some(u=>Fc(a,u))).length;n*=.5+.5*(i/r.length)}return(e.forbiddenActions??[]).some(i=>t.functionCalls.some(a=>Fc(i,a)))&&(n*=.2),Math.max(0,Math.min(1,n))}function Km(s,e){let t=new Set(s.map(r=>r.id));if(e==="actor"){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[...t];let n=[...e];for(let r of n)if(!t.has(r))throw new Error(`AxAgent.optimize(): unknown target program ID "${r}"`);return n}var nr=class extends Error{constructor(t){super(`AxAgent protocol completion: ${t}`);this.type=t;this.name="AxAgentProtocolCompletionSignal"}};function _c(s){return{finalFunction:(...r)=>{s("final",r)},askClarificationFunction:(...r)=>{s("ask_clarification",r)},protocol:{final:(...r)=>{throw s("final",r),new nr("final")},askClarification:(...r)=>{throw s("ask_clarification",r),new nr("ask_clarification")}}}}function Wm(s,e,t){return{model:s?.model,modelConfig:s?.modelConfig,debug:e,verbose:s?.verbose,rateLimiter:s?.rateLimiter,fetch:s?.fetch,tracer:s?.tracer,meter:s?.meter,timeout:s?.timeout,excludeContentFromTrace:s?.excludeContentFromTrace,abortSignal:t,logger:s?.logger,sessionId:s?.sessionId,debugHideSystemPrompt:s?.debugHideSystemPrompt,traceContext:s?.traceContext,thinkingTokenBudget:s?.thinkingTokenBudget,showThoughts:s?.showThoughts,useExpensiveModel:s?.useExpensiveModel,corsProxy:s?.corsProxy,retry:s?.retry,contextCache:s?.contextCache,examplesInSystem:s?.examplesInSystem,customLabels:s?.customLabels}}function Nc(s){let e=s?.preset??"full",t=Vm(e),n=s?.expert?.rankPruning,r=n?.enabled??(n?.minRank!==void 0?!0:t.hindsight),o=s?.state?.summary??t.stateSummary,i=s?.state?.inspect??t.inspect,a=s?.checkpoints?.enabled??t.checkpointsEnabled;if(a&&!o&&!i)throw new Error("contextPolicy.checkpoints requires either state.summary or state.inspect to be enabled");return{preset:e,summarizerOptions:s?.summarizerOptions,pruneUsedDocs:s?.pruneUsedDocs??t.pruneUsedDocs,actionReplay:s?.expert?.replay??t.actionReplay,recentFullActions:Math.max(s?.expert?.recentFullActions??t.recentFullActions,0),errorPruning:s?.expert?.pruneErrors??t.errorPruning,hindsightEvaluation:r,pruneRank:n?.minRank??t.pruneRank,rankPruneGraceTurns:$m,tombstoning:s?.expert?.tombstones,stateSummary:{enabled:o,maxEntries:s?.state?.maxEntries??t.maxEntries,maxChars:s?.state?.maxChars??t.maxStateChars},stateInspection:{enabled:i,contextThreshold:s?.state?.inspectThresholdChars??t.inspectThreshold},checkpoints:{enabled:a,triggerChars:s?.checkpoints?.triggerChars??t.checkpointTriggerChars}}}function Vm(s){switch(s){case"adaptive":return{actionReplay:"adaptive",recentFullActions:2,errorPruning:!0,hindsight:!1,pruneRank:2,pruneUsedDocs:!0,stateSummary:!0,inspect:!0,inspectThreshold:8e3,maxEntries:6,maxStateChars:1200,checkpointsEnabled:!0,checkpointTriggerChars:12e3};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};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}}}var Kr=class s{ai;judgeAI;program;actorProgram;responderProgram;agents;agentFunctions;agentFunctionModuleMetadata=new Map;debug;options;rlmConfig;runtime;actorFieldNames;localFieldNames;sharedFieldNames;globalSharedFieldNames;excludedSharedFields;excludedAgents;excludedAgentFunctions;actorDescription;responderDescription;judgeOptions;recursionForwardOptions;actorForwardOptions;responderForwardOptions;inputUpdateCallback;contextPromptConfigByField=new Map;agentModuleNamespace=vs;functionDiscoveryEnabled=!1;runtimeUsageInstructions="";enforceIncrementalConsoleTurns=!1;activeAbortControllers=new Set;_stopRequested=!1;state;stateError;func;_parentSharedFields=new Set;_parentSharedAgents=new Set;_parentSharedAgentFunctions=new Set;_reservedAgentFunctionNamespaces(){return new Set(["inputs","llmQuery","final","ask_clarification","inspect_runtime",vs,this.agentModuleNamespace,...this.functionDiscoveryEnabled?[ga,fa]:[]])}_mergeAgentFunctionModuleMetadata(e){let t=!1;for(let n of e){let r=this.agentFunctionModuleMetadata.get(n.namespace);if(!r){this.agentFunctionModuleMetadata.set(n.namespace,n),t=!0;continue}if(r.title!==n.title||r.selectionCriteria!==n.selectionCriteria||r.description!==n.description)throw new Error(`Conflicting agent function group metadata for namespace "${n.namespace}"`)}return t}_validateConfiguredSignature(e){if(e.getDescription())throw new Error("AxAgent does not support signature-level descriptions. Use setActorDescription() and/or setResponderDescription() to customize the actor and responder prompts independently.");let t=new Set(e.getInputFields().map(r=>r.name)),n=new Set(e.getOutputFields().map(r=>r.name));for(let r of this.rlmConfig.contextFields)if(!t.has(r))throw new Error(`RLM contextField "${r}" not found in signature`);for(let r of this.sharedFieldNames)if(!t.has(r))throw new Error(`sharedField "${r}" not found in signature input fields`);for(let r of this.globalSharedFieldNames)if(!t.has(r))throw new Error(`globalSharedField "${r}" not found in signature input fields`);for(let r of this.actorFieldNames)if(!n.has(r))throw new Error(`RLM actorField "${r}" not found in output signature`)}_validateAgentFunctionNamespaces(e){let t=this._reservedAgentFunctionNamespaces();for(let n of e){let r=n.namespace??"utils";if(t.has(r))throw new Error(`Agent function namespace "${r}" conflicts with an AxAgent runtime global and is reserved`)}}constructor({ai:e,judgeAI:t,agentIdentity:n,agentModuleNamespace:r,signature:o},i){let{debug:a,contextFields:u,runtime:l,maxSubAgentCalls:c,maxRuntimeChars:p,maxBatchedLlmQueryConcurrency:d,maxTurns:m,contextPolicy:g,actorFields:f,actorCallback:x,mode:b,recursionOptions:h,actorOptions:y,responderOptions:I,judgeOptions:C,inputUpdateCallback:R}=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=l??new Zt,this.runtimeUsageInstructions=this.runtime.getUsageInstructions(),this.enforceIncrementalConsoleTurns=Ag(this.runtimeUsageInstructions);let M=r??n?.namespace??vs;if(this.agentModuleNamespace=Tg(M,{normalize:r===void 0}),new Set(["inputs","llmQuery","final","ask_clarification","inspect_runtime",ga,fa]).has(this.agentModuleNamespace))throw new Error(`Agent module namespace "${this.agentModuleNamespace}" is reserved`);let E=this._reservedAgentFunctionNamespaces(),k=ha(i.functions?.local,E),O=ha(i.functions?.shared,E),L=ha(i.functions?.globallyShared,E);this.agentFunctions=k.functions,this._mergeAgentFunctionModuleMetadata(k.moduleMetadata);let{agents:F,fields:P,functions:_,judgeOptions:B,inputUpdateCallback:H,...D}=i;this.program=new we(o,D);let J=this.program.getSignature().getInputFields(),U=fg(u,J,Lm);this.contextPromptConfigByField=U.promptConfigByField,this.rlmConfig={contextFields:U.contextFieldNames,sharedFields:i.fields?.shared,runtime:this.runtime,maxSubAgentCalls:c,maxRuntimeChars:p,maxBatchedLlmQueryConcurrency:d,maxTurns:m,contextPolicy:g,actorFields:f,actorCallback:x,mode:b},this.recursionForwardOptions=h;let{description:ie,...he}=y??{},{description:Fe,...G}=I??{};this.actorDescription=ie,this.actorForwardOptions=he,this.responderDescription=Fe,this.responderForwardOptions=G,this.judgeOptions=C?{...C}:void 0,this.inputUpdateCallback=R;let j=this.agents;for(let te of j??[]){let Q=te.getFunction().name;this.program.register(te,Q)}n&&(this.func={name:Yc(n.name),description:n.description,parameters:this._buildFuncParameters(),func:async()=>{throw new Error("Use getFunction() to get a callable wrapper")}});let ee=f??[];this.actorFieldNames=ee;let re=i.fields?.shared??[];this.sharedFieldNames=re,this.excludedSharedFields=i.fields?.excluded??[];let V=i.fields?.globallyShared??[];this.globalSharedFieldNames=V,this.localFieldNames=i.fields?.local??[];let pe=i.agents?.shared??[],be=i.agents?.globallyShared??[];this.excludedAgents=i.agents?.excluded??[];let ve=O.functions,Oe=L.functions;this.excludedAgentFunctions=i.functions?.excluded??[];let se=[...this.agentFunctions,...ve,...Oe];for(let te of se){if(!te.parameters)throw new Error(`Agent function "${te.name}" must define parameters schema for agent runtime usage.`);if(te.examples){for(let[Q,Ce]of te.examples.entries())if(!Ce.code.trim())throw new Error(`Agent function "${te.name}" example at index ${Q} must define non-empty code`)}}if(this._validateConfiguredSignature(this.program.getSignature()),this._validateAgentFunctionNamespaces(se),re.length>0&&j){let te=J.filter(Q=>re.includes(Q.name));for(let Q of j){if(!(Q instanceof s))continue;let Ce=new Set(Q.getExcludedSharedFields()),ge=te.filter(xe=>!Ce.has(xe.name));ge.length!==0&&Q._extendForSharedFields(ge,this.rlmConfig.contextFields)}}if(pe.length>0&&j)for(let te of j)te instanceof s&&te._extendForSharedAgents(pe);if(V.length>0&&j){let te=J.filter(Q=>V.includes(Q.name));for(let Q of j){if(!(Q instanceof s))continue;let Ce=new Set(Q.getExcludedSharedFields()),ge=te.filter(xe=>!Ce.has(xe.name));ge.length!==0&&Q._extendForGlobalSharedFields(ge,this.rlmConfig.contextFields)}}if(be.length>0&&j)for(let te of j)te instanceof s&&te._extendForGlobalSharedAgents(be);if(ve.length>0&&j)for(let te of j)te instanceof s&&te._extendForSharedAgentFunctions(O);if(Oe.length>0&&j)for(let te of j)te instanceof s&&te._extendForGlobalSharedAgentFunctions(L);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(R=>t.includes(R.name)),o=r.filter(R=>this.contextPromptConfigByField.has(R.name)&&!n.has(R.name)).map(R=>({...R,isOptional:!0})),i=e.filter(R=>!t.includes(R.name)&&!n.has(R.name)),a=this.program.getSignature().getOutputFields(),u=a.filter(R=>this.actorFieldNames.includes(R.name)),l=a.filter(R=>!this.actorFieldNames.includes(R.name)),c=de().addInputFields(i).addInputFields(o).input("contextMetadata",de.string("Metadata about pre-loaded context variables (type and size)")).input("actionLog",de.string("Chronological trace of code executions or actions and their outputs so far")).output("javascriptCode",de.code("JavaScript code to execute in runtime session"));u.length>0&&(c=c.addOutputFields(u));let p=c.build(),d=de().addInputFields(i).input("contextData",de.json("Context data to help synthesize the final answer.")).addOutputFields(l).build(),m=this.rlmConfig.maxSubAgentCalls??Mc,g=this.rlmConfig.maxTurns??Pc,f=this.agents?.map(R=>{let M=R.getFunction();return{name:M.name,description:M.description,parameters:M.parameters}})??[],x=this.agentFunctions.map(R=>({name:R.name,description:R.description,parameters:R.parameters,returns:R.returns,namespace:R.namespace??"utils"})),b=new Set(x.map(R=>R.namespace??"utils"));f.length>0&&b.add(this.agentModuleNamespace);let h=[...b].sort((R,M)=>R.localeCompare(M)).map(R=>({namespace:R,selectionCriteria:this.agentFunctionModuleMetadata.get(R)?.selectionCriteria})),y=Nc(this.rlmConfig.contextPolicy),I=Ss(this.actorDescription,r,l,{runtimeUsageInstructions:this.runtimeUsageInstructions,maxSubAgentCalls:m,maxTurns:g,hasInspectRuntime:y.stateInspection.enabled,hasLiveRuntimeState:y.stateSummary.enabled,hasCompressedActionReplay:y.actionReplay!=="full"||y.checkpoints.enabled||y.errorPruning||!!y.tombstoning||this.functionDiscoveryEnabled&&y.pruneUsedDocs,enforceIncrementalConsoleTurns:this.enforceIncrementalConsoleTurns,agentModuleNamespace:this.agentModuleNamespace,discoveryMode:this.functionDiscoveryEnabled,availableModules:h,agents:f,agentFunctions:x}),C=ks(this.responderDescription,r);this.actorProgram?(this.actorProgram.setSignature(p),this.actorProgram.setDescription(I)):this.actorProgram=new we(p,{...this._genOptions,description:I}),this.responderProgram?(this.responderProgram.setSignature(d),this.responderProgram.setDescription(C)):this.responderProgram=new we(d,{...this._genOptions,description:C})}_extendForSharedFields(e,t){let n=this.program.getSignature(),r=n.getInputFields(),o=!1;for(let i of e){if(r.some(a=>a.name===i.name)){if(this._parentSharedFields.has(i.name))throw new Error(`Duplicate shared field "${i.name}" \u2014 already propagated from a parent`);continue}this._parentSharedFields.add(i.name),n.addInputField(i),o=!0}o&&this.program.setSignature(n);for(let i of e)t.includes(i.name)&&!this.rlmConfig.contextFields.includes(i.name)&&this.rlmConfig.contextFields.push(i.name);this._buildSplitPrograms(),this.func&&(this.func.parameters=this._buildFuncParameters())}_extendForSharedAgents(e){if(e.length===0)return;let t=new Set((this.agents??[]).map(o=>o.getFunction().name)),n=new Set(this.excludedAgents),r=[];for(let o of e){if(o===this)continue;let i=o.getFunction().name;if(!n.has(i)){if(t.has(i)){if(this._parentSharedAgents.has(i))throw new Error(`Duplicate shared agent "${i}" \u2014 already propagated from a parent`);continue}this._parentSharedAgents.add(i),t.add(i),r.push(o)}}if(r.length!==0){this.agents=[...this.agents??[],...r];for(let o of r){let i=o.getFunction().name;this.program.register(o,i)}this._buildSplitPrograms()}}_extendForGlobalSharedFields(e,t){let n=this.program.getSignature(),r=n.getInputFields(),o=!1;for(let i of e){if(r.some(a=>a.name===i.name)){if(this._parentSharedFields.has(i.name))throw new Error(`Duplicate shared field "${i.name}" \u2014 already propagated from a parent`);continue}this._parentSharedFields.add(i.name),n.addInputField(i),o=!0}o&&this.program.setSignature(n);for(let i of e)t.includes(i.name)&&!this.rlmConfig.contextFields.includes(i.name)&&this.rlmConfig.contextFields.push(i.name);for(let i of e)this.sharedFieldNames.includes(i.name)||this.sharedFieldNames.push(i.name);if(this._buildSplitPrograms(),this.func&&(this.func.parameters=this._buildFuncParameters()),this.agents)for(let i of this.agents){if(!(i instanceof s))continue;let a=new Set(i.getExcludedSharedFields()),u=e.filter(l=>!a.has(l.name));u.length!==0&&i._extendForGlobalSharedFields(u,t)}}_extendForGlobalSharedAgents(e){let t=this.agents?this.agents.filter(n=>n instanceof s):[];this._extendForSharedAgents(e);for(let n of t)n._extendForGlobalSharedAgents(e)}_extendForSharedAgentFunctions(e){if(e.functions.length===0&&e.moduleMetadata.length===0)return;let t=new Set(this.agentFunctions.map(i=>`${i.namespace??"utils"}.${i.name}`)),n=new Set(this.excludedAgentFunctions),r=[],o=this._mergeAgentFunctionModuleMetadata(e.moduleMetadata);for(let i of e.functions){if(n.has(i.name))continue;let a=`${i.namespace??"utils"}.${i.name}`;if(t.has(a)){if(this._parentSharedAgentFunctions.has(a))throw new Error(`Duplicate shared agent function "${a}" \u2014 already propagated from a parent`);continue}this._parentSharedAgentFunctions.add(a),t.add(a),r.push(i)}r.length===0&&!o||(r.length>0&&(this.agentFunctions=[...this.agentFunctions,...r]),this._buildSplitPrograms())}_extendForGlobalSharedAgentFunctions(e){let t=this.agents?this.agents.filter(n=>n instanceof s):[];this._extendForSharedAgentFunctions(e);for(let n of t)n._extendForGlobalSharedAgentFunctions(e)}stop(){this._stopRequested=!0;for(let e of this.activeAbortControllers)e.abort("Stopped by user");this.program.stop(),this.actorProgram.stop(),this.responderProgram.stop()}getId(){return this.program.getId()}setId(e){this.program.setId(e)}namedPrograms(){return this.program.namedPrograms()}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?er(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?er(e):void 0,this.stateError=void 0}async optimize(e,t){let n=jm(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 o=t?.judgeAI??this.judgeAI??t?.teacherAI??this.ai??r,i={...this.judgeOptions??{},...t?.judgeOptions??{}},a=Km(this.namedPrograms(),t?.target??"actor"),u=t?.metric??this._createAgentOptimizeMetric(o,i),l=this._createOptimizationProgram(a),c=Math.max(1,Math.floor(t?.maxMetricCalls??Math.max(Dm,n.train.length*4))),d=await new Ut({studentAI:r,teacherAI:t?.teacherAI??o,verbose:t?.verbose,debugOptimizer:t?.debugOptimizer,optimizerLogger:t?.optimizerLogger,onProgress:t?.onProgress,onEarlyStop:t?.onEarlyStop}).compile(l,n.train,u,{validationExamples:n.validation,maxMetricCalls:c,verbose:t?.verbose});return t?.apply!==!1&&d.optimizedProgram&&this.applyOptimization(d.optimizedProgram),d}_createOptimizationProgram(e){return{getId:()=>this.getId(),setId:t=>this.setId(t),getSignature:()=>Bm,forward:async(t,n,r)=>this._forwardForEvaluation(t,n,r),streamingForward:async function*(t,n,r){yield{version:1,index:0,delta:await this.forward(t,n,r)}},getTraces:()=>this.getTraces(),namedProgramInstances:()=>this.namedProgramInstances().filter(t=>e.includes(t.id)),setDemos:(t,n)=>this.setDemos(t,n),applyOptimization:t=>this.applyOptimization(t),getUsage:()=>this.getUsage(),resetUsage:()=>this.resetUsage()}}_createAgentOptimizeMetric(e,t){let n=qm(t.criteria),r=new Gt(Um,{ai:e,...t,criteria:n});return async({example:o,prediction:i})=>{let a=o,u=i,l={taskInput:dt(a.input),criteria:a.criteria,expectedOutput:a.expectedOutput,expectedActions:a.expectedActions,forbiddenActions:a.forbiddenActions,metadata:a.metadata},c={completionType:u.completionType,clarification:dt(u.clarification),finalOutput:dt(u.output),actionLog:u.actionLog,functionCalls:dt(u.functionCalls),toolErrors:u.toolErrors,turnCount:u.turnCount,usage:dt(u.usage??[])},p=await r.evaluate(l,c);return Hm(p.score,a,u)}}async _forwardForEvaluation(e,t,n){let r=this.state?er(this.state):void 0,o=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=Tt(i.signal,n?.abortSignal);this.activeAbortControllers.add(i);try{let u=this.ai??e,l=n?.debug??this.debug??u?.getOptions()?.debug??!1,c=[],{nonContextValues:p,actorResult:d,actorFieldValues:m,actionLog:g,turnCount:f}=await this._runActorLoop(u,t.input,n,a,c),x=c.filter(y=>!!y.error).map(y=>`${y.qualifiedName}: ${y.error??"unknown error"}`);if(d.type==="ask_clarification")return{completionType:"ask_clarification",clarification:Kc(d.args[0]),actionLog:g,functionCalls:c,toolErrors:x,turnCount:f};let b={...this._genOptions,...this.responderForwardOptions,...n,debug:l,abortSignal:a,maxSteps:1};return{completionType:"final",output:{...await this.responderProgram.forward(u,{...p,contextData:d},b),...m},actionLog:g,functionCalls:c,toolErrors:x,turnCount:f}}finally{this.state=r?er(r):void 0,this.stateError=o,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,o)=>{let i=this.ai??o?.ai;if(!i)throw new Error("AI service is required to run the agent");let a=await e(i,r,o),l=this.program.getSignature().getOutputFields();return Object.keys(a).map(p=>{let d=l.find(m=>m.name===p);return d?`${d.title}: ${a[p]}`:`${p}: ${a[p]}`}).join(`
939
+ ${t}`:e}function Fc(s,e){return e.qualifiedName===s||e.name===s||e.qualifiedName.endsWith(`.${s}`)}function Hm(s,e,t){let n=Math.max(0,Math.min(1,s)),r=e.expectedActions??[];if(r.length>0){let i=r.filter(a=>t.functionCalls.some(u=>Fc(a,u))).length;n*=.5+.5*(i/r.length)}return(e.forbiddenActions??[]).some(i=>t.functionCalls.some(a=>Fc(i,a)))&&(n*=.2),Math.max(0,Math.min(1,n))}function Km(s,e){let t=new Set(s.map(r=>r.id));if(e==="actor"){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[...t];let n=[...e];for(let r of n)if(!t.has(r))throw new Error(`AxAgent.optimize(): unknown target program ID "${r}"`);return n}var nr=class extends Error{constructor(t){super(`AxAgent protocol completion: ${t}`);this.type=t;this.name="AxAgentProtocolCompletionSignal"}};function _c(s){return{finalFunction:(...r)=>{s("final",r)},askClarificationFunction:(...r)=>{s("ask_clarification",r)},protocol:{final:(...r)=>{throw s("final",r),new nr("final")},askClarification:(...r)=>{throw s("ask_clarification",r),new nr("ask_clarification")}}}}function Wm(s,e,t){return{model:s?.model,modelConfig:s?.modelConfig,debug:e,verbose:s?.verbose,rateLimiter:s?.rateLimiter,fetch:s?.fetch,tracer:s?.tracer,meter:s?.meter,timeout:s?.timeout,excludeContentFromTrace:s?.excludeContentFromTrace,abortSignal:t,logger:s?.logger,sessionId:s?.sessionId,debugHideSystemPrompt:s?.debugHideSystemPrompt,traceContext:s?.traceContext,thinkingTokenBudget:s?.thinkingTokenBudget,showThoughts:s?.showThoughts,useExpensiveModel:s?.useExpensiveModel,corsProxy:s?.corsProxy,retry:s?.retry,contextCache:s?.contextCache,examplesInSystem:s?.examplesInSystem,customLabels:s?.customLabels}}function Nc(s){let e=s?.preset??"full",t=Vm(e),n=s?.expert?.rankPruning,r=n?.enabled??(n?.minRank!==void 0?!0:t.hindsight),o=s?.state?.summary??t.stateSummary,i=s?.state?.inspect??t.inspect,a=s?.checkpoints?.enabled??t.checkpointsEnabled;if(a&&!o&&!i)throw new Error("contextPolicy.checkpoints requires either state.summary or state.inspect to be enabled");return{preset:e,summarizerOptions:s?.summarizerOptions,pruneUsedDocs:s?.pruneUsedDocs??t.pruneUsedDocs,actionReplay:s?.expert?.replay??t.actionReplay,recentFullActions:Math.max(s?.expert?.recentFullActions??t.recentFullActions,0),errorPruning:s?.pruneErrors??t.errorPruning,hindsightEvaluation:r,pruneRank:n?.minRank??t.pruneRank,rankPruneGraceTurns:$m,tombstoning:s?.expert?.tombstones,stateSummary:{enabled:o,maxEntries:s?.state?.maxEntries??t.maxEntries,maxChars:s?.state?.maxChars??t.maxStateChars},stateInspection:{enabled:i,contextThreshold:s?.state?.inspectThresholdChars??t.inspectThreshold},checkpoints:{enabled:a,triggerChars:s?.checkpoints?.triggerChars??t.checkpointTriggerChars}}}function Vm(s){switch(s){case"adaptive":return{actionReplay:"adaptive",recentFullActions:2,errorPruning:!0,hindsight:!1,pruneRank:2,pruneUsedDocs:!0,stateSummary:!0,inspect:!0,inspectThreshold:8e3,maxEntries:6,maxStateChars:1200,checkpointsEnabled:!0,checkpointTriggerChars:12e3};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};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}}}var Kr=class s{ai;judgeAI;program;actorProgram;responderProgram;agents;agentFunctions;agentFunctionModuleMetadata=new Map;debug;options;rlmConfig;runtime;actorFieldNames;localFieldNames;sharedFieldNames;globalSharedFieldNames;excludedSharedFields;excludedAgents;excludedAgentFunctions;actorDescription;responderDescription;judgeOptions;recursionForwardOptions;actorForwardOptions;responderForwardOptions;inputUpdateCallback;contextPromptConfigByField=new Map;agentModuleNamespace=vs;functionDiscoveryEnabled=!1;runtimeUsageInstructions="";enforceIncrementalConsoleTurns=!1;activeAbortControllers=new Set;_stopRequested=!1;state;stateError;func;_parentSharedFields=new Set;_parentSharedAgents=new Set;_parentSharedAgentFunctions=new Set;_reservedAgentFunctionNamespaces(){return new Set(["inputs","llmQuery","final","ask_clarification","inspect_runtime",vs,this.agentModuleNamespace,...this.functionDiscoveryEnabled?[ga,fa]:[]])}_mergeAgentFunctionModuleMetadata(e){let t=!1;for(let n of e){let r=this.agentFunctionModuleMetadata.get(n.namespace);if(!r){this.agentFunctionModuleMetadata.set(n.namespace,n),t=!0;continue}if(r.title!==n.title||r.selectionCriteria!==n.selectionCriteria||r.description!==n.description)throw new Error(`Conflicting agent function group metadata for namespace "${n.namespace}"`)}return t}_validateConfiguredSignature(e){if(e.getDescription())throw new Error("AxAgent does not support signature-level descriptions. Use setActorDescription() and/or setResponderDescription() to customize the actor and responder prompts independently.");let t=new Set(e.getInputFields().map(r=>r.name)),n=new Set(e.getOutputFields().map(r=>r.name));for(let r of this.rlmConfig.contextFields)if(!t.has(r))throw new Error(`RLM contextField "${r}" not found in signature`);for(let r of this.sharedFieldNames)if(!t.has(r))throw new Error(`sharedField "${r}" not found in signature input fields`);for(let r of this.globalSharedFieldNames)if(!t.has(r))throw new Error(`globalSharedField "${r}" not found in signature input fields`);for(let r of this.actorFieldNames)if(!n.has(r))throw new Error(`RLM actorField "${r}" not found in output signature`)}_validateAgentFunctionNamespaces(e){let t=this._reservedAgentFunctionNamespaces();for(let n of e){let r=n.namespace??"utils";if(t.has(r))throw new Error(`Agent function namespace "${r}" conflicts with an AxAgent runtime global and is reserved`)}}constructor({ai:e,judgeAI:t,agentIdentity:n,agentModuleNamespace:r,signature:o},i){let{debug:a,contextFields:u,runtime:l,maxSubAgentCalls:c,maxRuntimeChars:p,maxBatchedLlmQueryConcurrency:d,maxTurns:m,contextPolicy:g,actorFields:f,actorCallback:x,mode:b,recursionOptions:h,actorOptions:y,responderOptions:I,judgeOptions:C,inputUpdateCallback:R}=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=l??new Zt,this.runtimeUsageInstructions=this.runtime.getUsageInstructions(),this.enforceIncrementalConsoleTurns=Ag(this.runtimeUsageInstructions);let M=r??n?.namespace??vs;if(this.agentModuleNamespace=Tg(M,{normalize:r===void 0}),new Set(["inputs","llmQuery","final","ask_clarification","inspect_runtime",ga,fa]).has(this.agentModuleNamespace))throw new Error(`Agent module namespace "${this.agentModuleNamespace}" is reserved`);let E=this._reservedAgentFunctionNamespaces(),k=ha(i.functions?.local,E),O=ha(i.functions?.shared,E),L=ha(i.functions?.globallyShared,E);this.agentFunctions=k.functions,this._mergeAgentFunctionModuleMetadata(k.moduleMetadata);let{agents:F,fields:P,functions:_,judgeOptions:B,inputUpdateCallback:H,...D}=i;this.program=new we(o,D);let J=this.program.getSignature().getInputFields(),U=fg(u,J,Lm);this.contextPromptConfigByField=U.promptConfigByField,this.rlmConfig={contextFields:U.contextFieldNames,sharedFields:i.fields?.shared,runtime:this.runtime,maxSubAgentCalls:c,maxRuntimeChars:p,maxBatchedLlmQueryConcurrency:d,maxTurns:m,contextPolicy:g,actorFields:f,actorCallback:x,mode:b},this.recursionForwardOptions=h;let{description:ie,...he}=y??{},{description:Fe,...G}=I??{};this.actorDescription=ie,this.actorForwardOptions=he,this.responderDescription=Fe,this.responderForwardOptions=G,this.judgeOptions=C?{...C}:void 0,this.inputUpdateCallback=R;let j=this.agents;for(let te of j??[]){let Q=te.getFunction().name;this.program.register(te,Q)}n&&(this.func={name:Yc(n.name),description:n.description,parameters:this._buildFuncParameters(),func:async()=>{throw new Error("Use getFunction() to get a callable wrapper")}});let ee=f??[];this.actorFieldNames=ee;let re=i.fields?.shared??[];this.sharedFieldNames=re,this.excludedSharedFields=i.fields?.excluded??[];let V=i.fields?.globallyShared??[];this.globalSharedFieldNames=V,this.localFieldNames=i.fields?.local??[];let pe=i.agents?.shared??[],be=i.agents?.globallyShared??[];this.excludedAgents=i.agents?.excluded??[];let ve=O.functions,Oe=L.functions;this.excludedAgentFunctions=i.functions?.excluded??[];let se=[...this.agentFunctions,...ve,...Oe];for(let te of se){if(!te.parameters)throw new Error(`Agent function "${te.name}" must define parameters schema for agent runtime usage.`);if(te.examples){for(let[Q,Ce]of te.examples.entries())if(!Ce.code.trim())throw new Error(`Agent function "${te.name}" example at index ${Q} must define non-empty code`)}}if(this._validateConfiguredSignature(this.program.getSignature()),this._validateAgentFunctionNamespaces(se),re.length>0&&j){let te=J.filter(Q=>re.includes(Q.name));for(let Q of j){if(!(Q instanceof s))continue;let Ce=new Set(Q.getExcludedSharedFields()),ge=te.filter(xe=>!Ce.has(xe.name));ge.length!==0&&Q._extendForSharedFields(ge,this.rlmConfig.contextFields)}}if(pe.length>0&&j)for(let te of j)te instanceof s&&te._extendForSharedAgents(pe);if(V.length>0&&j){let te=J.filter(Q=>V.includes(Q.name));for(let Q of j){if(!(Q instanceof s))continue;let Ce=new Set(Q.getExcludedSharedFields()),ge=te.filter(xe=>!Ce.has(xe.name));ge.length!==0&&Q._extendForGlobalSharedFields(ge,this.rlmConfig.contextFields)}}if(be.length>0&&j)for(let te of j)te instanceof s&&te._extendForGlobalSharedAgents(be);if(ve.length>0&&j)for(let te of j)te instanceof s&&te._extendForSharedAgentFunctions(O);if(Oe.length>0&&j)for(let te of j)te instanceof s&&te._extendForGlobalSharedAgentFunctions(L);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(R=>t.includes(R.name)),o=r.filter(R=>this.contextPromptConfigByField.has(R.name)&&!n.has(R.name)).map(R=>({...R,isOptional:!0})),i=e.filter(R=>!t.includes(R.name)&&!n.has(R.name)),a=this.program.getSignature().getOutputFields(),u=a.filter(R=>this.actorFieldNames.includes(R.name)),l=a.filter(R=>!this.actorFieldNames.includes(R.name)),c=de().addInputFields(i).addInputFields(o).input("contextMetadata",de.string("Metadata about pre-loaded context variables (type and size)")).input("actionLog",de.string("Chronological trace of code executions or actions and their outputs so far")).output("javascriptCode",de.code("JavaScript code to execute in runtime session"));u.length>0&&(c=c.addOutputFields(u));let p=c.build(),d=de().addInputFields(i).input("contextData",de.json("Context data to help synthesize the final answer.")).addOutputFields(l).build(),m=this.rlmConfig.maxSubAgentCalls??Mc,g=this.rlmConfig.maxTurns??Pc,f=this.agents?.map(R=>{let M=R.getFunction();return{name:M.name,description:M.description,parameters:M.parameters}})??[],x=this.agentFunctions.map(R=>({name:R.name,description:R.description,parameters:R.parameters,returns:R.returns,namespace:R.namespace??"utils"})),b=new Set(x.map(R=>R.namespace??"utils"));f.length>0&&b.add(this.agentModuleNamespace);let h=[...b].sort((R,M)=>R.localeCompare(M)).map(R=>({namespace:R,selectionCriteria:this.agentFunctionModuleMetadata.get(R)?.selectionCriteria})),y=Nc(this.rlmConfig.contextPolicy),I=Ss(this.actorDescription,r,l,{runtimeUsageInstructions:this.runtimeUsageInstructions,maxSubAgentCalls:m,maxTurns:g,hasInspectRuntime:y.stateInspection.enabled,hasLiveRuntimeState:y.stateSummary.enabled,hasCompressedActionReplay:y.actionReplay!=="full"||y.checkpoints.enabled||y.errorPruning||!!y.tombstoning||this.functionDiscoveryEnabled&&y.pruneUsedDocs,enforceIncrementalConsoleTurns:this.enforceIncrementalConsoleTurns,agentModuleNamespace:this.agentModuleNamespace,discoveryMode:this.functionDiscoveryEnabled,availableModules:h,agents:f,agentFunctions:x}),C=ks(this.responderDescription,r);this.actorProgram?(this.actorProgram.setSignature(p),this.actorProgram.setDescription(I)):this.actorProgram=new we(p,{...this._genOptions,description:I}),this.responderProgram?(this.responderProgram.setSignature(d),this.responderProgram.setDescription(C)):this.responderProgram=new we(d,{...this._genOptions,description:C})}_extendForSharedFields(e,t){let n=this.program.getSignature(),r=n.getInputFields(),o=!1;for(let i of e){if(r.some(a=>a.name===i.name)){if(this._parentSharedFields.has(i.name))throw new Error(`Duplicate shared field "${i.name}" \u2014 already propagated from a parent`);continue}this._parentSharedFields.add(i.name),n.addInputField(i),o=!0}o&&this.program.setSignature(n);for(let i of e)t.includes(i.name)&&!this.rlmConfig.contextFields.includes(i.name)&&this.rlmConfig.contextFields.push(i.name);this._buildSplitPrograms(),this.func&&(this.func.parameters=this._buildFuncParameters())}_extendForSharedAgents(e){if(e.length===0)return;let t=new Set((this.agents??[]).map(o=>o.getFunction().name)),n=new Set(this.excludedAgents),r=[];for(let o of e){if(o===this)continue;let i=o.getFunction().name;if(!n.has(i)){if(t.has(i)){if(this._parentSharedAgents.has(i))throw new Error(`Duplicate shared agent "${i}" \u2014 already propagated from a parent`);continue}this._parentSharedAgents.add(i),t.add(i),r.push(o)}}if(r.length!==0){this.agents=[...this.agents??[],...r];for(let o of r){let i=o.getFunction().name;this.program.register(o,i)}this._buildSplitPrograms()}}_extendForGlobalSharedFields(e,t){let n=this.program.getSignature(),r=n.getInputFields(),o=!1;for(let i of e){if(r.some(a=>a.name===i.name)){if(this._parentSharedFields.has(i.name))throw new Error(`Duplicate shared field "${i.name}" \u2014 already propagated from a parent`);continue}this._parentSharedFields.add(i.name),n.addInputField(i),o=!0}o&&this.program.setSignature(n);for(let i of e)t.includes(i.name)&&!this.rlmConfig.contextFields.includes(i.name)&&this.rlmConfig.contextFields.push(i.name);for(let i of e)this.sharedFieldNames.includes(i.name)||this.sharedFieldNames.push(i.name);if(this._buildSplitPrograms(),this.func&&(this.func.parameters=this._buildFuncParameters()),this.agents)for(let i of this.agents){if(!(i instanceof s))continue;let a=new Set(i.getExcludedSharedFields()),u=e.filter(l=>!a.has(l.name));u.length!==0&&i._extendForGlobalSharedFields(u,t)}}_extendForGlobalSharedAgents(e){let t=this.agents?this.agents.filter(n=>n instanceof s):[];this._extendForSharedAgents(e);for(let n of t)n._extendForGlobalSharedAgents(e)}_extendForSharedAgentFunctions(e){if(e.functions.length===0&&e.moduleMetadata.length===0)return;let t=new Set(this.agentFunctions.map(i=>`${i.namespace??"utils"}.${i.name}`)),n=new Set(this.excludedAgentFunctions),r=[],o=this._mergeAgentFunctionModuleMetadata(e.moduleMetadata);for(let i of e.functions){if(n.has(i.name))continue;let a=`${i.namespace??"utils"}.${i.name}`;if(t.has(a)){if(this._parentSharedAgentFunctions.has(a))throw new Error(`Duplicate shared agent function "${a}" \u2014 already propagated from a parent`);continue}this._parentSharedAgentFunctions.add(a),t.add(a),r.push(i)}r.length===0&&!o||(r.length>0&&(this.agentFunctions=[...this.agentFunctions,...r]),this._buildSplitPrograms())}_extendForGlobalSharedAgentFunctions(e){let t=this.agents?this.agents.filter(n=>n instanceof s):[];this._extendForSharedAgentFunctions(e);for(let n of t)n._extendForGlobalSharedAgentFunctions(e)}stop(){this._stopRequested=!0;for(let e of this.activeAbortControllers)e.abort("Stopped by user");this.program.stop(),this.actorProgram.stop(),this.responderProgram.stop()}getId(){return this.program.getId()}setId(e){this.program.setId(e)}namedPrograms(){return this.program.namedPrograms()}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?er(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?er(e):void 0,this.stateError=void 0}async optimize(e,t){let n=jm(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 o=t?.judgeAI??this.judgeAI??t?.teacherAI??this.ai??r,i={...this.judgeOptions??{},...t?.judgeOptions??{}},a=Km(this.namedPrograms(),t?.target??"actor"),u=t?.metric??this._createAgentOptimizeMetric(o,i),l=this._createOptimizationProgram(a),c=Math.max(1,Math.floor(t?.maxMetricCalls??Math.max(Dm,n.train.length*4))),d=await new Ut({studentAI:r,teacherAI:t?.teacherAI??o,verbose:t?.verbose,debugOptimizer:t?.debugOptimizer,optimizerLogger:t?.optimizerLogger,onProgress:t?.onProgress,onEarlyStop:t?.onEarlyStop}).compile(l,n.train,u,{validationExamples:n.validation,maxMetricCalls:c,verbose:t?.verbose});return t?.apply!==!1&&d.optimizedProgram&&this.applyOptimization(d.optimizedProgram),d}_createOptimizationProgram(e){return{getId:()=>this.getId(),setId:t=>this.setId(t),getSignature:()=>Bm,forward:async(t,n,r)=>this._forwardForEvaluation(t,n,r),streamingForward:async function*(t,n,r){yield{version:1,index:0,delta:await this.forward(t,n,r)}},getTraces:()=>this.getTraces(),namedProgramInstances:()=>this.namedProgramInstances().filter(t=>e.includes(t.id)),setDemos:(t,n)=>this.setDemos(t,n),applyOptimization:t=>this.applyOptimization(t),getUsage:()=>this.getUsage(),resetUsage:()=>this.resetUsage()}}_createAgentOptimizeMetric(e,t){let n=qm(t.criteria),r=new Gt(Um,{ai:e,...t,criteria:n});return async({example:o,prediction:i})=>{let a=o,u=i,l={taskInput:dt(a.input),criteria:a.criteria,expectedOutput:a.expectedOutput,expectedActions:a.expectedActions,forbiddenActions:a.forbiddenActions,metadata:a.metadata},c={completionType:u.completionType,clarification:dt(u.clarification),finalOutput:dt(u.output),actionLog:u.actionLog,functionCalls:dt(u.functionCalls),toolErrors:u.toolErrors,turnCount:u.turnCount,usage:dt(u.usage??[])},p=await r.evaluate(l,c);return Hm(p.score,a,u)}}async _forwardForEvaluation(e,t,n){let r=this.state?er(this.state):void 0,o=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=Tt(i.signal,n?.abortSignal);this.activeAbortControllers.add(i);try{let u=this.ai??e,l=n?.debug??this.debug??u?.getOptions()?.debug??!1,c=[],{nonContextValues:p,actorResult:d,actorFieldValues:m,actionLog:g,turnCount:f}=await this._runActorLoop(u,t.input,n,a,c),x=c.filter(y=>!!y.error).map(y=>`${y.qualifiedName}: ${y.error??"unknown error"}`);if(d.type==="ask_clarification")return{completionType:"ask_clarification",clarification:Kc(d.args[0]),actionLog:g,functionCalls:c,toolErrors:x,turnCount:f};let b={...this._genOptions,...this.responderForwardOptions,...n,debug:l,abortSignal:a,maxSteps:1};return{completionType:"final",output:{...await this.responderProgram.forward(u,{...p,contextData:d},b),...m},actionLog:g,functionCalls:c,toolErrors:x,turnCount:f}}finally{this.state=r?er(r):void 0,this.stateError=o,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,o)=>{let i=this.ai??o?.ai;if(!i)throw new Error("AI service is required to run the agent");let a=await e(i,r,o),l=this.program.getSignature().getOutputFields();return Object.keys(a).map(p=>{let d=l.find(m=>m.name===p);return d?`${d.title}: ${a[p]}`:`${p}: ${a[p]}`}).join(`
940
940
  `)}}}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,b)=>({...x,...b.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 o={...n},i=r?new Set(r):new Set(this.program.getSignature().getInputFields().map(x=>x.name)),a=[...this.sharedFieldNames,...this.globalSharedFieldNames],u=this._getBypassedSharedFieldNames(),l={},c={},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:o,signatureInputFieldNames:i,sharedFieldValues:l,recomputeTurnInputs:x=>{let b={},h={};for(let[I,C]of Object.entries(o))this.rlmConfig.contextFields.includes(I)?b[I]=C:u.has(I)||(h[I]=C);if(x){for(let I of this.rlmConfig.contextFields)if(!g.has(I)&&(!(I in b)||b[I]===void 0))throw new Error(`RLM contextField "${I}" is missing from input values`)}let y={};for(let[I,C]of this.contextPromptConfigByField){if(u.has(I)||!(I in b))continue;let R=dg(b[I],C);R!==void 0&&(y[I]=R)}c=b,p=h,d=y;for(let I of Object.keys(l))delete l[I];for(let I of a)I in o&&(l[I]=o[I]),I in c&&(l[I]=c[I]);m=hg(c,{promptConfigByField:this.contextPromptConfigByField,inlinedFields:new Set(Object.keys(d))})||"(none)"},getNonContextValues:()=>p,getActorInlineContextValues:()=>d,getContextMetadata:()=>m}}_createRuntimeExecutionContext({ai:e,inputState:t,options:n,effectiveAbortSignal:r,debug:o,completionState:i,completionBindings:a,actionLogEntries:u,functionCallRecorder:l}){let c=this.rlmConfig,p=this.runtime,d=c.maxSubAgentCalls??Mc,m=c.maxRuntimeChars??Fm,g=Math.max(1,c.maxBatchedLlmQueryConcurrency??_m),f=this.recursionForwardOptions?.maxDepth??Nm,x=Math.max(0,f),b=Nc(c.contextPolicy),h=0,y=Math.floor(d*.8),{maxDepth:I,...C}=this.recursionForwardOptions??{},{description:R,mem:M,sessionId:v,...E}=n??{},k={...this.recursionForwardOptions??{},maxDepth:Math.max(0,x-1)},O=["context"],L=de().input("task",de.string("Task for recursive analysis")).input("context",de.json("Optional context for the recursive task")).output("answer",de.string("Answer from recursive analysis")).build(),P=(c.mode??"simple")==="advanced"&&(k.maxDepth??0)>0?"advanced":"simple",_;x>0&&(P==="advanced"?_=new s({agentModuleNamespace:this.agentModuleNamespace,signature:L},{debug:o,...c,agents:{local:this.agents},functions:{local:this.agentFunctions,discovery:this.functionDiscoveryEnabled},contextFields:O,actorFields:void 0,recursionOptions:k,actorOptions:this.actorForwardOptions,responderOptions:this.responderForwardOptions}):_=new we(L,k));let B=async(N,K)=>{if(!Array.isArray(N)&&typeof N=="object"&&N!==null&&"query"in N)return B(N.query,N.context??K);if(r?.aborted)throw new $e("rlm-llm-query",r.reason?String(r.reason):"Aborted");if(Array.isArray(N))return xg(N,g,async w=>{try{return await B(w.query,w.context)}catch(S){if(S instanceof $e)throw S;return`[ERROR] ${S instanceof Error?S.message:String(S)}`}});if(!e)throw new Error(Gm);let oe=N,Te=w=>{if(w==null)return"";if(typeof w=="string")return mt(w,m);try{return mt(JSON.stringify(w),m)}catch{return mt(String(w),m)}},A=await(async(w,S)=>{let T=S===void 0?void 0:typeof S=="string"?mt(S,m):S;if(h++,h>d)return`[ERROR] Sub-query budget exhausted (${d}/${d}). Use the data you have already accumulated to produce your final answer.`;if(x<=0||!_)return`[ERROR] Recursion depth limit reached (${f}).`;let $=3,q,W=z=>`[ERROR] ${z instanceof Error?z.message:String(z)}`;for(let z=0;z<$;z++)try{let Y=await _.forward(e,{task:w,...T!==void 0?{context:T}:P==="advanced"?{context:""}:{}},{...E,...C,abortSignal:r,debug:o});return Te(Y.answer)}catch(Y){if(Y instanceof $e)throw Y;if(q=Y,!rg(Y)||z>=$-1)return W(Y);let fe=Math.min(6e4,1e3*Math.pow(2,z));await new Promise((_e,ae)=>{let Ie=!1,Ne,ke=()=>{r&&Ne&&r.removeEventListener("abort",Ne)},Ct=setTimeout(()=>{Ie||(Ie=!0,ke(),_e())},fe);if(r){if(Ne=()=>{Ie||(Ie=!0,clearTimeout(Ct),ke(),ae(new $e("rlm-llm-query-retry-backoff",r.reason?String(r.reason):"Aborted during retry backoff")))},r.aborted){Ne();return}r.addEventListener("abort",Ne,{once:!0})}})}return W(q)})(oe,K);return h===y?`${A}
941
941
  [WARNING] ${h}/${d} sub-queries used. Plan to wrap up soon.`:A},H=this.buildRuntimeGlobals(r,t.sharedFieldValues,e,a.protocol,l),D=[...new Set(this.agentFunctions.map(N=>N.namespace??"utils"))],J={...t.currentInputs},U=new Set(["inputs","llmQuery",vs,this.agentModuleNamespace,"final","ask_clarification",...D,...b.stateInspection.enabled?["inspect_runtime"]:[],...Object.keys(H)]),ie=[...new Set([...Object.keys(J),...t.signatureInputFieldNames])].filter(N=>!U.has(N)),he={};for(let N of ie)he[N]=J[N];let Fe=()=>{for(let N of Object.keys(J))delete J[N];for(let[N,K]of Object.entries(t.currentInputs))J[N]=K;for(let N of ie)he[N]=t.currentInputs[N]},G=[...U],j=[...U,...ie],ee=u??[],re,V,pe=N=>typeof N.inspectGlobals=="function"?N:void 0,be=async()=>{try{let N=await re.execute(vc(),{signal:r,reservedNames:j});if(typeof N!="string")return[];let K=JSON.parse(N);return Array.isArray(K)?K.filter(oe=>typeof oe=="string"):[]}catch{return[]}},ve=async()=>(V||(V=await be()),V),Oe=async()=>{try{let N=pe(re);if(N?.inspectGlobals)return await N.inspectGlobals({signal:r,reservedNames:j});let K=await ve(),oe=kc(j,K),Te=await re.execute(oe,{signal:r,reservedNames:j});return typeof Te=="string"?Te:String(Te)}catch(N){return`[inspect_runtime error: ${N instanceof Error?N.message:String(N)}]`}},se=(N,K)=>{let oe=ig(N);if(!oe)return ag(N,K);let Te=Ts(ee);return Dc(oe,Te,K)},te=b.stateInspection.enabled?async()=>se(await Oe()):void 0,Q=()=>(V=void 0,p.createSession({...he,inputs:J,llmQuery:B,final:a.finalFunction,ask_clarification:a.askClarificationFunction,...te?{inspect_runtime:te}:{},...H}));re=Q();let Ce=async()=>{if(!i.payload)for(let N=0;N<3&&!i.payload;N++)await new Promise(K=>{setTimeout(K,0)})},ge=async()=>{if(!b.stateSummary.enabled)return;let N=await Oe();return se(N,{maxEntries:b.stateSummary.maxEntries&&b.stateSummary.maxEntries>0?b.stateSummary.maxEntries:8,maxChars:b.stateSummary.maxChars&&b.stateSummary.maxChars>0?b.stateSummary.maxChars:void 0})||"(no user variables)"},xe=N=>{if(typeof N.patchGlobals!="function")throw new Error("AxCodeSession.patchGlobals() is required when restoring AxAgent state or using inputUpdateCallback");return N},Ee=N=>{if(typeof N.snapshotGlobals!="function")throw new Error("AxCodeSession.snapshotGlobals() is required to export AxAgent state");return N},Re=N=>{let K=new Set(j),oe={};for(let[ze,A]of Object.entries(N.runtimeBindings??{}))K.has(ze)||(oe[ze]=A);let Te=(N.runtimeEntries??[]).filter(ze=>!K.has(ze.name));return{runtimeBindings:oe,runtimeEntries:Te,actionLogEntries:Xm(N.actionLogEntries),checkpointState:N.checkpointState,provenance:{...N.provenance??{}}}};return{effectiveContextConfig:b,captureRuntimeStateSummary:ge,exportRuntimeState:async()=>{let K=await Ee(re).snapshotGlobals({signal:r,reservedNames:j}),oe=Ts(ee);return{version:1,runtimeBindings:K.bindings,runtimeEntries:K.entries,actionLogEntries:Ym(ee),provenance:Zm(oe)}},restoreRuntimeState:async N=>{let K=Re(N);return await xe(re).patchGlobals(K.runtimeBindings,{signal:r}),K},syncRuntimeInputsToSession:async()=>{Fe();let N=async K=>{await xe(K).patchGlobals({inputs:{...J},...he},{signal:r})};try{await N(re)}catch(K){if(r?.aborted)throw new $e("rlm-session",r.reason??"Aborted");if(K instanceof Error&&(K.name==="AbortError"||K.message.startsWith("Aborted")))throw K;if(Bc(K)){re=Q(),await N(re);return}throw new Error(`Failed to sync runtime inputs: ${Es(K,m)}`)}},executeActorCode:async N=>{let K={output:Os(void 0,m),isError:!1};try{let oe=await re.execute(N,{signal:r,reservedNames:G});return i.payload||Gc(N)&&Uc(oe)&&(await Ce(),i.payload)?K:{output:Os(oe,m),isError:!1}}catch(oe){if(oe instanceof nr||i.payload)return K;if(r?.aborted)throw new $e("rlm-session",r.reason??"Aborted");if(oe instanceof Error&&(oe.name==="AbortError"||oe.message.startsWith("Aborted")))throw oe;if(cg(oe))return{output:mt(`${Ms}
942
942
  ${Es(oe,m)}`,m),isError:!0};if(Bc(oe))try{re=Q(),i.payload=void 0;let Te=await re.execute(N,{signal:r,reservedNames:G});return{output:mt(`${Ms}