Tools and model contracts for coding agents

View Source

ExAgent 3.0.0. Names are relative to ExAgent unless qualified. Usage means Message.Usage. Candidate APIs can change across releases. Run failures use %RunError{}. Provider admission and hosted-provider evidence are separate properties.

Tools, Toolset and execution controls

APIContract
use Tools, Tools.deftool/2 and Tools.deftool/3Defines a function plus a tool entry exposed by the host module's tools/0. The first parameter is RunContext. Remaining named parameters become JSON object properties. @doc supplies the trimmed description. Macro options are effect: :write | :read and requires_deferral: false | true. Invalid controls fail compilation.
Tools.tool_plain/2All parameters are tool arguments. Signature variables may be annotated with ::. Patterns and defaults require a manual schema or matching inside the body. A when guard remains an Elixir guard. A schema-valid call can still raise FunctionClauseError.
Tool.new/1Builds a manual tool from a keyword list. Unknown or duplicate options, invalid names and invalid execution controls raise ArgumentError. Tool.definition/1 projects %{name: name, description: description, parameters: schema}. Tool.validate_args/2 and Tool.validate_result/2 return {:ok, original} or {:error, [%{path: json_pointer, keyword: keyword, message: message}]}. Root pointer is "". Argument validation compares atom and string keys as JSON strings, rejects collisions, preserves the original representation, and applies neither coercion nor defaults. Result schema validation checks the JSON encoded by Jason, including encodable structs.
Tool.new/1 optionDefault and constraints
:name, :descriptionBoth nil. Constructor accepts a nil or nonempty name. Inventory requires a named tool, unique by final name, with the final_result prefix reserved. Use portable function names matching ^[A-Za-z_][A-Za-z0-9_-]{0,63}$, required for names produced by Toolset. Output branch names match ^[A-Za-z0-9_-]{1,64}$ and must avoid collisions.
:parameters_json_schema%{}. JSON Schema map or boolean. Invocation still requires a JSON object. MCP export requires an explicit object schema.
:result_schema, :result_modenil and :json. JSON Schema map or boolean runs after result hooks and before shortening/offload. :multimodal requires result_schema: nil.
:kind:function. Also accepts :output or :external. Ordinary application callbacks use :function.
:call, :takes_ctxnil and true. Callable arity 2 takes (ctx, args). Set takes_ctx: false for arity 1 (args). Invocation rejects a mismatched callback with {:invalid_tool_callable, name}.
:requires_approval, :requires_deferralBoth false and boolean. Approval composes with permission rules. Set requires_deferral: true for tools requiring a durable inbox, including timers. Volatile runs and Frame 10/11 leaves reject before effect intent. Root and delegated Frame 3 support deferrals, with migration 1 on PostgreSQL.
:effect, :reconcile:write and nil. Authorized recovery can repeat an uncertain :read. A context-aware write can supply a read-only fn key -> ... end or fn key, recorded_external_deferral_meta -> ... end returning {:confirmed, data} | :not_executed | :unknown. ctx.idempotency_key is assigned before dispatch and reused across attempts. The external service owns deduplication. Effect, deferral and reconciliation declarations enter the continuation binding.
:timeout, :concurrencynil inherits agent tool_timeout: 30_000 ms. Override with a positive integer. :parallel (default) groups adjacent calls and :exclusive waits for earlier calls and finishes before later ones. A paused call releases ordering within that attempt. Receipts preserve the model's call order.
:max_retries1, nonnegative integer. Consecutive retryable failures consume the tool budget. Zero fails on the first one. Success and confirmed domain errors reset it.
:max_heap_bytes (candidate)nil inherits the VM policy. Round down to BEAM words, bounded by the VM :min_heap_size and (1 <<< (word_bytes * 8 - 5)) - 1 words. GC enforces the task heap threshold and counts shared binaries. A task kill with no timer expiry evidence reports {:exit, :killed} and preserves observed confirmation. Native allocations, ETS and other tasks have independent lifecycles.
:reservation_cents (candidate)nil or a positive host quote before dispatch. Applies to the current tool definition. Output, delegate and CodeMode tools cannot use it. Report price via Usage.with_estimated_cost/2. Unknown or partial charge leaves the outstanding hold for reconciliation. Internally priced Media tools need no duplicate quote.
  • Toolset.prefix(tools, prefix) prepends the literal prefix including any separator. Toolset.rename(tools, %{old => new}) renames simultaneously. Toolset.filter(tools, selection) preserves order. Toolset.require_approval(tools, selection \\ :all) forces review even on :allow and survives renames. Explicit selections take a name list, {:except, names}, or an arity-one predicate. Unknown names, output tools, collisions and reserved names raise. MCP renames preserve remote identity. Permissions, Search, RepeatGuard, OutputLimit, eval and telemetry use the final names.
  • Derived schema Schema.from_type/1 supports integer(), non_neg_integer(), pos_integer(), byte() (0–255), literal ascending integer ranges, float(), number(), boolean(), Binary.t(), String.t(), binary(), string(), atom() (JSON string), map() (object), and nonempty literal atom-keyed object types with unique fields. Fields of those objects are required and additional properties are allowed. list(t)/[t] allow empty arrays, nonempty_list(t)/[t, ...] require one item, and list(), [], nonempty_list()/[...] leave items unconstrained. Literal unions become enum (atoms stringify except booleans and nil). Typed unions become anyOf. Untyped, any() and unresolved forms produce %{}. cursor :: String.t() | nil requires the key and permits null. For omission, leave the property out of a manual schema's required and use Map.get(args, "cursor", default).

  • max_concurrent_tools: positive_integer at run level overrides the agent's limit. Default group size is System.schedulers_online(). Slot wait consumes the run deadline. Admission (hooks, schema, permissions, synchronous approve:) and dispatched execution each have their own tool timeout capped by that deadline. Admission expiry is :not_executed with {:tool_admission_timeout, name}. Execution expiry is :unknown with {:tool_execution_failed, name, {:exit, :timeout}}. Approval raise/throw/exit records :not_executed and :tool_approval_failed. Resume uses current timeout, concurrency and heap controls. A stored run-level concurrency override remains effective unless superseded.
  • Validate offered tool definitions before effects. Invalid schemas give {:invalid_tool_schema, name, errors}. Schema-invalid args produce :validation_error with JSON pointers and skip invocation. Invalid rewrites by host hooks produce a fixed diagnostic. Regex backtracking exhaustion is indeterminate_pattern even inside not, anyOf and patternProperties. Unoffered tools give {:unknown_tool, name} with one correction, including a budget preserved on open durable workflow batches. Legacy batches opened with zero retain it. Durable schema diagnostics keep an ordered prefix and truncated count in at most 4,096 JSON bytes.
  • Post-decode retention measures uncompressed Erlang external terms. Defaults max_payload_bytes: 1_048_576 and max_history_bytes: 8_388_608, each 1 byte–64 MiB. Every call reserves its return before dispatch, including a 4 KiB usage allowance plus identity and omission overhead (about 4.5 KiB for short names/IDs). Admission may fail at :tool_return or :history. Prepared arguments are bounded again before decode. If a return exceeds the slot after execution, the receipt retains identity/outcome with payload_omitted and the run fails. Hook shortening cannot recover it. Retained binary slices in text/lists/plain maps are detached with equal slices sharing one copy per result. Custom structs and other processes control their own references.
  • LangChain 0.15.8 text adapter pattern uses LangChain.Function.execute(function, args, ctx.deps) with the existing parameter schema or FunctionParam.to_parameters_schema/1. Map async to :parallel or :exclusive, keep text from {:ok, text} or {:ok, text, processed}, and map a confirmed text error to {:tool_error, message}. Preserve the host review policy and handle multimodal, interruption and unconfirmed effects separately.

Closed tool result vocabulary

Callable returnReceipt and run
JSON-portable value, {:ok, value}, {:ok, value, %Usage{}}:succeeded, continues. Reset retry count. A declared schema mismatch gives a fixed :tool_error, preserving the effect and usage. The rejected value and JSV diagnostics stay host-side.
{:content, parts} or {:content, parts, %Usage{}}:succeeded with result_mode: :multimodal and a profile supporting image returns. See content contract below.
{:tool_error, message} or {:tool_error, message, %Usage{}}Confirmed :tool_error. Continues with a model-visible error and resets retries. Anthropic and Bedrock carry an error marker, Chat-compatible wire uses the text signal.
{:retry, message} or raise ExAgent.ModelRetry:validation_error, for corrections before any effect. Exhaustion is :tool_retries_exhausted. Messages must be UTF-8.
{:error, reason}:failed with fixed model notice “The tool failed.” Host error {:tool_execution_failed, name, reason}.
{:unknown, reason}, {:unknown, reason, %Usage{}}, exception/throw/exit or unconfirmed checkpoint, Server/Jobs delivery, memory write or MCP result:unknown with fixed “The tool did not return a confirmed result.” Host reconciles effect. The three-element form retains usage.
Invalid shape, bare :error, returned %ModelRetry{} (also in {:error, _}), malformed message or nonportable schema-free result:unknown with {:invalid_tool_result, name, :unsupported_return} or JSON errors for a nonportable value.
{:defer, meta} or {:defer, meta, kind: :external | :input}:deferred, default kind :external. Metadata is a JSON object up to 64 KiB visible to the host. Without supported C7 this produces :unknown and {:deferral_unsupported, name}. Timer variant {:defer, meta, kind: :timer, wake_at: utc_ms} (candidate) also admits automatic expiry.
  • Multimodal parts are string-keyed JSON maps with %{"type" => "text", "text" => text} or %{"type" => "image", "media_type" => mime, "data" => padded_base64} and at least one image. PNG, JPEG and WebP bytes must match their MIME signatures. Cap the tagged term at 1 MiB before base64 decode, including part overhead. General payload/history reservations also apply. A plain list/map success uses JSON text. Tool.Content retains the accepted parts for tool-output checks, actual result and C7. Events, transcript and telemetry use an image-count notice. Oversize OutputLimit replaces the content with that notice without text offload or truncation callback.
  • Domain errors still run applicable result hooks/guardrails, regardless of message text. Durable workflows retain effect receipts when checking/transforming a return fails and withhold unchecked content. Recovery of a confirmed raw result applies schema and OutputLimit, including offload, without rerunning host result hooks or on_truncate.

Tools guide · Durability guide

Structured output and validators

