Peios Learn
Documentation

Peios

Peios Peios Kernel Universal Directory Project

Developer Tools

Trail Acta Provium clackatoo CAF GCSL Pekit

Applications

Framewright

Standards and Conventions

Standards and Conventions Peios Specifications
CAF

Getting Started

Single-page view · as markdown

What Is CAF

CAF / Getting Started

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, and clackatoo is its first user.

What it does for you #

Coding agents speak the Agent Client Protocol (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.
  • 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, 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: 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. Its types are generated from CAF's own, and shared test cases hold it to exactly what the core does.
  • The debugger, 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 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, 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 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: 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 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

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.

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) 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.

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.

Watch it #

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

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.

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 #

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 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.

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:

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

Each line after it is one event, in order:

{"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:

{"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:

DirectiveWhere it goes
AgentAgentDriver::apply
TimerTimerDriver::wake_at
Policy: decideThe policy, whose answer comes back to the core
Policy: withdrawnStops that decision
ViewerWakes the chat's watches
SetupSetupDriver::apply, whose reports come back to the core
ReportThe 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

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 #

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 #

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:

StateMeaning
HostYou start it with your own command
UnknownCAF 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:

StateMeaning
UnknownNothing has said yet
SignedOutSigned 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 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).

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:

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 #

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:

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:

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

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:

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:

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). 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 #

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 #

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:

WhyMeaning
NotFoundIt isn't on that shelf.
InUseAnother 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.
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:

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:

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.

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:

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:

#[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) 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, 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:

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:

<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).

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

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:

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 #

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:

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:

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

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.

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.

~/.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, 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 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.

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.

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 #

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:

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

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), 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:

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), 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:

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

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. It isn't on npm yet.

The backend #

Start CAF as in A Chat on Tokio. 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:

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:

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:

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 #

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 #

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.typeWhat it means
RefusedThe core refused it, and nothing changed. why.value says why, such as QueueFull.
NotAllowedThe host doesn't let viewers do this.
GoneCAF has shut down, or is shutting down: nothing was done.
CannotRestoreA saved chat couldn't be restored: see Saved chats.
UnknownIt went in a way this version of the SDK doesn't know, from a later CAF. why.value.outcome is its name.
DisconnectedThe 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:

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 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:

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.typeWhy
NotFoundIt isn't on that shelf.
InUseAnother program has it open: a chat is never open twice.
NewerA newer CAF saved it, in a version of the format (why.value.value.version) this one can't read.
DamagedIts save is damaged: the value says how.
AppDataThe app can't read the data it saved with it: the value says why.
StoreThe 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. 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.

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.

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.

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.

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:

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.

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:

<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:

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:

<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):

<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

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. Its page is a web app in ts/debugger, which has to be built first:

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).

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

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);
  • 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 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.

[[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"
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, 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 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:

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:

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:

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

See Usage.

The Agents panel shows each agent's account limits 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:

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:

~/.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:

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.

Peios Learn — documentation for Peios software.

Built with Trail.