@ax-llm/ax 19.0.1 → 19.0.2

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
@@ -690,7 +690,7 @@ ${o}
690
690
  ### Responder output fields
691
691
  The responder is looking to produce the following output fields: ${s}
692
692
 
693
- ### APIs (Some of the api's you can use in your code)
693
+ ### Functions for context analysis and responding
694
694
  - \`await llmQuery(query:string, context:object|array|string) : string\` \u2014 Have a sub agent work on a part of the task for you when the context is too large or complex to handle in a single turn. Its a way to divide and conquer but do not overuse it.
695
695
 
696
696
  - \`await llmQuery([{ query:string, context:object|array|string }, ...]) : string\` \u2014 A batched version of \`llmQuery\` that allows you to make multiple queries in parallel. Use this to speed up processing when you have many items to analyze. Sub-agent calls have a call limit of ${r}. Oversized values are truncated automatically.
@@ -699,7 +699,7 @@ The responder is looking to produce the following output fields: ${s}
699
699
 
700
700
  - \`ask_clarification(...args)\` \u2014 Signal that more user input is needed and provide clarification arguments for the responder. Requires at least one argument. Execution ends after calling it.
701
701
  ${n.hasInspectRuntime?"\n- `await inspect_runtime() : string` \u2014 Returns a compact snapshot of all user-defined variables in the runtime session (name, type, size, preview). Use this to re-ground yourself when the action log is large instead of re-reading previous outputs.\n":""}${n.agents&&n.agents.length>0?`
702
- ### Available Sub-Agents
702
+ ### Available Agents Functions
703
703
  The following agents are pre-loaded under the \`agents\` namespace. Call them for specialized tasks:
704
704
  ${n.agents.map(l=>`- \`await agents.${l.name}(${xu(l.parameters)})\` \u2014 ${l.description}`).join(`
705
705
  `)}
@@ -782,7 +782,7 @@ ${e.output}${e.actorFieldsOutput}`).join(`
782
782
  } catch { preview = String(v).slice(0, 80); }
783
783
  return k + ': ' + type + (size ? ' (' + size + ')' : '') + ' = ' + preview;
784
784
  }).join('\\n') || '(no user variables)';