output_mode:Request, local acceptance and limits
:tool (default)output: :text (default) permits text with no output tool. A module, JSON object schema or Output.tool(schema, name: ..., description: ...) yields final_result for a single plain branch. A nonempty list can include distinct named branches and at most one :text. Defaults are final_result_<underscored_module_basename> or final_result_json in a union. A selected branch yields Result.output_name and the effective output_mode. Text has a nil branch.
:nativeOne map or Ecto module, no function/union. OpenAI Chat response_format and Responses text.format project non-strict schemas. Anthropic catalogue json.schema uses output_config.format with closed declared objects and reduced constraints. Enumerate objects and array items. Dynamic map keys, free-form object fields and multi-branch allOf are refused on Anthropic. Projection keeps scalar enums/consts and omits unsupported bounds, lengths, patterns, maxItems and minItems > 1. Caps 24 optional properties and 16 union nodes. Full local validation still applies. Gemini has no native mode. Constructor rejects unsupported profiles and keywords such as external identifiers, dialects, $ref and $defs. Wire refusals only affect admission when exposed by stock ReqLLM.
:promptedOne map or Ecto module. Adds a canonical JSON Schema system instruction after agent/capability instructions solely to the request. Adapter receives text mode. Entire answer or one Markdown fence must contain the JSON object. Leading/trailing explanatory text or invalid syntax yields correction. Works without native/tool support.
  • JSON Schema output takes an explicit type: "object" map (including when a draft 7 root reference resolves differently), maximum 65,536 compact JSON bytes per branch including escaping. Atom/string definition keys may not normalize to the same name. JSV supports local refs in draft 2020-12 (default) and draft 7, with fetching and executable casts disabled. ReqLLM tool/native transports use a reference-free subset. Results retain JSON types and recursively string keys. Omitted optional keys stay absent. Repeated keys, including escaped equivalents in nested objects, give uniqueKeys. Exact decimal/exponent checks prevent rounded floats from passing the wrong constraint. Integer tokens retain precision. minContains and maxContains count matching items in tools, previews and final values.
  • Ecto is optional ({:ecto, "~> 3.14 and >= 3.14.3"} for an Ecto consumer). Use embedded_schema and optionally changeset/2. JSON Schema checks first, so casts such as "7" into integer do not bypass the contract. Without changeset, scalars and embeds_one are required and missing embeds_many defaults to []. Child rules recurse. validate_required/2 advertises required keys even with defaults. Omitted optional keys preserve defaults and explicit null needs its own policy. {:map, :integer} projects dynamic keys with integer or null values, including inside arrays. Ecto.Enum advertises dumped integer/string values and casts to the atom. Recognized metadata on validate_change/4 can project constraints. Tightest number bounds win per keyword. Decimal bounds/choices remain exact in changesets. JSON Schema length counts codepoints, matched by count: :codepoints. validate_subset/3 on arrays projects items.enum using declared enum storage values and permits repetitions.
  • Invalid output uses output_retries: 1 by default. Zero fails the first invalid answer. Schema errors include pointer paths or Ecto paths such as ["items", 1, "name"]. Exhaustion names the schema and attempts with up to five validation paths. Server.chat/3 returns accepted Result.output inside {:ok, %Result{}}. Event/history projection uses Jason then Ecto embedded dump fallback under the payload bound. :run_finished may carry output_name.
  • :output_validators accepts ordered fn output, ctx -> ... end and {:pure, fn output -> ... end}. :ok accepts, {:ok, value} passes the replacement onward, {:retry, message} or raised ModelRetry spends the shared budget, {:error, reason} yields {:output_validation_failed, reason}. Other returns yield {:output_validation_failed, {:invalid_validator_result, _}}. Check deadline, limits and cancellation again after validators. A correction at the last step gives {:max_steps_exceeded, max_steps}. A pure declared chain on a direct durable Flow branch can certify a returned veto. Version its output_ref. Exceptions, malformed returns or context-aware validators do not certify one. Durable workflows reject validators with text/native path as {:unsupported, :output_validators_without_output_tool}.
  • Output.function(name, schema, fun, opts \\ []) adds an arity-two fun.(validated_output, ctx) after validators in tool mode. Option :description. {:ok, value} sets output and branch name. Retry uses the same budget. Failure is {:output_function_failed, name, reason}, including {:raised, message}/{:invalid_result, inspected}. Use pure or idempotent functions since a pre-checkpoint crash can repeat them. C7 requires exact JSON (string keys, no structs or non-JSON atoms) or {:output_not_persistable, name}. Final guardrails/evaluators see the transformed value. MCP.Server.agent_tool/2 infers outputSchema only for one map branch without transforms or validators. Supply result_schema: for transformed or union values.
  • {:output_partial, %{output: draft}} carries completed valid members from streamed text or the first identified output-tool branch/index. Map preview disables required recursively, so other constraints still constrain preview eligibility. Ecto preview casts partials. Caps per model request are 32 distinct updates, min(65_536, max_payload_bytes) retained bytes and 4,096 nonempty fragments. These are provisional content events independent of accepted output, history, journal and tool execution.
  • Frame 3 binds the schema, mode, branch kind and function marker, supports approvals in all three modes, and rejects a changed binding with :continuation_output_changed. A resumed run does not revalidate an already accepted output. Frame 10/11 require tool certification for map output. Native map and a map union allowing text give {:unsupported, :composition_json_output_without_tool}. A direct prompted step gives {:unsupported, :composition_request_projection} before opening/claiming. A loaded delegate is checked as soon as its definition is available.

Model reviewers

  • Judge.output_validator/1 (candidate) accepts model: and nonblank UTF-8 criteria:, optional model_settings:, max_transcript_bytes: 24_000 (minimum 1,024), on_error: :accept | :fail (default :accept). PASS accepts, FAIL contributes retry feedback. An unrecognized verdict retries with a formatting reminder and updated model state once. Subreviews inherit live scope accounting. C7 uses a separate scoped deadline and rejects any model request/token/cost/model-concurrency limit on the run or ancestor with {:output_validation_failed, {:judge_failed, :continuation_child_descriptor_required}} before reviewer IO. Deadline, usage/concurrency, strict accounting, cancellation, fixture misses and denied live review fail despite :accept.

  • Judge.approver/1 (candidate) accepts model: and nonblank UTF-8 policy:, optional model_settings:, timeout: 20_000 and arity-one escalate:. ALLOW/DENY are explicit and ASK or reviewer failure escalates (default deny). Arguments exceeding 8,192 encoded bytes or unusable JSON go straight to escalation with the original call. It consumes the tool's admission time and runs with separate usage. A denied live review or replay miss in a fixture fails with {:tool_approval_failed, name, {:exit, {:model_request_failed, %RequestError{provider: :fixture}}}}. Both constructors can take classifier: in place of model/settings/criteria or policy. The classifier receives conversation/answer or tool_name/args JSON, uses labels "allow", "deny" and optional "ask", and is unsupported in chat cassettes. The classifier output validator additionally needs a live execution scope and rejects C7.
  • Tool.Advisor.new/1 (candidate) requires :model plus optional name: "consult_advisor", description:, instructions:, model_settings: [], max_uses: 3, max_transcript_bytes: 32_000 (minimum 1,024) and timeout: 120_000 ms. Wrapper timeout is reviewer timeout + 5,000 ms. Tool schema requires string question. Bounded plain transcript excludes signed replay. Uses count per user message, including failed consultation and limit notices. Earlier calls in the batch reserve places even if later rejected. Timeout/failure yields a recoverable :tool_error notice. Live scoped child usage counts once against the parent. With C7, any own/ancestor request, token, cost or model-concurrency limit gives unavailable before reviewer IO. With only tool limits or deadline, independent consultation inherits deadline and contributes reported tool usage outside the durable request count.

Permissions, guardrails, capabilities, sandbox and large tool catalogues

Authorization and policy hooks

  • Permissions.new!(rules: [], default: :allow). Set default: :deny for an allowlist. Actions :allow | :ask | :deny. Rule {name_glob, action} or {name_glob, action, args: %{path => predicate}} (candidate). Permissions.decide/2 checks a name with empty args. decide/3 and match_rule/3 (candidate) use validated arguments. Last matching rule wins. Predicates in one rule are ANDed. Missing values skip the rule. Glob matches all bytes, including newlines, via * (zero or more) and ? (one). Nested selectors are lists of JSON-key strings. A supplied malformed structured operand for that tool denies the call.

  • Structured comparators (candidate) use {:command, argv_prefix} for complete literal argv words (list or ASCII space/tab separated string). Reject shell syntax, non-ASCII whitespace, zero-width space and BOM. Executable identity is literal. {:url, prefix} requires absolute HTTP(S), compares normalized origin including effective port and path segments. DNS/IPv4 normalization uses optional {:idna, "~> 8.0"}. Prefix disallows query/fragment. Collapse repeated slashes and dot segments including encoded dots. Reject credentials and ambiguous or encoded separators. The callable owns query, DNS and redirect handling. {:path, directory} expands the configured root and compares case-sensitive normalized absolute paths. Filesystem containment and symlinks belong to the callable. URL/path accept nonempty lists with all members required for :allow/:ask and any for :deny.
  • permissions: and approve: are run controls. Permissions see prepared, schema-valid normalized args. Reviewer edits go through the schema and each policy again and must preserve each winning rule. requires_approval: true forces :ask when policy otherwise grants execution. Missing callback denies synchronous :ask. Argument rules persist as C7 policy version 2. Model-provided tier or other labels cannot establish authority without checking the underlying trusted constraint.
Capability callback (all optional)Ordering, writable fields and result
tools(cap), settings(cap), instructions(cap, ctx), guardrails(cap)Identical tool entries deduplicate after agent tools. Same-name differences raise. Settings precedence is capability < agent < run < request hook. Instructions return nil/string/list once per attempt after agent instructions, only in the request projection. Guardrails kept in declaration order.
before_model_request(cap, %ModelRequest{}, ctx)List order, {:ok, req} | {:skip, response} | {:error, reason}. Writable messages, tools, settings, model only. Each request starts from the full inventory and current run settings. Offer only registered tools.
after_model_request(cap, response, request, ctx)Reverse order, {:ok, response} | {:error, reason}. Can alter response parts only. Finish, usage and continuation remain adapter-owned.
on_model_request_error(cap, reason, request, ctx)Reverse order, {:error, reason} | {:recover, response}. Skip/recovery response must be text-only with finish_reason: :stop and continuation: nil. Missing finish yields {:invalid_field, :finish_reason}. Skip makes zero requests with explicit zero usage. Recovery retains observed usage, accounting and usage_status: :partial. Post-hooks cannot add tool calls/thinking to either. C7 rejects {:unsupported, {:capability_skip, :continuation}} and {:unsupported, {:capability_recover, :continuation}}.
before_tool_call(cap, call, ctx)List order, {:ok, call} | {:skip, {:deny, message}} | {:error, reason}. Only args writable. A 1–4,096-byte denial yields :denied without dispatch or review. Root C7 reruns hooks after approval. A prepared Frame 10/11 call restores recorded effective args and skips preparation.
after_tool_call(cap, return, call, ctx)Reverse order, {:ok, return} | {:error, reason}. Can modify content on :succeeded, :tool_error and :validation_error after effect confirmation.
after_run(cap, terminal)Once per admitted attempt such as pause or resume, reverse order. Input is %Result{} or %RunError{}. No observer for a pre-admission stale ref. Leaf agents observe their own terminals. Lazy stream starts observers after worker cleanup. Each gets a fresh monitored process, owner-led :"$callers" and 250 ms. Failures log bounded categories, timeouts kill the observer, and its return does not change the terminal.
  • Hook error, exception, invalid return or read-only mutation gives {:capability_failed, module, hook, reason} with no dispatch before the corresponding boundary and any prior confirmation retained. instructions: also accepts arity-one functions returning nil/string/list of strings, in list order. Failure is {:capability_failed, ExAgent, :instructions, reason}. Dynamic instructions enter the persisted request, outside history. Frame 10/11 refuse request-only instruction functions.

Guardrails, receipts and C7 certification

