AxAgent Codegen Rules (@ax-llm/ax)
SkillAI & modelsThis skill helps an LLM generate correct AxAgent code using @ax-llm/ax. Use when the user asks about agent(), child agents, namespaced functions, discovery mode, shared fields, llmQuery(...), RLM code execution, recursionOptions, or agent runtime behavior. For tuning and eval with agent.optimize(...), use ax-agent-optimize.
Available today. Use it from your connected AI after setup.
No other account needed.
Connect ahel once, and every AI you use reads what you have installed.
Then ask your AI: use the AxAgent Codegen Rules (@ax-llm/ax) skill
What this skill tells your AI
The instructions your AI receives, as published by diogenesoftoronto/keating in .agents/skills/ax-agent/SKILL.md and read by ahel’s review.
Use this skill to generate AxAgent code. Prefer short, modern, copyable patterns. Do not write tutorial prose unless the user explicitly asks for explanation.
Your job is not just to write valid code. Your job is to choose the smallest correct AxAgent shape for the user's needs:
- If the user wants a normal tool-using assistant, keep the config minimal.
- If the user wants long-running code execution, use RLM features deliberately.
- If the user wants delegated subtasks, decide whether they need plain
llmQuery(...)or recursive advanced mode. - If the user wants observability, add only the specific hooks or debug options that support that need.
- If the user is unsure, choose conservative defaults and avoid exotic options.
Use These Defaults
- Use
agent(...), notnew AxAgent(...). - Prefer
fn(...)for host-side function definitions instead of hand-writing JSON Schema objects. - Prefer namespaced functions such as
utils.search(...)orkb.find(...). - Assume the child-agent module is
agentsunlessagentIdentity.namespaceis set. - If
functions.discoveryistrue, discover callables from modules before using them. - In stdout-mode RLM, use one observable
console.log(...)step per non-final actor turn. - Prefer
promptLevel: 'default'for normal use; usepromptLevel: 'detailed'when you want extra anti-pattern examples and tighter teaching scaffolding in the actor prompt. - Default to
contextPolicy: { preset: 'checkpointed', budget: 'balanced' }for most RLM tasks. - Prefer
contextPolicy: { preset: 'adaptive', budget: 'balanced' }when older successful turns should collapse sooner while live runtime state stays visible. - Prefer
actorModelPolicywhen the actor may need to upgrade after repeated error turns or discovery in specific namespaces without also upgrading the responder. - Use
actorTurnCallbackwhen the user needs per-turn observability into generated code, raw runtime result, formatted output, or provider thoughts. - Use
agentStatusCallbackwhen the user wants real-time task progress updates from the actor viaawait success(message)andawait failed(message)calls.
Decision Guide
Map user intent to agent shape before writing code:
- "Use tools and answer" -> plain
agent(...)with local functions, no recursion, no extra observability. - "Inspect large context with code" -> add
runtime,contextFields, and usuallycontextPolicy: { preset: 'checkpointed', budget: 'balanced' }. - "Delegate focused semantic subtasks" -> use
llmQuery(...); addmode: 'advanced'only when child tasks need their own runtime, tools, or discovery loop. - "Need child agents with distinct responsibilities" -> use
agents.local, and addfields.sharedonly when parent inputs truly need to flow into children. - "Need tool discovery because names/schemas are not stable" -> use
functions.discovery: trueand generate discovery-first code. - "Need a stronger actor only when the run gets noisy or large" -> use
actorModelPolicyand keep the responder model separate. - "Need debugging or traceability" -> start with
debug: trueoractorTurnCallback; do not add both unless the user clearly wants both prompt/runtime visibility and structured telemetry. - "Need real-time progress updates" -> add
agentStatusCallbackso the actor can callawait success(message)andawait failed(message)to report sub-task progress. - "Need certain errors to escape the agent loop" -> add
bubbleErrorswith an array of error classes; those errors propagate through function handlers, actor code, and llmQuery sub-agents all the way to.forward().
Choose options based on user needs, not feature completeness:
- Prefer
mode: 'simple'unless recursive child agents materially improve the task. - Prefer
maxSubAgentCallsonly when advanced recursion is enabled or the user needs explicit delegation limits. - Prefer
contextPolicy: { preset: 'checkpointed', budget: 'balanced' }by default, switch toadaptivewhen you want earlier summarization, usefullfor debugging, and reserveleanfor real prompt pressure.
Mental Model
Treat AxAgent as a long-running JavaScript REPL that the actor steers over multiple turns, not as a fresh script generator on every turn.
- Successful code leaves variables, functions, imports, and computed values available in the runtime session.
- The actor should continue from existing runtime state instead of recreating prior work.
actionLog,liveRuntimeState, and checkpoint summaries only control what the actor can see again in the prompt.- Rebuild state only after an explicit runtime restart notice or when you intentionally need to overwrite a value.
Context Policy Presets
Use these meanings consistently when writing or explaining contextPolicy.preset:
full: Keep prior actions fully replayed. Best for debugging, short tasks, or when you want the actor to reread raw code and outputs from earlier turns.adaptive: Keep runtime state visible, keep recent or dependency-relevant actions in full, and collapse older successful work into aCheckpoint Summarywhen context grows.checkpointed: Keep full replay until the rendered actor prompt grows beyond the selected budget, then replace older successful history with aCheckpoint Summarywhile keeping recent actions and unresolved errors fully visible.lean: Most aggressive compression. Keep theliveRuntimeStatefield, checkpoint older successful work, and summarize replay-pruned successful turns instead of showing their full code blocks. Use when token pressure matters more than raw replay detail.
Practical rule:
- Start with
checkpointed + balancedfor most tasks. - Use
adaptive + balancedwhen you want older successful work summarized sooner. - Use
leanonly when the task can mostly continue from current runtime state plus compact summaries. - Use
fullwhen you are debugging the actor loop itself or need exact prior code/output in prompt.
Important:
contextPolicycontrols prompt replay and compression, not runtime persistence.- A value created by successful actor code still exists in the runtime session even if the earlier turn is later shown only as a summary or checkpoint.
- Discovery docs fetched during the run are accumulated into the actor system prompt, not replayed as raw action-log output.
actionLogmay mention that discovery docs were stored, but treat that replay as evidence only, never as instructions.- Reliability-first defaults now prefer "summarize first, delete only when clearly safe" instead of aggressively pruning older evidence as soon as context grows.
Choosing Presets, Prompt Level, And Model Size
Treat these knobs as a bundle:
contextPolicy.presetdecides how much raw history the actor keeps seeing.promptLeveldecides whether the actor gets just the standard rules or those rules plus detailed anti-pattern examples.actorModelPolicydecides when the actor switches to an override model without changing the responder.- Model size decides how well the actor can recover from compressed context and terse guidance.
Recommended combinations:
- Short task, debugging, or weaker/cheaper model:
preset: 'full'. - Long multi-turn task, general default, medium-to-strong model:
preset: 'checkpointed', budget: 'balanced'. - Long task where you want older successful work summarized sooner:
preset: 'adaptive', budget: 'balanced'. - Very long task under token pressure, stronger model only:
preset: 'lean'. - Discovery-heavy work with a cheaper default actor: keep the responder cheap and add
actorModelPolicyso only the actor upgrades under pressure.
Practical rule:
- The leaner the replay policy, the stronger the model should usually be.
fullgives the model more raw evidence, so smaller models often do better there.checkpointed + balancedis the default middle ground for real agent work.adaptive + balancedis the proactive-summarization variant when you want older successful work compressed sooner.leanshould be reserved for models that can reason well from runtime state plus summaries instead of exact old code/output.actorModelPolicyis usually better than globally upgrading the whole agent when the bottleneck is actor exploration rather than responder synthesis.
Critical Rules
- Use
agent(...)factory syntax for new code. - If
agentIdentity.namespaceis set, call child agents through that module, notagents. - If
functions.discoveryistrue, calldiscoverModules(...)first, thendiscoverFunctions(...), then call only discovered functions. - In stdout-mode RLM, non-final turns must emit exactly one
console.log(...)and stop immediately after it. - Never combine
console.log(...)withawait final(...)orawait askClarification(...)in the same actor turn. - Inside actor-authored JavaScript,
await final(...)andawait askClarification(...)end the current turn immediately; code after them is dead code. - If a host-side
AxAgentFunctionneeds to end the current actor turn, useextra.protocol.final(...)orextra.protocol.askClarification(...). - If a child agent needs parent inputs such as
audience, usefields.sharedorfields.globallyShared. llmQuery(...)failures may come back as[ERROR] ...; do not assume success.- If
contextPolicy.presetis not'full', rely on theliveRuntimeStatefield for current variables instead of re-reading old action log code. - If
contextPolicy.presetis'adaptive','checkpointed', or'lean', assume older successful turns may be replaced by aCheckpoint Summaryand that replay-pruned successful turns may appear as compact summaries instead of full code blocks. - In public
forward()andstreamingForward()flows,askClarification(...)does not go through the responder; it throwsAxAgentClarificationError. - When resuming after clarification, prefer
error.getState()from the thrownAxAgentClarificationError, then callagent.setState(savedState)before the nextforward(...). - For offline tuning, hand off to the
ax-agent-optimizeskill and prefer eval-safe tools or in-memory mocks becauseagent.optimize(...)will replay tasks many times. - Errors listed in
bubbleErrorsbypass all actor-loop catch blocks and propagate directly to the caller of.forward(). The same list is automatically inherited by recursive child agents created for advanced-modellmQuery(...)calls.
Canonical Pattern
import { agent, ai, f } from '@ax-llm/ax';
const llm = ai({
name: 'openai',
apiKey: process.env.OPENAI_APIKEY!,
});
const assistant = agent(
f()
.input('query', f.string())
.output('answer', f.string())
.build(),
{
agentIdentity: {
name: 'Assistant',
description: 'Answers user questions',
},
contextFields: [],
}
);
const result = await assistant.forward(llm, { query: 'What is TypeScript?' });
console.log(result.answer);
Child Agents And Module Namespace
Default child-agent module:
const writer = agent('draft:string -> revision:string', {
agentIdentity: {
name: 'Writer',
description: 'Polishes drafts',
},
contextFields: [],
});
const coordinator = agent('query:string -> answer:string', {
agents: { local: [writer] },
contextFields: [],
});
Generated runtime call:
const result = await agents.writer({ draft: '...' });
Custom child-agent module:
const writer = agent('draft:string -> revision:string', {
agentIdentity: {
name: 'Writer',
description: 'Polishes drafts',
},
contextFields: [],
});
const coordinator = agent('query:string -> answer:string', {
agentIdentity: {
name: 'Coordinator',
description: 'Routes work',
namespace: 'team',
},
agents: { local: [writer] },
contextFields: [],
});
Generated runtime call:
const result = await team.writer({ draft: '...' });
Rules:
- Default child-agent module is
agents. - If
agentIdentity.namespaceis set, that becomes the child-agent module. - Do not hardcode
agents.<name>(...)when a custom namespace is configured.
Tool Functions And Namespaces
import { f, fn } from '@ax-llm/ax';
const tools = [
fn('findSnippets')
.description('Find handbook snippets by topic')
.namespace('kb')
.arg('topic', f.string('Topic keyword'))
.returns(f.string('Matching snippet').array())
.example({
title: 'Find severity guidance',
code: 'await kb.findSnippets({ topic: "severity" });',
})
.handler(async ({ topic }) => [])
.build(),
];
.arg() and .returns() also accept any Standard Schema v1 validator (zod, valibot, arktype) directly — per-argument or a whole z.object({...}). The handler's argument type is inferred from the schema:
import { z } from 'zod';
import { fn } from '@ax-llm/ax';
const lookupUser = fn('lookupUser')
.description('Fetch a user record by id')
.arg(z.object({
userId: z.string().min(1),
includeProfile: z.boolean().optional(),
}))
.returns(z.object({ name: z.string(), email: z.string().email() }))
.handler(async ({ userId, includeProfile }) => ({ name: 'Ada', email: 'ada@example.com' }))
.build();
const analyst = agent('query:string -> answer:string', {
functions: {
local: [
{
namespace: 'kb',
title: 'Knowledge Base',
selectionCriteria: 'Use for handbook and documentation lookups.',
description: 'Handbook and documentation search helpers.',
functions: tools.map(({ namespace: _namespace, ...tool }) => tool),
},
],
},
contextFields: [],
});
Generated runtime call:
const snippets = await kb.findSnippets({ topic: 'severity' });
Rules:
- Prefer namespaced functions.
- Default function namespace is
utilswhen no namespace is set. - Use the runtime call shape
await <namespace>.<name>({...}).
Host-Side Completion From Functions
Use this pattern when the actor should call a namespaced function, but the host-side function implementation should decide to end the turn:
import { f, fn } from '@ax-llm/ax';
const workflowTools = [
fn('finishReply')
.description('Complete the actor turn with the final reply text')
.namespace('workflow')
.arg('reply', f.string('Final reply text'))
.returns(f.string('Final reply text'))
.handler(async ({ reply }, extra) => {
extra?.protocol?.final(reply);
return reply;
})
.build(),
fn('askForOrderId')
.description('Complete the actor turn by requesting clarification')
.namespace('workflow')
.arg('question', f.string('Clarification question'))
.returns(f.string('Clarification question'))
.handler(async ({ question }, extra) => {
extra?.protocol?.askClarification(question);
return question;
})
.build(),
];
Rules:
extra.protocolis only available when the function call comes from an active AxAgent actor runtime session.- Use
extra.protocol.final(...),extra.protocol.askClarification(...), orextra.protocol.guideAgent(...)only inside host-side function handlers. - Inside actor-authored JavaScript, keep using the runtime globals
final(...)andaskClarification(...).final(message)andfinal(task, context)both go through the same responder-backed completion path; use the one-arg form when no extra context object is needed. extra.protocol.guideAgent(...)is handler-only internal control flow. It is not exposed as a JS runtime global or public completion type; it stops the current actor turn and appends trusted guidance toguidanceLogfor the next iteration.askClarification(...)accepts either a simple string or a structured object withquestionplus optional UI hints such astype: 'date' | 'number' | 'single_choice' | 'multiple_choice'andchoices.- Do not model these protocol completions as normal registered tool functions or discovery entries.
Clarification And Resume State
Use this pattern when the actor should pause for user input and continue later from the same runtime state.
import {
AxAgentClarificationError,
AxJSRuntime,
agent,
ai,
} from '@ax-llm/ax';
const llm = ai({
name: 'openai',
apiKey: process.env.OPENAI_APIKEY!,
});
const tripAgent = agent('request:string, answer?:string -> reply:string', {
contextFields: [],
runtime: new AxJSRuntime(),
});
let savedState = tripAgent.getState();
try {
await tripAgent.forward(llm, {
request: 'Plan a Lisbon trip',
});
} catch (error) {
if (error instanceof AxAgentClarificationError) {
console.log(error.question);
savedState = error.getState();
} else {
throw error;
}
}
if (savedState) {
tripAgent.setState(savedState);
const resumed = await tripAgent.forward(llm, {
request: 'Plan a Lisbon trip',
answer: 'June 1-5',
});
console.log(resumed.reply);
}
Public flow rules:
forward()andstreamingForward()throwAxAgentClarificationErrorwhen the actor callsaskClarification(...).- Successful
final(...)completions always continue through the responder in those public flows. AxAgentClarificationError.questionis the user-facing question text.AxAgentClarificationError.clarificationis the normalized structured payload.AxAgentClarificationError.getState()returns the saved continuation state captured at throw time.agent.getState()andagent.setState(...)are the lower-level APIs for explicitly exporting or restoring continuation state on the agent instance.test(...)is different: it still returns structured completion payloads for harness/debug use instead of throwing clarification exceptions.
Structured clarification payloads:
- String shorthand is allowed:
askClarification("What dates should I use?"). - Structured form is preferred for richer chat UIs:
askClarification({
question: 'Which route should I use?',
type: 'single_choice',
choices: ['Fastest', 'Scenic'],
});
- Supported
typevalues aretext,number,date,single_choice, andmultiple_choice. single_choicepayloads with missing, empty, or malformedchoicesare downgraded to a plain clarification question instead of failing the turn.multiple_choicepayloads must include at least two valid choices; otherwise the actor turn fails with a corrective runtime error that tells the model how to fix the call.- Choice entries may be strings or
{ label, value? }objects. - Invalid clarification payloads such as a missing
questionare still treated as actor-turn runtime errors, not as successful clarification completions.
What AxAgentState contains:
version: serialized state schema version.runtimeBindings: the actual restorable JavaScript globals, limited to serializable values.runtimeEntries: inspect-style metadata for prompt rendering, including summary-only non-restorable values.actionLogEntries: prior actor turns that should still be replayed after resume.checkpointState: checkpoint summary text plus the covered turns when checkpointing was active.provenance: per-binding metadata for the last actor code that set that variable.
Practical notes:
runtimeBindingsrestores execution state;runtimeEntries,actionLogEntries, andcheckpointStaterestore prompt context.- Resume does not create a fake rehydration action-log turn; provenance still points to the original actor code that set the value.
- When
contextPolicy.presetis'adaptive','checkpointed', or'lean', resumed prompts include aRuntime Restorenotice plus theliveRuntimeStatefield. - When
contextPolicy.presetis'full', restore still happens, but theliveRuntimeStatefield is absent from the actor signature. - Only serializable/structured-clone-friendly values are guaranteed to round-trip through
getState()/setState(...). - Reserved runtime globals such as
inputs, tools, and protocol helpers are rebuilt fresh and are not part of saved state. - Treat one agent instance as conversation-scoped when using
setState(...); do not share one mutable resumed instance across unrelated concurrent conversations.
Bubble Errors
Use bubbleErrors when certain exceptions thrown inside function handlers or llmQuery sub-agent calls should propagate all the way out to the caller of .forward() instead of being caught by the actor loop and returned as [ERROR] strings.
import { agent, ai, f, fn } from '@ax-llm/ax';
class DatabaseError extends Error {
constructor(message: string) {
super(message);
this.name = 'DatabaseError';
}
}
class AuthError extends Error {
constructor(message: string) {
super(message);
this.name = 'AuthError';
}
}
const dbTool = fn('queryUsers')
.description('Query the user database')
.namespace('db')
.arg('filter', f.string('Filter expression'))
.returns(f.string('JSON result'))
.handler(async ({ filter }) => {
if (!isConnected()) throw new DatabaseError('DB connection refused');
return JSON.stringify(await db.query(filter));
})
.build();
const myAgent = agent('query:string -> answer:string', {
contextFields: [],
functions: { local: [dbTool] },
bubbleErrors: [DatabaseError, AuthError],
});
try {
const result = await myAgent.forward(llm, { query: 'find active users' });
console.log(result.answer);
} catch (err) {
if (err instanceof DatabaseError) {
console.error('DB is down:', err.message);
} else if (err instanceof AuthError) {
console.error('Auth failed:', err.message);
} else {
throw err;
}
}
Rules:
bubbleErrorstakes an array of Error constructor classes (checked viainstanceof).- A matching error thrown anywhere — inside a function handler, during actor code execution, or inside a nested
llmQuery(...)child agent — propagates immediately to.forward(). - The same
bubbleErrorslist is automatically propagated to recursive child agents created for advanced-modellmQuery(...)calls. - Use
bubbleErrorsfor fatal infrastructure errors (DB down, auth failures, quota exceeded) that should abort the run entirely rather than let the actor retry. - Do not use
bubbleErrorsfor expected recoverable errors; let those return as[ERROR] ...strings so the actor can handle them. AxAgentClarificationErrorandAxAIServiceAbortedErroralways bubble up unconditionally — they do not need to be listed inbubbleErrors.
Unified Final Signal
There are two ways to end a successful run through the responder:
- In actor JS code: Call
final(message)when no extra context object is needed, orfinal(task, context)when you gathered evidence. - In function handlers: Use
extra.protocol.final(...)with the same one-arg or two-arg forms.
import { agent, ai, f, fn } from '@ax-llm/ax';
const checkAccess = fn('checkAccess')
.description('Verify access and complete if denied')
.arg('resource', f.string('Resource name'))
.returns(f.string('Access status'))
.handler(async ({ resource }, extra) => {
if (!hasAccess(resource)) {
extra?.protocol?.final(`Access denied for ${resource}`);
}
return 'granted';
})
.build();
const result = await myAgent.forward(llm, { query });
console.log(result);
Rules:
- Use
final(message)when the actor already knows the answer and no extra context object is needed. - Use
final(task, context)when context was gathered and needs synthesis into output fields. - In function handlers, use
extra.protocol.final(...)instead of a separate respond API. - The responder still runs for both successful
final(...)forms. - Use
askClarification(...)when the user must provide more information to continue.
Discovery Mode
Shortened here. Read the whole file on GitHub.
Signals
- GitHub stars
- 36
- Last commit
- Sep 2026
Advanced
- Catalog kind
- skill
- Gateway key
ax-agent- Source
- github.com/diogenesoftoronto/keating