ExAgent. Capability behaviour
(ExAgent v3.0.0)
View Source
The single extension point of an agent: a package of tools, settings and instructions plus optional hooks around each model request and tool call.
Stability — Stable.
A capability is a module or a configured struct. That value is passed as the
first argument to its callbacks, so configuration stays explicit without
global state. Every callback is optional: implement only the ones you need.
use ExAgent.Capability declares the behaviour and refuses, at compile time,
a module that still defines a 2.x hook (see "Migrating from 2.x").
Package
guardrails(cap)— a list ofExAgent.Guardrailor candidate classifier guards, in policy order. Like inventory, this declaration must be pure and stable. The runtime checks the effective value outside the mutable hook chain.tools(cap)— function tools the capability contributes.ExAgent.new/1resolves them once into the agent's inventory, after the agent's own:toolsand in capability order. An identical tool is kept once; another tool with the same name raisesArgumentError. Inventory tools are validated, authorized and persisted in continuations like any other tool. Keep it pure and cheap: each run checks that it is still in the inventory.settings(cap)— options ofExAgent.ModelSettings.new/1. In increasing precedence: capabilities (in list order), the agent's:model_settings, the run's:model_settingsand abefore_model_request/3hook.instructions(cap, ctx)—nil, a string or a list of strings, evaluated once per run attempt, before its first model request. They enter the request projection asExAgent.Message.Part.Systemparts after the instructions of its first request and the agent's instruction functions, never the history ornew_messages, so they are fresh in every run (and everyExAgent.Serverturn).
Hooks
before_* hooks run in list order; after_* and on_*_error hooks run in
reverse order, so the first capability wraps the others.
after_run(cap, terminal)— observes the finalExAgent.ResultorExAgent.RunErrorafter an admitted attempt closes, in reverse order. This includes a confirmed pause and each admitted resume. A delegated run invokes its own capabilities. Each callback runs in a fresh monitored process with a 250 ms timeout. Its$callerschain starts with the terminal owner. Pass other context in the capability or terminal. Returns are ignored. Timeouts, exceptions, throws and exits log a content-free warning and later observers still run. For slow work (database writes, HTTP), hand the terminal to a process you own, such as aGenServer.cast/2or aTask.Supervisorchild, and return. The stream consumer starts the observers after worker cleanup and before yielding its terminal, including a guardian-reported worker failure. Abandoning a stream without consuming its terminal skips them.before_model_request(cap, request, ctx)— receives anExAgent.ModelRequestand returns{:ok, request},{:skip, response}or{:error, reason}. Only:messages,:tools,:settingsand:modelare writable. Each request starts from the whole inventory and the run's settings, and from the model the previous request used (the struct carries its state).{:skip, response}answers the step instead of the model (see "Answering for the model").after_model_request(cap, response, request, ctx)— returns{:ok, response}or{:error, reason}. Only:partsmay change; the reported usage, finish reason and other fields are read-only.on_model_request_error(cap, reason, request, ctx)— runs after the failed request is closed, for a{:model_request_failed, %ExAgent.RequestError{}}failure. It returns{:error, reason}with the reason it received, or{:recover, response}to answer for the request. Guard reasons (deadline, limits, accounting, retention, cancellation, an incomplete finish) never reach it.before_tool_call(cap, call, ctx)— runs in the tool's task and returns{:ok, call},{:skip, {:deny, message}}or{:error, reason}. Only:argsmay change; the runtime validates the effective arguments against the schema and authorizes the effective call after every hook. A denial settles the call:deniedwithmessage(1 to 4096 bytes of UTF-8) for the model, without consultingExAgent.Permissions, the approver or the continuation, and runs nothing; durable runs record it as"capability_denied". A capability can add a denial, never an approval.after_tool_call(cap, tool_return, call, ctx)— runs after the outcome is confirmed and returns{:ok, tool_return}or{:error, reason}. Only the:contentof a:succeeded,:tool_erroror:validation_errorreturn may change; it is validated again as JSON.
ctx is the ExAgent.RunContext of the run (of the call, in tool hooks).
Answering for the model
{:skip, response} and {:recover, response} stop the chain: later hooks
of the same stage do not run. The response is validated as a final answer
of the model: ExAgent.Message.Part.Text parts only (a tool batch needs an
admitted request, and thinking without the provider's continuation is
foreign history the next provider request rejects), an explicit
:finish_reason of :stop, no :continuation, and a binary or nil :model_name.
The usage is the runtime's: a skip reports an explicit zero and makes no
request, so it adds no model telemetry, span or request count; a recovered
request keeps the usage it recorded (usage_status: :unknown when no
counts are known) and its accounting checks, so a usage that strict accounting or the
usage validation rejects fails the run as it would for a model's answer. The
answer carries usage: nil. It then follows the path of a model response:
after_model_request/4 hooks, which keep it text only, the history, output
validation and a :model_response stream element, without text deltas.
Neither is
supported in a durable run, which fails with {:unsupported, {:capability_skip, :continuation}} or {:unsupported, {:capability_recover, :continuation}} instead of persisting an answer no request produced.
Policy outside the chain
Hooks cannot widen authority. The runtime always applies, on the hooks'
output: immutable call identity and schema validation of effective
arguments; ExAgent.Permissions, ancestor policies and approvals after all
before_tool_call hooks; limits, deadline, concurrency and retention at
admission and before dispatch; and request.tools ⊆ request.inventory.
The history is append-only and the projection is validated as before.
Errors
{:error, reason}, an exception, a throw, an exit or an invalid return value
fails the run with {:capability_failed, module, hook, reason}, where
reason is the returned reason, the exception, {kind, value},
:invalid_return, {:read_only, field}, {:invalid_field, field} or
{:unknown_tool, name}; an invalid answer or denial is
{:invalid_field, field} too. A failure always closes its stage: before the model,
without IO; before a tool, with the call :not_executed and the run failing
after the batch; after a tool, keeping the confirmed effect. Stream
cancellation passes through every hook.
Example
defmodule MyApp.Guard do
use ExAgent.Capability
@impl true
def before_model_request(_cap, req, _ctx),
do: {:ok, %{req | messages: redact(req.messages)}}
@impl true
def before_tool_call(_cap, call, _ctx), do: {:ok, call}
end
ExAgent.new(model: model, capabilities: [ExAgent.Tool.Search.new(deferred: tools), MyApp.Guard])Migrating from 2.x
Rename before_tool_execute/3 to before_tool_call/3 and
after_tool_execute/4 to after_tool_call/4, read the request from
ExAgent.ModelRequest instead of the run state, return {:ok, value}, and
move tools injected by a hook into tools/1. After-hooks now run in reverse
order. use ExAgent.Capability raises CompileError for a module that
defines a 2.x hook, and ExAgent.new/1 raises ArgumentError for one that
exports it, so a 2.x hook never stays silently inert.
Summary
Types
Callbacks
@callback after_model_request( cap :: t(), ExAgent.Message.Response.t(), ExAgent.ModelRequest.t(), ExAgent.RunContext.t() ) :: {:ok, ExAgent.Message.Response.t()} | {:error, term()}
@callback after_run(cap :: t(), ExAgent.Result.t() | ExAgent.RunError.t()) :: term()
@callback after_tool_call( cap :: t(), ExAgent.Message.Part.ToolReturn.t(), ExAgent.Message.Part.ToolCall.t(), ExAgent.RunContext.t() ) :: {:ok, ExAgent.Message.Part.ToolReturn.t()} | {:error, term()}
@callback before_model_request( cap :: t(), ExAgent.ModelRequest.t(), ExAgent.RunContext.t() ) :: {:ok, ExAgent.ModelRequest.t()} | {:skip, ExAgent.Message.Response.t()} | {:error, term()}
@callback before_tool_call( cap :: t(), ExAgent.Message.Part.ToolCall.t(), ExAgent.RunContext.t() ) :: {:ok, ExAgent.Message.Part.ToolCall.t()} | {:skip, {:deny, String.t()}} | {:error, term()}
@callback guardrails(cap :: t()) :: [ ExAgent.Guardrail.t() | ExAgent.Classifier.guardrail() ]
@callback instructions(cap :: t(), ExAgent.RunContext.t()) :: nil | String.t() | [String.t()]
@callback on_model_request_error( cap :: t(), term(), ExAgent.ModelRequest.t(), ExAgent.RunContext.t() ) :: {:error, term()} | {:recover, ExAgent.Message.Response.t()}
@callback tools(cap :: t()) :: [ExAgent.Tool.t()]