ConstructorValue and stage
Guardrail.input/2Normalized new user text or multipart input once per logical run before model IO and before opening C7.
Guardrail.stream/3%{text: binary, commentary: binary} disjoint UTF-8 windows before release on both channels. max_bytes: 1024 (4–65,536), max_ms: 50 (1–1,000). Smallest declared limits apply to all checks. Timer starts at first retained text. Review the last short window, oversized deltas split on codepoint boundaries, and terminal text differing from released deltas is reviewed. Buffered text uses byte windows.
Guardrail.tool_input/2Normalized ToolCall after preparation/schema. Live before approval and after edits. Root C7 checks approved args prior to effect intent. Host callable retains its original key representation.
Guardrail.tool_output/2Effective confirmed ToolReturn before further model IO. Sees checked schema-bound business value before OutputLimit. For schema-free offload it sees preview/reference, and each reader page undergoes its own check.
Guardrail.output/2Accepted candidate after schema, validators and output function. Veto ends delivery without retry.
  • Check callbacks return :ok | {:tripwire, info} | {:error, reason}. info is nil or a content-free 1–64-character ASCII identifier using letters, digits, dots, underscores or hyphens, as are names. First non-:ok stops the chain. Error/exception/throw/exit/invalid return gives {:capability_failed, ExAgent.Guardrail, stage, reason}. Stream check failures use :guardrail_check_failed. A trip emits {:guardrail_tripped, %{step: step, name: name, stage: stage}} and a terminal error. Event and telemetry omit the checked content and diagnostic code.

  • Tool-output review withholds the return until verdict. Veto or unconfirmed review keeps receipt status/usage with content_withheld: true. Already-dispatched tasks can finish and closed admission marks waiting calls :not_executed. A trip discards the current window and leaves previously released text provisional. Missing provider terminal leaves cost unknown with observed usage partial. Live Server with guardrails advances history on accepted turns and retains failure effects in RunError.partial.
  • Root C7 binds all five stages with versioned :policy, ordered stages/names and stream limits. Persisted handoffs certify destination input and continue prior checks. Frame 3 delegated agents reject guardrails at :agent_continuation_delegate. Restrictions for tool guardrails plus durable delegation/custom rehydration use :agent_continuation_delegation/:agent_continuation_rehydrate_tools. Frame 10/11 certify tool guards through the journal and reject input/stream/final policies at :composition.
  • Classifier.guardrail/4 (candidate) uses ordered policy labels and allow:. Tool-stage and stream classifiers require input: projector. Stream accepts the same window controls, and each nonempty window may consume a model slot while the source stream is in flight. First disallowed label trips. Backend/deadline/limit failure withholds content. Live guards use scoped request/quota accounting. C7 needs host admission or an explicit classifier tool effect.
  • Tool.OutputLimit.new/1 (candidate) options max_bytes: 32_768 (minimum 256), keep: :head_tail | :head | :tail, tools: :all | [names] | {:except, names}, one of offload: {backend, handle} or on_truncate: fn %{tool_name: n, tool_call_id: id, content: value, bytes: bytes} -> hint_or_nil end (both default nil). Shortens success/domain errors on UTF-8 boundaries using text or encoded JSON. Fatal and retry results retain their normal path. UTF-8 hints fit whole or are dropped. Oversize multimodal becomes an image-count notice.

  • Set OutputLimit earlier in the capability list than hooks that need full schema-free returns. Without offload, an in-flight checkpoint may keep raw content. With offload, schema-free live results project before confirmation/hooks. Schema-bound results validate first. Raw journal, delegated output and externally supplied results can still retain original sources. Preview begins with [exagent-result ...] ref and byte count. An oversize preview falls back to just the header. If the header fails the slot, normal retention failure applies. Storage failure marks unavailable. Filter data in the producing callable.
  • Tool.ResultStore (candidate) reader tools use the current run ID, separate from other runs, children and turns. read_result(ref, offset, limit) returns UTF-8 text and next_offset, zero-based byte offsets and nil at EOF, max page 4,096 bytes. grep_result(ref, pattern, offset, limit, mode) scans at most 65,536 starting byte positions, 64 nonoverlapping offsets, literal UTF-8 1–256 bytes. mode: "regex" supports up to 16 nonempty literal alternatives and takes the longest at the first matching position. Continue from next_offset even on an empty page. Foreign/evicted/expired refs share the recoverable missing result response.
  • Tool.ResultStore.ETS.start_link/1 (candidate) local owner, optional name:, defaults 8 MiB, 256 entries, 300,000 ms TTL (max 4,294,967,295 ms). FIFO eviction and owner restart remove refs. Tool.ResultStore.Postgres.new(repo, scope: scope, ...) (candidate) same quota defaults, trusted scope, migration 1 creates exagent_tool_results. Writers in that scope share quotas and should use identical settings. SQL admission is READ COMMITTED, FIFO and DB-clock TTL. Duplicate ref returns {:error, :unavailable} preserving old data. Quota failure rolls back insertion. DB read failure differs from expiration. cleanup_expired(repo, limit) and delete_run(handle, run_id, limit) take 1–1,000 rows, return {:ok, count} | {:error, :unavailable} and skip locked rows. Erase abandoned data after its writers stop.

  • Tool.RepeatGuard.new/1 (candidate) accepts warn_at: 3, tools: :all or name inclusion/exclusion. Counts identical calls (same tool and args) since last user turn. Adds a request-only reminder at the configured repetition threshold. Exclude polling and put it after compaction. It leaves permissions, history and events intact.
  • Tool.Search.new/1 (candidate) requires a nonempty deferred: list of uniquely named function tools. Defaults name: "search_tools", max_results: 5 (1–50), mode: :load. Exact names separated by spaces/commas or ranked keyword terms from name/description/top-level parameters. A miss suggests up to 200 names. Load requests add matched tools from the next step, in history order, while inventory retains all. If a success is shortened, Search can replay its recorded query against the current catalogue. Place Search before compaction and request restriction hooks after Search. Avoid using skill gates for the same tools. Hiding tools does not grant or revoke permissions.
  • Search mode: :bridge (candidate) exposes fixed search_tools, describe_tool and call_tool. describe_tool returns name/description/parameters. call_tool takes %{"name" => n, "arguments" => args} under the outer mandatory wire envelope. Selected tool schema, rules, approval names and C7 identity apply. Reserve bridge names and start in bridge mode to keep the prefix fixed from the first request.

Tool programs and isolated execution

  • Tool.CodeMode.new/1 (candidate) needs distinct tools: [names]. Defaults name: "run_tool_program", max_calls: 8 (1–32), timeout: 5_000 ms per admission/execution, max_heap_bytes: 8_388_608. Exclusive wrapper accepts %{"calls" => [%{"tool" => name, "args" => args, "bindings" => bindings}]} with optional nested bindings for unset args. A leaf is [earlier_zero_based_step, optional_string_keys_or_zero_based_indices...]. Preflight all bindings and enrolled, directly offered ordinary JSON functions before effects. Deferred bridge dispatcher and declared deferral tools are ineligible.
  • Each step uses ordinary hooks, schemas, guardrails, budgets and sync approval. Wrapper uses one tool slot plus one per admitted step. First failure stops the sequence. Missing path/denial/retryable step rejection yields a step-specific tool error. Unexpected deferral after dispatch fails with an unknown outcome. The nested deadline caps each step and combined retained binding values share the wrapper's return slot (external term bytes). Release values after last use. Overflow is {:retention_limit_exceeded, %{boundary: :tool_program, bytes: bytes, limit: limit}}. Only the last accepted result returns to the model.
  • CodeMode nested receipts carry call_ref, program_call_ref, one-based program_step/step and effect. RunError.confirmed_program_steps keeps observed confirmations including withheld output. The transcript carries the wrapper call/return. C7 refuses CodeMode with {:unsupported, {:code_mode, :continuation}}. Expose ordinary tools across rounds for durable per-effect admissions.
  • Sandbox.new/1 and Sandbox.tools(sandbox, opts \\ []) (candidate). Bind host backend: {module, config}, nonempty scope:, string-keyed identity: %{"id" => id, "version" => version}, optional read-only absolute host mounts at unique /inputs/name, network: :none and limits:. Code max 65,536 bytes. Limits default/range are cpu_millicores: 500 / 10..4000, memory_bytes: 134_217_728 / 16_777_216..4_294_967_296, time_ms: 10_000 / 10..900_000, processes: 32 / 2..256, output_bytes: 16_384 / 1..65_536, capture_bytes: 262_144 / 1..524_288, scratch_bytes: 16_777_216 / 1_048_576..134_217_728. Host chooses all limits/mounts.
  • sandbox_execute forces approval. sandbox_read returns bounded merged UTF-8 output. model: adds sandbox_capture for image tool returns, with active profile checked at call time. Docker runner reads regular PNG at /tmp/capture.png. jobs: adds approved sandbox_start for a same-scope Jobs owner, returns "submitted" and operation_id used as job ID. Jobs keeps the receipt and sandbox keeps the output. Cancellation of the job and adapter execution have separate lifecycles. Confirmations carry operation_id, status, exit_code, truncated. Confirmed "timed_out"/"output_limit" use null exit codes. Local defaults four running, 64 retained, ten-minute retention.
  • Sandbox reserves operation ID before dispatch. Sandbox.new_id/0 makes a fresh ID for execute/3. read/2, capture/2, destroy/2 operate on the same handle and operation ID. Reservation, unavailable lookup and uncertain outcomes use {:operation_exists, id}, {:unavailable, id}, {:result_unconfirmed, id} respectively inside {:error, ...}. Mutation lost acknowledgements become :unknown. Queries give fixed :tool_error messages and each takes at most 5,000 ms or half the remaining tool budget. Retained reservation is volatile unless the host supplies a durable backend.
  • C7 effect ID equals sandbox operation ID. Identity/version binds executor, scope, mounts and limits. retry_effect/4 cannot repeat a sandbox operation. Reconcile execution against authoritative receipt with matching ID (drop "text" from a read result). Reconcile sandbox_start against original Jobs admission. Missing evidence leaves uncertainty. Durable Jobs can wrap a C7 sandbox call.
  • Docker uses Linux UID/GID 65534, dropped capabilities, no-new-privileges, no network, read-only root and binds, cgroups for CPU/memory/swap/PIDs and sized tmpfs. Guest and host CLI have separate wall/output bounds and logging is disabled. Host daemon/socket, image and shared kernel are trusted. Mount contents may be printed, so authenticate scopes and curate inputs. Startup {:error, :docker_unavailable} calls for verifying local socket access, docker info platform/controllers (linux true true true true), installed image sha256: ID, no declared volumes and /usr/local/bin/python3. Bind directories need search permission as viewed by mapped guest identity. Cleanup labels io.exagent.sandbox.operation and private exagent-sandbox-* directories identify residuals after daemon/VM loss.

Tool control and sandbox recipes · Event and trace contracts

Memory, skills, plan and workspace

Memory

