@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.d.cts CHANGED
@@ -10036,7 +10036,8 @@ interface AxCodeSession {
10036
10036
  type AxContextPolicyPreset = 'full' | 'adaptive' | 'lean';
10037
10037
  /**
10038
10038
  * Public context policy for the Actor loop.
10039
- * Presets provide the common behavior; `state` and `expert` override specific pieces.
10039
+ * Presets provide the common behavior; top-level toggles plus `state`,
10040
+ * `checkpoints`, and `expert` override specific pieces.
10040
10041
  */
10041
10042
  interface AxContextPolicyConfig {
10042
10043
  /**
@@ -10064,6 +10065,15 @@ interface AxContextPolicyConfig {
10064
10065
  * - `lean`: true
10065
10066
  */
10066
10067
  pruneUsedDocs?: boolean;
10068
+ /**
10069
+ * Prune error entries after a successful (non-error) turn.
10070
+ *
10071
+ * Defaults by preset:
10072
+ * - `full`: false
10073
+ * - `adaptive`: true
10074
+ * - `lean`: true
10075
+ */
10076
+ pruneErrors?: boolean;
10067
10077
  /** Runtime-state visibility controls. */
10068
10078
  state?: {
10069
10079
  /** Include a compact live runtime state block ahead of the action log. */
@@ -10090,8 +10100,6 @@ interface AxContextPolicyConfig {
10090
10100
  replay?: 'full' | 'adaptive' | 'minimal';
10091
10101
  /** Number of most-recent actions that should always remain fully rendered. */
10092
10102
  recentFullActions?: number;
10093
- /** Prune error entries after a successful (non-error) turn. */
10094
- pruneErrors?: boolean;
10095
10103
  /** Rank-based pruning of low-value actions. Off by default for built-in presets. */
10096
10104
  rankPruning?: {
10097
10105
  enabled?: boolean;
package/index.d.ts CHANGED
@@ -10036,7 +10036,8 @@ interface AxCodeSession {
10036
10036
  type AxContextPolicyPreset = 'full' | 'adaptive' | 'lean';
10037
10037
  /**
10038
10038
  * Public context policy for the Actor loop.
10039
- * Presets provide the common behavior; `state` and `expert` override specific pieces.
10039
+ * Presets provide the common behavior; top-level toggles plus `state`,
10040
+ * `checkpoints`, and `expert` override specific pieces.
10040
10041
  */
10041
10042
  interface AxContextPolicyConfig {
10042
10043
  /**
@@ -10064,6 +10065,15 @@ interface AxContextPolicyConfig {
10064
10065
  * - `lean`: true
10065
10066
  */
10066
10067
  pruneUsedDocs?: boolean;
10068
+ /**
10069
+ * Prune error entries after a successful (non-error) turn.
10070
+ *
10071
+ * Defaults by preset:
10072
+ * - `full`: false
10073
+ * - `adaptive`: true
10074
+ * - `lean`: true
10075
+ */
10076
+ pruneErrors?: boolean;
10067
10077
  /** Runtime-state visibility controls. */
10068
10078
  state?: {
10069
10079
  /** Include a compact live runtime state block ahead of the action log. */
@@ -10090,8 +10100,6 @@ interface AxContextPolicyConfig {
10090
10100
  replay?: 'full' | 'adaptive' | 'minimal';
10091
10101
  /** Number of most-recent actions that should always remain fully rendered. */
10092
10102
  recentFullActions?: number;
10093
- /** Prune error entries after a successful (non-error) turn. */
10094
- pruneErrors?: boolean;
10095
10103
  /** Rank-based pruning of low-value actions. Off by default for built-in presets. */
10096
10104
  rankPruning?: {
10097
10105
  enabled?: boolean;
package/index.global.js CHANGED
@@ -712,7 +712,7 @@ ${we}`)}if(w?.data!==void 0&&Q.push(`Data: ${se(w.data)}`),w?.cause!==void 0){le
712
712
  `)};Q.push(`Caused by: ${ee(w.cause,1)}`)}return Q.join(`
713
713
  `)},z=new Map,q=0,Z=o,X=!1,H=[],oe=b=>{if(!b||typeof b!="object"||Array.isArray(b))return!1;let S=Object.getPrototypeOf(b);return S===Object.prototype||S===null},de=b=>typeof b=="string"&&b.trim().length>0,Ae=b=>{if(!de(b)){if(!oe(b))throw new Error("ask_clarification() choice entries must be non-empty strings or objects with a non-empty label");if(!de(b.label))throw new Error("ask_clarification() choice objects require a non-empty label");if(b.value!==void 0&&!de(b.value))throw new Error("ask_clarification() choice object values must be non-empty strings")}},Re=b=>{if(de(b))return;if(!oe(b))throw new Error("ask_clarification() requires a non-empty string or an object payload");if(!de(b.question))throw new Error("ask_clarification() object payload requires a non-empty question");let S=new Set(["text","number","date","single_choice","multiple_choice"]),F;if(b.type===void 0)F=Array.isArray(b.choices)&&b.choices.length>0?"single_choice":void 0;else{if(typeof b.type!="string"||!S.has(b.type))throw new Error("ask_clarification() object payload type must be one of: text, number, date, single_choice, multiple_choice");F=b.type}let w=F==="single_choice"||F==="multiple_choice",j=b.choices;if(j!==void 0){if(!Array.isArray(j)||j.length===0)throw new Error("ask_clarification() choices must be a non-empty array when provided");for(let W of j)Ae(W)}else if(w)throw new Error("ask_clarification() choice payloads require a non-empty choices array")},ie=(b,S)=>{if(b==="final"){if(S.length===0)throw new Error("final() requires at least one argument");return}if(b==="ask_clarification"){if(S.length!==1)throw new Error("ask_clarification() requires exactly one argument");Re(S[0])}},ne=b=>{if(b==="final"||b==="ask_clarification")return b;let F=/^fn_\d+_(.+)$/.exec(b)?.[1];if(F==="final"||F==="ask_clarification")return F},J=b=>(...S)=>{let F=ne(b);F&&ie(F,S);let w=++q,j=!1,W=new Promise((le,we)=>{z.set(w,{resolve:le,reject:we}),g({type:"fn-call",id:w,name:b,args:S})}),Q=W.then.bind(W),K=W.catch.bind(W),ee=W.finally.bind(W),be=()=>{j=!0},_e=new Proxy(W,{get(le,we,Ne){return we==="then"?(...Ee)=>(be(),Q(...Ee)):we==="catch"?(...Ee)=>(be(),K(...Ee)):we==="finally"?(...Ee)=>(be(),ee(...Ee)):Reflect.get(le,we,Ne)}});return W.catch(le=>{j||H.push(le)}),_e},ye=async()=>{for(let b=0;b<50&&z.size>0;b+=1)await new Promise(S=>{setTimeout(S,0)})},ge=b=>{if(!b||typeof b!="object")return b;if(Array.isArray(b)){for(let F=0;F<b.length;F+=1)b[F]=ge(b[F]);return b}let S=b;if(r in S){let F=S[r];return typeof F=="string"?J(F):void 0}for(let[F,w]of Object.entries(S))S[F]=ge(w);return b},Ie=b=>{for(let[S,F]of Object.entries(b)){let w=ge(F),j=e[S];if(oe(j)&&oe(w)){for(let W of Object.keys(j))Object.hasOwn(w,W)||delete j[W];for(let[W,Q]of Object.entries(w))j[W]=Q;continue}e[S]=w}},Me=b=>{if(b.globals&&typeof b.globals=="object"&&Ie(b.globals),Array.isArray(b.fnNames))for(let S of b.fnNames)typeof S=="string"&&(e[S]=J(S))},ke=async b=>{let S=h(b),F=[];try{F=O(b)}catch{F=[]}let w=M(F),j=S;try{j=_(S)}catch{j=S}let W=j;if(w){let ee=j.lastIndexOf(`
714
714
  return (`);ee!==-1?W=j.slice(0,ee)+w+j.slice(ee):W=j+w}let Q=T(W)?W:T(j)?j:S;return await new n(Q)()},Tt=b=>{let S=k(b),F=[];try{F=O(b)}catch{F=[]}let w=M(F),j=w?S+w:S;return(0,eval)(j)},Qe=(b,S)=>{if(Z!==i)return b;let F=S.join(`
715
- `).trim();return F||b},st=(b,S)=>b.length<=S?b:`${b.slice(0,S-3)}...`,Oe=b=>{if(b===null)return"null";if(b===void 0)return"undefined";let S=typeof b;if(typeof b=="string")return JSON.stringify(st(b,40));if(S==="number"||S==="boolean"||S==="bigint"||S==="symbol")return String(b);if(S==="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 F=b&&typeof b=="object"&&"constructor"in b&&b.constructor&&typeof b.constructor.name=="string"?b.constructor.name??"":"";return F&&F!=="Object"?`[${F}]`:"[object]"},Ke=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 S=typeof b;return S!=="object"?{type:S}:{type:"object",ctor:b&&typeof b=="object"&&"constructor"in b&&b.constructor&&typeof b.constructor.name=="string"?b.constructor.name??void 0:void 0}},G=(b,S)=>{if(S==="string")return`${b.length} chars`;if(S==="array")return`${b.length} items`;if(S==="map"||S==="set")return`${b.size} items`;if(S==="object"&&b&&typeof b=="object")return`${Object.keys(b).length} keys`},Y=(b,S,F)=>{if(S==="array")return"["+b.slice(0,3).map(j=>Oe(j)).join(", ")+(b.length>3?", ...":"")+"]";if(S==="map"){let w=b,j=Array.from(w.entries()).slice(0,3).map(([W,Q])=>`${Oe(W)} => ${Oe(Q)}`);return"Map("+w.size+") {"+j.join(", ")+(w.size>3?", ...":"")+"}"}if(S==="set"){let w=b,j=Array.from(w.values()).slice(0,5).map(W=>Oe(W));return"Set("+w.size+") {"+j.join(", ")+(w.size>5?", ...":"")+"}"}if(S==="date"||S==="error"||S==="function")return Oe(b);if(S==="object"&&b&&typeof b=="object"){let w=Object.keys(b),j=w.slice(0,4);return(F&&F!=="Object"?`${F} `:"")+"{"+j.join(", ")+(w.length>j.length?", ...":"")+"}"}return Oe(b)},ue=b=>{let S=new Set([...t,...b??[]]),F=Object.getOwnPropertyNames(e).filter(w=>!S.has(w)&&!w.startsWith("_")).sort().flatMap(w=>{try{let j=Object.getOwnPropertyDescriptor(e,w);if(!j)return[];if("get"in j&&typeof j.get=="function"&&!("value"in j))return[{name:w,type:"accessor",preview:"[getter omitted]"}];let W="value"in j?j.value:e[w],Q=Ke(W),K=G(W,Q.type),ee=Y(W,Q.type,Q.ctor);return[{name:w,type:Q.type,...Q.ctor?{ctor:Q.ctor}:{},...K?{size:K}:{},...ee?{preview:st(ee,96)}:{}}]}catch{return[{name:w,type:"unknown",preview:"[unavailable]"}]}});return JSON.stringify({version:1,entries:F})},Se=b=>{if(typeof structuredClone=="function")try{return structuredClone(b),!0}catch{return!1}try{return JSON.stringify(b),!0}catch{return!1}},ze=b=>{let S=new Set([...t,...b??[]]),F={};return{version:1,entries:Object.getOwnPropertyNames(e).filter(j=>!S.has(j)&&!j.startsWith("_")).sort().flatMap(j=>{try{let W=Object.getOwnPropertyDescriptor(e,j);if(!W)return[];if("get"in W&&typeof W.get=="function"&&!("value"in W))return[{name:j,type:"accessor",preview:"[getter omitted]",restorable:!1}];let Q="value"in W?W.value:e[j],K=Ke(Q),ee=G(Q,K.type),be=Y(Q,K.type,K.ctor),_e=Se(Q);return _e&&(F[j]=typeof structuredClone=="function"?structuredClone(Q):Q),[{name:j,type:K.type,...K.ctor?{ctor:K.ctor}:{},...ee?{size:ee}:{},...be?{preview:st(be,96)}:{},restorable:_e}]}catch{return[{name:j,type:"unknown",preview:"[unavailable]",restorable:!1}]}}),bindings:F}};f(async b=>{let S=b.data;if(!S||typeof S!="object"||typeof S.type!="string")return;if(S.type==="init"){Z=S.outputMode===i?i:o,X=S.captureConsole!==void 0?!!S.captureConsole:Z===i;let K=S.allowUnsafeNodeHostAccess===!0;Me(S),t=Object.getOwnPropertyNames(e).sort(),$(S.permissions),D(K);return}if(S.type==="fn-result"){if(typeof S.id!="number")return;let K=z.get(S.id);K&&(z.delete(S.id),S.error!==void 0?K.reject(U(S.error)):K.resolve(S.value));return}if(S.type==="update-globals"){if(typeof S.id!="number")return;try{S.globals&&typeof S.globals=="object"&&Ie(S.globals),g({type:"result",id:S.id,value:void 0})}catch(K){g({type:"result",id:S.id,error:B(K)})}return}if(S.type==="inspect-globals"){if(typeof S.id!="number")return;try{let K=Array.isArray(S.reservedNames)?S.reservedNames.filter(ee=>typeof ee=="string"):void 0;g({type:"result",id:S.id,value:ue(K)})}catch(K){g({type:"result",id:S.id,error:B(K)})}return}if(S.type==="snapshot-globals"){if(typeof S.id!="number")return;try{let K=Array.isArray(S.reservedNames)?S.reservedNames.filter(ee=>typeof ee=="string"):void 0;g({type:"result",id:S.id,value:ze(K)})}catch(K){g({type:"result",id:S.id,error:B(K)})}return}if(S.type!=="execute"||typeof S.id!="number"||typeof S.code!="string")return;let F=S.id,w=S.code,j=/\bawait\b/.test(w),{output:W,cleanup:Q}=R();try{H.length=0;let K=j?await ke(w):Tt(w);if(z.size>0&&await ye(),await Promise.resolve(),H.length>0)throw H[0];let ee=Qe(K,W);try{g({type:"result",id:F,value:ee})}catch{g({type:"result",id:F,value:String(ee)})}}catch(K){V(K)?g({type:"result",id:F,value:he(K,w,j?2:0)}):g({type:"result",id:F,error:B(K)})}finally{Q()}})}var Ea=4,Qc=16,Ma="__ax_rlm_fn_ref__",Pa=16;function Zc(){let s={functionRefKey:Ma,maxErrorCauseDepth:Pa},e=`(${_s.toString()})(${JSON.stringify(s)});
715
+ `).trim();return F||b},st=(b,S)=>b.length<=S?b:`${b.slice(0,S-3)}...`,Oe=b=>{if(b===null)return"null";if(b===void 0)return"undefined";let S=typeof b;if(typeof b=="string")return JSON.stringify(st(b,40));if(S==="number"||S==="boolean"||S==="bigint"||S==="symbol")return String(b);if(S==="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 F=b&&typeof b=="object"&&"constructor"in b&&b.constructor&&typeof b.constructor.name=="string"?b.constructor.name??"":"";return F&&F!=="Object"?`[${F}]`:"[object]"},Ke=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 S=typeof b;return S!=="object"?{type:S}:{type:"object",ctor:b&&typeof b=="object"&&"constructor"in b&&b.constructor&&typeof b.constructor.name=="string"?b.constructor.name??void 0:void 0}},G=(b,S)=>{if(S==="string")return`${b.length} chars`;if(S==="array")return`${b.length} items`;if(S==="map"||S==="set")return`${b.size} items`;if(S==="object"&&b&&typeof b=="object")return`${Object.keys(b).length} keys`},Y=(b,S,F)=>{if(S==="array")return"["+b.slice(0,3).map(j=>Oe(j)).join(", ")+(b.length>3?", ...":"")+"]";if(S==="map"){let w=b,j=Array.from(w.entries()).slice(0,3).map(([W,Q])=>`${Oe(W)} => ${Oe(Q)}`);return"Map("+w.size+") {"+j.join(", ")+(w.size>3?", ...":"")+"}"}if(S==="set"){let w=b,j=Array.from(w.values()).slice(0,5).map(W=>Oe(W));return"Set("+w.size+") {"+j.join(", ")+(w.size>5?", ...":"")+"}"}if(S==="date"||S==="error"||S==="function")return Oe(b);if(S==="object"&&b&&typeof b=="object"){let w=Object.keys(b),j=w.slice(0,4);return(F&&F!=="Object"?`${F} `:"")+"{"+j.join(", ")+(w.length>j.length?", ...":"")+"}"}return Oe(b)},ue=b=>{let S=new Set([...t,...b??[]]),F=Object.getOwnPropertyNames(e).filter(w=>!S.has(w)&&!w.startsWith("_")).sort().flatMap(w=>{try{let j=Object.getOwnPropertyDescriptor(e,w);if(!j)return[];if("get"in j&&typeof j.get=="function"&&!("value"in j))return[{name:w,type:"accessor",preview:"[getter omitted]"}];let W="value"in j?j.value:e[w],Q=Ke(W),K=G(W,Q.type),ee=Y(W,Q.type,Q.ctor);return[{name:w,type:Q.type,...Q.ctor?{ctor:Q.ctor}:{},...K?{size:K}:{},...ee?{preview:st(ee,96)}:{}}]}catch{return[{name:w,type:"unknown",preview:"[unavailable]"}]}});return JSON.stringify({version:1,entries:F})},Se=b=>{if(typeof structuredClone=="function")try{return structuredClone(b),!0}catch{return!1}try{return JSON.stringify(b),!0}catch{return!1}},ze=b=>{let S=new Set([...t,...b??[]]),F={};return{version:1,entries:Object.getOwnPropertyNames(e).filter(j=>!S.has(j)&&!j.startsWith("_")).sort().flatMap(j=>{try{let W=Object.getOwnPropertyDescriptor(e,j);if(!W)return[];if("get"in W&&typeof W.get=="function"&&!("value"in W))return[{name:j,type:"accessor",preview:"[getter omitted]",restorable:!1}];let Q="value"in W?W.value:e[j],K=Ke(Q),ee=G(Q,K.type),be=Y(Q,K.type,K.ctor),_e=Se(Q);return _e&&(F[j]=typeof structuredClone=="function"?structuredClone(Q):Q),[{name:j,type:K.type,...K.ctor?{ctor:K.ctor}:{},...ee?{size:ee}:{},...be?{preview:st(be,96)}:{},restorable:_e}]}catch{return[{name:j,type:"unknown",preview:"[unavailable]",restorable:!1}]}}),bindings:F}};f(async b=>{let S=b.data;if(!S||typeof S!="object"||typeof S.type!="string")return;if(S.type==="init"){Z=S.outputMode===i?i:o,X=S.captureConsole!==void 0?!!S.captureConsole:Z===i;let K=S.allowUnsafeNodeHostAccess===!0;Me(S),$(S.permissions),D(K),t=Object.getOwnPropertyNames(e).sort();return}if(S.type==="fn-result"){if(typeof S.id!="number")return;let K=z.get(S.id);K&&(z.delete(S.id),S.error!==void 0?K.reject(U(S.error)):K.resolve(S.value));return}if(S.type==="update-globals"){if(typeof S.id!="number")return;try{S.globals&&typeof S.globals=="object"&&Ie(S.globals),g({type:"result",id:S.id,value:void 0})}catch(K){g({type:"result",id:S.id,error:B(K)})}return}if(S.type==="inspect-globals"){if(typeof S.id!="number")return;try{let K=Array.isArray(S.reservedNames)?S.reservedNames.filter(ee=>typeof ee=="string"):void 0;g({type:"result",id:S.id,value:ue(K)})}catch(K){g({type:"result",id:S.id,error:B(K)})}return}if(S.type==="snapshot-globals"){if(typeof S.id!="number")return;try{let K=Array.isArray(S.reservedNames)?S.reservedNames.filter(ee=>typeof ee=="string"):void 0;g({type:"result",id:S.id,value:ze(K)})}catch(K){g({type:"result",id:S.id,error:B(K)})}return}if(S.type!=="execute"||typeof S.id!="number"||typeof S.code!="string")return;let F=S.id,w=S.code,j=/\bawait\b/.test(w),{output:W,cleanup:Q}=R();try{H.length=0;let K=j?await ke(w):Tt(w);if(z.size>0&&await ye(),await Promise.resolve(),H.length>0)throw H[0];let ee=Qe(K,W);try{g({type:"result",id:F,value:ee})}catch{g({type:"result",id:F,value:String(ee)})}}catch(K){V(K)?g({type:"result",id:F,value:he(K,w,j?2:0)}):g({type:"result",id:F,error:B(K)})}finally{Q()}})}var Ea=4,Qc=16,Ma="__ax_rlm_fn_ref__",Pa=16;function Zc(){let s={functionRefKey:Ma,maxErrorCauseDepth:Pa},e=`(${_s.toString()})(${JSON.stringify(s)});
716
716
  `,t="";return e.includes("__name")&&(t+=`var __name=(fn,_n)=>fn;
717
717
  `),t?`${t}${e}`:e}var Xc=()=>typeof Worker<"u"&&typeof Blob<"u"&&typeof URL<"u"&&typeof URL.createObjectURL=="function",Ns=()=>typeof process<"u"&&!!process.versions?.node,mg=()=>!!globalThis.Deno?.version?.deno,gg=()=>globalThis.Deno?.version?.deno??null,fg=s=>{let e=/^(\d+)\.(\d+)\.(\d+)$/.exec(s.trim());return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3])}:null},ep=s=>Number.isFinite(s)?Math.max(1,Math.min(Qc,Math.floor(s))):Ea,hg=()=>{if(!Ns())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},xg=s=>{if(s!==void 0)return ep(s);let e=hg();return e?ep(Math.ceil(e/2)):Ea},Ag=s=>s?.debugNodeWorkerPool?!0:(globalThis.process?.env??{}).AX_RLM_DEBUG_NODE_POOL==="1",yg=s=>{let e=new Set(s),t={};return e.has("network")&&(t.net=!0),Object.keys(t).length>0?t:"none"},bg=(s,e)=>{let t=gg(),n=t?fg(t):null;if(n?n.major>=1:!0)try{return new Worker(s,{type:"module",deno:{permissions:yg(e)}})}catch{}return new Worker(s,{type:"module"})},tp=(s,e)=>{let t=new Blob([s],{type:"application/javascript"}),n=URL.createObjectURL(t),r=mg()?bg(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},$a=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},La=class{source;maxSize;idle=[];pendingCreates=0;constructor(e,t){this.source=e,this.maxSize=t}warm(){if(Ns())for(;this.idle.length+this.pendingCreates<this.maxSize;)this.pendingCreates+=1,$a(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(),$a(this.source)}release(e){e.onmessage=null,e.onerror=null,e.terminate(),this.warm()}},np=new Map,Ig=(s,e)=>`${e}:${s}`,Cg=(s,e)=>{let t=Ig(s,e),n=np.get(t);if(n)return n;let r=new La(s,e);return np.set(t,r),r},rp=(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),{[Ma]: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}},op=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}`)}},Fa=s=>!!s&&/[A-Za-z0-9_$]/.test(s),_a=s=>!!s&&/[A-Za-z_$]/.test(s),Tg=(s,e)=>{let t=new Set(e);for(let m of eo(s))if(t.has(m))return m;let n=or(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&&Fa(n[o]);)o++;return n.slice(m,o)},d=m=>{let g=n.slice(m,m+2);return n.slice(m,m+3)==="==="||g==="=="||g==="=>"?!1:n[m]==="="||["+=","-=","*=","/=","%=","&=","|=","^=","&&=","||=","??=","**=","<<=",">>=",">>>="].some(h=>n.startsWith(h,m))};for(;o<r;){let m=n[o];if(m==="{"){i++,o++;continue}if(m==="}"){i--,o++;continue}if(m==="("){a++,o++;continue}if(m===")"){a--,o++;continue}if(i===0&&a===0&&_a(m)){let g=o,f=p();if((f==="function"||f==="class")&&c(g)){let h=u(o);if(_a(n[h])){let A=h+1;for(;A<r&&Fa(n[A]);)A++;let x=n.slice(h,A);if(t.has(x))return x}continue}if(f==="async"&&c(g)){let h=u(o);if(n.startsWith("function",h)){let A=u(h+8);if(_a(n[A])){let x=A+1;for(;x<r&&Fa(n[x]);)x++;let y=n.slice(A,x);if(t.has(y))return y}}continue}if(t.has(f)){let h=l(g-1),A=h>=0?n[h]:void 0,x=u(o),y=A==="."||A==="?"||A==="["&&n[x]==="]",I=n.startsWith("++",x)||n.startsWith("--",x)||h>0&&(n.slice(h-1,h+1)==="++"||n.slice(h-1,h+1)==="--");if(!y&&(I||d(x)))return f}continue}o++}};function Na(s){if(s==null||typeof s!="object")return String(s);try{return JSON.stringify(s,null,2)}catch{return String(s)}}function sp(s,e=Pa,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):Na(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=sp(p,e,t+1,n):a={name:"Error",message:Na(p)}}catch{a={name:"Error",message:Na(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 ip(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=ip(s.cause)),s.data!==void 0&&(t.data=s.data),t}function wg(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 Rg(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(wg),bindings:n}}var Da=(i=>(i.NETWORK="network",i.STORAGE="storage",i.CODE_LOADING="code-loading",i.COMMUNICATION="communication",i.TIMING="timing",i.WORKERS="workers",i))(Da||{}),sn=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=xg(e?.nodeWorkerPoolSize),this.debugNodeWorkerPool=Ag(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 Mp(s,e){return e.qualifiedName===s||e.name===s||e.qualifiedName.endsWith(`.${s}`)}function pf(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=>Mp(a,u))).length;n*=.5+.5*(i/r.length)}return(e.forbiddenActions??[]).some(i=>t.functionCalls.some(a=>Mp(i,a)))&&(n*=.2),Math.max(0,Math.min(1,n))}function df(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 lr=class extends Error{constructor(t){super(`AxAgent protocol completion: ${t}`);this.type=t;this.name="AxAgentProtocolCompletionSignal"}};function Pp(s){return{finalFunction:(...r)=>{s("final",r)},askClarificationFunction:(...r)=>{s("ask_clarification",r)},protocol:{final:(...r)=>{throw s("final",r),new lr("final")},askClarification:(...r)=>{throw s("ask_clarification",r),new lr("ask_clarification")}}}}function mf(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 Fp(s){let e=s?.preset??"full",t=gf(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:nf,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 gf(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 oo=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=Hs;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",Hs,this.agentModuleNamespace,...this.functionDiscoveryEnabled?[Ka,Wa]:[]])}_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:h,mode:A,recursionOptions:x,actorOptions:y,responderOptions:I,judgeOptions:C,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=l??new sn,this.runtimeUsageInstructions=this.runtime.getUsageInstructions(),this.enforceIncrementalConsoleTurns=Df(this.runtimeUsageInstructions);let _=r??n?.namespace??Hs;if(this.agentModuleNamespace=zf(_,{normalize:r===void 0}),new Set(["inputs","llmQuery","final","ask_clarification","inspect_runtime",Ka,Wa]).has(this.agentModuleNamespace))throw new Error(`Agent module namespace "${this.agentModuleNamespace}" is reserved`);let O=this._reservedAgentFunctionNamespaces(),M=Va(i.functions?.local,O),P=Va(i.functions?.shared,O),N=Va(i.functions?.globallyShared,O);this.agentFunctions=M.functions,this._mergeAgentFunctionModuleMetadata(M.moduleMetadata);let{agents:v,fields:R,functions:E,judgeOptions:$,inputUpdateCallback:D,...L}=i;this.program=new ve(o,L);let B=this.program.getSignature().getInputFields(),U=Nf(u,B,tf);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:h,mode:A},this.recursionForwardOptions=x;let{description:V,...se}=y??{},{description:he,...z}=I??{};this.actorDescription=V,this.actorForwardOptions=se,this.responderDescription=he,this.responderForwardOptions=z,this.judgeOptions=C?{...C}:void 0,this.inputUpdateCallback=T;let q=this.agents;for(let ne of q??[]){let J=ne.getFunction().name;this.program.register(ne,J)}n&&(this.func={name:Jp(n.name),description:n.description,parameters:this._buildFuncParameters(),func:async()=>{throw new Error("Use getFunction() to get a callable wrapper")}});let Z=f??[];this.actorFieldNames=Z;let X=i.fields?.shared??[];this.sharedFieldNames=X,this.excludedSharedFields=i.fields?.excluded??[];let H=i.fields?.globallyShared??[];this.globalSharedFieldNames=H,this.localFieldNames=i.fields?.local??[];let oe=i.agents?.shared??[],de=i.agents?.globallyShared??[];this.excludedAgents=i.agents?.excluded??[];let Ae=P.functions,Re=N.functions;this.excludedAgentFunctions=i.functions?.excluded??[];let ie=[...this.agentFunctions,...Ae,...Re];for(let ne of ie){if(!ne.parameters)throw new Error(`Agent function "${ne.name}" must define parameters schema for agent runtime usage.`);if(ne.examples){for(let[J,ye]of ne.examples.entries())if(!ye.code.trim())throw new Error(`Agent function "${ne.name}" example at index ${J} must define non-empty code`)}}if(this._validateConfiguredSignature(this.program.getSignature()),this._validateAgentFunctionNamespaces(ie),X.length>0&&q){let ne=B.filter(J=>X.includes(J.name));for(let J of q){if(!(J instanceof s))continue;let ye=new Set(J.getExcludedSharedFields()),ge=ne.filter(Ie=>!ye.has(Ie.name));ge.length!==0&&J._extendForSharedFields(ge,this.rlmConfig.contextFields)}}if(oe.length>0&&q)for(let ne of q)ne instanceof s&&ne._extendForSharedAgents(oe);if(H.length>0&&q){let ne=B.filter(J=>H.includes(J.name));for(let J of q){if(!(J instanceof s))continue;let ye=new Set(J.getExcludedSharedFields()),ge=ne.filter(Ie=>!ye.has(Ie.name));ge.length!==0&&J._extendForGlobalSharedFields(ge,this.rlmConfig.contextFields)}}if(de.length>0&&q)for(let ne of q)ne instanceof s&&ne._extendForGlobalSharedAgents(de);if(Ae.length>0&&q)for(let ne of q)ne instanceof s&&ne._extendForSharedAgentFunctions(P);if(Re.length>0&&q)for(let ne of q)ne instanceof s&&ne._extendForGlobalSharedAgentFunctions(N);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)),o=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)),l=a.filter(T=>!this.actorFieldNames.includes(T.name)),c=fe().addInputFields(i).addInputFields(o).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&&(c=c.addOutputFields(u));let p=c.build(),d=fe().addInputFields(i).input("contextData",fe.json("Context data to help synthesize the final answer.")).addOutputFields(l).build(),m=this.rlmConfig.maxSubAgentCalls??Op,g=this.rlmConfig.maxTurns??Ep,f=this.agents?.map(T=>{let _=T.getFunction();return{name:_.name,description:_.description,parameters:_.parameters}})??[],h=this.agentFunctions.map(T=>({name:T.name,description:T.description,parameters:T.parameters,returns:T.returns,namespace:T.namespace??"utils"})),A=new Set(h.map(T=>T.namespace??"utils"));f.length>0&&A.add(this.agentModuleNamespace);let x=[...A].sort((T,_)=>T.localeCompare(_)).map(T=>({namespace:T,selectionCriteria:this.agentFunctionModuleMetadata.get(T)?.selectionCriteria})),y=Fp(this.rlmConfig.contextPolicy),I=zs(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:x,agents:f,agentFunctions:h}),C=qs(this.responderDescription,r);this.actorProgram?(this.actorProgram.setSignature(p),this.actorProgram.setDescription(I)):this.actorProgram=new ve(p,{...this._genOptions,description:I}),this.responderProgram?(this.responderProgram.setSignature(d),this.responderProgram.setDescription(C)):this.responderProgram=new ve(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?ar(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?ar(e):void 0,this.stateError=void 0}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 o=t?.judgeAI??this.judgeAI??t?.teacherAI??this.ai??r,i={...this.judgeOptions??{},...t?.judgeOptions??{}},a=df(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(rf,n.train.length*4))),d=await new Kt({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:()=>af,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=cf(t.criteria),r=new Ht(sf,{ai:e,...t,criteria:n});return async({example:o,prediction:i})=>{let a=o,u=i,l={taskInput:gt(a.input),criteria:a.criteria,expectedOutput:a.expectedOutput,expectedActions:a.expectedActions,forbiddenActions:a.forbiddenActions,metadata:a.metadata},c={completionType:u.completionType,clarification:gt(u.clarification),finalOutput:gt(u.output),actionLog:u.actionLog,functionCalls:gt(u.functionCalls),toolErrors:u.toolErrors,turnCount:u.turnCount,usage:gt(u.usage??[])},p=await r.evaluate(l,c);return pf(p.score,a,u)}}async _forwardForEvaluation(e,t,n){let r=this.state?ar(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=Rt(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),h=c.filter(y=>!!y.error).map(y=>`${y.qualifiedName}: ${y.error??"unknown error"}`);if(d.type==="ask_clarification")return{completionType:"ask_clarification",clarification:qp(d.args[0]),actionLog:g,functionCalls:c,toolErrors:h,turnCount:f};let A={...this._genOptions,...this.responderForwardOptions,...n,debug:l,abortSignal:a,maxSteps:1};return{completionType:"final",output:{...await this.responderProgram.forward(u,{...p,contextData:d},A),...m},actionLog:g,functionCalls:c,toolErrors:h,turnCount:f}}finally{this.state=r?ar(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 Mp(s,e){return e.qualifiedName===s||e.name===s||e.qualifiedName.endsWith(`.${s}`)}function pf(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=>Mp(a,u))).length;n*=.5+.5*(i/r.length)}return(e.forbiddenActions??[]).some(i=>t.functionCalls.some(a=>Mp(i,a)))&&(n*=.2),Math.max(0,Math.min(1,n))}function df(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 lr=class extends Error{constructor(t){super(`AxAgent protocol completion: ${t}`);this.type=t;this.name="AxAgentProtocolCompletionSignal"}};function Pp(s){return{finalFunction:(...r)=>{s("final",r)},askClarificationFunction:(...r)=>{s("ask_clarification",r)},protocol:{final:(...r)=>{throw s("final",r),new lr("final")},askClarification:(...r)=>{throw s("ask_clarification",r),new lr("ask_clarification")}}}}function mf(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 Fp(s){let e=s?.preset??"full",t=gf(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:nf,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 gf(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 oo=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=Hs;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",Hs,this.agentModuleNamespace,...this.functionDiscoveryEnabled?[Ka,Wa]:[]])}_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:h,mode:A,recursionOptions:x,actorOptions:y,responderOptions:I,judgeOptions:C,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=l??new sn,this.runtimeUsageInstructions=this.runtime.getUsageInstructions(),this.enforceIncrementalConsoleTurns=Df(this.runtimeUsageInstructions);let _=r??n?.namespace??Hs;if(this.agentModuleNamespace=zf(_,{normalize:r===void 0}),new Set(["inputs","llmQuery","final","ask_clarification","inspect_runtime",Ka,Wa]).has(this.agentModuleNamespace))throw new Error(`Agent module namespace "${this.agentModuleNamespace}" is reserved`);let O=this._reservedAgentFunctionNamespaces(),M=Va(i.functions?.local,O),P=Va(i.functions?.shared,O),N=Va(i.functions?.globallyShared,O);this.agentFunctions=M.functions,this._mergeAgentFunctionModuleMetadata(M.moduleMetadata);let{agents:v,fields:R,functions:E,judgeOptions:$,inputUpdateCallback:D,...L}=i;this.program=new ve(o,L);let B=this.program.getSignature().getInputFields(),U=Nf(u,B,tf);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:h,mode:A},this.recursionForwardOptions=x;let{description:V,...se}=y??{},{description:he,...z}=I??{};this.actorDescription=V,this.actorForwardOptions=se,this.responderDescription=he,this.responderForwardOptions=z,this.judgeOptions=C?{...C}:void 0,this.inputUpdateCallback=T;let q=this.agents;for(let ne of q??[]){let J=ne.getFunction().name;this.program.register(ne,J)}n&&(this.func={name:Jp(n.name),description:n.description,parameters:this._buildFuncParameters(),func:async()=>{throw new Error("Use getFunction() to get a callable wrapper")}});let Z=f??[];this.actorFieldNames=Z;let X=i.fields?.shared??[];this.sharedFieldNames=X,this.excludedSharedFields=i.fields?.excluded??[];let H=i.fields?.globallyShared??[];this.globalSharedFieldNames=H,this.localFieldNames=i.fields?.local??[];let oe=i.agents?.shared??[],de=i.agents?.globallyShared??[];this.excludedAgents=i.agents?.excluded??[];let Ae=P.functions,Re=N.functions;this.excludedAgentFunctions=i.functions?.excluded??[];let ie=[...this.agentFunctions,...Ae,...Re];for(let ne of ie){if(!ne.parameters)throw new Error(`Agent function "${ne.name}" must define parameters schema for agent runtime usage.`);if(ne.examples){for(let[J,ye]of ne.examples.entries())if(!ye.code.trim())throw new Error(`Agent function "${ne.name}" example at index ${J} must define non-empty code`)}}if(this._validateConfiguredSignature(this.program.getSignature()),this._validateAgentFunctionNamespaces(ie),X.length>0&&q){let ne=B.filter(J=>X.includes(J.name));for(let J of q){if(!(J instanceof s))continue;let ye=new Set(J.getExcludedSharedFields()),ge=ne.filter(Ie=>!ye.has(Ie.name));ge.length!==0&&J._extendForSharedFields(ge,this.rlmConfig.contextFields)}}if(oe.length>0&&q)for(let ne of q)ne instanceof s&&ne._extendForSharedAgents(oe);if(H.length>0&&q){let ne=B.filter(J=>H.includes(J.name));for(let J of q){if(!(J instanceof s))continue;let ye=new Set(J.getExcludedSharedFields()),ge=ne.filter(Ie=>!ye.has(Ie.name));ge.length!==0&&J._extendForGlobalSharedFields(ge,this.rlmConfig.contextFields)}}if(de.length>0&&q)for(let ne of q)ne instanceof s&&ne._extendForGlobalSharedAgents(de);if(Ae.length>0&&q)for(let ne of q)ne instanceof s&&ne._extendForSharedAgentFunctions(P);if(Re.length>0&&q)for(let ne of q)ne instanceof s&&ne._extendForGlobalSharedAgentFunctions(N);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)),o=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)),l=a.filter(T=>!this.actorFieldNames.includes(T.name)),c=fe().addInputFields(i).addInputFields(o).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&&(c=c.addOutputFields(u));let p=c.build(),d=fe().addInputFields(i).input("contextData",fe.json("Context data to help synthesize the final answer.")).addOutputFields(l).build(),m=this.rlmConfig.maxSubAgentCalls??Op,g=this.rlmConfig.maxTurns??Ep,f=this.agents?.map(T=>{let _=T.getFunction();return{name:_.name,description:_.description,parameters:_.parameters}})??[],h=this.agentFunctions.map(T=>({name:T.name,description:T.description,parameters:T.parameters,returns:T.returns,namespace:T.namespace??"utils"})),A=new Set(h.map(T=>T.namespace??"utils"));f.length>0&&A.add(this.agentModuleNamespace);let x=[...A].sort((T,_)=>T.localeCompare(_)).map(T=>({namespace:T,selectionCriteria:this.agentFunctionModuleMetadata.get(T)?.selectionCriteria})),y=Fp(this.rlmConfig.contextPolicy),I=zs(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:x,agents:f,agentFunctions:h}),C=qs(this.responderDescription,r);this.actorProgram?(this.actorProgram.setSignature(p),this.actorProgram.setDescription(I)):this.actorProgram=new ve(p,{...this._genOptions,description:I}),this.responderProgram?(this.responderProgram.setSignature(d),this.responderProgram.setDescription(C)):this.responderProgram=new ve(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?ar(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?ar(e):void 0,this.stateError=void 0}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 o=t?.judgeAI??this.judgeAI??t?.teacherAI??this.ai??r,i={...this.judgeOptions??{},...t?.judgeOptions??{}},a=df(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(rf,n.train.length*4))),d=await new Kt({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:()=>af,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=cf(t.criteria),r=new Ht(sf,{ai:e,...t,criteria:n});return async({example:o,prediction:i})=>{let a=o,u=i,l={taskInput:gt(a.input),criteria:a.criteria,expectedOutput:a.expectedOutput,expectedActions:a.expectedActions,forbiddenActions:a.forbiddenActions,metadata:a.metadata},c={completionType:u.completionType,clarification:gt(u.clarification),finalOutput:gt(u.output),actionLog:u.actionLog,functionCalls:gt(u.functionCalls),toolErrors:u.toolErrors,turnCount:u.turnCount,usage:gt(u.usage??[])},p=await r.evaluate(l,c);return pf(p.score,a,u)}}async _forwardForEvaluation(e,t,n){let r=this.state?ar(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=Rt(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),h=c.filter(y=>!!y.error).map(y=>`${y.qualifiedName}: ${y.error??"unknown error"}`);if(d.type==="ask_clarification")return{completionType:"ask_clarification",clarification:qp(d.args[0]),actionLog:g,functionCalls:c,toolErrors:h,turnCount:f};let A={...this._genOptions,...this.responderForwardOptions,...n,debug:l,abortSignal:a,maxSteps:1};return{completionType:"final",output:{...await this.responderProgram.forward(u,{...p,contextData:d},A),...m},actionLog:g,functionCalls:c,toolErrors:h,turnCount:f}}finally{this.state=r?ar(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(h=>h.role==="user").reduce((h,A)=>({...h,...A.values}),{}):n=e;let r=t?.allowedFieldNames?new Set(t.allowedFieldNames):void 0;if(r&&t?.validateInputKeys){for(let h of Object.keys(n))if(!r.has(h))throw new Error(`AxAgent.test() only accepts context field values. "${h}" is not configured in contextFields.`)}let o={...n},i=r?new Set(r):new Set(this.program.getSignature().getInputFields().map(h=>h.name)),a=[...this.sharedFieldNames,...this.globalSharedFieldNames],u=this._getBypassedSharedFieldNames(),l={},c={},p={},d={},m="(none)",g=new Set(this.program.getSignature().getInputFields().filter(h=>this.rlmConfig.contextFields.includes(h.name)&&h.isOptional).map(h=>h.name));return{currentInputs:o,signatureInputFieldNames:i,sharedFieldValues:l,recomputeTurnInputs:h=>{let A={},x={};for(let[I,C]of Object.entries(o))this.rlmConfig.contextFields.includes(I)?A[I]=C:u.has(I)||(x[I]=C);if(h){for(let I of this.rlmConfig.contextFields)if(!g.has(I)&&(!(I in A)||A[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 A))continue;let T=Pf(A[I],C);T!==void 0&&(y[I]=T)}c=A,p=x,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=$f(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??Op,m=c.maxRuntimeChars??Zg,g=Math.max(1,c.maxBatchedLlmQueryConcurrency??Xg),f=this.recursionForwardOptions?.maxDepth??ef,h=Math.max(0,f),A=Fp(c.contextPolicy),x=0,y=Math.floor(d*.8),{maxDepth:I,...C}=this.recursionForwardOptions??{},{description:T,mem:_,sessionId:k,...O}=n??{},M={...this.recursionForwardOptions??{},maxDepth:Math.max(0,h-1)},P=["context"],N=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(),R=(c.mode??"simple")==="advanced"&&(M.maxDepth??0)>0?"advanced":"simple",E;h>0&&(R==="advanced"?E=new s({agentModuleNamespace:this.agentModuleNamespace,signature:N},{debug:o,...c,agents:{local:this.agents},functions:{local:this.agentFunctions,discovery:this.functionDiscoveryEnabled},contextFields:P,actorFields:void 0,recursionOptions:M,actorOptions:this.actorForwardOptions,responderOptions:this.responderForwardOptions}):E=new ve(N,M));let $=async(G,Y)=>{if(!Array.isArray(G)&&typeof G=="object"&&G!==null&&"query"in G)return $(G.query,G.context??Y);if(r?.aborted)throw new Le("rlm-llm-query",r.reason?String(r.reason):"Aborted");if(Array.isArray(G))return Lf(G,g,async S=>{try{return await $(S.query,S.context)}catch(F){if(F instanceof Le)throw F;return`[ERROR] ${F instanceof Error?F.message:String(F)}`}});if(!e)throw new Error(of);let ue=G,Se=S=>{if(S==null)return"";if(typeof S=="string")return ft(S,m);try{return ft(JSON.stringify(S),m)}catch{return ft(String(S),m)}},b=await(async(S,F)=>{let w=F===void 0?void 0:typeof F=="string"?ft(F,m):F;if(x++,x>d)return`[ERROR] Sub-query budget exhausted (${d}/${d}). Use the data you have already accumulated to produce your final answer.`;if(h<=0||!E)return`[ERROR] Recursion depth limit reached (${f}).`;let j=3,W,Q=K=>`[ERROR] ${K instanceof Error?K.message:String(K)}`;for(let K=0;K<j;K++)try{let ee=await E.forward(e,{task:S,...w!==void 0?{context:w}:R==="advanced"?{context:""}:{}},{...O,...C,abortSignal:r,debug:o});return Se(ee.answer)}catch(ee){if(ee instanceof Le)throw ee;if(W=ee,!Tf(ee)||K>=j-1)return Q(ee);let be=Math.min(6e4,1e3*Math.pow(2,K));await new Promise((_e,le)=>{let we=!1,Ne,Ee=()=>{r&&Ne&&r.removeEventListener("abort",Ne)},wt=setTimeout(()=>{we||(we=!0,Ee(),_e())},be);if(r){if(Ne=()=>{we||(we=!0,clearTimeout(wt),Ee(),le(new Le("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 Q(W)})(ue,Y);return x===y?`${b}
941
941
  [WARNING] ${x}/${d} sub-queries used. Plan to wrap up soon.`:b},D=this.buildRuntimeGlobals(r,t.sharedFieldValues,e,a.protocol,l),L=[...new Set(this.agentFunctions.map(G=>G.namespace??"utils"))],B={...t.currentInputs},U=new Set(["inputs","llmQuery",Hs,this.agentModuleNamespace,"final","ask_clarification",...L,...A.stateInspection.enabled?["inspect_runtime"]:[],...Object.keys(D)]),V=[...new Set([...Object.keys(B),...t.signatureInputFieldNames])].filter(G=>!U.has(G)),se={};for(let G of V)se[G]=B[G];let he=()=>{for(let G of Object.keys(B))delete B[G];for(let[G,Y]of Object.entries(t.currentInputs))B[G]=Y;for(let G of V)se[G]=t.currentInputs[G]},z=[...U],q=[...U,...V],Z=u??[],X,H,oe=G=>typeof G.inspectGlobals=="function"?G:void 0,de=async()=>{try{let G=await X.execute(Sp(),{signal:r,reservedNames:q});if(typeof G!="string")return[];let Y=JSON.parse(G);return Array.isArray(Y)?Y.filter(ue=>typeof ue=="string"):[]}catch{return[]}},Ae=async()=>(H||(H=await de()),H),Re=async()=>{try{let G=oe(X);if(G?.inspectGlobals)return await G.inspectGlobals({signal:r,reservedNames:q});let Y=await Ae(),ue=Rp(q,Y),Se=await X.execute(ue,{signal:r,reservedNames:q});return typeof Se=="string"?Se:String(Se)}catch(G){return`[inspect_runtime error: ${G instanceof Error?G.message:String(G)}]`}},ie=(G,Y)=>{let ue=Sf(G);if(!ue)return vf(G,Y);let Se=Us(Z);return $p(ue,Se,Y)},ne=A.stateInspection.enabled?async()=>ie(await Re()):void 0,J=()=>(H=void 0,p.createSession({...se,inputs:B,llmQuery:$,final:a.finalFunction,ask_clarification:a.askClarificationFunction,...ne?{inspect_runtime:ne}:{},...D}));X=J();let ye=async()=>{if(!i.payload)for(let G=0;G<3&&!i.payload;G++)await new Promise(Y=>{setTimeout(Y,0)})},ge=async()=>{if(!A.stateSummary.enabled)return;let G=await Re();return ie(G,{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})||"(no user variables)"},Ie=G=>{if(typeof G.patchGlobals!="function")throw new Error("AxCodeSession.patchGlobals() is required when restoring AxAgent state or using inputUpdateCallback");return G},Me=G=>{if(typeof G.snapshotGlobals!="function")throw new Error("AxCodeSession.snapshotGlobals() is required to export AxAgent state");return G},ke=G=>{let Y=new Set(q),ue={};for(let[ze,b]of Object.entries(G.runtimeBindings??{}))Y.has(ze)||(ue[ze]=b);let Se=(G.runtimeEntries??[]).filter(ze=>!Y.has(ze.name));return{runtimeBindings:ue,runtimeEntries:Se,actionLogEntries:Af(G.actionLogEntries),checkpointState:G.checkpointState,provenance:{...G.provenance??{}}}};return{effectiveContextConfig:A,captureRuntimeStateSummary:ge,exportRuntimeState:async()=>{let Y=await Me(X).snapshotGlobals({signal:r,reservedNames:q}),ue=Us(Z);return{version:1,runtimeBindings:Y.bindings,runtimeEntries:Y.entries,actionLogEntries:xf(Z),provenance:yf(ue)}},restoreRuntimeState:async G=>{let Y=ke(G);return await Ie(X).patchGlobals(Y.runtimeBindings,{signal:r}),Y},syncRuntimeInputsToSession:async()=>{he();let G=async Y=>{await Ie(Y).patchGlobals({inputs:{...B},...se},{signal:r})};try{await G(X)}catch(Y){if(r?.aborted)throw new Le("rlm-session",r.reason??"Aborted");if(Y instanceof Error&&(Y.name==="AbortError"||Y.message.startsWith("Aborted")))throw Y;if(Gp(Y)){X=J(),await G(X);return}throw new Error(`Failed to sync runtime inputs: ${Ws(Y,m)}`)}},executeActorCode:async G=>{let Y={output:Ks(void 0,m),isError:!1};try{let ue=await X.execute(G,{signal:r,reservedNames:z});return i.payload||Lp(G)&&Dp(ue)&&(await ye(),i.payload)?Y:{output:Ks(ue,m),isError:!1}}catch(ue){if(ue instanceof lr||i.payload)return Y;if(r?.aborted)throw new Le("rlm-session",r.reason??"Aborted");if(ue instanceof Error&&(ue.name==="AbortError"||ue.message.startsWith("Aborted")))throw ue;if(Ef(ue))return{output:ft(`${Vs}
942
942
  ${Ws(ue,m)}`,m),isError:!0};if(Gp(ue))try{X=J(),i.payload=void 0;let Se=await X.execute(G,{signal:r,reservedNames:z});return{output:ft(`${Vs}