# Liberas Agent in five minutes

Liberas Agent is the kernel of an agent harness as an HTTP API. It does not call a model and it does not run tools: you do. You send the run's state and one event (a user message, what the model produced, a tool's result, a person's approval, a cancel) and get back the next state and the commands to carry out: call the model with these messages, run this tool, ask a person about that one, finish with this outcome. The decisions that make an agent safe to run unattended, an atomic budget, an explicit tool policy, a context window, exactly one end, are rules anyone can read and anyone can replace with a cheaper implementation. This page is for people and for agents; the full HTTP surface is in [api.md](api.md).

## 1. Get a key

Sign in, open the [product page](/products/agent) and press **Start free**: 200 calls, once per account. With the CLI:

```sh
liberas login                  # once: a token from /me
liberas trial agent            # prints the key and saves it for `liberas run`
```

A paid pack is 5,000 calls per key. One step of the loop is one call.

## 2. Run the loop

The host keeps a `state` and feeds `agent-step` one event at a time. Start idle, with a system prompt, a budget, a policy and a context limit:

```sh
STATE='{"messages":[{"role":"system","content":"You are a careful assistant.","tool-call-id":null}],
        "budget":{"tool-calls":20,"turns":10,"tool-bytes":65536},
        "policy":{"deny":["shell*"],"ask":["write*"],"allow":["read*"],"fallback":{"tag":"ask"}},
        "status":"idle","pending":[],"awaiting":[],"context-tokens":8000,"outcome":null}'
curl -s https://liberas.dev/api/run/agent-step \
  -H 'content-type: application/json' \
  -d "{\"key\":\"$KEY\",\"input\":{\"current\":$STATE,\"event\":{\"tag\":\"user-message\",\"val\":\"read a.txt and summarize it\"}}}"
```

The answer is `{ "ok": true, "output": { "state": …, "commands": [ { "tag": "call-model", "val": [ …messages… ] } ] }, "deps": { "agent-budget": …, "agent-context": … } }`. A turn was charged, the status is `thinking`, and the one command says which messages to send to your model (those that fit `context-tokens`, system messages always). Keep `output.state`; it is the next call's `current`.

Then the model answers. Translate what it said into one event and step again:

```json
{ "tag": "model-output", "val": { "text": "Reading it.", "tool-calls": [ { "id": "c1", "name": "read-file", "arguments": "{\"path\":\"a.txt\"}" } ] } }
```

Now the commands are what to do: `run-tool` for each allowed call, `ask-approval` for each the policy says to ask about, nothing for a denied one (the model gets a tool message `denied: …` instead). Run the tool and send its answer as `{ "tag": "tool-result", "val": { "tool-call-id": "c1", "output": "…", "ok": true } }`; ask the person and send `{ "tag": "approval", "val": { "tool-call-id": "c2", "allowed": true } }`. Once every pending call is answered, the next command is `call-model` again. A `model-output` with no tool calls ends the run: the state's `status` is `finished`, its `outcome` is `completed(text)`, and the command is `finish`. A finished run refuses every further event.

`cancel` and `error(why)` end the run from the outside, at any point. A budget that runs out ends it too, as `failed("budget: …")`.

| event | when | what happens |
|---|---|---|
| `user-message(text)` | status `idle` | the message is appended, a turn is charged, `call-model` |
| `model-output({ text, tool-calls })` | status `thinking` | with no calls: `finish(completed(text))`; with calls: the budget is charged for all of them or none, each is decided by the policy, `run-tool` / `ask-approval` / a `denied:` tool message |
| `tool-result({ tool-call-id, output, ok })` | the call is pending and not awaiting approval | the tool message (or `error: output` when `ok` is false), and `call-model` once nothing is pending |
| `approval({ tool-call-id, allowed })` | the call is awaiting | allowed: `run-tool`; refused: the tool message `denied: refused by the user` |
| `cancel` | any status but `finished` | `finish(cancelled)` |
| `error(why)` | any status but `finished` | `finish(failed(why))` |

## 2½. The reference host

`examples/agent/host.mts` is the loop above as a program: every decision is one of the calls in this guide, and the host only calls the model, runs four file tools in a directory, and asks you before a write. From a checkout:

```sh
liberas trial agent                                  # once: the key the host reads
ANTHROPIC_API_KEY=… pnpm agent:host "summarize README.md into notes/summary.md" --dir ~/some/project
```

`OPENAI_API_KEY` instead selects the OpenAI pair of specs (`--provider`, `--model` to choose explicitly; `MODEL_URL` points either at a compatible server). `--yes` approves every ask. The host validates each tool call's arguments before running it, retries the provider with `agent-backoff`, recalls notes from earlier runs through `agent-memory` into the system prompt and remembers the outcome, and checks at the end that `agent-outcome` folds the run's events to the same outcome the loop reached. It is about two hundred lines; read it as the worked example of the table below.