APIContract
Memory.tool(backend, opts)Required trusted scope: string (1–200 bytes) or arity-one selector receiving RunContext. Default name: "memory", optional description:, read_only: false, overwrite_on_create: true, max_file_bytes: 32_000, max_total_bytes: 128_000 and max_files: 100. Scope function failures are {:memory_scope_failed, exception_module | :throw | :exit} before access. Read-only offers only view and ignores the overwrite switch.
Memory.capability(backend, opts)Same options plus preload: false | true | [mode: mode, max_bytes: bytes, priority_paths: paths]. True or mode: :data attaches an exagent.memory block to the active user turn. mode: :system requires read-only operator scope. Once per attempt before first fresh request, including approval resume and destination handoff. C7 saves the projected request and fixtures can capture it. Frame 10/11 reject preload with {:unsupported, :composition_request_projection}.
Memory.preload(backend, scope, opts \\ []){:ok, text} | {:error, reason}. max_bytes: 8_000 covers framing, escapes, listings and notices for both forms of preload. Visit priority_paths: [] in given order (skip missing/directory, reject normalized duplicates), then remaining paths in path order. At first oversized file switch to listing paths. Returns {:ok, ""} if framing/notice cannot fit. Fix a reviewed block in a versioned agent definition to keep it stable through pause.
Memory.files/2, Memory.update/3, Memory.clear/2Host reads {:ok, files} or error. Update callback takes file map and returns {:ok, replacement} | {:error, reason}. Only returned {:error, :conflict} retries, maximum eight attempts. Compare the reviewed digest inside the callback and return {:error, :stale} on change. Callbacks may run repeatedly and host edits bypass tool quotas.
Memory.load/2, store/4, validate/1, erase_scope/2 (candidate callback)Backend callbacks. Load returns {:ok, version, files} and uses {:ok, 0, %{}} for absence. Compare-and-swap store returns a fresh positive version even for identical files, or 0 when an empty scope is left absent. Versions cannot be reused after deletion. validate/1 and erase_scope/2 are optional. Erasure requires quiescent writers and returns Retention.outcome() or error.
  • Commands under /memories are view(path, view_range?), create(path, file_text), str_replace(path, old_str, new_str), insert(path, insert_line, insert_text), delete(path) and rename(old_path, new_path). Paths up to 255 bytes, segments up to 100 bytes. Ranged views are one-based, first line must exist, end may exceed length, -1 means through EOF. Insert line 0 prepends, and insert scans bytes and preserves existing line endings. Replacement requires exactly one match counting overlaps. Ambiguity reports count and up to ten locations. Check insertion/replacement growth before assembly. A scope above quota accepts non-growing changes. Edits serialize and survive failed runs. overwrite_on_create: false makes creation exclusive even after retries, including existing empty files. A normal create can overwrite concurrent changes.
  • :ets means {Memory.ETS, Memory.ETS}, with scope versions protecting against a stale writer after owner replacement. PostgreSQL takes configured backend {Memory.Postgres, ...} and migration 1. SQL reads/writes suppress query telemetry and logs. [:exagent, :memory, :command] carries count 1 and command/status only. PostgreSQL rejects an unrepresentable expected bigint as :conflict after config validation, before encoding or SQL.
  • Invalid tool commands and unavailable reads yield confirmed :tool_error. A scope error in preload yields {:capability_failed, ExAgent.Memory.Capability, hook, {:throw, {:memory_scope_failed, kind}}} with hook :preload or :instructions. Backend preload failure emits %{command: :preload, status: :unavailable} and supplies a bounded notice when possible. Host callback throws return {:error, {:memory_backend_throw, term}} and malformed store replies {:error, :invalid_memory_backend_result}. An unconfirmed tool write yields :unknown with :memory_write_unconfirmed inside :tool_execution_failed. Confirm using effect-specific evidence if reads could show stale or identical content.

Skills and request projection

  • Skills.from_dir(root, opts \\ []) returns {:ok, skills} or error. Skills.from_dir!/2 raises ArgumentError on error. Discover sorted immediate visible subdirectories with SKILL.md. Any invalid skill rejects the catalogue. tools: %{skill_name => [tools]} keys by normalized frontmatter name, including names different from directories. Unknown keys give {:unknown_skill_tools, names}. Unreadable root gives {:invalid_skills_dir, root, reason}. Skill.from_dir/1,2 and Skill.parse/1,2 parse UTF-8 metadata/body. Skill.new/1 supports in-code content. A directory file with an invalid body may give {:invalid_skill, path, :missing_content}.
  • Name NFKC normalization, 1–64 codepoints, Unicode letters/numbers, lowercase cased letters and single internal hyphens. Duplicates after normalization collide. Description up to 1,024 characters. Required YAML name/description must use supported values. Other fields are best effort and allowed-tools is informational. SKILL.md body reloads on each invocation while catalogue changes require agent rebuild. Keep skills as trusted host instructions. Skill loading never runs its scripts.
  • Skills.tools/2 and Skills.capabilities/2 have only max_file_bytes: 262_144, a positive byte limit for the loaded instructions and each reference file. File listing/wrapper/tool names are additional. load_skill returns instructions and up to 200 file paths. Traversal examines up to 2,000 visible entries and descends up to eight directories. A truncated traversal adds (list truncated) even when no path was found. read_skill_file is supplied for directory-backed skills. It can read an omitted listed candidate by relative path. Reject absolute paths, hidden components, escapes through ../symlinks, non-UTF-8 and oversized files as correctable domain :tool_error without spending tool retries.
  • :skills installs Skills.Gate before application request hooks and Skills.Restore after them. Manual Skills.capabilities(skills, opts) returns %{gate: gate, restore: restore} for ordering around compaction. A skill tool stays in the inventory but is unavailable until successful load. Identical copies in :tools are also gated, different same-name tools and load_skill/read_skill_file name collisions raise. Later hooks can narrow or expand offered registered tools, so keep authorization in Permissions. An unavailable call receives ordinary {:unknown_tool, name} correction. Skills.loaded(messages) lists successful loads once in most-recent-load order, using call IDs to join parallel calls with returns.
  • Loads are ordinary history returns and survive subsequent turns/snapshots/C7. If compaction removes a load from the request, Restore inserts a user-level message with the recorded instructions after leading instructions-only messages, before the first combined instruction/prompt when applicable. It uses the recorded body, not an edited file, until another load. This request-only projection happens after compaction threshold evaluation.

Plan and workspace (candidate)

  • Plan.capability/1 adds write_todos and Result.plan. Replace the whole checklist with unique stable item IDs and pending/in_progress/completed statuses. Empty clears. Defaults max_items: 32 and max_bytes: 8192 compact JSON (ranges 1–128 and 1–32,768). Request-only final-user reminder preserves signed prefix, history keeps call plus short ack. Fresh runs start fresh plans and workflow nodes own their own list. C7 re-derives per-request plan from confirmed effective args and checks the projection against journaled requests. Denials preserve the previous list. An approved edit uses {:approve, args: %{"items" => items}} where request.decisions includes :edit. Prepared Frame 10/11 steps with input guards or tool-preparation hooks only offer approval/denial of the saved args.
  • Workspace.capability/1 mounts 1–32 {"/name", backend, :read_only | :read_write} tuples, default {"/scratch", :scratch, :read_write}. Paths are absolute virtual paths under one mount, with single slashes and no trailing slash, dot segments or hidden names. Options default/max are max_file_bytes: 32_768/1_048_576, max_total_bytes: 131_072/8_388_608, max_entries: 128/1024, max_results: 32/128. Minima 1. Limits count hidden/unlisted POSIX entries. Grep bounds backend reads by remaining byte budget and gives :scan_limit when an additional file exceeds it.

  • Workspace tools ls(path) (use "/" to discover mounts) returns sorted direct child paths. read_file(path, offset?, limit?) returns UTF-8 text and next_offset (nil at EOF), page limit 4–4,096 bytes. write_file(path, text) replaces file. edit_file(path, old, new) replaces exactly one occurrence, counting overlaps, and a concurrent change conflicts. Both mutations run exclusively. glob(path, pattern) matches descendant basenames with at most one *. grep(path, pattern) searches a literal. Listings/searches return paths and truncated. Scans over the entry cap fail explicitly.
  • Scratch lives in private run-node ETS, released at scope close. Scratch and Memory mounts make implicit directories. Workspace.memory(backend, scope) loads/validates the full host scope before workspace bounds. Workspace.results(store) is read-only and resolves known /results/<ref> in the originating run within file-size limits. It has no listing. The store owns TTL and PostgreSQL scope identity. C7 reconstructs plan/scratch from confirmed effective args in recorded order, detects an earlier pending update superseded by a later one, and never replays external writes.
  • Workspace.directory(root) binds a pre-existing POSIX root's device/inode. Rechecks root identity and File.lstat/2 components. Accepts singly linked regular files. Host owns root, ancestors and contents. Hostile concurrent namespace swaps leave a TOCTOU window. Writers must honor .exagent-write-lock, verify expected text and quota under lock, close an exclusive private temp and atomically rename. On abrupt owner death, inspect destination and remove stale lock/temp only after verifying quiescence. Directory listing can materialize one directory before enforcing the scan cap. Casefold aliases count once using the resolved destination's size. All workspace backends use ordinary tool authorization/effect receipts. Unacknowledged writes require reconciliation and stable host mount bindings. Custom backends implement Workspace.Backend.

Memory guide · Skills guide

Models, provider profiles and wire contracts

Model.resolve/2 resolves the adapter and Model.profile/1 describes admitted feature sets. Models.ReqLLM.new/1 uses official stock ReqLLM generate_text/3, stream_text/3 and ReqLLM.StreamResponse.process_stream/2. Local resolution does no request IO. Pass a catalogue string, LLMDB.Model or explicit map/stock model spec. Keep provider, id, capabilities, modalities, limits, cost and extra.wire.protocol true to the deployed backend. Local resolution or declaration alone gives no compatibility/price evidence.

Concrete profileResolutionTools/streamNative schemaReasoning
:chat_tools_v1:openai wire "openai_chat"YesYes:disabled
:chat_tools_v1:ollama, :lmstudio, :vllm, :groq, :deepseek, :mistral, :xai Chat CompletionsYes, loopback evidenceNo:disabled
:chat_tools_v1:azure Chat Completions incl. catalogue "openai_completion"Yes, loopback evidenceNo:disabled
:openrouter_chat_tools_v1:openrouter ChatYesNoBoth
:openai_responses_v1:openai or :azure wire "openai_responses"Yes (Azure loopback)YesBoth
:anthropic_messages_v1:anthropic MessagesYesCatalogue json.schemaBoth
:anthropic_messages_v1:google_vertex Claude rawPredict or :amazon_bedrock Claude InvokeModel with catalogue toolsYes, loopback evidenceNoBoth
:gemini_v1:google Gemini API or :google_vertex Gemini generateContentYes (Vertex loopback)NoBoth
:text_v1Any other route, :openai with no wire, Cerebras, Bedrock Converse, or explicit downgradeBuffered textNoCatalogue default
  • profile: :auto selects via ReqLLM-resolved wire/default. Explicit profile must equal the selected one or be :text_v1. Stock puts o-series, GPT-4o, GPT-4.1, GPT-5 and later on Responses for the corresponding resolved IDs. Tools require tools.enabled except for unlisted local Ollama/LM Studio/vLLM IDs. Chat rejects catalogue tools.strict. ModelSpec resolves those local IDs silently via stock inline specs, preserves existing catalogue metadata and stores a resolved LLMDB.Model on the instance. Use Model.model_name/1 for the ID. Ollama endpoint defaults to http://localhost:11434/v1. Local models use tool/prompted output. All profiles receive prompted output as text with a request instruction.
  • Cerebras stays text-only because stock ReqLLM 1.31.0 strips wrapped constraints, including minimum on buffered/SSE. Bedrock Converse stock merges distinct IDs with identical args and loses server_tool_use ownership in buffered/chunk data. Tool requests reject before IO. Bedrock Claude InvokeModel retains IDs in loopback including AWS EventStream and ETS/SQL approval resume. Buffered/SSE normalization still hides wire duplicate keys there. Hosted Azure/Vertex/Bedrock and additional local/Chat routes need endpoint qualification. Tests of sample routes describe that deployment and SDK version.
  • Models.ReqLLM.new/1 keys model: (required), profile: :auto, api_key: nil, auth_token: nil, base_url: nil (HTTP(S), no userinfo), reasoning_mode: nil (derived), reasoning_effort: nil, total_timeout: 120_000 ms (1–300,000), foreign_history: :reject, prompt_cache: nil, service_tier: nil (candidate), provider_options: [], http_options: []. http_options allows :receive_timeout and a trusted :adapter for buffered transport. Reject nonempty provider defaults in app config or model extra as {:unsupported_options, :provider_defaults} before IO/C7 binding.
  • ModelSettings.new/1 takes map/keyword/struct with max_tokens (positive integer), temperature, top_p, presence_penalty, frequency_penalty (numbers), timeout (positive ms or :infinity) and extra (map/keyword). Defaults nil except extra: %{}, with non-nil overrides and shallow extra merge. ReqLLM rejects nonempty extra and profile-incompatible controls. Receive inactivity precedence is request timeout, http_options[:receive_timeout], 60,000 ms capped by run deadline. Stock pool checkout defaults derive from receive timeout. ExAgent owns a linked model worker under the minimum of operation/run deadlines. Stock total timeout is disabled inside it. Streaming requires a tool profile and no injected HTTP adapter, max_tokens: 4096 by default, range 1–4,096. Post-decode cap 4,096 public chunks, 65,536 external-term bytes/chunk and 1,048,576 total. Halt, deadline, exception and owner death close backend and owned work. Pre-decode allocations remain with stock.
  • ExAgent.new(model: "provider:id") makes environment mode for a model without explicit credentials, resolving through ReqLLM.Keys each request (app config then provider env). Models.ReqLLM.new/1 and Model.resolve/2 with credentials use instance mode. Anthropic auth_token: OAuth overrides api_key:. Ollama is key-free, LM Studio uses LMSTUDIO_API_KEY and vLLM OPENAI_API_KEY through stock. Missing required key before IO gives {:model_request_failed, %RequestError{reason: :missing_credentials}} naming the env variable in body. Never persist live adapter credentials. Persisted identity includes effective endpoint even when inherited. Rotate credentials within the same trusted account/scope and requalify metadata/route changes. Library lock does not pin consumer req_llm/llm_db versions.
