# Using ExAgent in an application

## Dependency resolution

From the consuming Mix project run
`mix run --no-start -e 'IO.puts(Path.expand(Map.fetch!(Mix.Project.deps_paths(), :exagent)))'`.

Resolve all package paths below from that directory. For a host configured with
UsageRules, run `mix usage_rules.sync` after changing the dependency version.
Start with `docs/guides/agents.md`. Check `priv/api-stability.exs` and the installed
module docs before using a member, option, field, variant or Mix switch.

## Skill router

| Task | Load `usage-rules/skills/<skill>/SKILL.md` |
|---|---|
| One-shot execution, result handling, lazy stream | `exagent-run-agent` |
| Tool schema and callback, permissions, typed output | `exagent-tools` |
| Cloud or local models, retries, quotas, spend and context | `exagent-models` |
| Stateful chat, admission, demand events, approval UI | `exagent-server` |
| Background work, notices, Oban recovery | `exagent-jobs` |
| Store, migrations, persisted continuations, dirty saves | `exagent-store` |
| Delegated agent, scoped child, handoff, durable workflow | `exagent-coordination` |
| Participant turns, shared state, state codec | `exagent-session` |
| TestModel, ExUnit, Eval fixtures, replay | `exagent-test` |
| MCP clients, tools, protocol, durable identity | `exagent-mcp` |
| Telemetry, OpenTelemetry, bounded export, online Eval | `exagent-observability` |

## Hard API contracts and return shapes

| Call | Contract |
|---|---|
| `ExAgent.new/1` | Keyword configuration → agent struct. Invalid definitions and impossible profile combinations raise `ArgumentError` before IO. |
| `ExAgent.run/3` | `{:ok, %ExAgent.Result{status: :succeeded, output: output}}`, `{:ok, %ExAgent.Result{status: :paused, continuation: ref}}`, or `{:error, %ExAgent.RunError{reason: reason, partial: partial}}` after valid configuration. |
| `ExAgent.run!/3` | Returns accepted output. Raises the run error or `ExAgent.RunPaused`. |
| `ExAgent.run_stream/3` | Lazy enumerable. Consume once. Deltas and drafts are provisional. Full consumption ends with one `{:result, result}` or `{:error, error}`. Pass along unknown element types with a catch-all. |
| `ExAgent.Server.chat/3`, `ExAgent.Server.resume/3` | `{:ok, result}` or `{:error, reason}`. An error may be a boundary reason, a run error or `%ExAgent.CheckpointError{}`. `:result_unconfirmed` requires a read of the original operation. |
| `ExAgent.Server.send_message/3`, `ExAgent.Server.receipt/3` | `{:ok, receipt}` or `{:error, reason}`. Keep the admission key, run ID and request ID. `{:delivery_unconfirmed, request_id}` means lookup the same key and correlate the original request. Admission can precede dispatch. |
| `ExAgent.Server.attach/3`, `ExAgent.Server.events_since/3`, `ExAgent.Server.ack_events/4` | Attach with `delivery: :demand` before taking the history page. Read `{:ok, %{items: events, cursor: cursor}}` with the notice. Apply the batch before acknowledging that notice and cursor. |
| `ExAgent.Continuation.get/2`, `ExAgent.Continuation.pending/2` | `{:ok, details}` or `{:ok, items}` respectively, or `{:error, reason}`. `ExAgent.Continuation.get(store, id, diagnostics: true)` can include the stored body. |
| `ExAgent.Continuation.decide/4`, `ExAgent.Server.decide/4`, `ExAgent.Continuation.supply_result/4` | `{:ok, reply}` or `{:error, reason}`. The reply has `:revision`, `:status`, `:pending`, `:replayed` and `:continuation`. An actionable decision or supply returns a new exact reference. Nil means this reply grants no resume. |
| `ExAgent.resume/3` | `ExAgent.resume(agent_or_catalog, ref, continuation: config)` returns the same result shape as a run. Bind the trusted definition, policy and model to the authorized Store and revision. |
| `ExAgent.Store.scoped/2`, `ExAgent.Store.namespace/1` | Scope the backend with a host-owned nonempty UTF-8 namespace. Read the namespace from the opaque scoped value. A nil namespace uses legacy unscoped keys. |
| `ExAgent.Catalog.new/1`, `ExAgent.Catalog.cast/1`, `ExAgent.Catalog.resolve/2` | Build from versioned host entries. Cast returns `{:ok, catalog}` or `:error`. Resolve a saved identity to `{:ok, entry}` or `{:error, reason}`. |
| `ExAgent.Migration.up/1`, `ExAgent.Migration.down/1` | In a host Ecto migration, pin `version: 1` up and `version: 0` down for a fresh or 2.x install. Both return `:ok` when queued in the migration. |

