# API Reference Complete reference for all Axl factories, context primitives, and configuration options. > Migrating from 0.15.x? `TraceEvent` and `StreamEvent` collapsed into a single `AxlEvent` discriminated union. Several event tag names changed (`agent_call` → `agent_call_end`, `tool_call` → `tool_call_end`) and `ExecutionInfo.steps` is now `ExecutionInfo.events`. See the [unified event model migration guide](./migration/unified-event-model.md) for the full diff. ## Factories ### `tool(config)` Define a tool with Zod-validated input and a handler function. ```typescript import { tool } from '@axlsdk/axl'; import { z } from 'zod'; const search = tool({ name: 'search', description: 'Search the web', input: z.object({ query: z.string() }), handler: async ({ query }) => fetchResults(query), retry: { attempts: 3, backoff: 'exponential' }, sensitive: false, requireApproval: false, }); ``` | Option | Type | Default | Description | |--------|------|---------|-------------| | `name` | `string` | **required** | Unique tool name | | `description` | `string` | **required** | Description shown to the LLM | | `input` | `ZodType` | **required** | Zod schema for input validation | | `handler` | `(input, ctx) => T \| Promise` | **required** | Function that executes the tool. `ctx` is a child `WorkflowContext` for nested agent invocations (see below) | | `retry` | `RetryPolicy` | see below | Retry configuration for the handler | | `sensitive` | `boolean` | `false` | When `true`, return value is redacted from LLM context in subsequent turns | | `maxStringLength` | `number` | `10000` | Max length for any string argument. Set to `0` to disable | | `requireApproval` | `boolean` | `false` | When `true`, agent-initiated calls trigger `ctx.awaitHuman()` before execution. Skipped for direct `tool.run()` calls | | `hooks` | `ToolHooks` | — | Lifecycle hooks (see below) | | `toModelOutput` | `(output: Readonly) => ToolModelOutput` | — | Synchronously allowlist the successful, post-`after` result sent to the model. The complete result remains available to the host on `tool_call_end` unless trace redaction is enabled | #### `RetryPolicy` | Option | Type | Default | Description | |--------|------|---------|-------------| | `attempts` | `number` | `1` | Total attempts (1 = no retry) | | `backoff` | `'none' \| 'linear' \| 'exponential'` | `'exponential'` | `none`: no delay. `linear`: attempt * 1s. `exponential`: 2^(attempt-1) * 1s | | `on` | `(error: Error & { status?: number }) => boolean` | all errors | Return `true` to retry this error, `false` to stop | #### `ToolHooks` | Hook | Signature | Description | |------|-----------|-------------| | `before` | `(input: TInput, ctx: WorkflowContext) => TInput \| Promise` | Transform input before handler runs | | `after` | `(output: TOutput, ctx: WorkflowContext) => TOutput \| Promise` | Transform output after handler runs | Execution order for agent-initiated calls: approval gate → `hooks.before` → handler → `hooks.after`. For direct `tool.run()` calls: `hooks.before` → handler → `hooks.after` (no approval gate). A normally returned value is successful regardless of its fields. Axl never interprets an `error` property as lifecycle control. `hooks.after` therefore runs exactly once after every normal handler return and never after a handler throw. #### Model-safe tool failures Throw `ToolFailure` only when a known failure is safe for the model to act on: ```typescript import { ToolFailure } from '@axlsdk/axl'; throw new ToolFailure({ message: 'Inventory reservation conflicted', modelMessage: 'That item is no longer available; offer another item.', code: 'OUT_OF_STOCK', cause, }); ``` | Option | Type | Default | Description | |---|---|---|---| | `message` | `string` | **required** | Host diagnostic retained on the terminal event subject to redaction | | `modelMessage` | `string` | **required** | Author-declared provider-safe content used for agent-loop continuation | | `code` | `string` | `'TOOL_FAILURE'` | Stable application code | | `cause` | `unknown` | — | Non-enumerable host-only cause | A handler-thrown `ToolFailure` follows the existing `RetryPolicy`; hook failures are not retried. A terminal `ToolFailure` from `before`, the handler, or `after` closes the call as `failed` with `disposition: 'continue'`; the model receives only `modelMessage` (or the fixed marker for a sensitive tool). An ordinary throw closes the call as `failed` with `disposition: 'abort'`, emits no provider tool content, and aborts the ask. Direct `tool.run()` and `_execute()` propagate both kinds of throw to their caller and emit no provider-issued `tool_call_*` lifecycle. #### Model-facing tool output `toModelOutput` separates the complete application result from the compact content sent back to the model on the next turn: ```typescript const findOrder = tool({ name: 'find_order', description: 'Find an order and return application actions', input: z.object({ orderId: z.string() }), handler: async ({ orderId }) => ({ humanMessage: 'Order is ready for pickup.', action: { label: 'Open order', internalId: orderId }, payload: await loadLargeOrderPayload(orderId), }), toModelOutput: (result) => ({ message: result.humanMessage }), }); ``` The mapper is synchronous, runs inline once per accepted agent-invoked tool call that has completed `hooks.after` and can continue to the provider, and receives the same result reference retained for the terminal host event. Axl rechecks cancellation before and after projection; cancellation closes the call as `cancelled` and sends no tool message. `Readonly` is shallow and is an authoring contract: Axl does not clone or freeze the result. Treat the mapper as pure; mutating the value is unsupported and can also mutate the object retained by the host event. A slow mapper blocks the ask once it starts. If a later workflow run re-executes the tool call, it evaluates the mapper again; a checkpoint replay that skips the call also skips mapping. Provider transport retries reuse the already-serialized tool message rather than rerunning the mapper or tool. `ToolModelOutput` supports strings, finite numbers, booleans, `null`, dense arrays, and plain or null-prototype records recursively. An `undefined` object property is omitted. A top-level `undefined`, array hole/`undefined`, bigint, function, symbol, non-finite number, cycle, Promise/thenable, accessor, callable custom `toJSON`, any symbol key, or non-plain object fails with exported `ToolModelOutputError`. Shared non-cyclic references are valid. Projected strings become verbatim canonical tool-message content; every other value is validated and JSON-encoded once. Prefer record projections when the distinction between JSON-looking text and structured data must survive every provider's native tool-result envelope. Without a mapper, legacy `JSON.stringify` behavior is unchanged, including quoted string results. Configured local tools use this precedence: 1. `sensitive: true` sends `[REDACTED - sensitive tool output]` and never runs the mapper. 2. An explicit `ToolFailure` from `before`, the handler, `after`, or a configured mock sends only its author-declared `modelMessage` and never runs the mapper. 3. An ordinary thrown handler, hook, or mock error aborts the ask without provider tool content and never runs the mapper. 4. A normally returned value runs `hooks.after` exactly once and then runs `toModelOutput` when configured. This includes any value with an `error` property: property names have no lifecycle meaning. 5. Otherwise Axl uses legacy serialization. Projection runs only for configured local tools invoked by an agent, including the agent-as-tool pattern. `tool.run()` and `_execute()` always return the complete value without projecting. MCP tools and handoff pseudo-tools are unchanged. A matching `AxlTestRuntime.mockTool()` bypasses the real handler, validation, approval, retry, and hooks as before, but inherits the configured tool's `sensitive` and `toModelOutput` policy. An override with no configured tool keeps legacy behavior. If mapping or validation fails, Axl closes the accepted call as `failed` / `projection` and then throws `ToolModelOutputError` with code `TOOL_MODEL_OUTPUT_ERROR`, `toolName`, and a generic message. It never falls back to the raw result, appends no tool message, and makes no next provider call. The terminal outcome retains the complete post-`after` result for trusted host observation. At that point the handler and successful `after` hook have already completed; retrying the surrounding workflow can therefore repeat their effects unless the application uses its normal idempotency/checkpoint strategy. The host-only `.cause` may contain mapper-supplied details. It is non-enumerable so ordinary `JSON.stringify(error)` does not include it, but serializers that inspect non-enumerable properties still can; do not export it without applying your own redaction policy. `tool_call_end.duration` and the `axl.tool.call` span cover total wall time through output preparation. This is a model/provider-facing data-minimization boundary, not a host-event security or delivery boundary. Projection is an allowlist, not a size or token budget: it may be larger than the complete result, and Axl does not truncate it automatically. `tool_call_end.data.outcome.result` remains complete on result-bearing variants subject to `trace.redact`; it does not gain a projected field. Critical side effects must happen in the handler or workflow logic, not solely in an event listener: `ctx.events`, `AxlStream`, and trace listeners retain their existing redaction, bounded-queue, overflow, and persistence behavior. #### Child Context in Tool Handlers When a tool is invoked by an agent, the handler receives a child `WorkflowContext` as its second parameter. This enables the "agent-as-tool" composition pattern — tools can invoke other agents via `ctx.ask()`. ```typescript const researchTool = tool({ name: 'research', description: 'Delegate a research question to a specialist agent', input: z.object({ question: z.string() }), handler: async (input, ctx) => { return ctx.ask(researcher, input.question); }, }); ``` The child context shares budget tracking, abort signals, trace emission, the `ctx.events` bus, and explicit streaming mode with the parent. Nested-ask events propagate to the same bus; consumers wanting root-only behavior filter on `event.depth === 0`, while per-ask consumers route by `askId`. Session history is isolated. Created internally via `WorkflowContext.createChildContext()`. --- ### `agent(config)` Define an agent with a model, system prompt, tools, and optional handoffs. ```typescript import { agent } from '@axlsdk/axl'; const myAgent = agent({ model: 'openai-responses:gpt-5.5', system: 'You are a helpful assistant.', tools: [search, calculator], temperature: 0.7, maxTokens: 8192, effort: 'high', maxTurns: 10, timeout: '30s', }); ``` | Option | Type | Default | Description | |--------|------|---------|-------------| | `name` | `string` | model string or `Agent_N` | Display name used in traces | | `model` | `string \| (ctx) => string` | **required** | Provider URI (e.g., `'openai:gpt-4o'`, `'anthropic:claude-sonnet-4-6'`). Function form enables dynamic model routing | | `system` | `string \| (ctx) => string` | **required** | System prompt. Function form enables per-request customization | | `tools` | `Tool[]` | `[]` | Tools this agent can call. Acts as an ACL — the agent cannot call tools not in this list | | `handoffs` | `HandoffDescriptor[] \| (ctx) => HandoffDescriptor[]` | `[]` | Agents this agent can hand off to. Function form receives `{ metadata?: Record }` for dynamic routing (see below) | | `mcp` | `string[]` | `[]` | MCP server names to connect. Tools from these servers are merged into the agent's tool set | | `mcpTools` | `string[]` | — | Whitelist: only expose these specific MCP tools | | `temperature` | `number` | provider default | LLM sampling temperature | | `maxTokens` | `number` | `4096` | Maximum tokens in the LLM response | | `effort` | `Effort` | — | Unified effort level: `'none'` \| `'low'` \| `'medium'` \| `'high'` \| `'xhigh'` \| `'max'`. Controls reasoning depth across all providers. `'xhigh'` is supported natively on Anthropic Opus 4.8/4.7 and OpenAI gpt-5.2+ (including gpt-5.5); clamps to `'high'` on other models | | `thinkingBudget` | `number` | — | Explicit thinking token budget (advanced). Overrides effort-based allocation. Set to `0` to disable thinking while keeping effort | | `includeThoughts` | `boolean` | — | Return reasoning summaries in responses. Supported on OpenAI Responses API and Gemini | | `toolChoice` | `'auto' \| 'none' \| 'required' \| { type: 'function', function: { name } }` | — | Tool choice strategy: `'auto'` lets the model decide, `'none'` forbids tool use, `'required'` forces at least one tool call, or specify a function name to force a specific tool | | `stop` | `string[]` | — | Stop sequences — generation stops when any sequence is encountered. Not supported by the `openai-responses` provider (silently ignored) | | `providerOptions` | `Record` | — | Provider-specific options shallow-merged into the raw API request body via `Object.assign`. Not portable across providers. See [shallow merge caveat](providers.md#provideroptions) | | `maxTurns` | `number` | `25` | Maximum tool-call loop iterations before throwing `MaxTurnsError`. **A "turn" in axl is one provider call inside a single `ctx.ask()`** — not a user↔assistant exchange. Schema/validate/guardrail retries also consume turns. See [Sessions → Turns vs. Exchanges](#turns-vs-exchanges) | | `timeout` | `string` | none | Duration string (e.g., `'30s'`, `'5m'`, `'1h'`). Throws `TimeoutError` when exceeded | | `maxContext` | `number` | — | Estimated token limit for context window management | | `version` | `string` | — | Prompt version label attached to trace events | | `guardrails` | `GuardrailsConfig` | — | Input/output validation (see [Guardrails](#guardrails)) | #### `HandoffDescriptor` | Option | Type | Default | Description | |--------|------|---------|-------------| | `agent` | `Agent` | **required** | Target agent | | `description` | `string` | — | Description shown to the LLM to help it decide when to hand off | | `mode` | `'oneway' \| 'roundtrip'` | `'oneway'` | `oneway`: transfers the conversation — source agent's loop exits. `roundtrip`: delegates and returns the result to the source agent | #### Dynamic Handoffs The `handoffs` option accepts a function for runtime-conditional routing. The function receives `{ metadata?: Record }` (from `AskOptions.metadata` or workflow metadata) and returns the handoff array: ```typescript const router = agent({ name: 'support-router', model: 'openai-responses:gpt-5-mini', system: 'Route to the right specialist.', handoffs: (ctx) => { const base = [ { agent: billingAgent, description: 'Billing issues' }, { agent: shippingAgent, description: 'Shipping questions' }, ]; if (ctx.metadata?.tier === 'enterprise') { base.push({ agent: priorityAgent, description: 'Priority support' }); } return base; }, }); ``` --- ### `workflow(config)` Define a named workflow with typed input/output. ```typescript import { workflow } from '@axlsdk/axl'; import { z } from 'zod'; const myWorkflow = workflow({ name: 'MyWorkflow', input: z.object({ query: z.string() }), output: z.object({ answer: z.string() }), handler: async (ctx) => { const answer = await ctx.ask(myAgent, ctx.input.query); return { answer }; }, }); ``` | Option | Type | Default | Description | |--------|------|---------|-------------| | `name` | `string` | **required** | Workflow name used for `runtime.execute(name, input)` | | `input` | `ZodType` | **required** | Zod schema for workflow input | | `output` | `ZodType` | — | Optional Zod schema for output validation | | `handler` | `(ctx: WorkflowContext) => Promise` | **required** | Async function receiving the workflow context | ### `runtime.createContext(options?)` Create a `WorkflowContext` for ad-hoc use outside of workflows — evals, tool testing, prototyping. The context automatically emits trace events to the runtime's EventEmitter and tracks cost. Traces from ad-hoc contexts are visible in Studio's cost dashboard and trace explorer. ```typescript const ctx = runtime.createContext(); const answer = await ctx.ask(myAgent, 'hello'); console.log(ctx.totalCost); // accumulated cost from all agent calls ``` | Option | Type | Default | Description | |--------|------|---------|-------------| | `metadata` | `Record` | `{}` | Metadata passed to the context | | `budget` | `string` | — | Cost budget (e.g., `'$0.50'`). Enforced via `finish_and_stop` policy | | `signal` | `AbortSignal` | — | Abort signal for cancellation/timeouts | | `sessionHistory` | `ChatMessage[]` | — | Prior conversation history for multi-turn testing | | `awaitHumanHandler` | `(options) => Promise` | — | Handler for tool approval requests. Required when the agent uses tools with `requireApproval` — without it, the call throws a clear error | | `events` | `EventStreamOptions` | `{ maxQueued: 10_000, onOverflow: 'drop-oldest-non-terminal' }` | Configures the iterator-queue cap and overflow policy on the lazy `ctx.events` bus. See [`EventStreamOptions`](#eventstreamoptions) | > **Removed callback options.** `onToken`, `onToolCall`, and `onAgentStart` are > no longer part of `CreateContextOptions`. An untyped object containing any of > those keys throws `INVALID_CONFIG` immediately, even if the value is > `undefined`; the value is neither read nor invoked. Iterate `ctx.events` (an > `AxlEventBus` — the same `AsyncIterable` + `EventEmitter` shape as > `AxlStream`) or use another observation surface from the > [migration guide](migration/stream-first-observation.md). **When to use vs. workflows:** Use `createContext()` when you want to call agents without registering a workflow — eval files, one-off scripts, tests, API endpoints. Use `runtime.execute()` when you want execution lifecycle tracking (status, duration, history in Studio's executions panel). **Budget and timeout:** ```typescript const controller = new AbortController(); setTimeout(() => controller.abort(), 30_000); const ctx = runtime.createContext({ budget: '$1.00', signal: controller.signal, }); ``` **Tool approval in evals:** ```typescript const ctx = runtime.createContext({ awaitHumanHandler: async () => ({ approved: true }), // auto-approve in evals }); ``` ### `runtime.trackExecution(fn, options?)` Track cost and execution metadata across any runtime operations within `fn`. Returns `{ result, cost, unpriced, metadata, traces? }` where `unpriced` is `true` when any tracked call was unpriced (making `cost` a **lower bound** — the aggregate counterpart of `ExecutionInfo.unpriced`), and `metadata` includes `models` (unique model URIs), `modelCallCounts`, `tokens` (input/output/reasoning sums — agent calls only, not embedder tokens), `agentCalls` count, `workflows` (insertion-ordered unique names), and `workflowCallCounts`. Uses `AsyncLocalStorage` for per-call scoping — correct with concurrent calls. Works with both `createContext()` and `execute()` inside `fn`. **Note on `metadata.tokens`:** narrowly scoped to agent prompt/completion/reasoning tokens. Embedder tokens from semantic memory ops are deliberately not summed in (different pricing, different model). Consumers who want embedder token counts should subscribe to `runtime.on('trace', ...)` and read `data.usage.tokens` on `memory_remember` / `memory_recall` events. | Option | Type | Default | Description | |--------|------|---------|-------------| | `captureTraces` | `boolean` | `false` | When `true`, collects every `AxlEvent` observed during `fn` and returns it on `result.traces`. On failure, the captured traces are attached to the thrown error as a non-enumerable `axlCapturedTraces` property (eval runners read this side-channel to populate `EvalItem.traces` on failed items). Verbose-mode `agent_call_start.data.messages` snapshots are stripped from captured traces to keep memory bounded | ```typescript const { result, cost, metadata } = await runtime.trackExecution(async () => { const ctx = runtime.createContext(); return ctx.ask(myAgent, 'hello'); }); console.log(`Cost: $${cost}, Models: ${metadata.models.join(', ')}`); // With per-invocation trace capture: const { result, traces } = await runtime.trackExecution( async () => runtime.execute('my-workflow', input), { captureTraces: true } ); console.log(`${traces.length} trace events captured`); ``` ### `runtime.trackCost(fn)` Convenience wrapper around `trackExecution()` that returns only `{ result, cost, unpriced }` (`unpriced` makes `cost` a lower bound — see `trackExecution`). Use when you don't need metadata. ```typescript const { result, cost } = await runtime.trackCost(async () => { return runtime.execute('my-workflow', input); }); ``` The eval runner and CLI use `trackExecution` internally to capture cost and model metadata for each eval item. --- ## Context Primitives All primitives are available on `ctx` inside workflow handlers. ### `ctx.ask(agent, prompt, options?)` Invoke an agent. Runs the tool-call loop until the agent produces a final response or hits `maxTurns`. ```typescript const answer = await ctx.ask(myAgent, 'What is 2+2?'); // With structured output const data = await ctx.ask(myAgent, 'Extract the user profile', { schema: UserProfile, retries: 3, }); ``` | Option | Type | Default | Description | |--------|------|---------|-------------| | `schema` | `ZodType` | — | Validates and parses the response as structured output. On validation failure, retries with accumulating context | | `schemaPrompt` | `'json-schema' \| 'none' \| { render: string \| (schema) => string }` | `'json-schema'` | How `schema` is rendered into the model-facing prompt. `'none'` appends nothing (schema stays the parse gate; fires a `schema_prompt_none_no_guidance` diagnostic); `{ render }` appends exactly your string/function output. Does NOT affect the `.parse` gate. See [Structured Output](#structured-output) | | `nativeStructuredOutput` | `boolean` | `false` | Opt into the provider's native `json_schema` path, deriving the provider schema from the same `schema` (no second, contradictable schema). Only when a `schema` is set and no tools. Providers that can't honor it downgrade/ignore it and a `native_output_unsupported` diagnostic warns; the call proceeds. See [Structured Output](#structured-output) | | `retries` | `number` | `3` | Number of schema validation retries | | `validate` | `OutputValidator` | — | Post-schema business rule validation. Receives the parsed typed object. Only runs when `schema` is set. See [Validate](#validate) | | `validateRetries` | `number` | `2` | Maximum retries for `validate` failures | | `metadata` | `Record` | — | Merged with workflow metadata and passed to dynamic `model`/`system` selector functions | | `temperature` | `number` | agent config | Override sampling temperature for this call | | `maxTokens` | `number` | agent config or `4096` | Override max tokens for this call | | `effort` | `Effort` | agent config | Override effort level for this call | | `thinkingBudget` | `number` | agent config | Override thinking budget for this call | | `includeThoughts` | `boolean` | agent config | Override includeThoughts for this call | | `toolChoice` | `'auto' \| 'none' \| 'required' \| { type: 'function', function: { name } }` | agent config | Override tool choice for this call | | `stop` | `string[]` | agent config | Override stop sequences for this call | | `providerOptions` | `Record` | agent config | Override provider-specific options for this call. Shallow-merged; see [caveat](providers.md#provideroptions) | **Precedence:** Per-call `AskOptions` > agent-level `AgentConfig` > internal defaults. **Returns:** `Promise` — parsed output if `schema` is provided, otherwise `string`. **Retry mechanics:** All output retries (guardrail, schema, validate) use **accumulating context** — the LLM's failed response is appended as an assistant message, followed by a system message explaining the error. On subsequent retries, the LLM sees all prior failed attempts, giving it increasing context for self-correction. Failed responses are **not** persisted to session history; only the final successful response is recorded. See the [Output Pipeline](#output-pipeline) for the full gate-by-gate flow. **Streaming + validate:** As of 0.16.0, `validate` and token streaming (via `runtime.stream()`) coexist — validate runs against the buffered response after streaming completes. (Pre-0.16.0 this combination threw `INVALID_CONFIG`.) For structured output, the typed result is still only available after the full response arrives. --- ### `ctx.delegate(agents, prompt, options?)` Select the best agent from a list of candidates and invoke it. Creates a temporary router agent that uses handoffs to pick the right specialist. **Parameters:** | Parameter | Type | Description | |-----------|------|-------------| | `agents` | `Agent[]` | Candidate agents to choose from (at least 1) | | `prompt` | `string` | The prompt to route and process | | `options.schema` | `z.ZodType` | Zod schema for structured output from the selected agent | | `options.routerModel` | `string` | Model URI for the internal router (default: first candidate's model) | | `options.metadata` | `Record` | Additional metadata passed to router and selected agent | | `options.retries` | `number` | Retries for structured output validation | | `options.validate` | `OutputValidator` | Post-schema business rule validation. Forwarded to the final `ctx.ask()` call | | `options.validateRetries` | `number` | Maximum retries for validate failures (default: 2) | **Returns:** `Promise` — the selected agent's response. **Behavior:** - With 1 agent: calls `ctx.ask()` directly (no routing overhead) - With 2+ agents: creates a temporary router agent with `temperature: 0` and `maxTurns: 2` that hands off to the best candidate - Emits a `delegate` trace event with candidate names and router model **Example:** ```typescript const result = await ctx.delegate( [billingAgent, shippingAgent, generalAgent], customerMessage, ); ``` **With structured output:** ```typescript const result = await ctx.delegate( [billingAgent, shippingAgent], customerMessage, { schema: z.object({ answer: z.string(), category: z.string() }), routerModel: 'openai-responses:gpt-5-mini', }, ); ``` --- ### `ctx.spawn(n, fn, options?)` Run N concurrent tasks in parallel. ```typescript // Wait for all 3 const results = await ctx.spawn(3, (i) => ctx.ask(agent, prompts[i])); // Wait for 2 of 3, cancel the rest const results = await ctx.spawn(3, (i) => ctx.ask(agent, prompts[i]), { quorum: 2 }); ``` | Option | Type | Default | Description | |--------|------|---------|-------------| | `quorum` | `number` | — | Resolve as soon as this many tasks succeed. Remaining tasks are cancelled via `AbortController`. Throws `QuorumNotMet` if fewer than `quorum` succeed | **Returns:** `Promise[]>` where `Result` is `{ ok: true, value: T } | { ok: false, error: string }`. --- ### `ctx.vote(results, options)` Pick a winner from an array of `Result` values. All built-in strategies are deterministic — no LLM involved. Use `scorer` or `reducer` for async/LLM-based judging. ```typescript const winner = await ctx.vote(results, { strategy: 'majority', key: 'answer' }); ``` | Option | Type | Default | Description | |--------|------|---------|-------------| | `strategy` | `VoteStrategy` | **required** | See strategy table below | | `key` | `string` | — | Field name to compare when results are objects | | `scorer` | `(value: T) => number \| Promise` | — | Score each candidate. **Only works with `highest` and `lowest`** | | `reducer` | `(values: T[]) => T \| Promise` | — | Custom aggregation function. **Only works with `custom`** | #### Vote Strategies | Strategy | Description | Compatible options | |----------|-------------|-------------------| | `'majority'` | Picks the value that appeared most often | `key` | | `'unanimous'` | Returns the value if all agree; throws `NoConsensus` if they differ | `key` | | `'highest'` | Picks the candidate with the highest numeric value | `key` or `scorer` | | `'lowest'` | Picks the candidate with the lowest numeric value | `key` or `scorer` | | `'mean'` | Computes the arithmetic mean | Values must be numbers | | `'median'` | Computes the median | Values must be numbers | | `'custom'` | Delegates to your `reducer` function | `reducer` | **Throws:** `NoConsensus` if no successful results, if `unanimous` values differ, or if an invalid strategy/option combination is used. --- ### `ctx.verify(fn, schema, options?)` Retry-until-valid loop with schema and business rule validation. Calls `fn`, validates the result against `schema` (and optionally `validate`). On failure, calls `fn` again with a retry context describing what went wrong. Use `ctx.verify()` to validate and retry any async operation — API calls, data transformations, multi-step pipelines — or to wrap `ctx.ask()` as a programmatic repair fallback when the LLM can't satisfy business rules on its own: ```typescript const OrderSchema = z.object({ items: z.array(z.object({ sku: z.string(), qty: z.number() })), shipping: z.enum(['standard', 'express']), }); const orderValidator = (order: z.infer) => { if (order.items.some(i => i.qty <= 0)) { return { valid: false, reason: 'All quantities must be positive' } as const; } return { valid: true } as const; }; // ctx.ask() retries internally (schema: 3, validate: 2 by default). // If it still fails, ctx.verify() catches the error and provides retry.parsed. const order = await ctx.verify( async (retry) => { if (retry?.parsed) { // LLM couldn't get it right — repair programmatically return { ...retry.parsed, items: retry.parsed.items.filter(i => i.qty > 0) }; } return ctx.ask(extractAgent, 'Extract the order from this email', { schema: OrderSchema, validate: orderValidator, }); }, OrderSchema, { retries: 1, validate: orderValidator }, ); ``` **`fn` signature:** `(retry?: VerifyRetry) => Promise` On the first call, `retry` is `undefined`. On retries, it contains: | Field | Type | Description | |-------|------|-------------| | `retry.error` | `string` | Error message from the failed attempt | | `retry.output` | `unknown` | Raw return value from the previous `fn` call | | `retry.parsed` | `T \| undefined` | Schema-parsed object — **only present when schema passed but validate failed**. Safe to modify and return. Absent on schema failures | See [Validated Data Extraction](use-cases.md#validated-data-extraction) for more patterns including API data repair and non-LLM use cases. **Error extraction from `fn()` throws:** When `fn()` throws instead of returning, `verify` inspects the error and extracts structured output so the next retry has data to work with. Since `fn()` never returned a value, `retry.output` would normally be `undefined` — but `verify` recovers it from the error's `lastOutput` property: - **`ValidationError`** (e.g., `ctx.ask()` with `validate` exhausted its retries): `retry.parsed` and `retry.output` are both populated from `err.lastOutput` — the schema-valid, parsed object that passed schema but failed business rules. Use `retry?.parsed` to repair it programmatically. - **`VerifyError`** (e.g., `ctx.ask()` with `schema` exhausted its retries, or nested `ctx.verify()`): `retry.output` is populated from `err.lastOutput` — the raw LLM response string that failed schema parsing. `retry.parsed` remains `undefined` since the output couldn't be parsed. - **Other errors**: `retry.output` and `retry.parsed` are both `undefined` (no structured output to extract). | Option | Type | Default | Description | |-------|------|---------|-------------| | `retries` | `number` | `3` | Maximum retry attempts | | `fallback` | `T` | — | Return this value instead of throwing when retries are exhausted | | `validate` | `OutputValidator` | — | Post-schema business rule validation. Runs after schema parse succeeds | **Throws:** `VerifyError` (schema failure) or `ValidationError` (validate failure) if retries exhausted and no fallback provided. When `fn()` throws a `VerifyError` or `ValidationError`, `verify` re-throws the original error (not a new wrapper) after retries are exhausted. **Retry mechanics:** `ctx.verify()` is **not** conversation-aware. It is a plain loop that calls your function, validates the return value (schema then validate), and on failure passes a `VerifyRetry` context to your next call. What you do with that context is entirely up to you — `ctx.verify()` does not modify any LLM conversation or session history. This makes it suitable for retrying any async operation, not just LLM calls. --- ### `ctx.budget(options, fn)` Cost-bounded execution. Tracks LLM spend inside `fn` and enforces the limit based on the `onExceed` policy. ```typescript const result = await ctx.budget({ cost: '$5.00', onExceed: 'hard_stop' }, async () => { return await ctx.ask(agent, prompt); }); if (result.budgetExceeded) { console.log(`Spent $${result.totalCost}, budget exceeded`); } ``` | Option | Type | Default | Description | |--------|------|---------|-------------| | `cost` | `string` | **required** | Dollar amount (e.g., `'$5.00'`, `'$0.50'`) | | `onExceed` | `'finish_and_stop' \| 'hard_stop' \| 'warn'` | `'finish_and_stop'` | See policies below | #### `onExceed` Policies | Policy | Behavior | |--------|----------| | `'finish_and_stop'` | Let the current LLM call finish, then prevent further calls. The function completes normally with whatever result is available | | `'hard_stop'` | Abort immediately via `AbortController`. The current LLM call is cancelled mid-flight. Returns `{ value: null, budgetExceeded: true }` | | `'warn'` | Log a warning but allow execution to continue past the budget | **Returns:** `BudgetResult`: `{ value: T | null, budgetExceeded: boolean, totalCost: number, unpriced: boolean }` - **`unpriced`** — `true` when the block ran a model with no usable per-call cost (unpriced model / pricing-table miss) that did measurable work. `totalCost` is then a **lower bound** (the unknown component is omitted). The same condition is readable mid-block via [`ctx.getBudgetStatus().unpriced`](#ctxgetbudgetstatus), and Axl logs a one-time `console.warn` per budget block when it happens. - ⚠️ **`unpriced` is observability only — cost limits / `hard_stop` are NOT enforced on unpriced spend.** The enforcement rail never sees the unknown cost, so a `hard_stop` budget does **not** govern unpriced models (e.g. Bedrock, self-hosted). Token-denominated budgets are the planned fix for governing unpriced spend. Until then, treat `unpriced: true` as "this limit could not be enforced for part of this block." **Nesting:** Budget blocks can be nested. Inner budgets roll their costs — **and their `unpriced` lower-bound flag** — up to the parent. #### `ctx.getBudgetStatus()` Returns the live status of the active budget block, or `null` outside any block: `{ spent: number, limit: number, remaining: number, unpriced: boolean }`. `unpriced` mirrors `BudgetResult.unpriced`; when `true`, `spent` is a lower bound and `remaining` an upper bound (see the enforcement caveat above). ### `ctx.totalCost` Read-only getter returning the total cost accumulated by agent calls in this context. Inside a `ctx.budget()` block, returns only that block's accumulated cost; after the block completes, the nested cost is rolled up into the parent total. > **Unpriced models → lower bound.** A call to an unpriced model (pricing-table miss / a provider that reports no per-call cost) contributes `undefined` cost, which counts as nothing — so `ctx.totalCost` (and `ExecutionInfo.totalCost`, `ctx.budget()` accounting) **understate** total spend when unpriced models run. Detect it via: `ExecutionInfo.unpriced` (the execution-level aggregate from `runtime.execute()` / `getExecutions()`), `runtime.trackExecution().unpriced`, the owning `ask_end.unpriced`, `BudgetResult.unpriced` / `ctx.getBudgetStatus().unpriced` for a `ctx.budget()` block, and the Studio Cost Dashboard's `CostData.unpricedCalls`. Because the unknown component is invisible to the budget rail, a `ctx.budget()` cost limit / `hard_stop` **cannot enforce on unpriced spend** — it only reports it. ```typescript const ctx = runtime.createContext(); await ctx.ask(agent, 'hello'); console.log(ctx.totalCost); // e.g. 0.05 ``` --- ### `ctx.events` Lazy `AxlEventBus` exposing every `AxlEvent` emitted by this context (and its child contexts — agent-as-tool nested asks bubble up). Same `AsyncIterable` + `EventEmitter` shape as `AxlStream`, with the same curated views. ```typescript // Schemas + agents the example uses — declared so the snippet is // self-contained. const outlineSchema = z.object({ outline: z.array(z.string()) }); const draftSchema = z.object({ draft: z.string() }); const planner = agent({ model: 'openai:gpt-4o', system: 'Plan an outline.' }); const writer = agent({ model: 'openai:gpt-4o', system: 'Write the draft.' }); const wf = workflow({ name: 'two-step', input: z.object({ topic: z.string() }), handler: async (ctx) => { // Allocate the bus first — `ctx.events` is a lazy getter; the // streaming code path inside ctx.ask() only activates when an // observer was present at the time the ask started. Touching the // getter synchronously here wires every ask in this handler. // (The IIFE pattern alone is correct, since `for await // (...ctx.events.partialObjects)` evaluates the getter // synchronously before the first await — but the explicit // `const events = ctx.events;` is unambiguous and survives // refactors that move the iterator setup into a helper.) const events = ctx.events; void (async () => { for await (const partial of events.partialObjects) { // partial: { askId, agent?, object, attempt } console.log( `[ask ${partial.askId} attempt ${partial.attempt}]`, partial.object, ); } })().catch((err) => ctx.log('observer.failed', { error: String(err) })); const outline = await ctx.ask(planner, ctx.input.topic, { schema: outlineSchema }); // ctx.ask's second arg is a string prompt — serialize the // structured outline for the next agent. const draft = await ctx.ask(writer, JSON.stringify(outline), { schema: draftSchema }); return draft; }, }); ``` | Member | Type | Description | |--------|------|-------------| | `[Symbol.asyncIterator]` | `AsyncIterator` | Iterate every event in emission order via `for await` | | `.text` | `AsyncIterable` | Root-only token chunks (chat-bubble view) | | `.lifecycle` | `AsyncIterable` | Structural events only — `ask_*`, `agent_call_*`, `tool_call_*` (including `tool_call_rejected`), `tool_approval`, `handoff_start`, `handoff_return`, `delegate`, `pipeline`, `verify`, `schema_diagnostic`, `workflow_*`, `checkpoint_save`, `checkpoint_replay`, `await_human`, `await_human_resolved`. Skips per-token chatter and progressive `partial_object` emissions. Identical to `AxlStream.lifecycle` (single source of truth: `LIFECYCLE_TYPES` in `event-stream.ts`) | | `.textByAsk` | `AsyncIterable<{ askId, agent?, text }>` | Per-ask token chunks for split-pane UIs | | `.partialObjects` | `AsyncIterable` (`{ askId, agent?, object, attempt }`) | **Coalescing view** — yields the latest `partial_object` payload per `askId`. `attempt` is the 1-indexed attempt number; on schema/validate/guardrail retry, the runtime emits `pipeline(failed)` and the view drops any undrained pending value for the affected ask, so attempt-N snapshots cannot leak across the retry boundary. Listener-based: does NOT race with the main iterator; running both concurrently each receive every event. Memory bounded by `O(active asks)`, not `O(events emitted)` | | `.stringStream(opts?)` | `AsyncIterable` (`{ askId, agent?, path, delta, accumulated, attempt }`) | **Streaming view** over `string_delta` events with optional `{ path?, askId? }` filters. `delta` contains all new chars for that ask/path since this subscriber's previous yield (slow subscribers may receive several provider chunks coalesced); `accumulated` is canonical text-so-far. Late subscribers seed through the same bounded queue. Listener-based: does NOT race with the main iterator. Each subscriber is bounded by `EventStreamOptions`: pending updates coalesce per ask/path, and distinct fields use the configured overflow policy. Per-ask state clears on `pipeline(failed)` and `ask_end` | | `.on(type, handler)` / `.off(type, handler)` | `(this)` | Subscribe/unsubscribe per AxlEvent type. Names outside `AxlEventType` are silently ignored on `AxlEventBus` (the bus emits no other names). On `AxlStream`, non-AxlEvent names like `'close'`, `'data'`, `'end'`, `'error'`, `'pause'`, `'resume'`, `'readable'` fall through to the underlying Node `Readable` — those work as standard Node stream events | | `.isFinished` | `boolean` | Whether the bus has been finalized (auto-set on `workflow_end` / `error`) | **Lifecycle:** - The bus is allocated lazily on first `ctx.events` access. Contexts that never observe pay zero overhead. - Auto-terminates when `emitEvent` fires `workflow_end` or `error`. Iterators resolve with `done: true`. - For ad-hoc `runtime.createContext()` flows that never run a workflow, call `ctx.disposeEvents()` to terminate iterators manually. - Child contexts (created via `ctx.createChildContext()`, used internally by the agent-as-tool pattern) share the parent's bus through a mutable slot, so a late subscription on the parent still receives events from a child that already exists. **Subscribe early.** The streaming code path inside `ctx.ask()` only activates when an observer is present at the time the ask starts. If you allocate `ctx.events` AFTER a `ctx.ask()` has begun, that in-flight ask will not stream `token` / `partial_object` events at all (the agent loop went through the non-streaming `provider.chat` code path). Subsequent asks (started after the bus exists) stream normally — the gate is re-checked per ask. Subscribe at the top of the workflow handler — `const events = ctx.events;` on the first line is the unambiguous pattern. The bus's iterator queue retains events emitted before any consumer iterates, so a late `for await (const e of ctx.events)` will still drain whatever is already queued. The `partialObjects` view additionally seeds from a per-bus `latestPartialByAsk` map at subscription time, so a late subscriber may see the latest coalesced state from earlier in the run. **Neither mechanism rescues you from the streaming-gate behavior** — for full token/partial fidelity, allocate the bus before the first ask. **Cost rollup — pick one channel.** `event.cost` flows on `agent_call_end`, `tool_call_end`, `memory_remember`, `memory_recall` (cost-bearing leaves) and on `ask_end` (per-ask rollup excluding nested asks). Naive `total += event.cost` from `ctx.events` PLUS `runtime.on('trace', …)` double-counts because the same events fan out to both. Use `eventCostContribution(event)` from `@axlsdk/axl` (skips `ask_end` rollups), or read pre-aggregated `ctx.totalCost`. The four observation channels — `ctx.events`, `runtime.stream()`, `runtime.on('trace', …)`, `runtime.execute()` final result — are alternatives, not additive. **Handler exceptions still terminate the bus.** When a workflow handler throws, the runtime emits a terminal `error` event and finishes the bus, so `for await (const e of ctx.events)` resolves cleanly with `done: true`. You don't need defensive `try/finally` around the observer iteration; the thrown error is independently rejected on the `runtime.execute()` / `runtime.stream()` promise. **Agent-as-tool nested asks bubble up.** Tool handlers receive `(input, ctx)` where `ctx` is a child `WorkflowContext` that shares the parent's bus through a mutable slot. Partials emitted from `ctx.ask()` calls inside a tool handler surface on the OUTER workflow's `ctx.events.partialObjects` iterator, scoped via `askId`/`parentAskId`/`depth`. Filter on `event.depth >= 1` to isolate nested-ask events. #### `EventStreamOptions` Configures the iterator-queue cap and overflow policy on `ctx.events` and on the `AxlStream` returned by `runtime.stream()`. | Field | Type | Default | Description | |-------|------|---------|-------------| | `maxQueued` | `number` | `10_000` | Soft cap on events buffered while waiting for a consumer, including distinct pending fields in each listener-based `stringStream()` subscriber. Terminal events (`done`, `error`, `workflow_end`) are exempt from the main queue. Set to `Infinity` to disable | | `onOverflow` | `'drop-oldest-non-terminal' \| 'throw'` | `'drop-oldest-non-terminal'` | Policy on cap exceeded. `'drop-oldest-non-terminal'` drops the oldest non-terminal event and emits a one-shot `console.warn` per bus instance. `'throw'` throws an `EventStreamOverflowError` at the producer call site — **this will fail the active workflow** (the throw unwinds the agent loop and the runtime promise rejects with the typed error; catch via `instanceof EventStreamOverflowError`). Note: on `runtime.execute()` (no `AxlStream`), the throw only fires if the handler allocated `ctx.events` and that bus saturates. On `runtime.stream()`, the wire-side `AxlStream` bus always applies the policy. Use only in tests / strict environments | **Behavior change in this release.** Existing `AxlStream` consumers on 0.x gain the cap automatically. If your workflow somehow relied on unbounded queueing, opt out via `events: { maxQueued: Infinity }`. ### `ctx.disposeEvents()` Manually finish the `ctx.events` bus, terminating any active iterators with `done: true`, and remove the constructor-registered abort listener so a long-lived `signal` reused across many ad-hoc contexts doesn't accumulate listeners. Idempotent. **Prefer signal-based auto-dispose** for ad-hoc contexts — `runtime.createContext({ signal })` auto-finishes the bus when the signal aborts, which composes naturally with `AbortSignal.timeout(...)`, user cancellation, and budget hard-stops. `disposeEvents()` is the explicit fallback for flows where you can't pin a signal — e.g., a one-shot context iterated from a script: ```typescript const ctx = runtime.createContext(); const observer = (async () => { for await (const e of ctx.events) console.log(e.type); })(); await ctx.ask(myAgent, 'hello'); ctx.disposeEvents(); // tell the observer to stop iterating await observer; ``` Workflow-driven contexts (`runtime.execute` / `runtime.stream`) terminate automatically — `emitEvent` finishes the bus on `workflow_end` / `error`. Don't need `disposeEvents()` there. --- ### `ctx.race(fns, options?)` Run multiple functions in parallel, return the first successful result. Remaining functions are cancelled. ```typescript const fastest = await ctx.race([ () => ctx.ask(fastAgent, question), () => ctx.ask(smartAgent, question), ], { schema: AnswerSchema }); ``` | Option | Type | Default | Description | |--------|------|---------|-------------| | `schema` | `ZodType` | — | Validate each result. Invalid results are discarded and the race continues until a valid result is produced | | `validate` | `OutputValidator` | — | Post-schema business rule validation. Results that fail are discarded like schema failures. Requires `schema` | **Returns:** `Promise` — the first valid result. --- ### `ctx.parallel(fns)` Run independent tasks concurrently. Unlike `race`, waits for all to complete. ```typescript const [users, orders] = await ctx.parallel([ () => ctx.ask(agentA, 'fetch users'), () => ctx.ask(agentB, 'fetch orders'), ]); ``` No options. Returns a tuple of results matching the input array. --- ### `ctx.map(items, fn, options?)` Map over an array with bounded concurrency. Like `Array.map()` but with parallel workers and optional quorum. ```typescript const results = await ctx.map(reviews, async (review) => { return await ctx.ask(analyst, review, { schema: SentimentScore }); }, { concurrency: 10, quorum: 150 }); ``` | Option | Type | Default | Description | |--------|------|---------|-------------| | `concurrency` | `number` | `5` | Maximum number of concurrent workers | | `quorum` | `number` | — | Resolve when this many items succeed. Remaining work is cancelled. Throws `QuorumNotMet` if not met | **Returns:** `Promise[]>` — results in the same order as `items`. Some may be `{ ok: false }` if they errored. --- ### `ctx.awaitHuman(options)` Suspend the workflow and wait for a human decision. The pending request is persisted to the state store and survives process restarts. Automatic resolution is reliable while the original process is alive; cross-process exactly-once decision replay is not yet provided (see Security > Approval Gates). ```typescript const decision = await ctx.awaitHuman({ channel: 'manager_approval', prompt: `Refund of $${amount} requires approval`, metadata: { orderId, amount }, }); if (decision.approved) { // proceed } else { console.log(`Denied: ${decision.reason}`); } ``` | Option | Type | Default | Description | |--------|------|---------|-------------| | `channel` | `string` | **required** | Channel name for routing decisions in your host app | | `prompt` | `string` | **required** | Human-readable description of what needs approval | | `metadata` | `Record` | — | Arbitrary data attached to the decision (e.g., order ID, amount) | **Returns:** `HumanDecision`: - `{ approved: true, data?: string }` — approved, with optional response data - `{ approved: false, reason?: string }` — denied, with optional reason Untyped input is validated at this boundary. `approved` must be an own boolean data property on a plain object; approval may carry only optional string `data`, and denial may carry only optional string `reason`. Arrays, accessors, truthy non-booleans, and contradictory branch fields fail with `AxlError` code `INVALID_HUMAN_DECISION` before the pending request is mutated. **Resolution:** The host app resolves decisions via `runtime.getPendingDecisions()` and `runtime.resolveDecision(executionId, decision)`. See [Security > Approval Gates](./security.md#approval-gates). **Cancellation:** If the execution is aborted while suspended at `awaitHuman` — via `runtime.abort(id)`, `runtime.deleteExecution(id)`, an external `options.signal`, or a budget hard-stop — the awaitHuman Promise rejects with `AbortError` and the workflow unwinds. The runtime cleans up its own bookkeeping (resolver map + persisted decision row) atomically as part of the delete sweep. --- ### `ctx.checkpoint(name, fn)` Persist a named result under the current execution ID and replay it when that same execution scope evaluates the checkpoint again. The legacy process-restart resume helper currently fails closed because the state-store contract has no complete cross-process decision, lease, or checkpoint-lineage protocol; do not rely on it for exactly-once side effects. ```typescript const value = await ctx.checkpoint('refund-customer', async () => expensiveOperation()); ``` | Param | Type | Description | |-------|------|-------------| | `name` | `string` | Stable, caller-supplied identifier. Must be the same across runs of the same execution for replay to work. Names starting with `__auto/` are reserved for runtime auto-checkpointing of `ctx.ask` / `spawn` / `race` / `parallel` / `map` and will throw | | `fn` | `() => Promise` | Function whose result is checkpointed | Names are scoped to a single execution and must be unique within it. Reusing a name (e.g. inside a loop) gives last-write-wins behavior — for loops, compose names from the iterator: `ctx.checkpoint(\`process-${id}\`, fn)`. **Why named?** Anonymous positional checkpoints (a counter that auto-increments per call) silently break when you add or remove `ctx.checkpoint` calls between deployments — every subsequent step shifts and in-flight executions read stale values from the wrong slot. Named checkpoints are immune to structural drift. Same model used by Temporal, Inngest, and Restate. Returns the result of `fn`. --- ### `ctx.remember(key, value, options?)` Store a value in working memory. ```typescript await ctx.remember('user_preference', { theme: 'dark' }, { scope: 'global', embed: true }); ``` | Option | Type | Default | Description | |--------|------|---------|-------------| | `scope` | `'session' \| 'global'` | `'session'` | `session`: scoped to the current session. `global`: accessible across all sessions | | `metadata` | `Record` | — | Arbitrary metadata stored alongside the value | | `embed` | `boolean` | `false` | When `true`, also generates an embedding for semantic search. Requires a vector store and embedder in the runtime config | **Cost tracking.** When `embed: true`, the embedder call cost is automatically attributed to the current execution scope — `runtime.trackExecution()` picks it up via the trace-event cost rail, and Studio's Cost Dashboard displays it under "Memory (Embedder)" bucketed by embedder model. See [observability.md](./observability.md#event-types) for details. **Budget enforcement.** Semantic memory calls (`embed: true` / `query`) count against `ctx.budget({ cost, onExceed: 'hard_stop' })` the same way agent calls do. `ctx.remember` and `ctx.recall` check `budgetContext.exceeded` at call top and throw `BudgetExceededError` before hitting the embedder if a prior call already breached the limit. The composed `AbortSignal` (user-abort + budget-hard_stop) is also forwarded to the embedder fetch so in-flight calls cancel promptly. **Audit events.** `ctx.remember`, `ctx.recall`, and `ctx.forget` emit a `memory_remember` / `memory_recall` / `memory_forget` event on both success and failure, with `{ key, scope, hit?, count?, embed?, usage?, error? }`. Values are never in the trace — only operation shape. Under `config.trace.redact`, `key` is scrubbed. --- ### `ctx.recall(key, options?)` Retrieve a value from memory by exact key, or perform semantic similarity search. ```typescript // Exact key lookup const pref = await ctx.recall('user_preference'); // Semantic search const related = await ctx.recall('preferences', { query: 'What color theme does the user like?', topK: 3, scope: 'global', }); ``` | Option | Type | Default | Description | |--------|------|---------|-------------| | `scope` | `'session' \| 'global'` | `'session'` | Memory scope to search | | `query` | `string` | — | When provided, performs semantic similarity search instead of exact key lookup. Requires a vector store and embedder | | `topK` | `number` | `5` | Number of results to return from semantic search | **Returns:** `unknown | null` for exact lookup, `VectorResult[]` for semantic search. **Cost tracking.** When `query` is provided, the embedder cost for the query embedding is attributed to the current execution scope (same rail as `ctx.remember({embed: true})`). --- ### `ctx.forget(key, options?)` Delete a memory entry. ```typescript await ctx.forget('user_preference', { scope: 'global' }); ``` | Option | Type | Default | Description | |--------|------|---------|-------------| | `scope` | `'session' \| 'global'` | `'session'` | Memory scope | --- ### Memory cost: `Embedder`, `EmbedResult`, `EmbedUsage` Embedders report cost through a structured return type so it flows through `runtime.trackExecution()` and Studio's cost aggregator the same way agent-call cost does. ```typescript interface Embedder { readonly dimensions: number; embed(texts: string[], signal?: AbortSignal): Promise; } type EmbedResult = { vectors: number[][]; usage?: EmbedUsage }; type EmbedUsage = { tokens?: number; cost?: number; model?: string }; ``` **Breaking change in 0.15.0:** `embed()` previously returned `Promise`. Custom `Embedder` implementations must wrap their vectors: ```typescript class MyEmbedder implements Embedder { readonly dimensions = 1536; async embed(texts: string[], signal?: AbortSignal): Promise { const vectors = await myEmbedCall(texts, { signal }); return { vectors }; // `usage` optional — omit if you don't compute cost } } ``` **`OpenAIEmbedder` pricing table:** | Model | Cost | |---|---| | `text-embedding-3-small` | $0.02 / 1M tokens | | `text-embedding-3-large` | $0.13 / 1M tokens | | `text-embedding-ada-002` | $0.10 / 1M tokens | Unknown models report `tokens` but no `cost`. The `signal` parameter is propagated through `fetchWithRetry` so budget hard-stops and user aborts cancel in-flight embedder calls mid-retry. **`MemoryManager` wrappers** (only relevant if you call `MemoryManager` directly — `ctx.remember`/`ctx.recall` hide these): ```typescript type RememberResult = { usage?: EmbedUsage }; type RecallResult = { data: unknown | VectorResult[] | null; usage?: EmbedUsage }; ``` --- ### `ctx.log(event, data?)` Emit a structured trace event. ```typescript ctx.log('custom_event', { userId: '123', action: 'checkout' }); ``` No options beyond the event name and optional data payload. --- ## Guardrails User-defined validation functions that run at the agent boundary, before and after each LLM call. ```typescript const safe = agent({ model: 'openai-responses:gpt-5.5', system: 'You are a helpful assistant.', guardrails: { input: async (prompt, ctx) => { if (containsPII(prompt)) return { block: true, reason: 'PII detected' }; return { block: false }; }, output: async (response, ctx) => { if (isOffTopic(response)) return { block: true, reason: 'Off-topic response' }; return { block: false }; }, onBlock: 'retry', maxRetries: 2, }, }); ``` ### `GuardrailsConfig` | Option | Type | Default | Description | |--------|------|---------|-------------| | `input` | `InputGuardrail` | — | Runs before each LLM call | | `output` | `OutputGuardrail` | — | Runs after each LLM response | | `onBlock` | `'retry' \| 'throw' \| GuardrailBlockHandler` | `'throw'` | What to do when a guardrail blocks. See policies below | | `maxRetries` | `number` | `2` | Maximum retries when `onBlock` is `'retry'` | ### `onBlock` Policies | Policy | Behavior | |--------|----------| | `'retry'` | Append the LLM's blocked output (as an assistant message) and the block reason (as a system correction prompt) to the conversation, then re-call the LLM so it can self-correct. Only applies to **output** guardrails — input guardrails always throw since the prompt is user-supplied | | `'throw'` | Throw a `GuardrailError` immediately | | `(reason, ctx) => string` | Custom function that receives the block reason and returns a fallback response (does not retry the LLM) | **Retry mechanics:** On each retry, the LLM's blocked response is appended to the conversation as an assistant message, followed by a system message: *"Your previous response was blocked by a safety guardrail: {reason}. Please provide a different response that complies with the guidelines."* These messages **accumulate** across retries — if the guardrail blocks twice, the LLM sees both failed attempts and both correction prompts before its third try, giving it increasing context about what to avoid. All retry messages are ephemeral — they exist only within the `ctx.ask()` call and are **not** persisted to session history. Only the final successful response is recorded in the session, so subsequent turns never see the blocked attempts. Schema retries and validate retries use the same accumulating pattern — see [Validate](#validate) and the [Output Pipeline](#output-pipeline) for the full flow. ### Callback Signatures ```typescript type InputGuardrail = ( prompt: string, ctx: { metadata: Record }, ) => GuardrailResult | Promise; type OutputGuardrail = ( response: string, ctx: { metadata: Record }, ) => GuardrailResult | Promise; type GuardrailResult = { block: boolean; reason?: string }; ``` --- ## Validate Post-schema business rule validation that receives the **parsed, typed object** — not the raw LLM string. Configured per-call on `AskOptions`, co-located with the `schema` it validates. Designed for domain-specific constraints that can't be expressed in a Zod schema (e.g., cross-field relationships, computed totals, referential integrity). ```typescript const result = await ctx.ask(agent, prompt, { schema: MySchema, validate: (data) => { if (!isValid(data)) return { valid: false, reason: 'explain what is wrong' }; return { valid: true }; }, }); ``` **Requires `schema`.** Without a schema, `validate` is silently skipped — use output guardrails for raw text validation instead. This enforces a clean separation: guardrails own content safety (raw text, per-agent), validate owns business rules (typed object, per-call). **Supported on:** `ctx.ask()`, `ctx.delegate()`, `ctx.race()`, and `ctx.verify()`. On delegate and handoffs, validate is forwarded to the final agent call. On race, results that fail validate are discarded (same as schema failures). ### Repairing output (vs. rejecting it) `validate` is a boolean gate — it rejects and retries, it doesn't repair. When output is *recoverable*, two mechanisms repair it in place, no new `ctx.ask` API needed: - **Pure, deterministic repair → put a `.transform()` in the schema.** `z.object({...}).transform(repair)` runs *inside* `schema.parse`, so the repaired value is what flows downstream — no extra LLM turn. The prompt is rendered from the transform's **input** side, so the model is told the pre-transform shape it must produce (not the computed fields the transform adds). See [In-schema repair with `.transform()`](use-cases.md#repair-in-place-with-transform-no-extra-llm-turn). - **LLM-in-the-loop / parse-failure repair → `ctx.verify`.** Wrap `ctx.ask` in `ctx.verify`; on retry, `retry.parsed` is the typed object ("safe to modify and return") for programmatic repair. See [LLM-first with repair fallback](use-cases.md#advanced-llm-first-with-programmatic-repair-fallback). See [Validated Data Extraction](use-cases.md#validated-data-extraction) for complete examples. ### `OutputValidator` ```typescript type OutputValidator = ( output: T, ctx: { metadata: Record }, ) => ValidateResult | Promise; // Note: uses `valid: true` = pass, unlike GuardrailResult which uses `block: true` = fail type ValidateResult = { valid: boolean; reason?: string }; ``` | AskOptions field | Type | Default | Description | |--------|------|---------|-------------| | `validate` | `OutputValidator` | — | Validation function. Receives the schema-parsed object. `T` is inferred from `schema` | | `validateRetries` | `number` | `2` | Maximum retries before throwing `ValidationError` | **Retry mechanics:** The LLM's failed response and the validation error are appended to the conversation history as assistant + system messages. Context **accumulates** across retries, so the LLM sees all previous failed attempts and can reason about what to fix. The validation `reason` is fed back in the system message: *"Your response parsed correctly but failed validation: {reason}."* If the validator throws an exception, it's treated as a validation failure — the error message is fed back and the retry counter is incremented. On retry, the new LLM response goes through the **full output pipeline** again (guardrail → schema → validate). See [Output Pipeline](#output-pipeline) below. ### Output Pipeline Every LLM response passes through three gates in order. Each gate has its own retry counter. On any failure, the loop restarts from the LLM call — the new response goes through **all gates** again: ``` LLM response (raw string) → Gate 1: Output guardrail (raw text — content safety) → Gate 2: Schema validation (JSON parse + Zod — structural correctness) → Gate 3: Validate (typed object — business rules) → Return result ``` | Gate | Receives | Configured by | Default retries | Error on exhaustion | |------|----------|---------------|-----------------|---------------------| | Output guardrail | Raw string | `AgentConfig.guardrails.maxRetries` | 2 | `GuardrailError` | | Schema validation | Raw string | `AskOptions.retries` | 3 | `VerifyError` | | Validate | Parsed object | `AskOptions.validateRetries` | 2 | `ValidationError` | Retry counts refer to **retries only** — the initial LLM call does not count. With the defaults (guardrail: 2, schema: 3, validate: 2), the worst case is `1 + 2 + 3 + 2 = 8` total LLM calls: 1 initial call plus up to 7 retries across all gates. Retries are **additive, not multiplicative** — each gate has its own counter that only increments when *that gate* fails. A response that passes gate 1 but fails gate 2 only increments the gate 2 counter. Counters are persistent across the entire `ctx.ask()` call and do not reset when a different gate fails. The `maxTurns` limit (default 25) provides a hard ceiling on total LLM calls regardless of gate failures. --- ## Structured Output Passing a `schema` to `ctx.ask()` (or `delegate`/`race`/`verify`) makes the reply a parsed, typed object instead of a string. Two things happen, and you control them independently: 1. **What the model is told** — the model-facing prompt (`schemaPrompt`). 2. **How the reply is enforced** — the Zod `schema` always runs as the parse gate (Gate 2 of the [Output Pipeline](#output-pipeline)), with self-correcting retries. ### Default: prompt-guided + client-side validation By default Axl appends a JSON-Schema description of your schema to the prompt and sends `responseFormat: { type: 'json_object' }` — the provider is told "reply with JSON," and your Zod schema is what actually enforces the shape (with retries). This is portable across every provider and degrades gracefully; it's the recommended path for anything non-trivial. Client-side Zod validation is the enforcement boundary in **every** mode below. > Native constrained decoding is **not** the default: it caps schema depth, degrades on complex schemas (large discriminated unions especially), and behaves differently per provider. Prompt-guided + Zod is predictable everywhere. See [providers.md](providers.md#structured-output-prompt-guided-default-vs-native). ### `schemaPrompt` — the model-facing rendering Controls only the prompt text; the `.parse` gate is unaffected. | `schemaPrompt` | Prompt behavior | Notes | |---|---|---| | `'json-schema'` **(default)** | Appends the compact, `$ref`-hoisted JSON Schema | Rendered from the schema's **input** side (`z.toJSONSchema(..., { io: 'input' })`), so a `.transform()` shows its pre-transform fields, not an empty `{}` | | `'none'` | Appends nothing | Schema is the parse gate only; pair with your own system-prompt guidance. Fires a `schema_prompt_none_no_guidance` [diagnostic](observability.md#schema-diagnostics) | | `{ render: string }` | Appends exactly that string | You own the guidance text | | `{ render: (schema) => string }` | Appends your function's output | Receives the Zod schema | The `'json-schema'` renderer also hoists sub-schemas shared across (e.g.) discriminated-union arms into `$defs`/`$ref` once and drops pretty-print whitespace — an order-of-magnitude token cut for large unions, with no code change ([prompt cost](observability.md#structured-output-prompt-cost)). ### `nativeStructuredOutput` — the provider's native path (default `false`) Set `true` to opt into the provider's native `json_schema` response format. Axl derives the provider schema from the **same** Zod schema (input side — no second, contradictable JSON Schema) and sends `responseFormat: { type: 'json_schema', json_schema: { name, schema } }`. Only takes effect when a `schema` is set and **no tools** are registered (JSON mode is disabled when tools are present). Providers can't all honor it. Each adapter reports a tier via the optional `Provider.nativeStructuredOutputSupport(model)`; when it isn't fully honored Axl emits a `native_output_unsupported` [diagnostic](observability.md#schema-diagnostics), **warns once, and proceeds** (the prompt text remains the parse contract): | Tier | Meaning | Examples | |---|---|---| | `schema` | Native `json_schema` accepted | OpenAI, OpenAI Responses, Mistral, OpenRouter, xAI, Groq `openai/gpt-oss-*` | | `downgraded` | Accepted but downgraded to `json_object` (shape not enforced) | DeepSeek, Groq `llama`/`gemma`/… | | `lossy` | Accepted but the schema is sanitized (keywords stripped) | Gemini | | `unsupported` | Ignored structurally; uses a system-prompt JSON instruction | Anthropic | > On OpenAI the `json_schema` is currently sent **non-strict** (schema-as-guidance, not hard constrained decoding). True strict mode needs an OpenAI-strict-subset transform and is a follow-up; client-side Zod is the guarantee. Full per-provider detail: [providers.md](providers.md#structured-output-prompt-guided-default-vs-native). ### Wire summary | Situation | `responseFormat` sent | |---|---| | `schema`, no tools, default | `{ type: 'json_object' }` | | `schema`, no tools, `nativeStructuredOutput: true` | `{ type: 'json_schema', json_schema: {…} }` | | `schema` **with tools** | none — JSON mode is gated off; the schema still parses client-side | ### Precedence & forwarding `schemaPrompt` and `nativeStructuredOutput` live on both `AskOptions` (per-call) and `AgentConfig` (agent default): **AskOptions > AgentConfig > default**. Both are forwarded through `ctx.delegate` to the terminal agent (single- and multi-candidate/handoff paths). ### Repairing recoverable output See [Repairing output](#repairing-output-vs-rejecting-it) — a `.transform()` in the schema (pure, no extra LLM turn) or `ctx.verify` (LLM-in-the-loop). Because the prompt renders the transform's input side, the model produces the raw shape and the transform derives the rest. ### Related diagnostics Silent structured-output cliffs surface as `schema_diagnostic` events — oversized appended/tool schema, dropped `.refine()`s, streaming disabled, zero-guidance `'none'`, and `native_output_unsupported`. See [observability.md#schema-diagnostics](observability.md#schema-diagnostics). --- ## Sessions Multi-turn conversation state that persists across HTTP requests. ```typescript const session = runtime.session('user-123', { history: { maxMessages: 100, summarize: true, summaryModel: 'openai-responses:gpt-5-mini', }, persist: true, }); const result = await session.send('HandleSupport', { msg: 'Help me' }); ``` ### `SessionOptions` | Option | Type | Default | Description | |--------|------|---------|-------------| | `history.maxMessages` | `number` | — | Keep the last N messages. Older messages are trimmed (or summarized if `summarize` is `true`) | | `history.summarize` | `boolean` | `false` | When `true` and `maxMessages` is exceeded, summarize old messages instead of dropping them | | `history.summaryModel` | `string` | — | Model URI for summarization (e.g., `'openai:gpt-4o-mini'`). **Required** when `summarize` is `true` | | `persist` | `boolean` | `true` | Save session history to the state store. When `false`, history exists only in memory for the session lifetime | ### Session Methods | Method | Description | |--------|-------------| | `session.send(workflow, input, { signal?, events? })` | Execute a workflow with session history. Returns the result. Serialized per `sessionId` (see [Concurrency](#concurrency-and-races)). Pass `signal` to cancel via `AbortSignal` — fires the same path as `runtime.abort(executionId)`. A pre-aborted signal short-circuits before acquiring the lock. `events` configures the iterator-queue cap and overflow policy on the underlying `ctx.events` bus (see [`EventStreamOptions`](#eventstreamoptions)) | | `session.stream(workflow, input, { signal?, events? })` | Execute a workflow with session history. Returns an `AxlStream`. Serialized per `sessionId` — the lock is held until the stream's terminal `done`/`error` event fires. `signal` aborts the stream and releases the lock. `events` configures the iterator-queue cap and overflow policy on both the returned `AxlStream` and the workflow's `ctx.events` bus | | `session.history()` | Get the last persisted message history snapshot from the store. Does **not** await in-flight `send()`/`stream()` — returns the previously committed state, which may be stale by one exchange | | `session.handoffs()` | Get the handoff history for this session. Same snapshot semantics as `history()` | | `session.end()` | Close the session and delete history from the store. Serialized: queues behind any in-flight `send`/`stream` so the delete is the final state | | `session.fork(newId, { overwrite? })` | Create a copy of this session with a new ID. Copies: history, `summaryCache`, `handoffHistory`, and session-scoped key-value memory entries (vector embeddings are NOT copied — re-embed on the fork if you need semantic recall). Acquires both source and target locks so it captures a committed snapshot and does not race a concurrent `runtime.session(newId).send(...)`. Throws if `newId === source id` or if the target id already has history (pass `{ overwrite: true }` to replace it) | ### What's stored A session's persisted state is a flat `ChatMessage[]` of `user` and `assistant` turns, keyed by `sessionId` in the configured `StateStore`. Summarization caches and handoff history are stored alongside as session metadata. The `Session` object itself holds no message cache — every `send()`/`stream()` reads history from the store, mutates it during execution, and writes it back. Calling `runtime.session(id)` does not pre-load anything and does not check whether the id exists. ### Sharing semantics History is **session-scoped, not agent-scoped or workflow-scoped**. Concretely: - **Across workflows.** `session.send('workflowA', ...)` followed by `session.send('workflowB', ...)` shares one history. Workflow B sees A's prior `user`/`assistant` turns as ordinary conversation; workflow names are not encoded in messages. - **Across agents within one workflow.** `ctx.ask(agentA)` and `ctx.ask(agentB)` in the same `WorkflowContext` share the same `sessionHistory` array. Agent B sees A's reply as a prior assistant turn. As of 0.17.4, every assistant message committed via `ctx.ask()` is stamped with `ChatMessage.agent` (the agent's `name`), so consumers and tooling can attribute history; the field is observability-only today and does not yet alter what is included in subsequent prompts. Per-agent filtering is on the roadmap. - **Child contexts (agent-as-tool).** `ctx.createChildContext()` deliberately starts with empty session history, so nested asks invoked from a tool handler do not pollute the parent conversation. - **Failed retries.** Schema/validate/guardrail retry attempts within a single `ctx.ask()` are stripped from the persisted history — only the final committed assistant message is recorded. If you want per-agent or per-workflow scoping, use distinct `sessionId`s. There is no built-in sub-scoping today. ### Turns vs. exchanges These are different concepts in axl: | Term | Meaning | |------|---------| | **Turn** | One iteration of the tool-call loop inside a single `ctx.ask()` — i.e., one provider HTTP call. Capped by `AgentConfig.maxTurns` (default 25). Schema/validate/guardrail retries each consume a turn. Stamped on `agent_call_start`/`agent_call_end` events as `turn: N` | | **Exchange** (or "round") | One user↔assistant round-trip at the session level — roughly one `session.send()` call. An exchange can internally invoke multiple `ctx.ask()` calls, each running its own turn loop | If you are coming from other LLM SDKs where "turn" means a conversational round-trip, mentally rename axl's `maxTurns` to "max provider calls per ask". ### Concurrency and races `Session.send()`, `stream()`, `end()`, and `fork()` are **serialized per session id within one runtime instance**. Concurrent calls on the same id queue FIFO behind the in-flight task; reads (`history()`, `handoffs()`) bypass the queue and return the last persisted snapshot. Mechanism: the runtime keeps a per-id `Promise` chain (`AxlRuntime._serializeSession`, internal). Two `runtime.session('x')` handles share the same lock — the lock lives on the runtime, not the `Session` instance. When a queue forms, the runtime emits a `'session_lock_contended'` event: ```typescript runtime.on('session_lock_contended', ({ sessionId }) => { console.warn(`[axl] session ${sessionId} has contention`); }); ``` Useful when you suspect a session is slow because of queueing (rather than the LLM itself). #### Runtime events The `AxlRuntime` extends `EventEmitter`. Subscribe to lifecycle signals: | Event | Payload | Description | |---|---|---| | `'trace'` | `AxlEvent` | Fires for every event emitted by every `execute()` / `stream()` / `createContext()` call. The cross-execution observability firehose | | `'eval_result'` | `EvalHistoryEntry` | Fires when `saveEvalResult` lands (used by Studio's eval-trends aggregator; available to any consumer) | | `'execution_deleted'` | `{ executionId, workflow, wasActive, hadPendingDecision, removed }` | Audit signal for `runtime.deleteExecution(id)`. Fires on every call including attempts against unknown ids (`removed: false`, `workflow: undefined`). The `workflow` field is captured BEFORE the delete so compliance pipelines can categorize by workflow without a follow-up lookup. Synchronous — listeners run before `deleteExecution` returns; throwing listeners surface to the caller. Studio's aggregators subscribe to this and rebuild on every delete | | `'eval_deleted'` | `{ id, eval, removed }` | Symmetric audit signal for `runtime.deleteEvalResult(id)`. Fires on every call; `eval` captured before delete. Studio's `EvalAggregator` subscribes and rebuilds eval-trends snapshots on delete | | `'session_lock_contended'` | `{ sessionId }` | Fires when a `Session.send` / `stream` / `end` / `fork` queues behind an in-flight task on the same id | > **⚠️ Cross-process locking is NOT provided.** The lock is in-process — multiple Node workers (e.g., a horizontally-scaled web app) all hitting the same Redis-backed `sessionId` will still race. Production deployments behind a load balancer must either: > > - **Pin sessions to workers** (sticky routing on `sessionId`), so all writes for a given session go through the same process, or > - **Use distinct `sessionId`s per request** if cross-request continuity isn't required. > > A future release may offer optimistic concurrency on the StateStore — in the meantime, treat session ids as single-writer. **Lifecycle ordering.** `end()` sets a per-instance `closed` flag synchronously, then queues the delete behind the lock. After `await session.end()` resolves, no further calls on that `Session` instance succeed (`closed` short-circuits at the top of `send`/`stream`). However, `closed` is per-instance — a *different* `Session` object on the same id (e.g., from a fresh `runtime.session(id)` call elsewhere) is unaffected. If you need a global "this id is dead" signal, coordinate it at the application layer. ### Summarization Two independent summarization paths exist: - **Session-level** (controlled here via `history.maxMessages` + `history.summarize`). Triggers when persisted history exceeds `maxMessages`. Drops the oldest excess messages, summarizes them with `summaryModel`, and stores the rolling summary as session metadata so it carries across `send()` calls. - **Ask-level** (controlled by `AgentConfig.maxContext`). Triggers inside `ctx.ask()` when the prompt + history would exceed the agent's configured context window. Independent of `SessionOptions`. Both can fire in the same `send()`. --- ## AxlStream Returned from `runtime.stream()` and `session.stream()`. An `AsyncIterable` (the wire format **is** the trace format — same shape, full fidelity, no translation layer). Also exposes accessors for filtered views. ```typescript import type { AxlEvent } from '@axlsdk/axl'; const stream = runtime.stream('MyWorkflow', input); for await (const event of stream) { if (event.type === 'token') process.stdout.write(event.data); if (event.type === 'tool_call_end' && event.data.outcome.status === 'succeeded') { console.log('tool result:', event.tool, event.data.outcome.result); } if (event.type === 'error') console.error('error:', event.data.message); if (event.type === 'done') console.log('result:', event.data.result); } ``` | Accessor | Type | Description | |---|---|---| | `for await ... of stream` | `AsyncIterable` | Every `AxlEvent`, in the order emitted | | `stream.lifecycle` | `AsyncIterable` | Structural events only — `ask_*`, `agent_call_*`, `tool_call_*` (including `tool_call_rejected`), `tool_approval`, `handoff_start`, `handoff_return`, `delegate`, `pipeline`, `verify`, `workflow_*`, `checkpoint_save`, `checkpoint_replay`, `await_human`, `await_human_resolved`. Skips token chatter | | `stream.text` | `AsyncIterable` | Root-only token stream (`depth === 0`). Nested-ask tokens (agent-as-tool handlers, `delegate`, `race` branches) are omitted — use `stream.textByAsk` or filter the raw stream on `event.depth >= 1` to see them | | `stream.textByAsk` | `AsyncIterable<{ askId, agent?, text }>` | **Every** token tagged with the producing ask frame. Complements `.text` — use for split-pane UIs that render each sub-agent's output in its own lane, grouped by `askId` | | `stream.partialObjects` | `AsyncIterable` (`{ askId, agent?, object, attempt }`) | **Coalescing view** — yields the latest `partial_object` payload per `askId`. `attempt` is the 1-indexed attempt number; the view drops pending snapshots on `pipeline(failed)` so attempt-N values never leak after a schema/validate/guardrail retry begins. Listener-based: does NOT race with the main iterator. Memory bounded by `O(active asks)`, not `O(events)`. The right shape for streaming-structured-output UIs | | `stream.stringStream(opts?)` | `AsyncIterable` (`{ askId, agent?, path, delta, accumulated, attempt }`) | **Streaming view** over `string_delta` events with optional `{ path?, askId? }` filters. `delta` is every new char since that subscriber's previous yield (several source chunks may coalesce); `accumulated` is canonical text-so-far. Late subscribers seed through the configured bounded queue. Listener-based: does NOT race with the main iterator. Per-ask state clears on `pipeline(failed)` and `ask_end` | | `stream.fullText` | `string` | Accumulated text from root-only tokens, committed on `pipeline(committed)`. Retried-attempt tokens are discarded on `pipeline(failed)` or `ask_end({ok:false})` so only the winning attempt's text appears | | `stream.promise` | `Promise` | Resolves with the workflow result; rejects with the thrown error. Errors are ALSO delivered via the iterator and `.on('error', ...)` (as a synthesized `AxlEvent{type:'error'}`). The promise has an internal no-op `.catch(() => {})` so consumers who only read the iterator never see unhandled-rejection warnings | | `stream.on('done', ...)` / `.on('error', ...)` | `EventEmitter` | Terminal events. `done.data = { result }`, `error.data = { message, name?, code? }` | **Renamed in 0.16.0:** `stream.steps` → `stream.lifecycle`. The old `StreamEvent` union (`tool_result`, `agent_start`, `agent_end`, `step`) is gone — use the unified `AxlEvent` variants (`tool_call_end`, `agent_call_start`, `agent_call_end`, etc.) directly. --- ## AxlRuntime The central orchestrator. Manages workflow registration, provider resolution, state storage, execution lifecycle, and eval history. ```typescript import { AxlRuntime } from '@axlsdk/axl'; const runtime = new AxlRuntime({ state: { store: 'sqlite', sqlite: { path: './data/axl.db' } }, }); ``` ### Registration | Method | Description | |--------|-------------| | `register(workflow)` | Register a workflow | | `registerTool(...tools)` | Register one or more standalone tools | | `registerAgent(...agents)` | Register one or more standalone agents | | `registerProvider(name, provider)` | Register a custom provider instance | | `registerEval(name, config, executeWorkflow?)` | Register an eval configuration | ### Execution | Method | Returns | Description | |--------|---------|-------------| | `execute(name, input, options?)` | `Promise` | Execute a workflow and return the full result. Tracks execution lifecycle (status, duration, cost, traces) | | `stream(name, input, options?)` | `AxlStream` | Execute a workflow and return a stream of events. Same lifecycle tracking as `execute()` | | `session(id, options?)` | `Session` | Create or resume a multi-turn session (see [Sessions](#sessions)) | | `abort(executionId)` | `void` | Abort a running execution by ID | | `resumeExecution(executionId)` | `Promise` | Reserved legacy entry point. Currently fails closed with `CROSS_PROCESS_RESUME_UNSUPPORTED` because the state-store contract cannot replay a decision exactly once | | `resumePending()` | `Promise` | Audits pending execution-state rows through the fail-closed resume entry point and emits `resume_failed`; it does not re-execute them | | `getPendingDecisions()` | `Promise` | List all pending human decisions | | `resolveDecision(executionId, decision)` | `Promise` | Resolve a pending human decision in the owning runtime. A persisted request with no in-process resolver fails with `CROSS_PROCESS_RESUME_UNSUPPORTED` before mutation; see Security > Approval Gates | `ExecuteOptions` (accepted by both `execute()` and `stream()`; exported from `@axlsdk/axl`): | Option | Type | Default | Description | |--------|------|---------|-------------| | `metadata` | `Record` | `{}` | Metadata passed to the workflow context. Reserved keys: `sessionId`, `sessionHistory`, `resumeMode` | | `awaitHumanHandler` | `(options) => Promise` | — | In-process approval handler for tool calls with `requireApproval`. Parity with `CreateContextOptions.awaitHumanHandler` — lets tests and embedded use cases resolve approvals inline instead of suspending execution and polling `getPendingDecisions()` | | `signal` | `AbortSignal` | — | External abort signal. Cancels the workflow exactly as `runtime.abort(executionId)` would. Lets callers use the standard JS pattern without having to track the execution id | | `events` | `EventStreamOptions` | `{ maxQueued: 10_000, onOverflow: 'drop-oldest-non-terminal' }` | Configures the iterator-queue cap and overflow policy on `ctx.events` (and on the `AxlStream` returned by `runtime.stream()`). See [`EventStreamOptions`](#eventstreamoptions) | > **No observation callbacks here or on `runtime.createContext()`.** > `runtime.execute()` is final-result-only by design. To observe tokens, tool > calls, or any other event from inside the workflow handler, read `ctx.events` > (see [`ctx.events`](#ctxevents)). To observe from outside, use > `runtime.stream()` and consume the returned `AxlStream`, or use the runtime > trace listener for cross-execution observation. ### Execution History Completed and failed executions are automatically persisted to the state store (when the store implements `saveExecution`). Historical executions are lazy-loaded on first access. | Method | Returns | Description | |--------|---------|-------------| | `getExecutions()` | `Promise` | All executions (active + historical), sorted by `startedAt` descending. New/live entries are v2; stored v1 entries remain explicitly typed as legacy | | `getExecution(id)` | `Promise` | Look up a specific execution. Checks in-memory first, then falls through to the state store | | `deleteExecution(id)` | `Promise` | Remove an execution from in-memory caches and the state store. Returns `true` if anything was removed. Used for GDPR right-to-be-forgotten and operator cleanup. Sweeps every per-execution surface: data blob + indexes, checkpoints, suspended-state, streaming buffer, pending awaitHuman decision, in-memory resolver map. If the execution is still running, auto-aborts the workflow (which now correctly wakes a paused `ctx.awaitHuman()`) AND marks the id for skip-on-persist so the row can't resurrect after the operator-initiated delete. Emits `execution_deleted` on the runtime's `EventEmitter` (audit trail). Studio's `DELETE /api/executions/:id` route additionally scrubs the WS replay buffer for the deleted execution channel | | `recoverIncompleteStreams()` | `Promise` | Synthesize partial execution records for executions whose process died while `state.persist: 'streaming'` was configured. The recovered record keeps the streaming buffer's event schema version and never invents missing tool terminals. Reads from `StateStore.listStreamingExecutions` + `getStreamingEvents`, synthesizes with `status: 'failed'` and `error: 'process terminated'`, persists via `saveExecution`, and finalizes the streaming buffer. Skips ids of executions actively running in the current process, bounds `events` to `state.maxEventsPerExecution`, and preserves the buffer on save failure. Idempotent; run after lazy-loading history and before accepting work. | `ExecutionInfo`: | Field | Type | Description | |-------|------|-------------| | `executionId` | `string` | Unique execution ID | | `workflow` | `string` | Workflow name | | `status` | `'running' \| 'completed' \| 'failed' \| 'waiting'` | Current status | | `eventSchemaVersion` | `2` | Required on live/current `ExecutionInfo`; selects the v2 event reducer without scanning `events` | | `events` | `AxlEvent[]` | All events for this execution. Renamed from `steps` in 0.16.0; `SQLiteStore` auto-migrates the `execution_history.steps` column to `events` on first open | | `totalCost` | `number` | Accumulated cost in USD. A **lower bound** when `unpriced` is `true` | | `unpriced` | `boolean \| undefined` | `true` when any cost-bearing call in the execution did billable work but had no usable cost (unpriced model / pricing-table miss) — `totalCost` is then a lower bound. `false` when every call was priced. The aggregate counterpart of `ask_end.unpriced` / `BudgetResult.unpriced` — read this instead of scanning `events`. `undefined` only on executions recorded before this field existed | | `startedAt` | `number` | Start timestamp (ms) | | `completedAt` | `number \| undefined` | Completion timestamp (ms) | | `duration` | `number` | Duration in ms | | `result` | `unknown \| undefined` | Workflow return value (when `status === 'completed'`) | | `error` | `string \| undefined` | Error message (when `status === 'failed'`) | | `metadata` | `Record \| undefined` | Caller-supplied metadata lifted from `ExecuteOptions.metadata` (or `runtime.stream()`'s `options.metadata`). Stable, queryable surface for tags like `userId`, `tenantId`, or correlation ids — filter via `runtime.getExecutions()` + an in-process `.filter()`. Persisted by all three built-in stores (`MemoryStore`/`SQLiteStore`/`RedisStore`); `SQLiteStore` adds a `metadata` column in schema v3 (auto-migrated on first open). The internal control-plane keys `sessionHistory`, `sessionId`, and `resumeMode` are stripped before persistence — they remain readable on `ctx.metadata` for dynamic selectors but don't bloat the queryable surface. The snapshot is `structuredClone`'d so caller mutations to the original `options.metadata` after `execute()`/`stream()` returns don't surface mid-run. Scrubbed to `{ redacted: true }` by Studio's REST endpoints when `config.trace.redact: true`. Secondary indexes are intentionally not provided — `StateStore` is a persistence boundary, not a query engine | History readers return `HistoricalExecutionInfo = LegacyExecutionInfoV1 | ExecutionInfoV2`. Missing `eventSchemaVersion` is the v1 sentinel. New writers emit only v2; built-in stores preserve v1 payloads and do not infer v2 tool outcomes from legacy event shapes. Narrow on `eventSchemaVersion === 2` before using `AxlEventV2`-only fields such as `tool_call_end.data.outcome`. ### Eval History Eval results are automatically persisted when using `runRegisteredEval()`. Historical results are lazy-loaded on first access. | Method | Returns | Description | |--------|---------|-------------| | `runRegisteredEval(name, options?)` | `Promise` | Run a registered eval by name. Automatically persists the result to eval history. `options` accepts `{ metadata?, onProgress?, signal?, captureTraces? }` — `metadata: Record` injects custom metadata, `onProgress: (event: EvalProgressEventShape) => void` fires on `item_done` and `run_done` progress events, `signal: AbortSignal` cancels remaining items, `captureTraces: boolean` populates per-item `EvalItem.traces` on success and failure paths (forwarded to `runEval`) | | `getEvalHistory()` | `Promise` | All eval results, most recent first. Merges in-memory results with historical data from the state store | | `saveEvalResult(entry)` | `Promise` | Manually save an eval result to history. Persists to the in-memory cache + `StateStore` and emits an `eval_result` event on the runtime's `EventEmitter` (load-bearing for Studio's live eval-trends aggregation — any custom consumer wanting live eval updates can subscribe via `runtime.on('eval_result', ...)`) | | `deleteEvalResult(id)` | `Promise` | Remove a single eval history entry. Mutates the in-memory cache and delegates to `StateStore.deleteEvalResult?`. Returns `true` if the id existed | | `eval(config, options?)` | `Promise` | Run an ad-hoc eval (not registered). Does **not** auto-persist to history. `options` accepts the same `{ onProgress?, signal?, captureTraces? }` as `runRegisteredEval` | | `evalCompare(baseline, candidate)` | `Promise` | Compare two eval results for regressions/improvements | `EvalHistoryEntry`: | Field | Type | Description | |-------|------|-------------| | `id` | `string` | Unique result ID | | `eval` | `string` | Eval name | | `timestamp` | `number` | When the eval was run (ms) | | `data` | `unknown` | Full `EvalResult` object from `@axlsdk/eval` | ### Introspection | Method | Returns | Description | |--------|---------|-------------| | `getWorkflows()` | `Workflow[]` | All registered workflows | | `getWorkflow(name)` | `Workflow \| undefined` | Look up a workflow by name | | `getWorkflowNames()` | `string[]` | All registered workflow names | | `getAgents()` | `Agent[]` | All registered agents | | `getAgent(name)` | `Agent \| undefined` | Look up an agent by name | | `getTools()` | `Tool[]` | All registered tools | | `getTool(name)` | `Tool \| undefined` | Look up a tool by name | | `getRegisteredEvals()` | `Array<{ name, workflow, dataset, scorers }>` | All registered eval configs | | `getRegisteredEval(name)` | `{ config, executeWorkflow? } \| undefined` | Look up a specific eval registration | | `resolveProvider(uri)` | `{ provider, model }` | Resolve a `provider:model` URI to a Provider instance and stripped model name | | `getStateStore()` | `StateStore` | The runtime's state store instance | | `getMcpManager()` | `McpManager \| undefined` | The runtime's MCP manager (if initialized) | | `isRedactEnabled()` | `boolean` | Narrow public getter for `config.trace.redact`. Use this instead of reaching into the config object — the full config was intentionally not exposed because `Readonly` is shallow and consumers could mutate nested fields. Used by Studio's REST routes and WS broadcast paths to decide whether to scrub user/LLM content at the observability boundary | ### Lifecycle | Method | Returns | Description | |--------|---------|-------------| | `initializeTelemetry()` | `Promise` | Enable OpenTelemetry span emission. Call before executing workflows | | `initializeMcp()` | `Promise` | Connect to configured MCP servers | | `shutdown()` | `Promise` | Abort all in-flight executions, close MCP connections, memory manager, state store, and span manager | ### Ad-hoc Context and Cost Tracking See [`runtime.createContext()`](#runtimecreatecontextoptions) and [`runtime.trackCost()`](#runtimetrackcostfn) above. --- ## StateStore Pluggable persistence interface. Built-in implementations: `MemoryStore` (in-memory, for development), `SQLiteStore` (file-based, for single-process production), `RedisStore` (distributed, for multi-process production). ```typescript import { AxlRuntime, SQLiteStore, RedisStore } from '@axlsdk/axl'; // String shortcut const runtime = new AxlRuntime({ state: { store: 'sqlite' } }); // Instance for full control const runtime2 = new AxlRuntime({ state: { store: await RedisStore.create('redis://localhost:6379') }, }); // RedisStore with a custom key prefix (e.g. for shared-cluster deployments) const runtime3 = new AxlRuntime({ state: { store: await RedisStore.create({ url: 'redis://localhost:6379', keyPrefix: 'axl:prod:', }), }, }); ``` ### RedisStore options `RedisStore.create()` accepts either a URL string (back-compat) or an options object: | Field | Type | Default | Description | |-------|------|---------|-------------| | `url` | `string?` | `'redis://localhost:6379'` | Redis connection URL | | `keyPrefix` | `string?` | `'axl:'` | Prepended to every key written by this store. Concatenated as-given — no normalization (include the trailing colon if you want one). Empty string is rejected. Useful when two Axl deployments share a Redis cluster, or when coexisting with other applications' keys | | `skipMigration` | `boolean?` | `false` | Skip the one-time lazy backfill of the execution / eval-history sorted-set indexes on startup. Set to `true` for installs at six-figure execution counts where the startup cost is unacceptable, then call `store.backfillExecutionIndex()` / `store.backfillEvalIndex()` manually during a maintenance window. Until then, `listExecutions` / `listEvalResults` fall back to the legacy SET + N×GET + JS-sort read path — correct but slow at scale | | `defaultTtl` | `number?` | — | Default TTL in **seconds** applied to every TTL-capable storage category. Without a TTL, every `save*` accumulates forever — strongly recommended in production | | `ttls` | `object?` | — | Per-category TTL overrides in seconds (`session`, `sessionMeta`, `checkpoint`, `executionState`, `executionHistory`, `evalHistory`, `memory`, `streamingEvents`). Set a category to `null` to explicitly opt out even when `defaultTtl` is set. `pendingDecision` is intentionally NOT configurable — pending decisions share a hash, so a TTL would expire all of them at once. **Window semantics:** `memory`, `session`, and `sessionMeta` are sliding (every write refreshes TTL — active users keep their data, inactive users forget; reads do NOT refresh); `checkpoint` and `streamingEvents` are fixed-creation (TTL set on first write only); `executionState` / `executionHistory` / `evalHistory` are fixed-refresh (TTL via `SET ... EX`). **`streamingEvents` is opt-in only** — does NOT fall back to `defaultTtl`. Must be longer than your max time-between-restarts or `recoverIncompleteStreams()` will miss crashed-run buffers that aged out before the next process started. Non-positive and non-finite values (`0`, negative, `NaN`, `Infinity`) are defensively treated as no-TTL. Per-category TTLs are independent. Legacy memory entries (pre-`memory-methods` patch) migrate forward on first read with the configured TTL applied. `listPendingExecutions` self-prunes stale ids when their `executionState` blob has TTL-evicted | ### Provider configuration `config.providers.` (`ProviderConfig`) accepts: | Field | Type | Default | Description | |-------|------|---------|-------------| | `apiKey` | `string \| (() => string \| Promise)` | env var | API key, or a function (`ApiKeySource`) resolved **per request** for expiring credentials (Azure-Entra, Bedrock short-term, Databricks/IBM OAuth) — your callback owns refresh/caching. Falls back to the provider's env var (e.g. `OPENAI_API_KEY`) | | `baseUrl` | `string` | provider default | Override the API base URL (proxies, gateways) | | `authHeader` | `AuthHeader` | profile default | OpenAI-compatible presets only: override the profile auth header shape. Use `providers.azure.authHeader: 'bearer'` with an Entra token callback; the Azure preset defaults to `'api-key'` for API-key auth | | `rateLimit` | `RateLimitConfig` | — | Opt-in client-side rate governor for this provider's chat calls. See below. `openai-responses` inherits the `openai` block (incl. `rateLimit`) when it has no config of its own — but as a **separate governor instance**, not a shared counter (using both adapters ⇒ effective concurrency is the sum) | **`RateLimitConfig`** — proactive pacing through the shared `fetchWithRetry` chokepoint (complementary to the automatic 429/503/529 backoff). Exported from `@axlsdk/axl` alongside the `RateLimiter` class. | Field | Type | Description | |-------|------|-------------| | `maxConcurrent` | `number` | Max requests in flight for this provider. Finite integer ≥ 1; invalid values disable the cap (with a `console.warn`). `1` serializes (a throughput floor, not a deadlock — permits aren't held across a nested `ctx.ask()`) | | `minIntervalMs` | `number` | Minimum ms between successive request *grants* (global spacing, no burst bucket) | | `acquireTimeoutMs` | `number` | If set, a call queued longer than this rejects (fail loud) instead of hanging on a misconfigured cap | > **Scope:** caps request *concurrency*, not token throughput (TPM) — a permit releases at response headers. Governs **chat calls only** (memory embedder calls are not governed in this version) and is **per provider instance / process** (not shared across processes on the same key). Full caveats in [providers.md → Rate limiting](providers.md#rate-limiting-opt-in). ### Provider profiles The generic `OpenAICompatibleProvider` is parameterized by a `ProviderProfile`. Built-in presets (OpenRouter, Azure, xAI, DeepSeek, Mistral, Groq, Bedrock, ollama/vllm/lmstudio/llamacpp/sglang) are profiles; build your own by cloning one. Guide: [providers.md → presets](providers.md#openai-compatible-providers--presets). **`ProviderProfile`** | Field | Type | Default | Description | |-------|------|---------|-------------| | `name` | `string` | — | Machine name = `Provider.name` and the `provider:` URI key | | `label` | `string` | `name` | Human label used in error messages | | `defaultBaseUrl` | `string` | — | Base URL when neither config `baseUrl` nor `envBaseUrl` is set | | `envBaseUrl` | `string` | — | Env var consulted for the base URL | | `envApiKey` | `string` | — | Env var consulted for the API key | | `authHeader` | `AuthHeader` | `'bearer'` | `'bearer'` (`Authorization: Bearer`), `'api-key'` (Azure), or `{ header, scheme? }` | | `headers` | `Record` | — | Static headers merged into every request | | `allowMissingApiKey` | `boolean` | `false` | Allow an empty key (local servers) → no auth header sent | | `pricing` | `PricingSource` | — | How per-call cost is derived | | `reasoning` | `ReasoningProfile` | — | Effort emission + reasoning capture/round-trip | | `capabilities` | `CapabilityFlags` | — | Wire-quirk flags | | `roleFor` | `(role, model) => string` | identity | Map a message role to the wire role (OpenAI: `system`→`developer` on o-series) | | `maxTokensField` | `'max_completion_tokens' \| 'max_tokens'` | `'max_completion_tokens'` | Output-token field name | | `parallelToolCalls` | `PerModel` | off | Send `parallel_tool_calls: true` when tools are present | | `requestDefaults` | `Record` | — | Static body fields merged before `providerOptions` | **`PricingSource`** — `{ kind: 'table'; table: PricingTable }` · `{ kind: 'from-response' }` (provider returns `usage.cost`) · `{ kind: 'zero' }` (local) · `{ kind: 'unknown' }`. A `'table'` miss yields `cost: undefined`, never `0`. **`ReasoningProfile`** — `{ emit: ReasoningEmit; capture: ReasoningCapture; roundTrip?: ReasoningRoundTrip }`. - `capture`: `'none'` · `'reasoning_content'` · `'reasoning'` · `'reasoning_details'` · `'think_tags'` (inline ``). - `roundTrip`: `'none'` (default) · `'on-tool-call-turns'` (echo captured reasoning only on assistant turns that carried `tool_calls`). - Helpers: `reasoningEffortEmit(map)` writes top-level `reasoning_effort`; `reasoningObjectEmit(mapEffort)` writes OpenRouter's `reasoning` object (effort XOR `max_tokens`). **`CapabilityFlags`** — `emitsMessageName?` (default `true`) · `forbiddenParams?: PerModel` (strip engine-computed values, preserve user `providerOptions`) · `supportsJsonSchema?: PerModel` (default `true`; falls back to `json_object`) · `supportsStreamUsage?` (default `true`). **`PerModel`** = `T | ((model: string) => T)` — a value, or a function resolved per call against the model id (for providers whose constraints differ by model). ### State configuration `config.state` accepts the following options: | Field | Type | Default | Description | |-------|------|---------|-------------| | `store` | `'memory' \| 'sqlite' \| StateStore` | `'memory'` | Backend implementation. Pass an instance for `RedisStore` (use `await RedisStore.create(url)`) or a custom store | | `sqlite` | `{ path: string }` | — | Path for the `'sqlite'` store. Required when `store === 'sqlite'` | | `maxEventsPerExecution` | `number` | `50_000` | Maximum number of events retained in `ExecutionInfo.events` per execution. When the cap is hit, subsequent events are dropped from the array (with a sentinel `log` event recording the truncation) — but the trace channel (`runtime.on('trace')`) and WS broadcast continue to receive every event, so live observability isn't degraded. Must be a positive integer or `Infinity` (explicit unbounded opt-out — only safe for short-lived executions). Pathological values (`0`, negative, fractional, `NaN`) are rejected at construction with a `RangeError` | | `persist` | `'terminal' \| 'streaming'` | `'terminal'` | When to write events to the state store. `'terminal'` (default, back-compat): events buffered in memory, written at the terminal `done`/`error` event. Fastest path; if the process crashes mid-run, events are lost. `'streaming'`: events batched and written throughout the run via `StateStore.appendStreamingEvents`; on a process crash, call `runtime.recoverIncompleteStreams()` from the next process to reconstruct a partial `ExecutionInfo` from the surviving buffer. Excluded from streaming flush: `token`, `partial_object`, `string_delta` (high-volume stream-only, reconstructable from persisted `agent_call_end.data`) | | `streamingBatchSize` | `number` | `100` | Number of events buffered before flushing to the streaming store. Set to `1` for per-event flush (highest durability, one Redis round-trip per emit — adds latency proportional to RTT). Only meaningful when `persist === 'streaming'` | | `streamingBatchInterval` | `number` | `1000` | Max milliseconds between flushes when the batch hasn't filled up. With `streamingBatchSize`, bounds the "events lost on crash" window. Only meaningful when `persist === 'streaming'` | ### Required Methods Every `StateStore` implementation must provide these methods. **Checkpoints** (for `ctx.checkpoint()` / suspend-resume): | Method | Description | |--------|-------------| | `saveCheckpoint(executionId, name, data)` | Save a checkpoint under a caller-supplied stable name | | `getCheckpoint(executionId, name)` | Look up a specific checkpoint by name (returns `null` if missing) | **Sessions**: | Method | Description | |--------|-------------| | `saveSession(sessionId, history)` | Save session message history | | `getSession(sessionId)` | Get session message history (returns `[]` if not found) | | `deleteSession(sessionId)` | Delete a session and its metadata | | `saveSessionMeta(sessionId, key, value)` | Save session metadata (e.g., context summaries) | | `getSessionMeta(sessionId, key)` | Get session metadata | **Human-in-the-loop decisions**: | Method | Description | |--------|-------------| | `savePendingDecision(executionId, decision)` | Persist a pending human decision | | `getPendingDecisions()` | List all pending decisions | | `resolveDecision(executionId, result)` | Resolve a pending decision | **Execution state** (for suspend/resume): | Method | Description | |--------|-------------| | `saveExecutionState(executionId, state)` | Save execution state for resume | | `getExecutionState(executionId)` | Get execution state | | `listPendingExecutions()` | List execution IDs with status `'waiting'` | ### Optional Methods These methods are optional (`?` on the interface). The runtime checks for their existence before calling. All three built-in stores implement all optional methods. **Memory** (for `ctx.remember()` / `ctx.recall()` / `ctx.forget()`): | Method | Description | |--------|-------------| | `saveMemory?(scope, key, value)` | Save a memory entry | | `getMemory?(scope, key)` | Get a memory entry | | `getAllMemory?(scope)` | Get all entries for a scope | | `deleteMemory?(scope, key)` | Delete a memory entry | **Execution history** (for `runtime.getExecutions()`): | Method | Description | |--------|-------------| | `saveExecution?(execution)` | Save a completed/failed `ExecutionInfo` to history | | `getExecution?(executionId)` | Get a specific execution from history | | `listExecutions?(limit?)` | List recent executions, most recent first. Pass `undefined` for no limit | | `deleteExecution?(executionId)` | Delete an execution from history. Returns `true` if an entry was removed. Symmetric to `deleteEvalResult` | | `appendStreamingEvents?(executionId, events)` | Append a batch of events to the streaming buffer. Called by the runtime when `state.persist: 'streaming'` is configured. Should register the executionId in an in-flight index on first call | | `finalizeStreamingEvents?(executionId)` | Delete the streaming buffer + un-register from the in-flight index. Called by the runtime after the canonical `executionHistory` blob has been written | | `listStreamingExecutions?()` | List execution IDs that have a streaming buffer but no corresponding completed `executionHistory`. Used by `runtime.recoverIncompleteStreams()` | | `getStreamingEvents?(executionId)` | Read the events accumulated in the streaming buffer for an execution. Returns `[]` if no buffer exists | **Eval history** (for `runtime.getEvalHistory()`): | Method | Description | |--------|-------------| | `saveEvalResult?(entry)` | Save an `EvalHistoryEntry` to history | | `listEvalResults?(limit?)` | List eval results, most recent first. Pass `undefined` for no limit | **Introspection and lifecycle**: | Method | Description | |--------|-------------| | `listSessions?()` | List all session IDs (used by Studio's session browser) | | `close?()` | Close the underlying connection (called by `runtime.shutdown()`) | | `deleteCheckpoints?(executionId)` | Delete all checkpoints for an execution (called on successful completion) | ### Implementing a Custom StateStore Implement the required methods. Optional methods are only called if they exist on the object — omitting them is safe. ```typescript import type { StateStore } from '@axlsdk/axl'; class MyStore implements StateStore { // Required: implement all checkpoint, session, decision, and execution state methods // Optional: implement saveExecution/listExecutions for execution history, // saveEvalResult/listEvalResults for eval history, etc. } const runtime = new AxlRuntime({ state: { store: new MyStore() } }); ``` --- ## AxlEvent Every agent call, tool invocation, handoff, and system event emits an `AxlEvent`. `AxlEvent` is the live v2 contract and always carries `schemaVersion: 2`. These events accumulate in `ExecutionInfo.events` and are broadcast via WebSocket in Studio. The wire format (streaming) and trace format (persisted) are the same shape — no translation layer. Stored readers use `HistoricalAxlEvent` for the v1/v2 union. ```typescript import type { AxlEvent, AxlEventType, AxlEventOf, AskScoped } from '@axlsdk/axl'; ``` > Renamed from `TraceEvent`/`StreamEvent` in 0.16.0. See the [migration guide](./migration/unified-event-model.md) for the full diff. ### `AxlEventBase` (common fields on every variant) | Field | Type | Description | |-------|------|-------------| | `schemaVersion` | `2` | Required event-schema discriminator on every live v2 event | | `executionId` | `string` | Execution this event belongs to | | `step` | `number` | Monotonic per-execution step counter, shared across nested asks via `AsyncLocalStorage` | | `type` | `AxlEventType` | See `AXL_EVENT_TYPES` below | | `workflow` | `string?` | Workflow name (auto-stamped from the active context) | | `agent` | `string?` | Agent name. Required on variants like `agent_call_start`/`agent_call_end` | | `tool` | `string?` | Tool name (on tool-related events) | | `model` | `string?` | Model URI (on agent-related events) | | `promptVersion` | `string?` | Agent version (on agent-related events) | | `cost` | `number?` | Cost in USD for this step. Required on `agent_call_end` and `ask_end` (narrowing). **`ask_end.cost` is a per-ask rollup — see double-counting note below** | | `tokens` | `{ input?, output?, reasoning? }?` | Token usage from the provider (on `agent_call_end` events). Maps from `ProviderResponse.usage` | | `duration` | `number?` | Duration in ms (set on `_end` variants) | | `data` | event-specific | Variant-specific payload — narrow via `type` | | `timestamp` | `number` | Event timestamp (ms) | ### `AskScoped` (mixin on every event originating within `ctx.ask()`) | Field | Type | Description | |-------|------|-------------| | `askId` | `string` | UUID for this ask invocation. Stable for all events emitted within a single `ctx.ask()` | | `parentAskId` | `string?` | The enclosing ask (absent on the root) | | `depth` | `number` | `0` for root, `+1` per nested `ctx.ask()` | | `agent` | `string?` | Emitting agent's name | `handoff_start` and `handoff_return` are the single exception — they span two asks atomically and carry `fromAskId` / `toAskId` / `sourceDepth` / `targetDepth` instead. ### `AxlEvent` variants `AxlEvent` is a **discriminated union** over `type`. Narrow via `event.type === 'agent_call_end'` etc. Use `AxlEventOf<'agent_call_end'>` to extract a specific variant. | `type` | Mixin | Required variant fields | When emitted | |---|---|---|---| | `workflow_start` / `workflow_end` | — | `workflow`, `data: WorkflowStartData/WorkflowEndData` | Workflow lifecycle | | `ask_start` | `AskScoped` | `prompt: string` | Top of every `ctx.ask()` | | `ask_end` | `AskScoped` | `outcome: { ok: true, result } \| { ok: false, error }`, `cost`, `duration` | Every `ctx.ask()` exit. Ask-internal failures surface here, NOT via the workflow-level `error` event | | `agent_call_start` | `AskScoped` | `agent: string`, `model: string`, `turn: number`, `data: AgentCallStartData` | Before each LLM call (one per loop turn) | | `agent_call_end` | `AskScoped` | `agent: string`, `model: string`, `cost: number`, `duration: number`, `data: AgentCallEndData` | After each LLM call returns | | `token` | `AskScoped` | `data: string` | Streaming text chunk. **Stream-only** — never persisted to `ExecutionInfo.events` | | `tool_call_rejected` | `AskScoped` | `tool: string`, `callId: string`, `data: ToolCallRejectedData` | Provider request rejected before execution starts; no start/end pair | | `tool_call_start` | `AskScoped` | `tool: string`, `callId: string`, `data: ToolCallStartDataV2` | After availability, JSON, and local argument validation succeeds | | `tool_call_end` | `AskScoped` | `tool: string`, `callId: string`, `duration: number`, `cost?`, `data: ToolCallEndData` | Exactly one terminal outcome for an accepted call in a complete trace | | `tool_approval` | `AskScoped` | `tool: string`, `callId?`, `data: ToolApprovalData` | `requireApproval` gate fires (both approve and deny) | | `delegate` | `AskScoped` | `data: DelegateData` | `ctx.delegate()` routes (including single-agent short-circuit) | | `handoff_start` | — (spans two asks) | `fromAskId`, `toAskId`, `sourceDepth`, `targetDepth`, `data: HandoffStartData` | Fires BEFORE the target ask begins. Emitted on EVERY handoff (both oneway and roundtrip). Orders ahead of the target's `ask_start` in step-sorted timelines | | `handoff_return` | — (spans two asks) | `fromAskId`, `toAskId`, `sourceDepth`, `targetDepth`, `data: HandoffReturnData` | Fires AFTER control returns to the source agent. **Roundtrip mode only** — oneway handoffs are terminal at the target and emit no return event | | `pipeline` | `AskScoped` | `status: 'start'\|'failed'\|'committed'`, `stage`, `attempt`, `maxAttempts`, `reason?` | Retry/validation lifecycle; `AxlStream.fullText` commits on `pipeline(committed)` and discards in-progress tokens on `pipeline(failed)` | | `partial_object` | `AskScoped` | `attempt: number`, `data: { object: unknown }` | Progressive structured output — emitted at string-safe boundaries when a `schema` is set on `ctx.ask()` and no tools are registered | | `string_delta` | `AskScoped` | `attempt: number`, `data: StringDeltaData` (`{ path: string, delta: string }`) | Per-chunk character-level deltas inside string VALUES of progressive structured output. Same gating as `partial_object` (schema set, no tools, root is `ZodObject`). **Important:** `handoffs: [...]` configured on an agent registers as tools internally, so a router agent never emits `string_delta` — only the handoff target (or any leaf agent with no tools and a schema) does. `path` is an RFC 6901 JSON Pointer to the string field (`/summary`, `/sources/0/title`); `delta` is the unescaped chars added in this chunk. Designed for chat-style typewriter rendering of long string fields — see `AxlStream.stringStream` / `AxlEventBus.stringStream` view helpers below. Stream-only; never persisted to `ExecutionInfo.events` | | `verify` | `AskScoped` | `data: VerifyData` | `ctx.verify()` completes (pass or fail) | | `schema_diagnostic` | `AskScoped` | `data: SchemaDiagnosticData` (`kind`-discriminated) | A silent structured-output cliff was detected (oversized appended/tool schema, dropped `.refine()`s, streaming disabled, or `schemaPrompt:'none'` with no guidance). One per ask per cliff. Threshold + silencing via `AxlConfig.diagnostics`. See [observability.md#schema-diagnostics](./observability.md#schema-diagnostics) | | `guardrail` / `schema_check` / `validate` | `Partial` | `data: GuardrailData/SchemaCheckData/ValidateData` | Per-gate retry events emitted alongside `pipeline` | | `log` | `Partial` | `data: unknown` | `ctx.log()` user event | | `memory_remember` / `memory_recall` / `memory_forget` | `Partial` | `data: MemoryEventData` | Memory ops audit | | `checkpoint_save` / `checkpoint_replay` | `Partial` | `data: CheckpointEventData` | `ctx.checkpoint(name, fn)` — `save` on first execution, `replay` when a saved value short-circuits the function call | | `await_human` | `Partial` | `data: AwaitHumanData` | `ctx.awaitHuman()` suspends execution for a human decision (paired with `await_human_resolved`) | | `await_human_resolved` | `Partial` | `data: AwaitHumanResolvedData` | The decision arrives and resumes the workflow | | `done` | — | `data: { result: unknown }` | Terminal — workflow completed | | `error` | `Partial` | `data: { message: string, name?, code? }` | Terminal — non-ask-internal error (top-level workflow throws, infra/abort errors) | Per-variant data shape exports from `@axlsdk/axl`: `AgentCallStartData`, `AgentCallEndData`, `AgentCallParams`, `ToolCallStartDataV2`, `ToolCallRejectedData`, `ToolArgumentIssue`, `ToolCallEndData`, `ToolCallOutcome`, `ToolCallFailure`, `ToolCallCancellation`, `ToolEventError`, `ToolApprovalData`, `HandoffStartData`, `HandoffReturnData`, `DelegateData`, `VerifyData`, `WorkflowStartData`, `WorkflowEndData`, `MemoryEventData`, `CheckpointEventData`, `AwaitHumanData`, `AwaitHumanResolvedData`, `GuardrailData`, `SchemaCheckData`, `ValidateData`, `StringDeltaData`. Versioned exports include `AxlEventV2`, `HistoricalAxlEvent`, `ExecutionInfoV2`, `LegacyExecutionInfoV1`, and `HistoricalExecutionInfo`. View-helper event types: `CoalescedPartialObject`, `StringStreamEvent`, `StringStreamFilter`. The constant tuple `AXL_EVENT_TYPES` is the single source of truth for the live discriminator. **Cost double-counting guard:** `ask_end.cost` is the per-ask rollup of `agent_call_end.cost` + `tool_call_end.cost` emitted within that ask, **excluding nested asks** (nested asks contribute to their own `ask_end`). Use the exported helper `eventCostContribution(event)` — returns `0` on `ask_end` and on non-finite values, `event.cost` otherwise. Axl's built-in `runtime.trackExecution`, `ExecutionInfo.totalCost`, Studio's cost aggregator, and `AxlTestRuntime.totalCost()` all use this helper internally: ```typescript import { eventCostContribution } from '@axlsdk/axl'; const total = info.events.reduce((sum, e) => sum + eventCostContribution(e), 0); ``` Also exported: `isCostBearingLeaf(event: AxlEvent): boolean` (takes an event, checks its `type` against the leaf set — pass the event, not the type string), `isUnpricedLeaf(event): boolean` (the single source of truth for the unpriced signal — `true` when a cost-bearing leaf did billable work but had no usable cost; drives `ExecutionInfo.unpriced` / `trackExecution().unpriced` / Studio's `unpricedCalls`), `COST_BEARING_LEAF_TYPES` (the canonical `as const` tuple: `agent_call_end`, `tool_call_end`, `memory_remember`, `memory_recall`), and `isRootLevel(event: AxlEvent): boolean` (true when `depth === 0` or undefined — used for root-only token filtering). **`parsePartialJson(text: string): unknown`** — tolerant JSON parser used internally for `partial_object` streaming. Recovers from truncated input (unclosed strings/objects/arrays) and is hardened against deeply-nested input via a 256-depth cap (returns `null` on overflow). Exported from `@axlsdk/axl` for consumers building their own progressive-render pipelines that need to share Axl's truncation-recovery and stack-overflow guard rails. Zero dependencies. **`stringStreamFromEvents(source: AsyncIterable, opts?: StringStreamFilter): AsyncIterable`** — browser-safe reconstructor for the `stringStream` view from a raw `AxlEvent` source. Use when consuming events over WebSocket / SSE on the client side, where you don't have access to `AxlStream` / `AxlEventBus`. Same `{ path?, askId? }` filter shape and same retry/`ask_end`-clear semantics as `AxlEventBus.stringStream`. Yields `StringStreamEvent` (`{ askId, agent?, path, delta, accumulated, attempt }`); maintains a per-(askId, path) text accumulator client-side. Pure ECMAScript, no Node dependencies. **Differences from the live-bus view:** no late-subscriber seeding (start iterating before events arrive); no race-with-iterator pending buffer (events yield as they arrive). For full SPA recipe see `docs/observability.md`. **`AnyWorkflow`** — type alias for `Workflow`, exported from `@axlsdk/axl`. Used by `AxlRuntime.register` (and `AxlTestRuntime.register`) to accept any workflow regardless of its specific input/output schema. Useful for typing helper functions that operate on registered workflows generically. ### `AgentCallStartData` (data on `agent_call_start` events — request side) Populated at dispatch time, before the provider responds. Lets consumers render "what's being asked" without waiting for completion. | Field | Type | Description | |-------|------|-------------| | `prompt` | `string` | Original user prompt passed to `ctx.ask()`. Does not include retry feedback or tool results | | `system` | `string?` | Resolved system prompt (dynamic selectors evaluated at call time) | | `params` | `AgentCallParams?` | Resolved model parameters sent to the provider: `{ temperature?, maxTokens?, effort?, thinkingBudget?, includeThoughts?, toolChoice?, stop? }` | | `turn` | `number` | 1-indexed iteration of the tool-calling loop for this `ctx.ask()` call | | `retryReason` | `'schema' \| 'validate' \| 'guardrail'?` | Set when this call is a retry triggered by a failed gate on the previous turn | | `toolNames` | `string[]?` | Names of tools exposed to the model on this call. Empty/omitted when no tools are bound | | `messages` | `ChatMessage[]?` | Full `ChatMessage[]` sent to the provider this turn. **Only populated when `config.trace.level === 'full'`** | ### `AgentCallEndData` (data on `agent_call_end` events — response side) Populated when the provider returns (success or recoverable failure). Pair invariant: every `agent_call_start` is followed by exactly one `agent_call_end`, even on provider error. | Field | Type | Description | |-------|------|-------------| | `response` | `string` | Final LLM response content for this turn. Empty string on error | | `thinking` | `string?` | Reasoning/thinking content returned by the provider, when available | | `turn` | `number` | 1-indexed iteration of the tool-calling loop. Mirrors the matching `agent_call_start.data.turn` | | `retryReason` | `'schema' \| 'validate' \| 'guardrail'?` | Mirrors `agent_call_start.data.retryReason` so cost-attribution consumers reading `agent_call_end` (where `cost` lives) can bucket without joining | | `error` | `string?` | Provider error message when the call threw (network failure, 4xx/5xx, abort, etc). Mutually exclusive with `response` content. Subject to `config.trace.redact` | | `status` | `number?` | HTTP status when the throw was a `ProviderError` (`0` for network failures). Mirrors `ProviderError.status`; omitted for non-provider errors. The raw error `body` is **not** on the event (redaction-eligible) | | `retryable` | `boolean?` | Semantic failover hint when the throw was a `ProviderError` (mirrors `ProviderError.retryable`). Omitted for non-provider errors | `AgentCallParams` is also exported from `@axlsdk/axl` for consumers needing to type the resolved parameters object directly. ### `GuardrailData` / `SchemaCheckData` / `ValidateData` (symmetric shape) | Field | Type | Description | |-------|------|-------------| | `valid` / `blocked` | `boolean` | Check outcome. Guardrails use `blocked`; schema_check and validate use `valid` | | `guardrailType` | `'input' \| 'output'?` | Guardrail events only | | `reason` | `string?` | Human-readable failure reason | | `attempt` | `number?` | 1-indexed attempt. Omitted for input guardrails (they don't retry) | | `maxAttempts` | `number?` | Maximum attempts allowed before throwing. Equals `retries + 1` | | `feedbackMessage` | `string?` | The exact corrective message about to be injected into the conversation. **Only set when the check failed and a retry is happening** — gives observability into what the LLM sees between retry attempts | ### `ToolApprovalData` (data on `tool_approval` events) | Field | Type | Description | |-------|------|-------------| | `approved` | `boolean` | Whether the human approved the tool call | | `args` | `unknown` | Tool arguments that were pending approval | | `reason` | `string?` | Denial reason (set only when `approved: false`) | ### Tool lifecycle data `ToolCallStartDataV2` is `{ args: unknown; requestedTool?: string }`. `args` is the validated logical input before any `before`-hook transform. `requestedTool` is present when the provider-visible name differs from the canonical trace name. `ToolCallRejectedData` is a pre-start union: - `{ reason: 'unavailable', requestedTool, availableTools }` - `{ reason: 'invalid_json', requestedTool, message }` - `{ reason: 'invalid_arguments', requestedTool, args, issues }` An issue is `{ path: readonly (string | number)[]; code: string; message? }` and contains no rejected values. Rejections never emit `tool_call_start` or `tool_call_end`. `ToolCallEndData` is `{ args, requestedTool?, outcome }`. `callId` stays top-level on the event. End args exactly match start args. The outcome union is: ```typescript type ToolCallOutcome = | { status: 'succeeded'; result: unknown } | { status: 'failed'; failure: ToolCallFailure } | { status: 'denied'; reason?: string } | { status: 'cancelled'; cancellation: ToolCallCancellation }; ``` `ToolCallFailure` discriminates `phase`, `kind`, and `disposition`: - approval infrastructure failures: `approval` / `infrastructure` / `abort`; - hook failures: `before_hook` or `after_hook`, with `tool_failure` / `continue` or `unexpected` / `abort`; - handler failures: `tool_failure` or `mcp_error` / `continue`, or `unexpected` / `abort`, plus `attempts`; - output failures: `projection` or `serialization` / `output` / `abort`. After-hook and output failures retain the available raw or post-hook `result`. Handler throws, approval failure, denial, and pre-result cancellation do not invent one. `ToolCallCancellation.phase` is `approval`, `before_hook`, `handler`, `after_handler`, `after_hook`, `projection`, or `serialization`; post-result phases retain `result`. Every accepted call settles at most once. In a complete v2 trace, pair start and end by `(executionId, askId, callId)`. Lossy queues, capped persistence, disconnection, or process death may yield an explicitly incomplete consumer view; never synthesize a terminal outcome for an orphan start. ### `HandoffStartData` (data on `handoff_start` events) Emitted BEFORE the target ask begins. Fires on every handoff (both oneway and roundtrip). | Field | Type | Description | |-------|------|-------------| | `source` | `string` | Agent name that initiated the handoff. Mirrors `event.agent` for join-convenience | | `target` | `string` | Agent name receiving the handoff | | `mode` | `'oneway' \| 'roundtrip'` | Handoff mode. Determines whether a matching `handoff_return` will follow | | `message` | `string?` | The `message` argument the source agent passed when invoking `handoff_to_X` in roundtrip mode. Populated only on roundtrip handoffs with a custom message; subject to `config.trace.redact` | ### `HandoffReturnData` (data on `handoff_return` events) Emitted AFTER control returns to the source agent. **Roundtrip mode only** — oneway handoffs are terminal at the target and emit no return event. The returned value itself is observable via the target ask's `ask_end.outcome`; this event marks the control transfer back to the source and carries the round-trip duration. | Field | Type | Description | |-------|------|-------------| | `source` | `string` | Agent name that initiated the handoff | | `target` | `string` | Agent name that received the handoff and has now returned | | `duration` | `number` | Wall-clock ms from `handoff_start` emission to control returning to source | ### `DelegateData` (data on `delegate` events) | Field | Type | Description | |-------|------|-------------| | `candidates` | `string[]` | Agent names the delegation router considered | | `selected` | `string?` | Chosen agent, if the router completed a routing decision | | `routerModel` | `string?` | Model URI used by the routing ask | | `reason` | `'single_candidate' \| 'routed'` | `'single_candidate'` on the short-circuit path (only one agent available), `'routed'` when a router was actually invoked | ### `VerifyData` (data on `verify` events) | Field | Type | Description | |-------|------|-------------| | `passed` | `boolean` | Whether the verification ultimately succeeded | | `attempts` | `number` | Number of attempts before the terminal outcome | | `lastError` | `string?` | Error message from the final failing attempt, when applicable | ### `WorkflowStartData` (data on `workflow_start` events) | Field | Type | Description | |-------|------|-------------| | `input` | `unknown` | Workflow input, after Zod schema validation. Subject to `config.trace.redact` | ### `WorkflowEndData` (data on `workflow_end` events) | Field | Type | Description | |-------|------|-------------| | `status` | `'completed' \| 'failed'` | Terminal status | | `duration` | `number` | Total wall-clock duration in ms | | `result` | `unknown?` | Workflow return value (when `status === 'completed'`). Subject to `config.trace.redact` | | `error` | `string?` | Error message (when `status === 'failed'`). Subject to `config.trace.redact` | | `aborted` | `boolean?` | `true` when the execution ended via `AbortSignal` (user cancel, budget `hard_stop`, parent-scope abort). Lets consumers distinguish cancellation from genuine error | ### Verbose trace mode and redaction - **`config.trace.level === 'full'`** opts into verbose mode: `agent_call_start.data.messages` is populated with the full `ChatMessage[]` about to be sent to the provider on each turn. This grows with tool results and retry feedback across turns, so it's off by default - **`config.trace.redact === true`** is an **observability-boundary filter** — scrubs user/LLM content everywhere it would otherwise flow to observability consumers (events, Studio REST route responses, Studio WebSocket broadcasts). Structural metadata (workflow names, agent names, tool names, cost/token metrics, durations, roles, IDs, attempt counters, scorer scores, ask-graph fields like `askId`/`parentAskId`/`depth`) stays visible so the Trace Explorer, Memory Browser, Session Manager, Cost Dashboard, and Eval Runner all remain usable under compliance mode. See [`observability.md`](./observability.md#pii-and-redaction) for the complete per-route scrubbed/preserved table. Programmatic callers of `runtime.execute()` and direct `StateStore` access still receive raw values — redaction is an observability filter, not a data-at-rest transform. Access the flag from Studio consumers via `runtime.isRedactEnabled(): boolean` - **Per-variant scrub rules are exported.** `REDACTED`, `REDACTION_RULES: Record>`, and `redactEvent(event)` from `@axlsdk/axl` are the single source of truth for which fields scrub on which event variants. Both core's emit-time path and Studio's WS-boundary path consult the same table — adding a new variant to `AXL_EVENT_TYPES` without a corresponding rule is a typecheck error. Custom observability sinks that re-export events to third-party platforms can apply `redactEvent(event)` to inherit the same per-variant contract --- ## Error Types All errors extend `AxlError`. | Error | Thrown by | Description | |-------|----------|-------------| | `ToolFailure` | tool authors | Explicit model-safe tool failure. Constructor takes `{ message, modelMessage, code?, cause? }`; terminal agent-invoked calls may continue with `modelMessage`, while direct calls still throw | | `VerifyError` | `ctx.ask()`, `ctx.verify()` | Schema validation failed after all retries. Includes `.lastOutput`, `.zodError`, `.retries` | | `ValidationError` | `ctx.ask()`, `ctx.verify()` | Post-schema business rule validation failed after all retries. Includes `.lastOutput`, `.reason`, `.retries` | | `QuorumNotMet` | `ctx.spawn()`, `ctx.map()` | Fewer tasks succeeded than the required quorum. Includes `.results` | | `NoConsensus` | `ctx.vote()` | No successful results to vote on, unanimous vote failed, or invalid strategy/option combination | | `TimeoutError` | `ctx.ask()` | Agent exceeded its configured `timeout` | | `MaxTurnsError` | `ctx.ask()` | Agent exceeded its configured `maxTurns` | | `BudgetExceededError` | `ctx.budget()` | Budget exceeded with `hard_stop` policy. Includes `.limit`, `.spent`, `.policy` | | `GuardrailError` | `ctx.ask()` | Guardrail blocked and retries exhausted. Includes `.guardrailType`, `.reason` | | `ProviderError` | provider adapters (via `ctx.ask()`) | Non-2xx HTTP response, or a normalized network failure (`status: 0`). `code: 'PROVIDER_ERROR'`. Includes `.provider`, `.status`, `.retryable`, `.retryAfterMs?`, `.requestId?`, `.body?`. Message is the provider's text verbatim (no prefix). | | `AxlError` / `INVALID_HUMAN_DECISION` | approval handlers, `runtime.resolveDecision()` | Untyped decision is not the exact plain-object approval/denial union; rejected before resolver/store mutation | | `AxlError` / `CROSS_PROCESS_RESUME_UNSUPPORTED` | `runtime.resolveDecision()`, `runtime.resumeExecution()` | Execution has no in-process decision resolver. Fails before deleting any pending request or re-executing side effects, even when execution-state persistence is missing or stale | ### `ProviderError` fields | Field | Type | Description | |-------|------|-------------| | `provider` | `string` | Adapter / preset name: `'openai'`, `'anthropic'`, `'google'`, `'openai-responses'`, or a compatible-preset name | | `status` | `number` | HTTP status; `0` for non-HTTP (network) failures | | `retryable` | `boolean` | Semantic failover hint (see table below). **Distinct** from the transport auto-retry set (`429`/`503`/`529`) | | `retryAfterMs` | `number \| undefined` | Parsed `Retry-After` (raw/unclamped) when the header was present; supports numeric-seconds and HTTP-date | | `requestId` | `string \| undefined` | Provider request id (`x-request-id` / `request-id`) when present | | `body` | `string \| undefined` | Raw provider error body. Lives only on the error — never on the event stream (redaction-eligible) | **`retryable` classification** (also exposed as the exported helper `isRetryableStatus(status: number): boolean`): | status | `retryable` | |---|---| | `408`, `429`, `500`, `502`, `503`, `504`, `529` | `true` | | `0` (network) | `true` | | `400`, `401`, `403`, `404`, `409`, `413`, `422`, `425`, other 4xx | `false` (conservative default) | `agent_call_end` events on a provider error also carry `data.status` and `data.retryable` (message in `data.error`); the raw `body` is never emitted. See `docs/observability.md`. --- ## Evaluation Types Types from `@axlsdk/eval` used by `runEval()`, `runtime.eval()`, and the CLI. ### `EvalConfig` Configuration for `runEval()` and `runtime.eval()`. | Field | Type | Default | Description | |-------|------|---------|-------------| | `workflow` | `string` | required | Workflow name (label for results; must match a registered workflow when using `runtime.eval()`) | | `dataset` | `Dataset` | required | Dataset to evaluate against | | `scorers` | `Scorer[]` | required | Scoring functions to apply to each output | | `concurrency` | `number` | `5` | Maximum parallel item executions | | `scorerConcurrency` | `number` | `5` | Maximum parallel scorers **within a single item**. Worst-case concurrent scorer calls is `concurrency × scorerConcurrency`; set to `1` for a serial judge phase. Cost/timing/ordering are preserved deterministically | | `budget` | `string` | — | Cost limit (e.g., `"$10.00"`). Stops processing when exceeded. With concurrent scorers it is a **soft** ceiling — the per-item check runs once before an item's scorers, so overshoot is bounded by `concurrency × scorerConcurrency × max-scorer-cost` | | `failOnScorerErrorRate` | `number` (0–1) | — | Opt-in **source-side** trust gate. When set, `runEval` marks the run `summary.degraded` (and the CLI exits non-zero) if a scorer's failure rate exceeds tolerance. **Type-aware**: deterministic scorers tolerate **0** failures (a deterministic scorer that throws is a bug); LLM scorers use this rate. Failure rate = `failed / (scored + failed)`; `0` means "any LLM failure degrades". Items a scorer's `applies` predicate skipped are in neither `scored` nor `failed`, so they're excluded from the denominator — the supported way to scope a conditional scorer without polluting the gate (do NOT return `NaN` for inapplicable items; the gate treats a non-finite score as a real failure). `runEval` never throws on this — it flags and returns, so the (still-useful) result is persisted and the consumer decides. An out-of-range value is **rejected at config load** by the CLI (`validateEvalConfig`, fails loud like `--max-scorer-error-rate`); a programmatic `runEval()` caller that bypasses that validation gets a `console.warn` and the gate is skipped. Catches the silent-thinned-sample trap: a `--fail-on-regression` gate computed over surviving scores can look green when half the judges 429'd. Distinct from the gate-side `axl-eval compare --max-scorer-error-rate` (which refuses to certify an already-thinned baseline/candidate). | | `metadata` | `Record` | — | Arbitrary metadata attached to the result (e.g., model version, prompt variant) | ### `DatasetConfig` Configuration for `dataset()`. | Field | Type | Default | Description | |-------|------|---------|-------------| | `name` | `string` | required | Dataset name (appears in results and comparisons) | | `schema` | `z.ZodType` | required | Zod schema for dataset item inputs | | `annotations` | `z.ZodType` | — | Zod schema for ground-truth annotations | | `items` | `DatasetItem[]` | — | Inline dataset items (each has `input` and optional `annotations`) | | `file` | `string` | — | Path to a JSON file containing items (alternative to inline `items`) | | `basePath` | `string` | `cwd` | Base directory for resolving relative `file` paths | | `onExtraAnnotationKeys` | `'warn' \| 'error' \| 'ignore'` | `'warn'` | What to do when an item's `annotations` contain keys not declared in the `annotations` schema. Zod strips unknown keys by default, so such fields are silently dropped before reaching scorers (a common cause of no-op scorers). `'warn'` logs one consolidated `console.warn` per dataset listing the dropped key paths; `'error'` throws; `'ignore'` restores the silent-strip behavior. Detection is recursive (reports nested paths like `persona.role`) and covers file-based datasets, which get no compile-time checking. Only runs when the `annotations` schema is a `ZodObject` — schemas wrapping a `.transform()`/`.preprocess()` are skipped, since their parsed output is reshaped by design. Scoped to `annotations`, not `input`. | > **Annotation/schema drift.** A scorer that reads `annotations?.someKey` silently returns garbage when `someKey` was stripped because it isn't in the `annotations` schema (e.g. a typo, or a key added to a `file:` dataset but not the schema). On Zod v4 TypeScript catches *some* of this — an inline item literal triggers an excess-property error, and a schema declared `z.ZodType` that is structurally narrower than `T` is itself a compile error. What stays uncaught at compile time is variable-sourced items, `file:` (JSON) datasets, and explicit `as unknown as` casts. `onExtraAnnotationKeys` (default `'warn'`) is the runtime backstop that catches all of those regardless. Set it to `'error'` in CI to fail the build on drift. ### `ScorerResult` Rich result from a scorer, returned instead of a plain number when the scorer needs to convey metadata or cost. | Field | Type | Description | |-------|------|-------------| | `score` | `number` | Score value (0-1) | | `metadata` | `Record?` | Arbitrary metadata (e.g., `reasoning`, `confidence`). LLM scorers populate this with the full schema response | | `cost` | `number?` | LLM cost incurred by this scorer invocation | ### `ScorerDetail` Per-scorer data stored on each `EvalItem`, providing richer detail than the `scores` map. | Field | Type | Description | |-------|------|-------------| | `score` | `number \| null` | Score value, or `null` if the scorer failed | | `metadata` | `Record?` | Scorer metadata (e.g., reasoning from LLM scorers) | | `duration` | `number?` | Scorer execution time in ms. Absent on a skipped scorer (it never ran) | | `cost` | `number?` | LLM cost for this scorer invocation | | `skipped` | `boolean?` | `true` when the scorer's `applies` predicate returned `false` for this item, so it was deliberately **not run** (`score` is `null`, no `duration`). Distinct from a ran-and-failed scorer (`null` score WITH a `duration`) and from cancellation (no marker, no duration). A skipped scorer is excluded from the mean AND from the failure-rate denominator — see `EvalSummary.scorers[].skipped` and `failOnScorerErrorRate` | ### `EvalItem` Per-item result from an eval run. `scores` provides quick numeric access; `scoreDetails` provides the full picture (metadata, per-scorer timing, per-scorer cost). | Field | Type | Description | |-------|------|-------------| | `input` | `unknown` | The dataset input | | `annotations` | `unknown?` | Ground truth annotations | | `output` | `unknown` | Workflow output | | `error` | `string?` | Workflow-level error message | | `scorerErrors` | `string[]?` | Scorer-level error messages (thrown exceptions or out-of-range scores) | | `scores` | `Record` | Quick numeric access to scores. `null` = scorer error (see `scorerErrors`) **or** a scorer skipped by its `applies` predicate — disambiguate via `scoreDetails[name].skipped` | | `duration` | `number?` | Workflow execution time in ms (set even when workflow errors) | | `cost` | `number?` | Workflow LLM cost | | `scorerCost` | `number?` | Total scorer cost for this item (sum of all `scoreDetails[*].cost`) | | `scoreDetails` | `Record?` | Rich per-scorer data — includes `metadata` (e.g., LLM reasoning), per-scorer `duration`, and `cost` | | `metadata` | `Record?` | Execution metadata forwarded from the runtime (e.g., `models`, `tokens`, `agentCalls`) | | `traces` | `AxlEvent[]?` | Per-item events. Populated only when the eval was run with `{ captureTraces: true }`. Includes events on the failure path (recovered from the `axlCapturedTraces` side-channel on thrown errors) | ### `EvalResult` Full result from an eval run. | Field | Type | Description | |-------|------|-------------| | `id` | `string` | Unique eval run ID | | `dataset` | `string` | Dataset name. Definitional — `evalCompare` enforces matching datasets. | | `metadata` | `Record` | User-provided metadata merged with runner-populated fields (see below) | | `timestamp` | `string` | ISO 8601 timestamp | | `totalCost` | `number` | Total LLM cost (workflow + LLM scorers) | | `duration` | `number` | Wall-clock time in ms | | `items` | `EvalItem[]` | Per-item results | | `summary` | `EvalSummary` | Aggregate statistics | **Runner-populated metadata** (on top of user-provided `EvalConfig.metadata`): | Key | Type | Description | |-----|------|-------------| | `models` | `string[]` | Unique model URIs observed during execution, sorted by call count desc | | `modelCounts` | `Record` | Per-model call counts | | `workflows` | `string[]` | Unique workflow names observed (trace-derived), sorted by call count desc. Parallel to `models`. Readers that want a single "primary" workflow use `workflows[0]`. When no traces are captured, falls back to `config.workflow` | | `workflowCounts` | `Record` | Per-workflow call counts | | `scorerTypes` | `Record` | Scorer kind for threshold calibration | | `runGroupId` | `string?` | Shared ID across multi-run groups (`--runs N`) | | `runIndex` | `number?` | Position within a multi-run group | | `batchAttempted` | `number?` | Planned multi-run count. Stamped on every persisted run by both the CLI and Studio's run endpoint so any later viewer (compare, history, trends) can derive partial-batch state by comparing the actual run count against this | | `batchCompleted` | `number?` | Number of runs actually completed when the batch is partial (only set when `batchCompleted < batchAttempted`) | | `fromPartialBatch` | `boolean?` | Set on every successful run from a partial batch — flags "this run came from a batch that did not complete," NOT "this run is partial." Defensive consumers should NOT skip runs based on this flag (they completed and have valid data) | | `batchFailure` | `string?` | The error message that stopped a partial batch. Coalesced from `Error.message \|\| String(error)` so it's never blank; omitted when the partial state came from user cancellation rather than a thrown failure | | `droppedAnnotationKeys` | `string[]?` | Annotation key paths the dataset's `annotations` schema stripped before items reached scorers (e.g. `expectedTone`, `persona.role`). Present only when non-empty. Mirrors the dataset's `console.warn`; Studio's Eval Runner renders it as a banner. See `DatasetConfig.onExtraAnnotationKeys` | | `scorerFiltered` | `boolean?` | Set when the CLI `--scorers` flag ran only a subset of scorers. A guard so a filtered run isn't silently used as a full baseline — `axl-eval compare` warns and refuses to gate (`--fail-on-regression`) on it. Distinct from the multi-run `partial` concept | | `scorersRun` | `string[]?` | The scorer names that actually ran, set alongside `scorerFiltered` | > `EvalResult` used to have a top-level `workflow: string` field. It was removed in 0.14.x because it could not honestly represent multi-workflow runs (nested execution, heterogeneous callbacks). Use `metadata.workflows` instead. `EvalConfig.workflow` (the scheduling input) is unchanged. ### `EvalSummary` Aggregate statistics across all items. | Field | Type | Description | |-------|------|-------------| | `count` | `number` | Total items | | `failures` | `number` | Items where the workflow threw an error | | `scorers` | `Record` | Per-scorer aggregate stats (all score values 0-1). `scored` is the number of items that produced a valid numeric score — the sample size `mean` actually covers; `failed` is the number whose scorer **ran and failed** (threw / out-of-range); `skipped` is the number whose `applies` predicate returned `false` (deliberately not run). Neither a skipped nor a cancelled scorer is in `scored`/`failed`, so `scored + failed` is the honest "attempted" count and the failure rate excludes skips. A non-zero `failed` means `mean` rests on a thinned sample. All optional (absent on pre-0.18.0 artifacts → recompute from `items`) | | `timing` | `{ mean, min, max, p50, p95 }?` | Per-item duration statistics in ms | | `degraded` | `DegradedScorer[]?` | Present only when `EvalConfig.failOnScorerErrorRate` is set **and** one or more scorers exceeded tolerance. Each entry is `{ scorer, rate, limit, type, scored, failed }`. `runEval` sets this and returns normally (it never throws); the CLI turns a non-empty `degraded` into a non-zero exit | | `DegradedScorer` | `{ scorer: string; rate: number; limit: number; type: 'llm' \| 'deterministic'; scored: number; failed: number }` | One scorer that tripped the failure-rate gate. `rate = failed / (scored + failed)`; `limit` is the tolerance exceeded (`0` for deterministic). Exported from `@axlsdk/eval` | ### `Scorer` A scoring function returned by `scorer()` or `llmScorer()`. | Field | Type | Description | |-------|------|-------------| | `name` | `string` | Unique scorer name | | `description` | `string` | What this scorer evaluates | | `isLlm` | `boolean` | `true` for LLM scorers | | `score` | `(output, input, annotations?, context?) => number \| ScorerResult \| Promise` | Scoring function (returns 0-1 or a `ScorerResult` with metadata/cost). `context` is a `ScorerContext` passed by the eval runner | | `applies` | `(output, input, annotations?) => boolean` (optional) | Conditional-scorer predicate. The runner evaluates it **before** `score`; a `false` verdict skips the scorer for that item — for an `llmScorer`, no provider call is made — and the item counts as neither `scored` nor `failed` (excluded from the mean and the failure-rate denominator). The skip surfaces as `scoreDetails[name].skipped === true`. A predicate that throws is recorded as a scorer failure, not a skip. Omit to run on every item | ### `LlmScorerConfig` Configuration for `llmScorer()`. | Field | Type | Default | Description | |-------|------|---------|-------------| | `name` | `string` | required | Unique scorer name | | `description` | `string` | required | What this scorer evaluates | | `model` | `string` | required | Provider:model URI (e.g., `openai:gpt-4o`) | | `system` | `string` | required | System prompt for the judge LLM | | `schema` | `z.ZodType<{ score: number; ... }>` | `z.object({ score: z.number(), reasoning: z.string() })` | Response schema — converted to JSON Schema and included in the prompt so the LLM knows the exact structure to produce | | `temperature` | `number` | `0.2` | Low for scoring consistency | | `maxTokens` | `number` | provider default | Cap on response tokens | | `effort` | `Effort` | provider default | Unified reasoning/thinking level (`'none' \| 'low' \| 'medium' \| 'high' \| 'xhigh' \| 'max'`). On reasoning-capable judges (gpt-5.x, Anthropic Opus 4.5+, Sonnet 4.6+, Gemini 3.x), `'high'` or `'max'` materially improves calibration. Provider-specific mapping (`xhigh` clamps, `none` semantics, etc.) lives on the [`Effort`](#effort) type — judges follow the same rules as agents | | `thinkingBudget` | `number` | — | Precise thinking-token budget override; `0` disables thinking while keeping `effort` for output control (Anthropic). On other providers, simply disables reasoning | | `includeThoughts` | `boolean` | provider default | Surface reasoning summaries in the judge's response. Effective on Gemini and the `openai-responses:` provider; no-op on Anthropic and OpenAI Chat Completions (`openai:`). Resolved to `false` if unset | | `stop` | `string[]` | — | Stop sequences forwarded to the provider | | `providerOptions` | `Record` | — | Provider-specific escape hatch merged last into the raw API request. Not portable across providers. Can override the hardcoded `responseFormat: { type: 'json_object' }` — pass `providerOptions: { response_format: { type: 'json_schema', ... } }` to switch to strict JSON Schema mode | | `applies` | `(output, input, annotations?) => boolean` | — | Conditional-scorer predicate (see `Scorer.applies`). Evaluated before the judge call, so a `false` verdict means **no provider call** is made for that item — the conditional-LLM-judge cost / rate-limit win. The item counts as neither `scored` nor `failed` | ### `ScorerContext` Context passed to scorers by the eval runner. | Field | Type | Description | |-------|------|-------------| | `resolveProvider` | `(modelUri: string) => { provider: Provider, model: string }` | Resolves a `provider:model` URI to a `Provider` instance and stripped model name. Used by LLM scorers to obtain their provider | | `signal` | `AbortSignal?` | Forwarded from `RunEvalOptions.signal`. Scorers should pass this into provider calls so a long-running judge call gets aborted mid-flight when the eval is cancelled | ### `EvalComparison` Result from `evalCompare()` comparing a baseline and candidate eval run. | Field | Type | Description | |-------|------|-------------| | `baseline` | `{ id, metadata, runCount, partial? }` | Baseline run identity. `runCount` is the number of runs actually used in mean / regression / timing / cost computation — `evalCompare` truncates both sides to `min(baseline.length, candidate.length)` so the displayed means align with the paired bootstrap CI's sample. `partial` (an `EvalComparisonPartial`) is set when the pooled run count is less than the original batch's planned count | | `candidate` | `{ id, metadata, runCount, partial? }` | Candidate run identity. Same shape as `baseline` | | `scorers` | `Record` | Per-scorer mean comparison. `ci` is `{ lower: number; upper: number }` (95% bootstrap CI on paired differences). `significant` is `true` when the CI excludes zero and \|delta\| exceeds the threshold. `pRegression`/`pImprovement` are bootstrap probability estimates. `n` is the **paired sample size** — items scored on BOTH sides — always populated (incl. `0`/`1`); the CI/`significant` are computed only when `n >= 2`. Note the asymmetry: `delta` is the difference of the two **independent** per-side means (each over `{baseline,candidate}Scored` items), whereas the CI is paired over `n`, so when `n` is much smaller than the per-side scored counts the two rest on different samples (Studio's compare view surfaces a "paired n" note). `{baseline,candidate}{Scored,Failed}` are per-side success/failure counts over the **same truncated pool** the means/CI use (raw counts; consumer divides) — a non-zero `*Failed` means that side's mean rests on a thinned sample, and `axl-eval compare --max-scorer-error-rate` refuses to certify when over tolerance. `{baseline,candidate}Skipped` are per-side `applies`-skipped (N/A) counts — excluded from both the mean and the failure-rate denominator; when the two sides differ, the means cover different applicable subsets (the CLI prints an advisory `NOTE`) | | `timing` | `{ baselineMean, candidateMean, delta, deltaPercent }?` | Per-item duration comparison | | `cost` | `{ baselineTotal, candidateTotal, delta, deltaPercent }?` | Total cost comparison | | `regressions` | `EvalRegression[]` | Items that got worse | | `improvements` | `EvalImprovement[]` | Items that got better | | `summary` | `string` | Human-readable summary | ### `EvalComparisonPartial` Sample-size context for one side of a comparison. Set on `EvalComparison.baseline.partial` / `.candidate.partial` when the pooled runs reflect fewer than the original batch's planned count — either because the batch failed mid-way (`metadata.batchAttempted > runs.length`) or the user picked a subset from the comparison picker. | Field | Type | Description | |-------|------|-------------| | `completed` | `number` | Number of runs actually included in this side's pool | | `attempted` | `number` | Original planned run count (read from `metadata.batchAttempted` on any run in the pool) | ### `EvalRegression` / `EvalImprovement` Individual item that regressed or improved between runs. | Field | Type | Description | |-------|------|-------------| | `itemIndex` | `number` | Index into the items array for lookup | | `input` | `unknown` | The dataset input for this item | | `scorer` | `string` | Which scorer detected the change | | `baselineScore` | `number` | Score in the baseline run | | `candidateScore` | `number` | Score in the candidate run | | `delta` | `number` | Score difference (candidate - baseline) | ### `normalizeScorerResult(result)` Converts a scorer return value (`number | ScorerResult`) to a `ScorerResult`. Returns the input as-is if already a `ScorerResult`, or wraps a plain number as `{ score: result }`. ### `EvalCompareOptions` Options for `evalCompare()`. | Field | Type | Default | Description | |-------|------|---------|-------------| | `thresholds` | `Record \| number` | auto-calibrate | Minimum absolute delta to consider meaningful. A single number applies to all scorers. A per-scorer map allows different thresholds per scorer (scorers not in the map fall through to auto-calibration). Default: auto-calibrates from `scorerTypes` metadata — `0` for deterministic scorers, `0.05` for LLM scorers, `0.1` legacy fallback for results without metadata | ### `evalCompare(baseline, candidate, options?)` Compare baseline and candidate eval results to detect regressions and improvements. Both arguments accept `EvalResult | EvalResult[]` — passing arrays enables multi-run comparison, which pools per-item paired differences across runs for tighter bootstrap CIs. Throws if the datasets or scorer names don't match between baseline and candidate. ### `runtime.evalCompare(baseline, candidate, options?)` Convenience wrapper that dynamically imports `@axlsdk/eval` and calls `evalCompare()`. Accepts an optional `EvalCompareOptions` third parameter. ### `evaluateScorerErrorRateGate(comparison, maxScorerErrorRate)` Pure, side-effect-free decision for the gate-side scorer-failure-rate check (what `axl-eval compare --max-scorer-error-rate` runs). Returns a human-readable refusal reason `string`, or `null` to allow. Build your own CI gate on top of `evalCompare()` with it. - **Type-aware** via the baseline's `metadata.scorerTypes`: a scorer explicitly marked `'deterministic'` tolerates **zero** failures; everything else — including an unknown/missing type on a pre-`scorerTypes` artifact — uses the LLM `maxScorerErrorRate` (the permissive tier, so an old baseline isn't hard-failed on its first flake). - Also refuses when a scorer produced **zero scored items** on a side (a mean over an empty sample can't be certified). - Reads the per-side `scored`/`failed` counts on `EvalComparison.scorers[name]`, computed over the same truncated pool as the means/CI. ### `evaluateScorerTolerance(scored, failed, type, limit)` The single shared pure helper backing **both** failure-rate gates (source-side `runEval` and gate-side `evaluateScorerErrorRateGate`). Returns a `ScorerToleranceVerdict`: | Field | Type | Description | |-------|------|-------------| | `attempted` | `number` | `scored + failed` — the rate denominator (excludes cancelled / never-run) | | `rate` | `number` | `failed / attempted`, or `0` when nothing was attempted | | `exceeds` | `boolean` | Over tolerance AND something was attempted. Deterministic: `failed > 0`; LLM: `rate > limit` (strict) | | `zeroSample` | `boolean` | `attempted === 0` — no basis to certify a rate (callers choose their policy) | ### `BootstrapCIResult` Result from `pairedBootstrapCI()`. | Field | Type | Description | |-------|------|-------------| | `lower` | `number` | Lower bound of the confidence interval | | `upper` | `number` | Upper bound of the confidence interval | | `mean` | `number` | Mean of the original differences | | `pRegression` | `number` | Proportion of bootstrap resamples where mean difference < 0 (probability of regression) | | `pImprovement` | `number` | Proportion of bootstrap resamples where mean difference > 0 (probability of improvement) | ### `pairedBootstrapCI(differences, options?)` Compute a percentile-based bootstrap confidence interval on paired differences. Resamples with replacement and returns the CI bounds, sample mean, and probability estimates (`pRegression`/`pImprovement`). | Option | Type | Default | Description | |--------|------|---------|-------------| | `nResamples` | `number` | `1000` | Number of bootstrap resamples | | `alpha` | `number` | `0.05` | Significance level (0.05 = 95% CI) | | `seed` | `number` | — | Seed for xorshift32 PRNG. When provided, results are deterministic | ### `RescoreOptions` Options for `rescore()`. | Field | Type | Default | Description | |-------|------|---------|-------------| | `concurrency` | `number` | `5` | Maximum parallel item rescores | | `scorerConcurrency` | `number` | `5` | Maximum parallel scorers within a single item (see `EvalConfig.scorerConcurrency`) | | `signal` | `AbortSignal` | — | Cancels in-flight scorer LLM calls and short-circuits remaining items | ### `rescore(result, scorers, runtime, options?)` Re-run scorers on the saved outputs of an existing `EvalResult` without re-executing the workflow. Returns a new `EvalResult` with `rescored: true` and `originalId` set in metadata. Strips `runGroupId` and `runIndex` from inherited metadata (rescored results are independent evaluations). Only tracks scorer cost (no workflow cost). ### `MultiRunSummary` Result from `aggregateRuns()`. Computes mean +/- std of per-scorer means across multiple runs. | Field | Type | Description | |-------|------|-------------| | `runGroupId` | `string` | Shared group ID across runs | | `runCount` | `number` | Number of runs aggregated | | `workflows` | `string[]` | Union of workflow names observed across runs (deduped, first-seen order). Parallel to `EvalResult.metadata.workflows`. Homogeneous groups (`axl-eval --runs N`) typically have one entry; heterogeneous groups (custom callbacks) can have multiple | | `dataset` | `string` | Dataset name | | `totalCost` | `number` | Sum of all runs' costs | | `totalDuration` | `number` | Sum of all runs' durations (ms) | | `scorers` | `Record` | Per-scorer aggregate: mean of means, std across runs, min/max of means | | `timing` | `{ mean, std }?` | Timing aggregate across runs (present when all runs have timing data) | ### `aggregateRuns(runs)` Aggregate multiple `EvalResult[]` into a `MultiRunSummary` with mean +/- std per scorer. Throws if the array is empty. ### `scorerTypes` metadata convention `runEval()` automatically stores `scorerTypes: Record` in `EvalResult.metadata`. This metadata is used by `evalCompare()` to auto-calibrate regression thresholds: `0` for deterministic scorers (any change is meaningful) and `0.05` for LLM scorers (accounts for natural variance). Results without `scorerTypes` fall back to a `0.1` legacy threshold. ### `runEval(config, executeWorkflow, runtime, options?)` Run an evaluation. LLM scorer providers are auto-resolved from the runtime's provider registry using each scorer's `model` URI. No explicit provider export is needed from eval files -- ensure the relevant API key environment variable is set or register providers via `runtime.registerProvider()`. `RunEvalOptions`: | Option | Type | Default | Description | |--------|------|---------|-------------| | `onProgress` | `(event: EvalProgressEvent) => void` | — | Called synchronously on two events: `item_done` (after each dataset item finishes — success, failure, cancellation, or budget-exceeded) and `run_done` (once after all items finish and stats are computed). Useful for progress bars, live log streams, or WS broadcasts | | `signal` | `AbortSignal` | — | Checked before each item AND between scorers within an item. Remaining items are marked as cancelled in the result | | `captureTraces` | `boolean` | `false` | Wrap `executeWorkflow` in `runtime.trackExecution(..., { captureTraces: true })`. Per-item `EvalItem.traces` is populated on both success and failure (failure path reads the `axlCapturedTraces` side-channel on the thrown error) | `EvalProgressEvent`: ```typescript type EvalProgressEvent = | { type: 'item_done'; itemIndex: number; totalItems: number } | { type: 'run_done'; totalItems: number; failures: number }; ``` `run_done` fires once after the final `item_done` — use it to transition a progress UI from "processing items" to "computing stats" before the full `EvalResult` returns. The runtime surface (`runtime.runRegisteredEval` / `runtime.eval`) re-exports the same shape as `EvalProgressEventShape` from `@axlsdk/axl` so you can type callbacks without importing the optional `@axlsdk/eval` peer dep. **Type-guarded cost/metadata extraction.** When a custom `executeWorkflow` returns `{ output, cost, metadata }`, the runner validates the untrusted fields before accepting them: `cost` must be a non-negative finite number, `metadata` must be a plain object (rejects `Date`/`Map`/`Set`/`Error`/class instances). Invalid values trigger a `console.warn` and fall back to trace-derived values from `trackExecution`. Previously a buggy workflow returning `{ cost: 'free' }` could silently NaN-poison `totalCost`. --- ## Multi-Agent Decision Tree A guide for choosing the right primitive for multi-agent coordination: ``` START: I need to coordinate multiple agents | +-- Do I know WHICH agent to call? | +-- YES -> ctx.ask(agent, prompt) | | +-- Need structured output? -> { schema } | | +-- Need business rule validation? -> { schema, validate } | | | +-- NO, I need to pick from candidates | +-- The AGENT's LLM should decide (mid-conversation) -> Handoffs | | +-- Static candidate list -> handoffs: [{ agent, description }] | | +-- Context-dependent list -> handoffs: (ctx) => [...] | | +-- Transfer control permanently -> mode: 'oneway' | | +-- Get result back and continue -> mode: 'roundtrip' | | | +-- The WORKFLOW should decide (orchestration level) | -> ctx.delegate(agents, prompt, { schema, validate }) | +-- Do I need MULTIPLE agents working simultaneously? | +-- Same task, different perspectives -> ctx.spawn(n, fn) | | +-- Need to pick a winner? -> ctx.vote(results, { strategy }) | | | +-- Different items, same processing -> ctx.map(items, fn, { concurrency }) | | | +-- First-to-finish wins -> ctx.race(fns, { schema, validate }) | | | +-- Different tasks, need typed results -> ctx.parallel(fns) | +-- Do I need to VALIDATE and RETRY non-LLM operations? | +-- YES -> ctx.verify(fn, schema, { validate }) | +-- LLM can't satisfy rules? -> Wrap ctx.ask() in ctx.verify() | for programmatic repair via retry.parsed | +-- Do I need SEQUENTIAL agent stages? | +-- YES -> Sequential ctx.ask() calls (imperative TypeScript) | +-- Do I need an AGENT to orchestrate other agents? | +-- YES -> Agent-as-tool pattern: | +-- Define tools whose handlers call ctx.ask(subAgent, ...) | +-- Give those tools to the orchestrator agent | +-- Do I need COST CONTROL across the whole workflow? +-- YES -> Wrap with ctx.budget({ cost: '$10' }, fn) ```