Cloud routeIdentity and options
AzureEnv AZURE_OPENAI_BASE_URL/AZURE_OPENAI_API_KEY with AZURE_BASE_URL/AZURE_API_KEY fallbacks. provider_options: [deployment: name, api_version: version] as needed. Use Azure v1 or Foundry endpoint for named Responses deployment. Pass api_key: "Bearer " <> token for Entra. Effective resource/deployment/API version enter binding.
Vertex AIADC or auth_token: oauth_access_token and provider_options: [project_id: project, region: region]. GOOGLE_CLOUD_PROJECT/GOOGLE_CLOUD_REGION and :req_llm, :google_vertex config for project, region, access token or service account JSON. Default region "global". Identity binds project/region/API model.
BedrockEnv AWS_BEARER_TOKEN_BEDROCK, AWS_REGION default "us-east-1". Explicit key requires provider_options: [region: region] (lowercase ASCII alphanumeric/hyphens, initial alphanumeric, 1–63 chars). Constructor raises for missing/invalid region. InvokeModel binds runtime path, region and model ID. Vertex and Bedrock reject request retry keys with {:unsupported, :idempotency_transport} because streaming transport drops custom headers.

Mandatory tool argument envelope

  1. Each ReqLLM tool schema is wrapped as %{"type" => "object", "properties" => %{"arguments" => inner}, "required" => ["arguments"], "additionalProperties" => false}. The request includes a backend-only instruction. Caller shape is exactly {"arguments": {...}}, including {"arguments": {}} for no args. Default %{} parameter schema accepts any inner object. Explicitly close a zero-arg schema to forbid its keys. ReqLLM requires an object/boolean schema root and its reference-free subset. Logical schema and offered-name checks follow envelope admission.
  2. Complete objects with unique observable keys and no stock error can be corrected if any call fails the envelope shape. Invalidate the entire batch before hooks, permissions, approval or tool/output effects. Return one Part.Retry per call instructing the model to resend every call with the exact envelope. Charge once per distinct function tool name against its max_retries (ordinary unknown-name budget for unoffered name). If any output tool is present charge one output_retries instead. Retry uses another model step and normal request/usage limits. Live and Frame 3 (including delegates) can record and resume the correction without tool intent. Frame 10/11 rejects immediately.
  3. exagent.arguments/1 is the normal per-call codec. exagent.raw_arguments/1 marks a malformed-shape call in metadata["arguments_codec"] and replays the original object shape without wrapping it. Correct siblings keep their own codec. JSON history and v5 continuation preserve both. Older readers cannot replay the raw codec. Loopback exercised hosted-protocol replay. Hosted provider acceptance remains separate.
  4. Truncated/unreadable JSON, nonobject root, visible duplicate keys including escaped equivalents, stock error/invalid_arguments metadata, exhausted/zero retry budget or Frame 10/11 rejection return {:model_request_failed, %RequestError{reason: :invalid_tool_arguments}}. The fatal request emits [:exagent, :model, :request, :exception] before on_model_request_error/4. Live recovery is text-only per capability rules. C7 refuses hook recovery. In stock 1.31.0 only buffered OpenAI/Azure Responses preserves the original argument bytes on qualified routes. Other routes, including Responses SSE, normalize arguments and fixtures observed first-key retention upstream. The host cannot reject a duplicate that stock removed.
  5. strict: false default. Responses qualifies strict mode when every object explicitly closes additionalProperties: false and declares every property required, including empty object schemas. Required nullable replaces omission when suitable. Strict subset type, properties, required, additionalProperties, items, anyOf, enum, minItems/maxItems, numeric bounds, pattern, description, title. Across the wrapped schema, max 5,000 properties, 10 nesting levels, 1,000 enum values and 120,000 characters of property names/enum strings. One enum over 250 entries may total up to 15,000 string characters. Exceeding a strict bound keeps non-strict wire and local checks.

Reasoning, history, caching and tiers

  • reasoning_mode is stored as :disabled when advertised off is available or reasoning absent, :enabled otherwise. Constructor rejects unsupported modes. Disabled sends the off control where declared and can still receive thinking. reasoning_effort requires enabled plus a supported catalogue string "minimal"/"low"/"medium"/"high"/"xhigh"/"max" with Gemini's narrower set. Reasoning can consume the output token budget.
  • Chat keeps unsigned plain text as Part.Thinking and sends provisional {:thinking_delta, text} on streaming. Replay omits it and rejects explicit reasoning_details or opaque/signed blocks. Derived unsigned SSE detail can describe the same text. OpenAI reasoning Chat uses reasoning_effort: "none", max_completion_tokens 1–4,096 (default 4,096), nil temperature. DeepSeek uses thinking.type: disabled for reasoning models. Use buffered text profile where required reasoning cannot be disabled.
  • OpenAI Responses uses store: false, include: ["reasoning.encrypted_content"] and no previous_response_id. Replays encrypted reasoning locally. max_completion_tokens at least 16. Reject sampling parameters and penalties. Only provider completed authorizes completion. failed→:error, cancelled→:cancelled, other noncompleted success finishes→:incomplete. provider_options[:reasoning_summary] (candidate) accepts :auto/:concise/:detailed or matching strings in enabled mode outside the C7 binding.
  • Responses Part.Text.phase :commentary | :final_answer | nil. Commentary reported on its own stream channel, answer text drives Message.Response.text/1, output, previews and validation. A narration-only completed response advances within limits. Buffered progress emits a commentary delta per accepted part. ReqLLM late phase metadata can restore phase at terminal while earlier unlabelled SSE deltas appear provisionally as text. Buffered stock can collapse identical adjacent commentary/final into the final answer. Native history replays labels, portable foreign history drops commentary. Usage includes both.

  • Anthropic Messages replays signed thinking and redacted_thinking byte-for-byte with matching tool_use.input. Enabled thinking forces auto tool choice and output retries enforce required output. Fixed thinking budget beyond max_tokens gives {:unsupported, :thinking_budget}. Direct Messages options anthropic_version: "2023-06-01" and stop_sequences:. Text profile also admits :anthropic_top_k and :store, subject to adapter validation.
  • Gemini preserves signatures on each thought/text/function part. Changed/missing bound signature gives :invalid_history. Edited thought/text content loses its signature and unsigned thought is omitted. First function call must be signed in enabled mode, stock supplies its placeholder on the other parallel/portable calls. Call IDs aren't replayed on Gemini. Keep parallel result order to avoid stock 1.31.0 misassociation. reasoning_effort maps to Gemini 3 thinkingLevel or a 2.5 budget, only supported catalogue levels among minimal/low/medium/high, default allowed set low/medium/high if none listed. Only wire STOP admits tool/output. Missing finish or blocked prompt with no candidates maps incomplete. A named choice uses ANY/allowedFunctionNames. Penalties reject, stock removes additionalProperties from declarations and local validation still checks.
  • OpenRouter enabled replays reasoning_details unchanged and requests auto tool choice. Disabled reasoning needs off and effort "none" capabilities and uses one max_tokens. provider_options: [openrouter_provider: routing, app_title: title, app_referer: referer] where routing accepts order/only/ignore lists of 1–32 bounded IDs and allow_fallbacks/require_parameters booleans. Bind upstream route, mode, effort and attribution. Pin the actual upstream for native replay of its reasoning. OpenAI Chat gateway configuration can instead truthfully declare an explicit :openai/"openai_chat" model spec and bind its endpoint/key.
  • Native response continuation v5 binds profile, target, routing, mode, effort, codec, metadata and reasoning. Versions 1–4 remain readable. foreign_history: :reject (default) gives {:continuation_mismatch, :target | :routing | :mode} for foreign native history. Plain text without continuation is portable. :portable sends foreign text/tool exchanges without foreign reasoning/signatures and keeps file ownership checks. Custom adapter tool IDs should be distinct UTF-8 strings of 1–512 bytes per response or nil for host-generated IDs. Definition-incompatible features raise with profile/model at construction. Per-request incompatibility yields %RequestError{reason: {:unsupported, what}} before IO.

  • Model.profile(model).reasoning_binding == :prefix for Claude Fable/Mythos 5.1–5.2, Claude Opus/Sonnet/Haiku 5.5 Messages and GPT-6.2 onward Responses. Fallback exposes it if any leaf does. Adapter checks the effective projected instructions, tools, prior input and consecutive reasoning blocks. Retire through newest invalid block and retain compatible later chain where possible. Missing legacy fingerprint resets. History remains intact. Emit [:exagent, :model, :reasoning_prefix, :reset] for retired reasoning, including portable switches. Tool catalogue changes and temporary projections can invalidate. Prefix check covers the data supplied to stock, so maintain stable file content, credentials and endpoint.
  • prompt_cache: true or [ttl: "5m" | "1h"] on OpenRouter/Anthropic. OpenRouter marks last system/newest message. Anthropic stock marks last tool, last system block and newest message. OpenAI automatically caches eligible prefixes, accepts true/[key: key] and supported GPT-5.6+ policies ttl: "30m" (Responses also "12h"). Unknown rate for 12h write leaves partial estimate. Gemini implicit cache reports cache_read, rejects this option. Reads can appear in usage.details["cached_tokens"]. Tier and cache preferences do not change the C7 binding.

  • service_tier: (candidate) only direct OpenAI, accepts strings or atoms auto/default/flex/priority/fast/ultrafast/scale. Flex requires stock LLMDB eligibility for model and API. Ineligible constructor raises, invalid preflight gives {:invalid_option, :service_tier}. Price with Usage.service_tier/1 returned level. Missing evidence of level-dependent rates can leave cost partial. Same-endpoint Flex→Default can continue native history, no same-candidate retry for immediate 429 fallback, reserve for Default pricing. Local catalogue warns about EU Priority retirement on GPT-5.2/GPT-5.4/GPT-5.4 mini scheduled January 11, 2027. See candidate Doctor switch below.