## 3. The pieces

Each is a spec of its own, callable on its own at `POST /api/run/{spec}` with the same key, and exactly what it computes is on its page.

| spec | what it decides |
|---|---|
| [agent-budget](/specs/agent-budget) | `charge(budget, calls)`: all of a model's tool calls or none of them, counted and in bytes of arguments; `turn(budget)`: one model turn. |
| [agent-policy](/specs/agent-policy) | `decide(policy, call)`: `deny`, `ask`, `allow` lists of tool names or `prefix*` patterns, tried in that order, else the policy's `fallback`. |
| [agent-context](/specs/agent-context) | `fit(messages, limit)`: every system message, then the newest of the rest that fit; `estimate(messages)`: ceil(bytes/4) + 4 per message. |
| [agent-outcome](/specs/agent-outcome) | `fold(events)`: a run's events to its one outcome: cancel wins, an error fails, else the last model text completes. For logs and replays. |
| [agent-backoff](/specs/agent-backoff) | `delay(attempt, base, cap)`: exponential with jitter, in milliseconds; the jitter comes from the host's random source and the answer carries `host.random` so the call can be replayed (ADR 0057). |
| [agent-step-2](/specs/agent-step-2), [agent-step-3](/specs/agent-step-3) | the loop again, with every assistant message carrying the model's tool calls (`tool-calls`) and the provider's own turn (`extra`), so a provider's transcript can be replayed from the messages. The newest answers at `agent-step`'s URL. |
| [agent-anthropic-request](/specs/agent-anthropic-request), [agent-anthropic-response](/specs/agent-anthropic-response) | `body(request) -> JSON text` for `POST /v1/messages`; `parse(body) -> model-output` from its response. Pure text to text: the host does the HTTP. |
| [agent-openai-request](/specs/agent-openai-request), [agent-openai-response](/specs/agent-openai-response) | the same for `POST /v1/chat/completions`. |
| [agent-sse](/specs/agent-sse), [agent-anthropic-stream](/specs/agent-anthropic-stream), [agent-openai-stream](/specs/agent-openai-stream), [agent-anthropic-delta](/specs/agent-anthropic-delta), [agent-openai-delta](/specs/agent-openai-delta) | streaming: frame the server-sent events, fold them into the unstreamed body, show text deltas. |
| [agent-schedule](/specs/agent-schedule) | `next(schedule, now)`: the next fire time of `at`, `every` or a five-field UTC cron; `wake(schedules, since)` asks the clock once and says which fired and when the next is. For hosts that run agents on a timer. |
| [agent-delegate](/specs/agent-delegate) | sub-agents: `spawn(parent, call, share)` carves a child state out of the parent's budget and policy (no asking a person in a child); `finish(child, call)` turns its outcome into the parent's tool result; `refund` gives back what the child left. The reference host offers the model a `delegate` tool with `--delegate <share>`. |
| [agent-json-equal](/specs/agent-json-equal) | the comparator (ADR 0055) that judges request bodies: equal as JSON values, whatever the formatting. |
| [agent-validate](/specs/agent-validate), [agent-validate-2](/specs/agent-validate-2), [agent-validate-3](/specs/agent-validate-3) | `validate(schema, input) -> problems`: a tool call's arguments against the tool's JSON Schema (a documented subset) before `run-tool`. Empty means valid; each problem has a JSON Pointer path and a message. The second reads `pattern` too, through agent-regex; the first promised to ignore it, so both stay. The third is the second's new version (it answers at that address): `patternProperties`, `propertyNames`, and `format` for `date`, `time`, `date-time`, `uuid` and `ipv4`. |
| [agent-edit](/specs/agent-edit) | `apply(text, edits) -> text`: each edit's `find` replaced by `replace`, in order; `find` must occur exactly once (or at least once with `all`), else the error names the edit. What the reference host's `edit-file` tool means. |
| [agent-regex](/specs/agent-regex) | `matches(pattern, input)`: a defined subset of ECMAScript's regular expressions (no backreferences or lookaround), matched in linear time whatever the pattern. What `pattern` means in a schema. |
| [agent-memory](/specs/agent-memory) | `remember(note) -> n`, `recall(limit) -> notes`, `forget() -> n`: notes that outlive a run, in the store the host keeps per license key (`liberas:host/kv`, ADR 0060). Pass `"fn"` with the key and input to pick the function. |
| [agent-step](/specs/agent-step) | the reducer above, assembled from the first three. |

### Calling a model

The `call-model` command gives you messages; a wire-format spec turns them and your tools into the provider's request body, and another turns the response into the next event. The host only moves bytes:

```sh
# 1. the messages from call-model, your tools, the model → the request body
BODY=$(curl -s https://liberas.dev/api/run/agent-anthropic-request -H 'content-type: application/json' \
  -d "{\"key\":\"$KEY\",\"input\":{\"request\":{\"model\":\"claude-opus-5-5\",\"max-tokens\":16000,\"messages\":$MESSAGES,\"tools\":$TOOLS}}}" | jq -r .output)
# 2. the provider
RESPONSE=$(curl -s https://api.anthropic.com/v1/messages -H "x-api-key: $ANTHROPIC_API_KEY" -H 'anthropic-version: 2023-06-01' -H 'content-type: application/json' -d "$BODY")
# 3. the response → a model-output event for agent-step
EVENT=$(curl -s https://liberas.dev/api/run/agent-anthropic-response -H 'content-type: application/json' \
  -d "{\"key\":\"$KEY\",\"input\":{\"body\":$(jq -Rs . <<<"$RESPONSE")}}}" | jq '{tag:"model-output",val:.output}')
```

A tool is `{ "name", "description", "input-schema": "<JSON Schema as text>" }`. The OpenAI pair works the same way against `/v1/chat/completions`.

To stream instead, add `"stream": true` to the body the request spec gave you and read the server-sent events. [agent-sse](/specs/agent-sse) frames them (`feed(buffer, chunk)`, call it per chunk or once with the whole text), [agent-anthropic-stream](/specs/agent-anthropic-stream) / [agent-openai-stream](/specs/agent-openai-stream) fold the events into the body the provider would have sent unstreamed, which the response spec then parses as usual; [agent-anthropic-delta](/specs/agent-anthropic-delta) / [agent-openai-delta](/specs/agent-openai-delta) give the text an event adds, for display as it arrives. The reference host does this with `--stream`.

The response specs also return `extra`: the provider's own representation of the turn (for Anthropic the whole `content` array, reasoning blocks and signatures included). `agent-step` copies it onto the assistant message, and the request specs replay such a message unchanged instead of rebuilding it from text and tool calls. So a model whose thinking is always on keeps its thinking across tool turns, and the host never looks inside. Messages you write yourself have no `extra` and are rebuilt.

Check a `run-tool` command's arguments before running the tool: the model's JSON is not always what the schema promised.

```sh
curl -s https://liberas.dev/api/run/agent-validate-2 -H 'content-type: application/json' \
  -d "{\"key\":\"$KEY\",\"input\":{\"schema\":$(jq -Rs . <<<"$SCHEMA"),\"input\":$(jq -Rs . <<<"$ARGUMENTS")}}" | jq .output
# [] when valid, else [{ "path": "/text", "message": "expected string, got number" }, { "path": "/path", "message": "must match the pattern ^[\\w./-]+$" }, …]
```

A problem list is a good tool result to send back as `ok: false`: the model gets to fix its call.

Memory is the one piece with an effect: a call of `agent-memory` reads the key's store and its writes are kept when the call succeeds, so the next call sees them. It is still verified the way everything else is: a case says what the store holds, and a build must leave the store exactly as the reference does.

```sh
curl -s https://liberas.dev/api/run/agent-memory -H 'content-type: application/json' \
  -d "{\"key\":\"$KEY\",\"fn\":\"remember\",\"input\":{\"note\":\"the user prefers short answers\"}}"   # 1
curl -s https://liberas.dev/api/run/agent-memory -H 'content-type: application/json' \
  -d "{\"key\":\"$KEY\",\"fn\":\"recall\",\"input\":{\"limit\":10}}"                                       # ["the user prefers short answers"]
```

`agent-step` is pure: the same state and event always give the same transition, on any implementation, which is how a contributor's cheaper build is verified before it answers your calls. Model calls, tool runs and the person's answers are yours to make, with any model and any tools.

## 4. Limits and errors

| status | meaning |
|---|---|
| `400 bad_input` | The JSON does not match the interface: an unknown status, a missing field, a message without `tool-call-id` (`null` is fine). Nothing ran and nothing was counted. |
| `402 quota_exhausted` | The key has made every call its pack holds. Get a paid pack on the product page. |
| `403 license_invalid` | The key is malformed, revoked, or for another product. |
| `429 rate_limited` | More than 300 calls in a minute on one key. Wait a moment. |

`ok: false` with an `error` string is the kernel's own answer: an event the status does not allow (`a user message while thinking`, `the run is finished`), a tool result for a call that is not pending, an approval for a call that was not asked about.

## 5. Make it better, get paid

Every piece here has shares; a contributor whose component is the cheapest passing one earns them, and revenue from every pack sold is distributed to them (ADR 0021). The [roadmap](/products/agent) lists what is planned next. See [contributing.md](contributing.md).