785
- })()`}var Cu=50,Gp=5e3,Dp=8,Tu=10,Up=2,Er=class i{ai;program;actorProgram;responderProgram;agents;agentFunctions;debug;options;rlmConfig;runtime;actorFieldNames;sharedFieldNames;globalSharedFieldNames;excludedSharedFields;excludedAgents;excludedAgentFunctions;actorDescription;responderDescription;recursionForwardOptions;actorForwardOptions;responderForwardOptions;activeAbortControllers=new Set;_stopRequested=!1;func;_parentSharedFields=new Set;_parentSharedAgents=new Set;_parentSharedAgentFunctions=new Set;constructor({ai:e,agentIdentity:t,signature:n},r){let{debug:o,contextFields:s,runtime:a,maxLlmCalls:l,maxRuntimeChars:u,maxBatchedLlmQueryConcurrency:c,maxTurns:p,trajectoryPruning:d,contextManagement:m,actorFields:g,actorCallback:h,mode:f,recursionOptions:y,actorOptions:x,responderOptions:A}=r;this.ai=e,this.agents=r.agents?.local,this.agentFunctions=r.functions?.local??[],this.debug=o,this.options=r,this.runtime=a??new jt,this.rlmConfig={contextFields:s,sharedFields:r.fields?.shared,runtime:this.runtime,maxLlmCalls:l,maxRuntimeChars:u,maxBatchedLlmQueryConcurrency:c,maxTurns:p,trajectoryPruning:d,contextManagement:m,actorFields:g,actorCallback:h,mode:f},this.recursionForwardOptions=y;let{description:w,...I}=x??{},{description:T,...v}=A??{};this.actorDescription=w,this.actorForwardOptions=I,this.responderDescription=T,this.responderForwardOptions=v;let{agents:N,fields:E,functions:G,...U}=r;this.program=new Te(n,U);let B=this.agents;for(let W of B??[]){let X=W.getFunction().name;this.program.register(W,X)}t&&(this.func={name:Hp(t.name),description:t.description,parameters:this._buildFuncParameters(),func:async()=>{throw new Error("Use getFunction() to get a callable wrapper")}});let k=this.program.getSignature().getInputFields();for(let W of s)if(!k.some(X=>X.name===W))throw new Error(`RLM contextField "${W}" not found in signature`);if(this.program.getSignature().getDescription())throw new Error("AxAgent does not support signature-level descriptions. Use setActorDescription() and/or setResponderDescription() to customize the actor and responder prompts independently.");let j=this.program.getSignature().getOutputFields(),_=g??[];this.actorFieldNames=_;for(let W of _)if(!j.some(X=>X.name===W))throw new Error(`RLM actorField "${W}" not found in output signature`);let J=r.fields?.shared??[];this.sharedFieldNames=J;for(let W of J)if(!k.some(X=>X.name===W))throw new Error(`sharedField "${W}" not found in signature input fields`);this.excludedSharedFields=r.fields?.excluded??[];let O=r.fields?.globallyShared??[];this.globalSharedFieldNames=O;for(let W of O)if(!k.some(X=>X.name===W))throw new Error(`globalSharedField "${W}" not found in signature input fields`);let L=r.agents?.shared??[],te=r.agents?.globallyShared??[];this.excludedAgents=r.agents?.excluded??[];let F=r.functions?.shared??[],ee=r.functions?.globallyShared??[];this.excludedAgentFunctions=r.functions?.excluded??[];let Ae=new Set(["agents","llmQuery","final","ask_clarification"]);for(let W of[...this.agentFunctions,...F,...ee]){let X=W.namespace??"utils";if(Ae.has(X))throw new Error(`Agent function namespace "${X}" is reserved`)}if(J.length>0&&B){let W=k.filter(X=>J.includes(X.name));for(let X of B){if(!(X instanceof i))continue;let se=new Set(X.getExcludedSharedFields()),ye=W.filter(ke=>!se.has(ke.name));ye.length!==0&&X._extendForSharedFields(ye,s)}}if(L.length>0&&B)for(let W of B)W instanceof i&&W._extendForSharedAgents(L);if(O.length>0&&B){let W=k.filter(X=>O.includes(X.name));for(let X of B){if(!(X instanceof i))continue;let se=new Set(X.getExcludedSharedFields()),ye=W.filter(ke=>!se.has(ke.name));ye.length!==0&&X._extendForGlobalSharedFields(ye,s)}}if(te.length>0&&B)for(let W of B)W instanceof i&&W._extendForGlobalSharedAgents(te);if(F.length>0&&B)for(let W of B)W instanceof i&&W._extendForSharedAgentFunctions(F);if(ee.length>0&&B)for(let W of B)W instanceof i&&W._extendForGlobalSharedAgentFunctions(ee);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.sharedFieldNames,...this.globalSharedFieldNames],r=e.filter(x=>t.includes(x.name)),o=e.filter(x=>!t.includes(x.name)&&!n.includes(x.name)),s=this.program.getSignature().getOutputFields(),a=s.filter(x=>this.actorFieldNames.includes(x.name)),l=s.filter(x=>!this.actorFieldNames.includes(x.name)),u=he().addInputFields(o).input("contextMetadata",he.string("Metadata about pre-loaded context variables (type and size)")).input("actionLog",he.string("Chronological trace of code executions or actions and their outputs so far")).output("javascriptCode",he.code("JavaScript code to execute in runtime session"));a.length>0&&(u=u.addOutputFields(a));let c=u.build(),p=he().addInputFields(o).input("contextData",he.json("Context data to help synthesize the final answer.")).addOutputFields(l).build(),d=this.rlmConfig.maxLlmCalls??Cu,m=this.rlmConfig.maxTurns??Tu,g=this.agents?.map(x=>{let A=x.getFunction();return{name:A.name,description:A.description,parameters:A.parameters}})??[],h=this.agentFunctions.map(x=>({name:x.name,description:x.description,parameters:x.parameters,returns:x.returns,namespace:x.namespace??"utils"})),f=us(this.actorDescription,r,l,{runtimeUsageInstructions:this.runtime.getUsageInstructions(),maxLlmCalls:d,maxTurns:m,hasInspectRuntime:!!this.rlmConfig.contextManagement?.stateInspection,agents:g,agentFunctions:h}),y=cs(this.responderDescription,r);this.actorProgram=new Te(c,{...this._genOptions,description:f}),this.responderProgram=new Te(p,{...this._genOptions,description:y})}_extendForSharedFields(e,t){let n=this.program.getSignature(),r=n.getInputFields(),o=!1;for(let s of e){if(r.some(a=>a.name===s.name)){if(this._parentSharedFields.has(s.name))throw new Error(`Duplicate shared field "${s.name}" \u2014 already propagated from a parent`);continue}this._parentSharedFields.add(s.name),n.addInputField(s),o=!0}o&&this.program.setSignature(n);for(let s of e)t.includes(s.name)&&!this.rlmConfig.contextFields.includes(s.name)&&this.rlmConfig.contextFields.push(s.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){let s=o.getFunction().name;if(!n.has(s)){if(t.has(s)){if(this._parentSharedAgents.has(s))throw new Error(`Duplicate shared agent "${s}" \u2014 already propagated from a parent`);continue}this._parentSharedAgents.add(s),t.add(s),r.push(o)}}if(r.length!==0){this.agents=[...this.agents??[],...r];for(let o of r){let s=o.getFunction().name;this.program.register(o,s)}this._buildSplitPrograms()}}_extendForGlobalSharedFields(e,t){let n=this.program.getSignature(),r=n.getInputFields(),o=!1;for(let s of e){if(r.some(a=>a.name===s.name)){if(this._parentSharedFields.has(s.name))throw new Error(`Duplicate shared field "${s.name}" \u2014 already propagated from a parent`);continue}this._parentSharedFields.add(s.name),n.addInputField(s),o=!0}o&&this.program.setSignature(n);for(let s of e)t.includes(s.name)&&!this.rlmConfig.contextFields.includes(s.name)&&this.rlmConfig.contextFields.push(s.name);for(let s of e)this.sharedFieldNames.includes(s.name)||this.sharedFieldNames.push(s.name);if(this._buildSplitPrograms(),this.func&&(this.func.parameters=this._buildFuncParameters()),this.agents)for(let s of this.agents){if(!(s instanceof i))continue;let a=new Set(s.getExcludedSharedFields()),l=e.filter(u=>!a.has(u.name));l.length!==0&&s._extendForGlobalSharedFields(l,t)}}_extendForGlobalSharedAgents(e){let t=this.agents?this.agents.filter(n=>n instanceof i):[];this._extendForSharedAgents(e);for(let n of t)n._extendForGlobalSharedAgents(e)}_extendForSharedAgentFunctions(e){if(e.length===0)return;let t=new Set(this.agentFunctions.map(o=>`${o.namespace??"utils"}.${o.name}`)),n=new Set(this.excludedAgentFunctions),r=[];for(let o of e){if(n.has(o.name))continue;let s=`${o.namespace??"utils"}.${o.name}`;if(t.has(s)){if(this._parentSharedAgentFunctions.has(s))throw new Error(`Duplicate shared agent function "${s}" \u2014 already propagated from a parent`);continue}this._parentSharedAgentFunctions.add(s),t.add(s),r.push(o)}r.length!==0&&(this.agentFunctions=[...this.agentFunctions,...r],this._buildSplitPrograms())}_extendForGlobalSharedAgentFunctions(e){let t=this.agents?this.agents.filter(n=>n instanceof i):[];this._extendForSharedAgentFunctions(e);for(let n of t)n._extendForGlobalSharedAgentFunctions(e)}stop(){this._stopRequested=!0;for(let e of this.activeAbortControllers)e.abort("Stopped by user");this.program.stop(),this.actorProgram.stop(),this.responderProgram.stop()}getId(){return this.program.getId()}setId(e){this.program.setId(e)}namedPrograms(){return this.program.namedPrograms()}getTraces(){return this.program.getTraces()}setDemos(e,t){this.program.setDemos(e,t)}getUsage(){return this.program.getUsage()}resetUsage(){this.program.resetUsage()}getFunction(){if(!this.func)throw new Error("getFunction() requires agentIdentity to be set in the constructor");let e=this.forward.bind(this);return{...this.func,func:async(r,o)=>{let s=this.ai??o?.ai;if(!s)throw new Error("AI service is required to run the agent");let a=await e(s,r,o),u=this.program.getSignature().getOutputFields();return Object.keys(a).map(p=>{let d=u.find(m=>m.name===p);return d?`${d.title}: ${a[p]}`:`${p}: ${a[p]}`}).join(`
785
+ })()`}var Cu=50,Gp=5e3,Dp=8,Tu=10,Up=2,Er=class i{ai;program;actorProgram;responderProgram;agents;agentFunctions;debug;options;rlmConfig;runtime;actorFieldNames;sharedFieldNames;globalSharedFieldNames;excludedSharedFields;excludedAgents;excludedAgentFunctions;actorDescription;responderDescription;recursionForwardOptions;actorForwardOptions;responderForwardOptions;activeAbortControllers=new Set;_stopRequested=!1;func;_parentSharedFields=new Set;_parentSharedAgents=new Set;_parentSharedAgentFunctions=new Set;constructor({ai:e,agentIdentity:t,signature:n},r){let{debug:o,contextFields:s,runtime:a,maxLlmCalls:l,maxRuntimeChars:u,maxBatchedLlmQueryConcurrency:c,maxTurns:p,trajectoryPruning:d,contextManagement:m,actorFields:g,actorCallback:h,mode:f,recursionOptions:y,actorOptions:x,responderOptions:A}=r;this.ai=e,this.agents=r.agents?.local,this.agentFunctions=r.functions?.local??[],this.debug=o,this.options=r,this.runtime=a??new jt,this.rlmConfig={contextFields:s,sharedFields:r.fields?.shared,runtime:this.runtime,maxLlmCalls:l,maxRuntimeChars:u,maxBatchedLlmQueryConcurrency:c,maxTurns:p,trajectoryPruning:d,contextManagement:m,actorFields:g,actorCallback:h,mode:f},this.recursionForwardOptions=y;let{description:w,...I}=x??{},{description:T,...v}=A??{};this.actorDescription=w,this.actorForwardOptions=I,this.responderDescription=T,this.responderForwardOptions=v;let{agents:N,fields:E,functions:G,...U}=r;this.program=new Te(n,U);let B=this.agents;for(let W of B??[]){let X=W.getFunction().name;this.program.register(W,X)}t&&(this.func={name:Hp(t.name),description:t.description,parameters:this._buildFuncParameters(),func:async()=>{throw new Error("Use getFunction() to get a callable wrapper")}});let k=this.program.getSignature().getInputFields();for(let W of s)if(!k.some(X=>X.name===W))throw new Error(`RLM contextField "${W}" not found in signature`);if(this.program.getSignature().getDescription())throw new Error("AxAgent does not support signature-level descriptions. Use setActorDescription() and/or setResponderDescription() to customize the actor and responder prompts independently.");let j=this.program.getSignature().getOutputFields(),_=g??[];this.actorFieldNames=_;for(let W of _)if(!j.some(X=>X.name===W))throw new Error(`RLM actorField "${W}" not found in output signature`);let J=r.fields?.shared??[];this.sharedFieldNames=J;for(let W of J)if(!k.some(X=>X.name===W))throw new Error(`sharedField "${W}" not found in signature input fields`);this.excludedSharedFields=r.fields?.excluded??[];let O=r.fields?.globallyShared??[];this.globalSharedFieldNames=O;for(let W of O)if(!k.some(X=>X.name===W))throw new Error(`globalSharedField "${W}" not found in signature input fields`);let L=r.agents?.shared??[],te=r.agents?.globallyShared??[];this.excludedAgents=r.agents?.excluded??[];let F=r.functions?.shared??[],ee=r.functions?.globallyShared??[];this.excludedAgentFunctions=r.functions?.excluded??[];let Ae=new Set(["agents","llmQuery","final","ask_clarification"]);for(let W of[...this.agentFunctions,...F,...ee]){let X=W.namespace??"utils";if(Ae.has(X))throw new Error(`Agent function namespace "${X}" is reserved`)}if(J.length>0&&B){let W=k.filter(X=>J.includes(X.name));for(let X of B){if(!(X instanceof i))continue;let se=new Set(X.getExcludedSharedFields()),ye=W.filter(ke=>!se.has(ke.name));ye.length!==0&&X._extendForSharedFields(ye,s)}}if(L.length>0&&B)for(let W of B)W instanceof i&&W._extendForSharedAgents(L);if(O.length>0&&B){let W=k.filter(X=>O.includes(X.name));for(let X of B){if(!(X instanceof i))continue;let se=new Set(X.getExcludedSharedFields()),ye=W.filter(ke=>!se.has(ke.name));ye.length!==0&&X._extendForGlobalSharedFields(ye,s)}}if(te.length>0&&B)for(let W of B)W instanceof i&&W._extendForGlobalSharedAgents(te);if(F.length>0&&B)for(let W of B)W instanceof i&&W._extendForSharedAgentFunctions(F);if(ee.length>0&&B)for(let W of B)W instanceof i&&W._extendForGlobalSharedAgentFunctions(ee);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.sharedFieldNames,...this.globalSharedFieldNames],r=e.filter(x=>t.includes(x.name)),o=e.filter(x=>!t.includes(x.name)&&!n.includes(x.name)),s=this.program.getSignature().getOutputFields(),a=s.filter(x=>this.actorFieldNames.includes(x.name)),l=s.filter(x=>!this.actorFieldNames.includes(x.name)),u=he().addInputFields(o).input("contextMetadata",he.string("Metadata about pre-loaded context variables (type and size)")).input("actionLog",he.string("Chronological trace of code executions or actions and their outputs so far")).output("javascriptCode",he.code("JavaScript code to execute in runtime session"));a.length>0&&(u=u.addOutputFields(a));let c=u.build(),p=he().addInputFields(o).input("contextData",he.json("Context data to help synthesize the final answer.")).addOutputFields(l).build(),d=this.rlmConfig.maxLlmCalls??Cu,m=this.rlmConfig.maxTurns??Tu,g=this.agents?.map(x=>{let A=x.getFunction();return{name:A.name,description:A.description,parameters:A.parameters}})??[],h=this.agentFunctions.map(x=>({name:x.name,description:x.description,parameters:x.parameters,returns:x.returns,namespace:x.namespace??"utils"})),f=us(this.actorDescription,r,l,{runtimeUsageInstructions:this.runtime.getUsageInstructions(),maxLlmCalls:d,maxTurns:m,hasInspectRuntime:!!this.rlmConfig.contextManagement?.stateInspection,agents:g,agentFunctions:h}),y=cs(this.responderDescription,r);this.actorProgram=new Te(c,{...this._genOptions,description:f}),this.responderProgram=new Te(p,{...this._genOptions,description:y})}_extendForSharedFields(e,t){let n=this.program.getSignature(),r=n.getInputFields(),o=!1;for(let s of e){if(r.some(a=>a.name===s.name)){if(this._parentSharedFields.has(s.name))throw new Error(`Duplicate shared field "${s.name}" \u2014 already propagated from a parent`);continue}this._parentSharedFields.add(s.name),n.addInputField(s),o=!0}o&&this.program.setSignature(n);for(let s of e)t.includes(s.name)&&!this.rlmConfig.contextFields.includes(s.name)&&this.rlmConfig.contextFields.push(s.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 s=o.getFunction().name;if(!n.has(s)){if(t.has(s)){if(this._parentSharedAgents.has(s))throw new Error(`Duplicate shared agent "${s}" \u2014 already propagated from a parent`);continue}this._parentSharedAgents.add(s),t.add(s),r.push(o)}}if(r.length!==0){this.agents=[...this.agents??[],...r];for(let o of r){let s=o.getFunction().name;this.program.register(o,s)}this._buildSplitPrograms()}}_extendForGlobalSharedFields(e,t){let n=this.program.getSignature(),r=n.getInputFields(),o=!1;for(let s of e){if(r.some(a=>a.name===s.name)){if(this._parentSharedFields.has(s.name))throw new Error(`Duplicate shared field "${s.name}" \u2014 already propagated from a parent`);continue}this._parentSharedFields.add(s.name),n.addInputField(s),o=!0}o&&this.program.setSignature(n);for(let s of e)t.includes(s.name)&&!this.rlmConfig.contextFields.includes(s.name)&&this.rlmConfig.contextFields.push(s.name);for(let s of e)this.sharedFieldNames.includes(s.name)||this.sharedFieldNames.push(s.name);if(this._buildSplitPrograms(),this.func&&(this.func.parameters=this._buildFuncParameters()),this.agents)for(let s of this.agents){if(!(s instanceof i))continue;let a=new Set(s.getExcludedSharedFields()),l=e.filter(u=>!a.has(u.name));l.length!==0&&s._extendForGlobalSharedFields(l,t)}}_extendForGlobalSharedAgents(e){let t=this.agents?this.agents.filter(n=>n instanceof i):[];this._extendForSharedAgents(e);for(let n of t)n._extendForGlobalSharedAgents(e)}_extendForSharedAgentFunctions(e){if(e.length===0)return;let t=new Set(this.agentFunctions.map(o=>`${o.namespace??"utils"}.${o.name}`)),n=new Set(this.excludedAgentFunctions),r=[];for(let o of e){if(n.has(o.name))continue;let s=`${o.namespace??"utils"}.${o.name}`;if(t.has(s)){if(this._parentSharedAgentFunctions.has(s))throw new Error(`Duplicate shared agent function "${s}" \u2014 already propagated from a parent`);continue}this._parentSharedAgentFunctions.add(s),t.add(s),r.push(o)}r.length!==0&&(this.agentFunctions=[...this.agentFunctions,...r],this._buildSplitPrograms())}_extendForGlobalSharedAgentFunctions(e){let t=this.agents?this.agents.filter(n=>n instanceof i):[];this._extendForSharedAgentFunctions(e);for(let n of t)n._extendForGlobalSharedAgentFunctions(e)}stop(){this._stopRequested=!0;for(let e of this.activeAbortControllers)e.abort("Stopped by user");this.program.stop(),this.actorProgram.stop(),this.responderProgram.stop()}getId(){return this.program.getId()}setId(e){this.program.setId(e)}namedPrograms(){return this.program.namedPrograms()}getTraces(){return this.program.getTraces()}setDemos(e,t){this.program.setDemos(e,t)}getUsage(){return this.program.getUsage()}resetUsage(){this.program.resetUsage()}getFunction(){if(!this.func)throw new Error("getFunction() requires agentIdentity to be set in the constructor");let e=this.forward.bind(this);return{...this.func,func:async(r,o)=>{let s=this.ai??o?.ai;if(!s)throw new Error("AI service is required to run the agent");let a=await e(s,r,o),u=this.program.getSignature().getOutputFields();return Object.keys(a).map(p=>{let d=u.find(m=>m.name===p);return d?`${d.title}: ${a[p]}`:`${p}: ${a[p]}`}).join(`
786
786
  `)}}}getExcludedSharedFields(){return this.excludedSharedFields}getExcludedAgents(){return this.excludedAgents}getExcludedAgentFunctions(){return this.excludedAgentFunctions}getSignature(){return this.program.getSignature()}setSignature(e){this.program.setSignature(e)}applyOptimization(e){this.program.applyOptimization?.(e)}async _runActorLoop(e,t,n,r){let o=this.rlmConfig,s=this.runtime,a=n?.debug??this.debug??e?.getOptions()?.debug??!1,l={},u={},c;Array.isArray(t)?c=t.filter(M=>M.role==="user").reduce((M,Q)=>({...M,...Q.values}),{}):c=t;let p=[...this.sharedFieldNames,...this.globalSharedFieldNames];for(let[M,Q]of Object.entries(c))o.contextFields.includes(M)?l[M]=Q:p.includes(M)||(u[M]=Q);let d={};for(let M of p)M in c&&(d[M]=c[M]),M in l&&(d[M]=l[M]);for(let M of o.contextFields)if(!(M in l))throw new Error(`RLM contextField "${M}" is missing from input values`);let m=o.maxLlmCalls??Cu,g=o.maxRuntimeChars??Gp,h=Math.max(1,o.maxBatchedLlmQueryConcurrency??Dp),f=o.maxTurns??Tu,y=0,x=Math.floor(m*.8),A=this.recursionForwardOptions?.maxDepth??Up,w=Math.max(0,A),{maxDepth:I,...T}=this.recursionForwardOptions??{},{functions:v,description:N,mem:E,sessionId:G,...U}=n??{},B={...this.recursionForwardOptions??{},maxDepth:Math.max(0,w-1)},k=["context"],j=he().input("task",he.string("Task for recursive analysis")).input("context",he.json("Optional context for the recursive task")).output("answer",he.string("Answer from recursive analysis")).build(),J=(o.mode??"simple")==="advanced"&&(B.maxDepth??0)>0?"advanced":"simple",O;w>0&&(J==="advanced"?O=new i({signature:j},{debug:a,...o,agents:{local:this.agents},functions:{local:this.agentFunctions},contextFields:k,actorFields:void 0,recursionOptions:B,actorOptions:this.actorForwardOptions,responderOptions:this.responderForwardOptions}):O=new Te(j,B));let L=M=>{if(M==null)return"";if(typeof M=="string")return bt(M,g);try{return bt(JSON.stringify(M),g)}catch{return bt(String(M),g)}},te=async(M,Q)=>{if(!Array.isArray(M)&&typeof M=="object"&&M!==null&&"query"in M)return te(M.query,M.context??Q);if(r?.aborted)throw new Ee("rlm-llm-query",r.reason?String(r.reason):"Aborted");if(Array.isArray(M))return qp(M,h,async pe=>{try{return await te(pe.query,pe.context)}catch(H){if(H instanceof Ee)throw H;return`[ERROR] ${H instanceof Error?H.message:String(H)}`}});let ie=await(async(pe,H)=>{let Z=H===void 0?void 0:typeof H=="string"?bt(H,g):H;if(y++,y>m)return`[ERROR] Sub-query budget exhausted (${m}/${m}). Use the data you have already accumulated to produce your final answer.`;if(w<=0||!O)return`[ERROR] Recursion depth limit reached (${A}).`;let ne=3,fe;for(let xe=0;xe<ne;xe++)try{let le=await O.forward(e,{task:pe,...Z!==void 0?{context:Z}:J==="advanced"?{context:""}:{}},{...U,...T,abortSignal:r,debug:a});return L(le.answer)}catch(le){if(fe=le,!Bp(le)||xe>=ne-1)throw le;let at=Math.min(6e4,1e3*Math.pow(2,xe));await new Promise((gt,We)=>{let Ve=!1,He,Ze=()=>{r&&He&&r.removeEventListener("abort",He)},Ct=setTimeout(()=>{Ve||(Ve=!0,Ze(),gt())},at);if(r){if(He=()=>{Ve||(Ve=!0,clearTimeout(Ct),Ze(),We(new Ee("rlm-llm-query-retry-backoff",r.reason?String(r.reason):"Aborted during retry backoff")))},r.aborted){He();return}r.addEventListener("abort",He,{once:!0})}})}throw fe})(M,Q);return y===x?`${ie}