Multimodal input, tool images and attachments

  • Prompt is UTF-8 string or nonempty ordered list of maps canonicalized to string keys. Part types text, image_url (http/https/data), image, Base64 file and file_reference. Bad part {:invalid_prompt_part, zero_based_index}, empty/invalid prompt :invalid_prompt. Shape, Base64 and UTF-8 checks leave verification of media contents, raw size, image size and URL trust to host. Whole prompt incl. metadata/Base64 spends history limit, exceeding it gives {:retention_limit_exceeded, %{boundary: :input, bytes: bytes, limit: limit}}. Outputs/tool payloads spend per-payload and total history limits.
  • Images need :image input. PDF needs :pdf catalogue input and OpenRouter, Anthropic, Gemini or Responses transport (input_file). OpenAI Chat and OpenAI text profile only transport image attachments. Model.profile(model).supports_image_tool_results requires tools and image input (all fallback leaves). Unsupported offered multimodal or replayed tool images gives {:unsupported, :image_tool_results}. Responses function_call_output.output uses input_text/input_image data URLs. Messages tool_result.content uses text and a base64 source for original tool ID. Gemini 3+ uses functionResponse.response.content for captions and ordered functionResponse.parts images with stock inline_data/mime_type. Other profiles default unsupported. Buffered and fragmented SSE tool-image replay have offline public transport evidence.
  • Message.Part.User.file_reference(provider, file_id, media_type, size_bytes) (candidate) builds a v1 portable type: "file_reference" map with those fields. Opaque ID up to 2,048 UTF-8 bytes, positive size, MIME lowercase without parameters. Gemini PDF URI maps to fileData. Anthropic Files supports authorized catalogue PDF, text/plain and JPEG/PNG/GIF/WebP. ModelProfile.file_references defaults to [], accepts [{provider_string, media_type}] and Fallback intersects. Owning provider mismatch gives :file_reference_provider_mismatch, unsupported pair {:unsupported, :file_reference}, both before intent/IO. Host verifies actual file access, ownership, size and validity across resume, fallback and handoff. The retained reference spends metadata bytes and does not embed the file. Trusted full history can expose IDs. Text export omits them.
  • Gemini inline audio input needs :gemini_v1 and :audio catalogue input. Check Model.profile(model).supports_audio_input, false by default and all Fallback leaves required. Use file with optional filename, MIME audio/wav, audio/mp3, audio/aiff, audio/aac, audio/ogg, audio/flac, audio/mpeg, audio/m4a, audio/l16, audio/opus, audio/alaw, audio/mulaw or audio/webm. Validate encoded bound before decoding up to 1,048,576 bytes per clip. Oversize {:attachment_limit, :audio}, incompatible MIME/model {:unsupported, :modality}. Requests replay retained clips even in later text turns or restored Server. Host can supply filtered message_history: for a new turn. Resume uses saved history. Handoff requires explicit grant.

Media, embeddings, classifiers and citations (candidate)

  • Media.transcribe/3, speak/3, generate_image/3, ocr/3 take model, input and options. Transcription/OCR use {:binary, bytes, mime} or {:base64, encoded, mime} from an authorized source. Speech/image take UTF-8 text. Typed {:ok, result} or {:error, %Media.Error{}}. OCR returns markdown/indexed pages. Images carry data/media_type or hosted url. Finalize open RIFF/WAVE lengths 0xffffffff before returning/storing, preserving other layouts.
  • Media/Embeddings direct defaults max_input_bytes: 1_048_576, max_output_bytes: 4_194_304, max_items: 64, timeout: 30_000, rate_limiter: nil, estimated_tokens: nil, spend_budget: nil, observability: nil and req_llm: [] for admitted stock options. Embeddings max_items ≤1,000. Bounds are on input and decoded/serialized output. Matching TPM requires a positive estimate and quota retains reservation when usage missing. HTTP 429 applies positive Retry-After or 1s cooldown. Media result is %Media.Error{reason: :provider_rejected, status: 429}. 5xx/ambiguous transport can yield :result_unconfirmed and durable uncertainty. Local cancellation/deadline stops its worker and provider receipt may still be unknown. Strict token limits fail before tool HTTP with {:accounting_unavailable, dimension, :normalized_only}. Estimated mode plus finite request limit permits qualified subtotals.
  • Media.tools/1 takes configured transcribe:/speak:/generate_image:/ocr: keyword lists with model: and direct options, required result_store:, optional requires_approval: false and resolve_input: fn ctx, ref -> {:ok, tagged_bytes} | {:error, reason} end required for input references. Tools use media_ prefixes and inherit rate/spend/tracing with configured defaults. Return ref/bytes. Media.fetch(store, run_id, ref) reads v1 operation/result JSON under original run ID, audio/inline images Base64. Invalid envelope :invalid_media_reference. Media.preprocess_audio(target, prompt, transcription_model, opts) uses direct options plus max_clips: 4 under shared deadline/output bound. Keeps supported audio or transcribes in original part positions. Returns {:ok, prompt, usage} or error with prior observed usage. Host owns preprocessing accounting.

  • Embeddings.embed(model, text_or_texts, opts) returns ordered vectors and usage. Embeddings.rerank(model, query, documents, opts) returns descending relevance with zero-based document indices. One request per call. Input bound covers query+documents. Options price_per_token_cents: and price_per_search_unit_cents: price observed evidence. Stock rounded-zero estimate stays unknown. Embeddings.tools/1 configures embed:/rerank: with model/options, store and optional approval. Embeddings.fetch(store, run_id, ref) reads v1 artifact. Durable calls use normal effect reconciliation and stable tool/store binding.
  • Classifier.new/1 requires adapter struct and labels: %{id => description} (2–32 IDs, 1–64 ASCII letters/digits/dots/underscores/hyphens. Descriptions UTF-8 ≤1,024 bytes). Optional instructions: ≤4,096 bytes, timeout: 30_000, max_input_bytes: 65_536, rate_limiter: and estimated_tokens:. Classifier.classify/2 takes text or JSON object/array, returns label, optional confidence and qualified usage or error. Classifier.ReqLLM.new/2 uses stock single-choice evaluation. Model catalogue via ReqLLM.evaluation_models/0. Classifier.NxServing.new(serving_or_name, opts) requires optional :nx, decodes string label or {label, confidence} (0..1 or nil), validates labels, and leaves usage unknown. Named serving owns batch/distribution and can finish after caller deadline. Failure is :result_unconfirmed.
  • Classifier.evaluator(classifier, name, input: projection, pass: labels, version: version) retains available usage on grading failure. Classifier.selector(routes, label_from_input \\ default) maps a trusted preclassified input to a versioned Flow route. Preflight usage belongs to host. Classifier.tool/2 permits requires_approval: true and charges scoped request/usage in live runs. C7 confirms label/usage through tool receipt and ambiguous provider results require reconciliation. Confirming label alone does not confirm charge.
  • Result.citations/1 reads accepted citations and Message.Response.citations/1 reads against the normalized response text. Typed sources URL, attachment ID or document ID/index. Ranges are half-open, answer offsets zero-based UTF-8 bytes and source coordinates retain provider basis. Max 32 citations, 16,384 JSON bytes together, 2,048 reference bytes, title 256, quotation 1,024 (UTF-8 prefix). Oversized IDs are dropped whole. Invalid citations are discarded without rejecting valid terminal/usage. Text-changing hooks clear answer ranges. Only unchanged accepted text output preserves answer ranges. History/C7 stores metadata, next request omits citations. :model_response and :run_finished carry source vs accepted citations respectively. Strip through Event.strip_content/1 for export.
  • Citation wire limits. Responses stock normalizes URL/file annotations without part association, so no answer ranges, omit annotations when commentary phase is present. Gemini grounding can use ranges for exactly matching leading segments. Anthropic can project normalized source locations, but stock 1.31 drops native citation blocks and deltas in offline captures. Validate application citations separately against trusted document identity and half-open source byte range.
  • Evidence on stock 1.31.0 (2026-11-26) covers OpenAI Whisper, TTS-1 WAV length finalization, GPT-Image-2 PNG, Anthropic hosted PDF/text/PNG C7, and OpenAI/Google embeddings. Google embedding probe lacked public token/cost and left its hold open. Vertex Mistral OCR and Cohere rerank have loopback evidence, while Gemini Developer API has no stock OCR route. Gemini audio has an opt-in hosted WAV probe. Hosted PDF ref uses EXAGENT_LIVE_GEMINI_PDF_REFERENCE=1 with Google selected and ready-file URI/size. Qualification should distinguish local evidence and actual deployment responses.

Models and limits guide · Supported profiles · Known limits · Migration

Budgets, quotas, fallback, compaction and accounting

Usage limits and qualified accounting

  • %UsageLimits{request_limit: nil, total_tokens_limit: nil, input_tokens_limit: nil, output_tokens_limit: nil, tool_calls_limit: nil, max_budget_cents: nil, accounting: :strict}. Counters nonnegative integers and budget nonnegative cents. Agent, per-call (candidate), ancestor and saved C7 policies intersect at smallest non-nil limits and strictest accounting. Request and tool counts are exact host admissions. A Fallback logical request can include many HTTP attempts. Reject whole tool batch if its count will exceed the allowance. Mark all :not_executed. Recheck cost/tokens after permissions for individual tools and just before model dispatch. A blocked admitted request still counts and can have unknown usage/open acknowledged intent. In-flight work may exceed retrospective thresholds. Child scope cannot widen ancestors, root totals already include scoped children.
  • UsageLimits.check_before_request(limits, usage, admitted, quote \\ nil) checks a supplied snapshot. Limit error {:usage_limit_exceeded, dimension, value} with :requests/:total_tokens/:input_tokens/:output_tokens/:tool_calls/:budget_cents. Strict metric policy rejects declared normalized-only contracts with {:accounting_unavailable, dimension, :normalized_only} before IO. Unknown profile is checked against actual reports. Strict monetary cap requires a complete explicit estimate_cost: and otherwise can stop with :cost_unknown. Estimated metric/cost limits require a finite request cap in current or ancestor scope and use known subtotals. Independent runs inside tools have independent ledgers. Frame 10/11 check recorded subtotals before preparing successors, including input mapping.
  • estimate_cost: fn model, usage -> cents | {:partial, cents} | :unknown end takes precedence over qualified upstream estimate, including unknown/failure. CostGuard.estimator/1 accepts only atom keys :input_per_1k_cents and :output_per_1k_cents, either may be absent. It prices available token counts with partial marker when coverage/rates are partial. A direction marked unavailable gives unknown even if a legacy number is retained. Fallback supplies the group, so per-rate maxima across eligible leaves bound a flat estimate. Usage.with_estimated_cost/2 accepts nil or usage and complete/partial nonnegative cents.

  • %Usage{input_tokens: integer_or_nil, output_tokens: integer_or_nil, details: %{}, accounting: nil, units: %{}}. A custom adapter with plain counts can leave accounting: nil to qualify provided counts as reported. Unknown is nil, observed zero is evidence. Explicit accounting is a closed string-key v1 map. Fields version: 1, source: "model" | "req_llm" | "aggregate" | "legacy_snapshot", quality: "reported" | "normalized" | "mixed" | "unknown", provider_presence: "unknown", input_semantics: "inclusive" | "exclusive_cache" | "unknown", reasoning_semantics: "included_in_output" | "separate" | "unknown", availability for input/output/cache_read/cache_write/reasoning and cost. Optional service_tier (1–32 ASCII letters/digits/underscore/hyphen). Coverage values "available"/"partial"/"unavailable". Cost has source, quality: "estimated", availability, cents, subtotal_cents. Message.new_response/2 reports invalid field paths.

  • ReqLLM usage is normalized. Tool profiles include cached tokens in input except Anthropic exclusive cache. All include reasoning in output. Evidence comes from stock usage_reported where exposed, otherwise positive cache counts, and provider reasoning detail (Responses, or Chat detail apart from whole completion). Anthropic has no measured thinking count. A synthesized zero or zero input+output beside generated output does not establish token coverage. Stock USD→cents conversion occurs once. Missing billable dimensions yield partial if a subtotal is known, unavailable otherwise. Inclusive input without separate cache rate avoids double pricing. OpenRouter's reported charge can supply complete pricing. cost_cents is the full estimate only when complete. Known portion lives at usage.accounting["cost"]["subtotal_cents"].
  • Cumulative stream updates replace observed directions (including zero) and keep prior values as partial when the latest report omits them. A missing terminal report retains observed partial evidence. An unsuccessful dispatched attempt with no usage makes later aggregate partial/unknown. A skipped preflight does not. Legacy reported numbers can remain in aggregates with partial coverage, so sum original qualified rows for measured-only subtotals. usage_status: :complete | :partial | :unknown follows available evidence, separate from cost_status. A model's incomplete terminal is diagnostic, preserving partial.pending_response and qualified usage.

  • Usage.units (candidate) keys audio_input_milliseconds, audio_output_milliseconds, input_characters, output_images, output_pages and rerank_search_units. Each has "value", "availability" and "quality". Qualities measured/reported/normalized/mixed for a known count, unavailable nil/unknown. An omitted unit makes no assertion. Stock transcription duration can be normalized from segment endpoints (numeric zero preserved). Speech uses input graphemes, image/OCR use returned item counts. Media price_per_unit_cents prices input milliseconds for transcription, graphemes for TTS, images for generation and pages for OCR. Absent unit can use a qualified stock price. Known units with missing tokens can yield partial run usage.
  • Tenant accounting uses root accepted :run_finished keyed by tenant/conversation/run ID once, cumulative across resumes. Pauses are interim. Failures/cancellations can carry payload.partial and Jobs by durable job ID. Authorization and logical-turn reservation/idempotency are host responsibilities. Reuse same key/estimator term/pricing on retry, inspect lost admissions and reconcile unknown charges. Server.usage/2 reads conversation aggregate. Independently verified zero may close a hold. Missing cost remains null.