## Common LLM traps

| DO | DO NOT |
|---|---|
| Use `Tool.new/1` with `call:`. Set `takes_ctx: false` for `fn args -> ... end`. Match JSON string keys. Declare `effect: :read` for pure reads or calculations. | Use `callable:`, assume atom keys, use unary callbacks with the default context, or assume tools default to read. The default is `effect: :write`. |
| Deliver `result.output` only after matching `status: :succeeded`. Persist a paused reference as pending work. | Treat every `{:ok, result}` or stream draft as a delivered answer. |
| Queue the exact `:continuation` from the confirmed decision or result-supply reply. Replaying the same command can recover its receipt. | Resume with the replaced pause reference, synthesize a reference from three keys, or upgrade a delayed job to the latest revision. |
| Inspect the run error's `:partial` and authorized effect journal after failure. On `:execution_uncertain` or an `:unknown` write, reconcile via a declared read-only lookup such as `Continuation.reconcile_tool/4`. | Resubmit a write on timeout, restart, worker failure, cancellation or a lost acknowledgement. |
| Retry the save via `Server.checkpoint/1` or `Session.checkpoint/1` when the owner is dirty. | Replay the prompt, tool or state callback to obtain an acknowledged save. |
| Script one response for every model request in `%ExAgent.Models.Test{script: [...]}`. Include the turn after a tool and the final output-tool call (usually `final_result`) with typed `:tool` output. | Script only the first tool call or send final text for a required output tool. The script cannot supply an extra turn after exhaustion. |
| Send stock ReqLLM wire tool arguments as a one-field object `{"arguments": {...}}`. Empty arguments use `{"arguments": {}}`. For logical `ToolCall` args and Elixir callbacks, use the inner map. | Dispatch any sibling of a rejected batch, guess missing JSON, or wrap an already decoded TestModel call. |
| Use `ollama:`, `vllm:` or `lmstudio:` for local `:chat_tools_v1` routes with plain thinking and `:tool`/`:prompted` output (use `vllm:` + `base_url:` for llama.cpp). | Assume local `:chat_tools_v1` supports `:native` structured output or replays plain thinking in history. |
| On any stock ReqLLM route (live or Frame 3), complete JSON objects with unique keys and no stock argument error auto-retry envelope shape mismatches — spending `max_retries` per distinct function tool or `output_retries` once for a batch with an output tool. | Retry truncation, non-object or unparseable JSON, stock argument errors, observable duplicate keys, zero/exhausted budgets, or malformed envelopes in Frame 10/11. Some stock routes normalize duplicates before ExAgent can see them. |
| Derive namespace, actor, tool permissions and versioned bindings from authenticated host state. Apply ancestor limits to children. Use explicit allowlists via `Permissions.new!/1`. | Accept actor, scope, authority or a callable supplied by prompt, deferral, receipt or restored data. |
| Keep exact dispatch counters, qualified token/cost fields and lower-bound subtotals distinct. Use the content-free event/Telemetry projections at external boundaries. | Turn missing usage into zero or serialize live results, tools and model structs for logs. |

## Durable operations

- Preserve the exact version 1 continuation reference, including `:version`,
  `:id`, `:record_id`, `:revision`, `:run_id` and any `:attempt_id`. To restore a
  legacy three-key reference, look up its authorized revision and verify the
  originating decision before scheduling delivery.
- Give each scope its own Jobs owner. Bind `Jobs.tools/2` to that owner.
  Route volatile job notices to the authorized `Conversations.via/2` address.
  Use `job_status` on the same scope to read the result.
- Use stable `Catalog` bindings with `Continuation.census/2` and
  `Continuation.adopt/4` when replacing an in-use definition version. Reconcile
  uncertain effects first. Bind the original admission key when reopening an
  owner after unconfirmed `Conversations.stop/3`.
- For PostgreSQL, `mix exagent.upgrade --yes` (candidate) generates the pinned
  host migration. Review, then apply with `mix ecto.migrate`. Unified version 1
  includes C7 run headers, keyed turn receipts, segmented snapshots,
  the pending timer index, Budget attribution and thresholds, and scheduled
  follow-ups. Rebuild and verify run headers on each enrolled table with 2.x C7
  journals before enabling writers or Recovery. Opt into fragmented writes
  with `segments: true`. Retain the per-adapter helpers for historical migrations.
- Offer confirmed terminals to `Eval.Online`. For C7, bind the authorized source
  Store. For durable grading, bind the effective evaluator version with
  `Eval.Online.Durable` (candidate). Treat a confirmed cancellation and an
  uncertain cancellation as different evidence.