787
787
  [WARNING] ${y}/${m} sub-queries used. Plan to wrap up soon.`:ie},F=this.buildRuntimeGlobals(r,d,e),ee,Ae=(M,Q)=>{if(Q.length===0)throw new Error(`${M}() requires at least one argument`);ee={type:M,args:Q}},W=(...M)=>Ae("final",M),X=(...M)=>Ae("ask_clarification",M),ye=["llmQuery","agents","final","ask_clarification",...[...new Set(this.agentFunctions.map(M=>M.namespace??"utils"))],...o.contextManagement?.stateInspection?["inspect_runtime"]:[],...o.contextFields,...Object.keys(F)],ke=o.contextManagement?.stateInspection?async()=>{try{let M=Iu(ye),Q=await Le.execute(M,{signal:r,reservedNames:ye});return typeof Q=="string"?Q:String(Q)}catch(M){return`[inspect_runtime error: ${M instanceof Error?M.message:String(M)}]`}}:void 0,ge=()=>s.createSession({...l,llmQuery:te,final:W,ask_clarification:X,...ke?{inspect_runtime:ke}:{},...F}),we="[The JavaScript runtime was restarted; all global state was lost and must be recreated if needed.]",Le=ge(),Oe=!1,$e=M=>M instanceof Error&&M.message==="Session is closed",C=M=>M instanceof Error&&M.message==="Execution timed out",S=M=>{if(M===void 0)return"(no output)";if(typeof M=="string")return bt(M||"(no output)",g);try{return bt(JSON.stringify(M,null,2),g)}catch{return bt(String(M),g)}},R=M=>{let Q=M,oe=Q?.name??"Error",ae=Q?.message??String(M),ie=[`${oe}: ${ae}`];if(Q?.data!==void 0)try{ie.push(`Data: ${JSON.stringify(Q.data,null,2)}`)}catch{ie.push(`Data: ${String(Q.data)}`)}if(Q?.cause!==void 0){let pe=(H,Z)=>{if(Z>4)return"[cause chain truncated]";let ne=H,fe=ne?.name??"Error",xe=ne?.message??String(H),le=[`${fe}: ${xe}`];if(ne?.data!==void 0)try{le.push(`Data: ${JSON.stringify(ne.data,null,2)}`)}catch{le.push(`Data: ${String(ne.data)}`)}return ne?.cause!==void 0&&le.push(`Caused by: ${pe(ne.cause,Z+1)}`),le.join(`
788
788
  `)};ie.push(`Caused by: ${pe(Q.cause,1)}`)}return bt(ie.join(`