Shared spend budget

  • UsageLimits.Budget.new(adapter: {module, handle}, reservation_cents: quote, timeout: 5000) creates a scoped account handle. Attach with spend_budget: (candidate). Reserves each physical attempt (incl. retries, Fallback, classifier/Media) or separately priced tool before dispatch, once per fee. Descendants inherit account. C7 restores same authorized account. Replayed responses skip reservation. Amounts are accounted internally in bounded signed 64-bit microcents. Windows align with Unix epoch and a hold carries across windows. Complete charge (including confirmed zero) replaces reservation. Partial charge can raise hold. Missing/unconfirmed final price retains it. Closures remain idempotent.
  • UsageLimits.Budget.ETS.start_link/1 requires name:, limit_cents:, window_ms:, defaults max_receipts: 10_000 (refuses when full) and thresholds: [] (candidate). Local owner loss loses state. ETS committed balance reads don't contend with admission. UsageLimits.Budget.Postgres.new(repo, scope: scope, limit_cents: limit, window_ms: window, thresholds: []) uses authorized shared scope and migration 1. Use same limits/window on replicas. Reservation and hold increases serialize per account. Final charges within holds lock receipt only. A dedicated supervised Repo pool isolates Budget connection occupancy from C7.
  • Budget.balance(budget, opts) (candidate) returns window_start UTC ms, limit_cents, charged_cents, held_cents, partial?. With gaps, charge is a subtotal or nil when no positive subtotal is known. Budget.Postgres.pending/1,2 and statement/2 (candidate statement) page :items and :cursor with limit: 100, after: nil, timeout: 5000. Statements carry receipt/request ID, reservation time/window, held/charged cents and candidate labels model, requested tier, host agent and kind. Omit invalid or >64-byte label values. Pending or open receipt has unknown final charge. Budget.reconcile(budget, receipt_id, billed_cents) is idempotent for equal amount, {:error, :budget_settlement_conflict} for differing closed amount.
  • Budget.Postgres.update_limits(account, limit_cents: new_limit) retains window/charges/holds. Compare previous policy and accept repeat of current limit. Stale handles can settle earlier holds but reservations give :spend_budget_policy_mismatch. Account refusal {:usage_limit_exceeded, :budget_cents, {:retry_after_ms, wait}}, with :unknown for unresolved holds or :infinity when quote exceeds limit. Lost ack {:accounting_unavailable, "cost", :budget_unavailable} can leave a committed hold. First refusal adds zero model requests/effects. Eligible durable Jobs with proof of effect-free preparation can reschedule a finite denial.
  • thresholds: (candidate) distinct integer percentages 1–100, claimed once per receipt's reservation window/account across replicas based on observed ceiling. [:exagent, :usage_limits, :budget, :threshold] is best effort. [:exagent, :usage_limits, :budget, :settlement] carries observed charge/subtotal/coverage.

Provider quota and model fallback

  • RateLimiter.start_link/1 or child spec requires name: (local atom or via Registry) and limits: %{key => [rpm: ..., tpm: ..., concurrency: ..., default_output_tokens: 4096]}. Limits are positive, at least one RPM/TPM/concurrency per key. Key is Model.system/1 string or {provider, model_name} with one granularity per provider. Unconfigured keys pass through. Use stable named limiter or local PID on agents. Delegates inherit. A per-tenant Registry + DynamicSupervisor can own independent accounts.
  • Local max_queue: 1024 waiters/key, optional clock: fn -> monotonic_ms end for quota time. FIFO, rolling 60s from dispatch with expiry rounded up to second. TPM estimates projected input at ~4 encoded B/token (incl. tools, native schema and provider reasoning replay) plus output cap or default token estimate. Complete terminal counts replace estimate. Partial/missing leaves it charged. Monitor owners/deadline for unused holds. Restart clears history/cooldowns while already granted local permits can proceed.
  • Denial {:rate_limited, key, wait_ms | :infinity | :queue_full | :unknown}. Estimate bigger than TPM window or cooldown above 4,294,967,295 ms gives infinity. Known wait incompatible with deadline denies before enqueue, missing deadline ack gives :deadline_exceeded. Unavailable limiter :rate_limiter_unavailable. 429/503 hints cool the key, Google typed google.rpc.RetryInfo.retryDelay can raise Retry-After. RateLimiter.reset_cooldown(name, key, timeout: 5000) clears only matching key's cooldown. Lost acknowledgement {:error, :result_unconfirmed}. Reconciliation uses original operation evidence. Require authorization ack before first logical request/C7 intent and recheck deadline after C7 ack. Failed settlement retains observed usage in partial and complete diagnostic response in pending_response. Incomplete reason takes priority.

  • Shared shared: [adapter: {RateLimiter.Postgres, handle}, lease_ms: 120_000, timeout: 5000]. RateLimiter.Postgres.new(repo, scope: scope) with equal limits/scope and PostgreSQL quota schema 1. Local clock/max_queue are local-mode options. Shared refusals immediate and fresh permit per physical attempt. Lease/deadline bound backend and provider attempt. Lease expiry frees concurrency and leaves rolling charges for one more minute, acknowledged terminal frees slot and caps charge duration at 1 minute from settlement. Confirmed unused drops charges. First settlement wins. Background settlement retries same ID/outcome, 25 ms to 1s backoff while it fits, with final bounded report if deadline expired before ack. Shared reset_cooldown/3 works from any replica. {:rate_limiter_migration_required, 1} covers missing/malformed tables, columns (incl. settled default/nullability) and indexes. RateLimiter.Postgres.cleanup_expired(repo, limit) reclaims expired attempts/cooldowns.
  • Models.Fallback.new/1 requires nonempty ordered models: (resolved executable structs, can nest), defaults max_retries: 2 (0–10), backoff_ms: 500, max_backoff_ms: 8000, retry_statuses: [408, 429, 500, 502, 503, 504, 529], retry_transport: false, fallback_on_quota_denial: false. Leaf implements request/4, model_name/1, system/1 and optional request_stream/4. Streaming-only leaf gives {:error, {:unsupported, :buffered}}. Buffered success needs a Message.Response and executable updated model. Invalid shape is :invalid_model_result. Preflight checks capabilities of full tree, intersects support for tools/native/files/audio/image results, and selects history-compatible candidates.
  • Retry only eligible no-output failures. Transport/total timeout may have billed and require transport opt-in. First model stream event (incl. cumulative :usage) commits attempt unless it is an eligible pre-output error. Backoff exponential+jitter and at least Retry-After when available. Delay above ceiling or exhausting deadline skips remaining same-leaf retries. Buffered Chat can hide Retry-After. Telemetry [:exagent, :model, :retry] has scheduled delay_ms. Recheck deadline after handler/wait and history validation, return last dispatched provider error if available, otherwise {:timeout, :total} pre-dispatch. Updated RequestError.model is revalidated before another attempt. Unusable replacement stops with prior usable state. Nested max attempts per leaf multiply outer and inner (retries+1). Terminal inner preflight stops outer routing.
  • Default quota denial stops. With fallback_on_quota_denial: true, compatible leaves request immediate permits with or without deadline, and confirmed denials skip leaf retries throughout subtree without disturbing queued waiters or spending requests/usage. Lost ack, unavailable limiter or deadline still stops. If all refuse pre-dispatch, shortest finite delay wins, otherwise :queue_full then :unknown then :infinity. After provider error keep last error if remaining leaves refused/mismatched. Durable Jobs can defer only safe initial refusals with schedulable waits.
  • validate_resume/4 target/routing/mode mismatches skip candidate before IO/retry telemetry. If all mismatch, first mismatch unless prior dispatched error. Other preflight errors are terminal without dispatch. foreign_history: :portable on ReqLLM leaf can admit otherwise foreign history, excluding reasoning/proprietary metadata and retaining ExAgent tool codecs. All C7 leaves implement preflight, including backups, even with static matching binding. Models.Fallback.codec(Models.ReqLLM.codec()) or resolver function needs dump/1/load/2 for every leaf, including unused backups, or {:model_state_not_persistable, module}. Preserve ordered tree and stateful script positions. Use response model_name only when unique to identify answering route, otherwise join host attempt receipt with route label. Inclusive run cost cannot be attributed solely to the answering leaf.

