# CAF

> The Clackatoo Agent Framework: a Rust library for building robust, feature-rich chats with coding agents into your own program.

---

# What Is CAF

_CAF / Getting Started_

> CAF, the Clackatoo Agent Framework, is a Rust library for building chats with coding agents such as Claude Code into your own program, robustly, without learning each agent's quirks.

**CAF**, the Clackatoo Agent Framework, is a Rust library for putting chats
with coding agents, such as Claude Code and Codex, into your own program. It
grew out of the agent backend of
[clackatoo](https://github.com/clackatoo/clackatoo), and clackatoo is its
first user.

## What it does for you

Coding agents speak the
[Agent Client Protocol](https://agentclientprotocol.com) (ACP), through an
*adapter*: a small program that turns the agent into an ACP server. ACP says
what messages exist, but not how each adapter really behaves. Adapters
differ, and what you declare to one can change how it behaves for the whole
connection. Getting a chat right means knowing all of that.

CAF holds that knowledge so your program doesn't have to:

- **It talks to the agent.** It starts the adapter, opens sessions, sends
  messages, follows the reply as it streams in, and stops a turn when asked.
- **It gives the agent only your tools.** Every agent runs with none of its
  own: no built-in file editing or commands, and none of the user's own
  setup. See [Agents and profiles](/caf/concepts/agents-and-profiles.md#an-agent-has-only-your-tools).
- **It keeps its own record of every chat**, in one format for every agent,
  so your program draws a chat the same way whichever agent it's with.
- **It absorbs each agent's quirks** in a profile per adapter, so nothing
  past that profile knows which agent it's talking to.
- **It survives things going wrong**: an adapter that dies, hangs, floods
  its output, or never answers. Every request it sends has an end, and every
  request the agent sends is answered exactly once.

Your program describes what it can show, in plain terms, and draws the chat
from CAF's record. CAF itself draws nothing.

## How it's built

CAF's heart is [the core](/caf/concepts/the-core.md), which holds every chat's
state and the rules that change it, and does no I/O at all. Small drivers do
the I/O around it: starting adapter programs, keeping time, asking whether
the agent may do something, showing chats. `caf-driver-tokio` has drivers
for programs built on tokio; a program with its own event loop, such as
clackatoo, writes its own.

## What exists today

CAF is being built a feature at a time, each feature designed in full before
it's built. The first, *talking to one agent*, covers starting an adapter,
opening a session or continuing one, sending messages, seeing the reply
stream in, stopping a turn, and surviving the adapter dying or hanging. It
supports Claude Code, through its adapter `claude-agent-acp`.

The second, *the reference app and inspector*, puts chats in other places:

- **[Viewers](/caf/concepts/viewers.md)**: a small, versioned set of messages
  that any window or web page can use to follow chats and act on them.
  `caf_driver_tokio::viewer::serve` is CAF's side of it.
- **A TypeScript caf-sdk**, `@clackatoo/caf`, for
  [a chat in the browser](/caf/getting-started/a-chat-in-the-browser.md).
  Its types are generated from CAF's own, and shared test cases hold it to
  exactly what the core does.
- **[The debugger](/caf/getting-started/the-debugger.md)**, `caf-debugger`: a
  chat view to copy, beside an inspector of every step CAF takes. It records
  every run, replays recordings, and moves back and forth through them.

The third, *installing and signing in to agents*, means a program no longer
has to find an agent itself:

- **[Installing](/caf/getting-started/installing-and-signing-in.md)**: CAF
  installs each agent at the version it has checked, in one folder every
  CAF program shares, asking the user first. Old versions go once nothing
  has used them for two weeks.
- **Signing in**: CAF runs each agent's own sign-in and shows its link, so a
  web page can sign the user in without a terminal. It knows whether each
  agent is signed in, and how, but never who.
- **Built for any agent**: everything about one agent is data in its
  [profile](/caf/concepts/agents-and-profiles.md), so adding an agent is
  adding a profile.

The fourth, *saving and restoring chats*, lets a chat outlive the program
that opened it:

- **[Saving](/caf/getting-started/saving-and-restoring-chats.md)**: CAF saves
  each chat as it goes, whole, with the agent's session and your own data
  on it, on shelves your program names, in files or a store of your own.
- **Restoring**: a chat comes back with its record, tidied of whatever was
  under way, and carries on the agent's session when a message is sent.
  Chats can be put away, closed, deleted and moved, from your program or a
  viewer.
- **Readable forever**: a save from any version of CAF stays readable by
  every later one, and an older CAF never writes over a newer one's.

The fifth, *choosing the model*, lets the user choose how the agent
answers, whichever agent it is:

- **[Settings](/caf/getting-started/choosing-the-model.md)**: each chat
  offers its agent's models, how hard each thinks, and fast mode, as the
  agent lists them, in one shape for every agent.
- **Choosing**: for a chat, as it opens or at any time, or as your
  program's default for an agent. A change made during a reply applies
  from the next message. A message never goes with a choice made for the
  chat silently replaced: it fails, saying so, or the chat says what
  changed. Your program's defaults the agent doesn't offer are dropped
  quietly. Each turn records the model it was sent on.
- **Before any chat**: CAF learns what an agent offers without sending a
  message, so your program can offer its models before a chat opens.
  Viewers choose and learn too.

The sixth, *usage*, says what the agent costs:

- **[Each turn and chat](/caf/getting-started/usage.md)**: CAF records what
  every turn spent, in tokens by model and as the agent reported its cost,
  and adds up each chat's spend, estimating the cost the agent didn't
  report.
- **One ledger for the machine**: every turn of every CAF app goes into a
  ledger they all share, unless the app turns the ledger off, never with what was said, so your program can
  show how much the user has used across all of them, by day, app, agent
  and model.
- **Prices**: the user's own, then LiteLLM's table, fetched once a day,
  then a snapshot that comes with CAF. A price put right puts every
  figure right.

---

# A Chat on Tokio

_CAF / Getting Started_

> Run CAF in a tokio program with caf-driver-tokio. Start it, open a chat, watch it change, send messages, answer questions, stop a turn, shut down, and record a run to replay as a test.

`caf-driver-tokio` runs CAF in a tokio program. It has the drivers the core
needs and the wiring that joins them up, so most programs use only one type
from it: `Caf`.

## Start CAF and open a chat

Describe your program with a `Host`, list the agents it offers, and start
CAF. It runs in a task of its own on the current tokio runtime.

```rust
let claude = AgentSpec::command(
    "claude",
    SpawnCommand::new("/opt/claude-agent-acp/bin/claude-agent-acp"),
    ProfileChoice::Builtin(Builtin::ClaudeAgentAcp),
);
let (caf, running) = Caf::<NoAppItems>::start(Config::new(Host::new("eyespy", "0.4.0"), vec![claude]));
let chat = caf.open_chat(OpenChat::new("claude", "/home/me/project")).await?;
```

A chat takes messages at once. Messages sent before its session is open wait
for it.

The agent has none of its own tools: only those you give it, CAF's own
(`OpenChat::with_tools`, see [Serving tools](/caf/concepts/serving-tools.md))
and your MCP servers (`OpenChat::mcp_servers`). `OpenChat::instructions` tells it about your
program and the work, after CAF's own short instructions. See
[Agents and profiles](/caf/concepts/agents-and-profiles.md#an-agent-has-only-your-tools).

Here your program says how to start the agent's adapter. CAF can also
install it, and sign in to it, itself: see
[Installing and signing in](/caf/getting-started/installing-and-signing-in.md).

## Watch it

A watch gives you the whole chat first, then what changes:

```rust
let mut watch = chat.watch();
chat.send(UserMessage::text("Fix the tests")).await?;
while let Some(update) = watch.next().await {
    match update {
        Update::Picture(chat) => draw_all(&chat),
        Update::Changes(changes) => changes.iter().for_each(draw_change),
        _ => {}
    }
}
```

A watch reads only when you ask it to, so nothing piles up for one you don't
read. If it falls further behind than the chat's list of changes is long
(`Limits::kept_changes`, 4096 by default), it gets the whole chat again.

`next` returns `None` once the chat is gone, put away or deleted (closing
a saved chat puts it away), or CAF has shut down. Closing a chat that isn't
saved archives it, and its watch goes on, as it may be unarchived. A watch
that hasn't seen how shutting down left the chat gets it as one last picture
first, even one that never read before.

A watch doesn't keep CAF running: see [Shut down](#shut-down).

## Answer questions and stop turns

Questions wait on the chat, in `Chat::questions`. The agent asks permission
to do things, and CAF asks when a session is slow to open. Answer each with
`ChatHandle::answer`. A question is answered once, and only while it stands:
a second answer, or an answer to a question that's gone, is refused.

The default policy, `AlwaysAsk`, puts every permission request to the user.
A program can give `Config::policy` its own. Its `decide` should return at
once, with a future that does the work: that future may take as long as it
needs, and is dropped if the request is withdrawn, such as when the user
stops the turn. If either panics, the request is refused.

`ChatHandle::stop` stops the running turn and drops the ones waiting.

## Shut down

```rust
caf.shutdown().await;
running.await;
```

`shutdown` returns once every adapter has exited and been reaped, and what
each started has been sent SIGKILL. From the moment it's called, anything
else asked of CAF fails with `Error::Gone`.

If every `Caf` and `ChatHandle` is dropped, CAF shuts down by itself. Watches
don't count: a task still waiting on a watch gets the chat's last picture,
then `None`.

## Logs

The core's reports go to the [`log`](https://docs.rs/log) facade, with target
`caf`, at the level the core gave them: debug, info or warn. They never hold
the account email Claude's adapter sends.

## Record a run

Set `Config::record` to a file that doesn't exist yet, and CAF writes down
everything the core is given, with its time, as JSON lines. Replayed into a
fresh `Core`, a recording ends in the same state, so a real session becomes a
test.

```rust
let mut config = Config::new(host, agents);
config.record = Some("/home/me/caf-run.jsonl".into());
```

The first line holds the host and the agents:

```json
{"caf_recording": 3, "host": {…}, "agents": [{…}]}
```

Each line after it is one event, in order:

```json
{"now": {"wall": 1795600000000, "mono": 1953000000}, "event": {"type": "Host", "value": {"type": "Send", "value": {…}}}}
```

Every enum is written as its variant's name as `type`, with what it holds, if
anything, as `value`, as everywhere in CAF: `{"type": "Woken"}`. This is
version 3 of the format: check `caf_recording` before reading the rest.
Until CAF is released, an older version's recording isn't read: its
events change shape with no migration, as version 3's did for archiving
and the names on notes about settings.
Each `type` comes before its `value`, and must stay there: what the agent
sent is kept exactly as it came, and reads back only in that order.

To replay it, make a `Core` from the first line with `Core::new`, read each
line's event as an `Event`, and give it to `Core::handle` at its time. A
recording cut short ends with a `stopped` line (see below): stop there.

### What's hidden

None of this changes what the core does with the recording:

- **Claude's sign-in status** (`_auth/status_update`) holds the account's
  email. It's written with its params as the kind of sign-in alone, such as
  `{"authStatus": {"kind": "account"}}`, which is all the core reads.
- **A code the user pasted** into a sign-in (`Caf::paste`) is written as
  `null`. A replay takes it as text it doesn't have.
- **Each agent's arguments** are left out, and **its environment variables**
  are written with their names but not their values.
- **Each MCP server's environment variables and HTTP headers** are written
  with their names but not their values.

### What's kept

Everything else goes in as it came:

- the host, and each agent's name, program, folder and profile;
- what the user sent, and everything the agent said;
- the agent's error output, exactly: as text where a piece of it is UTF-8,
  and as bytes where it isn't, such as one that ends partway through a
  character;
- folders;
- each MCP server's name, program, arguments and URL;
- what the setup driver reported, with the folder installs live in, and a
  sign-in's link and code, each good for one sign-in only.

So don't put secrets in MCP arguments or URLs. Names of variables and
arguments are written as arrays of bytes, as Rust writes them. Treat a
recording as private, and read it through before you share it.

### How it's written

The file is made new, readable only by you. If anything is at that path
already, even a link, CAF logs a warning and doesn't record. It's written on
a thread of its own, so the disk never holds CAF up, and it's complete once
`shutdown` returns.

If a write fails, CAF logs a warning and stops recording. If more than
256 MiB waits to be written because the disk has fallen behind, it stops too,
and once what came before is written, it ends the file with a line saying
why:

```json
{"stopped": "the disk has fallen behind"}
```

Either way, what's in the file still replays, as far as it goes.

## What goes where

Inside, one task owns the core and its drivers. Every directive the core
gives goes to its driver:

| Directive | Where it goes |
|---|---|
| Agent | `AgentDriver::apply` |
| Timer | `TimerDriver::wake_at` |
| Policy: decide | The policy, whose answer comes back to the core |
| Policy: withdrawn | Stops that decision |
| Viewer | Wakes the chat's watches |
| Setup | `SetupDriver::apply`, whose reports come back to the core |
| Report | The `log` facade |

A program with its own event loop can use `AgentDriver`, `TimerDriver`,
`SetupDriver` and a `Policy` on their own, and wire them to the core itself.

---

# Installing and Signing In

_CAF / Getting Started_

> Let CAF install an agent's adapter and sign in to it from a tokio program. Offer an agent CAF installs, follow where each agent stands, install it with the user's consent, run its sign-in, and let viewers do the same.

CAF can install an agent's adapter itself and sign in to it, so your program
needs no terminal and no `npm` of its own. Everything about one agent (which
version, how to install it, how to sign in) is in its profile, so this works
the same for every agent CAF has a profile for. Today that's Claude.

## Offer an agent CAF installs

```rust
let claude = AgentSpec::installed("claude", Builtin::ClaudeAgentAcp);
let (caf, running) = Caf::<NoAppItems>::start(Config::new(Host::new("eyespy", "0.4.0"), vec![claude]));
```

CAF installs the adapter at exactly the version its profile was checked at,
in a folder of its own, named after its profile whatever you call the
agent: `claude-agent-acp-0.98.0`. Every CAF program on the machine shares
the folder these live in, and so one install of each agent: by default `~/.local/share/caf/agents`
(`$XDG_DATA_HOME/caf/agents` if that's set). `Config::installs` names
another.

An agent offered with `AgentSpec::command` is started with your own command
instead. CAF doesn't install it, but it can still sign in to it if its
profile says how.

## Follow where each agent stands

```rust
let mut agents = caf.watch_agents();
while let Some(statuses) = agents.next().await {
    for status in &statuses {
        draw_agent(status); // its install state and sign-in state
    }
}
```

`watch_agents` gives every agent's status at once, then again each time any
of it changes. If it changes faster than you read, you get only the latest.
Each `AgentStatus` has two parts.

Its **install state**:

| State | Meaning |
|---|---|
| `Host` | You start it with your own command |
| `Unknown` | CAF hasn't looked yet |
| `Missing { size }` | Not installed: installing takes about `size` bytes |
| `Installing { done, size }` | Being installed |
| `Installed { version }` | Installed |
| `Cannot(why)` | It can't be: no Node, or one too old; no npm; no build for this machine; or the last try failed, and why |

Its **sign-in state**:

| State | Meaning |
|---|---|
| `Unknown` | Nothing has said yet |
| `SignedOut` | Signed out |
| `SigningIn(link)` | The user has something to do: open `link.url`, maybe type `link.code` there, maybe paste a code back |
| `SignedIn(how)` | Signed in, with an account, an API key or a gateway |

CAF keeps how an agent is signed in, never who: the account's email never
reaches its state, its logs or a recording.

It also says whether CAF can turn off the agent's own tools
(`own_tools_off`), which it must to run it: see
[Agents and profiles](/caf/concepts/agents-and-profiles.md#an-agent-has-only-your-tools).

CAF looks as it starts. Call `caf.check_agents()` to look again, such as
after the user installs Node: it looks at every agent, and at what the
machine has. A viewer can ask the same, with a **Check again** button
([below](#let-viewers-do-it)).

## Install it

Installing Claude's adapter takes about 630 MB, so it's the user's decision.
A chat opened with an agent that isn't installed waits for it
(`ChatState::WaitingForAgent`), with its messages waiting too. Show the
agent's status beside the chat, with an Install button:

```rust
caf.install(&AgentName("claude".into())).await?;
```

Progress shows in `watch_agents`. Once it's installed, every chat waiting
for it starts. If it fails, their waiting messages stop, with a note, and
the agent's status says why. `caf.stop_install` stops it, and stopping a
waiting chat stops its messages.

What CAF does to install it:

- **npm packages** are installed with `npm ci --ignore-scripts` from a
  lockfile CAF ships, so every dependency comes at the exact version and
  hash it was checked with, and no install script runs. This needs Node 22
  or later, and npm, on `PATH`. CAF never installs Node itself.
- **Downloads** come over `https` only, and are checked against their
  SHA-256 before anything is unpacked. They take their proxy from the
  environment variables npm reads (`npm_config_https_proxy`, then
  `HTTPS_PROXY` or `HTTP_PROXY`), unless `NO_PROXY` names the host or a
  domain it's in. A proxy set only in `.npmrc` is npm's alone.
- **An agent that keeps its sign-in in a folder CAF gives it** gets one,
  named after its profile like its installs, such as
  `claude-agent-acp-private`, beside them, readable only by the user. It
  outlives every version, and CAF never removes it.
- **Each install** is built in a hidden folder and renamed into place whole,
  so one cut off partway leaves nothing that looks installed. Two programs
  installing the same agent at once install it once: a lock in the folder
  makes the second wait, and it then finds the first's.
- **Old versions** are removed once the version your program pins has
  started, but only once no process, in any CAF program, has started from
  the old one for 14 days, and never while one still runs from it. So two
  programs pinning different versions don't remove each other's.

## Patched adapters

Sometimes an adapter needs a fix its upstream hasn't made yet. Rather than
wait, CAF patches it as it installs it: a profile's recipe may carry exact
edits to files npm installed, or a download unpacked, kept in CAF's
repository and compiled in, never downloaded. CAF doesn't send these
fixes upstream for now.

A patched install is of a version of its own: the upstream version, then
`+caf.` and the patch's level. Claude's adapter is installed patched, as
`0.98.0+caf.1`, in `claude-agent-acp-0.98.0+caf.1`, and
`Installed { version }` says `0.98.0+caf.1`.

Patching is an install's last step, and each file is checked three ways:

- it must be exactly the file the patch was written for, by its SHA-256;
- each edit's text must be in it exactly once, as the edits before it left
  it;
- the result must be exactly the file CAF tested, by its SHA-256 again.

The original is kept beside it, as `<file>.caf-original`, and the patched
file written whole and renamed into place. If any check fails, the install
fails with `InstallFailure::Patch`, saying which file and which check, and
nothing of it is left: CAF never runs a half-patched adapter. Trying again
downloads it afresh. If that fails the same way, the patch doesn't fit
what upstream serves, and only a newer CAF fixes it.

A later CAF may patch the same upstream version again, at a higher level.
If an earlier level of it is installed, CAF makes the new one from it,
since nothing is downloaded: it links the earlier install's files into a
new folder, puts back each original, and patches that. Nothing is changed
in place, so the earlier install, and any program still running from it,
is untouched.

- **As CAF looks at what's installed**, it does so without asking,
  unless the user stopped installing it this run (`caf.stop_install`).
  The agent shows `Installing`, then `Installed`. If this fails, the agent
  reads as `Missing`, its waiting chats go on waiting, and installing it,
  with the user's leave, downloads it as any other.
- **When you call `caf.install`**, it's made this way too, if it can be,
  even if CAF had already started making it by itself. The user has agreed
  to install it, so if this fails, CAF downloads it at once, and the agent
  goes on `Installing`.
- **A `caf.install` before CAF has first looked** shows `Installing`, and
  waits for the look to choose: made from an earlier level, downloaded,
  already installed, or, if the machine can't install it, `Cannot` and why,
  with the messages waiting for it stopped, as for an install that failed.
  If CAF can't look, it downloads.

Once making a level from an earlier one has failed, CAF doesn't try it
again this run.

An earlier patch level of the version your program pins counts as an older
version, and is removed as one is. A later level, which another program
may pin, never is.

## Sign in

```rust
let claude = AgentName("claude".into());
caf.sign_in(&claude).await?;
```

CAF runs the sign-in the agent's profile names, never one the agent
suggests. For Claude that's its adapter's own `--cli auth login`, which
needs no terminal. Its state becomes `SigningIn`, and once the command gives
its link, `link.url` has it. Show it to the user to open. CAF has already
checked it points at one of the sites the profile allows, such as
`claude.ai`, and a sign-in whose link points anywhere else is stopped.

The user approves in their browser, and the sign-in finishes by itself. If
their browser is on another machine, the page gives them a code to paste
back instead. When `link.paste` is true, take it from them and pass it on:

```rust
caf.paste(&claude, code).await?;
```

When the sign-in ends, the state becomes `SignedIn`. A chat whose last turn
failed because the agent was signed out gets a note saying the user signed
in. Its Send again stays: CAF never resends by itself. A failed or stopped
sign-in (`caf.stop_sign_in`) goes back to how it was.

`caf.sign_out` runs the profile's sign-out command.

A failed turn whose remedy is `Remedy::SignIn` is a button for exactly this
call.

## Let viewers do it

A viewer hears every agent's status, as a `ToViewer::Agents` message right
after the welcome and again each time any of it changes. Installing and
signing in from a viewer is your decision, as opening chats is. It's off by
default:

```rust
let mut rules = ViewerRules::default();
rules.agents = true;
```

It covers every `FromViewer::Agent` request: installing, signing in or out,
learning an agent's settings, and checking again (`AgentAction::CheckAgain`),
which is `caf.check_agents()`, for every agent, whichever the request
names. With it off, each is answered
`NotAllowed`, and it sees a sign-in under way without its link or code.
Whoever opens the link and approves it, or types the code on the
provider's site, chooses whose account the agent signs in to: a viewer
that may only watch mustn't be able to sign your agent in to its own.

## Recordings

A recording (`Config::record`) keeps what it needs to replay the run, and
nothing a sign-in should keep private:

- a pasted code is written as `null`;
- Claude's sign-in status is written as its kind alone, such as
  `{"authStatus": {"kind": "account"}}`;
- the sign-in link and the code shown on the site are kept as they came.
  Each is good for one sign-in only.

## On your own loop

A program that wires the core up itself uses `SetupDriver` like the other
drivers: hand it each `Setup` directive with `apply`, and give the core each
report from `next` as `Event::Setup`. Start each adapter process with a
shared lock on its install folder, as `AgentDriver` does with
`AgentDirective::Start`'s `hold`, so no CAF program removes the folder while
the process runs.

---

# Saving and Restoring Chats

_CAF / Getting Started_

> Keep chats from one run of your program to the next. Give CAF a store, keep chats on shelves, list and restore them, put them away, close (archive), unarchive, delete and move them, keep your own data on each, and write a store of your own, with what CAF saves, when, and its promise that a save stays readable.

CAF can save every chat as it goes, so the user can close your program, open
it again tomorrow, and carry on where they were. Your program says where
chats are kept; CAF decides what to write and when, and brings a chat back
with its whole record, its own data, and the agent's session to carry on.

## Give CAF a store

A **store** is where chats are kept. CAF comes with one that keeps them in
files, `FileStore` in the crate `caf-save`:

```rust
use caf_save::FileStore;

let mut config = Config::new(Host::new("eyespy", "0.4.0"), vec![claude]);
let root = FileStore::default_root("eyespy").expect("a home folder");
config.store = Some(Box::new(FileStore::new(root)));
let (caf, running) = Caf::<NoAppItems>::start(config);
```

`FileStore::default_root("eyespy")` is `~/.local/share/eyespy/chats`
(`$XDG_DATA_HOME/eyespy/chats` if that's set). The store runs on a thread of
its own, so the disk never holds CAF up.

With no store, CAF saves nothing: opening a chat on a shelf, listing,
restoring, deleting and moving are all refused with `Refused::NotSaved`.

## Keep a chat on a shelf

Each saved chat is kept on a **shelf**, a name your program chooses: one per
project, per user, or just one. The store decides what a shelf is; to
`FileStore` it's a folder. A chat is saved if it's opened with a shelf:

```rust
let mut open = OpenChat::new("claude", "/home/me/project");
open.shelf = Some(Shelf("project-x".into()));
let chat = caf.open_chat(open).await?;
```

A chat opened without one lives in memory only, and is gone when CAF stops.
A shelf's name may be up to 256 bytes long, but not empty, and with no
control characters in it.

## What's saved, and when

**Everything a chat is, is saved**: its whole record, the agent's session to
carry on, and your program's data on it ([below](#your-own-data-on-each-chat)).
What belongs to one run isn't: adapter processes, requests in flight,
timers, and the chat's MCP servers, which hold tokens and sockets, so your
program gives them again when it restores the chat. Questions waiting for an
answer are saved with the record, and dropped when it's restored, as what
asked them is gone.

CAF writes a chat:

- **a second after it changes** (`host.timers.save`), with every change since
  it was last written: streamed words to one item are one change;
- **at once when a turn ends**;
- **whole** the first time, when it's put away or closed, as CAF shuts down,
  and whenever its changes outgrow the last whole copy.

A write that fails, such as on a full disk, is tried again later, whole,
with a warning in the log each time, waiting longer each time up to a
minute. Shutting down waits until it's written, so check the store can be
written to as your program starts.

`caf.shutdown()` returns once every saved chat is written whole and let go,
so the next run, or another program, can have it.

## List what's saved

```rust
let mut saved = caf.watch_saved();
caf.list_saved(Shelf("project-x".into())).await?;
while let Some(chats) = saved.next().await {
    draw_saved(&chats);
}
```

`watch_saved` follows every shelf you've listed, with their chats in the
order they were made, whatever shelf each is on: the whole list at once,
then again each time it changes. Once listed, a shelf is kept up to date as chats on it are saved,
put away and deleted. List it again to see chats another program saved
since.

Each `SavedChat` has its `shelf`, its `header`, which is what to show
without loading it (its id, agent, folder, when it was made and last
changed, your `label` for it, the first line of its first message, how many
turns it has, whether it was closed, and when it was archived), and its
`state`: `Saved`,
`Restoring`, `Loaded`, or `Failed` with why the last restore failed.

## Restore a chat

```rust
let chat = caf.restore(RestoreChat::new(id, Shelf("project-x".into()))).await?;
```

`restore` returns the chat's handle once it's loaded, with the same id it
had. Give it its tools in `RestoreChat::mcp_servers`, as you would to a new
chat. The shelf needn't have been listed.

**Restoring is lazy.** A restored chat is `Idle`: no agent is started until
a message is sent. Then CAF carries on the agent's session: resumed where
the agent can, or loaded, with what the agent replays thrown away, as CAF
has the record already. An agent that can do neither opens a new session,
and the chat says so.

**What was under way is tidied**, as a save may have come at any moment: a
turn that was running is cut off, its unfinished tool calls have failed,
and a message waiting to be sent is stopped, never sent by itself, as what
the user meant then may not stand now.

A chat whose agent your program no longer offers still comes back, with its
record, and sending to it is refused with `Refused::NoSuchAgent`. If you
renamed the agent, and exactly one agent you offer has its built-in
profile, the chat comes back with that one.

A chat that can't be restored is left as it was, and `restore` fails with
`Error::CannotRestore`, saying why:

| Why | Meaning |
|---|---|
| `NotFound` | It isn't on that shelf. |
| `InUse` | Another program, or another `Caf`, has it open: a chat is never open twice. |
| `Newer { version }` | A newer CAF saved it, in a version of the format this one can't read. It's left untouched for that one. |
| `Damaged(why)` | Its save is damaged. |
| `AppData(why)` | Your program can't read the data it saved with it: see [What your program reads, it must keep](#what-your-program-reads-it-must-keep). |
| `Store(why)` | The store failed, such as a disk error. |

Trying again may help after `InUse` or `Store`. The core may also refuse it:
`Refused::Loaded` for a chat that's loaded or being restored already.

## Put away, close, unarchive, delete and move

**Put away** a chat to save it whole and let it go from memory, such as when
the user hasn't looked at it for a while:

```rust
chat.put_away().await?;
```

Its session is closed, its adapter stopped if nothing else uses it, and it's
let go in the store, so another program can have it. A turn running is cut
off first, and messages waiting are stopped. It stays on its shelf, and
restoring it carries on. A watch of it gets how it was left, one last time,
and ends. Until it's written, which is at once unless a move of its shelf is
under way, restoring it is refused as `Loaded`, though it's listed as
saved: try again in a moment.

**Close** a chat when the user is done with it: it's **archived**, as of
then (`Chat::archived`), and a watch of it sees it archived. Its session is
closed, and its adapter stopped if nothing else uses it. A saved chat is
then put away, marked closed, with when it was archived in its header
(`Header::archived`), and can still be restored. One that isn't saved
stays, archived, until CAF stops, and its watches go on. An archived
chat's settings can't be chosen (`Refused::Closed`).

**Archiving sticks.** A closed chat restored is still archived, as it was
left, with no agent started, however many times it's put away and
restored, so your program can keep it in an archive rather than among the
user's chats. Putting it away, or closing it again, keeps when it was
archived. It's unarchived only when your program says so, or when the user
sends it a message:

```rust
chat.unarchive().await?; // or send to it: that unarchives it first
```

Unarchived, it's `Idle`, and its agent starts when a message is sent, as a
restored chat's does. Unarchiving a chat that isn't archived does nothing.
A message sent to an archived chat goes as to any other; one refused, such
as an empty message, leaves it archived. While it's archived, its settings
can't be chosen (`Refused::Closed`). Putting an archived chat away, or
closing it again, keeps when it was archived. A chat saved closed by a CAF
from before archiving is restored archived, as of when it's restored.

**Delete** a chat for good, loaded or not: one that's loaded is closed and
let go first.

```rust
caf.delete(id, Shelf("project-x".into())).await?;
```

**Move** a shelf to move every chat on it, loaded or not, such as when the
user renames a project:

```rust
caf.move_shelf(Shelf("project-x".into()), Shelf("project-y".into())).await?;
```

All of it moves, or none: a move onto a shelf that has chats already isn't
supported, and a chat on it that another program has open stops the move.
Either way the move fails, says so in the log, and every chat stays where it
was. Meanwhile, CAF holds back everything else for chats on either shelf, so
nothing is written in the wrong place.

## Your own data on each chat

Each chat has a slot for your program's own data about it, such as its
title, saved and restored with it. Give CAF your type, which says what one
line to show for the chat, its **label**:

```rust
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
struct Notes {
    title: String,
    pinned: bool,
}

impl AppData for Notes {
    fn label(&self) -> Option<String> {
        Some(self.title.clone())
    }
}

let (caf, running) = Caf::<NoAppItems, Notes>::start(config);
chat.set_data(Notes { title: "Fixing the tests".into(), pinned: true }).await?;
let notes = chat.data().await?;
```

A chat's data is the default until you set it, and is set whole. Its label
shows in `watch_chats`, in each saved chat's header, and to viewers, who
never see the data itself. A recording ([`Config::record`](/caf/getting-started/the-debugger.md#what-a-recording-holds))
holds the data each time it's set, so keep secrets out of it.

### What your program reads, it must keep

A save stays readable while your program changes, so CAF checks your data
as it reads it back. Your data comes back only if what your type writes
back holds all of what was saved: every key of every map, with what it
held, every list as long, and everything else equal. Keys your type adds,
as a newer version of your program does, are fine. Anything else, such as a
field your type no longer has, would be lost when the chat is next saved, so
CAF refuses to restore it (`AppData`) and leaves the save as it was, for a
version of your program that can read it.

So add new fields with `#[serde(default)]`, and never remove or rename one.

Items of your program's own kind in the record are checked the same way,
except that one your program can't read doesn't stop the chat: it comes
back as an `Unknown` item with the summary it had, and is saved back
exactly as it was, so a version of your program that can read it gets it
back. Items in a tool call have no such wrapping, so they stop the chat as
your data does. Through JSON, an item keeps only text keys and no raw
bytes.

## Viewers

A viewer, such as a page using the
[TypeScript caf-sdk](/caf/getting-started/a-chat-in-the-browser.md#saved-chats),
gets the saved chats on every shelf you've listed, right after the agents,
and again whenever they change. Each chat in its list of chats loaded, in
the order they were made, says its label and shelf, and when it was
archived if it is: an archived chat restored, or closed and not saved, is
listed, marked. A viewer may close and unarchive chats
(`FromViewer::Close`, `FromViewer::Unarchive`) as it may act on them
(`ViewerRules::act`). Closing a chat that isn't saved ends no watch of it,
as it may be unarchived, so a viewer should unwatch an archived chat it
stops showing: each watch counts against `ViewerRules::max_watches`. Its
request to restore a chat goes to `ViewerRules::restore`, which gives it
its tools, or refuses it; by default it refuses every one:

```rust
let mut rules = ViewerRules::default();
rules.restore = Box::new(|chat, shelf| {
    (shelf.0 == "project-x").then(|| RestoreChat::new(chat, shelf.clone()))
});
```

## The files

`FileStore` keeps each shelf in a folder of its own, and each chat as four
files in it:

```text
<root>/<shelf>/<chat>.head      what lists show
<root>/<shelf>/<chat>.caf       the chat whole, as last written
<root>/<shelf>/<chat>.journal   what changed since
<root>/<shelf>/<chat>.lock      held while a program has it loaded
```

The folders and files `FileStore` makes are readable only by the user; a
folder that's there already, such as the root you give it, keeps its own
permissions: make a root of your own private yourself. A whole copy replaces the
old one in one step, and each change is synced before it counts as written,
so a crash leaves the chat as it was last written, and at worst loses a
change being written. The locks are the system's, so a program that dies
lets go of its chats; for that, the root must be on a local disk, not a
network one.

Chats are compressed as they're written, quickly. `FileStore::squeeze`
compresses again, as hard as it can, every chat nobody has changed for a
while: run it now and then, such as once a day for chats a week old, on a
thread of its own, as it's slow.

## Writing your own store

A program that keeps its data somewhere else, such as eyespy in its own
SQLite database, can keep chats there too, by writing a `caf_save::Store`.
A store only keeps bytes: CAF turns chats into bytes and back, so the format
stays CAF's. For each chat it keeps three things, by shelf and chat id: its
header, its snapshot (the chat whole) and its journal (records added to the
end).

```rust
impl Store for MyStore {
    fn list(&mut self, shelf: &Shelf) -> Result<Vec<(ChatId, Vec<u8>)>, StoreError> { … }
    fn load(&mut self, shelf: &Shelf, chat: ChatId) -> Result<Stored, StoreError> { … }
    fn snapshot(&mut self, shelf: &Shelf, chat: ChatId, header: &[u8], snapshot: &[u8]) -> Result<(), StoreError> { … }
    fn append(&mut self, shelf: &Shelf, chat: ChatId, header: &[u8], record: &[u8]) -> Result<(), StoreError> { … }
    fn release(&mut self, shelf: &Shelf, chat: ChatId) { … }
    fn delete(&mut self, shelf: &Shelf, chat: ChatId) -> Result<(), StoreError> { … }
    fn move_shelf(&mut self, from: &Shelf, to: &Shelf) -> Result<(), StoreError> { … }
}
```

Its calls block, and come from one thread at a time, in the order CAF gives
them. It must:

- **lock a chat for one program at a time**, from when it's loaded or first
  written until it's released, so a second gets `StoreError::InUse`;
- **replace a snapshot and empty the journal in one step**, so a crash
  leaves one or the other, whole;
- **add each record after everything before it**: one cut off by a crash
  may be left, as the format finds it;
- **replace a header whole**;
- **never remove or change a chat it wasn't told to.**

A store that can say whether it holds a chat's lock already
(`Store::holds`) lets CAF let go of a chat it loaded and couldn't read only
if loading it took the lock. A write that fails is tried again until it's
written, and shutting down waits for it, so fail only when you must. A
store that panics fails what it was doing, as if it had said so, lets go
of a chat it was loading, and is used again. On a runtime other than tokio, `caf_save::carry_out` does one
of the core's directives to your store and gives back its answer: the
storage driver's whole job.

## A save stays readable

**Saves stay readable forever, and a CAF never changes one it can't read.**
The format's version, `caf_save::VERSION`, goes up with every change to
what's saved, even a field added. So a CAF meeting a save from a newer one
always knows, and leaves it untouched (`Newer`), rather than read it, lose
what it doesn't know, and write it back without it. A newer CAF reads every
older version's saves, and the first time it writes one, writes it whole in
its own version. A change of shape, rather than an addition, is migrated
from every older version as a save is read: version 5's notes about
settings, which name their choice, read from an older save with no name.
Every version has a sample chat, saved by it, that each release of CAF is
tested against.

---

# Choosing the Model

_CAF / Getting Started_

> Let the user choose an agent's model, how hard it thinks and fast mode, for any agent, from a tokio program. Read what the agent offers, choose for a chat or as your program's default, follow what the agent changes by itself, and learn what an agent offers before any chat.

An agent says which models it has, how hard each can think, and whether it
has a fast mode, and the list differs by account, gateway and version. CAF
reads it from whichever way the agent says it, and gives you one shape for
every agent: three settings, `Model`, `Effort` and `Fast`.

## See what the agent offers

Once a chat's session opens, its `settings` hold what the agent offers and
what was chosen:

```rust
for setting in &chat.settings.offered {
    match &setting.form {
        SettingForm::Choices(choices) => draw_menu(setting, choices), // models, effort levels
        SettingForm::Switch => draw_toggle(setting),                  // fast mode
        _ => {}
    }
}
```

Each setting has the agent's own `name` for it and what the agent says it
is now (`current`). Each choice has the agent's id, its name, and maybe a
description and a group. A choice such as Claude's `default` model, which
stands for whatever the agent would pick, is passed on as it is.

What the agent offers changes as it goes: Claude's effort levels depend on
the model, and fast mode is offered only while the model has it. Read
`settings` again whenever the chat changes.

## Choose

```rust
chat.set_setting(SettingChoice::model("sonnet")).await?;
```

What's chosen is in `settings.chosen`, apart from what the agent says is
current: where they differ, the change is waiting. It's sent at once if no
turn is running, and otherwise as the turn ends, so it applies from the
next message. Only the latest choice of each setting counts.

Choices are matched exactly, by the agent's own ids: `opus` never quietly
becomes `opus[1m]`. What the agent says it uses counts as offered, even
if it isn't in its list. Once the agent has said what it offers, in this
run, a choice it doesn't offer is refused (`Refused::NoSuchSetting`). A
choice is checked against what's offered when it's made, so an effort
level only a new model has can be chosen once the model change is
answered, not with it.

A message never goes with a choice made for the chat silently replaced:
either it fails, or the chat says what changed. If a choice made for the chat itself can't be
applied, because the agent doesn't offer it or refuses it, every message
waiting fails (`FailureReason::SettingNotApplied`), with Send again, and
the chat says so whether or not any waits (`Note::NotOffered`, or
`Note::NotApplied` for one refused). The setting falls back to your
program's default, if the agent offers it, and otherwise to what the
agent uses. Your program's own default that can't be applied is dropped
quietly.

Each note about a setting holds the choice, and the agent's name for it,
such as "Opus (1M context)", as CAF last knew it (`name`): from what the
agent offers now, or offered before, in this chat's session or any other.
A choice never offered, and a switch such as fast mode, have none; show
the choice's id then.

A change the agent never answers doesn't fail anything: as with any
request it leaves unanswered for `Timers::request` (60 s), its program is
taken to be stuck and restarted, or, while another chat is mid-turn on
it, only this chat's session is closed. The session opens again at once
if a message waits, and otherwise with the next, and every choice is
sent again before the messages go. If the agent had lost the session,
it's opened again and the choice sent to it, as a message would be.

A choice already applied that the agent stops offering, such as fast mode
when the model changes to one without it, falls back the same way, and
the chat says so (`Note::NotOffered`); the messages go on.

## Choose before the chat opens

A chat can choose as it's opened, and your program can choose for every
chat with an agent:

```rust
let mut claude = AgentSpec::installed("claude", Builtin::ClaudeAgentAcp);
claude.settings = vec![SettingChoice::model("haiku")]; // the cheapest, for every chat

let mut open = OpenChat::new("claude", "/home/me/project");
open.settings = vec![SettingChoice::effort("high")]; // this chat's own
```

The chat's own choice comes first, then your program's default, then the
agent's own. They're sent as the session opens, before any message. A
default the agent doesn't offer is dropped quietly; a chat's own choice
that it doesn't offer fails every message waiting, saying so.

Which choices are the chat's own is saved with it (`settings.own`). A
restored chat keeps them, and takes your program's defaults as they are
then for the rest: what the agent chose by itself in an earlier run never
outranks them.

Claude reads the user's own default model even with none of their
settings, so CAF sends a chat's choices again each time its session
opens.

## What the agent changes by itself

An agent may change a setting itself, as Claude falls back to another
model when one refuses. The choice follows it, and the chat says so with a
note (`Note::AgentChanged`), in the turn it happened in. Either way, the
choice is the agent's now, not the chat's own.

Each turn records the model it was sent on (`Turn::model`).

## Learn what an agent offers before any chat

To offer models before the user opens a chat:

```rust
caf.learn_settings(&AgentName("claude".into())).await?;
```

CAF starts the agent if it isn't running, opens a session with none of the
agent's tools, reads what it offers, and closes it. The session is in
CAF's installs' folder if CAF has found installs there, and otherwise in
`/`, as no chat gives it a folder. No message is sent, so it costs
nothing. Where it stands is in the agent's status from `watch_agents`, as
`settings`: `Unknown`, `Learning`, `Known(settings)` or `Failed(why)`,
`why` a `LearnFailure` that says what went wrong, such as `NotInstalled`
or `SignInNeeded`, for your program to word; where the agent or the system
said why, its words are kept apart (`Refused { message }`,
`CouldNotStart { error }`), to show as theirs.
What was learned before stays shown while it's learned again, and if that
fails. If the agent's adapter serves chats and can't close sessions, the
session stays until the adapter stops. Every chat's session tells it too.
It isn't saved: it depends on the account and the agent's version, so it's
learned again each run.

## Saving

A chat's settings are saved with it, and a restored chat sends its choices
as its session opens, like any other.

## Viewers

A viewer chooses with `FromViewer::Set`, allowed as the rest of acting on
chats is, and learns an agent's settings with `AgentAction::LearnSettings`,
allowed as installing is.

---

# Usage

_CAF / Getting Started_

> Show what each turn and each chat spent, in tokens and money, and how much every CAF app on the machine has used over a day, a week or a month. What a turn records, a chat's spend, the ledger every app shares and where it is, prices and their three layers, summaries, letting viewers see them, and turning it off.

CAF records what every turn spends, if the agent says: its tokens, by
model, and what it cost. Each chat adds its turns up, and every turn also
goes into a **usage ledger** that every CAF app on the machine shares, so
your program can show how much the user has used, across all of them.

## What a turn records

When a turn ends, the agent's answer says how many tokens it used. CAF
keeps them on the turn, as `Turn::spent`:

- **tokens**, by kind: input read fresh, input read from the cache, input
  written to the cache, and output, with how much of it was thinking if the
  agent says;
- **by model**: an agent that splits them by model, as Claude and Codex do,
  counts what its subagents and compaction spent too, so CAF keeps that
  split; otherwise one row, against the turn's model. Each row has the
  agent's id for its model, and a `name` to show where the agent's profile
  knows how its ids are named: Claude's `claude-opus-5-5` is "Opus 5.5";
- **cost**, as the agent reported it, if it did: Claude says what its
  session has cost so far, and the turn's cost is how much that rose;
- **fast mode**, if it was on, which costs more.

A turn the agent says nothing about has no record. It still happened; it
just isn't counted.

## A chat's spend

Each chat has a `spend`: its turns' records added up, with the tokens, the
cost the agent reported, and the cost CAF estimated for turns it didn't.

```rust
let spend = &chat.spend;
draw_cost(spend.cost(), spend.estimated > 0.0); // say "about" if any was estimated
```

It's sent again (`Change::Spend`) whenever a turn adds to it, or the prices
change, so every viewer shows the same figure. A reported cost is never
replaced by an estimate. An estimate is never stored: it's worked out with
the prices of the time, so a price put right puts every figure right.
Tokens on a model no price covers are counted as `unpriced`, and their cost
is in neither figure. Money is in US dollars: a cost an agent reports in
another currency is kept as it came, but estimated instead in the spend,
as CAF converts no currency.

A chat's spend is saved with it, but a restored chat's is worked out again
from its turns. Turns from before CAF recorded usage have no record, so it
counts from when it began.

## The ledger

Every turn's record also goes, as one line, into the ledger: one folder
for the whole machine, shared by every CAF app on it.

```text
~/.local/share/caf/usage/        ($XDG_DATA_HOME/caf/usage if that's set;
  clackatoo/2026-10.jsonl.zst     %APPDATA%\caf\usage on Windows)
  clackatoo/2026-11.jsonl
  eyespy/2026-11.jsonl
  prices/own.json
  prices/litellm.json
  limits/claude-agent-acp.json
```

Each app has a folder, named for its host (`Host::new("eyespy", …)`), and
a file per month, with a line per turn. So no host may be named `prices`
or `limits`, in any case, as those folders are CAF's: its lines are
refused, which is reported to the log, and never written. A month that has ended is
compressed. Lines are only ever added, each whole, so two copies of an app
never mix theirs. A line holds when the turn ended, the app, the chat and
turn, the agent, and what it spent: never what was said, and never the
folder a chat worked in, so the ledger can't tell which projects you work
on.

It's on by default: `Config::new` keeps it in that folder. Writing it is a
thread's of its own, and it never holds a chat up. A line it can't write
is kept, and tried again with the next and every hour; the first failure
in a row is reported to the log (target `caf`). By the time
`Caf::shutdown` returns, every line is written, or reported lost. A disk
that has hung holds shutting down up for thirty seconds at most: then how
many lines may be lost is reported, and CAF stops without them.

The folder also keeps each agent profile's [account
limits](/caf/getting-started/account-limits.md), how much of the
subscription's five hours and week is used, as the agent last said:
a file per profile in `limits/`, so CAF has them as it starts, before the
agent says again. Each save is merged with the file, window by window, the
latest heard winning, so two apps never undo each other's news. Another
app's news reaches this one as it starts, or with its own next save, when
it finds that news in the file: not before. Limits that can't be kept are
reported to the log, and tried again with the next save, every hour and as
CAF shuts down; they cost only keeping them across restarts.

## Prices

CAF estimates cost from a table of prices, in three layers. The first that
has a model prices it:

1. **the user's own**, in `prices/own.json`, so every app agrees;
2. **LiteLLM's table**, as last fetched, in `prices/litellm.json`;
3. **the snapshot bundled with CAF**: what prices are before the first
   fetch, offline, or with fetching off.

[LiteLLM's table](https://github.com/BerriAI/litellm/blob/main/model_prices_and_context_window.json)
is fetched once a day, by whichever app looks first, so every app sharing
the folder shares the fetch. A fetch that fails changes nothing, and is
tried again an hour later. A model is found by the agent's id for it:
`claude-haiku-5-5` is also found as `anthropic/claude-haiku-5-5`, and
`claude-haiku-5-5-20261001` as `claude-haiku-5-5`.

```rust
let prices = caf.prices().await?; // each model's price, and its layer
caf.set_price("claude-haiku-5-5".into(), Some(ModelPrice::new(1.0, 5.0))).await?; // per million tokens
caf.set_price("claude-haiku-5-5".into(), None).await?; // the next layer prices it again
```

`ModelPrice::new` gives input and output prices, with the cache prices the
same as input's; set its fields for the rest. A price set is in force for
every chat once `set_price` returns. Another app sharing the folder takes
it within the hour, as each app reads its prices again every hour, and
before every summary it reads, so a summary is always priced as the
prices are now.

## Summaries

A **summary** is how much was used over a period, from every app's lines:
what a usage page is drawn from.

```rust
let query = UsageQuery::new(since, until, "Europe/London"); // by day, in the user's time zone
let summary = caf.usage(query).await?;
for bucket in &summary.buckets {
    // one per day, app, agent, model and fast mode, with turns in it
    draw_bar(bucket.start, &bucket.app, &bucket.agent, &bucket.model, bucket.reported + bucket.estimated);
}
```

Each bucket has its tokens, its reported and estimated cost, its unpriced
tokens and how many turns. `query.by = Resolution::Hour` cuts it by hour
instead, and `apps` and `agents` keep only those named. Every other view, by agent, app, model or day,
is a sum of buckets. An agent is named by its built-in profile, such as
`claude-agent-acp`, so one agent two apps name differently counts as one.
`chats` says how many chats the period covers, `prices` the price of each
model in it, and `unreadable` any file that couldn't be read: a summary is
never quietly short.

A bucket names its model by the agent's id for it, such as
`claude-opus-5-5`. `names` gives each model a name to show, such as
*Opus 5.5*, sorted by id: the name its latest turn was recorded with
(`ModelTokens::name`), or, for turns recorded before CAF named models, or
with an empty name, the name the agent's built-in profile gives it now
(`Builtin::model_name`). A model with neither, such as one of an agent with
no profile, isn't in it: show its id.

It's read on a thread of its own, so it never holds a chat up. A turn
that ended a moment ago may not be in it yet. A time zone CAF doesn't know,
or a period that's empty or longer than 400 days, is `Error::BadQuery`.

## Viewers

A viewer watching a chat sees its turns' records and its spend, as it sees
the rest of the chat. Summaries and prices cover every app on the machine,
so they're for viewers the host lets: `ViewerRules::usage`, off by default.
The welcome says if it's on (`Rights::usage`). A viewer asks for a summary
with `FromViewer::Usage`, answered with `ToViewer::Usage`, and sets a price
with `FromViewer::SetPrice`, answered `Done`, or `PriceNotSet` with the
system's words if it couldn't be written. One that isn't let is answered
`NotAllowed`.
The link goes on while a summary is read.

## Turning it off

```rust
config.usage = None; // no ledger
```

With no ledger, chats still record their turns and their spend, priced with
the bundled snapshot, but there's no summary and no price of the user's
own: both are `Error::NoLedger`, and `Outcome::NoLedger` to a viewer.

To keep the ledger and never reach the network, turn fetching off:

```rust
let mut usage = UsageConfig::new(folder);
usage.fetch_prices = false; // the user's own prices and the bundled snapshot only
config.usage = Some(usage);
```

Tests should do one or the other, so they never write to the user's
ledger.

---

# Account Limits

_CAF / Getting Started_

> Show how much of the user's subscription each agent has used, window by window, as the agent reports it, such as Claude's five hours, its week and each model's week. Where limits come from, whose they are, how they change over time, where they're kept, and how a viewer shows them with the SDK's helpers.

A subscription allows so much use in each of a few windows of time:
Claude's, five hours from the first turn in them, a week, and a week for
each of some models. When a window's allowance is used up, the agent
refuses turns until it resets. CAF keeps what the agent last said of
each, its **account limits**, so your program can show the user how much
is left before they run out.

## Where they come from

Only Claude says, for now, and only, as the Claude Agent SDK documents
its `rate_limit_info` (type `SDKRateLimitInfo` in its `sdk.d.ts`, as
bundled with `@agentclientprotocol/claude-agent-acp` 0.98.0), for
"claude.ai subscription users": an account signed in with an API key
should expect none. Its adapter tells a session of them in a
`usage_update`. An agent that never says has none.

Claude reports them from a reply's rate-limit headers when they say
something other than what that Claude process last heard, and first from
a quota check it makes as it starts. Upstream's adapter drops that first
report, which arrives before the first prompt's turn has begun, and any
that arrives before a turn has had a reply; and as the turn's own reply
then says nothing new, a new chat may never show its limits. CAF installs
Claude's adapter patched
([Installing and Signing In](/caf/getting-started/installing-and-signing-in.md)),
as `0.98.0+caf.1`, and that passes on every report it hears while the
session lasts (one still held as the session closes is lost): so a chat
hears the limits with its first prompt, as a live run confirms. A host that runs
upstream's adapter itself, by its own command, may never hear them.

After that, a report comes only when something changes, which may be
rarely: show limits as news when they come, and say how old they are.

Each window has:

- **`kind`**: `FiveHours`, `Week`, `ModelWeek` with the model's name in
  lower case (`opus`, `sonnet`), `ExtraWeek` (the week with extra usage
  counted in), or `Other`, with the agent's own name for a window CAF
  doesn't know;
- **`used`**: how much of it is used, a whole percent, 0–100;
- **`resets`**: when it starts again, if the agent said;
- **`state`**: `Fine`, `Warning` (the agent warns it's near the end), or
  `Refused` until it resets, always 100% used;
- **`heard`**: when CAF last heard of it.

`extra_usage` says whether extra usage, paid for beyond the plan as it
goes, is in use, if the agent has said.

## Whose they are

An account's, not a chat's: every chat with an agent, and every agent with
the same profile, shares them, as they share one sign-in. They come with
the agent's status, as `AgentStatus::limits`, the same for every viewer:

```rust
use std::time::{SystemTime, UNIX_EPOCH};
use caf_core::time::Wall;

let mut agents = caf.watch_agents();
while let Some(statuses) = agents.next().await {
    let since = SystemTime::now().duration_since(UNIX_EPOCH)?;
    let now = Wall(i64::try_from(since.as_millis())?); // milliseconds since the epoch
    for status in &statuses {
        for window in &status.limits.windows {
            draw_limit(&status.name, window, window.pace(now)); // see "Showing them"
        }
    }
}
```

They're information only. CAF never holds a message back for them, nor
warns before sending: a turn the agent refuses for its limits fails as
it does without them, as `FailureReason::UsageLimit`.

## Over time

- **The latest news wins, window by window.** A report changes only the
  windows it names, each replacing the one of its kind if it was heard
  later, whichever chat, app or saved copy it came from.
- **A window is forgotten once its reset has passed**, and the statuses
  are told again. One with no reset stays until another replaces it.
- **Signing out, and a sign-in finishing, clears them**, as the account
  may have changed. A window heard before that is never taken back.
- **A limit reset early** by the provider, or raised by a new plan, shows
  as it was until the agent next says, with the next turn: CAF can't ask.
  `heard` lets you say how old a window is.

## Where they're kept

In the usage folder every CAF app on the machine shares
([Usage](/caf/getting-started/usage.md)), a file per profile in `limits/`,
such as `limits/claude-agent-acp.json`. So an app has them as it starts,
before the agent says again. Each save is merged with the file, so two
apps never undo each other's later news, and an app takes in what another
kept as it starts and whenever it saves news of its own. With no usage
folder (`config.usage = None`), limits are still kept while CAF runs, but
not across restarts.

## Showing them

A window's **pace** is how much of it has gone by, as a whole percent:
where `used` would be at an even pace. Used above it is ahead of pace, on
the way to running out before the reset. A window CAF doesn't know the
length of (`Other`), or with no reset, has none.

The TypeScript SDK has the rest, so every viewer says the same of them:

```ts
import { label, left, lowest, lowness, pace } from "@clackatoo/caf";

for (const agent of caf.agents) {
  const worst = lowest(agent.limits); // the window with least left, for a glance
  if (worst !== null) drawDot(agent.name, lowness(worst)); // "fine", "low" or "out"
  for (const window of agent.limits.windows) {
    drawBar(label(window.kind), left(window), pace(window, Date.now()));
  }
}
```

- `label` names a window for showing: `5-hour`, `Weekly`, `Weekly · Opus`,
  `Weekly · extra included`, or the agent's own name for it.
- `left` is how much is left, as a whole percent: none once refused.
- `lowness` is `low` at 20% left or less (`LOW_LEFT`), and `out` at 10%
  or less (`OUT_LEFT`), or once refused; otherwise `fine`.
- `lowest` is the window with the least left, the first of them on a tie,
  or `null` with none.
- `pace` and `length` match caf-core's `LimitWindow::pace` and
  `WindowKind::length` exactly.

Each takes an agent's status as a watch gives it, read-only. A kind of
window newer than the SDK has no length and no pace, and is named by its
type.

Pace and resets move with the clock, not with news, so draw them again as
time passes: a viewer has no other word that a window is nearer its
reset.

---

# A Chat in the Browser

_CAF / Getting Started_

> Show and drive CAF's chats from a web page. A Rust backend serves each browser with caf_driver_tokio::viewer::serve over a WebSocket, and the page follows chats and acts on them with the TypeScript caf-sdk's Connection.

CAF runs in Rust, but the chat can be drawn anywhere. A **viewer** is
anything that shows chats, such as a web page. It talks to CAF over the
**viewer wire**: a small set of messages, sent as JSON to a browser, that
let it follow chats and act on them.

A chat in the browser has two halves:

- **the backend**, a Rust program running CAF with `caf-driver-tokio`, which
  serves each browser that connects with `caf_driver_tokio::viewer::serve`;
- **the front end**, a web page using the TypeScript caf-sdk, whose
  `Connection` follows chats and sends what the user does.

The TypeScript caf-sdk is `@clackatoo/caf`, in `ts/sdk` of
[CAF's repository](https://github.com/clackatoo/caf). It isn't on npm yet.

## The backend

Start CAF as in [A Chat on Tokio](/caf/getting-started/a-chat-on-tokio.md).
Then, for each browser that connects, run `serve` with two channels: one for
the messages the browser sends, one for the messages it's sent. `serve`
doesn't touch the network itself, so it works over any transport. The host
moves messages between the channels and the socket, and encodes them as JSON.

Here it is over a WebSocket with [axum](https://docs.rs/axum):

```rust
async fn viewer(ws: WebSocketUpgrade, State(caf): State<Caf<NoAppItems>>) -> Response {
    ws.on_upgrade(move |socket| link(socket, caf))
}

async fn link(socket: WebSocket, caf: Caf<NoAppItems>) {
    let (to_caf, from) = mpsc::channel(16);
    let (to, mut to_viewer) = mpsc::channel(64);
    tokio::spawn(serve(caf, Arc::new(ViewerRules::default()), from, to));

    let (mut sink, mut stream) = socket.split();
    let writer = tokio::spawn(async move {
        while let Some(message) = to_viewer.recv().await {
            let text = serde_json::to_string(&message).expect("CAF's messages are JSON");
            if sink.send(Message::Text(text.into())).await.is_err() {
                break;
            }
        }
        // serve has ended: close the socket, so the browser hears it.
        let _ = sink.close().await;
    });
    while let Some(Ok(message)) = stream.next().await {
        let Message::Text(text) = message else { continue };
        // A message that isn't the wire's ends the link.
        let Ok(message) = serde_json::from_str::<FromViewer>(&text) else { break };
        if to_caf.send(message).await.is_err() {
            break;
        }
    }
    writer.abort();
}
```

`serve` runs until either side closes or CAF shuts down. When it ends, the
writer closes the socket, so the browser hears the link end; without that,
the page would wait on a socket nothing writes to. A viewer doesn't keep
CAF running: once the host drops its own `Caf`, CAF shuts down, and each
viewer sees its chats end.

Keep the channel to the viewer bounded. While it's full, `serve` stops
taking that viewer's changes. A viewer that falls far behind gets the chat
whole again rather than every change it missed, so a slow browser never
makes CAF hold more than one picture of each chat for it.

### What viewers may do

`ViewerRules` says what viewers may do:

- **`open`** turns a viewer's request to open a chat into an `OpenChat`, or
  refuses it. The default refuses every one, so viewers can only watch and
  use chats the host opened.
- **`restore`** does the same for a request to restore a saved chat: it
  gives the chat its tools, or refuses. The default refuses every one.
- **`act`** says whether viewers may send, stop, answer, choose a chat's
  settings, close and unarchive. It's `true` by default.

Opening is always the host's decision, because a chat's MCP servers are
programs to run. A viewer only asks for an agent CAF offered, a folder, and
a new session or one to continue. The host chooses the rest, and may limit
the folders:

```rust
let mut rules = ViewerRules::default();
rules.open = Box::new(|request: &OpenRequest| {
    if !request.cwd.starts_with("/home/me/projects") {
        return None;
    }
    let mut open = OpenChat::new(request.agent.0.clone(), request.cwd.clone());
    open.session = request.session.clone();
    Some(open)
});
```

`open` runs on the viewer's task, so it should decide at once. A host that
needs to ask its user, or read a file, decides beforehand or refuses.

A viewer may watch any chat in its `Caf`: one `Caf` is one circle of trust.
A host whose users mustn't see each other's chats runs a `Caf` for each.

A viewer that may open chats starts agents in your folders, and any website
can try to reach a port on your machine. A backend for one person on one
machine should listen on `127.0.0.1` only, check the WebSocket's `Origin`,
and ask for a token it made at start.

## The front end

Connect, and the SDK says hello and agrees a version of the wire with CAF:

```ts
import { Connection, webSocket } from "@clackatoo/caf";

const caf = await Connection.open(await webSocket("ws://127.0.0.1:7320/viewer"));
caf.agents; // every agent on offer: its name, whether it's installed and signed in
caf.chats; // the chats loaded: id, agent, folder, the app's label and shelf, and when archived, if any
caf.onChats((chats) => drawList(chats));
caf.onAgents((agents) => drawAgents(agents));
```

`Connection.open` takes any `Transport`, an object that sends and hears one
JSON text per message. `webSocket` is the one the SDK ships. If CAF speaks
no version of the wire the SDK does, `open` rejects with a `CafError` whose
`why` is `NoCommonVersion`. It waits as long as CAF takes to say hello
back: to give up sooner, pass a signal, as in
`Connection.open(transport, { signal: AbortSignal.timeout(5000) })`.

CAF says where its agents stand right after its hello, and `open` resolves
once it has, so `agents` is right from the start. `onChats` and `onAgents`
each return a function that stops them.

`caf.may` says what the host lets this page do: `act` on chats (send,
stop, answer, choose their settings, close and unarchive), and on `agents`
(install them, sign in and out, learn their settings, and check again what
the machine has). Offer only what it may: anything else is answered `NotAllowed`. A
page that may not act on agents gets no sign-in's link or code. Whether it
may open chats, or restore saved ones, isn't said, as the host decides each
request.

### Watch a chat

```ts
const watching = caf.watch(chatId, (event) => {
  if (event.type === "Chat") render(event.chat);
  else showEnded();
});
// …and when the page no longer shows it:
watching.stop();
```

The listener is given the chat whole each time it changes. It's a plain
object, of the same types as CAF's Rust ones, generated from them: every
enum is `{ type, value }`, so `switch (item.kind.type)` tells each kind
apart.

Each new chat shares every turn and item that didn't change with the one
before it, so Svelte, React or plain DOM code can tell what changed by
comparing objects, and redraw only that. It also shares them with the SDK's
own copy, so it's typed read-only all the way down (`DeepReadonly<Chat>`):
changing it would change the copy. `apply` takes a read-only chat too.

CAF first sends a watched chat whole, then its numbered changes. The SDK
applies them itself. If one is missing, doesn't fit, or is of a kind this
version of the SDK doesn't know, it asks CAF for the chat whole again, and
the listener only ever sees the right chat. The listener hears `Ended` once
the chat is gone, put away or deleted (closing a saved chat puts it away),
or CAF has shut down. A chat closed and still loaded is archived, and its
watch goes on, as it may be unarchived.

### Act

```ts
const chat = await caf.open({ agent: "claude", cwd: "/home/me/projects/app", session: { type: "New" } });
const turn = await caf.send(chat, { parts: [{ type: "Text", value: "Fix the tests" }] });
await caf.stop(chat);
await caf.answer(question.id, { type: "Permission", value: option.id });
await caf.close(chat); // archives it
await caf.unarchive(chat); // or send to it: that unarchives it too
```

`open` resolves once the chat is open, and `send` once the core has taken
the message, with the turn it will be: not once the turn has run, which
the watch shows. `stop`, `answer`, `close` and `unarchive` resolve once
they're done.
Questions waiting for an answer are on the chat, in `chat.questions`. When
something isn't done, the promise rejects with a `CafError`, whose `why`
says why:

| `why.type` | What it means |
|---|---|
| `Refused` | The core refused it, and nothing changed. `why.value` says why, such as `QueueFull`. |
| `NotAllowed` | The host doesn't let viewers do this. |
| `Gone` | CAF has shut down, or is shutting down: nothing was done. |
| `CannotRestore` | A saved chat couldn't be restored: see [Saved chats](#saved-chats). |
| `Unknown` | It went in a way this version of the SDK doesn't know, from a later CAF. `why.value.outcome` is its name. |
| `Disconnected` | The link ended before the answer came. |

A later CAF may add reasons: to `Refused` and `CannotRestore` here, and to
a chat's `Lost` and a failed turn's `FailureReason`. The types list only
the reasons this version of the SDK knows, but a new one still comes
through, by its name. So give every `switch` on a reason a `default` that
shows it by its `type`:

```ts
function refusal(reason: Refused): string {
  switch (reason.type) {
    case "QueueFull":
      return "Too many messages are waiting.";
    // …
    default:
      return `Refused (${reason.type})`;
  }
}
```

### Saved chats

A host that [saves its chats](/caf/getting-started/saving-and-restoring-chats.md)
keeps them on **shelves**, names of its own choosing, and lists the shelves
it wants viewers to see. `caf.saved` holds
the chats saved on them, open or not, in the order they were made:

```ts
caf.saved; // each: its shelf, its header, and its state
caf.onSaved((saved) => drawSaved(saved));
const [first] = caf.saved;
const chat = await caf.restore(first.header.chat, first.shelf);
```

CAF sends the list right after the agents, and again, whole, whenever it
changes, so it may come just after `open` resolves: read `saved`, and
follow `onSaved`, which returns a function that stops it. A host that
lists no shelves never sends it, and `saved` stays empty.

Each chat's `header` is what to show without loading it: its `chat` id,
`agent`, `cwd`, when it was `made` and last `changed`, the app's `label`
for it, the `first` line of its first message, how many `turns` it has,
whether it was `closed`, and when it was `archived`, if it is (null for a
chat saved closed by a CAF from before archiving: `closed` says it's
archived). Its `state` is `Saved`, `Restoring`, `Loaded`, or `Failed`, with
why the last restore failed.

`restore` resolves with the chat's id once it's loaded. It's then in the
next `Chats`, so in `chats` once `onChats` hears it, and watched like any
other. A chat keeps its id when it's saved and restored. A restored chat is
`Idle`: no session is open until a message is sent, which opens one,
continuing the agent's session where the agent can. One saved archived is
restored archived, and `Closed` until it's unarchived, or sent to, which
makes it `Idle`.

The host decides each restore, as it does each open, so `may` doesn't say
whether this page may: one it doesn't allow rejects with `NotAllowed`. One
that can't be restored rejects with `CannotRestore`, and its save is left as
it was. `why.value` says why:

| `why.value.type` | Why |
|---|---|
| `NotFound` | It isn't on that shelf. |
| `InUse` | Another program has it open: a chat is never open twice. |
| `Newer` | A newer CAF saved it, in a version of the format (`why.value.value.version`) this one can't read. |
| `Damaged` | Its save is damaged: the value says how. |
| `AppData` | The app can't read the data it saved with it: the value says why. |
| `Store` | The store failed, such as a disk error: the value says how. |

Trying again may help after `InUse` or `Store`, not after the rest. The
core may also refuse it: `Loaded`, for a chat that's open or being restored
already, or `BadShelf`, for a shelf's name it can't take.

An item of the app's own that this version of the app can't read comes
back as an `Unknown` item whose `what` is `App`, with the `summary` it had:
show that. Its data is kept exactly as it was, and saved back unchanged.

### Install and sign in

Each of `caf.agents` is an `AgentStatus`: its `name`, its `install` state
and its `sign_in` state. These are the agent's, shared by every chat with
it. The `install` state is `Missing` with its size, `Installing` with how
far it has got, `Installed` with its version, `Cannot` with why, `Host` for
an agent the host starts itself, or `Unknown` until CAF has looked. The
`sign_in` state is `SignedOut`, `SigningIn` with what the user must do,
`SignedIn` with how (never who), or `Unknown`. `can_sign_in` says whether
`signIn` would be accepted now, so offer Sign in only while it's true. It
changes as CAF runs: an agent the host starts itself can be signed in to
only once it has answered as the adapter its profile is for.
`own_tools_off` says whether CAF can turn off the agent's own tools, as it
must to run it: while it's false, a chat with the agent is refused, or gets
no session, so don't offer one. It's false for an agent with the cautious
profile, turns false once an adapter answers that isn't the one its
profile is for, and true again once one that is answers. See
[Agents and profiles](/caf/concepts/agents-and-profiles.md#an-agent-has-only-your-tools).
`limits` are its account's limits, as the agent last said them: how much
of each window of its subscription is used, and when it resets, shared by
every agent with its profile. See [Account
limits](/caf/getting-started/account-limits.md).

```ts
await caf.install("claude");
await caf.stopInstall("claude");
await caf.signIn("claude");
await caf.paste("claude", code); // the code a sign-in page gave the user
await caf.stopSignIn("claude");
await caf.signOut("claude");
```

Each resolves once CAF has started it: how it goes shows in `agents`.
While signing in, the status's `SigningIn` value holds the `url` to open
(null until the agent's sign-in command gives it), a `code` to type there,
if any, and whether the user may `paste` a code back. Open the link in a
new tab with `rel="noopener noreferrer"`, and only if it starts with
`https://`. CAF has checked its site against the agent's profile, but a
page should check for itself too.

The host decides whether viewers may do any of this, as it does for opening
chats, and `caf.may.agents` says so. When it doesn't let them, each rejects
with `NotAllowed`. The core may refuse too:

- `NoSuchAgent`, for an agent it doesn't offer;
- `NotInstallable` or `AlreadyInstalled`, for an install;
- `NothingToStop`, for stopping an install that isn't under way;
- `CannotSignIn`, for signing in or out where CAF can't now;
- `NotSigningIn`, for a paste or a stop with no sign-in under way;
- `Unsupported`, for a paste the sign-in doesn't take: empty, more than
  one line, or too long.

A chat with an agent that isn't installed yet is `WaitingForAgent`, and its
messages wait. They're sent once the agent is installed. Stopping the chat
stops them, and a note in the chat says so.

### Choose the model

A chat's `settings` say what its agent offers that the user may choose,
and what was chosen. Its `offered` lists each `Setting` in the agent's
order: what it's about (its `kind`: `Model`, `Effort` or `Fast`), what the
agent calls it, its `form`, and what the agent says it is now (`current`).
The form is `Choices`, each with the agent's own `id`, its `name`, and any
`description` and `group`, or a `Switch`, on or off. Draw a setting by its
form, so one of a kind a later CAF adds still shows. A choice such as
Claude's `default`, which stands for whatever model the agent would pick,
comes as the agent gives it. `offered` is empty until the chat's session
first opens, and for an agent that offers none.

```ts
await caf.setSetting(chatId, { kind: { type: "Model" }, value: { type: "Choice", value: "sonnet" } });
await caf.setSetting(chatId, { kind: { type: "Fast" }, value: { type: "Switch", value: true } });
```

Choices are by the agent's own ids, matched exactly. The chat's `chosen`
holds them, with the host's defaults for the agent, and its `own` says
which kinds were chosen for the chat itself. Where a choice differs from
its setting's `current`, the change is waiting. A change made while a turn
runs waits for it to end, and applies from the next message; with none
running, it's sent at once. One made before the session opens is applied
as it opens, before any message goes, and if it can't be, the message
fails, `SettingNotApplied`, offering Send again. A choice the agent
doesn't offer, or refuses, is dropped, with a note in the chat
(`NotOffered`, `NotApplied`), and the setting falls back to the host's
default, if the agent offers it, or else to what the agent uses; a host's
default the agent doesn't offer is dropped quietly. When the agent changes
a setting by itself, such as falling back to another model, the chat
follows it, and a note says so (`AgentChanged`). Each turn's `model` names
the model that answered it, if the agent says.

The core refuses `NoSuchSetting` for a setting, or a value of it, that the
agent has said it doesn't offer.

To offer them before any chat, each agent's status says what CAF knows of
its settings: `Unknown`, `Learning`, `Known` with what a session with it
last offered, or `Failed` with why. Every chat's session tells CAF. To
learn them sooner, ask: CAF opens a session and sends nothing, so it costs
nothing.

```ts
await caf.learnSettings("claude");
```

A chat can't be opened with its settings from the page: open it, then
choose them, before anything is sent.

### Usage

A chat's `spend` is what it has cost so far, over the turns that have a
record: their tokens, the cost the agent `reported`, the cost `estimated`
at API prices for turns it didn't, and the tokens no price covered
(`unpriced`). CAF works it out and sends it again whenever a turn adds to
it or the prices change, so every page shows the same figure. Each turn's
`spent` is its own record. `usage` is how full the agent's context is, as
it last said.

```ts
import { cost, total } from "@clackatoo/caf";

cost(chat.spend); // reported and estimated, in US dollars
total(chat.spend.tokens); // input, both cache counts and output
```

A page the host lets (`caf.may.usage`) can ask for a summary of every
CAF app's usage on the machine over a period, and set prices of the
user's own. A summary is buckets, one per period, app, agent, model and
fast mode; the SDK's helpers add them up, so no page writes its own sums:

```ts
import { group, price, split, totals } from "@clackatoo/caf";

const summary = await caf.usage({
  since, until, zone: Intl.DateTimeFormat().resolvedOptions().timeZone,
  by: { type: "Day" }, apps: [], agents: [],
});
totals(summary); // every bucket added up
group(summary, "agent"); // by agent, biggest cost first; or "app", "model", "fast"
group(summary, "model", "tokens"); // biggest by tokens first
group(summary, "period"); // in time order, every day of the period, empty ones too
split(summary, "app"); // each day's groups: a stacked chart's bars
price(summary, "claude-haiku-5-5"); // the entry that priced it, as the summary's `matched` says
await caf.setPrice("claude-haiku-5-5", { input: 1, cache_read: 0.1, cache_write: 1.25, output: 5, fast: null });
await caf.setPrice("claude-haiku-5-5", null); // the table's price again
```

Periods are worked out in the query's zone, so a day is the user's own,
23 or 25 hours across a change of clocks. A summary isn't pushed: ask
again for newer figures. It rejects with `NotAllowed` for a page the host
doesn't let, `NoLedger` if CAF keeps no ledger, and `BadQuery` saying why
for a zone CAF doesn't know or a period it can't sum. `unreadable` names
any part of the record that couldn't be read: say the figures are short.

### When the link drops

When the link ends, for any reason, every request still waiting rejects with
`Disconnected`, and `onClose` is called. A watch isn't ended: `onClose` is
how the page hears. `watch` on a connection that has ended throws
`Disconnected`.

Reconnecting is the page's choice. To pick up where it left off, connect
again and watch each chat `from` the copy its last watch had: CAF then sends
only what changed since, if it still can, and the chat whole if not.

```ts
const stopReconnecting = caf.onClose(() => {
  reconnect().catch((error) => showOffline(error));
});

async function reconnect() {
  const again = await Connection.open(await webSocket(url));
  if (again.run !== caf.run) return startOver(again); // CAF restarted
  again.watch(chatId, listener, watching.copy ?? undefined);
}
```

`onClose` returns a function that stops it, such as when the page is done
with the connection.

A chat keeps its id for good, but a restarted CAF numbers each chat's
changes from the start again, and a chat open before may not be open now.
Each connection's `run` names the run of CAF it reached, and is different
every time CAF starts. So compare it with the old connection's: if it
changed, the page's copies mean nothing now, and it starts again from the
new `chats`.
`watch` checks too: it only resumes from a copy one of its watches made on
a connection to the same run, and otherwise asks for the chat whole. A
`ChatCopy` the page made itself, such as from storage, isn't resumed from.

`disconnect` ends the link from the page's side.

### What the SDK does with what it doesn't expect

Nothing CAF sends makes the SDK throw:

- a message of a type it doesn't know, from a later version of the wire, is
  ignored;
- a change it can't apply asks for the chat whole again, as above;
- an answer of a kind it doesn't know rejects that request with `Unknown`,
  as above;
- anything else that can't be CAF's ends the link, as if it had dropped:
  text that isn't JSON, a message missing what it needs, or an answer that
  doesn't fit what was asked. Ignoring it could leave a request waiting
  forever or a chat silently wrong; ending the link tells the page, and
  rejects every request still waiting.

A listener of the page's own that throws doesn't end the link. Its error is
reported as uncaught, and the other listeners are still called.

## A chat view to copy

CAF's debugger draws its chats with a reference chat view, in Svelte, in
`ts/debugger/src/chat/` of CAF's repository. It draws everything a chat
holds: its state and why a session was lost, each turn with what started
it and how it ended, words, thinking, tools, CAF's notes, items CAF
couldn't read, the questions waiting, and the context ring.
It says each of CAF's reasons in CAF's words, and names one it doesn't know
by its `type`.

It's a pure renderer: give it a chat and the functions to call when the
user acts, and it calls them. It never talks to CAF itself, so it doesn't
care where the chat came from:

```svelte
<script lang="ts">
  // Kept as it changes, so the view follows an install's progress and a
  // sign-in's link as they come, until the component goes.
  let agents = $state.raw(caf.agents);
  $effect(() => caf.onAgents((now) => (agents = now)));
</script>

<ChatView
  {chat}
  label={caf.chats.find((each) => each.id === chat.id)?.label ?? null}
  agent={agents.find((agent) => agent.name === chat.agent)}
  may={caf.may}
  actions={{
    send: (message) => caf.send(chat.id, message),
    stop: () => caf.stop(chat.id),
    answer: (question, answer) => caf.answer(question, answer),
    sendAgain: (message) => caf.send(chat.id, structuredClone(message)),
    close: () => caf.close(chat.id),
    unarchive: () => caf.unarchive(chat.id),
    install: () => caf.install(chat.agent),
    stopInstall: () => caf.stopInstall(chat.agent),
    signIn: () => caf.signIn(chat.agent),
    paste: (text) => caf.paste(chat.agent, text),
    stopSignIn: () => caf.stopSignIn(chat.agent),
    setSetting: (choice) => caf.setSetting(chat.id, choice),
    learnSettings: () => caf.learnSettings(chat.agent),
    checkAgain: () => caf.checkAgain(chat.agent),
  }}
/>
```

It offers only what `may` lets it: without `act`, the chat can be watched,
not acted in; without `agents`, it says what's happening to the agent but
offers no Install, sign-in or Check again. An archived chat says so above
its composer, which stays usable, as sending brings it back, and offers
Unarchive, if `unarchive` is given; only its settings can't be chosen.

A saved chat is put away as it's archived, so CAF refuses to send to it or
unarchive it (`NoSuchChat`) until it's restored, and its watch has ended.
The same folder has what a host needs to do it as the debugger does:
`orRestored` restores the chat, archived still, then tries again;
`restoreOnceFree` tries the restore again for a moment while CAF refuses it
as `Loaded`, still writing the chat just archived; and `oneAtATime` shares
one restore per chat, so two actions at once restore it once. The host
then watches the chat again, as its watch ended when it was put away:

```ts
import { oneAtATime, orRestored, restoreOnceFree } from "./chat";

const restoring = oneAtATime<ChatId>();

// Sends to, or unarchives, the chat shown, restoring it first if it was put
// away; `shelf` is where `saved` lists it, if it's saved: a chat that isn't
// is never put away.
async function toChat<T>(act: () => Promise<T>): Promise<T> {
  const restore =
    shelf === undefined ? undefined : () => restoring(chat.id, () => restoreOnceFree(() => caf.restore(chat.id, shelf)));
  try {
    return await orRestored(act, restore);
  } finally {
    watchAgain(chat.id); // as it was watched before, unless another chat is shown by then
  }
}
```

and gives the view `send: (message) => toChat(() => caf.send(chat.id,
message))`, and `unarchive` the same way.

Given its agent's status, the view also shows what the agent needs before
the chat can go on. While the chat waits for an agent that isn't
installed, it offers Install, naming the size, and Not now, which stops the
waiting message. It shows progress while the agent installs, and says why
when it can't be. While the agent is being signed in to, it shows the link,
the code, a box to paste a code into if the agent takes one, and Stop. A
turn that failed for want of signing in offers Sign in, and still offers
Send again: once signed in, the user sends it again, since CAF never does
by itself. Sign in shows only while the agent's status says CAF can sign
in to it now.

Beside the composer, the view offers the agent's settings: its model and
effort as menus of the agent's own choices, in its order and groups, each
choice's description shown, and fast mode as a switch, saying it may cost
more. A change waiting shows as such: "Sonnet, from your next message"
while a turn runs or the session isn't open, and "Changing to Sonnet…"
otherwise. Before the session first opens, it offers what the agent's
status knows, or, with `act` and `agents`, to learn it. Each turn names
the model that answered it.

By Send is the context ring: how full the agent's context is, amber
past 80% and red past 95%. Clicking it shows what the chat has used and
spent: the context, its cost so far, marked as an API estimate where any
of it is, with the tokens no price covered, and the tokens processed.
Given `openUsage`, it links to the page's usage page: give it only if
`caf.may.usage`. `UsagePage` is one to copy, after CAF SI's: a period's
total, each agent's or app's share and a chart of it by day (or hour),
tokens by kind and what the cache saved, cost by kind and by speed, and a
breakdown by model, app or day, with each model's price a click away and a
price of the user's own:

```svelte
<UsagePage
  load={(query) => caf.usage(query)}
  setPrice={(model, price) => caf.setPrice(model, price)}
  close={() => dialog.close()}
/>
```

Given its `label`, from the chat's summary in `caf.chats`, the view heads
the chat with it. Beside it, `ChatList` lists the open chats, by their
labels where they have them, and opens new ones. Given the agents'
statuses, it offers choosing the model of an agent whose models are known,
passing the choice to its `open(agent, cwd, settings)` action, for the
page to choose once the chat is open. `openThenChoose` does both, and
resolves once the chat is open even if its settings couldn't be chosen,
so it's never opened twice: say why in the chat, with `ChatView`'s
`notice`. `SavedList` lists `caf.saved`: each
chat's label or first line, its agent, folder, when it last changed and its
turns, whether it's loaded or why it can't be, and Restore. Its actions are
`select(chat)`, to show a loaded one, and `restore(chat, shelf)`:

```svelte
<script lang="ts">
  let saved = $state.raw(caf.saved);
  $effect(() => caf.onSaved((now) => (saved = now)));
</script>

<SavedList
  {saved}
  actions={{
    select: (chat) => show(chat),
    restore: async (chat, shelf) => show(await caf.restore(chat, shelf)),
  }}
/>
```

It imports only the caf-sdk, Svelte and markdown-it, which a check in CI
holds it to, so the folder can be lifted out whole. Copy it, or read it for
what a good chat on CAF shows.

The agent's words are untrusted: an agent may repeat a web page or a file,
and HTML in it could script the page. So the view renders Markdown with
HTML off, links only `http` and `https` addresses, opening each in a new
tab with `rel="noopener noreferrer"`, and links to images rather than
loading them. A sign-in link isn't the agent's words, but it opens one the
same way, and only if it's `https`. Whatever a page built on CAF draws the
agent's words with, it should do the same.

---

# The Debugger

_CAF / Getting Started_

> Run caf-debugger to chat with an agent beside an inspector of every step CAF takes, install agents and sign in to them, choose the agent's model, save chats and restore them in a later run, record each run, replay a recording, and move back and forth through it, with what its token is for, what a recording holds, and what "replay diverged" means.

`caf-debugger` is CAF's own debugging tool. It opens a page in your browser
with two halves:

- **the chat**, on the left: CAF's reference chat view, showing the chats as
  any host's page would, through the TypeScript caf-sdk;
- **the inspector**, on the right: every **step** CAF takes (one event given
  to the core, and the directives it gave out), the core's whole state after
  each one, and each chat's numbered changes.

A timeline along the bottom moves through the steps. Because the core does
no I/O and decides everything from its events, any moment of a run can be
rebuilt by replaying the events up to it. So every bug report can be a
recording, stepped through to the moment it went wrong.

It's a tool for working on CAF, not part of CAF's API: what it shows and
how it talks to its page change without notice.

## Run it

The debugger is a Rust program, `crates/debugger` in
[CAF's repository](https://github.com/clackatoo/caf). Its page is a web app
in `ts/debugger`, which has to be built first:

```sh
cd ts
npm ci
npm run build --workspace debugger
cd ..
cargo run --release -p caf-debugger
```

Build it with `--release`: a debug build replays steps about ten times
slower, which a long run makes noticeable when moving through time (see
[Moving through time](#moving-through-time)).

It prints where it records the run, where it keeps chats, and a URL to
open:

```text
Running CAF with claude, fake.
Recording to /home/me/.local/state/caf/debugger/2026-11-20T14-03-22Z-4182.jsonl.
Keeping chats in /home/me/.local/share/caf-debugger/chats.
Open http://127.0.0.1:7320/#token=5f0c…
```

Open that URL. Ctrl-C shuts CAF down, which ends each chat cleanly and
finishes the recording; so do `SIGTERM`, and `SIGHUP` as its terminal
closes. A second one stops the debugger at once, without waiting for CAF.

`--port` picks another port; `--port 0` picks a free one. If the app isn't
built, the page says how to build it. The page and the server are built
apart, so after pulling a new CAF, build the app again: a page built for
another version of the server says so, rather than half working.

## The agents

With no `--agents`, the debugger offers:

- **`claude`**, Claude's adapter, installed by CAF when you ask (see
  [Installing and signing in](#installing-and-signing-in));
- **`fake`**, if it can be found (below): CAF's fake agent, which has no
  model behind it, so the debugger is useful with no real agent and no
  cost. It answers any message
  at once with a few words. Send it exactly `ask`, and it asks permission
  to run a command: answer it, or try Stop while it waits. Send it exactly
  `tools`, and it uses a tool of every kind it can report: an edit, with
  its diff, a command, a web search giving back text, a picture and
  links, and a fetch that failed. Answer its `ask` with Reject to see a
  call refused, or Stop to see one cancelled. Send it exactly
  `fail`, and the turn fails, the first time in each chat, so sending it
  again shows Send again working. Send it exactly `sign in`, and the turn
  fails for want of signing in, the first time in each chat. It offers two
  models, three effort levels and fast mode, so the
  [model picker](#choosing-the-model) can be tried, though they change
  nothing it says.

The fake agent is built by Cargo as the debugger starts, so start the
debugger with `cargo run`. Started any other way, it offers the fake agent
only if `CAF_FAKE_AGENT_BIN` names the `caf-fake-agent` program, and says
why not otherwise.

To offer other agents, list them in a file and pass it with `--agents`.
Then those are all it offers: not `claude` or `fake`, unless the file names
them.

```toml
[[agent]]
name = "claude"
installed = true
profile = "claude-agent-acp"

[[agent]]
name = "my-claude"
program = "/home/me/.local/bin/claude-agent-acp"
args = []
profile = "claude-agent-acp"

[[agent]]
name = "mine"
program = "my-adapter"
profile = "cautious"
```

```sh
cargo run -p caf-debugger -- --agents agents.toml
```

`profile` is one of:

- `claude-agent-acp`, CAF's profile for Claude's adapter;
- `cautious`, plain ACP with nothing risky switched on, for any other
  adapter. CAF can't turn off such an agent's own tools, so it's listed,
  but a chat with it is refused;
- `fake`, a profile for CAF's fake agent, for trying installs and
  sign-ins with no real agent. Installed, its install always fails at
  once, as if offline, so nothing is ever installed. Started from
  `caf-fake-agent` (with its script as its argument), it signs in, out and
  says whether it's signed in with `caf-fake-agent auth`, which does what
  the file `CAF_FAKE_AGENT_AUTH` names says. Its sign-in link must be to
  `caf.example`.

Each agent is either:

- **`installed = true`**: CAF installs it, and starts it from its install.
  Only an agent with one of CAF's own profiles can be, since the profile
  says how, so not `cautious`. It has no `program` or `args`.
- **started by its `program`**: an absolute path, or a bare name looked up
  on `PATH` as the debugger starts, with any `args`. CAF signs in to one
  only once it has answered as the adapter its profile is for, so open a
  chat with it first.

In the chat view, "New chat" opens a chat with any of these agents in any
folder, given as an absolute path. The debugger gives chats no MCP servers,
asks you about every permission request, and starts an adapter of its own for
each chat. **CAF's tools**, ticked by default, gives the chat
[CAF's own tools](/caf/concepts/cafs-own-tools.md), Read, Edit, Write and Bash,
served through the debugger itself; untick it for only the agent's own.

## Choosing the model

Above the message box of each chat, the debugger shows the settings
its agent offers: its models and effort levels as menus, as the agent
lists and names them, and fast mode as a switch. A change made while the
agent is replying, or before its session opens, says so ("Large, from your
next message") and is sent once it can be; one made while it's idle is
sent at once. If the agent refuses a choice, the chat says so, and the
message that waited on it fails, with Send again. Each turn shows the
model it was sent on.

Before a chat's session first opens, it shows what CAF knows the agent
offers, if it knows, or offers to learn it: **Learn it now** asks the agent
without sending any message. Once CAF knows an agent's models, "New chat"
offers them too, to open a chat on one. See
[Choosing the model](/caf/getting-started/choosing-the-model.md) for how CAF
does it.

## Installing and signing in

The **Agents** panel, under the list of chats, shows each agent the
debugger offers: whether it's installed, and whether it's signed in.

- **Install** installs an agent CAF installs itself, showing its size
  first and its progress as it goes; **Stop** stops it. If it can't be
  installed, the panel says why, such as a missing Node or npm.
- **Sign in** runs the agent's own sign-in, from CAF's profile for it. It
  shows only where CAF can sign in now: for an agent the debugger starts
  itself, once it has answered in a chat as the adapter its profile is
  for. It shows while signed in too, to switch accounts.
  The sign-in then shows a link to open in a new tab, a code to type there
  if the agent shows one, and a box to paste a code into, for when the
  sign-in page gives you one instead. **Stop signing in** stops it. It
  shows in the chat beside the panel, if that chat is with the agent and
  isn't closed, and the panel says "Signing in: see the chat."; otherwise
  in the panel.
- **Sign out** signs out of it.

The debugger lets its page do all of this. Installs go where every CAF
program keeps them, `~/.local/share/caf/agents/` (under `$XDG_DATA_HOME`
if that's set), so an agent installed here is installed for them all.
Claude's adapter is about 627 MB. Claude keeps its sign-in in its own
folder, `~/.claude`, so signing in here signs in Claude Code too.

A chat opened with an agent that isn't installed waits for it, and says so:
Install starts it, and Not now stops the message that waited. A chat whose
turn failed for want of signing in offers Sign in, and once you're signed
in, says so; send the message again then.

Nothing is shown in the panel while looking back or replaying: a recording
holds what CAF was told, not each agent's status.

## Saved chats

Every chat the debugger opens is saved, on the shelf `debugger`, in
`~/.local/share/caf-debugger/chats` (under `$XDG_DATA_HOME` if that's set),
or in the folder `--store` names:

```sh
cargo run -p caf-debugger -- --store /tmp/chats
```

As it starts, it checks it can write there, making the folder, private, if
it isn't there yet, and stops if it can't, saying why. Then it lists the
chats saved there, under **Saved**, below the
list of open chats: each with its title or first message, its agent and
folder, when it last changed, and how many turns it has. **Restore** brings
one back, with its record, idle until you send to it; its session then
carries on, as the fake agent resumes sessions. It has CAF's tools again,
unless it was opened without them: the debugger notes those in
`caf-debugger-untooled.json` in the store's folder, as a chat's save
doesn't say what tools it had, and forget a chat once it's deleted. Closing a chat puts it
away, closed, and it stays under Saved, to restore again. A chat another
program has open, or the debugger can't read, says so, and is left as it
was.

Ctrl-C saves every chat whole before the debugger stops, so the next run
finds them as you left them. Replaying keeps no chats: nothing is saved or
listed.

## Usage

Each turn's usage goes into the ledger every CAF program shares,
`~/.local/share/caf/usage/` (under `$XDG_DATA_HOME` if that's set), as the
app `caf-debugger`, or into the folder `--usage` names: real usage, as a
chat with Claude here is a real chat. The fake agent's turns say nothing
of what they spent, so they aren't recorded, unless asked (below). Its
page may read summaries of every app's usage and set prices of your own:
**Usage**, in its bar, opens the usage page, and the context ring by Send
shows what the chat itself has used and spent. Prices are
fetched from LiteLLM once a day; `--no-fetch-prices` never fetches them:

```sh
cargo run -p caf-debugger -- --usage /tmp/usage --no-fetch-prices
```

The fake agent says what its turns spent only with `--fake-usage`: it
makes the figures up (a chat's first turn costs $0.0125), and with the
shared ledger they would count in your real usage. Give it a ledger of its
own to try the usage page with them:

```sh
cargo run -p caf-debugger -- --usage /tmp/usage --no-fetch-prices --fake-usage
```

See [Usage](/caf/getting-started/usage.md).

The Agents panel shows each agent's [account
limits](/caf/getting-started/account-limits.md) under it, once the agent has
said them: one line with the window that has least left, with a dot and
a word, amber and `low` at 20% left or less, red and `out` at 10% or
less, and, opened, each window with a bar of what's left, a tick where an
even pace would have it, its state, when it resets and when CAF heard.

The fake agent says limits only with `--fake-limits`, in the shape
Claude's adapter says them in: its five hours climb from 60% used, a few
percent a turn, its week, its week with extra usage and Opus's week more
slowly, until the sixth turn's, each chat's fake starting the climb
again. Send it exactly `limit`, and its five hours are refused and the
turn fails for a usage limit, the first time in each chat. Its resets
are made up as the debugger starts, as its script can't say the time:
they're forgotten, the five hours after three hours, the weeks after four
days, until the debugger starts again. They're made up, and kept in the usage
folder under the fake's own profile, so give it one of its own:

```sh
cargo run -p caf-debugger -- --usage /tmp/usage --no-fetch-prices --fake-limits
```

## The token

The debugger starts agents in your folders, and any web page you visit can
try to reach a port on your machine. So it's locked down:

- It listens on `127.0.0.1` only, so nothing else on the network can reach
  it, and answers only requests addressed to it by that name or
  `localhost`, so a site that points its own name at your machine gets
  nothing.
- Each launch makes a new random **token**, in the URL it prints. It's in
  the part after `#`, which a browser never sends anywhere, so it stays out
  of logs. The page passes it on to the server, which refuses anything
  without it.
- The server only accepts the page's own connections: a page from any
  other site is refused, even with the token.

Treat the URL as you would a password while the debugger runs: anyone with
it can chat with your agents as you.

## Recordings

Every live run is recorded, from start to end, to a new file named for when
it started, in UTC, and the debugger's process:

```text
~/.local/state/caf/debugger/2026-11-20T14-03-22Z-4182.jsonl
```

That's under `$XDG_STATE_HOME/caf/debugger/` if `XDG_STATE_HOME` is set.
The debugger makes the folder readable only by you, each time it starts,
and CAF makes each file so too. **Save bug report**, in the top bar,
downloads the run's recording so far. If CAF can't make the file, the
debugger says so as it starts, runs unrecorded, and offers nothing to
download.

To replay a recording, pass it with `--replay`:

```sh
cargo run -p caf-debugger -- --replay 2026-11-20T14-03-22Z.jsonl
```

A replay starts nothing and writes nothing: it rebuilds the run from its
events alone. The chat view is read-only, and the timeline starts at the
end.

A recording copied while CAF was still writing it may end partway through
a line: the replay stops before it. Any other line that isn't one of CAF's
events, such as one from a newer CAF, makes the debugger refuse the file,
naming the line, since the replay would be wrong from there on. A
recording of another version of the format is refused too, saying which:
until CAF is released, only the debugger of the CAF that made a recording
replays it.

### What a recording holds

A recording is every event CAF's core was given, in order: what you sent,
everything each agent said, and its error output, and each chat restored,
whole, as it was read. That's enough to rebuild every chat exactly, so **a recording holds the whole conversation**, and
whatever the agent read out of your files along the way. Read one through
before sharing it.

A few things are left out, and replaying doesn't need them:

- the account's email, which Claude's adapter reports in its sign-in status,
  and all of that status but how you're signed in;
- a code you pasted into a sign-in;
- each agent's arguments, and the values of its environment variables;
- the values of each MCP server's environment variables and HTTP headers;
- what you paste into a sign-in, such as a code from the sign-in page.

A sign-in's link, and any code it showed you to type, are kept: each works
once, so it's no use by the time anyone reads the recording, and a replay
needs it.

The inspector itself shows everything, those too: it shows exactly what the
core was given. Only your browser can see it, but take care with
screenshots.

The debugger keeps every step in memory for as long as it runs, so moving
back through time can reach any of them. The steps take about what the
recording does. The copies of its core it keeps along the way (see
below) take more: at most 64 of them, each the whole core as it was then,
every chat with all its turns, so up to 64 times what the chats hold at
the end. So a long live run grows; restart the debugger to start afresh.

## Moving through time

Live, the page **follows** the run: the chat view shows the chats as they
are, through the same viewer wire any host uses, and the timeline sits at
the end as steps arrive.

Drag the timeline back, or pick a step in the inspector, and the page
**looks back**: the chat view and the core's state show the moment just
after that step, and the chat view is read-only. Steps go on arriving
meanwhile. Go back to the end to follow again.

Looking back works by replay: the debugger keeps a core of its own, and
gives it the run's events up to the step you chose. Every streamed chunk
of words is a step, so a long run has tens of thousands. So the debugger
keeps copies of its core along the way, and a move starts from the
nearest copy before the step:

- for the first 64,000 steps, a copy every 1000 steps, so a move replays
  at most 1000;
- after that, still at most 64 copies: each time there would be more,
  every other one goes and the spacing doubles, so a move replays at most
  a 32nd of the run.

The chat view gets those chats the way any viewer gets a chat: whole when
moving back, and as numbered changes when moving forward. So moving
through time also checks that the chat view's SDK and the core build the
same chat.

A move should take less than 50 ms, which holds, up to 64,000 steps,
while replaying runs at 50 µs a step or quicker. A release build replays
at a few µs a step, a debug build at a few tens, so in a release build it
holds far longer: a run of a million steps moves in about 60 ms. The first
time a move is slower, the debugger logs it, once a run.

## "Replay diverged"

The core does no I/O, so given the same events it must always give out the
same directives. Live, the debugger checks this at every step, twice:

- **the steps:** a core of its own is given each event exactly as CAF's
  core was, read back from JSON, and must give out exactly what CAF's own
  core did. That's what moving through time replays.
- **the recording:** another is given each event as the recording holds
  it, with its secrets hidden, as a replay of a bug report would be. It
  must give out what CAF's core did, but for the hidden secrets
  themselves: the values of MCP servers' variables and headers, which
  reach the agent in the message that opens its session, and a code
  pasted into a sign-in, which a replay passes on as empty.

If either ever differs, the inspector shows **"replay diverged at step
N"**, saying which check, with both lists of directives. That's a bug in
CAF: something it does isn't decided by its events alone, such as a clock
read or a random number, or something that affects it isn't in its
events, or isn't in a recording of them. Save the recording and report it.

After a divergence, that check stops. If it was the steps', the
debugger's replay no longer matches what CAF did, so what it shows when
looking back at later steps may be wrong. The run itself goes on.

---

# The Core

_CAF / Concepts_

> CAF's core holds every chat's state and rules and does no I/O. Drivers report what happened as events, and the core answers with directives, so the same events always give the same result.

CAF's **core**, the `caf-core` crate, holds the state of every chat and the
rules that change it. It does no I/O at all: it never reads a clock, starts a
process, sets a timer, touches a file, or decides whether the agent may do
something. Clippy checks that rule on every build.

## Events in, directives out

Everything that happens reaches the core as an **event**, with the time it
happened. Everything the core wants done leaves it as a **directive**:

```text
driver ──event──▶ core (rules, reading and updating state) ──directives──▶ drivers
```

Both lists are closed. Drivers report only the events the core knows, and the
core gives only the directives drivers know. One event can lead to no
directives or to several, for any driver.

The host's own requests, such as opening a chat or sending a message, are
events too. A program calls methods like `Core::send`, which record them, so
a recording of a session holds everything that happened in it.

## Drivers

Drivers are small, and each does one kind of job:

| Driver | Its job |
|---|---|
| Agent | Starts adapter programs and carries their bytes, knowing nothing of which agent it runs |
| Timer | Wakes the core at the one time it asked for |
| Policy | Answers "may the agent do this?" |
| Viewer | Tells the program's views that a chat changed |
| Storage | Saves and loads chats (a later feature) |
| Setup | Installs agents and runs their sign-in commands, as each one's [recipe](/caf/concepts/agents-and-profiles.md#installing) says |

Drivers never hear each other: only the core listens to them, and only the
core gives them work. A directive whose result the core waits for has a
**ticket**, and the result quotes it. Tickets are never reused, so a result
that arrives after the core stopped waiting is simply ignored. Each adapter
process is known by the ticket of the directive that started it, so output
from a process the core has replaced can't be mistaken for the new one's.

## Why no I/O

Given the same events, the core always gives the same directives and ends in
the same state. So:

- **Any session can be replayed as a test.** A bug becomes a recording of
  events, and its fix a check on what comes out.
- **It fits any program.** clackatoo runs it on its own event loop, under
  strict rules about never stalling; a tokio program uses the drivers in
  `caf-driver-tokio`.
- **Nothing can quietly block it.** Slow work happens in drivers, and its
  result comes back as one more event.

## What the core promises

1. Every request the agent sends is answered, exactly once.
2. Every request CAF sends ends. Every one has a deadline except a prompt,
   which may run as long as the agent works; once the user stops it, it has
   one too.
3. Nothing the agent sends is silently dropped.
4. Every event names what it belongs to, so a late update lands on its own
   row.
5. A result for a ticket the core no longer waits on is ignored.
6. A question is answered once, and only while it still stands.
7. Nothing an agent replays from a session's history acts.
8. When an adapter is restarted or lost, every chat it served is told.
9. The agent's words are never passed off as CAF's.

---

# Chats, Turns, and Items

_CAF / Concepts_

> CAF keeps its own record of every chat, in one format for every agent. A chat is a list of turns, a turn is a list of items, and views follow a chat through its numbered changes.

CAF keeps its own record of every chat, in one format for every agent. The
agent keeps its own transcript too, as its memory; CAF's record is what
happened and what the user saw. Each adapter's
[profile](/caf/concepts/agents-and-profiles.md) translates what it sends into
this format as it arrives.

## Chats, turns, and items

A **chat** is the user's conversation with an agent. It's a list of
**turns**, and each turn is a list of **items**.

A turn records what started it (the user, the agent itself, another chat's
agent, or the program) and where it is in its life:

| Life | Meaning |
|---|---|
| Waiting | Not sent yet: the chat is opening, or another turn is running |
| Running | The agent is working on it |
| Stopping | Stop was asked for, and the agent hasn't finished stopping |
| Finished | The agent finished |
| Stopped | The user stopped it |
| Failed | It went wrong, with the reason and what the user can do |
| Cut off | The program restarted while it ran |

An item is one thing the agent did: its words, its thinking, a tool it used,
a summary of its memory to make room, a note from CAF, the program's own kind
of item, or something CAF couldn't read, kept as it came so nothing is lost.
A tool call is recorded the same way for every agent and every tool, with
its diffs and output: see [Tool calls](/caf/concepts/tool-calls.md).

Every turn and item has a permanent id, never a position, and a window of
time: when CAF first heard of it, and when it ended. The times are when CAF
heard things, since ACP carries none.

Questions waiting for an answer, such as the agent asking permission to run
something, aren't items: they're a list on the chat, because they come and
go.

## What a turn spent

When a turn's message is answered, however the turn ended (finished,
stopped, or failed as the agent said), the answer says what it spent, and
CAF records it on the turn: its tokens by kind (input, cache read and
written, output, and how much of the output was thinking), one row per
model, and its cost if the agent reports one. Claude's adapter splits
the tokens by model, counting the subagents and compaction the turn set off
too; an agent that doesn't gets one row, against the model it said it used
during the turn, or else the model the turn was sent on. A turn's cost is
how much the agent says its session's cost rose over it, if it says so
during the turn; otherwise, or if the cost didn't change (Claude's adapter
leaves a stopped turn out of its total, though it spent tokens), the turn is
estimated like any other. An agent
that says nothing gives no record.

The chat adds up its turns' records as what it has **spent**: tokens,
the cost the agent reported, and an estimate, from a table of prices, for
turns it didn't report. Estimates are never stored on a turn or in the
ledger, so when the prices change, every chat's figure is worked out again.
The figure is saved with the chat, but never trusted: a chat restored from
its save works it out again from its turns. Each turn's record also
goes to a ledger every CAF program on the machine shares, so usage can be
summed across them.

## The program's own items

A program can add items of its own kind, such as eyespy's "the agent moved
the map here". Only the program adds them, never the agent. CAF keeps them in
order and saves them with the chat without looking inside. Each gives a
one-line summary for anything that doesn't know its type.

## Following a chat

Each chat keeps a numbered list of small changes, each naming what it changes
by id: a turn added, words appended to an item, a tool finished, a question
asked. A view remembers the number it has read up to and asks for what
follows. A view that's new, or has fallen too far behind, gets the whole chat
first and then the changes after it.

How a view outside the program follows a chat, and why every one ends with
the same chat, is in [Viewers](/caf/concepts/viewers.md).

---

# Tool Calls

_CAF / Concepts_

> What CAF records of each tool call, whoever ran it. Where a call came from, what CAF reads it as doing, the pieces it gave back (text, diffs, a command's output in colour, images and links), how much of each is kept, output that grows while it runs, who allowed it, and why CAF runs the tools that matter itself.

A tool call is one of the [items](/caf/concepts/chats-turns-and-items.md) of a
turn: the agent reading a file, changing one, running a command, searching
the web. CAF records every call the same way, whichever agent made it and
whoever ran the tool, so an app draws one kind of thing (a `ToolCall`) for
all of them.

## CAF runs the tools that matter

An agent comes with tools of its own for reading and changing files and
running commands, and each reports what they did in its own way, often as
little more than a line of text. CAF turns those off, and gives the agent
its own instead, over MCP: **Read**, **Edit**, **Write** and **Bash**. An
agent whose adapter won't let CAF turn its own off isn't run at all.

Since CAF runs them itself, it knows exactly what they did, for every
agent alike: which file was read, the diff an edit made, a command's output
in colour as it ran, and how it exited. It asks the app's policy, and the
user if need be, before anything runs, and it writes such a call's title
itself, from what the call does: the agent's would be a name like
`mcp__caf__Read`. A read, an edit or a write is *Read src/main.rs*,
*Edit src/main.rs* or *Write src/main.rs*, with the path from the chat's
folder when the file is inside it, and whole otherwise. A command is its
first line, followed by *…* if it has more. What each tool does is
[CAF's own tools](/caf/concepts/cafs-own-tools.md).

For an edit or a write, CAF works out the change before it asks anyone,
and puts its diff on the call, so whoever is asked sees exactly what they
allow. A refused change keeps its diff, and never happens.

The agent keeps the tools CAF doesn't replace, such as Claude's web search,
and reports them as before. CAF records those too, from what the agent
says.

## Where a call came from

A call's `origin` says whose tool it is:

| `Origin` | The tool |
| --- | --- |
| `Caf` | One of CAF's own: Read, Edit, Write or Bash. |
| `App` | One of the app's own tools, which CAF serves for it. *Later.* |
| `Server` | A tool of an MCP server the app gave the chat, by the server's name and the tool's. |
| `Agent` | The agent's own, by the agent's name for it, such as `WebSearch`. |
| `NotRecorded` | Saved before CAF kept where calls came from. |

The origin is never worked out from the call's title, nor from anything
else the model wrote. A call to a tool CAF serves gets its origin from the
connection it arrived on, which belongs to one chat. Any other gets its
origin from what the agent's adapter says, such as Claude's
`_meta.claudeCode.toolName`.

**One call, one item.** A call to a tool CAF serves arrives twice: the
agent reports that it's calling it, and the call itself reaches CAF's tool
server. Whichever comes first makes the item, and the other joins it, so
the chat has one item per call however many reports there were. For such a
call, CAF's record is the truth: it ran it. The agent's report adds only
its id for the call, and when it started.

## What it does, and what it was given

Once CAF has a call's whole input, it reads what the call does, its
`action`, and never changes it after:

| `Action` | Does |
| --- | --- |
| `Read` | Reads a file, and which lines, if not all. |
| `Edit` | Changes part of a file. |
| `Write` | Writes a whole file, new or over what was there. |
| `Run` | Runs a command, in a folder, and whether in the background. |
| `Tool` | Anything else, by its name: its input says the rest. |

Paths in an action are absolute, worked out against the chat's folder
before anything runs, so an action names exactly the file, whatever `..`
the model wrote. The action also gives a call its `kind` (`ToolKind`),
which an app uses for its icon and to count steps: Read is `Read`, Edit and
Write are `Edit`, Run is `Execute`. A call CAF didn't run has the kind the
agent gave it.

A call also keeps its `input`, as the model wrote it, and its `locations`:
the files, and lines in them, it's about, for an app to open.

## What it gave back

A call's `result` is a list of pieces, in order:

| `Piece` | What it is |
| --- | --- |
| `Text` | Plain text, such as a file read. |
| `Diff` | A file's change, as hunks: runs of changed lines, with three lines either side as they were, as `git diff` shows them. Each line has its number before and after, and the diff counts the lines it adds and removes. |
| `Output` | A command's output, as its terminal showed it: its lines, with their colours, and how it ended (an exit code or a signal), or that it ended without saying how. |
| `Image` | A picture, by its type, such as `image/png`. |
| `Link` | A file or web address the call points to, and its name. |
| `Unknown` | A piece CAF can't read yet, kept as it came, up to its cap. |

CAF works a diff's hunks out itself, from the file before and after,
whether CAF made the change or the agent sent both texts. An app draws them
as they are, and never compares texts.

A command's output keeps its colours, as the terminal's codes for them
(SGR), and nothing else a terminal would act on: CAF works out the
cursor's movements before it keeps the output, so a progress bar is its
latest line, not every redraw of it. An app turns the colour codes into
colour, and shows anything else as text, never acting on it.

What's kept is what's useful to the user: a diff, a command's output in
colour. What the model is answered is what's useful to it, and each of
CAF's tools says what that is. For a tool CAF runs, both come from the same
run.

### Caps

Everything in a call is bounded, so one call can't fill a chat's record.
Anything cut says how much of it was kept, of how much (a `Cut`, in bytes):

| What | Most kept | Which part |
| --- | --- | --- |
| `Text` | 64 KB | its start |
| `Output` | 64 KB, each line's ending counting as a byte | its end, in whole lines of at most 16 KB |
| `Diff` | 256 KB of its lines | whole hunks, then how many more there were (`more`) |
| `Image` | 2 MB | all of it, or none, with its size |
| `locations` | 256 | the first, then how many more (`locations_cut`) |
| `input` | 64 KB of its JSON | its start, as a string (`input_cut`) |
| `Unknown` | 64 KB of its JSON | its start, as a string in `raw` (its `cut`) |

An output keeps its last lines, as a terminal's scrollback does, and says
how many before them weren't kept (`dropped`). An image too big to keep
has no data, only its type and size, so an app can say it was too big.

### Output while it runs

A command's output grows while it runs. A call has at most one `Output`
piece, and while the command runs, `Change::OutputChanged` changes it in
place: the lines from one on are replaced by new ones (the last line may
still be being written, so it can change), then lines dropped from the top
to keep under the cap. Its `ending` is empty until the command ends. So a
viewer sees a build or a test run as it goes, sent only what changed.

## Where it is

A call's `status`:

| `ToolStatus` | Means |
| --- | --- |
| `Pending` | Not started yet: reported, or waiting for the policy. |
| `Asking` | Waiting for the user: its permission question is open. |
| `Running` | Running. |
| `Done` | Finished. |
| `Failed` | Went wrong: why is a `Text` piece, or its turn failed under it. |
| `Refused` | Not allowed, by the policy or the user. It never ran. |
| `Cancelled` | Stopped: the user stopped its turn, or the agent cancelled it. |

Every call ends Done, Failed, Refused or Cancelled. When its turn ends, a
call still Pending, Asking or Running is Cancelled if the user stopped the
turn, and Failed otherwise, and so is one a restored chat was cut off in.

## Who allowed it

A call's `decision` says whether it was allowed, and by whom:

| `Decision` | Means |
| --- | --- |
| `Undecided` | Not decided yet. |
| `NotAsked` | It needed no permission, such as a call the agent made without asking. |
| `Allowed` | Allowed, by the policy, with its reason if it gave one, or by the user, with the option they chose. |
| `Refused` | Refused, likewise. |
| `NotRecorded` | Saved before CAF kept who decided. |

When the user is asked, the question is on the chat (`Chat.questions`), and
names the call it's about (`Permission.tool`), so an app can show the
command or the change it asks about beside it. The agent may ask before CAF
has seen the call, so the question may name it only later.

## Drawing them

[The transcript](/caf/standard-interface/transcript.md) in CAF's Standard
Interface says how an app draws every part of a tool call: its status in
the colour roles, who decided, each kind of piece, and a question showing
what it asks about. The debugger draws them all.

---

# Serving Tools

_CAF / Concepts_

> How CAF gives an agent its own tools, Read, Edit, Write and Bash, over MCP. The one line every app adds to its main, choosing a chat's tools, how a connection is bound to its chat and what that does and doesn't guarantee, keeping long calls alive, cancelling, losing the tools mid-session, and what isn't built yet.

CAF turns off an agent's own tools and gives it its own instead:
**Read**, **Edit**, **Write** and **Bash**
(see [Tool calls](/caf/concepts/tool-calls.md#caf-runs-the-tools-that-matter)).
It serves them to the agent over MCP, as a server named `caf`, from inside
your program, so it knows exactly what each call does and can ask your
policy, and the user, before anything runs.

What the tools themselves do is [CAF's own tools](/caf/concepts/cafs-own-tools.md).

> [!NOTE]
> Windows isn't supported yet: serving needs Unix sockets.

## The relay

An agent's adapter starts an MCP server as a program of its own, talking
over its stdin and stdout. CAF's tools live in your program, so the program
the adapter starts is a *relay*: a small program that connects to your
program over a Unix socket and copies bytes both ways.

The relay is your own program, run again. Make this the first line of your
`main`, before anything else runs:

```rust
fn main() {
    caf_relay::relay_if_asked();
    // ...the rest of your program
}
```

When your program is started as a relay, `relay_if_asked` relays until the
agent is done with it, and exits; it never returns. Otherwise it returns at
once, and costs nothing. It needs nothing but the standard library, and
writes nothing to stdout but what it relays.

Then turn serving on: CAF serves no tools unless you ask it to.

```rust
let mut config = Config::new(Host::new("eyespy", "0.4.0"), vec![claude]);
config.tools.relay = Relay::ThisProgram;
```

| `Relay` | What CAF runs as the relay |
| --- | --- |
| `None` | Nothing: no tools are served. The default. |
| `ThisProgram` | Your program, which must call `relay_if_asked`. |
| `Command(SpawnCommand)` | Another program that relays as `caf-relay` does. |

With `ThisProgram` or `Command`, CAF checks the relay as it starts, by
running it once and checking its answer. If your `main` doesn't call
`relay_if_asked`, `Caf::try_start` returns `StartError::NoRelayHook`, whose
message says to add it, rather than every chat's tools failing later. So
does anything else that keeps CAF from serving, as another `StartError`:
`SocketPathTooLong` for a socket path that's too long, and `Serving` for
the rest. Nothing is started then. `Caf::start` panics with the same
message.

CAF listens on a socket in `$XDG_RUNTIME_DIR/caf`, or a folder of its own
in the temp folder if there's no runtime folder, readable only by the user
(`ToolsConfig::folder` says another). The socket is named after your program
and its process, numbered if the process starts more than one CAF, and
removed when CAF shuts down. A socket's path is
limited to about 108 bytes; the error for a longer one names the path.

## Choosing a chat's tools

A chat gets no tools unless you give it some:

```rust
let chat = caf
    .open_chat(OpenChat::new("claude", "/home/me/project").with_tools(Tools::caf([
        CafTool::Read,
        CafTool::Edit,
        CafTool::Write,
        CafTool::Bash,
    ])))
    .await?;
```

A chat's tools aren't saved: give them again when you restore it
(`RestoreChat::tools`), and in what `ViewerRules::restore` returns, for
chats a viewer restores. A chat restored without them has none.

Giving a chat tools while serving is off (`Relay::None`) is refused
(`Refused::ToolsNotServed`).

For a chat with tools, CAF adds its `caf` server to the MCP servers it gives
the agent, and tells the agent about them in its instructions, in place of
saying it has none. The agent may call only the tools the chat was given: a
call to any other is answered as an error, and never runs.

## How a connection finds its chat

Every chat's relay connects to the same socket, so CAF must know which chat
each connection is for, and that the relay is one it started:

- **A key per run.** CAF draws a random key from the system each time it
  starts. It's never saved, and recordings and the debugger hide it.
- **A token per chat.** The relay is started with its chat's id and a token
  in its environment: the key's HMAC of the chat's id. CAF checks the token
  before anything else, and closes a connection with a wrong one, or for a
  chat that's unknown or has no tools. A token is no use for any other
  chat, nor in another run.
- **A private folder.** Only the user can reach the socket.
- **The newest connection wins.** When the agent opens a chat's session
  again, a new relay may connect before the old one has gone. The new one is
  bound to the chat, and the old one closed, along with its open calls.

Each call then belongs to the chat whose connection it came on, which is
how CAF knows a call's origin without trusting anything the model wrote.

**What it doesn't guarantee.** This keeps one chat's agent from calling
tools as another chat by accident, or by guessing. It isn't isolation. An
agent that can run commands as the user, such as with Bash, can read other
processes' environments, a relay's token included, and could connect as
another chat. CAF's policy rules, and the user's answers, are guard rails
on what the model asks for, not a sandbox. Keeping agents truly apart needs
each one in a sandbox of its own.

## Long calls, and cancelling

**Long calls stay alive.** An agent may give up on a call that's silent for
too long. While a call is open, CAF sends the agent progress every minute,
if the agent asked for it: "Waiting for permission" while the user decides,
then "Running".

**Cancelling.** A call ends Cancelled (see
[Where it is](/caf/concepts/tool-calls.md#where-it-is)), and its `stopped_by`
says who stopped it:

| `StoppedBy` | Means |
| --- | --- |
| `User` | The user stopped the turn, or closed or deleted the chat: CAF cancels the call, stops its work, and answers the model that the user stopped it. Or the agent gave up on the call as the user stopped the turn: CAF stops its work, and answers nothing, as MCP says. |
| `Agent` | The agent cancelled it while its turn wasn't being stopped, or its relay went: it closed, or a newer one replaced it. CAF stops its work, and answers nothing, as MCP says. |

A turn that ends by itself with a call still open doesn't cancel it: the
call ends Failed, and `stopped_by` stays empty. So does a turn cut off
as the chat is put away or CAF shuts down: its calls end Failed, stopped
by no one.

Stopping a call's work drops it, so a tool still running is stopped too.

**A preview that fails** (an edit to a file not read first, say) ends its
call Failed with the reason, and no one is asked: the tool's driver has
already given the model the reason.

## Background jobs

A call can carry on after the model has been answered, as a **job**: for
example, Bash run with `run_in_background`, or a command still running when
its timeout is reached. Its driver reports the call `Detached` before
answering the model. It stays Running, and its `job` gives its number among
the chat's jobs (1, 2, …), which is how the model names it. A job keeps
running when:

- its turn ends, or the user stops it (Stop stops the turn, not its
  background work);
- its relay goes;
- a turn the agent started by itself goes quiet.

It ends in one of these ways:

| How | Ends |
| --- | --- |
| By itself | Done or Failed, and the agent hears of it in a **notice turn**, worded by the driver: at once, or after the turn running |
| TaskStop, from the model | Cancelled, `stopped_by` `Agent`. TaskStop needs no permission, and stops only jobs of its own chat: for any other number, the model is told "No task {id} in this conversation" |
| The chat closed or deleted | Cancelled, `stopped_by` `User` |
| The chat put away, or CAF shutting down | Failed, stopped by no one |

A restored chat has no jobs: one saved while running ends Failed. TaskStop
is served with Bash automatically. A notice turn is `Starter::Notice`: the
app can send its own with `Core::notify`, and it's queued like a message,
but never counts against the host's limit on messages waiting
(`queued_messages`): only the user's messages do.
The user's Stop drops the messages still waiting, but not the notices:
dropping a notice would mean the agent never learns that its job ended,
and sending it at once would set the agent working again just after the
user stopped it. So from the Stop on, every notice is **held**: those
waiting, and any job's that comes after, without starting the agent for
it. They're all sent just before the user's next message, or the app's
next notice, each as its own turn, in order.

Each chat also keeps a **shell folder**: where its last command's shell
ended, starting at its folder. Its next Bash command runs there. With
commands run side by side, the one that finishes last sets it. A job's
end doesn't change it, a folder that isn't an absolute path of at most
4096 bytes is ignored, and a restored chat starts again at its folder.

The driver must keep a job running when its relay goes. It reports a job
that ends by itself with a notice. When TaskStop stops a job, it reports
the job without one, before the TaskStop's own end. If the job ended by
itself first, it ends as it did, and TaskStop answers "No task {id} in
this conversation".

## Losing the tools

If a chat's relay goes while its session is still open, as when the
adapter's MCP server crashes, the chat loses CAF's tools until its session
is opened again. CAF ends the calls that were open, and adds a note to the
chat, once per session, so the user knows why the agent can't use them:

> CAF's tools stopped working for this conversation; they'll be back when
> it's opened again.

Nothing is noted when the chat is closing anyway.

---

# CAF's Own Tools

_CAF / Concepts_

> What CAF's own Read, Edit, Write, Bash and TaskStop do, as the model sees them and as the user does. Reading before changing and what counts as stale, encodings and line endings, Bash's folder, timeout and background, the files a long output goes to, background jobs and CAF's notice of each one's end, and giving CAF your editor's buffers and your terminals in place of the disk and its own pty.

CAF gives an agent its own tools in place of the agent's: **Read**,
**Edit**, **Write** and **Bash**, and **TaskStop** with Bash. How they
reach the agent is [Serving tools](/caf/concepts/serving-tools.md); what CAF
records of each call is [Tool calls](/caf/concepts/tool-calls.md). This page
is what the tools themselves do.

The model was trained on Claude Code's tools, so CAF's take the same
inputs, behave the same way and answer in the same words, Claude Code's
own, wherever CAF's design doesn't say otherwise. Where it does, this page
says so.

> [!NOTE]
> CAF's own tools, and `caf-driver-tokio` that runs them, are Linux only
> for now: they stop a command and everything it started through a pidfd.

Give a chat all of them with `Tools::caf(CafTool::ALL)`, or some:

```rust
let open = OpenChat::new("claude", folder).with_tools(Tools::caf(CafTool::ALL));
```

A chat given Bash gets TaskStop too, as Bash's background jobs need it.

## Read

`{file_path, offset?, limit?}`, and Claude's `allow_large` and `pages`,
which are taken. Its answer is the file's lines, numbered from 1, each as
`{n}\t{line}`.

- **How much:** 2,000 lines unless `limit` says. A read of more than about
  25,000 tokens (a quarter of its bytes) is refused, in Claude Code's
  words, telling the model to read part of it; so is a read of a whole
  file bigger than 256 KiB with no `limit`. `allow_large` lifts both:
  the whole file is read, up to 100,000 tokens.
- **Lines** are split at `\n`. A `\r` before it is dropped, so the model
  never sees a Windows line ending; Edit puts them back (below). A UTF-8
  byte order mark is skipped.
- **An empty file**, or an `offset` past the end, is answered with Claude
  Code's reminder saying so.
- **A picture** (`.png`, `.jpg`, `.jpeg`, `.gif` or `.webp` whose first
  bytes say it is one) is given to the model as a picture, and the record
  has it as an `Image` piece.
- **Refused:** a PDF ("Reading PDFs isn't supported yet."), anything
  that isn't UTF-8 text, a folder, and a file that isn't there, whose
  answer names the chat's folder, as Claude Code's does. A notebook
  (`.ipynb`) is read as its JSON.

The record has what was read as a `Text` piece, and the file and first
line as its location.

## Edit

`{file_path, old_string, new_string, replace_all?}`, with `path`,
`old_str` and `new_str` taken for them. It replaces `old_string` with
`new_string`, once, or everywhere with `replace_all`.

- **It's refused, in Claude Code's words,** if the strings are the same;
  if `old_string` isn't in the file, or is there more than once without
  `replace_all`; or if the file is over 16 MiB.
- **An empty `old_string` makes a new file,** and is refused for a file
  that has text.
- **Matching** is exact, then with curly quotes (‘’“”) taken as straight
  ones, as models write them straight. A match through curly quotes keeps
  them: straight quotes in `new_string` are curled as the file's are.
- **An empty `new_string`** deletes the match, and the line ending after it.

Before anything is asked, CAF works the change out, so the question the
user answers, and the record, show the `Diff` of exactly what would be
written (see [Tool calls](/caf/concepts/tool-calls.md)). An edit that can't
be made, such as one whose string isn't there, ends the call at once,
*Failed*, with why, and asks nobody.

## Write

`{file_path, content}`. It writes `content` as given, line endings and
all, as Claude Code's Write does, making the file and any folders it's in.
A folder, or anything that isn't a regular file (a device, a FIFO, a
socket), is refused. Its diff is worked out and shown before it's asked
about, as Edit's is, *New file* when there was none.

## Read before you change

The model may change a file only as it has seen it, so it never writes
over something it didn't know was there. CAF keeps, for each chat, the
files its model read: each one's version, and the hash of what was read.

- **A file the model hasn't read** can't be edited or written: "File has
  not been read yet. Read it first before writing to it." A new file needs
  no read. A read of any part of a file counts, as in Claude Code, so a
  file too big to read whole can still be changed.
- **A file that changed since** is *stale*: its version moved, and its
  bytes aren't the ones read, or were read only in part, so the model
  can't know they're the same. Someone else, the user or a formatter,
  changed it. Write is
  refused: "File has been modified since read, either by the user or by a
  linter. Read it again before attempting to write it." Edit, as Claude
  Code's does, still makes the change if it applies to the file as it is
  now, and its answer tells the model the file has changes
  it hasn't seen, so it reads it before an edit that depends on them.
  Otherwise it's refused as stale.
- **Between the question and the write,** the file may change again: the
  write is made only if the file's version is still the one the change
  was worked out from, else it fails as stale, and nothing is written.
- **After a change,** the model has seen the file whole, as it wrote it.
  Its answer says so, so it needn't read it back.

What a chat has read is kept for one run of the app: a chat restored in the
next run starts with none, and the model reads again.

## Encodings and line endings

CAF reads and writes UTF-8 text, and leaves the rest of a file's bytes as
they were.

- **A byte order mark** stays: Read skips it, Edit keeps it.
- **Line endings stay.** Each line Edit doesn't touch keeps its own
  ending. The lines the model's `new_string` puts in end as most of the
  file's do (the endings in its first 4,096 characters), so the model's
  `\n` becomes `\r\n` in a Windows file.
- **Write writes what it's given,** as Claude Code's does: no endings are
  changed.
- **Anything else,** a file in UTF-16 or Latin-1, or a binary one, can't be
  read or edited: "This tool cannot read binary files."

## Bash

`{command, timeout?, description?, run_in_background?}`. It runs the
command, in a shell, in a terminal of its own (a pty), so a program that
draws progress bars and colours does, and answers with what it printed.

**The folder.** The first command runs in the chat's folder. Each runs in
the folder the last one ended in: `cd src` in one call leaves the next in
`src`, as the model expects from Claude Code. Variables and functions
don't carry over. A restored chat starts in its folder again.

**What the user sees.** The command's output comes into the record as it
runs (an `Output` piece, its lines with their colours, the way the
terminal showed them, a progress bar redrawn in place), and ends with how
the command ended. The call's title is the command's first line.

**What the model gets.** The output without colours, blank lines at its
start and end dropped. A command that failed starts with `Exit code {n}`,
or `Killed by signal {n}` (exit 1 from `grep`, `find`, `diff`, `test`
and the like means "no", so isn't a failure, as in Claude Code). One the
user stopped ends with `<error>Command was aborted before completion</error>`.
Output over 30,000 characters is saved to a file, and the model is given
its path and its first 2,000 characters, to read the rest with Read.

**The timeout** is 2 minutes unless the model asks for another, at most
10. A command still running then **isn't killed:** it's moved to the
background, as Claude Code does now, and the model is told so.

**Its environment** is your program's, with `TERM=xterm-256color`, and
`PAGER` and `GIT_PAGER` set to `cat` so nothing waits for a key. `CLAUDECODE`
and CAF's own relay variables are taken out. **Its input is `/dev/null`,
and it has no controlling terminal:** a command that waits for input finds
none at once, rather than waiting out its timeout, and a password prompt
such as `sudo`'s, `ssh`'s or `gpg`'s fails at once. Its output is still a
terminal, so its colours and progress bars are drawn.

**Stopping** a command (the user's Stop, while its turn runs) sends
`SIGTERM` to it and everything it started, then `SIGKILL` 3 seconds later.

## Background jobs

A command run with `run_in_background`, or one still running at its
timeout, becomes a **job**: the model is answered at once, with the job's
number and the file its output is being written to, and the command runs
on, past the model's answer and its turn.

- **It runs until it ends,** or the model stops it with TaskStop, or its
  chat is closed, deleted or put away, or the app shuts down. **The user's
  Stop doesn't stop it:** Stop stops the turn, not the work it left in the
  background, as in Claude Code.
- **Its call stays running in the record,** with its job's number
  (`ToolCall::job`), in its turn, however many turns later it ends. Apps
  mark it *Background* (see [the transcript](/caf/standard-interface/transcript.md#background-jobs)).
- **When it ends, CAF tells the agent** with a notice, as Claude Code
  does: `<task-notification>` with the job's number, where its output is,
  and how it ended (completed, with its exit code, or failed). It's sent as a message is, in a turn of its own
  (`Starter::Notice`): at once if the chat is idle, else once the running
  turn ends. After the user's Stop, notices are held, so the agent isn't
  set working again, and each is sent as its own turn just before the
  user's next message (see
  [Serving tools](/caf/concepts/serving-tools.md#background-jobs)). Its call
  ends *Done* or *Failed* where it is. A job stopped by TaskStop gets no
  notice, as the agent stopped it itself, and nor does one stopped with its
  chat or by the app shutting down.
- **At most 8 run at once** in a chat; a ninth is refused, telling the
  model to stop one with TaskStop first.
- **Jobs don't outlive the app.** A restored chat has none: a call saved
  running ends *Failed*.

**TaskStop** `{task_id}` stops one of the chat's own jobs: "Stopped task
3", or "No task 3 in this conversation" for any other number. It never
asks anyone, as all it can do is stop what its own chat started. The job's
call ends *Cancelled*, stopped by the agent.

**Output files** (a job's, and a long output's) are kept at
`out/<runner>/<chat>/<call>.txt` under CAF's tools folder
(`ToolsConfig::folder`, by default `$XDG_RUNTIME_DIR/caf`), readable by the
user alone. `<runner>` is the app's process id, with `-1`, `-2`… after it
for a second runner in one process, a third, and so on, and each runner locks its folder, so one
never touches another's. Each holds at most 64 MiB of
output, then says the rest wasn't kept. They're removed when the chat is let
go or the app ends, and those an app that's gone left behind are removed as
the next starts.

## Your editor and your terminals

CAF reads and writes files, and runs commands, through two backends, which
your app may replace in its `ToolsConfig`:

```rust
let mut config = Config::new(host, agents);
config.tools.relay = Relay::ThisProgram;
config.tools.files = Arc::new(EditorBuffers::new(editor));      // your `Files`
config.tools.commands = Arc::new(VisibleTerminals::new(panes)); // your `Commands`
```

**`Files`** (default `DiskFiles`, the disk) has two methods. `read` gives a
file's raw bytes and its `Version`, anything that tells whether it changed;
`write` replaces them, if the version is still the one given, else fails
with `FileError::Changed`. An editor's would read its open buffer, unsaved
changes and all, so the model edits what the user sees, and make each write
one undoable change. CAF does the decoding, the line endings and the
read-before-change rules itself, so a backend only moves bytes.

`DiskFiles` reads only regular files, at most 256 MiB, never through a FIFO.
Its version is the file's modification time, size, inode and device, and its
content's hash. (A backend of your own may give the bytes' sha256 with what
it read, `FileRead::with_sha256`, if it has it already; CAF works it out
otherwise.) It writes atomically: to a new file beside it, with its
mode, synced, then renamed over it, once its version is checked again. A
symlink's target is written, and a file with other hard links is written in
place, so it keeps them.

**`Commands`** (default `PtyCommands`, a pty of CAF's own for each command)
starts a command, given its line, folder and variables. What it starts
gives CAF what the command prints when CAF asks for more (`Running::output`,
`None` at the end), so it's read only as fast as CAF takes it, as a terminal
nobody reads holds its command up: raw terminal bytes, which CAF works into
lines on its own screen, or lines already worked out, for a terminal
emulator of your own. It can be waited for, interrupted (Ctrl-C) and
stopped, and says where
the user can watch it, such as *terminal 7*: the model's answer then starts
*Ran in terminal 7*, so the model knows the user saw it. Dropping it must stop the command.

`PtyCommands` runs `bash -c`, or `sh -c` where there's no bash, in a
session and process group of its own, its pty the terminal. The folder its
shell ended in comes back with how it ended, which is how Bash's folder
carries over. Like the rest of CAF's tools, it runs on Linux only: it
signals the command's process group through a pidfd.

A backend's methods return at once, and do their work in the future they
give back, as CAF's other drivers' do.

---

# Agents and Profiles

_CAF / Concepts_

> A program describes itself to CAF in plain terms, and CAF works out what to tell each agent from that agent's profile, which holds everything CAF knows about one adapter at one version, down to how to turn off the agent's own tools, install it and sign in to it.

## The program describes itself

A program using CAF never speaks ACP. It says, in plain terms, what it can
show the user: permission questions, the agent's thinking, and so on. CAF
works out what to declare to each agent.

What a client declares can change how an adapter behaves for the whole
connection, so CAF declares whatever makes the agent behave best, and covers
any gap itself. Forms are declared even to a program that can't show them,
for example, because Claude's adapter drops its question tool otherwise. CAF
then answers any form itself.

## Profiles

A **profile** holds everything CAF knows about one adapter at one version:

- what to declare to it, and what those declarations do to it;
- which of its features have been checked;
- how to read its oddities, such as how it reports a failure;
- how to start and configure it;
- how it describes what it's doing;
- how to turn off its own tools;
- its **recipe**: how to install it, how to sign in and out, and how to tell
  whether it's signed in.

The core uses profiles to translate each adapter's way of using ACP into
CAF's own terms, so nothing past the profile knows which agent it's talking
to.

When an adapter starts, it says its name and version, and CAF checks them
against the profile:

| Check | What CAF does |
|---|---|
| This version was checked | Every feature the profile lists is on |
| A newer version than any checked | The last checked profile, with its risky features off, and its tools turned off the same way |
| A different adapter, or none named | The cautious profile, and no session is opened |

The **cautious profile** is for agents CAF doesn't know: plain ACP, with
nothing risky switched on. CAF can't turn off such an agent's own tools,
so it never runs one: see below.

Profiles are CAF's own: a program chooses one for each agent but never
changes one. Today CAF has profiles for Claude Code's adapter,
`claude-agent-acp`, checked at 0.98.0, and the cautious one.

Everything that's particular to one agent is data in its profile. Nothing
else in CAF is written for one agent, so adding an agent is adding a
profile.

## An agent has only your tools

Every agent runs with **none of its own tools**. Claude Code, for example,
can usually read and edit files, run commands and search the web, and it
loads the user's own setup: their MCP servers, skills, plugins, hooks,
slash commands, and instruction files such as `CLAUDE.md` and `AGENTS.md`.
CAF turns all of that off, as the agent's profile says how. The only tools
the agent has are the ones your program gives it: CAF's own, Read, Edit,
Write and Bash, as you choose for each chat (`OpenChat::with_tools`, see
[Serving tools](/caf/concepts/serving-tools.md)), and your own MCP servers
(`OpenChat::mcp_servers`).

CAF's tools replace the agent's own, in CAF's own terms: what each does,
the permission it needs, and how it shows in the chat. CAF serves them to
the agent as an MCP server named `caf`, so no server of yours may have that name, in
any case, nor one the agent would write as `caf`, or as `caf_` or
anything starting `caf__`: Claude Code writes each character but a
letter, a digit, `_` and `-` as `_`, so `caf.` and `caf__x` would name
tools as CAF's do (`caf.x`, written `caf_x`, is fine). Opening or restoring a chat with
one is refused (`Refused::ReservedServer`). Nor may two of your servers have
names the agent would write alike, such as `my tools` and `my.tools`, both
`my_tools`: a chat with them is refused (`Refused::SameServerName`), as
the agent couldn't tell their tools apart. The agent never asks permission for CAF's own
tools; CAF asks your policy, and the user, itself.

Each session starts in the agent's ordinary permission mode, in which it
asks before using a tool not yet allowed. Claude's adapter would start it
in the user's own default mode, from their `~/.claude/settings.json`, such
as plan mode, in which no tool runs; CAF sets it back to `default` as the
session opens, before anything is sent, unless the session says it's in
`default` already. If the agent won't, CAF logs a warning and carries on:
it still asks about its own tools itself, but your MCP servers' tools may
then run without the agent asking.

In place of the agent's built-in instructions, which describe tools it no
longer has, CAF gives it short ones of its own. For a program called
`framewright` they say:

> You are working inside framewright, the app the user is talking to you
> in. You have no tools of your own: you can't read or change files, run
> commands or browse the web, except through tools framewright gives you.
> Answer in Markdown.

That's for a chat with no tools of CAF's. For a chat given Read and Bash,
the second sentence names them instead:

> You are working inside framewright, the app the user is talking to you
> in. framewright gives you tools to read files (Read) and run commands
> (Bash), in the folder you're working in, asking the user's leave where it
> must. You have no other tools of your own: you can't do anything else,
> such as browse the web, except through other tools framewright gives
> you. Answer in Markdown.

Your program can add its own after them, such as a description of the
project open, with `OpenChat::instructions`. They're sent each time the
chat's session is opened, so they're kept to 64 KiB. They aren't saved:
give them again when you restore the chat (`RestoreChat::instructions`).

**CAF never runs an agent it can't strip.** An agent with the cautious
profile is refused (`Refused::OwnTools`): opening a chat with it fails, as
does sending a message to a restored chat with it. Its status says so
beforehand: `AgentStatus::own_tools_off` is false. An agent whose adapter
turns out not to be the one its profile is for falls to the cautious
profile, so its chats get no session: they're lost, as CAF can't turn off
its tools, and their waiting messages fail. From then on, in that run, its
status says `own_tools_off` is false too, until an adapter of it answers
as the one its profile is for. A status read from an older CAF, which
didn't turn tools off, says false.

For Claude, a few things stay as they are: settings an organisation
manages on the machine, the plugins built into Claude Code, and the
adapter's own `/mcp` command, which the user can send as a message (the
agent can't call it) to see the program's MCP servers and reconnect them.
The adapter offers `/remote-control` too, but it fails: CAF turns Remote
Control off, so a chat is never reachable from claude.ai. The user's sign-in is
untouched, but one that lives in their own Claude Code settings, such as
an API key helper, isn't read, so the chat asks them to sign in.

## Where an agent stands

A program offers each agent in one of two ways:

- **installed by CAF** (`AgentSpec::installed`), from its profile's recipe;
- **started by the program's own command** (`AgentSpec::command`), such as
  an adapter the user installed themselves.

Either way, each agent has a status that every chat with it shares, since
they share one install and one sign-in (`Core::agents`). It says whether
the agent is installed, being installed (with progress), or can't be, and
why; and whether it's signed in, signed out, being signed in to (with the
link to open), or not known yet. CAF keeps only *how* an agent is signed
in, such as by subscription or with an API key, never *who*.

## Installing

CAF installs an agent's adapter at exactly the version its profile was
checked at. Claude's comes from npm, with a lockfile CAF ships, so every
dependency, Claude Code itself included, comes at the version and checksum
in it, and no install script runs. It needs Node 22 or later and npm on the
machine; CAF checks, and says exactly what's missing. An agent that's
downloaded instead is checked against its SHA-256 before it's unpacked.

Installs live in one folder that every CAF program on the machine shares:
`$XDG_DATA_HOME/caf/agents/`, by default `~/.local/share/caf/agents/`.
Each version has its own folder there, named after the agent's profile,
never after what a program calls the agent, such as
`claude-agent-acp-0.98.0`. So every program that offers Claude shares one
install of it, whatever it calls it. An install
is built in a hidden folder and renamed into place whole, so one cut off
halfway leaves nothing that looks installed, and two programs installing at
once can't collide.

The **setup driver** does the work: the core decides, from the recipe,
what to install, and the setup driver downloads, checks and writes. It's
one of the core's [drivers](/caf/concepts/the-core.md), so every install is
recorded and replays like everything else.

Installing is the user's choice, as an adapter can be large (Claude's is
about 630 MB). A chat opened with an agent that isn't installed **waits for
its agent**: its messages wait with it, and its agent's status says it can
be installed, and how big it is. Then:

- **Install**: once it's done, the chat starts, and its messages go.
- **Not now**: stopping the chat stops its waiting messages, and the chat
  says the agent wasn't installed.
- **It fails**, say because the machine is offline: the waiting messages
  stop, the chat says the install failed, and the agent's status says why.
  Installing again tries again.

A CAF release that moves to a newer version installs it on next use,
asking again. Older versions are removed once the new one has started,
but only those no program has started an agent from for 14 days: another
program on the machine may pin an older version, and still use it. A
version is never removed while any program runs from it, and a program
never removes a version newer than its own.

## Signing in

CAF signs in to an agent with the agent's own command, as its recipe says,
never with anything the agent suggests. For Claude, that's the Claude Code
that came with its adapter, so the user needs no copy of their own, and
no terminal:

1. The program calls `Core::sign_in`, or the user chooses **Sign in** on a
   turn that failed for want of it.
2. CAF runs the sign-in command and catches the link it would open in a
   browser. The agent's status shows it, for the user to open.
3. CAF checks the link goes to one of the sites the recipe names, such as
   `claude.com`. A link anywhere else stops the sign-in, so CAF never
   shows the user a link to a site the agent's profile doesn't name.
4. The user approves the sign-in in their browser, and it finishes by
   itself. If their browser is on another machine, the page gives them a
   code to paste back, and the program passes it on (`Core::paste`).

Once it's done, each chat whose last turn failed for want of signing in
says so, and its message can be sent again. CAF never sends it again by
itself.

While a sign-in to an agent that was signed out is under way, new chats
with it **wait for their agent**, as they do for an install, since
starting it would only fail: its status shows the sign-in, with its link.
A sign-in nobody finishes is stopped after a while (10 minutes, unless the
program sets otherwise), and the chats waiting on it go ahead.

Agents CAF installs from one profile share one sign-in too, whatever
the program calls them: signing in to one signs in to all of them.

CAF learns whether an agent is signed in from what the agent says when it
starts and as it works, from a status command where the recipe has one,
and from failures. Of what the agent says about its account, CAF reads only
how it's signed in. The rest, such as the account's email, is never kept,
logged or recorded.

Sign-ins are kept by the agents themselves, as Claude keeps its own, so
every CAF program on the machine, and the user's own Claude Code, share one
sign-in. CAF stores no credentials. Signing out runs the agent's own
command too.

An agent started by the program's own command can be signed in to the same
way, if its profile says how, once it has started and said it's the adapter
that profile is for. The exception is an agent that keeps its sign-in in a
private folder CAF gives it: only CAF's own install of it is given one, so
CAF doesn't run commands that need it for the program's own.

## Settings

The user can choose an agent's model, how hard it thinks (its effort) and
fast mode, for any agent. The agent says what it offers, never CAF: once a
session opens, the agent's profile reads its list from however the agent
gives it (ACP's session config options, or an older agent's list of
models) into one shape, and a chat holds it beside what was chosen. What
the agent offers that CAF doesn't support yet, such as Claude's modes,
stays as the agent set it.

A chat's choices are sent before any message, one at a time and the model
first, as which effort levels there are depends on it; a change made while
a turn runs waits for it to end. A message never goes on a setting nobody
chose without saying so: a choice made for the chat itself that can't
be applied fails the messages waiting, and the chat says so; one that
stops being offered, or that the agent changes by itself, is said in the
chat too. The agent's status
says what it offers before any chat, once CAF has learned it
(`Core::learn_settings`). See
[Choosing the model](/caf/getting-started/choosing-the-model.md).

## Sharing an adapter

One adapter process can serve many chats. The program chooses whether each
agent's chats share one process, which saves memory, or each chat has its
own, so chats never affect each other. Either way, when a process is
restarted or lost, every chat it served is told.

---

# Viewers

_CAF / Concepts_

> A viewer is anything that shows chats, such as a window or a web page. It speaks to CAF in a small versioned set of messages, follows each chat as a picture and then changes, and asks the host, never CAF, to open a chat.

A **viewer** is anything that shows chats: clackatoo's window, a web page
using the TypeScript caf-sdk, or CAF's own debugger. It may be in another
process, or another language, from the program running CAF, so it talks to
CAF in messages: the **viewer wire**, in `caf_core::viewer`.

The wire is only the messages. It does no I/O, so every transport (a
WebSocket, a socket, a pipe) carries the same ones, and the program running
CAF chooses how. Rust viewers such as clackatoo's window send them as
MessagePack with field names; TypeScript sends them as JSON.

## A link, in order

1. The viewer says **Hello**, with the oldest and newest versions of the
   wire it speaks. Anything else first ends the link.
2. CAF answers **Welcome**, with the version both will speak, the agents a
   viewer may open chats with, the chats loaded (archived ones marked),
   which run of CAF this is, and what the host lets this viewer do: act on
   chats, and on agents. If there's no version in common, it says so and
   ends the link.
   Right after the welcome, CAF says where every agent stands (**Agents**):
   installed or not, signed in or not. It says so again, the whole list,
   each time any of it changes.
3. The viewer **watches** chats. For each, it gets the chat whole, then its
   changes as they happen, until the chat is put away or deleted, or CAF
   shuts down. Closing a chat that isn't saved only archives it, and its
   watch goes on, so a viewer unwatches an archived chat it stops showing.
4. It may act on them: send a message, stop a turn, answer a question, close
   a chat, which archives it, unarchive one, or ask to open one. It may ask
   to install an agent, sign in to or out of one, or have CAF check every
   agent again, such as after the user installs Node, if the host lets
   viewers. Each request carries a number the viewer
   chose, and CAF quotes it back with how it went: done, refused with the
   core's reason, not allowed by the host, or not done because CAF has
   shut down.

## Pictures and changes

Each chat keeps a numbered list of small changes (see
[Following a chat](/caf/concepts/chats-turns-and-items.md#following-a-chat)).
A viewer following a chat keeps a copy of it, and the number of the last
change it has.

- A **picture** is the chat whole, with the number of the last change it
  includes. A new viewer gets one first. So does one that fell too far
  behind, or reconnected after CAF dropped the changes it missed. A picture
  may come at any time, and replaces the copy.
- **Changes** come after it, oldest first, each naming what it changes by
  id: a turn added, words appended, a tool finished, a question asked or
  gone.

A viewer that reconnects can say which change it has, and gets only what
followed, if CAF still has it. Otherwise it gets a picture.

That holds only within one run of CAF. The welcome names the run, and the
name is different every time CAF starts, when its changes are numbered
again. A viewer that finds a different run from the one it was watching
drops its copies and watches each chat afresh.

### Applying a change

`Chat::apply` takes one change and updates a chat with it. It's the only way
a chat's record changes: the core builds its own record with it, and every
viewer's copy is built with it, or with its equal in another language. So
they can't drift apart.

A change that names something the chat doesn't have, such as words for an
item it never saw, doesn't fit. The chat is left as it was. In a viewer that
means it missed something, and needs a fresh picture. Inside the core it's a
bug, reported as one.

`ChatCopy` is a viewer's copy of one chat. It skips changes it already has,
and asks for a picture when a change is missing or doesn't fit, keeping what
it applied before then.

Every SDK's `apply` must turn the same changes into the same chat. The
**conformance fixtures** in `fixtures/apply/` check it. Each is one chat
from CAF's tests or recorded sessions, as the core saw it before its first
change, then each change and the chat after it. Some end in a change that
doesn't fit, with how it doesn't, so every SDK refuses the same changes
too.

## Versions

The two ends speak the older of their newest versions, and what a version
sends never changes. A later version may add messages, kinds of change,
reasons and fields, so a viewer skips what it doesn't know:

- a message it doesn't know, it ignores;
- a kind of change it doesn't know, it can't apply, so it asks for a fresh
  picture;
- a reason it doesn't know, such as why a chat lost its session, it shows as
  unknown, with its name;
- a field it doesn't know, it doesn't read. A field added later is always one
  an older viewer can do without.

`samples/viewer/v1.json` holds one of every message of version 1, and a test
fails if what CAF writes no longer matches it.

Every number on the wire is below 2^53, so JavaScript reads it exactly: CAF's
ids count up from 1, and times are milliseconds.

## Opening is the host's decision

A viewer can't open a chat by itself. It asks, with an agent CAF offered, a
folder, and a new session or one to continue, and the **host**, the program
running CAF, decides.

That's because of what opening a chat can do. The full request to open a
chat includes the chat's MCP servers, the tools the agent is given. An MCP
server may be a program to run on the machine, or a server reached with
secret headers. A viewer may be a web page, and a web page that could send
one could run anything, or reach anything. So the host turns a viewer's
request into a chat with the tools it chooses, or refuses it.

---

# The Standard Interface

_CAF / Standard Interface_

> How a chat with an agent should look and behave in any app built on CAF, so a user moving between CAF apps finds the same thing. What CAF SI standardises and what it leaves to the app, how firm each part is, the colour roles, the words, and how to use these pages, or point an agent at them, when building a UI.

CAF SI, the Standard Interface, is how a chat with an agent should look and
behave in any app built on CAF. CAF itself draws nothing: an app draws its
chats from what CAF tells its viewers. These pages say what to draw, so every
CAF app draws the same thing, and nobody has to invent it.

They're written to be followed exactly, by a person or by an agent building a
UI. To have an agent build a chat UI on CAF, point it at this section: every
page here is also published as plain Markdown, and the section as a whole is
one Markdown page too, which the site's `llms.txt` lists.

## What it covers

**CAF SI standardises a single chat, and says nothing about how an app
arranges its chats.**

The test for any part is whether a user moving between two CAF apps would be
confused or misled if it differed. If they would, it's standard. Everything
inside a chat passes that test: what the agent is doing, what's waiting on
the user, what went wrong and what to do about it.

How an app finds and arranges its chats doesn't. Every app already has its
own way of navigating its things: a sidebar, tabs, clackatoo's panes and
workspaces. Guidance there would only push an app into growing a second way,
which is exactly the awkward integration CAF SI exists to prevent.

## How firm each part is

Every part on these pages is marked with how firm it is:

- **Required.** Everything inside a chat; how a chat is identified wherever
  it appears; the words and actions for what happens to a chat; the colour
  roles. Copy these.
- **Suggested.** Where the app should choose, such as how the usage page is
  laid out. Take the way shown, or another the page names; don't invent one.
- **Up to the app.** The app's own frame: where chats are listed, panes,
  windows, workspaces, projects (CAF's shelves), search, keyboard shortcuts
  beyond the composer's, empty lists. Use what the app already has.
- **Later.** Drawn for something CAF doesn't provide yet, so the design is
  ready when it does. Don't build it until CAF does.

Nothing is enforced: an app that ignores CAF SI still works. But an app that
follows it looks and behaves like every other CAF app, which is the point.

## The pages

- [The composer](/caf/standard-interface/composer.md): where the user writes.
  Its settings menu, the context ring, waiting messages, and where questions
  and the agent banner attach.
- [The transcript](/caf/standard-interface/transcript.md): turns as a summary
  line that opens into a timeline; failures and their remedies, questions,
  CAF's notes, a chat that lost its agent, and the agent's own history.
- [Agents](/caf/standard-interface/agents.md): installing and signing in; the
  agent banner and the agents panel.
- [A chat's identity and lifecycle](/caf/standard-interface/chats.md): how a
  chat is named and marked wherever it appears; restoring, archiving,
  deleting and starting chats.
- [Usage](/caf/standard-interface/usage.md): context, cost and account limits in
  the chat, and the usage page.

Each page links to its mock-up, live: an HTML page drawing every state, in
dark and light, which you can click through. The pictures on these pages are
taken from those mock-ups, in the dark theme. **Where the words on a page
and a picture differ, the words are right.**

## Colour roles

**Required.** The mock-ups use clackatoo's colours. An app may use its own
palette, but keeps these roles, and uses each colour only for its role:

| Role | Means | Used for |
| --- | --- | --- |
| Accent | Act here, or happening now. | For example: the lit Send button, the caret, primary buttons, what's chosen (a tick's row, a lit switch, the slider, a filter's mark, a favourite's star, the focused search box), the edge of something waiting on the user (a question, the agent banner), and what's running now (a spinner, the *Working* mark). Kept to those kinds of thing, so it still means "here". |
| Warning | It went wrong, or can't go on. | Failed turns and steps; refusals, a step refused included; restores that can't happen; a limit that's out; context past 95%; an action that can't be undone, such as Delete. |
| Caution | Held, getting close, or needs the user soon. | A setting change waiting for the turn to end; context or limits filling up; a chat that lost its agent; a note that the agent remembers nothing; extra usage in use; the mark on an agent that still needs installing or signing in, in a list or the agents panel (the agent banner itself, waiting on the user, has its own tone). |
| Link | Something to follow. | Links that open a page. Never something to act on: *Copy link* and *Learn them now* are buttons. |
| CAF's voice | CAF is speaking. | The CAF badge on what CAF says in the transcript (its notes, failures, and questions it asks itself), so it never reads as the agent. A box that says what to do next, such as a lost chat's, is the app's own frame and carries none. |
| Muted | Matters less. | Times, counts, the agent's thinking, steps once they're done or cancelled (the user chose to stop them, so nothing went wrong), the agent's own history. |

Anything else is **calm**: the ordinary text colour, or muted, with no role.
Buttons come in three looks: **primary**, filled with the accent, for the
one thing to do; **plain**, raised but with no role colour; and **quiet**,
text only, in the muted colour, for a secondary action or a way out, such
as *Not now*.
An agent's or an app's own colour, such as Claude's orange, is identity, not
a role: it appears only in their marks and to tell them apart in charts, and
never on text, controls or edges.

clackatoo's values, which the mock-ups use:

| Role | Dark | Light |
| --- | --- | --- |
| Accent | `#d9b24a` | `#d9b24a`, and `#8a6a12` for text |
| Warning | `#e06c75` | `#c0404b` |
| Caution | `#e89a3c` | `#b0660f` |
| Link | `#7cb7f5` | `#2d6db5` |
| CAF's voice | `#6fd3c9` | `#1f9488` |
| Muted | `#8a9099` | `#666c75` |

## Words

**Required.**

- **Users never see CAF's own words:** *shelf*, *loaded*, *put away*,
  *session*, *adapter*. Use the app's words, or none.
- **CAF's *close* is shown as *Archive*.** Closing a tab or a pane never
  archives a chat: see [A chat's identity and lifecycle](/caf/standard-interface/chats.md)
  for what it does.
- **CAF speaks in its own voice**: its notes, failures and questions are
  marked as CAF, and the agent's words are quoted as the agent's. Neither is
  ever presented as the other.

---

# The Composer

_CAF / Standard Interface_

> Where the user writes to the agent, as every CAF app should draw it. Its parts, every state it can be in, the settings menu, messages that wait, settings changes held until a turn ends, the context ring, and what the user can't do, with the words for each and what CAF tells the app.

The composer is where the user writes to the agent. It sits at the foot of
the chat, under the transcript, and it's also where anything waiting on the
user appears: questions, and the agent banner when the agent isn't ready.

[See the composer live](/attachments/caf-si-composer/composer.html), every state, in dark
and light.

![The composer while the agent works, with two messages waiting](/caf/standard-interface/composer-waiting.webp "The composer while a turn runs, with two messages waiting for it")

**Required, all of it**, but for favourites, which are the app's. The
composer is inside the chat, and a user moving between CAF apps should find
it the same in each.

## Its parts

One rounded box. The message is on top and the controls run along the
bottom. Nothing sits above the text inside the box.

| Part | Where | What it is |
| --- | --- | --- |
| The message | The top of the box | Plain text, as many lines as the user writes. |
| The settings control | Bottom left | The agent's mark and one control for all its settings: *Opus 5.5 · High*, with a bolt when fast mode is on. It opens the settings menu. |
| The context ring | Bottom right | How full the agent's context is, as a ring and a percent. It opens the usage popover. |
| The round button | Bottom right, after the ring | **Send**, or **Stop** while a turn runs or the chat opens, and the box is empty. |
| The tray | Above the box | Messages waiting to be sent, why a message couldn't be sent, or that the chat is archived. |
| What's attached | Between the tray and the box, joined to the box | A question waiting on the user, or the agent banner. Only one at a time. |

From the top, then: the tray, then what's attached, then the box.

**One thing attaches at a time.** If a question and the agent banner both
apply, the question attaches, and the banner returns once it's answered. If
several questions wait, the oldest attaches, and the next takes its place
when it's answered.

The accent colour marks what to press and what's chosen, as the
[colour roles](/caf/standard-interface/overview.md#colour-roles) say: in the
composer, the lit round button, the caret, the effort slider, the lit fast
mode switch, the chosen row in the menu and its filter's mark, favourites'
stars, the search box's underline, and the edge of a question from the
agent. The agent banner's edge takes the banner's own tone, and a question
CAF asks itself, such as whether to keep waiting for a chat to open, is
calm.

## Writing

![The composer, empty](/caf/standard-interface/composer-empty.webp "Idle, nothing typed: Send is unlit")

**Empty.** The chat is idle and the box is empty. The box says
*Message Claude*, with the agent's name, and Send is unlit: pressing it does
nothing.

![The composer with a message typed](/caf/standard-interface/composer-typing.webp "Text in the box: Send lights up")

**Typing.** As soon as there's text, Send lights up in the accent.

![A message that couldn't be sent](/caf/standard-interface/composer-failed.webp "The message couldn't be sent: the text stays, and the tray says why")

**Couldn't send.** When a message can't be sent, its text goes back in the
box, untouched, and the tray says why, in the warning colour. The user's
words are never lost. The words, by what happened:

| What happened | The tray says |
| --- | --- |
| The link to the app dropped before CAF answered | *Couldn't send: the connection to the app dropped, so it may not have gone. Your message is still here: check the chat before sending it again.* |
| Too many messages are waiting (`Refused::QueueFull`; the app sets how many may, eight by default) | *Couldn't send: 8 messages are already waiting. Send this once one has gone.*, with the number that waits |
| The agent can't take the message (`Refused::Unsupported`) | *Couldn't send: Claude can't take this message.* |
| The chat isn't open any more (`Refused::NoSuchChat`) | *Couldn't send: this chat isn't open any more.* |

A chat whose agent is gone or can't be run (`Refused::NoSuchAgent`,
`Refused::OwnTools`) shows [Can't write](#what-the-chat-allows) instead, so
the user isn't invited to send at all. An archived chat isn't one: a
message to it is sent, and brings it back, as
[Archived](#what-the-chat-allows) says.

## Messages that wait

A message sent while the agent can't take it yet waits, and goes as soon as
it can (CAF queues it). Waiting messages sit on the tray, each with a clock,
under a heading that says what they wait for and how many there are. Send
stays available: more can wait.

| While | The tray's heading | The box says |
| --- | --- | --- |
| A turn runs | *Waiting for this turn · 2* | *Message Claude: it waits for this turn* |
| The chat is opening | *Waiting for Claude to open · 1* | *Message Claude: it waits for Claude to open* |
| The chat waits for its agent | As [Agents](/caf/standard-interface/agents.md) says | *Message Claude: it waits until Claude is ready* |

At the heading's other end, the tray says what drops them: *Stop drops these
too*, or *Stop drops it too* for one, while a turn runs or the chat opens.
While the chat waits for its agent, the round button stays **Send**, and the
agent banner's **Not now** drops what waits, as
[Agents](/caf/standard-interface/agents.md) says.

### While a turn runs

![The composer while the agent works](/caf/standard-interface/composer-running.webp "A turn running, the box empty: the button is Stop")

**Running.** While the agent works and the box is empty, the round button is
**Stop**, lit.

![Typing while the agent works](/caf/standard-interface/composer-running-typing.webp "Typing during a turn: Send again, with Stop beside it")

**Running, and typing.** Typing during a turn turns the round button back
into **Send**, because the message will wait. Stop moves to a smaller button
beside it, so it's still one click away. A note by the buttons says
*waits for this turn*.

**Messages waiting.** The picture at the top of this page: two messages wait
for the turn. Stop ends the turn and drops them too: they become turns that
were stopped before they were sent, as
[the transcript](/caf/standard-interface/transcript.md) shows.

![Stopping](/caf/standard-interface/composer-stopping.webp "Stop asked for: the button spins until the agent confirms")

**Stopping.** Once Stop is pressed, and until the agent confirms the turn has
stopped, the round button spins and can't be pressed again. Its tooltip says
*Stopping…*.

### While the chat opens

![A message waiting for the chat to open](/caf/standard-interface/composer-opening.webp "The chat still opening, with a message waiting")

**Waiting to open.** A message sent while the chat is still opening waits
for it. There's no turn yet, so the tray says *Waiting for Claude to open*.
The round button is **Stop**, as during a turn: it gives up opening, and
drops the message (`Core::stop`).

## Settings

The settings control shows what the agent uses now: the model, the effort,
and a bolt when fast mode is on. It opens one menu that holds them all.

![The settings menu](/caf/standard-interface/composer-menu.webp "The settings menu: a rail of filters, search, the models, and effort as a slider")

**The menu.** It's drawn as clackatoo's model menu:

- **A rail down the left** filters the list: favourites first, then the
  chat's agent. Fast mode is at its foot, lit in the accent when on, and gone
  when the model doesn't offer it. Its tooltip says
  *Fast mode on: faster answers, may cost more*, or *off*.
- **Search**, at the top: *Search models…*.
- **The models**, as the agent names and orders them, each with its
  description. A choice that stands for whatever the agent would pick, such
  as Claude's *Default (recommended)*, is listed as the agent names it. The
  one in use has a tick. Each has a star, to make it a favourite.
- **Effort, as a slider**, under the list, from the agent's lowest level to
  its highest, each level named.

Each setting appears only if the agent offers it. CAF says what the agent
offers in `Setting.form`: a list of `Choices` (models, effort levels) or a
`Switch` (fast mode). The menu is built from that, never from a list the app
keeps itself. See [Choosing the model](/caf/getting-started/choosing-the-model.md).

![The favourites filter](/caf/standard-interface/composer-menu-favs.webp "The favourites filter: starred models only")

**Favourites. Up to the app.** The star filter shows only starred models.
Favourites belong to the app, which keeps them as it likes; CAF knows
nothing of them. An app without favourites leaves out the stars and the
filter.

### A change not applied yet

A setting changed during a turn doesn't apply to it. CAF holds the change
and sends it as the turn ends, so it applies from the next message. A change
made while the chat opens, or while the agent hasn't answered it yet, waits
the same way.

CAF tells the app: a chat's `settings.chosen` differs from what the agent
says is `current` until the change applies. A part is drawn as not applied
yet, in the caution colour with a clock, when the chat's `settings.offered`
holds that setting, its `current` is known, and the choice differs from it.
While a setting's `current` isn't known (the agent doesn't say), or the chat
has no `offered` yet, the control shows what's chosen, plainly. The tooltip
says *From the next turn* while a turn runs, and *Not applied yet*
otherwise.

![Effort held](/caf/standard-interface/composer-held.webp "Effort changed during a turn: amber with a clock until it applies")

**Effort held.** The control shows what will apply, *Max*, with the clock.

![Model held](/caf/standard-interface/composer-held-model.webp "The model changed during a turn")

**Model held.** The same: the new model is in the caution colour with a
clock until it applies. Effort and fast mode stay as they are, because what
the new model offers isn't known until it applies.

![The menu while a model change is held](/caf/standard-interface/composer-held-menu.webp "The menu while the change is held: effort can't be changed yet")

**The menu, while a model change is held.** The current model keeps its
tick, and the one picked says *after this turn*, or *not applied yet*, with a
clock. Picking the current model again cancels the change. **Effort and fast
mode can't be changed until the new model applies**: they're dimmed, and
effort is headed *Effort · Opus 5.5's: change it once Sonnet 5.5 applies*.
CAF checks a choice against what's offered now, so an effort level only the
new model has can't be chosen before it applies.

### After the model changes

![The model changed](/caf/standard-interface/composer-switched.webp "The turn ended, and the new model applies")

**The model changed.** Once the turn ends, the new model applies. The agent
then says what that model offers, and the control follows: here, the new
model has no fast mode, so the bolt goes.

![The first turn on the new model](/caf/standard-interface/composer-switched-turn.webp "A divider marks where the model changed")

**A divider in the transcript** marks where the model changed: the agent's
mark, the new model, and *from* the old one, muted. The app draws it wherever
a turn's model (`Turn.model`) differs from the turn before, so it needs
nothing more from CAF, appears in restored chats too, and sits exactly where
answers start coming from the new model.

![The menu after the change](/caf/standard-interface/composer-switched-menu.webp "Effort shows the new model's levels")

**The menu after the change** shows the new model's effort levels, and the
fast mode switch is gone if the model doesn't offer it. If something the user
chose isn't offered any more, CAF falls back to what is, and puts a note in
the transcript (`Note::NotOffered`).

### Before CAF knows the settings

While a chat's `settings.offered` is empty, as it is until a chat first
opens, its settings are what CAF knows of the agent's:
`AgentStatus.settings`, which is `Unknown`, `Learning`, `Known` or
`Failed`. A new chat with an agent whose settings are `Known` shows the menu
as above, from those.

![Settings not known yet](/caf/standard-interface/composer-unknown.webp "A new chat, before CAF knows the settings")

**Not known yet** (`Unknown`). The control says *Settings not known yet*, or
*Settings* where it's narrow, and nothing more.

![The menu when the settings aren't known](/caf/standard-interface/composer-unknown-menu.webp "The menu offers to learn them now")

Its menu says *CAF doesn't know yet which models and settings Claude offers.
It finds out when the chat opens, or now, without sending a message.*, and
offers a **Learn them now** button, which has CAF find out
(`Core::learn_settings`). Only a viewer with the `agents` right sees the
button; for any other, the menu leaves out *, or now, without sending a
message*.

![Learning the settings](/caf/standard-interface/composer-learning.webp "CAF learning the settings")

**Learning** (`Learning`). The control says *Learning Claude's settings…*
with a spinner, and can't be opened.

![Couldn't learn the settings](/caf/standard-interface/composer-learn-failed.webp "CAF couldn't learn the settings")

**Couldn't learn them** (`Failed`). The control says
*Couldn't learn Claude's settings*, or *Settings* where it's narrow.

![The menu when the settings couldn't be learnt](/caf/standard-interface/composer-learn-failed-menu.webp "The menu says why, and offers to try again")

Its menu says *CAF couldn't learn which models and settings Claude offers.*,
then why, in bold, then *It tries again when the chat opens, or now.*, with
the same **Learn them now** button, and the same rule for a viewer without
the `agents` right. CAF says why as a `LearnFailure`, and the words are the
app's, with the agent's name in place of *Claude*:

| Why (`LearnFailure`) | The menu says | Learn them now |
| --- | --- | --- |
| `NotInstalled` | *Claude isn't installed.* | Yes |
| `NotLookedYet` | *CAF hadn't checked yet whether Claude is installed.* | Yes |
| `SigningIn` | *Claude was being signed in to.* | Yes |
| `SignInNeeded` | *Claude wants you to sign in first.* | Yes |
| `CouldNotStart` | *Claude couldn't be started.*, then what the system said | Yes |
| `Refused` | *Claude refused to open a chat.*, then what Claude said | Yes |
| `StartTimedOut` | *Claude didn't start in time.* | Yes |
| `OpenTimedOut` | *Claude didn't open a chat in time.* | Yes |
| `Unreadable` | *Claude's answer made no sense.* | Yes |
| `Restarted` | *Claude was restarted.* | Yes |
| `Stopped` | *Claude stopped.* | Yes |
| `ShutDown` | *The app was closing.* | No |
| `Incompatible` | *This version of Claude can't talk to this app.* | No |
| `OwnTools` | *Claude can't be used: its own tools can't be turned off.* | No |

Where [the transcript](/caf/standard-interface/transcript.md) words a chat
losing its agent for the same cause, the menu uses its sentence, so the
user meets one sentence for one cause: `CouldNotStart`, `SignInNeeded`,
`Restarted`, `Stopped` (its `AgentStopped`), `Unreadable` (its
`BadAnswer`) and `Incompatible` (its `Protocol`). Three are adapted, as
learning them opens no chat of the user's: `Refused` says *a chat*, not
*this chat*; `ShutDown` says the app *was closing*, not that it closed
while this chat was open; and `OwnTools` is the sentence for an agent CAF
won't run, as [A chat's identity and lifecycle](/caf/standard-interface/chats.md)
has it. The others, which no chat meets, are the menu's own. A reason
newer than the app knows has no sentence: the menu says its first and
last sentences, with the button.

**Where trying again can't help**, the menu ends with why, and has no
button and no *It tries again…*: the app is closing (`ShutDown`), or CAF
can't use the agent at all (`Incompatible`, `OwnTools`), which nothing
the user does from the menu changes.

![What the agent said, quoted](/caf/standard-interface/composer-learn-failed-agent.webp "Claude refused, and said why: its words, quoted apart")

**What the system or the agent said.** CAF keeps their words apart from
why: what the system said when the agent couldn't be started
(`CouldNotStart.error`), and what the agent said refusing
(`Refused.message`), each cleaned and capped. The menu shows them under
why, as theirs, and never as CAF's: the system's in a monospace font,
muted, as a chat that can't be restored shows the store's; the agent's
introduced as *Claude said:*, in quotation marks, muted, with a rule down
its left, as a failed turn quotes it. They often say what to do, such as
that a file is missing, which no sentence of the app's could. Either may be
empty, and is then left out.

![Couldn't learn them, for good](/caf/standard-interface/composer-learn-failed-never.webp "CAF can't use the agent: why, and nothing to press")

![An agent that offers no settings](/caf/standard-interface/composer-none.webp "An agent with no settings: its mark and name")

**None offered.** An agent that offers no settings shows only its mark and
name, with nothing to open.

## What the chat allows

![Waiting for the agent](/caf/standard-interface/composer-gate.webp "The agent banner attached to the composer")

**The agent isn't ready.** While the chat's agent isn't installed, is being
signed in to, or is signed out and can be signed in, the agent banner
attaches to the box, as a question does, joined to it in the banner's own
tone. Messages wait only while the chat waits for its agent
(`ChatState::WaitingForAgent`): then the box says
*Message Claude: it waits until Claude is ready*, and the user can still
write. An agent that's only signed out holds nothing back: the banner offers
to sign in, and the box is as usual. [Agents](/caf/standard-interface/agents.md)
says when the banner shows, and its words.

![The context filling up](/caf/standard-interface/composer-filling.webp "Context 86% full: the ring turns amber")

**The context ring.** The ring shows how much of the agent's context is
used, `Usage.used` of `Usage.size`, as a whole percent. Above 80% it turns to
the caution colour, and above 95% to the warning colour: strictly above,
so 80% is still calm. Its tooltip says *Context: 86% used*. A new chat,
before the agent has said, has no ring. Clicking the ring opens the usage
popover, and a dot on the ring warns of an account limit running low: see
[Usage](/caf/standard-interface/usage.md).

![An archived chat's composer](/caf/standard-interface/composer-archived.webp "Archived: the tray says so, and the box is as usual")

**Archived.** A chat stays archived (`Chat.archived`), restored or not,
until it's brought back. Sending a message brings it back: CAF unarchives
it and sends the message as to any other (`Core::send`). So the box stays
as usual, and the user can write and send. The tray says, calm, with an
archive box, *This chat is archived. Sending a message brings it back.*,
and offers **Unarchive**, plain, at its other end, which brings it back
without sending (`Core::unarchive`; a viewer's `Unarchive`, with the `act`
right). Either way the note goes at once, and the chat is an ordinary one,
its agent started when a message is sent, as for a restored chat.

A saved chat is put away as it's archived, so CAF no longer has it, and
refuses to send to it or unarchive it (`Refused::NoSuchChat`). An app that
still shows it restores it first (`Core::restore`), archived still, then
sends or unarchives: the user sees nothing of this, and never *Couldn't
send: this chat isn't open any more.* Right after it's archived, CAF may
still be writing it, and refuses to restore it (`Refused::Loaded`) until
it's done, which takes moments: the app tries again for a moment while it
does, as
[Closing a tab](/caf/standard-interface/chats.md#closing-a-tab) says for any
chat just put away.

If restoring it fails, the message stays in the box, and the tray says
*Couldn't send:* and why, in the words
[A chat's identity and lifecycle](/caf/standard-interface/chats.md#when-it-can-t-be-restored)
gives each reason a chat can't be restored, its heading made a clause,
such as *Couldn't send: this chat is open somewhere else.* or *Couldn't
send: this chat's save is damaged.* If Unarchive's restore fails, the tray
says the same, with *Couldn't unarchive:*.

While it's archived, only its settings can't be chosen, as CAF refuses to
change them (`Refused::Closed`): the control shows the model and effort,
without the bolt or the chevron, and can't be opened, as when the user
can't write. They can be chosen again once it's back. A viewer without the
`act` right sees the note without Unarchive, and the box as
[Can't write](#what-the-chat-allows) says.

![A composer the user can't write in](/caf/standard-interface/composer-blocked.webp "Watch-only: the box stays and says why")

**Can't write.** The box stays where it is, with a lock, and says why, by
the first of these that holds:

| Why | The box says |
| --- | --- |
| The viewer has no `act` right | *You can follow this chat, but not write in it.* |
| Its agent is gone, or CAF won't run it | As [A chat's identity and lifecycle](/caf/standard-interface/chats.md) says |
| Its agent can never be installed on this machine | As [Agents](/caf/standard-interface/agents.md) says |

It has no Send, Stop or settings menu. The control shows the model and
effort, without the bolt or the chevron, and can't be opened; the ring stays.
A question or the agent banner still shows, so the user knows the chat is
waiting. A question's answers show disabled for a viewer without the `act`
right. The banner's buttons follow their own rights, as
[Agents](/caf/standard-interface/agents.md) says: a viewer is offered nothing
it can't do. For the others, the banner keeps **Not now** while a message
already waits, so the user can drop it.

## Narrow

![The composer, narrow](/caf/standard-interface/composer-narrow.webp "In a side pane: the same parts, shorter words")

In a narrow pane the composer keeps every part. The placeholder keeps only
its first clause (*Message Claude*), the settings control may shorten
(*Settings*), and the *waits for this turn* note by the buttons is left out.

## Keys

**Enter** sends. **Shift+Enter** starts a new line. While an input method is
composing, Enter does nothing, so a user typing in Japanese, say, never sends
half a word.

## What CAF tells the app

| What the composer shows | Where it comes from |
| --- | --- |
| What can be sent | Text only, `Part::Text`: there are no attachments yet. |
| A message waiting | A message sent during a turn, or while the chat opens or waits for its agent, is queued by CAF (`TurnLife::Waiting`), and goes when it can. `Core::stop` drops it. |
| Why a message couldn't be sent | The `Refused` CAF answers with, or the link to the app dropping. |
| The settings menu | `Setting.form` for each setting the agent offers: `Choices` or a `Switch`. Before a chat opens, `AgentStatus.settings`. |
| A change not applied yet | `settings.chosen` differing from `current`, when `offered` holds the setting and its `current` is known. |
| The model divider | `Turn.model` differing from the turn before. |
| The context ring | `Usage.used` and `Usage.size`. |
| Whether the user may write | The viewer's `act` right, and the chat's state. |
| Archived | `Chat.archived`, by `Change::Archived`; `Refused::Closed` for a setting chosen meanwhile. |
| **Unarchive** | `Core::unarchive`, or a viewer's `Unarchive`, with the `act` right: `Chat.archived` goes back to none. `Core::send` unarchives a chat too, then sends. |
| Why the settings couldn't be learned | `AgentStatus.settings`'s `Failed`, a `LearnFailure`; the system's words in `CouldNotStart.error`, the agent's in `Refused.message`. |
| **Learn them now** | The viewer's `agents` right; `Core::learn_settings`. |
| The agent banner | The agent's status, as [Agents](/caf/standard-interface/agents.md) describes. |

---

# The Transcript

_CAF / Standard Interface_

> What a chat shows above the composer, as every CAF app should draw it. A finished turn as one summary line that opens into a timeline of its steps, a running turn live, tool calls with their diffs, output and who allowed them, questions attached to the composer, failures and their remedies, CAF's notes, a chat that lost its agent, and history from the agent's own record, with the words for each and what CAF tells the app.

The transcript is the chat itself: everything the user sent and everything
the agent did, in order, above the composer. It's built from CAF's record
of the chat, a list of turns, each a list of items (see
[Chats, turns, and items](/caf/concepts/chats-turns-and-items.md)).

[See the transcript live](/attachments/caf-si-transcript/transcript.html), every state, in
dark and light.

![A finished turn: the message, one summary line, and the answer](/caf/standard-interface/transcript-finished.webp "A finished turn: its message, one line of chips for the work, and the answer in full")

**Required, all of it**, but for the time dividers, which are the app's, and
what's marked **Later**. The transcript is inside the chat, and a user
moving between CAF apps should find it the same in each.

## Its parts

A turn is drawn top to bottom, in one column:

| Part | Where | What it is |
| --- | --- | --- |
| The message | Right, in a bubble | What the user sent. A turn the agent started by itself has none (see below). |
| The summary line | Under the message | What the work was, as a line of chips, led by how long it took. Clicking it opens the timeline. A turn with no steps has none. |
| The timeline | In place of the summary's chips, once opened | Every step in order, on a rail. |
| The answer | Under the summary | The agent's last words, in full. |
| What went wrong | Under the answer | A failure, in CAF's words, with its remedy. |
| The turn's line | At the foot of the turn | The model, how long the agent worked, when the message was sent, and how the turn ended if not finished. All muted. |

Between turns sit dividers (the time, a new model, history from the agent's
own record) and what CAF says about the chat. Anything waiting on the user
attaches to the top of the composer, not to the transcript.

Markdown in the agent's words is drawn as Markdown. A step's title and a
question's are shown as plain text, as given.

**Times.** The time on a turn's line is when the user sent the message
(the start of `Turn.window`), so a message that waited for the turn before
it shows when it was sent. How long the agent worked counts from the start
of its first item from the agent (its words, thinking or a tool, never one
of CAF's notes) to the turn's end, so the wait isn't counted as work. A turn
with no items from the agent shows no time taken. Where the app doesn't keep
thinking (`Host.shows.thinking`), the time the agent spent thinking before
its first words or tool isn't counted.

## Turns

**A finished turn** is its message, one summary line and the answer, as in
the picture at the top. The summary line is led by *Worked 42s*, then one
chip for each kind of step, counted:

- *Thought 8s* for thinking. Each stretch of thinking is listed, not
  summed: *Thought 8s + 2s*.
- *Read 1 file*, *Searched 1 time*, *Edited 2 files +7 −1*, *Fetched 1 page*,
  *Deleted 1 file*, *Moved 1 file*, by the tool's kind, with the plural as it
  should be. The edit chip adds up its edits' diffs: *+7* lines added and
  *−1* removed. A refused edit's diff never happened, so it isn't counted. A tool of kind `Think` or `Other` is counted as *Used 1 tool*.
- A single command is named by its title, here
  *cargo test -p caf-core config*, with a tick, or a cross in the warning
  colour if it failed. Two or more are counted: *Ran 2 commands*.
- *? 1 item this app can't show*, if the turn has any.
- Then *Show steps*, muted, with a chevron.

A chip with a step that failed or was refused is in the warning colour, so
it's seen without opening the turn. A cancelled step isn't a failure: its
chip stays calm. In history, where the times aren't known, the line
is led by *Work* alone.

The answer is the turn's last words from the agent (`ItemKind::Words`),
once the turn has finished, if nothing but CAF's notes comes after them.
Anything else the agent said along the way is a step.

![The same turn opened](/caf/standard-interface/transcript-finished-open.webp "Opened: every step in order, by its title, an edit open to its diff")

**Opened.** Clicking anywhere on the summary line opens the timeline in its
place, and the line's last words become *Hide steps*. Clicking again folds
it. Each step is one line on a rail, with its kind's icon:

- Thinking: *Thought for 8s*, muted and in italics. It opens to the
  thinking itself.
- A tool call: its title, exactly as given, such as
  *Read crates/core/src/config.rs* or *cargo test -p caf-core config*, with
  how long it ran on the right. CAF writes the title for its own tools, and
  the agent writes it for the rest; either way, the app draws the call's
  title and never rewords it. Only the icon comes from its kind. It opens to
  what the tool gave back (see [A tool call, opened](#a-tool-call-opened)).
- What the agent said along the way, muted, in full.

An edit is open already, to its diff: an edit is what the user most often
wants to check. Every other step opens when clicked.

![A turn running](/caf/standard-interface/transcript-running.webp "Running: the timeline is always open, the command running now at its foot, its output coming in")

**Running.** A running turn's timeline is always open, and can't be folded,
so the user can always see what the agent is doing. The summary line says
*Working 31s*, with a spinner in the accent, and has no chips; before the
agent's first item it says *Working*, with no time. The step running now has a
spinning dot in the accent. The turn's line says
*Opus 5.5 · 31s so far · 14:32 · Working*. The composer's round button is
Stop (see [The composer](/caf/standard-interface/composer.md)).

A running command is open, and shows its output as it comes, with a caret
in the accent at its end, so the user can watch a build or a test run
without opening anything. Other steps show what they've given back so far,
which for many tools is nothing until they end.

Once Stop is pressed, and until the agent confirms, the summary says
*Stopping…* in place of *Working* (not pictured).

![A turn stopped after a step failed](/caf/standard-interface/transcript-stopped.webp "Stopped: the failed step's chip is red, and a message that was waiting is stopped too")

**Stopped.** A turn the user stopped folds like a finished one, and its line
ends *Stopped*, muted. A step that failed makes its chip red: here,
*cargo build -p caf-core* with a cross. Opened, a failed step shows its
output. A step still waiting or running when the user stopped the turn is
*Cancelled*, muted; one a turn ended under any other way, such as a failure
or the app closing, is *Failed*.

**A message that never went.** Stop also stops the messages waiting for the
turn, and a message that waited for an agent that wasn't installed is
stopped too. Each stays in the transcript as a turn of its own: its message,
no summary line, and a line of *14:32 · Stopped*. CAF doesn't say whether a
stopped turn reached the agent, so the app doesn't either.

![A turn the agent started by itself](/caf/standard-interface/transcript-on-own.webp "Claude, on its own: no message, the rest as any turn")

**The agent, on its own.** An agent can start a turn by itself, such as when
a command it left running finishes. It has no message: in its place is the
agent's mark and *Claude, on its own*, muted. The rest is drawn as any turn.
CAF doesn't say why the agent started it, so neither does the app. (A
command left running by CAF's own Bash is different: CAF tells the agent
when it ends, in a turn of CAF's own, as
[Background jobs](#background-jobs) says.) Such a
turn never fails, so it never has a remedy: it ends finished, stopped, or
cut off.

**Cut off.** A turn that ended before it finished, without failing or being
stopped, ends *Cut off before it finished*, muted (see the last picture on
this page). That happens when the app shuts down during it, when the chat is
put away during it (`Core::put_away`), or when the app stopped unexpectedly
and the chat was restored.

A message waiting to be sent (CAF queues it while a turn runs or the chat
opens) isn't drawn in the transcript: it sits on the composer's tray until it
goes. A turn CAF starts with a notice, such as of a background job's end,
is drawn as the [Background jobs](#background-jobs) section says; one the
app starts with its own notice (`Core::notify`) is headed *A notice from
the app*, muted, with its words. **Later:** a turn sent by another chat's
agent.

## Tool calls

A tool call is a step on the timeline (see
[Tool calls](/caf/concepts/tool-calls.md) for what CAF records of one). Its
line is its kind's icon, its title, and on the right how long it ran or
where it is.

**Its title** is drawn as given, never made up by the app. For CAF's own
tools (see [CAF's own tools](/caf/concepts/cafs-own-tools.md)) CAF writes it,
the same for every agent, with a path inside the chat's folder relative to
it, and any other in full:

| Tool | Its title |
| --- | --- |
| Read | *Read src/config.rs* |
| Edit | *Edit src/config.rs* |
| Write | *Write docs/notes.md* |
| Bash | The command's first line, as the agent wrote it: *cargo test -p caf-core*, with *…* after it if it has more |
| TaskStop | *Stop task 2*, its icon a square |

Where it is, by its status:

| Status | Its dot | On the right | Role |
| --- | --- | --- | --- |
| `Pending` | Its kind's icon | *Waiting to start* | Calm |
| `Asking` | Its kind's icon, in the accent | *Waiting for you ↓* | Accent |
| `Running` | A spinner, in the accent | How long so far | Accent |
| `Done` | Its kind's icon, muted | How long it ran | Muted |
| `Failed` | A cross, in the warning colour | How long it ran | Warning |
| `Refused` | A cross, in the warning colour | *Refused* | Warning |
| `Cancelled` | Its kind's icon, muted | *Cancelled* | Muted |

*Cancelled* is muted, not a warning: the user stopped it, or the agent
did, so nothing went wrong. *Refused* is a warning, as a failure is: the
agent wanted to do it and couldn't, which the user should see without
looking for it, even when it was their own answer.

![A turn with a refused step](/caf/standard-interface/transcript-refused.webp "A step the policy refused, in the warning colour, opened to who refused it and why; a command the user allowed; and one cancelled when the turn was stopped")

**Who decided.** A call that needed permission says, first thing when
opened, who allowed or refused it, muted, in one line:

| `Decision` | It says |
| --- | --- |
| `Allowed(User)` | *Allowed by you* |
| `Allowed(Policy)` | *Allowed by the policy: reads inside the project are fine*, with the policy's reason, or *Allowed by the policy* if it gave none |
| `Refused(User)` | *Refused by you* |
| `Refused(Policy)` | *Refused by the policy: writes outside the project folder*, or *Refused by the policy* |
| `NotAsked`, `Undecided`, `NotRecorded` | Nothing |

*You* is whoever answered the question in this app. A refused call never
ran: under that line is only what it would have done, such as the diff of
an edit CAF worked out before asking, and why, if the agent said. It's
headed *What it would have done (never ran)*, muted, in place of nothing,
so it's never read as something that happened.

### A tool call, opened

A call opens to what it gave back, in order, each piece drawn by its kind.
Everything an agent sends is drawn as text: never as markup, never run.

- **Text**, such as a file read, in a monospace font. If CAF kept only its
  start, under it, muted: *Kept 64 KB of 1.2 MB*.
- **A diff**: the file's path, *New file* if there was none before, and
  *+3 −1* on the right, the lines added and removed. Then its hunks, as
  CAF worked them out, each line with its numbers before and after, added
  lines marked *+* on a green tint and removed ones *−* on a red one, and
  a gap between hunks. If CAF kept only some hunks, after them, muted:
  *and 2 more hunks*. The app draws the hunks as they are, and never
  compares texts itself.
- **A command's output**: its lines in a monospace font, in the colours
  the command gave them. Only its colours (text and background) and
  bold, dim, italic, underline, strikethrough and inverse are drawn; any
  other code a terminal would act on shows as it is, such as `^[[2K`,
  never acted on. Text whose background is its own colour keeps the
  app's background, so it can't hide itself. If CAF kept only the last lines, above them,
  muted: *120 earlier lines not kept*. While it runs, a caret in the
  accent ends it, and lines come and change as CAF sends them. Once it
  ends, under it: *Exited with code 0*, muted, or *Exited with code 101*,
  *Killed by signal 9*, in the warning colour; *Ended, without saying
  how* if the agent didn't say, muted. **Suggested:** an output of
  thousands of lines draws only its last 2,000, with *Show 500 earlier
  lines* above them, so the page keeps up as it grows.
- **An image**, drawn, as wide as the column at most. One too big for CAF
  to keep says *An image too big to keep (3.4 MB)*, muted, in its place.
  Only an image is drawn as one: anything else claiming to be, such as a
  page, is named by its type and never shown. One whose data can't be read
  as a picture says *An image this app couldn't read*.
- **A link**: a web address (`http` or `https`) is a link, in the Link
  colour, by its name, which opens in a new tab, and beside it, muted,
  the address it goes to, as the browser reads it, so a name can't say
  one place and go to another. A host spelled in another script is shown
  as the browser goes to it (`xn--pple-43d.com`). A link with no name,
  or a name of only spaces, is shown by its address. Any other address,
  such as a file's, is shown as text, its name and then the address, and
  never followed. Nothing an agent sends ever becomes a `javascript:`
  link.
- **A piece CAF couldn't read**, a dashed box:
  *Something Claude sent that this app can't show*. If CAF kept only the
  start of it, that says so, muted: *Kept 64 KB of 90 KB*.

**Suggested:** under what it gave back, the files the call is about, as
*src/main.rs:42*, each opening the file where the app can; and what the
call was given (its input), folded away. When CAF kept only the start of
the input, it says *Kept 64 KB of 200 KB* under it.

### Background jobs

![Two commands running in the background](/caf/standard-interface/transcript-background.webp "A finished turn whose two commands still run: each a chip of its own, and opened, each step marked Background, its output coming in")

A call to one of CAF's tools can go on after the agent was answered: a
command the agent ran in the background, or one that ran past its
timeout. CAF calls it a **job**, and numbers it in the chat: task 1,
task 2. The agent got its answer, so the turn goes on, and may finish,
while the job runs.

- **Running, it's marked *Background*:** a small chip in the accent after
  its title, as it's happening now. Its dot is a spinner and its output
  comes in, as any running step's. Its turn can be finished, stopped or
  far up the transcript: the step stays running there until the job ends,
  so the app never draws it as done because its turn is.
- **Folded,** its turn's summary line gives each job still running a chip
  of its own, in the accent: a spinner, its title and *Background*. A job
  that has ended is counted with the turn's other steps, as any is.
- **Stop doesn't stop it.** The user's Stop stops the turn, not the work
  it left in the background, as in Claude Code. A job ends by itself, or
  when the agent stops it with TaskStop, or when the chat is closed or
  deleted (*Cancelled*), or put away, or the app shuts down (*Failed*: a
  restored chat has no jobs).
- **When it ends,** it's drawn as any step that ended: *Done*, *Failed*
  or *Cancelled*, its output ended with its exit. The chip goes. Opened,
  the step may say, muted, that it ran in the background as task 2.

![A job's end, told by CAF, then one stopped](/caf/standard-interface/transcript-job-ended.webp "CAF's notice of the tests' end starts a turn of CAF's own; Claude reads the output and answers; later its TaskStop is a step, Stop task 1")

**CAF tells the agent when a job ends,** in a turn of its own, sent as a
message is: at once if nothing runs, or else once the running turn ends.
After the user's Stop, CAF holds them: none comes right after a Stop, and
each held one appears, as a turn of its own, just before the user's next
message (see [Serving tools](/caf/concepts/serving-tools.md#background-jobs)).
In place of a message, the turn starts with the CAF badge and what CAF
told the agent, in words: the notice's own summary, *Told Claude:
Background command "cargo test --test integration" completed (exit code
0)* (or *failed*), with `&amp;`, `&lt;` and `&gt;`
read back as `&`, `<` and `>`. It's CAF's voice, not the agent's nor the user's, so it never
looks like something the user sent. The rest of the turn is the agent's
answer, drawn as any. The agent was given the path of a file holding the
job's whole output too; the app needn't show it.

**TaskStop is a step.** When the agent stops one of its jobs, its call is a
step like any other, titled *Stop task 1*, and the job's own step, wherever
it is, ends *Cancelled*. TaskStop never asks: it can only stop a job its own
chat started. Folded, it's counted as *Stopped 1 task*.

## Asking

![A permission question, attached to the composer](/caf/standard-interface/transcript-permission.webp "CAF asks about a call to its own Bash: in its own voice, with the command, and its own two answers; the step points to it")

**Asking permission.** When the agent wants to do something that needs the
user's say, the question attaches to the top of the composer, joined to it
with an edge in the accent: the turn can't go on until it's answered.

Whose question it is depends on whose tool the call is:

- **One of CAF's own tools** (`Origin::Caf`: Read, Edit, Write, Bash). CAF
  asks, in its own voice, with the CAF badge. It says what the agent wants
  to do in CAF's words, from what the call does (its `Action`), then what
  it's about, as plain text, from the title CAF wrote for the call: for a
  file, the title without its *Read*, *Edit* or *Write* (the path, from
  the chat's folder when it's inside it); for a command, the title as it
  is (its first line, with *…* after it if it has more, capped). Never the
  whole title, whose verb would say it twice:
  *Claude wants to run a command: rm -rf target*,
  *Claude wants to change a file: src/config.rs*, *Claude wants to read a
  file: /etc/hosts*, *Claude wants to write a file: notes.md*. Its answers are CAF's
  own two, *Allow* and *Refuse*. Its edge stays in the accent, unlike CAF's
  question about a chat slow to open: like any permission question, it
  holds up the turn.
- **Any other tool.** The agent asks: *Claude asks permission:* and then
  the agent's own title for what it wants to do, as plain text, with the
  agent's own answers.

Once CAF has seen the call it's about (`Permission.tool`), the question
shows what the user is being asked to allow, under its title: the command
it would run, in a monospace font, with the folder it runs in under it,
muted; or the change it would make, as a diff, drawn as an opened step
draws one. A question asked before CAF has seen its call shows its title
alone, and gains the rest when the call arrives (CAF's own questions always
have their call). Under that are the answers, labelled as their asker
labels them, *Allow* and *Refuse* for CAF's, or for the agent's, such as
*Allow*, *Always allow* and *Reject*, all alike: none is chosen or focused
beforehand, and Enter answers nothing. On the right, muted: *Stop cancels this and stops the turn*.

The step it's about stays in the timeline, its dot in the accent, and says
*Waiting for you ↓* on the right (`ToolStatus::Asking`). The agent may ask
before CAF has seen the step, so the question never depends on it.

Answering it carries on the turn. Stop answers it as cancelled, and stops
the turn.

**Only one thing attaches to the composer at a time.** If several questions
wait, the oldest attaches, and the next takes its place once it's answered.
A question comes before the agent banner: when both apply, the question
attaches, and the banner returns once it's answered. Messages waiting on the
tray sit above whatever is attached.

## Failing

A failed turn folds like any other, and under it is what went wrong, in a
box in the warning colour: the CAF badge and CAF's sentence; what the agent
said about it, if anything, quoted apart; and the remedy, if there is one.
The turn's line ends *Failed*, in the warning colour.

![A turn that hit a usage limit](/caf/standard-interface/transcript-usage-limit.webp "CAF's sentence, the agent's words quoted apart, and Send again")

**What the agent said** is introduced as *Claude said:*, in quotation marks,
muted, with a rule down its left. It's the agent's words, never CAF's
advice, and never presented as CAF's.

**Send again** (`Remedy::SendAgain`) is the accent button, with a circling
arrow. It sends the same message again, as a new turn.

![A turn that needed a sign-in](/caf/standard-interface/transcript-sign-in.webp "Sign in, and Send again beside it, quiet")

**Sign in** (`Remedy::SignIn`) is the accent button. It signs in with CAF's
own command for the agent, never one the agent suggested, and doesn't send
the message again. So, as the one exception to offering only CAF's remedy,
**Send again** sits beside it, quiet, for once the user has signed in: CAF
never sends it again by itself.

CAF gives `SignIn` only where it can sign in to the agent now. When the
reason is `SignInNeeded` but the remedy isn't `SignIn`, the box says
*Sign in to Claude, then send again.* in place of the button, with any
remedy CAF gave instead.

![A turn whose setting couldn't be applied](/caf/standard-interface/transcript-setting.webp "CAF says the choice was dropped, and the message wasn't sent")

**A setting not applied.** When a setting chosen for the chat can't be
applied before a message goes, such as a model the agent no longer offers,
CAF doesn't send the message. CAF's note above it says which choice was
dropped, and the failure says the message wasn't sent, and that sending it
again uses what applies now. Such a turn never reached the agent, so its
line has no model and no time taken.

What CAF says for each reason, with the agent's name in place of *Claude*:

| Reason | CAF says |
| --- | --- |
| `TooLong` | The answer hit the model's length limit. |
| `TooManySteps` | Claude hit its limit of steps for one turn. |
| `Refused` | The model refused. The message and everything after it are gone from Claude's memory. |
| `SignInNeeded` | Claude wants you to sign in. |
| `AccessDenied` | The account or its credentials can't be used: signing in again doesn't fix it. |
| `BadRequest` | Claude's provider refused the request as it stood. Sending it again won't help. |
| `UsageLimit` | Claude hit a usage limit. |
| `ProviderError` | Claude's provider was overloaded or failed. |
| `AgentStopped` | Claude stopped while working on it. |
| `DidNotStop` | Claude didn't stop when asked, so CAF ended the turn and reconnected to Claude. |
| `BadAnswer` | Claude's answer made no sense. |
| `SettingNotApplied` | A setting chosen for this chat, such as a model, couldn't be applied, so CAF didn't send the message. The app's default, or else Claude's own, applies now: sending it again uses that. |
| `Other` | Claude reported an error. |

A reason the app doesn't know yet (a later CAF may add one) is shown as
*It failed, for a reason this app doesn't know.* Apart from Send again
beside Sign in, an app offers only the remedy CAF gives, never one of its
own. **Later:** *Start a new chat*, for `Remedy::NewChat`.

## Who may act

A person watching a chat may not have every right (see
[Viewers](/caf/concepts/viewers.md)). What they can't do is never offered
only to be refused:

- Without the `act` right: no Send again, and a question still attaches, so
  they can see what's waiting, but its answers are disabled, as are
  *Keep waiting*, *Try again* and *Stop* when a chat is slow to open.
- Without the `agents` right: no Sign in. The box says
  *Sign in to Claude, then send again.* in its place, and Send again stays,
  given `act`.

## CAF and the chat

![CAF's notes](/caf/standard-interface/transcript-notes.webp "CAF speaks with its badge: between turns, and inside one")

**CAF's notes.** CAF speaks in its own voice, never as the agent's: a box
with the CAF badge. Between turns, it says what happened to the chat; inside
a turn, what happened during it. A note is never folded away: inside a
folded turn it shows under the summary line, and in an opened one, in its
place on the timeline.

A note that the agent remembers nothing from before is in the caution colour,
with a warning sign, because the user's context is gone and they'll need to
give it again. The others are calm, with an *i*, muted. The words, with the
agent's name in place of *Claude*:

| Note | Tone | CAF says |
| --- | --- | --- |
| `SessionGone` | Caution | Claude no longer had this conversation, so a new one was started: it remembers nothing from before. |
| `CannotContinue` | Caution | Claude can't carry on earlier conversations, so a new one was started: it remembers nothing from before. |
| `SessionStuck` | Caution | Claude's conversation was stuck and couldn't be closed, so a new one was started: it remembers nothing from before. |
| `NotInstalled` | Calm | Claude isn't installed, so the message that waited for it was stopped. |
| `InstallFailed` | Calm | Claude's install failed, so the message that waited for it was stopped. |
| `SignedIn` | Calm | You signed in to Claude: send the message again to try it now. |
| `AgentChanged` | Calm | Claude changed by itself to the model Sonnet 5.5, and this chat follows it. |
| `NotOffered` | Calm | Claude doesn't offer the model `claude-opus-4-8`, so that choice was dropped: the app's default, or else Claude's own, applies. |
| `NotApplied` | Calm | Claude refused the model Opus 4.8, so that choice was dropped: the app's default, or else Claude's own, applies. |

A note about a setting names the choice by the agent's name for it, as the
agent last said it, which CAF keeps with the note (its `name`): *the model
Sonnet 5.5*. A choice the agent never named, such as a model it never
offered, has none, and is named by the agent's own id, in a monospace font,
as CAF keeps it: *the model `claude-opus-4-8`*. The name is kept with the
note, so it reads the same when the agent no longer offers the choice, and
in a restored chat. A switch that's on or off is named *fast mode on* or
*fast mode off*; one the agent doesn't offer is named *fast mode* alone:
*Claude doesn't offer fast mode, so that choice was dropped…*

When the agent changes a setting by itself, the composer follows it: after
the note here, it shows *Sonnet 5.5*. The turn's line still shows the model
it was sent on.

![A chat whose agent stopped](/caf/standard-interface/transcript-lost.webp "The agent stopped: why, what the next message does, and its last words")

**Lost.** Whenever a chat loses its agent, between turns or during one (the
turn then fails, and the chat is lost), a box in the caution colour at the
foot of the transcript says why, in bold, and under it, muted, what the
user's next message will do. Where the agent left its last lines of error
output, they're under that, in a monospace font. The box goes once a message
starts opening the chat again. It's the app's own frame for the chat's
state, not something CAF says, so it has no CAF badge.

While the agent banner shows, it stands in for this box, which isn't drawn:
a chat lost after the user chose *Not now* in the banner
(`Lost { reason: Stopped }`) has what to do next in the banner, and why in
CAF's note (see [Agents](/caf/standard-interface/agents.md)).

| Why | It says | Under it |
| --- | --- | --- |
| `CouldNotStart` | Claude couldn't be started. | Your next message tries to start it again. And what the system said. |
| `AgentStopped` | Claude stopped. | Your next message starts it again, and carries on this chat where Claude can. And its last lines. |
| `Restarted` | Claude was restarted. | Your next message carries on this chat where Claude can. |
| `SignInNeeded` | Claude wants you to sign in first. | Sign in, then send a message to carry on. |
| `Refused` | Claude refused to open this chat. | Your next message tries again. And what Claude said, quoted apart. |
| `Stopped` | You stopped it opening. | Your next message tries again. |
| `InUse` | Another chat already has this conversation open. | Your next message tries again. |
| `Incompatible` | One of the sentences below. | Nothing, but for `BadAnswer`. |
| `ShutDown` | The app closed while this chat was open. | Nothing. |

When Claude can't do what the chat needs (`Lost::Incompatible`), the box says
why:

| `Incompatible` | It says | Under it |
| --- | --- | --- |
| `Protocol` | This version of Claude can't talk to this app. | Nothing. |
| `HttpMcp` | Claude can't reach one of this chat's tools the way it's connected, so this chat can't run. | Nothing. |
| `BadAnswer` | Claude's answer made no sense. | Your next message tries again. |
| `OwnTools` | This isn't the Claude this app knows, so the app can't control its tools, and won't run it. | Nothing. |

![Slow to open](/caf/standard-interface/transcript-slow.webp "CAF's question, attached to the composer, with the message waiting on the tray above it")

**While a chat opens,** the transcript shows nothing new: the message
waits on the composer's tray, and the round button is Stop.

**Slow to open.** If a chat takes long to open, CAF asks the user whether to
keep waiting. It's CAF's own question, never framed as the agent's, so it
attaches to the composer calm, with the CAF badge, not in the accent:
*Claude is taking a while to open this chat. It may be busy, or stuck.* If
the agent hasn't answered at all, it says
*Claude is taking a while to start: it hasn't answered at all yet.* The
answers are **Keep waiting** and **Try again**, as buttons, then **Stop**,
quiet. Escape keeps waiting, as dismissing it does. Stop gives up, and the
waiting message ends as stopped. The message waiting for the chat to open
sits on the tray above it, headed *Waiting for Claude to open · 1* and
*Stop drops it too*; the box says *Message Claude: it waits for Claude to
open*, and the round button is Stop, as
[the composer](/caf/standard-interface/composer.md) draws it.

## History and dividers

![History from the agent's own record](/caf/standard-interface/transcript-history.webp "Turns the agent replayed, marked and muted, with no times. Later: the compaction line")

**The agent's own history.** A chat can carry on a conversation the agent
already had, such as one started in the agent's own app. What the agent
replays of it comes in as history CAF didn't see happen. It's headed by a
muted divider, *From Claude's own history*, with a circling arrow, and its
turns are muted too, with no times, no turn line and no model, since CAF
doesn't know them. They fold and open as any turn. A chat CAF restores from
its own save has its whole record already, and shows none of this.

**What the app can't show.** An item the agent sent that CAF couldn't read
is kept as it came, and drawn as a dashed box:
*Something Claude sent that this app can't show.* One of the app's own items
that this version of the app can't read shows the summary it had, if any,
or *An item of the app's that this version can't read*. The app draws its
own items (`ItemKind::App`) as it likes, in their place.

**Later: compaction.** Where the agent summarised its context to make room,
a muted line inside the turn says *Claude compacted its context: it has a
summary of everything before this*. CAF doesn't record compaction yet.

![A new model, and a turn cut off](/caf/standard-interface/transcript-model.webp "The model divider, then a turn cut off before it finished")

**A new model.** A divider marks where the model changed: the agent's mark,
the new model, and *from* the old one, muted, as on the composer page. The
app draws it wherever a turn's model differs from the turn before's.

**Time. Up to the app.** A divider with the time, such as *Today 14:32*,
where a while has passed between turns. When, and how it's worded, is the
app's.

## Colour

- **Accent:** what's happening now (the *Working* spinner, the running
  step's dot, the caret of a command's output as it runs, a job's
  *Background* chip), the edge of a
  question waiting on the user and the dot of the step it's about, and the
  remedy button.
- **Warning:** a failure's box, a failed or refused step's dot and chip,
  *Failed* on the turn's line, and a command that exited with an error or
  was killed.
- **Caution:** a lost chat, and a note that the agent remembers nothing.
- **CAF's voice:** the CAF badge, on notes, failures, CAF's own
  questions, permission questions about its own tools included, and its
  notice of a job's end.
- **Link:** a web link a call gave back.
- **Muted:** times, counts, thinking, what the agent said along the way,
  steps done or cancelled, who allowed a step, what was cut, the turn's
  line, the dividers, the icons of calm notes, and the agent's own history.

A step waiting to start is calm. A diff's added and removed lines are
tinted green and red, and its counts drawn in those colours: they say what
changed, not that anything went right or wrong, so they're no role's.

Everything else is calm.

## What CAF tells the app

| What the transcript shows | Where it comes from |
| --- | --- |
| The turns, in order | `Chat.turns`, each a `Turn`, in the order of the list. History and CAF's notes can be inserted before a waiting turn (`Change::TurnInserted`). |
| The message | `Turn.starter`: `Starter::User` holds the `UserMessage`. `Starter::Agent` is a turn the agent started by itself, and `Starter::Caf` one of CAF's notes. `Starter::Notice` holds a notice's text: CAF's own of a job's end is `<task-notification>…</task-notification>`, whose `<summary>` is what's shown; the app's is anything else. |
| How the turn ended | `Turn.life`: `TurnLife::Running`, `Stopping`, `Finished`, `Stopped`, `Failed` or `CutOff`. A `Waiting` one is on the composer's tray. |
| When it was sent | The start of `Turn.window`. |
| How long the agent worked | From the start of the first `Words`, `Thinking` or `Tool` item's `Item.window` to the end of `Turn.window`. |
| The turn's model | `Turn.model`, as the agent said when it was sent. |
| The steps | `Turn.items`: `ItemKind::Words`, `Thinking`, `Tool`, `Note`, `App` and `Unknown`. Thinking is kept only if the app asks for it (`Host.shows.thinking`). |
| A tool's line | `ToolCall.title`, as given; its `kind` (`ToolKind`) for the icon and the chip; its `status` (`ToolStatus::Pending`, `Asking`, `Running`, `Done`, `Failed`, `Refused` or `Cancelled`); and its `Item.window`. |
| Background | `ToolCall.job`, the job's number (`JobId`), set once the call went on after the agent was answered (`ToolEvent::Detached`). It's *Background* while `status` is `Running`. A TaskStop's `action` is `Action::Stop`, with the `job`. |
| Who decided | `ToolCall.decision`: `Decision::Allowed` or `Refused`, each with its `DecidedBy` (`User`, or `Policy` with its `reason`). |
| A tool, opened | `ToolCall.result`, a list of `Piece`s: `Text` (its `cut`, a `Cut`), `Diff`, `Output`, `Image`, `Link` and `Unknown` (its `cut`: if CAF kept only the start of its data, `raw` is the start of its JSON, as a string). Then `ToolCall.locations` (and `locations_cut`), and `ToolCall.input` (and `input_cut`). |
| An edit's diff and counts | A `Piece::Diff`: its `path`, `new_file`, `added`, `removed`, its `hunks`, each a list of `DiffLine`s (`change`, `old`, `new`, `text`), and `more`, the hunks not kept. |
| A command's output | A `Piece::Output`: its `lines`, with their SGR codes; `dropped`, the lines before them not kept; and its `ending` (`Ending::Exited`, with an `Exit`, or `Unknown`), `None` while it runs. |
| A command's output as it runs | `Change::OutputChanged`: the lines from `from` on replaced by `lines`, then `dropped` more gone from the top. |
| Compaction | **Later:** `ItemKind::Compacted`. |
| A question | `Chat.questions`, oldest first: `QuestionKind::Permission` (its `title`, `options` and the `tool` it's about, the `Item` whose `ToolCall` it shows, once there is one; CAF's own question when that call's `origin` is `Origin::Caf`) or `SlowToOpen` (`adapter_answered`). Answered with `Core::answer`, or a viewer's `FromViewer::Answer`. |
| Stop | `Core::stop`, or `FromViewer::Stop`: it answers the agent's questions as cancelled, and stops the waiting messages. |
| A failure | `TurnLife::Failed(Failure)`: its `reason` (`FailureReason`), `agent_said`, and `remedy` (`Remedy::SendAgain` or `SignIn`). |
| Send again | Sending the turn's message again: `Core::send`, or `FromViewer::Send`. |
| Sign in | `Core::sign_in`, or a viewer's `FromViewer::Agent` with `AgentAction::SignIn`. |
| Who may act | The viewer's `Rights`: `act` to send, stop and answer; `agents` to sign in. |
| A note | `ItemKind::Note`, a `Note`. A setting's (`AgentChanged`, `NotOffered`, `NotApplied`) holds the `choice`, and the agent's `name` for it, if it said one. |
| A lost chat | `ChatState::Lost`, with its `Lost` reason, and `Incompatible`'s. |
| History | `Turn.imported`, from a chat opened with `SessionChoice::Continue`. |
| The model divider | `Turn.model` differing from the turn before's. |

---

# Agents

_CAF / Standard Interface_

> Installing an agent and signing in to it, as every CAF app should show it. The agent banner attached to the composer, every install and sign-in state with its words, what each action does and what CAF may refuse, the agents panel, what a viewer without the agents right sees, and what CAF tells the app.

Before a chat can go on, its agent may need installing, or signing in to.
The agent banner says so, in the chat, and offers what to do. The agents
panel shows every agent at once, and is where the user signs out.

An agent's install and sign-in are the agent's, not a chat's: every chat
with Claude shares one install and one sign-in. So every chat with Claude
shows the same banner, and it changes in all of them at once.

[See the agents live](/attachments/caf-si-agents/agents.html), every state, in dark and
light.

![Claude not installed: the banner attached to the composer, with a message waiting](/caf/standard-interface/agents-missing.webp "The agent isn't installed: the banner offers Install, and the message waits")

**Required:** the banner, when it shows, its states, its words and its
actions, since they're inside the chat; and what each row of the agents
panel says and offers. **Up to the app:** where the agents panel is, and
how it's opened.

## Its parts

The banner attaches to the top of the composer, as a question does, and the
box is joined to it in the banner's tone. Whatever needs the user is then
in one place, just above where they write. See
[the composer](/caf/standard-interface/composer.md#what-the-chat-allows).

| Part | Where | What it is |
| --- | --- | --- |
| The mark | Left of the first line | The agent's mark; a spinner, in the accent, while CAF finds something out (whether it's installed, the sign-in's link); a tick once it's signed in. |
| What's needed | The first line | What stands in the way, in one sentence. Its subject is bold: all of it when it's short (*Claude isn't installed yet.*), or the part before the colon (***Couldn't install Claude:*** *the disk is full.*). |
| What happens | Under it, muted | What it costs, whether messages wait, and what to do next. |
| What CAF said | Under that, small and muted, in a monospace font | Only where CAF passes on words not its own, such as the installer's. |
| Progress | Under that, while installing | A bar in the accent, and how much is done. |
| The steps | Under that, while signing in | Numbered: the page to open, a code to type or paste, and that it ends by itself. |
| The actions | At the foot | In this order: at most one primary button, in the accent; **Stop**, plain; **Not now**, quiet. |

**Its tone** follows the state, and the box takes the same edge:

- **Accent** while it waits on the user: the agent isn't installed, it's
  signed out, or a sign-in waits for them.
- **Calm**, with no role colour, while CAF does the work (checking,
  installing, starting a sign-in), once it's done, and for a viewer that
  can do nothing about it.
- **Warning** when it went wrong, or can't go on: a failed install, or a
  machine that can't install the agent.

## When it shows

The banner follows the agent's status, not the chat's state. It shows in
every chat with the agent but an archived one (CAF's `Closed`), whether
the chat is open, idle or lost, while the first of these holds:

1. **The agent isn't installed.** It's one CAF installs, and its install
   (`AgentStatus.install`) is anything but `Installed`. (An agent the app
   starts itself is `Host`, and never needs installing.)
2. **A sign-in to it is under way** (`SignInState::SigningIn`).
3. **It's signed out** (`SignInState::SignedOut`), and CAF can sign in to it
   now (`can_sign_in`).

Once none holds, it goes, but for a moment after a sign-in, as
[Signed in](#signing-in) says.

**A question comes first.** When a question waits on the user as well, the
question attaches to the composer instead, and the banner comes back once
it's answered. Only one thing attaches at a time.

**Whether messages wait** is the chat's, not the agent's: they wait while
the chat is `ChatState::WaitingForAgent`. CAF makes a chat wait for an
agent it installs until it's installed, and, while a sign-in that started
when the agent was signed out is under way, a chat that isn't running its
agent yet waits too. A chat in any other state sends as usual.

While the chat waits, the composer says
*Message Claude: it waits until Claude is ready*, and a message sent waits
on the composer's tray, headed *Waiting for Claude · 1*, with
*Not now drops it*.

**Not now** is in the banner while the chat is `ChatState::WaitingForAgent`
with a message waiting, and the viewer may act. No turn can be running then,
so it drops this chat's waiting messages, and nothing else (`Core::stop`).
In any other state, such as a chat mid-turn while a sign-in to its agent is
under way, there's no Not now: a message queued behind the turn stays on
the tray as usual, with *Stop drops it too*. **Stop** stops the install or
the sign-in, for every chat with the agent.

The signed-out banner's Not now is the one exception: nothing waits there,
and it only hides the banner, as [Signing in](#signing-in) says.

## Installing

These are for an agent CAF installs (`AgentSpec::installed`). Sizes are in
MB of 1,000,000 bytes, rounded, or GB with one decimal from 1,000 MB, as
`627 MB`.

![Checking](/caf/standard-interface/agents-checking.webp "CAF hasn't looked yet")

**Checking.** Until CAF has looked at what's installed
(`InstallState::Unknown`), as just after the app starts, the banner is calm,
with a spinner: *Checking whether Claude is installed…*, and under it,
*Messages wait until Claude is ready.*

If CAF can't look, it stays `Unknown`, and nothing says so but CAF's log.
So after 10 seconds of checking, the banner adds **Install**, with no size (CAF
accepts it while it hasn't looked, and `Unknown` carries no size), and the
app calls `Core::check_agents` again, then every 30 seconds while it's
still `Unknown`.

**Not installed.** The main picture above. CAF has looked, and the agent
isn't installed (`InstallState::Missing`). The banner says
*Claude isn't installed yet.*, then
*Installing it takes about 627 MB of disk. Messages wait until it's installed.*
The size is what the install takes on disk (`Missing.size`, the recipe's
`size`): installing is the user's choice, so they're told what it costs
before they agree. The action is **Install · 627 MB**, with a download
arrow.

![After Not now](/caf/standard-interface/agents-not-now.webp "Not now dropped the message: CAF says so, and the banner stays")

**After Not now.** Not now dropped the message. The chat shows it as
stopped, and CAF says why, in its own voice:
*Claude isn't installed, so the message that waited for it was stopped.*
The agent still isn't installed, so the banner stays, with Install.

CAF adds that note only while the agent isn't installed (`Missing`,
`Installing` or `Cannot`). Not now pressed while it's checking, or while a
sign-in holds the chat, stops the message silently: it shows as stopped,
with no note.

The chat is now lost, as one stopped while opening is
(`Lost { reason: Stopped }`). While the agent banner shows, it stands in
for the transcript's box for a lost chat, which isn't drawn: what to do
next is in the banner, and why in CAF's note. The next message sent waits
again.

![Installing, getting ready](/caf/standard-interface/agents-starting.webp "Installing, nothing done yet: the bar moves")

**Getting ready.** Once Install is pressed, the banner is calm:
*Installing Claude…*, *Messages wait until it's installed.* Until any of it
is done (`Installing.done` is 0), the bar moves without filling, and says
*Getting ready*. The action is **Stop**.

![Installing](/caf/standard-interface/agents-installing.webp "Installing, with how much is done")

**Installing.** As it goes, the bar fills, and says how much is done, of
about how much: *276 of about 627 MB* (`Installing.done` and `size`). The
size is CAF's estimate, so `done` may pass it: the bar then stays full, and
says *640 MB so far*. Don't guess how long is left.

When it's done, every chat waiting for the agent starts, its waiting
messages go, and the banner goes.

**Installs nobody pressed for.** A later CAF may patch the version
installed again. It makes the new install from the one that's there,
without asking, as nothing is downloaded, and the agent shows
**Installing** by itself, in every chat with it. If that fails, it reads
as not installed, and installing it asks, as usual.

**Install pressed before CAF has looked.** For an agent CAF installs
patched, as it does Claude, the install waits for CAF to look, showing
*Getting ready*. It then goes on, or, if the machine can't install the
agent at all, stops every message waiting for it, with the note
*Claude's install failed, so the message that waited for it was stopped.*,
and shows why, as below. For any other agent, it downloads at once.

### When an install fails

An install that fails stops every message waiting for it, in every chat
with the agent, and each chat that had one says so in CAF's voice:
*Claude's install failed, so the message that waited for it was stopped.*
The banner takes the warning colour, says why, and offers **Try again**,
which installs it afresh. It says nothing of messages, since CAF's note
already does, where one was stopped. A message sent afterwards waits
again, with Not now.

![Failed: offline](/caf/standard-interface/agents-offline.webp "The network was out of reach")

**Offline** (`InstallFailure::Offline`):
*Couldn't install Claude: the network was out of reach.*, then
*Check the connection, then try again.*

![Failed: a damaged download](/caf/standard-interface/agents-corrupt.webp "A download didn't match its checksum")

**A damaged download** (`InstallFailure::Corrupt`): a download didn't match
its checksum, so CAF threw it away.
*Couldn't install Claude: what was downloaded wasn't what was expected, so it was thrown away.*,
then *Trying again usually works.*

![Failed: the disk is full](/caf/standard-interface/agents-nospace.webp "No room on the disk")

**The disk is full** (`InstallFailure::NoSpace`):
*Couldn't install Claude: the disk is full.*, then
*It takes about 627 MB. Free some space, then try again.*

![Failed: not finished](/caf/standard-interface/agents-patch.webp "CAF couldn't patch what it installed, and removed it")

**Not finished** (`InstallFailure::Patch`): CAF installs some agents
patched, and the patch didn't fit, so CAF removed the install rather than
run it half-patched.
*Couldn't install Claude: it couldn't be finished once downloaded, so it was removed.*
Under it is what CAF said: which file, and which check stopped it. Then
*Trying again downloads it afresh. If it fails the same way, this app needs updating.*
Only a newer CAF fixes a patch that doesn't fit what was downloaded.

![Failed: anything else](/caf/standard-interface/agents-other.webp "Any other failure, in the installer's words")

**Anything else** (`InstallFailure::Other`):
*Couldn't install Claude. The installer said:*, then what it said, as CAF
gives it (cleaned, and cut to 300 bytes).

**Stopped** (`InstallFailure::Stopped`): the installer reported it was
stopped, though CAF didn't stop it. (An install CAF stops, by the user's
Stop or as the app shuts down, just reads as not installed.)
*Couldn't install Claude: the last try was stopped.*, with Try again.

### When it can't be installed

Some machines can't install an agent at all (`InstallState::Cannot`).
Trying again would fail the same way, and CAF refuses it
(`Refused::NotInstallable`), so there's no Try again. The banner takes the
warning colour.

![Can't: Node](/caf/standard-interface/agents-node.webp "The machine's Node is too old")

**Node** (`CannotInstall::Node`):
*Claude can't be installed here: it needs Node 22 or newer, and this machine has Node 18.*,
or *…and this machine has no Node.* when it has none. Then
*Install a newer Node, then check again. Messages wait until it's installed.*
**Check again** has CAF look again (`Core::check_agents`, or a viewer's
`CheckAgain`); if the machine now has what's needed, the banner turns to
Install. It looks at what's installed and what the machine has for every
agent, not only this one. CAF never installs Node itself. Check again
needs the `agents` right: a viewer without it has none, and the app looks
again itself, such as when its window comes to the front, which any app
may do too.

![Can't: npm](/caf/standard-interface/agents-npm.webp "The machine has no npm")

**npm** (`CannotInstall::Npm`):
*Claude can't be installed here: it needs npm, and this machine has none.*,
then *Install npm, then check again. Messages wait until it's installed.*,
with Check again.

![Can't: no build](/caf/standard-interface/agents-platform.webp "Later: there's no build for this machine, so the box is locked")

**No build** (`CannotInstall::Platform`). **Later.** Only an agent CAF
downloads can lack a build for the machine. Today Claude is CAF's only
built-in agent, and it comes from npm, so no app can show this yet. It's
here for a future agent CAF downloads; the example is Codex.
*Codex can't be installed here: there's no build of it for this machine.*,
then *Start a new chat with another agent.* Nothing on this machine will
change that, so no message could ever go: the composer is locked, as when
the user can't write, and says
*Codex can't run on this machine, so this chat can't go on.* CAF would
still take a message, and hold it for ever, so the app doesn't offer to
send one. A message already waiting keeps Not now.

**No recipe** (`CannotInstall::NoRecipe`): CAF doesn't know how to install
this agent. Every built-in profile has a recipe, so this happens only when
the app offers an agent CAF installs with the cautious profile. That
profile can't turn off the agent's own tools either, so CAF won't run it
(`Refused::OwnTools`), and what
[A chat's identity and lifecycle](/caf/standard-interface/chats.md) says of an
agent CAF won't run wins: its lock and words, not a lock of this page's.
The banner says only *my-agent can't be installed by this app.*, with no
actions.

## Signing in

CAF signs in with the agent's own sign-in, never one the agent suggests,
and never sees a password. For Claude, that's a page on Claude's site,
opened in the user's browser.

![Signed out](/caf/standard-interface/agents-signed-out.webp "The agent is known to be signed out: Sign in, and nothing waits")

**Signed out.** When the agent is known to be signed out, and CAF can sign
in to it now (`can_sign_in`), the banner says *Claude is signed out.*, then
*Sign in with your Claude account to use it. Claude's sign-in page opens in your browser.*
The actions are **Sign in**, with a key, and **Not now**.

Nothing waits here: CAF doesn't hold a chat back because its agent is
signed out, so the box says only *Message Claude*. A message sent now goes,
and fails asking for a sign-in, with **Sign in** as its remedy
(`Remedy::SignIn`), as [the transcript](/caf/standard-interface/transcript.md)
shows. Here, Not now only hides the banner in this chat, until the agent's
state changes; CAF isn't asked anything.

While `can_sign_in` is false there's no Sign in, and no signed-out banner.
For an agent CAF installs, it's false until it's installed. For one the app
starts itself, it's false until it has started once in this run, and for
ever if its sign-in needs a file only CAF's own install has, or the private
folder CAF gives only its own installs.

![The link coming](/caf/standard-interface/agents-link-coming.webp "The sign-in has started, and hasn't given its link yet")

**The link coming.** Once Sign in is pressed, here, on a failed turn or in
the panel, the agent's sign-in starts. Until it gives its link
(`SignInLink.url` is `None`), the banner is calm, with a spinner:
*Starting Claude's sign-in…*, then
*The page to sign in on will be here in a moment.*, and, where the chat
waits, *Messages wait until you've signed in.* The action is **Stop**.

![Signing in: link and paste](/caf/standard-interface/agents-signing-in.webp "Claude's sign-in: a page to open, and a box to paste a code back into")

**Signing in.** The banner says *Sign in to Claude*, in the accent, then,
where the chat waits, *Messages wait until you've signed in.* It numbers
the steps:

1. *Open the sign-in page on claude.ai, and sign in there.*, naming the
   link's own site, with **Open the sign-in page**. Under it is the link
   itself, muted and cut short, with a **Copy link** button, for a browser
   elsewhere.
2. When the sign-in takes a code pasted back (`SignInLink.paste`, as
   Claude's does): *If the page gives you a code instead, paste it here:*,
   a box and **Send the code**, then
   *As it does when the browser is on another machine.*
3. Muted: *That's all: this goes on by itself once you've signed in.*

Open the link in a new browser tab or window, cut off from the app, and only
if it's `https`. CAF has already checked it goes to a site the agent's
profile names, and stops a sign-in whose link goes anywhere else; that's the
app's own check besides.

![Signing in: link and code](/caf/standard-interface/agents-signing-in-code.webp "Later: an agent whose sign-in shows a code to type on its site")

**A code to type.** **Later.** Some agents' sign-ins show a code to type on
the site (`SignInLink.code`). Claude's doesn't, and it's CAF's only
built-in agent today, so this is for a future one; Gemini is here only as
an example.
Step 2 is then *When it asks for a code, enter this one:*, with the code,
large and spaced, and **Copy**. A sign-in may have both a code and a box to
paste into; each is a step of its own, in that order.

**Stop** stops the sign-in (`Core::stop_sign_in`), and the agent goes back
to how it was, as it does when a sign-in nobody finishes is stopped, after
10 minutes (`Timers::sign_in`), and when a sign-in fails: it ends badly, its
command can't run, or its link goes to a site the profile doesn't name. CAF
gives no reason for a failure, as it could be what the command printed, so
the banner just goes back to how it was, and the chats that waited go
ahead: their messages go, and fail asking for a sign-in if the agent is
still signed out. Don't show a countdown: CAF doesn't tell a viewer when it
will stop a sign-in.

![Signed in](/caf/standard-interface/agents-signed-in.webp "Signed in: it says how, the message goes, and the banner goes after 4 seconds")

**Signed in.** When the agent turns from `SigningIn` to `SignedIn`, every
chat that was showing the sign-in keeps its banner for 4 seconds more,
calm, with a tick, saying how, as the current `SignedInAs` has it:
*Signed in to Claude with your account.*, *…with an API key.*,
*…through a gateway.*, or *Signed in to Claude.* while it's `Unknown`. CAF
first says `SignedIn(Unknown)`, and learns how a moment later, so the
banner may begin *Signed in to Claude.* and then say how. Under it, where a message waited,
*Your message is on its way.* CAF has no state for this: the app holds it.

A chat whose last message failed for want of signing in also gets a note
from CAF, saying the user signed in, and that the message can be sent
again (`Note::SignedIn`). CAF never sends it again by itself.

Agents CAF installs from one profile share one sign-in: signing in to one
signs in to all of them, in every chat. Each agent the app starts itself
has its own.

## What the actions do

| Action | What it does |
| --- | --- |
| **Install · 627 MB** | Installs the agent (`Core::install`). Pressing it while it's already installing does nothing more. |
| **Try again** | The same, after a failed install. It downloads afresh. |
| **Stop** (installing) | Stops the install, for every chat (`Core::stop_install`). The agent reads as not installed. Messages waiting for it are stopped, with the note *Claude isn't installed, so the message that waited for it was stopped.* |
| **Check again** | Has CAF look again at what's installed and what the machine has, for every agent (`Core::check_agents`, or a viewer's `CheckAgain`, with the `agents` right). |
| **Not now** | Drops this chat's waiting messages, as the composer's Stop would (`Core::stop`). Where nothing waits, on a signed-out agent, it only hides the banner. |
| **Sign in** | Starts the agent's sign-in (`Core::sign_in`). Pressed while one is under way, it does nothing more. |
| **Send the code** | Passes what was pasted to the sign-in (`Core::paste`), trimmed. Unlit while the box is empty. |
| **Stop** (signing in) | Stops the sign-in, for every chat (`Core::stop_sign_in`). |
| **Sign out** | Signs out with the agent's own command (`Core::sign_out`), stopping any sign-in first. Only in the agents panel. |

### When CAF refuses

If CAF refuses an action, the banner, or the panel's row, says why under its
actions, in the warning colour, and stays as it was:

| CAF refuses | It says |
| --- | --- |
| `NotInstallable` | *Claude can't be installed here.* |
| `AlreadyInstalled` | *Claude is installed already.* |
| `CannotSignIn`, signing in | *Claude can't be signed in to from here now.* |
| `CannotSignIn`, signing out | *Claude can't be signed out of from here.* |
| `NotSigningIn` | *Claude isn't being signed in to any more.* |
| `NothingToStop` | *There's nothing to stop now.* |
| `Unsupported`, pasting | *That can't be sent as a code: paste one line, of at most 4 KB.* CAF refuses a paste of more than one line, or longer than 4 KiB. |
| `NoSuchAgent` | *This app doesn't offer Claude any more.* |
| `NoSuchChat`, on Not now | *This chat isn't open any more.* |
| `Outcome::Gone`, to a viewer | *The app has closed, so nothing was done.* |
| `Outcome::NotAllowed`, to a viewer | *You can't install agents or sign in to them here.* |

## A viewer without the agents right

Installing agents and signing in to them is a right of its own
(`Rights.agents`). In `caf-driver-tokio` it's given by
`ViewerRules::agents`, which is off by default. Whoever opens the sign-in
link and approves it chooses whose account the agent signs in to, so a
viewer that may only watch never sees the link or the code: CAF doesn't send
them. Such a viewer is told what's happening, and offered nothing it can't
do. Its banner is calm, as what the agent needs is nothing this user can
act on. A viewer with the `act` right still gets Not now, quiet, as for
anyone: it drops only their own chat's message, so it doesn't make the
banner the user's to act on.

![Not installed, without the agents right](/caf/standard-interface/agents-viewer-missing.webp "Told what's needed, with no Install")

**Not installed.** *Claude isn't installed yet.*, then
*You can't install agents here. Messages wait until it's installed.* There's
no Install.

![Installing, without the agents right](/caf/standard-interface/agents-viewer-installing.webp "The install, with no Stop")

**Installing.** As for anyone, but with no Stop.

![Signing in, without the agents right](/caf/standard-interface/agents-viewer-signing-in.webp "No link or code: only what's happening")

**Signing in.** CAF sends the state, but no link or code, so the viewer
can't tell whether the link has come. The banner has a spinner:
*Someone is signing in to Claude.*, then
*You can't sign in to agents here.*, and, where the chat waits,
*Messages wait until they've signed in.*

**Not now** needs only the right to act (`Rights.act`), as it drops the
viewer's own chat's messages, so this viewer keeps it wherever a message
waits. A viewer without `act` can't write, so has no Not now, and its tray
has no note. The failure states show their words with no Try again or
Check again, and the signed-out banner isn't shown at all.

## The agents panel

![The agents panel](/caf/standard-interface/agents-panel.webp "Every agent at once, with what each needs; the Codex, Cursor and OpenCode rows are Later")

**Later**, in part: today Claude is the only agent CAF installs, so the
Codex, Cursor and OpenCode rows, which CAF would install, stand for future
agents. An agent the app starts itself, as Gemini and my-agent are here,
can sit beside Claude now.

The agents panel lists every agent the app offers, in the app's order
(`Core::agents`), one row each:

- **Its mark and name**, as in a chat, and its version as CAF installed it:
  *0.98.0+caf.1* (`Installed.version`). An agent the app starts itself says
  *started by this app* instead. An agent the app has no mark for shows its
  initial, in a muted square.
- **Its install**: *Installed*; *Not installed · about 52 MB*, in the
  caution colour; *Installing · 31 of about 70 MB*, with a spinner in the
  accent and a bar under the row; *Couldn't install:* or
  *Can't be installed:* and why, as the banner says it, in the warning
  colour. *Checking…* until CAF has looked.
- **Its sign-in**, once it's installed or started by the app:
  *Signed in with your account* (*with an API key*, *through a gateway*,
  or just *Signed in*), *Signed out* in the caution colour, *Signing in*,
  or nothing while CAF doesn't know.
- **Its tools**: *Uses only this app's tools*, when CAF can turn the agent's
  own tools off (`own_tools_off`), whether it's installed or not. When it
  can't, CAF won't run it, and the row says so, in the warning colour:
  *Can't be used: its own tools can't be turned off*. Chats with it are
  refused (`Refused::OwnTools`).
- **Its action**, on the right. One at most, the first of these that
  applies:

| The agent | The action |
| --- | --- |
| Not installed (`Missing`) | **Install**, primary |
| Not known yet (`Unknown`), after 10 seconds | **Install**, primary, with no size |
| Installing | **Stop** |
| Its last install failed (`Cannot(Failed)`) | **Try again**, primary |
| Can't be installed for want of Node or npm (`Cannot(Node)`, `Cannot(Npm)`) | **Check again** |
| Can't be installed otherwise (`Cannot`) | None: why is in the row |
| Being signed in to | **Stop**, with the steps under the row |
| Signed out or not known, and `can_sign_in` | **Sign in**, primary |
| Signed in | **Sign out**. CAF can refuse it, as for an agent whose profile has no way to sign out; the row then says *Claude can't be signed out of from here.* |

A sign-in shows its steps in the panel's row, as the banner draws them,
unless a chat with that agent is shown beside the panel, which shows them
already. CAF has no update action: a newer version of an agent comes with a
newer CAF, which asks to install it when it's next used, or makes it
without asking when it's only patched again, as above.

![The agents panel, without the agents right](/caf/standard-interface/agents-viewer-panel.webp "Where each agent stands, and no actions")

For a viewer without the `agents` right, the panel has no actions, and
says at its foot
*You can see the agents here, but not install them or sign in to them.*

## What CAF tells the app

| What the banner or panel shows | Where it comes from |
| --- | --- |
| Whether the banner shows | The agent's status: `install` neither `Installed` nor `Host`; `SignInState::SigningIn`; or `SignInState::SignedOut` with `can_sign_in`. In any chat but an archived one (`Chat.archived`). |
| Whether messages wait | The chat's `ChatState::WaitingForAgent`. |
| Every agent's status | `Core::agents`, and a viewer's `ToViewer::Agents`, again each time any of it changes. |
| The install states | `AgentStatus.install`: `Host`, `Unknown`, `Missing { size }`, `Installing { done, size }`, `Installed { version }`, `Cannot(why)`. |
| Why it can't be installed | `CannotInstall`: `Node { needs, has }`, `Npm`, `Platform`, `NoRecipe`, or `Failed(InstallFailure)`: `Offline`, `Corrupt`, `NoSpace`, `Stopped`, `Patch(what)`, `Other(what)`. |
| The sign-in states | `AgentStatus.sign_in`: `Unknown`, `SignedOut`, `SigningIn(SignInLink)`, `SignedIn(SignedInAs)`. |
| The sign-in's steps | `SignInLink`: `url` (checked against the profile's sites), `code`, `paste`. |
| Whether Sign in is offered | `AgentStatus.can_sign_in`. |
| *Uses only this app's tools* | `AgentStatus.own_tools_off`. |
| The notes in the chat | `Note::NotInstalled`, `Note::InstallFailed`, `Note::SignedIn`. |
| A refusal | `Refused`, or a viewer's `Outcome::NotAllowed`, as the table above gives them. |
| Who may do what | The viewer's `agents` right for installing, signing in and Check again, and its `act` right for Not now. |

See [Installing and signing in](/caf/getting-started/installing-and-signing-in.md)
for the calls, and [Agents and profiles](/caf/concepts/agents-and-profiles.md)
for what CAF does underneath.

---

# A Chat's Identity and Lifecycle

_CAF / Standard Interface_

> How every CAF app names and marks a chat wherever it shows one, at three sizes, and what happens to a chat over its life, with the words and actions for each state. Restoring, the six reasons a chat can't be restored, closing a tab, archiving, an agent that's gone or that CAF won't run, starting a new chat and deleting one, and what CAF tells the app.

A chat appears in more places than its own pane: in a sidebar, on a tab, in
a menu, on a workspace's badge. Wherever it appears, one component says which
chat it is and whether it needs the user. And over its life a chat is
restored, put out of sight, archived, deleted and started, which the chat
itself shows the same way in every CAF app.

[See it live](/attachments/caf-si-chats/chats.html): the identity at every size, and
every state, in dark and light.

![The identity component, in every state, at three sizes](/caf/standard-interface/chats-identity.webp "Each state, full, compact and minimal")

| Part | How firm |
| --- | --- |
| The identity component: its states, sizes and how each looks | **Required** |
| The lifecycle: every state below, its words, and what its actions do | **Required** |
| Where chats are listed, and where the component sits | **Up to the app** |
| Where actions live: buttons, context menus, keys | **Up to the app**. Only what they say and do is fixed. |
| Search, sorting, grouping, and empty states | **Up to the app** |
| Projects and workspaces (CAF's shelves) | **Up to the app**. They follow the app's own: there's no shelf picker. |

## The identity

One component says which chat this is and whether it needs the user. It has
three sizes; use whichever fits where the app shows chats:

| Size | For | What it shows |
| --- | --- | --- |
| **Full** | List rows | The agent's mark, the title, and on the right when it last changed or a dot. Under the title, a reason line: what's going on, or the number of turns. |
| **Compact** | Tabs and menus | One mark and the title. The mark is the agent's, or the state's dot or sign when there is one. |
| **Minimal** | Where there's room only for a mark, such as a pane header or a workspace's badge | The state's dot or sign alone, with the title as its tooltip. Nothing at all while the chat is idle or archived. |

### The title

**The app's label for the chat**, if it has one (`AppData::label`). Without
one, **the first line of the first message the user sent, in quotes and
italics**: *"Why does the file store take a flock before the rename?"*. A
chat with neither, a new one before anything is sent, is *New chat*. **Never its id.** A title too long for its
place ends in an ellipsis.

### The states

| State | Full | Compact and minimal | When |
| --- | --- | --- | --- |
| **Idle** | Agent's mark; when it last changed; *12 turns* | Agent's mark; minimal shows nothing | Nothing is going on. |
| **Working** | A pulsing dot in the accent; *Working · 31s*, in the accent | The pulsing dot | A turn is running, or stopping; the chat is starting its agent with a message waiting; or it waits for its agent while CAF does the work, such as installing it. |
| **Waiting on you** | A dot in the accent with a ring around it; what's waiting, such as *Wants to run a command*, in the accent | The ringed dot | A question is waiting, or the chat waits for its agent and the agent banner waits on the user, such as to install it or sign in. |
| **Failed** | A dot in the warning colour; why, such as *Usage limit*, in the warning colour | The dot in the warning colour | Its last turn failed. |
| **Lost its agent** | A hollow dot, a ring in the caution colour; why, such as *Claude stopped.*, in the caution colour | The hollow dot | The chat lost its agent between turns. What the next message does depends on why, as the transcript's box for it says: for most reasons it tries again, but after `Incompatible` or `ShutDown`, nothing can help. |
| **Restoring** | A spinner; *Restoring…* | The spinner | Briefly, as a saved chat opens. |
| **Archived** | Title muted; on the right, when it was archived; *22 turns ·* and an *Archived* badge | Muted; minimal shows nothing | The user archived it. It can still be opened, and stays archived, open or not, until the user unarchives it or sends to it. |
| **Can't restore** | A badge in the warning colour: *Can't restore: damaged*, naming the reason | A warning sign in the warning colour | Its last restore failed. |
| **Agent gone** | A crossed-out plug and *Gemini isn't available*, muted | The crossed-out plug | The app no longer offers its agent. It can be read but not carried on. |
| **Agent can't be used** | A lock and *Claude can't be used*, muted | The lock | CAF won't run its agent, as it can't turn off the agent's own tools. It can be read but not carried on. The lock is the composer's, as [An agent that's gone](#an-agent-that-s-gone) shows. |

The states and how each looks are fixed. Working's dot pulses, Waiting on
you's is ringed, and Lost's is hollow, so they differ by shape at every
size, not only by colour or movement. The reason line uses CAF's
words for what's going on: the transcript's for a failure and for a lost
agent, and the question's for what waits on the user.

Working counts from when its message was sent, so it includes any time the
message waited. While Stop is under way, its reason line says *Stopping…*;
while the chat starts its agent, *Starting Claude…*.

**A chat waiting for its agent** follows the
[agent banner](/caf/standard-interface/agents.md#its-parts), and the reason
line is the bold part of the banner's first line, without its full stop:

| The banner's tone | State | Reason line, for example |
| --- | --- | --- |
| Accent: it waits on the user | Waiting on you | *Claude isn't installed yet* |
| Calm, as CAF does the work: checking, installing, or a sign-in's link on its way | Working, with no time | *Installing Claude…*, *Checking whether Claude is installed…* |
| Calm, only because this viewer can't act on it | No dot: the agent's mark, and the reason line muted | *Claude isn't installed yet* |
| Warning: it went wrong, or can't go on | Failed | *Couldn't install Claude* |

A viewer that can't act on the agent gets no dot: Waiting on you would ask
it for something it can't do, and Working would say something is under way
when nothing is. The muted line still says why the chat isn't going on.

That holds while the chat is `WaitingForAgent`, and while it's
`Lost { reason: Stopped }` with the banner showing, as after Not now: the
banner stands in for the lost chat's box then, so the identity follows the
banner, not the loss.

**Which state.** A chat is in the first of these that holds:

1. **Restoring** or **Can't restore**, from how the chat is saved, while it
   isn't open; then **Archived**, while the chat is archived, open or not,
   saved or not.
2. **Agent gone**, when the app no longer offers its agent, or **Agent
   can't be used**, when CAF won't run it.
3. **Waiting on you**, while a question waits.
4. **The agent banner's state**, as above, while the chat is
   `WaitingForAgent`, or `Lost { reason: Stopped }` with the banner showing.
5. **Working**, while its last turn is running or stopping, or the chat is
   `Opening` with a message waiting.
6. **Failed**, when its last turn failed.
7. **Lost its agent**, while the chat is `Lost`.
8. **Idle**: anything else. That covers a chat whose last turn finished,
   was stopped or was cut off, and one `Opening` with no message waiting.

Its **last turn** is the last one the user or the agent started. A turn of
CAF's own, which only carries CAF's notes, such as the one saying the user
signed in, never counts: a chat that failed for want of signing in stays
Failed until the next turn.

### Hosting it

![The same component in a sidebar, on tabs, and in clackatoo's panes](/caf/standard-interface/chats-hosting.webp "Examples only: three apps, three ways of listing chats")

**Up to the app.** Three apps, three ways of listing chats, the same
component: full in a simple app's sidebar, compact on framewright's tabs,
minimal on clackatoo's workspaces with compact in its pane headers. They show
it fitting in; they're not layouts to copy. Put chats wherever the app
already puts its things.

**An archived chat in a list. Required.** Wherever a list shows an
archived chat, open or not, saved or not, it shows it in the identity's
**Archived** state, at whatever size the list uses: the title muted, and
at full size the *Archived* badge and when it was archived. It's never
shown as idle, nor left out because it's still open: an archived chat
the user has open is listed as archived until it's brought back, then as
any other at once. Whether a list keeps archived chats apart, such as under an
*Archived* heading, last, or behind a filter, is **up to the app**.

## The rules

**Required.**

1. **No CAF words.** Users never see *shelf*, *loaded*, *put away*,
   *session* or *adapter*. A shelf takes the app's own word, such as project
   or workspace, or none.
2. **Opening a chat just opens it.** If it was saved, CAF restores it, and
   that shows only as a brief *Restoring*. Users never manage what's in
   memory, so there's no "open" against "saved".
3. **Closing a tab or a pane never archives a chat.** A saved chat is put
   away; one that isn't saved stays open, out of sight.
   [Closing a tab](#closing-a-tab) says what happens to each.
4. **Archive is CAF's close**: "I'm done with this one". It's a deliberate
   action, never a side effect of closing a tab or a pane. **Archiving
   sticks**: an archived chat stays archived, opened or not, until the user
   unarchives it or sends to it.
5. **Delete can't be undone,** so it always asks first, naming the chat.
   Only a saved chat can be deleted.
6. **A new chat is an empty chat.** There's no form: the agent is chosen in
   the composer's own settings menu, and sending starts the chat.
7. **When a chat can't be restored,** say which of the six reasons it is, in
   the words below, with only the actions that can help.

## Restoring

![Restoring](/caf/standard-interface/chats-restoring.webp "A saved chat opening")

**Restoring.** Opening a saved chat restores it: CAF reads it back, and it
carries on as it was. Meanwhile the chat shows a spinner and *Restoring…*, and
its title in the header. This is the only sign it was saved.

A restored chat starts no agent until a message is sent. What was under way
when it was saved is tidied: a turn that was running is cut off, and a
message that was waiting is stopped, never sent by itself. The
[transcript](/caf/standard-interface/transcript.md) shows both.

### When it can't be restored

CAF gives one of six reasons, and leaves the chat's save exactly as it was,
whatever the reason. The chat shows a box in the warning colour: a heading in
bold, with a warning sign and no full stop, then a sentence or two under it.
When CAF has the store's or the system's own words, they follow in a
monospace font, muted. Under the box are only the actions that can help.

![Damaged](/caf/standard-interface/chats-cant-damaged.webp "The save can't be read: Delete is the only action")

**Damaged** (`Damaged`).

- Heading: **This chat's save is damaged**
- Under it: *It can't be read, so it can't be opened. The save is left
  exactly as it was.*
- Then what the store said, such as *chunk 3: zstd frame checksum
  mismatch*.

Trying again can't help, so the one action is **Delete…**, which asks
first, as [Delete](#deleting) does.

![In use](/caf/standard-interface/chats-cant-inuse.webp "Another program has it open")

**In use** (`InUse`). Another program has it open: another app, another
window of this one, or another copy of CAF.

- Heading: **This chat is open somewhere else**
- Under it: *A chat is never open in two places at once. Close it there,
  then try again.*

**Try again** restores it again.

![Newer](/caf/standard-interface/chats-cant-newer.webp "Saved by a newer version: no actions")

**Newer** (`Newer`).

- Heading: **Saved by a newer version**
- Under it: *A newer version of this app saved it, in a form this one can't
  read. It's left untouched until this app is updated.*

Nothing helps but updating, so there are no actions.

![The app's data](/caf/standard-interface/chats-cant-appdata.webp "The app can't read what it saved with the chat: no actions")

**The app's data** (`AppData`).

- Heading: **This app can't read its own data on this chat**
- Under it: *Another version of this app saved it, in a form this one can't
  read. The chat is left untouched, for a version that can.*
- Then what the app's reader said, such as *missing field `pinned`*.

There are no actions.

![Couldn't read](/caf/standard-interface/chats-cant-store.webp "The store failed: Try again")

**Couldn't read** (`Store`).

- Heading: **This chat couldn't be read**
- Under it: *Reading it failed, and nothing was changed. Try again in a
  moment.*
- Then what the system said, such as *Input/output error (os error 5)*.

**Try again** restores it again.

![Gone](/caf/standard-interface/chats-cant-gone.webp "Nothing is saved under it any more")

**Gone** (`NotFound`).

- Heading: **This chat is gone**
- Under it: *Nothing is saved under it any more. It may have been deleted
  elsewhere.*

**Remove from list** lists the saved chats again, and it drops out. Only
the app can list them, so a viewer shows no action.

**Try again** is offered only after *In use* and *Couldn't read*: for the
other four, trying again can't change the answer.

## Closing a tab

Closing a tab or a pane, or whatever the app uses to put a chat out of
sight, never archives it.

- **A saved chat is put away**: saved as it is, and let go of, so it takes
  nothing while it's closed. Opening it again restores it, as it was. When
  that happens depends on what the chat is doing:
  - **At once, unless** a turn runs or is stopping, a message waits behind
    one, a question waits, or the chat is `Opening` with a message waiting.
  - **In those cases, once they're done**, so closing a tab never stops the
    agent's work. A question keeps it open until it's answered, or until
    the app stops, which saves it anyway.
  - **A chat waiting for its agent is put away at once**, and its waiting
    messages are stopped, since they may wait for ever. Unlike Not now,
    this brings no note from CAF: the transcript shows them as stopped, with
    no reason. The app may warn first, such as *Closing this drops the
    message waiting for Claude.*

  Until it's put away, wherever the app lists it, it shows its state as
  usual, such as Working or Waiting on you. Opening it again before then
  just shows it: it's still open, and restoring it would be refused.
  Once it's put away, CAF may still be writing it for a moment, and
  refuses to restore it meanwhile (`Refused::Loaded`): opening it again
  then, the app tries again for a moment, until it can.
- **A chat that isn't saved stays open**, as it is, out of sight. The app
  can show it again, as it was, until the app stops; then it's gone.

## Archiving

**Archive** is CAF's close: the user is done with the chat. Its agent is let
go, and a saved chat is saved, archived, and put away. Wherever it appears,
it's muted, with an *Archived* badge, and the full identity shows on its
right when it was archived, in place of when it last changed. A chat saved
archived before CAF kept when shows when it last changed instead.

![An archived chat, opened](/caf/standard-interface/chats-archived.webp "Opened, it's still archived: the tray says so, and sending brings it back")

**Opening an archived chat** restores it, as any saved chat, and it's
still archived: archiving sticks. The chat shows it as anywhere else, with
its title and the *Archived* badge in the app's header for it, and its
composer's tray says *This chat is archived. Sending a message brings it
back.*, with **Unarchive**, as
[The composer](/caf/standard-interface/composer.md#what-the-chat-allows)
shows. It can be read, and written in; only its settings can't be changed
meanwhile.

**Bringing it back.** A message sent to an archived chat brings it back:
CAF unarchives it, then sends the message as to any other. **Unarchive**
brings it back without sending. Either way it's an ordinary chat again at
once: the badge and the tray's note go, and its agent starts when a
message is sent, as for a restored chat. Wherever it's listed, it goes
back to how its state shows it.

A saved chat is put away as it's archived, so the app no longer has it
open. To send to it or unarchive it, the app restores it first
(`Core::restore`), archived still, then sends or unarchives, as
[The composer](/caf/standard-interface/composer.md#what-the-chat-allows)
says: the user sees nothing of this. Right after it's archived, the
restore is refused (`Refused::Loaded`) while CAF finishes writing it, for
moments: the app tries again for a moment meanwhile, as
[Closing a tab](#closing-a-tab) says for any chat just put away. A chat
restored archived is `ChatState::Closed` until it's brought back, then
`Idle`.

A chat that isn't saved, once archived, stays in memory, archived, until
the app stops, and is brought back the same way.

## An agent that's gone

![Its agent gone](/caf/standard-interface/chats-agent-gone.webp "Readable, not continuable: the box says why")

**Agent gone.** A saved chat whose agent the app no longer offers still
opens, with all it held, and can be read but not carried on. Its composer
says why instead of offering to send: *Gemini isn't available in this app
any more. You can read this chat, but not carry it on.*, with a crossed-out
plug, the agent's mark and name, and the context ring.

If the app renamed the agent, the chat isn't gone: when exactly one agent
the app offers has the old one's built-in profile, CAF finds it by that, and
the chat comes back with the agent under its new name. With none, or more
than one, the agent is gone.

![An agent CAF won't run](/caf/standard-interface/chats-own-tools.webp "Its own tools can't be turned off: readable, not continuable")

**An agent CAF won't run.** CAF never runs an agent whose own tools it can't
turn off. A saved chat with such an agent still opens, and reads as an agent
gone does, with a lock in place of the plug: *Claude can't be used: its own
tools can't be turned off. You can read this chat, but not carry it on.*
[Agents](/caf/standard-interface/agents.md#the-agents-panel) says the same of
the agent in its panel.

It happens in two ways, and the app knows both from the agent's status
(`own_tools_off` is false):

- **The app gave the agent the cautious profile**, which doesn't say how to
  turn its tools off. CAF refuses to send to the chat (`Refused::OwnTools`).
- **The agent isn't the one its profile is for**, as when the program
  started as Claude turns out to be another. CAF learns this only once it
  has started the agent in this run. It doesn't refuse the message, but
  the chat loses its agent each time it opens
  (`Lost { reason: Incompatible(OwnTools) }`), so no message could ever go.
  Locking the composer then is the app's rule, not CAF's refusal, so the
  user isn't asked to write what can't be sent. Until CAF has started the
  agent, the chat looks ordinary, and its first message ends with the
  transcript's box for the loss.

## Starting a chat

![A new chat](/caf/standard-interface/chats-new.webp "An empty chat with the usual composer")

**New chat.** A new chat is an empty chat: its title is *New chat*, its body
says *New chat* and *Send a message to start.* under the agent's mark, and
its composer says *Message Claude to start*. There's no context yet, so no
ring. Sending starts it, and the message is its first.

![Choosing the agent](/caf/standard-interface/chats-new-agent.webp "The settings menu's rail lists every agent in a new chat")

**Choosing the agent.** The agent is chosen in the composer's settings
menu, as its model is in any chat. In a new chat, the menu's rail lists every
agent the app offers, each with its models, and a dot in the caution colour
on any that still needs installing or signing in. An agent whose settings
CAF doesn't know yet shows *Not known yet* and *Learn them now*, as
[The composer](/caf/standard-interface/composer.md#before-caf-knows-the-settings)
shows.

![Choosing the folder](/caf/standard-interface/chats-new-folder.webp "A folder control, only when the app lets users choose")

**Choosing the folder.** Only if the app lets users choose where the agent
works does the box have a second control, beside the settings: the folder,
such as *~/projects/caf*. An app that decides the folder itself has none.

![Choosing an agent that isn't ready](/caf/standard-interface/chats-new-not-ready.webp "The menu says what the agent still needs")

**An agent that isn't ready.** Picking one that still needs installing
shows, in place of its models, *Codex isn't installed yet. Choose it, and
this chat will offer to install it once you send. Its models show here once
it's ready.*, and **Use Codex**. One that needs signing in says
*Codex needs you to sign in.*, and that the chat will offer to sign the user
in. Once the message is sent, the chat waits for the agent, and the agent
banner takes over on the box, as [The composer](/caf/standard-interface/composer.md#what-the-chat-allows)
shows.

![A new chat refused](/caf/standard-interface/chats-new-refused.webp "The app refused the chat: the box says why")

**Refused.** The app decides each new chat, and may refuse one. When it
does, the box says why, in the app's words and the warning colour, attached
to the top of the box: *Chats can't be started in /etc. Choose another
folder.* The message stays in the box.

## Deleting

![Deleting](/caf/standard-interface/chats-delete.webp "Delete asks first, naming the chat")

**Delete** is wherever the app puts it, and always asks first:
*Delete "Usage ledger sketch"? It's gone for good: this can't be undone. To
keep it but put it out of the way, archive it instead.* The actions are
**Cancel**, **Archive**, and **Delete**, in the warning colour. Deleting
removes the chat for good, open or not.

Only a saved chat can be deleted: one that isn't saved is gone anyway when
the app stops, and is archived instead. Only the app can delete a chat, so a
viewer offers no Delete.

## What CAF tells the app

| What the chat shows | Where it comes from |
| --- | --- |
| The title | The app's label, `AppData::label`: in an open chat's `ChatSummary.label` and a saved one's `Header.label`. Else the first line of the first message the user sent: a saved chat's `Header.first`, or the first `Starter::User` turn's text. |
| The agent's mark | `Chat.agent`, `ChatSummary.agent` or `Header.agent`. |
| When it last changed; turns | A saved chat's `Header.changed` and `Header.turns`. A chat that isn't saved: the latest time in its turns' `Turn.window`, and how many `Chat.turns` it has. |
| Its last turn | The last of `Chat.turns` whose `Turn.starter` is `User` or `Agent`, never `Caf`. |
| Working | That turn's `TurnLife::Running` or `Stopping`, counted from its `Turn.window.start`; or `ChatState::Opening` with a turn `TurnLife::Waiting`. |
| Waiting on you | A question in `Chat.questions`; or `ChatState::WaitingForAgent`, or `Lost { reason: Stopped }` with the banner showing, while the banner's tone is accent. The banner's tone comes from the agent's `AgentStatus`, as [Agents](/caf/standard-interface/agents.md) says. |
| Failed | That turn's `TurnLife::Failed`, with its `Failure.reason`. |
| Lost its agent | `ChatState::Lost`, with its `Lost` reason, in the transcript's words; but `Lost { reason: Stopped }` follows the banner while it shows. |
| Restoring | `SavedState::Restoring`, or `Core::restoring`. |
| Archived | `Chat.archived`, when it was archived, while it is: for a chat that's open, and kept in its save. In a viewer's list of open chats, `ChatSummary.archived`. For a saved chat that isn't open, `Header.archived`, or, for a chat saved before CAF kept when, `Header.closed`. A chat's `Change::Archived` says when it's archived or unarchived. |
| Can't restore | `SavedState::Failed`, with its `CannotRestore` reason: `NotFound`, `InUse`, `Newer`, `Damaged`, `AppData` or `Store`. Restoring answers with it too: `Error::CannotRestore`, or a viewer's `Outcome::CannotRestore`. |
| Agent gone | The chat's agent isn't among those the app offers (`Core::agents`, or a viewer's `Welcome.agents`): sending is refused with `Refused::NoSuchAgent`. A renamed agent is found by `Header.profile`. |
| Agent can't be used | Its `AgentStatus.own_tools_off` is false. With the cautious profile, sending is refused with `Refused::OwnTools`. With an agent that isn't the one its profile is for, sending isn't refused, but each open ends `Lost { reason: Incompatible(OwnTools) }`, and the lock is the app's own rule. |
| Opening a saved chat | `Core::restore`, or a viewer's `Restore`, which the app decides (`ViewerRules::restore`; by default it refuses). |
| Closing a tab | `Core::put_away` for a saved chat: at once, unless a turn is `Running` or `Stopping`, a turn is `Waiting` behind one, a question is in `Chat.questions`, or the chat is `Opening` with a turn `Waiting`; then once none is. A `WaitingForAgent` chat is put away at once, which stops its waiting turns with no `Note`. Until then it's loaded, and `Core::restore` would be refused, `Refused::Loaded`. One that isn't saved is refused, `Refused::NotSaved`, and is left open. Viewers can't put a chat away. |
| Archive | `Core::close_chat`, or a viewer's `Close`, with the `act` right: `Chat.archived` is set to now. |
| Unarchive | `Core::unarchive`, or a viewer's `Unarchive`, with the `act` right: `Chat.archived` is none again, and the chat is `Idle`. `Core::send` to an archived chat unarchives it first. While it's archived, CAF refuses to change its settings (`Refused::Closed`). |
| Remove from list | `Core::list_saved` on the chat's shelf again, which reads the store anew. Viewers can't list. |
| Delete | `Core::delete`, which takes the chat's shelf: only a saved chat. Viewers can't delete a chat. |
| A new chat | `Core::open_chat` with an `OpenChat`: the agent, the folder, and the settings chosen in the menu (`OpenChat.settings`). A viewer asks with an `OpenRequest` (an agent and a folder), and sets the settings with `Set` once it's `Opened`. |
| The new chat's menu | The agents CAF offers, each with its `AgentStatus.settings`, and whether it's installed and signed in. |
| A new chat refused | The app's own reason. A viewer gets `Outcome::NotAllowed`, or a `Refused` such as `NoSuchAgent`, `RelativeFolder` or `OwnTools`. Opening or restoring a chat is also refused when the app gave it MCP servers CAF can't serve beside its own: `Refused::ReservedServer`, *An MCP server can't be named caf, nor anything the agent would write as caf_ or starting caf__, such as caf. or caf__tools, as its tools would look like CAF's own.*, or `Refused::SameServerName`, *Two of the MCP servers have names the agent would write alike, so their tools couldn't be told apart.* Both are the app's own mistake, not the user's. |

Only a loaded chat's summary comes to a viewer unasked: `ChatSummary` has its
id, agent, folder, label and shelf, and when it was archived, if it is.
Whether it's working, waiting on the user or failed, and its first message,
come from watching it.

---

# Usage

_CAF / Standard Interface_

> How every CAF app should show what a chat has used and spent, the agent's account limits, and how much every CAF app on the computer has used over the past 24 hours, or the last 7, 30 or 90 days. The ring's popover, the dot for a limit running low, the usage page and its states, prices, pace, the colours for a limit low or out, what needs the usage right, with the words for each and what CAF tells the app.

Usage is shown in two places. **In the chat**, the context ring by Send
opens a popover with what this chat has used and spent, and how much of the
agent's account limits is left; a dot on the ring says when one runs low.
**On the usage page**, the user sees how much every CAF app on the computer
has used over a period, by agent, app, model and day, and each agent's
limits in full.

[See usage live](/attachments/caf-si-usage/usage.html), every state, in dark and light.

![The usage popover, opened from the context ring](/caf/standard-interface/usage-popover.webp "The ring's popover: this chat, then the agent's limits")

How firm each part is:

- **In the chat: Required.** The ring, its popover, the dot and their words.
  They're inside the chat, so a user moving between CAF apps finds them the
  same in each.
- **The usage page's layout: Suggested.** Its parts, what they mean, their
  words and colours are as below. Take the layout shown, or the one other
  way this page names: where there's no room for two columns, the same parts
  in one column, in the same order.
- **Where the usage page lives: Up to the app.** A panel over the window, as
  pictured, a tab, a pane: whatever the app already uses for a page of its
  own. So is any way to open it besides *Open usage*.
- **Later: only the extra agents in the pictures.** The pictures show Codex
  and Gemini beside Claude, to show a page with several agents. CAF runs only
  Claude today, and hears limits only from Claude. The layout stands as it
  is: shares, stacks and columns per agent work with one agent too.

## Where the numbers come from

Three things, and they reach a viewer in three ways:

| What | Whose | How a viewer gets it |
| --- | --- | --- |
| The context, and what the chat has spent | The chat's | With the chat, to any viewer watching it. |
| The account limits | The agent's account: every chat with the agent shares them | With the agent's status, to every viewer. |
| Usage over a period, and prices | Every CAF app on the computer, from the ledger they share | Only to a viewer with the `usage` right. |

So everything in the popover is shown to anyone who can watch the chat,
except *Open usage*, which needs the `usage` right, as the usage page does.
See [Usage](/caf/getting-started/usage.md) and
[Account Limits](/caf/getting-started/account-limits.md) for how CAF keeps them.

**The agent's name** is the one the app gives it everywhere else, *Claude*,
here as on [the composer](/caf/standard-interface/composer.md). In a summary,
CAF names an agent by its profile, such as `claude-agent-acp`, so that one
agent two apps name differently counts as one; the app shows that profile
by its agent's name and mark. Three cases want a rule:

- **An agent with no profile**, from another app: CAF names it by that
  app's name for it, which this app may not know. Show that name as it
  comes, with no mark.
- **Two of this app's agents with one profile** are one agent to a summary,
  as they share one account. Name it by the product the profile is for, as
  the app names that product (*Claude*), not by either agent's own name.
- **The *All agents* menu** lists the summary's agents, by profile, or by
  name for those without one. On Limits it picks the app's agents whose
  profile it names, or, without a profile, whose name it names. Agents that
  share a profile share their limits, so Limits shows them once, under the
  product's name.

## In the chat

### The ring

The context ring sits by Send, as [the composer](/caf/standard-interface/composer.md)
describes: how full the agent's context is, as a ring and a percent, in the
caution colour above 80% and the warning colour above 95%. Clicking it opens
the popover, and clicking it again, or anywhere else, closes it. **Escape**
closes an open popover and does nothing else: whatever else would take
Escape, such as a question waiting on the user, waits for the next press.
Focus stays on the ring throughout. A new chat, before the agent has said how full
its context is, has no ring, and so no popover.

![The ring with a dot: a limit low](/caf/standard-interface/usage-ring-low.webp "A limit with 20% left or less: a caution dot on the ring")

**The dot.** When one of the chat's agent's limits runs low, the ring gains a
dot, so it's noticed without opening anything:

- **caution**, when the window with least left has **20% left or less**
  (*low*);
- **warning**, when it has **10% left or less**, or the agent refuses turns
  in it (*out*);
- none otherwise.

The window that counts is the one with least left (the TypeScript SDK's `lowest`), and
how low it is is the TypeScript SDK's `lowness`, so every app puts the dot in the same
place.

**The two kinds of threshold differ, deliberately.** The ring's colours go by
how full the context is, and change only *above* 80% and 95%, as the
composer's do. A limit's go by what's left, and change *at or below* 20% and
10%, as the TypeScript SDK's `LOW_LEFT` and `OUT_LEFT` do. Each follows the one rule
every app shares for its measure, so neither is bent to match the other.

### The popover

One card, above the ring, in sections. Each measure is a row: a label, a bar
and a value. It takes no focus, and the chat goes on around it.

**This chat**, headed *This chat*:

| Row | Shows |
| --- | --- |
| **Context** | A bar of how full the context is, and *195K / 1M*: tokens used, of what it holds. The bar takes the ring's colours. |
| **Cost so far** | What the chat has cost: *$1.84*, with *API estimate* beside it if any of it was estimated. Under it, a line saying how it was come by (below). *Nothing yet* while CAF has no record of any of its turns. |
| **Tokens processed** | Every token its turns used, short: *2.1M*. |

The line under the cost, by what the chat's spend holds:

| When | The cost | The line |
| --- | --- | --- |
| All of it reported by the agent | *$1.84* | *As the agent reported it.* |
| All of it estimated | *$1.84 API estimate* | *An estimate, at API prices.* |
| Some of each | *$1.84 API estimate* | *$1.62 as the agent reported it, $0.22 estimated at API prices.* |
| No price for its models, and nothing reported | *$0.00* | *No price is known for the models it used, and the agent reported no cost.* |

And when some tokens had no price, a further line:
*1.2M tokens on models with no known price aren't in it.*

![A chat with no turns on record](/caf/standard-interface/usage-popover-none.webp "No turns on record: Nothing yet. The limits stay, as they're the account's")

**No record yet.** A chat whose turns CAF has no record of, such as one from
before usage was recorded, or imported, shows *Nothing yet* for its cost and
*0* tokens. Its limits are still shown: they're the account's, not the
chat's. The viewer pictured also lacks the `usage` right, so there's no
*Open usage*.

**The agent's limits**, headed *Claude's limits*, with the agent's mark and
name, and *as of 22:42* at the right: when CAF heard of them. With windows
heard at different times, it's the oldest, so it never claims they're
fresher than they are. Then a row per window, in the order CAF gives them:

- **the label**, from the TypeScript SDK's `label`: *5-hour*, *Weekly*,
  *Weekly · Opus*, *Weekly · extra included*, or the agent's own name for a
  window CAF doesn't know;
- **a bar of what's left**, with a line where an even pace would have it now
  (see [Pace](#pace));
- **what's left**, as a percent: *72%*;
- **under it**, the pace, or the agent's own word for the window if it has
  one, then when it resets: *Under pace · resets in 1 h 52 min*.

Under the rows, *Bars show what's left. The line is where even use would
have it now.* An agent that hasn't said what its limits are has no limits
section.

**Open usage**, at the foot, in the link colour, goes to the usage page.
Only a viewer with the `usage` right sees it.

### A limit low or out

![A limit low](/caf/standard-interface/usage-popover-low.webp "20% left or less: the row and the ring's dot turn to the caution colour")

**Low.** A window with **20% left or less** is in the caution colour: its
bar, and its percent. The ring's dot is caution.

![A limit out, and the agent's own word for one](/caf/standard-interface/usage-popover-out.webp "Opus refused until the week resets: the warning colour. The week, near its limit at 50%: Claude's word")

**Out.** A window with **10% left or less**, or refused, is in the warning
colour, and so is the dot.

**The agent's word.** Claude also says, of each window, whether it still
takes turns in it. That's shown in words, in place of the pace:

| The agent says | Shown as |
| --- | --- |
| It warns the window is near its end (`Warning`) | *Near the limit*, in the caution colour |
| It refuses turns until the window resets (`Refused`) | *Refused until it resets*, in the warning colour, with *0%* left |
| Nothing more (`Fine`) | The pace |

The colour of the bar and the percent comes only from what's left, never
from the agent's word: Claude may warn of a window at 50% used, as here,
and that's no reason for a dot. A refused window always has nothing left, so
it's always out.

Limits are information only. Nothing in the composer changes for them, and a
message is never held back: a turn the agent refuses for its limits fails in
the transcript as [the transcript](/caf/standard-interface/transcript.md) shows.

![Extra usage in use](/caf/standard-interface/usage-popover-extra.webp "The five hours used up, and extra usage paying for what goes on")

**Extra usage.** When the account goes on beyond its plan, paid for as it
goes, the limits section ends with *Extra usage in use*, in the caution
colour, and *Beyond your plan, paid for as you go.* Nothing is shown when it
isn't in use, or the agent hasn't said.

### Pace

A window's **pace** is how much of it has gone by: where its use would be if
it were used evenly from start to reset. Drawn on a bar of what's left, it's
a line at 100% less the pace.

- **Ahead of pace**: more is used than the pace. At this rate, it runs out
  before it resets.
- **Under pace**: less is used than the pace.
- **On pace**: exactly the pace.

The pace words are muted: how much is left, and its colour, carry the
warning. A window with no reset, or one CAF doesn't know the length of, has
no pace: no line, and no pace words. Pace and resets move with the clock, not
with news, so the app draws them again as time passes.

### Times

Every time in these parts is given the same way:

- **how long until**: *under a minute*, *42 min*, *1 h 52 min*, *1 h*,
  *1 d 10 h*, *4 d*;
- **a moment**, in one form: the clock alone if it's today, *23:40*; the
  day of the week and the clock if it's within a week, *Mon 09:00*; else
  the date and the clock, *14 Nov 09:00*. The clock is the user's, 24-hour;
- **when a reset is**: *resets in 1 h 52 min* in the popover, and on the
  usage page with its moment too, *Resets in 1 d 10 h, at Mon 09:00*;
- **when something was heard or fetched**: *as of 22:42*, *as of Fri 18:05*;
  *fetched at 09:14*, *fetched Fri 09:14*.

A window whose reset has come but that CAF hasn't forgotten yet, as may
happen for a few minutes after the computer wakes, says *Resetting* in place
of when it resets. Once CAF forgets it, it's gone, until the agent says
again.

### Numbers

Every number in these parts, and on the usage page, is given the same way:

- **tokens**, short: whole under a thousand, *950*; whole thousands up to a
  million, *195K*; then one decimal, *2.1M*, *1.2B*. A tooltip may give the
  count in full, *2,104,391*;
- **money**, in US dollars to the cent, *$1.84*; anything above nothing but
  under a cent, *<$0.01*, so it isn't read as none;
- **prices**, per million tokens: whole dollars bare, *$5*; otherwise as
  many decimals as they need, up to four, and at least two, *$0.50*;
- **shares**, as percents: whole from 10% up, *76%*; one decimal under 10%,
  *3.0%*, *0.9%*; and *<0.1%* for a sliver above nothing;
- **what's left of a limit**, and the pace: whole percents, as CAF gives
  them.

## The usage page

![The usage page, by cost](/caf/standard-interface/usage-cost.webp "The usage page: a period, a total, a share per agent, a chart, totals and shares; the breakdown is further down")

**Suggested.** One page, with a header and a body that scrolls. The header
holds, in order:

- **Usage**, the page's name, then which agents and which apps it covers:
  *All agents*, *All apps*, each a menu to pick some;
- **the period**: *Past 24h*, *7 days*, *30 days*, *90 days*, with *7 days*
  chosen when the page opens;
- **what it measures**: *Cost*, *Tokens* or *Limits*;
- **Refresh**, and **Close** if the page is shown over something.

Only a viewer with the `usage` right has the page, as it covers every CAF
app on the computer, not just this one.

**The period asked for.** Each period ends now and is made of whole days, or
whole hours for *Past 24h*, in the user's own time zone, today's (or this
hour's) included. So the query (`UsageQuery`) is:

- `zone`: the user's own time zone;
- `by`: `Hour` for *Past 24h*, `Day` for the rest;
- `since`: the start of the day (or hour) 6 before today's for *7 days*, 29
  for *30 days*, 89 for *90 days*, 23 hours before this one for *Past 24h*;
- `until`: now;
- `apps` and `agents`: those picked in the menus, or empty for all.

That gives 7 days of bars for *7 days*, today's partly done. A period of a
fixed length back from now, such as *now less 7 × 24 hours*, would cut the
first day in two, and give 8 bars.

### Cost and Tokens

The body, from the top:

1. **The total**, large: *$50.88*, or the tokens, *64.8M*. Under it, how
   many chats it covers, and for cost how it was come by:
   - *54 chats · API estimate*, with an ⓘ whose tooltip says *What agents
     reported, and for turns they reported nothing, an estimate at the
     models' API prices. On a plan, it isn't what you pay.*, if any of it was
     estimated;
   - *54 chats · as agents reported it*, if none was;
   - and *· 0.9% of tokens had no price, and aren't in it*, if any had none.
     If none had a price and none was reported, that's all it says, under
     *$0.00*: *· 100% of tokens had no price, and aren't in it*.
2. **Shares**, *By agent* or *By app*: each with its colour, mark, name and
   chats, its cost or tokens, and under it *76% of cost · 44.4M tokens*, or
   when measuring tokens, *69% of tokens · $38.64*. Biggest first.
3. **A chart**, stacked by the same: *Daily cost, by agent*, or when
   measuring tokens, *Daily processed tokens, by agent*; *Hourly* in place of
   *Daily* for the past 24 hours, and *by app* when split by app. Every day or
   hour of the period has its place, empty ones too.
4. **Totals**:

   | Label | What it is |
   | --- | --- |
   | *Processed tokens* | Every token, `total` of the summary's `Tokens` |
   | *Cached input* | `cache_read` |
   | *Uncached input* | `input` |
   | *Cache writes* | `cache_write` |
   | *Output* | `output`, thinking included |
   | *Cache savings* | The TypeScript SDK's `cacheSavings`, with an ⓘ whose tooltip says *What reading input from the cache saved, against reading the same input fresh, at the models' prices.* |

   *Cache savings* is each cached token at its model's input rate, less what
   it cost read from the cache, fast mode's multiplier included, for the
   models that have a price. It's left out when nothing priced was read from
   the cache (`cacheSavings` is null).
5. **Three bars of shares**:
   - *Tokens by type*: *Input*, *Cache read*, *Cache write*, *Output*.
   - *Cost by type*, the same kinds, from the TypeScript SDK's `costByKind`: each kind
     of token at its model's rate, fast mode's multiplier included, for the
     models that have a price, with the note *At the prices the models have:
     an agent's reported cost isn't split by type.* It's left out when no
     model has a price (`costByKind` is null).
   - *Cost by speed*: *Standard*, *Fast mode*, by the buckets' `fast`.

   Their parts are tones of one colour, never an agent's or an app's.
6. **Breakdown**: a table by *Model*, *App* or *Day* (*Hour* for the past 24
   hours). Below.

![The same page in tokens](/caf/standard-interface/usage-tokens.webp "Tokens: the same page, measured in tokens")

**Tokens** is the same page measured in tokens: the total, the shares, the
chart and the breakdown's order are by tokens instead of cost.

![By app](/caf/standard-interface/usage-by-app.webp "Split by app: the shares and the chart's stacks are each CAF app's")

**By app** splits the shares and the chart by the app each turn came from,
from the ledger every CAF app on the computer shares.

![The past 24 hours](/caf/standard-interface/usage-hourly.webp "The past 24 hours, by hour")

**Past 24h** goes by hour: *Hourly cost, by agent*, hours on the chart, and
*Hour* in the breakdown.

### Names and colours

**Up to the app**, within these rules. Agents are named as
[above](#where-the-numbers-come-from). An app is named by its host's name
(*clackatoo*). A model is named by its name, *Opus 5.5*, as the agent's
profile names the agent's id for it (`Summary.names`, which the TypeScript
SDK's `modelName` looks up), and by the id itself, as it comes
(*gpt-6.1-sol*), where it has none, as for an agent whose profile doesn't
name its models. Where the id matters, as a price goes by it, the id
follows the name: its tooltip in the breakdown, and in brackets where a
price names the model. Each agent and app has a colour of its own, the same
wherever it appears. It's identity, not a colour role, so, as the
[overview](/caf/standard-interface/overview.md) says, it appears only in marks
and to tell them apart in charts: the dot by a share, the chart's stacks, a
row's bar in the breakdown. It's never on text, controls or edges, which is
why the *All agents* and *All apps* menus carry no coloured dots.

### The breakdown

![The breakdown by model, a price opened](/caf/standard-interface/usage-price.webp "By model: a model opened shows its price and where it came from")

**By model**, the default: *#*, *Model*, *Cost*, *Share*, *Tokens*, biggest
first, each model by name, with its agent's mark and a bar of its share in
the agent's colour.

- A model whose tokens no price covered, and whose turns reported no cost,
  has *Unpriced* in place of its cost; one with some such tokens has its
  cost, and *1.2M unpriced* beside it. Under the table: *Unpriced: tokens on
  a model with no known price, from turns whose agent reported no cost. They
  aren't in the cost.*
- Under that: *Click a model for its price, or to set your own.*

**A model's price.** Clicking a model opens its price under its row: where it
came from, the rates *In US dollars per million tokens* (*Input*,
*Cache read*, *Cache write*, *Output*, and *Fast mode* as a multiplier, *×2*,
if it has one), and buttons. Where it came from:

| Price | It says | Buttons |
| --- | --- | --- |
| The user's own | *Your own price.* | *Change your price*, *Remove your price* |
| LiteLLM's list, as fetched | *From LiteLLM's price list, fetched at 09:14.* | *Set your own price* |
| The list that came with the app | *From the price list built into the app.* | *Set your own price* |
| None | *No price is known for Opus 4.8 (`claude-opus-4-8`), so turns on it that didn't report a cost aren't counted in the cost.* | *Set your own price* |

If the list names the model otherwise than the agent does, it says so:
*…, as `anthropic/claude-opus-5-5`.*

*Set your own price* opens a form of the four rates and the fast mode
multiplier, headed *Your own price for Opus 5.5 (`claude-opus-5-5`), in US
dollars per million tokens. The other apps on this computer that share your usage record
use it too.*, with *Cancel* and *Save*. *Remove your price* takes the user's
own away: a list's price applies again if a list has one, and otherwise the
model is unpriced. The viewer can't tell beforehand which, as a summary
holds only the price that was used.

A price set or removed applies to every figure at once, as costs are
estimated with the prices of now, and reaches the other apps within the
hour. If it isn't done, the form stays, with why under it, in the warning
colour:

| CAF answers | It says |
| --- | --- |
| `PriceNotSet`, with the system's words | *Your price couldn't be saved, and prices are as they were:* then the system's words |
| `NoLedger` | *This app keeps no record of usage, so it can't keep a price of your own.* |
| `NotAllowed` | *You may not set prices here.* |
| `Gone` | *The app has shut down, so nothing was saved.* |
| The link dropped before the answer | *The link to the app dropped before the answer came, so your price may not have been saved.* |

![The breakdown by app](/caf/standard-interface/usage-breakdown-app.webp "By app: each app's chats, cost, share and tokens")

**By app**: *#*, *App*, *Chats*, *Cost*, *Share*, *Tokens*, with
*Click an app to see only its usage.* under it. Clicking an app picks it in
the *All apps* menu, which asks again with only that app (`UsageQuery.apps`).

![The breakdown by day](/caf/standard-interface/usage-by-day.webp "By day, split by agent: a column per agent")

**By day**: a row per day of the period, newest first (*Sat, 21 Nov*), empty
days too, then a column per agent, *Total*, and *Tokens* (or *Cost*, when
measuring tokens). A day an agent didn't work is *–*; a day nobody worked
has *–* in every column and a total of *$0.00*.

![The breakdown by day, split by app](/caf/standard-interface/usage-by-day-app.webp "By day, split by app: a column per app")

**Split by agent** or **Split by app** switches the columns.

### Limits

![The limits](/caf/standard-interface/usage-limits.webp "Each agent's limits: a card per window")

**Limits** shows the agents picked in the *All agents* menu (all of them, at
first), each with its mark, name and whether it's signed in, and the
account's limits as the agent last said them. The *All apps* menu and the
period go, as limits belong to neither. There's no Refresh: limits come only
as the agent works, and CAF can't ask for them. A card per window:

- **the label**, and **what's left**, large: *72% left*;
- **a bar of what's left**, with the pace's line;
- the agent's own word, if it has one: *Near the limit*, *Refused until it
  resets*;
- **the pace**: *Under pace · 38% of the window left*;
- **when it resets**, and **when it was heard**: *Resets in 1 h 52 min, at
  23:40*, and *as of 22:42*.

A fine window's bar is muted, so low and out stand out.

An agent with no limits heard says so plainly:
*Codex hasn't said what its limits are. Only some agents report them, and
only as they work. Its usage is still counted under Cost and Tokens.* At the
foot: *Limits are as each agent last said, so they have no period. Bars show
what's left; the line on each is where even use would have it now.*

![Limits low and out](/caf/standard-interface/usage-limits-low.webp "Low and out, in the caution and warning colours, as in the popover")

**Low and out** take the same colours as in the popover, and *Extra usage in
use*, in the caution colour, goes in the agent's heading when it is.

The limits here are the same as in the popover: a viewer without the `usage`
right, who has no usage page, still sees them in the chat.

## The page's states

![Reading again](/caf/standard-interface/usage-refreshing.webp "Reading again: the last figures stay up")

**Reading.** The first time, the page says *Reading usage…*. Read again, by
Refresh or a new period, the last figures stay up, with
*Reading again… the figures may still change.* and a spinning Refresh.

![Part of the record unreadable](/caf/standard-interface/usage-partial.webp "A file of the record couldn't be read: the figures are short, and it says which")

**Partly unreadable.** If any file of the usage record couldn't be read, the
figures are shown, and above them, in the warning colour:
*Some of the usage record couldn't be read, so these figures are short:
eyespy/2026-10.jsonl.zst.*, naming each file. If CAF names `.`, the record's
folder itself couldn't be read, and it says instead *The usage record's
folder couldn't be read, so these figures are short.* The page is never
quietly short.

![No chats in the period](/caf/standard-interface/usage-empty.webp "Nothing in the period")

**Nothing yet.** A period with no turns in it says
*No chats in the last 7 days.* (or *the past 24 hours*), with *$0.00*,
*0 chats*, and *Nothing to chart yet* where the chart goes. That includes a
computer with no usage record yet at all: CAF reads a missing record as
nothing used.

![Usage couldn't be read](/caf/standard-interface/usage-failed.webp "The summary couldn't be read at all")

**Couldn't read.** If the summary can't be made at all, the page shows only
why, in the warning colour, starting *Usage couldn't be read:*

| CAF answers | It says |
| --- | --- |
| The link dropped before the answer | *Usage couldn't be read: the link to the app dropped before the answer came.* |
| `Gone` | *Usage couldn't be read: the app has shut down.* |
| `BadQuery::Zone` | *Usage couldn't be read: the time zone Europe/Lndn isn't one the app knows, so it can't say where days begin.* |
| `BadQuery::Period` | *Usage couldn't be read: it can't be summed up over that period.* |
| `NotAllowed` | *Usage couldn't be read: you may not see usage here.* |

The periods above never give `BadQuery::Period`, and a viewer without the
`usage` right has no page to get `NotAllowed` on, but the words are there for
an app that strays. An app that keeps no usage record (`NoLedger`) isn't
failing: it says, muted, *This app keeps no record of usage, so there's
nothing to show here.*

## In an app not written in TypeScript

The helpers this page names are the TypeScript SDK's. caf-core, in Rust,
has `LimitWindow::pace`, `WindowKind::length`, `Tokens::total`, `Tokens::add`
and `Spend::cost`, and no more. An app that draws natively, in Rust or
anything else, does the rest itself, by these rules, so it says exactly what
every other app says:

| Helper | The rule |
| --- | --- |
| `left` | What's left of a window, as a whole percent: 0 if `Refused`, else 100 less `used`. |
| `lowness` | *out* at 10% left or less (`OUT_LEFT`), *low* at 20% left or less (`LOW_LEFT`), *fine* otherwise. So a refused window is always out. |
| `lowest` | The window with the least left; on a tie, the first of them in the order CAF gives the windows. None if there are none. |
| `label` | `FiveHours`: *5-hour*. `Week`: *Weekly*. `ModelWeek`: *Weekly ·* and the model's name with its first letter made a capital, *Weekly · Opus*. `ExtraWeek`: *Weekly · extra included*. `Other`: the agent's own name for it, as it comes. A kind newer than the app knows: the kind's own name, as CAF sends it. |
| `pace`, `length` | Use caf-core's `LimitWindow::pace` and `WindowKind::length`: a whole percent of the window gone by, rounded half up; none with no reset or no length. |
| `total` | Every token: input, cache read, cache write and output. Thinking is part of output, so isn't counted again (`Tokens::total`). |
| `cost` | Reported and estimated cost added up (`Spend::cost`, or a bucket's `reported` plus `estimated`). |
| `totals` | Every bucket's tokens, reported and estimated cost, unpriced tokens and turns, added up. |
| `group` | The buckets by app, agent, model or fast mode (*fast* or *standard*), each group's figures added up. Biggest first by the measure shown (cost, or tokens); on a tie, by the other measure; then by key, compared character code by character code, whatever the locale. By period: every period of the query, in time order, empty ones too. |
| `split` | Every period of the query, in time order, empty ones too, each with its buckets grouped as `group` does, by cost. |
| `price` | A model's price in a summary: the entry `Summary.matched` pairs with the agent's id for the model, found by name in `Summary.prices`; none if either is missing. |
| `modelName` | A model's name to show: the name `Summary.names` pairs with the agent's id for it, else the id itself. |
| `costByKind`, `cacheSavings` | As [Cost and Tokens](#cost-and-tokens) says: per bucket, at its model's `price`, times the price's `fast` multiplier if the bucket's `fast` is on; buckets with no price left out. `costByKind` is none if nothing was priced; `cacheSavings` is none if nothing priced was read from the cache. |

A period starts where the query's zone says it does: an hour at the top of
the zone's hour, a day at the first moment of its date there, which is
midnight unless the clocks skip it, so a day is 23 or 25 hours across a
change of clocks. A bucket belongs to the last period starting at or before
its `start`.

## What CAF tells the app

| What's shown | Where it comes from |
| --- | --- |
| The ring and the context row | `Usage.used` of `Usage.size`, on the chat. |
| *Cost so far* and its line | The chat's `spend` (`Spend`): `cost()`, `reported`, `estimated`, `unpriced` and `turns`, sent again (`Change::Spend`) whenever it changes. |
| *Tokens processed* | `Spend.tokens`, added up with the TypeScript SDK's `total`. |
| The limits | `AgentStatus.limits` (`AccountLimits`): each `LimitWindow`'s `kind`, `used`, `resets`, `state` (`Fine`, `Warning`, `Refused`) and `heard`. |
| A window's name | The TypeScript SDK's `label`. |
| What's left, low, out | The TypeScript SDK's `left` and `lowness`, at `LOW_LEFT` (20) and `OUT_LEFT` (10). |
| The ring's dot | `lowness` of the TypeScript SDK's `lowest`. |
| Pace | The TypeScript SDK's `pace` (caf-core's `LimitWindow::pace`), and `length`. |
| *Extra usage in use* | `AccountLimits.extra_usage`: `in_use`, `heard`. |
| *Open usage*, the page, prices | The viewer's `usage` right (`Rights::usage`, given with `ViewerRules::usage`). |
| The page's figures | A `Summary` for a `UsageQuery` (`since`, `until`, `zone`, `by`: `Day` or `Hour`; `apps`, `agents`), asked for with `FromViewer::Usage`. |
| Totals, shares, the chart, the breakdown | The summary's `buckets`, summed by the TypeScript SDK's `totals`, `group` (by `app`, `agent`, `model`, `period`, `fast`), `split`, `cost` and `total`. |
| *Cost by type*, *Cache savings* | The TypeScript SDK's `costByKind` and `cacheSavings`, at the prices the summary used. |
| Chats | `Summary.chats`: `all`, `by_app`, `by_agent`. |
| A model's name | The TypeScript SDK's `modelName`, from `Summary.names`: the name each model's lines were recorded with, or the one its agent's profile gives now. A turn's own record names its models too (`TurnUsage.models`' `ModelTokens.name`). |
| A model's price | The TypeScript SDK's `price`, from `Summary.prices` and `matched`: a `PricedModel`'s `price` (`ModelPrice`) and `layer` (`Own`, `Fetched`, `Bundled`), and `Summary.fetched`. |
| Setting a price | `FromViewer::SetPrice`, answered `Done`, `PriceNotSet`, `NoLedger`, `NotAllowed` or `Gone`. |
| *Some of the usage record couldn't be read* | `Summary.unreadable`: file names, or `.` for the folder. |
| *Usage couldn't be read* | `Outcome::Gone`, `BadQuery` (`Zone`, `Period`) or `NotAllowed`, or the link dropping. |
| *This app keeps no record of usage* | `Outcome::NoLedger`. |
