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

Concepts

Single-page view · as markdown

The Core

CAF / Concepts

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

Events in, directives out #

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

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

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

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

Drivers #

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

DriverIts job
AgentStarts adapter programs and carries their bytes, knowing nothing of which agent it runs
TimerWakes the core at the one time it asked for
PolicyAnswers "may the agent do this?"
ViewerTells the program's views that a chat changed
StorageSaves and loads chats (a later feature)
SetupInstalls agents and runs their sign-in commands, as each one's recipe says

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

Why no I/O #

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

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

What the core promises #

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

Chats, Turns, and Items

CAF / Concepts

CAF keeps its own record of every chat, in one format for every agent. The agent keeps its own transcript too, as its memory; CAF's record is what happened and what the user saw. Each adapter's profile translates what it sends into this format as it arrives.

Chats, turns, and items #

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

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

LifeMeaning
WaitingNot sent yet: the chat is opening, or another turn is running
RunningThe agent is working on it
StoppingStop was asked for, and the agent hasn't finished stopping
FinishedThe agent finished
StoppedThe user stopped it
FailedIt went wrong, with the reason and what the user can do
Cut offThe program restarted while it ran

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

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

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

What a turn spent #

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

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

The program's own items #

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

Following a chat #

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

How a view outside the program follows a chat, and why every one ends with the same chat, is in Viewers.

Tool Calls

CAF / Concepts

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

CAF runs the tools that matter #

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

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

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

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

Where a call came from #

A call's origin says whose tool it is:

OriginThe tool
CafOne of CAF's own: Read, Edit, Write or Bash.
AppOne of the app's own tools, which CAF serves for it. Later.
ServerA tool of an MCP server the app gave the chat, by the server's name and the tool's.
AgentThe agent's own, by the agent's name for it, such as WebSearch.
NotRecordedSaved before CAF kept where calls came from.

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

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

What it does, and what it was given #

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

ActionDoes
ReadReads a file, and which lines, if not all.
EditChanges part of a file.
WriteWrites a whole file, new or over what was there.
RunRuns a command, in a folder, and whether in the background.
ToolAnything else, by its name: its input says the rest.

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

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

What it gave back #

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

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

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

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

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

Caps #

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

WhatMost keptWhich part
Text64 KBits start
Output64 KB, each line's ending counting as a byteits end, in whole lines of at most 16 KB
Diff256 KB of its lineswhole hunks, then how many more there were (more)
Image2 MBall of it, or none, with its size
locations256the first, then how many more (locations_cut)
input64 KB of its JSONits start, as a string (input_cut)
Unknown64 KB of its JSONits start, as a string in raw (its cut)

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

Output while it runs #

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

Where it is #

A call's status:

ToolStatusMeans
PendingNot started yet: reported, or waiting for the policy.
AskingWaiting for the user: its permission question is open.
RunningRunning.
DoneFinished.
FailedWent wrong: why is a Text piece, or its turn failed under it.
RefusedNot allowed, by the policy or the user. It never ran.
CancelledStopped: the user stopped its turn, or the agent cancelled it.

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

Who allowed it #

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

DecisionMeans
UndecidedNot decided yet.
NotAskedIt needed no permission, such as a call the agent made without asking.
AllowedAllowed, by the policy, with its reason if it gave one, or by the user, with the option they chose.
RefusedRefused, likewise.
NotRecordedSaved before CAF kept who decided.

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

Drawing them #

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

Serving Tools

CAF / Concepts

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

What the tools themselves do is CAF's own tools.

Note

Windows isn't supported yet: serving needs Unix sockets.

The relay #

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

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

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

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

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

let mut config = Config::new(Host::new("eyespy", "0.4.0"), vec![claude]);
config.tools.relay = Relay::ThisProgram;
RelayWhat CAF runs as the relay
NoneNothing: no tools are served. The default.
ThisProgramYour program, which must call relay_if_asked.
Command(SpawnCommand)Another program that relays as caf-relay does.

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

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

Choosing a chat's tools #

A chat gets no tools unless you give it some:

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

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

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

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

How a connection finds its chat #

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

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

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

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

Long calls, and cancelling #

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

Cancelling. A call ends Cancelled (see Where it is), and its stopped_by says who stopped it:

StoppedByMeans
UserThe user stopped the turn, or closed or deleted the chat: CAF cancels the call, stops its work, and answers the model that the user stopped it. Or the agent gave up on the call as the user stopped the turn: CAF stops its work, and answers nothing, as MCP says.
AgentThe agent cancelled it while its turn wasn't being stopped, or its relay went: it closed, or a newer one replaced it. CAF stops its work, and answers nothing, as MCP says.

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

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

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

Background jobs #

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

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

It ends in one of these ways:

HowEnds
By itselfDone or Failed, and the agent hears of it in a notice turn, worded by the driver: at once, or after the turn running
TaskStop, from the modelCancelled, stopped_by Agent. TaskStop needs no permission, and stops only jobs of its own chat: for any other number, the model is told "No task {id} in this conversation"
The chat closed or deletedCancelled, stopped_by User
The chat put away, or CAF shutting downFailed, stopped by no one

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

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

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

Losing the tools #

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

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

Nothing is noted when the chat is closing anyway.

CAF's Own Tools

CAF / Concepts

CAF gives an agent its own tools in place of the agent's: Read, Edit, Write and Bash, and TaskStop with Bash. How they reach the agent is Serving tools; what CAF records of each call is Tool calls. This page is what the tools themselves do.

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

Note

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

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

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

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

Read #

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

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

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

Edit #

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

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

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

Write #

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

Read before you change #

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

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

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

Encodings and line endings #

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

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

Bash #

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

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

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

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

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

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

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

Background jobs #

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

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

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

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

Your editor and your terminals #

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

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

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

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

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

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

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

Agents and Profiles

CAF / Concepts

The program describes itself #

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

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

Profiles #

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

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

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

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

CheckWhat CAF does
This version was checkedEvery feature the profile lists is on
A newer version than any checkedThe last checked profile, with its risky features off, and its tools turned off the same way
A different adapter, or none namedThe cautious profile, and no session is opened

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

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

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

An agent has only your tools #

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

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

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

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

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

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

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

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

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

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

Where an agent stands #

A program offers each agent in one of two ways:

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

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

Installing #

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

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

The setup driver does the work: the core decides, from the recipe, what to install, and the setup driver downloads, checks and writes. It's one of the core's drivers, so every install is recorded and replays like everything else.

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

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

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

Signing in #

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

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

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

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

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

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

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

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

Settings #

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

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

Sharing an adapter #

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

Viewers

CAF / Concepts

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

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

A link, in order #

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

Pictures and changes #

Each chat keeps a numbered list of small changes (see Following a chat). A viewer following a chat keeps a copy of it, and the number of the last change it has.

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

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

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

Applying a change #

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

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

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

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

Versions #

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

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

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

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

Opening is the host's decision #

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

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

Peios Learn — documentation for Peios software.

Built with Trail.