Compaction, overflow and finish control

  • Compaction.capability(compactor, opts) projects request-only messages. Custom compact(messages, opts, %{deadline: deadline, params: params, run_id: id, step: step}) and optional validate/1. Invalid/failed projection leaves input and emits [:exagent, :compaction, :stop] status :error. Success :compacted/:no_change. Default estimator includes request content/tools/native-schema. Custom token_counter supplies entire estimate. Keep compaction before synthetic user notes and Skills restore after it. Frame 10/11 reject modified requests before model IO with {:unsupported, :composition_request_projection}.
  • Compaction.ClearToolResults (candidate) defaults threshold_tokens: 4000, keep_recent: 3 counted per successful/domain-error return, including parallel. exclude_tools: [] and keep_call_ids: [] pin matching returns. Replace only shorter payloads with marker keeping call, status/pair, offload ref and byte count. Pin the entire prefix through last provider-protected exchange. Canonical history, instructions, prompt and retries remain. estimated_tokens_saved is projection estimate, independent from billing.
  • Compaction.Summary (candidate) defaults threshold_tokens: 4000, keep_recent: 6 messages, or {:turns, n} with n≥1. Keep tool exchanges paired. Keep current user and instruction/conversation groups, bounding eligible region around active request. User-level summary goes before active user. Required summarize: fn old -> ... end or arity two with effective monotonic deadline/nil, optional token_counter:, memo: and preserve_signed_prefix: (true on prefix-bound profiles, false otherwise). Return nonblank UTF-8, {:no_change} or {:error, reason}. Invalid text :invalid_summary. Summarizer IO owns its accounting/deadline and can run again. Fixtures propagate to its nested run.
  • Compaction.Memo.start_link/1 (candidate) optional name: and max_entries: 1024. First-message key, stores positions/digest of earliest eligible exact messages. Reuse if still contiguous/eligible. Extend with prior summary + newly eligible when projection exceeds threshold. Changed/earlier eligible messages rebuild from original chronology. Use separate memo per policy. FIFO oldest conversation eviction, unavailable falls back to direct summarization. Wait at most remaining run deadline and 5s per memo operation. Already-running callbacks/writes may finish after expiry.
  • context_overflow: {compactor, opts} (candidate) permits one extra request per live run after explicit %RequestError{reason: :context_overflow} (recognized provider input-window codes). Fallback policies first, compaction before error hooks. Reprojection starts from effective request, preserving offered tools, active user, signed prefix, accepted steering and trailing plan/final reminders. Needs identifiable prompt and positive estimated savings. Retry same step with fresh request ID, admission/quota and prior usage, including qualified failed usage. Any text/thinking/tool-argument stream fragment commits original request and rules out retry. Second overflow terminates. :context_compacted emits step/reason/savings. Frame 3 rejects {:unsupported, :context_overflow_recovery}, Frame 10/11 {:unsupported, :composition_request_projection} before opening/claiming (even unselected steps. Late-loaded delegates on load).
  • UsageLimits.WrapUp.new/1 (candidate) final capability to close on next admissible step. Defaults remaining_requests: 1, remaining_tokens: 128, remaining_tool_calls: 0, remaining_budget_cents: 1, remaining_ms: 1000, optional instruction: ≤1,024 bytes nonblank UTF-8. Nil disables one trigger. Request removes function offers but retains output tool. Hard limits and validation still apply. Reserve one closing slot per needing ancestor. UsageLimits.WrapUp.reason/1 reads a retained closure, [:exagent, :usage_limits, :wrap_up] reports selection even if later failed. Frame 3 journals projection, Frame 10/11 reject. Last-slot uncertainty needs explicit Continuation.reconcile_model/5. Rerun requires another slot.
  • max_steps: 50 (positive) and on_max_steps: :error default. :final on last step appends request-only final instruction with functions declared but not executable. Sends tool_choice: none or output tool where supported. Late function call is :not_executed and {:max_steps_exceeded, max_steps}. Scoped child has own steps and shared request budget.

Terminal and error triage

BoundaryHost reason or evidence
Definition/call configArgumentError names invalid key, including mutated struct recheck before IO.
Model request{:model_request_failed, %RequestError{}}. Bare adapter/bad result/missing stream errors use provider nil if none known, Test :test, Fallback own :fallback. Examples :invalid_model_result, {:unsupported, :streaming}, :incomplete_stream, :invalid_stream_event. C7 missing/invalid callback :model_continuation_preflight_required/:invalid_model_continuation_preflight, ordinary preflight errors wrapped like request failures.
Provider model finish:stop and :tool_calls admit based on actual parts. :length/:content_filter/:cancelled/:error/:incomplete/:unknown/nil give {:incomplete_response, finish}, unrecognized→:unknown. ReqLLM SSE needs terminal evidence in a decoded chunk. An incomplete finish skips post/recovery hooks, execution and executable history. Provider cancel is failed status. Host cancel reason/status :cancelled.
Invalid model response:duplicate_tool_call_id, :invalid_tool_call_id, :invalid_model_usage, :invalid_model_response_transform.
Tool/output admission{:duplicate_tool_name, name}, :invalid_tool_definition, {:invalid_tool_schema, name, errors}, {:invalid_tool_callable, name}, {:invalid_tool_control, name, field}, {:tool_requires_deferral, name}, {:invalid_output_schema, errors}, :invalid_output_configuration, {:output_retries_exhausted, error}, {:tool_retries_exhausted, name, error}.
Retention/other{:retention_limit_exceeded, %{boundary: boundary, bytes: bytes, limit: limit}} or stream chunk count/limit 4096, :omitted_payload_history, {:execution_failed, exception}.
  • RunError.reason bounded to 4 KiB. partial.pending_response can preserve incomplete response and payload_omitted diagnostic. Other RequestError.partial_response copies can also omit payload at 4 KiB. run!/3 raises the RunError or RunPaused with result.continuation. Absolute monotonic deadline: is scope-wide and distinct from receive inactivity, operation timeout, tool admission/execution and C7 lease/active-time. Cleanup can outlast deadline and external IO remains subject to receipt reconciliation.

Diagnostics

mix exagent.doctor

  • From a compiled consumer. CLI loads paths and leaves the app stopped. Running Mix.Tasks.Exagent.Doctor.run(args) inside Mix sees live owners. Zero provider calls and credential presence only. Can temporarily start configured PostgreSQL Repo for --check-store or --check-recovery. --json returns %{schema_version: 1, status: :ok | :missing, checks: [%{id: id, status: status, required: bool, action: text, details: map}]}. Human mode prints rows and missing/unverified summary. Row ok/missing/unverified/warning. Prints before raising Mix.Error if required row missing. Invalid arguments/configure errors nonzero. Missing optional, warning and unverified permit successful CI.

  • Select catalogue with --model P:ID or --model test and --profile PROFILE (default auto). Candidate switches --catalogue-max-age-days N (default 30, nonnegative), --files-api, --stored-responses, --base-url URL and --service-tier TIER are optional advice inputs. Stable checks --check-store, --check-run-headers, --check-catalog-lock, --check-jobs, --check-quota; candidate checks --check-recovery, --check-catalog, --check-mcp-lock. CLI rejects repeats, unknowns and positional args.
  • Host config :my_app, :exagent_doctor, [...] keys model, profile, files_api, stored_responses, base_url, service_tier, catalogue_max_age_days, store, catalog, catalog_scopes, conversations, mcp_finch, quota_repo, jobs_repo. CLI wins. Optional packages report availability. json.jason_decimal is required and exercises decoder. Compile Decimal and run mix deps.compile jason --force if missing.
RowMeaning and diagnostics
model.profile, model.credentials, model.r1_2, model.catalogueCatalogue protocol and declared capabilities alongside admitted features, credential variable name/presence or key-free Ollama. An unlisted ID stays unverified without stock unverified-ID warning. Envelope row recommends qualify. Catalogue gives installed version/snapshot age.
model.lifecycle (candidate)Warning with canonical model, state retired/retirement_scheduled/deprecated/invalid_retirement_date and optional replacement/date. Invalid date sets invalid_retirement_date: true and null retires_at.
model.provider_redirect (candidate)Local advice for Google Developer API Gemini 2.5 Pro→3.8 Flash, Flash→3.5 Flash-Lite, date 2026-12-01. State scheduled/effective.
model.service_tier_retirement (candidate)For affected OpenAI EU models with Priority/fast tier, effective HTTPS host eu.api.openai.com (configured or resolved), effective date 2027-01-11 with scheduled/effective state and candidate model/tier metadata.
model.provider_files_retention, model.provider_responses_retention (candidate)Optional notices for provider-owned retention of Files API / stored responses, independent of local erasure.
req_llm.finch*, mcp.transport, mcp.finch, repo.configuration, repo.process, runtime.server, runtime.conversations, runtime.jobsCheck stock Finch config/process, named host HTTP/1-only MCP pool, Repo descriptors/processes and local owners/registry. App stopped leaves process observation unverified.
store.ets, store.custom, store.configuration, store.postgres, store.migration, store.format, store.maintenanceConfig, snapshot/admission/native data-level schema and maintenance indexes. Segment mode verifies fragment columns/cascade. Format reader/write level and unified migration 1. store_migration_required details include internal SQL version (headers 4, admission 5, recovery 6, timers 7 even with no rows) and unified_version: 1.
store.run_headers, store.recovery, store.catalogExplicit header-vs-journal verification with run_header_missing/mismatch and namespace/logical ID. Recovery checks SQL 6/index/projection without reading bodies. Catalogue census by definition/policy/model incl. settled unadopted records. Missing headers unverified, custom scope with missing references unclassified.
catalog.lock, mcp.lockVerify local generated lock against compiled app config or per-endpoint pinned files. MCP check never contacts remote or invokes the callback.
jobs.durable, quota.postgresRead-only schema/connection on configured Repo/search path. Distinguish absent Jobs table and incomplete admission. Quota missing schema reports rate_limiter_migration_required version 1, incl. settled default/nullability checks.

mix exagent.qualify (candidate)

  • Switches standalone --help/-h or required --model P:ID, optional --base-url URL, --json, --yes. Reject positional args/repeats/unknowns. With no yes, consent prompt gives model, destination, 10-request allowance, 2,048-token maximum and credential forwarding on override. Non-yes/EOF declines. HTTP only on localhost, 127/8 or ::1. Other destinations HTTPS. Reject userinfo, query, fragment. Vertex/Bedrock derive endpoint and reject overrides. Uses env-mode stock adapter, automatic profile, no output/tool retries and 45,000 ms per operation. Ordinary Chat/enabled reasoning 2,048 output tokens, other ordinary cases 256, truncation 32.
  • JSON v1 %{version: 1, model: spec, profile: profile, output_mode: mode, status: pass_or_fail, requests: observed, request_limit: 10, cost: %{currency: "USD", upper_bound: number_or_nil, basis: :catalogue_limits | :unknown}, cases: rows}. Row id,status,required,diagnostic,requests,effects,usage. diagnostic has code and bounded details. usage has qualified input_tokens, output_tokens, quality or nulls. Requests count matching [:finch, :request, :start] with synthetic marker including connect failures, not logical admissions or upper-bound estimates. Logs/confirmation to stderr in machine output. Print before nonzero on required failure. Unknown/custom/regional endpoint pricing yields null bound. For known default endpoint, sum applicable token/request rates across catalogue context/output ceilings and all allowances, apply multipliers, round USD upward to six decimals. Cancellation may incur provider charge.

CaseRequired evidence and diagnosis
tool_simple, tool_parallel, tool_stream (2 requests each)Expected batch 1/2/1, identical marker args for parallel with distinct IDs, matching successful receipts and exact effects, plus stream started/finished events. tool_round_trip on success. Negative codes parallel_calls_collapsed, unexpected_tool_call_count, parallel_calls_split, unexpected_tool_arguments, invalid_tool_call_ids, tool_receipts_mismatch, stream_tool_events_missing.
typed_output (1)Exact typed fixture value, typed_result or unexpected_typed_result. Prefer native by declared support, then tool, then prompted.
truncated_envelope (1)Zero effects and invalid_tool_arguments or length terminal with observed nonempty bad marker-tool argument fragments (incomplete_tool_arguments). Valid envelope, absence of evidence or thinking-only length do not pass. Negative truncated_envelope_executed, length_without_tool_evidence, truncation_not_observed.
cancellation (1)Halt on first provisional text/commentary/thinking/argument delta with zero effects, stream_halted or cancellation_not_observed.
reported_usage (1, optional)Both available input/output counts, usage_available or usage_unavailable.
  • not_applicable cases have zero requests/effects and streaming_unsupported (text profile stream/cancel) or tools_unsupported. Other diagnostics request_count_mismatch with expected/observed, terminal_missing, http_error with status, transport_error with transport, incomplete_response with finish, timeout, usage_limit_exceeded with dimension, exposed atom reason or run_failed. Successful local tests and passing protocol rows certify only tested boundaries, separate from response quality and deployed backends.
  • Host triage. Match event namespace, agent ID and request ID. For :checkpoint_pending inspect CheckpointError and health persistence then retry the exact checkpoint, never the original prompt/effect. For :unavailable no command sent. {:delivery_unconfirmed, id}/:result_unconfirmed require original receipt evidence. Langfuse/Opik empty input/output are normal when content capture is off. Provide sanitized boundary reason, partial counters, package/source version, Elixir/OTP and model/profile in reproductions. Keep credentials, whole results and unredacted traces private.

Troubleshooting guide · Testing guide · Agent entry points