Robi documentation
Robi is a desktop coding assistant: a Rust core that runs an agent loop against a local workspace, and a Solid front end that renders the conversation.
New here? Start with the Quickstart.
Guides
Task-focused pages. Each one gets you to a result.
- Quickstart — run the app, the local API, and your first message.
- Using an editor — open changed files in the editor you already use.
- Releases — how a push to
mainopens the version bump.
Concepts
Why Robi behaves the way it does.
- How Robi works — the crate layers, the loop, and the transcript.
- Approvals — per-call approval, the policy floor, and grants.
- Sessions and persistence — saved chats, the store, and settings.
- Skills — reusable instructions Robi loads on demand.
- Subagents —
exploreandgeneralchildren. - MCP — tools that come from outside Robi.
Reference
Lookups. Exact keys, names, and paths.
- Tools — every built-in tool and when it pauses.
- Configuration — keys in
config.tomlandsecrets.toml. - File locations — the
~/.robilayout. - HTTP API — the
robi-apiroutes and the event stream.
Project internals
Everything below this point is for contributors. These pages are the plan of record and the design decisions behind the code, not a description of behavior a user sees. Read them to build a milestone; read a Concept or Reference page to use the app.
- Roadmap — what Robi ships, in what order, and the open decisions.
- Design docs — one page per subsystem, grouped by the module it describes: Core, Providers, Shell, Persistence, Tools, Review, Reach, Compression.
- Discovery notes — research that fed a design, kept as an appendix: Skills discovery.
How these docs are organized
Guides teach, Concepts explain, and Reference states facts — one job per page.
Internals are separate so the design docs can stay spec-shaped (problem,
decision, rejected alternatives, interfaces, failure modes) without dressing up
as user documentation. Every page in this book is listed in SUMMARY.md; a page
that is not listed does not render.
Quickstart
Get Robi running and send your first message. Setup happens entirely in the app: open it, open a workspace, set up model providers, choose your default model, then start working. Robi is a desktop app — a Tauri window that starts the local API in the same process.
Install the app
Download the latest build from the releases page and open it.
Run from source
To build it yourself instead, you need:
- Rust (a recent stable toolchain) and Cargo.
- Node.js and pnpm.
pnpm tauri dev
The Vite dev server listens on port 1430. The API binds 127.0.0.1:1431, or
the next free port when that one is taken, and the window reads the bound origin
before it talks to the API.
To restart the API without rebuilding the window, skip the in-process server:
pnpm tauri:external-api # sets ROBI_EXTERNAL_API=1, webview uses the Vite /api proxy
make dev-api # run beside it
pnpm dev alone serves the web UI in a browser and does not start the API; run
make api alongside it. A packaged build ignores the flag.
1. Open the app
On first launch there are no workspaces, so Robi opens the Workspaces page.
2. Open a workspace
Click New workspace and pick a directory in the system folder dialog. The name is taken from the folder. Sessions stay with that folder, and the agent works from its root. You can add another at any time: Manage workspaces… in the workspace dropdown in the top bar opens the Workspaces page, where New workspace lives.
3. Set up model providers
Open Settings (it opens on General), then Model Providers.
Each provider has an Enabled switch and an API key field. Type a key and
it saves when the field loses focus; the status line reads Saved. The server
never returns the value, so a saved key shows as •••••••• with the hint A key
is saved. Enter a new value to replace it.
| Provider | Model ids | Extra |
|---|---|---|
| OpenCode Go | ocg_ | Optional Base URL |
| Anthropic | ant_ | |
| DeepSeek | dsk_ | Optional Base URL (default https://api.deepseek.com) |
An optional Brave API key under Web search enables web_search; each
search waits for approval.
Keys are written to ~/.robi/secrets.toml (mode 0600) and other settings to
~/.robi/config.toml — you never hand-edit these; the UI does it. See
Configuration for every key.
4. Set default model preferences
Open Settings → General → Model Defaults. Pick a Global model and reasoning effort (low / medium / high), then optionally override the model and effort for the Agent, Ask, and Plan modes. Any mode left unset uses the Global model and effort.
5. Start working
Click New chat, then describe the task in the composer (Describe a task or ask a question). Before sending you can pick a mode (Ask, Plan, Agent) and override the model and effort for that session only. A session is created on the first send.
The assistant reads files, searches, and proposes edits. In agent mode it can write files and run commands, always inside the safety model:
- a read inside the workspace is free;
- an edit to a protected path, a shell command that leaves the default sandbox, or a web fetch to a new host pauses for your approval;
- the approval bar shows the exact arguments, not a summary.
See Approvals for what does and does not ask.
Common commands
| Task | Command |
|---|---|
| Desktop app | pnpm tauri dev |
| Local API | make api |
| Restart the API on Rust changes | make dev-api |
| Web-only Vite dev | pnpm dev (port 1430) |
| Test the Rust workspace | make test |
| Lint and format | make lint, make fix |
| Build these docs | make docs, make docs-serve |
Next
- How Robi works — the layers and the loop.
- Tools — what the assistant can call.
- Configuration — every setting and environment variable.
The terminal app
robi is the same agent as the desktop app, in a terminal. Same sessions, same
tools, same settings; it links the same crate and builds the same state the local
API builds. It does not talk to the API over HTTP and opens no port.
Install
Download the tarball for your machine from the releases page:
| Machine | Asset |
|---|---|
| Apple Silicon macOS | robi-vX.Y.Z-aarch64-apple-darwin.tar.gz |
| x86_64 Linux | robi-vX.Y.Z-x86_64-unknown-linux-gnu.tar.gz |
tar -xzf robi-vX.Y.Z-aarch64-apple-darwin.tar.gz
sudo install -m 0755 robi-vX.Y.Z-aarch64-apple-darwin/robi /usr/local/bin/robi
The macOS binary is not notarised, so a downloaded copy is quarantined and the system refuses to run it. Clear the flag once:
xattr -d com.apple.quarantine /usr/local/bin/robi
The Linux tarball is built on Ubuntu 22.04, so it needs glibc 2.35 or newer: 22.04 and 24.04 both run it.
What Linux needs
The default sandbox is bubblewrap. Install it, or every sandboxed command is
refused:
sudo apt install bubblewrap
The container sandbox is separate and optional. It needs a Docker daemon and
the sandbox_mechanism = "container" setting; without either, the default
mechanism runs and the container setting is not used.
Run it
robi # the current directory
robi ~/code/app # a different workspace
The path decides which sessions you see. A path with no workspace behind it is a
question, not a guess: y creates a workspace there, n opens the workspace
switcher.
robi --help # usage
robi --version # robi X.Y.Z
Which database it opens
robi opens the desktop app’s database, so the sessions you see are the sessions
the app shows:
- A debug build, which is what
cargo runfrom a checkout gives you, opens the app’s dev database (~/Library/Application Support/com.github.cgund98.robi/dev/robi.dbon macOS), the same onepnpm tauri devuses. - A release build opens the app’s own database
(
~/Library/Application Support/com.github.cgund98.robi/robi.db).
ROBI_DATABASE_URL overrides both:
ROBI_DATABASE_URL=sqlite:///Users/you/.robi/sessions.db?mode=rwc robi
Settings, secrets, logs, and the UI state live under ~/.robi, the same
directory the app uses. See File locations.
Two terminals
Two terminals in one workspace are fine, and so is one beside the desktop app. Nothing is locked at startup: a lock covers one session, and it is taken when that session is used.
What that means in practice, for a chat another process has open:
- It renders. Text, tool names, arguments, and statuses are in the chat database.
Each tool result comes back as
open in another process (pid 4812)instead, because the bytes are in that session’s own blob file and only one process may open it. - Sending is refused, with the pid in the footer and your draft left in place. Approving a tool call is refused the same way.
- Deleting it is refused.
- A turn that pauses for approval keeps the session until you answer it or quits, so the other process cannot resume a call you are still looking at.
Work on a different chat in each terminal, or take turns. Two processes editing
the same workspace file are safe: the write tools take a per-file lock and wait
up to ten seconds for the other one, then refuse with locked rather than
overwrite a change they did not see.
Logs
~/.robi/logs/, one file per start, the same directory the app writes to. The
name is tui-<timestamp>.log, which tells a TUI run apart from the app’s
robi-api- and robi-dev- files in the same directory. Each prefix is pruned on
its own, so a TUI run never deletes the app’s logs. RUST_LOG sets verbosity
(default robi=info).
The file opens with the version, the workspace root, and the database it opened,
so two runs are easy to tell apart. The last line says whether the run finished
or failed. robi flushes the logger before it exits, because process::exit
skips the flush that a normal return would do and the last few lines would be
lost.
The log layer never writes to stderr: a tracing line there would land in the middle of the frame the terminal is drawing. A fatal error that stops the process before the frame exists still prints one line there, because nothing else is watching.
Using an editor
Robi is a coding assistant you run next to an editor. It talks to a model and changes files in the workspace through a sandboxed shell. Your editor is where you read the code, jump around, and keep working after Robi has changed something.
Robi does not replace that editor. It has no buffer, no tabs of open source files, and no keybindings for writing code. Day-to-day editing stays in the program you already use.
Open a changed file
A click on a path name in a tool-call card follows Open externally in Settings → General → Files.
- Under Open externally, put one glob per line.
*matches any run of characters, including/.*.rsmatches every Rust file. An empty list opens every path in Robi’s plain-text peek. - Under Open command, set how a match opens. Leave it empty to use the app your system uses for that file.
- Click the path on an edit card. A path that matches a glob opens outside Robi. Any other path opens in the peek.
The line Robi passes is the first added or removed line in that card. A click with no changed line opens the file without a line.
Point the command at your editor
Open command is one line. {file_path} is the absolute path.
{line} is that 1-based line.
file_open_command = "zed {file_path}:{line}"
That starts zed with one argument, the path and line joined by a colon, the
form Zed’s CLI expects. A few others:
| Editor | Command |
|---|---|
| Zed | zed {file_path}:{line} |
| VS Code | code --goto "{file_path}:{line}" |
| Cursor | cursor --goto "{file_path}:{line}" |
Double quotes group one argument, so a path with a space stays one argument.
The line is not run in a shell. When the click has no line, Robi drops {line}
and a colon immediately before it, so zed {file_path}:{line} becomes
zed /abs/path.
The same key is file_open_command in ~/.robi/config.toml. The full key list
is in Configuration.
Robi waits up to 10 seconds after it starts the program. An editor that is still running then has opened. A program that cannot start, or that exits non-zero inside that window, shows the error on the tool-call card and leaves the peek closed.
How Robi edits
An Agent-mode turn makes changes with shell commands, not a bespoke editor:
| Job | Command |
|---|---|
| Full overwrite | cat > path <<'EOF' … EOF, with the delimiter quoted |
| One exact replacement | a short Python that reads, replaces one occurrence, asserts the count, and writes |
| Delete | ls path, then rm path |
The system prompt carries those forms, and it also tells the model to verify before it reports success. Ask and Plan hold a read-only shell, so they can read and grep but not write.
There is no in-app undo. Because a command is opaque, Robi cannot record which paths it touched, so a turn records no checkpoint. Git is the undo.
See what changed
Robi is not where you review a change. A turn’s edits are on disk as soon as the
command runs, so git diff is the record:
git status --short # which paths this session touched
git diff -- path # what changed in one file
The chat streams every tool call as it happens, so the transcript says what ran
and on which path. To keep or discard work, use git: git checkout -- path
throws one file away, and git stash before a risky turn gives you a clean undo.
See Reviewing changes with git, and Quickstart if you have not run a turn yet.
Reviewing changes with git
Robi edits your workspace directly. There is no review screen inside the app: once a tool call runs, the change is on disk, and the record of it is your git repository plus the tool calls in the transcript.
This is the same loop you would use for a teammate’s branch. Read the diff, keep what you want, throw away what you do not.
See what a session changed
git status --short # paths this session touched
git diff # everything uncommitted, in full
git diff -- path/to/file # one file
The chat helps here: every edit and shell call streams into the transcript as it runs, so you can read which paths a turn touched without leaving the app. Ask the assistant to explain a diff and it reads the same output.
If the workspace is not a git repository, git init first, or ask the assistant
to. Without version control there is no undo, so start one before a large task.
Keep or discard
| Goal | Command |
|---|---|
| Throw away one file’s changes | git checkout -- path/to/file |
| Throw away everything uncommitted | git reset --hard |
| Save the current state before a risky turn | git stash (restore with git stash pop) |
| Keep a change | git add -p then git commit |
| Work on a throwaway branch | git switch -c attempt-1 |
On a new file, git checkout -- does nothing until it is tracked; delete it
with rm or git clean -i instead.
Approvals are not review
Approving a tool call is a decision about running the command, not about
keeping its result. Approving write_file writes the file. The change stays
until git says otherwise.
That distinction is why the diff matters. The approval card says what is about
to happen; git diff says what did.
A turn that went wrong
git status --short— see which paths moved.git diff -- path— read the change.git checkout -- pathorgit reset --hard— revert what you do not want.- Say what went wrong in the next message. The transcript still holds the tool call that made the change.
For a long task, commit before you start and commit again whenever the diff reads correctly. Each commit is a checkpoint you can return to.
Where this is specified
Streamlining roadmap records why the in-app review screen was removed. The API routes it used are still served and documented in HTTP API; nothing in the app calls them.
Next
- Using an editor — open a changed path in your own editor.
- Approvals — what prompts before a command runs.
Setting up MCP servers
The Model Context Protocol (MCP) lets Robi call tools that other programs
provide. Robi is an MCP host (client): it connects to servers you configure,
and each remote tool joins the assistant’s registry as
mcp_<server>_<tool>. Robi does not accept MCP connections from anyone.
MCP tools are registered in agent mode only. Ask and plan keep their built-in tool sets, and subagents never receive MCP tools.
This guide is the walkthrough. For how the host behaves under the hood, see MCP.
If you would rather be walked through it, load the bundled configure-mcp
skill (/configure-mcp, or just ask to add an MCP server). It asks where the
config belongs — global or this workspace — which tool you want to connect, the
transport and its settings, and any secret references, then writes the entry
and tells you to restart the app.
1. Choose an entry point to edit
Two JSON files share one shape:
~/.robi/mcp.json— your servers, available in every workspace.<workspace>/.robi/mcp.json— servers for one project.
Either edit the file directly, or open Settings → MCP. That page lists the servers Robi knows about and their connection state (the same list as the tray in the top bar), shows both files as stored, and points at where the server logs live. It has a Refresh button to reread the files and the list. A missing file is an empty server list.
The config is read when the workspace becomes the open one, and again on an agent-mode turn for a server that is not already connected. An edit therefore applies the next time the workspace is focused, or on the next message if the server is not up yet.
2. Write a server entry
A server has a command (stdio) or a url (HTTP), not both.
stdio — Robi spawns the server as a child process:
{
"mcpServers": {
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_PERSONAL_ACCESS_TOKEN": { "secret": "github_token" }
}
}
}
}
HTTP — Robi connects to the URL:
{
"mcpServers": {
"linear": {
"url": "https://mcp.linear.app/mcp",
"headers": {
"Authorization": { "secret": "linear_token" }
}
}
}
}
Fields that are enforced:
| Field | Applies to | Rule |
|---|---|---|
| server id | both | matches ^[A-Za-z0-9_-]{1,32}$; any other key is skipped and logged |
command | stdio | an executable name, or an absolute path; a relative path is a config error |
args | stdio | array of strings; default [] |
env | stdio | map overlaid on the scrubbed environment |
url | HTTP | https, or http on 127.0.0.1 or localhost |
headers | HTTP | map of header values |
timeout_seconds | both | whole-call budget; default 60, above 300 is a config error |
tools | both | patterns naming the tools to keep; absent or null keeps all, [] keeps none |
enabled | both | false skips the server |
Unknown fields are ignored, so a config copied from another host still parses.
Keeping a server’s tool list short
A server that publishes 40 tools puts 40 names, descriptions, and schemas in
front of the model on every request. tools keeps only the ones you want:
{
"mcpServers": {
"linear": {
"url": "https://mcp.linear.app/mcp",
"tools": ["get_*", "create_issue", "re:^search_[a-z]+$"]
}
}
}
An entry is a glob (*, ?, [abc], {a,b}) that must match the whole name,
or a regex when it starts with re:, which matches a substring unless you
anchor it. Either form can name the server’s own tool (create_issue) or the
registered one (mcp_linear_create_issue).
Leave tools out and every tool the server lists is registered, as before.
Set it to [] and the server contributes nothing. A pattern that does not
compile skips that server and is logged; a pattern that matches nothing is
logged when the server connects. The status line counts the tools that passed,
not the tools the server publishes. An edited list applies on the next message.
3. Reference secrets
An env or headers value is either a plain string or { "secret": "<name>" }.
A plain string is passed through. A secret object reads <name> from
~/.robi/secrets.toml and is never written back — so a token stays out of the
JSON you might commit. A missing secret skips that server and logs it; resolved
values are never logged.
4. Enable and trust
Your user file starts automatically — you wrote it.
The project file (<workspace>/.robi/mcp.json) does not start until you trust
its current contents. Robi stores a SHA-256 of the file on the workspace, and a
missing file, a changed file, or a fresh workspace leaves project servers off;
changing the file clears the match so a newly committed server does not start on
the next message.
To turn it on, open Settings → MCP and switch Project servers are trusted on. The panel lists the id and the command (or URL) of each server in the file, so you approve what starts rather than a filename. Env and header values stay out of that list.
In the terminal app, open the MCP section, put the cursor on Project config,
and press Enter. It asks first, then stores the hash. Enter on a trusted file
turns it off again.
Switching it off, or editing the file, stops the project servers on the next message. Nothing on disk is deleted.
The same id in both files: the project entry replaces the user entry, and only after the project file is trusted. Until then the user entry stays.
5. Start and see status
One connection per enabled server per workspace is shared by that workspace’s
sessions. The shell starts them when the workspace becomes the open one, and an
agent-mode turn starts any that are not up yet. Switching workspaces, or deleting
one, closes its servers. A server that drops restarts with backoff (1s, 2s, 4s,
8s, then 30s), at most five times in ten minutes; after that it is failed until
you retry or change the config.
The sidebar MCP tray shows a mark per configured server, coloured by status —
connected, starting, failed, or disconnected. Hovering a mark shows the
name, status, and (when connected) its tool count, and clicking it opens
Settings → MCP.
stdio servers run with a scrubbed environment — no DYLD_*, LD_PRELOAD,
LD_LIBRARY_PATH, or any name containing KEY, TOKEN, SECRET, PASSWORD,
or CREDENTIAL — with the workspace root as the working directory. They are
not run inside the shell sandbox: connecting to a server is itself the trust
decision, and it needs the network and the credentials its config names.
command resolves on your login shell’s PATH (plus the path_entries
setting), so uvx and npm work even when Robi is launched from Finder.
HTTP redirects are followed only while the next host still matches the url
rule. There is no OAuth flow; a 401 fails the server. Static headers
authenticate.
List a server’s tools
mcp-tools connects to one configured server and prints its tool names, so you
can see what an entry publishes before or after a tools filter:
cargo run -p robi --bin mcp-tools -- linear
It reads the same mcp.json and secrets.toml the app reads, and connects
through the same opener, so a stdio child gets the login PATH and the config’s
environment. It opens no database, so it runs beside robi-api or the desktop
app. The names are the registered ones, mcp_<server>_<tool>:
mcp_linear_create_issue
mcp_linear_get_issue
| Flag | Effect |
|---|---|
--remote | Print the server’s own names instead of the registered ones |
--kept | Print only the tools the entry’s tools filter keeps |
--long | Append the first line of each description, after a tab |
--home <DIR> | Robi’s home directory. Defaults to $HOME/.robi |
--workspace <DIR> | Read DIR/.robi/mcp.json too. Defaults to the working directory |
--trust | Use the project file’s servers. Without it the file is skipped with a note |
When the entry has a tools filter, a plain run still prints every tool and
writes tools filter keeps 2 of 3 to stderr. That is deliberate: the full list
is what the server publishes, and --kept is what a session will register. A
pattern that matches nothing is named on stderr too, because a typo otherwise
loads fewer tools without an error.
Exit codes are 0 for a printed list, 1 for a config or connection failure,
and 2 for a bad argument.
6. Approve calls
Every MCP tool asks on its first call in a session. The approval line is
Call and server / tool, with the pretty-printed arguments beneath it. When
the server set a hint, a muted line adds Server says: read-only,
Server says: destructive, or Server says: reaches the network — these are
the server’s labels and never change the decision.
- Approve runs this call.
- Allow for this session runs it and remembers that server + tool pair, so later calls run without asking.
- Reject does not call the server.
The remembered list lives on the chat session and does not outlive it. A server’s
readOnlyHint and destructiveHint are stored for the bar but never skip
approval.
Logs
Each server writes its own log under ~/.robi/logs/mcp/<server_id>/, one file
per connection. It captures the MCP messages in both directions and the server’s
own stderr, so this is where to look when a server connects but a tool
misbehaves. Header and env values are never written. Older files are pruned on
the same seven-day schedule as the process logs.
Limits
- A server may contribute up to 64 tools; the rest are logged and omitted.
- A tool whose
inputSchemaJSON exceeds 16 KiB is skipped. - A name that collides with a built-in leaves the built-in in place.
- A large result is compressed before it reaches the model; the original is retrievable. See MCP output.
Where this is specified
The host, the config files and trust hash, the transports, name sanitizing, and the approval rules are in MCP. The compression path is in MCP output.
Next
- MCP — how the host behaves.
- Subagents — why children never get MCP tools.
- Approvals — how the approval gates compose.
Releases
A push to main runs release-please. It opens one pull request that bumps the app version and updates CHANGELOG.md. Merging that pull request tags vX.Y.Z and publishes a GitHub release. The same workflow then builds everything and attaches it, with a SHA-256 checksum, to that release. The builds run in the release workflow because a release created with the repository token does not start another workflow.
Each release carries:
| Asset | What it is |
|---|---|
A .dmg | The desktop app for Apple Silicon macOS. Unsigned; ad-hoc signed only. |
An .AppImage | The desktop app for Linux, carrying its own runtime dependencies. |
A .deb | The desktop app for Debian and Ubuntu. |
robi-vX.Y.Z-aarch64-apple-darwin.tar.gz | The terminal app for arm64 macOS. |
robi-vX.Y.Z-x86_64-unknown-linux-gnu.tar.gz | The terminal app for x86_64 Linux. |
checksums.txt | SHA-256 of every asset above. |
Windows is not built.
What the builds need
The desktop bundles are built on Ubuntu 24.04, which sets their glibc floor at 2.39. A prebuilt ONNX Runtime archive used to force that; the dependency is gone, and the row stays until a 22.04 build of the bundles is tested. The .deb needs libwebkit2gtk-4.1 at runtime; the AppImage carries its own.
The terminal tarballs are built on Ubuntu 22.04 instead, so their glibc floor is 2.35 and one file runs on 22.04 and 24.04 both. They need no webview, no front end, and no Node: the job builds -p robi --features tui --bin robi and nothing else. Each tarball holds one directory, robi-vX.Y.Z-<target>/, with the robi binary and LICENSE. The binary is stripped, and on macOS re-signed ad-hoc after stripping.
Both tarballs run robi --version and compare it with the tag before they are uploaded, so a release that ships a binary whose version disagrees with the tag fails instead of publishing.
Install the terminal app
tar -xzf robi-vX.Y.Z-aarch64-apple-darwin.tar.gz
sudo install -m 0755 robi-vX.Y.Z-aarch64-apple-darwin/robi /usr/local/bin/robi
On macOS, delete the quarantine flag first, because the binary is not notarised:
xattr -d com.apple.quarantine robi-vX.Y.Z-aarch64-apple-darwin/robi
On Linux, the default sandbox runs commands through bubblewrap; without it, a sandboxed command is refused. See the terminal app.
The version
The version is one number for the whole app. The release pull request writes it in three files:
| File | Field |
|---|---|
Cargo.toml | workspace.package.version |
package.json | version |
src-tauri/tauri.conf.json | version |
Crates take the workspace version, so they are not listed separately. openapi/openapi.json is generated; the next make openapi-spec picks up the new version.
Cargo.lock also records the version of each workspace crate, and release-please cannot write it. The release pull request therefore arrives with a stale lock, and the rust CI job fails on cargo metadata --locked until cargo update --workspace is run and committed with it. The terminal build fetches the lock again before cargo build --locked, so that lock drift alone does not stop a release: a dependency missing from the lock still does.
Commits on main use Conventional Commits. While the version is below 1.0.0, fix and feat both open a patch (0.1.1), and feat! or BREAKING CHANGE opens a minor (0.2.0). Other types are omitted from the changelog unless they carry a breaking marker.
How Robi works
Robi is a desktop coding assistant. A Rust core runs an agent loop against a local workspace, a Tauri shell hosts it, and a Solid front end renders the conversation. The design keeps the interesting part — the loop — in a crate that cannot do I/O, so its behavior is provable in a unit test.
The layers
src-tauri → crates/robi → robi-core
(Tauri) (all I/O) (the loop)
Dependencies point one way and never reverse.
crates/robi-core— the agent loop and nothing else: the transcript types, the tool trait and registry, approval state, the event sink. It declares four traits —Model,Tool,MessageStore,EventSink— and implements none of them. No network, no filesystem, no Tauri.crates/robi— every implementation that does I/O. The crate root isagent,domain,adapters, andweb_api. Providers, the prompt, tools, the sandbox, review, skills, MCP, and compression live underagent. Each is a module, promoted to its own crate only for a real reason.src-tauri— the Tauri application: commands, IPC, wiring.src— the Solid + TypeScript front end.
The desktop app and robi-api share one composition root, bootstrap. The
window serves the API in-process and the webview calls the bound loopback port.
pnpm dev still proxies /api to a separate robi-api. The shell holds one
Server-Sent Events connection for updates; see HTTP API.
The turn
A turn runs from a user message to the last assistant message. The loop is a repeat-until-settled function:
- Settle any unresolved tool calls. If one still needs a decision, return
Paused. - If there is nothing to invoke and nothing was settled, stop.
- Enforce the model-turn cap.
- Take one model turn and append it.
- If the assistant message has no tool calls, the turn is complete.
- Otherwise process the tool calls and loop, so the model reads the results.
Three properties decide whether the loop is trustworthy, and each is worth stating:
- The transcript is the only state. The loop derives paused, runnable, and done from stored messages. Nothing lives in a local that a restart loses, so a paused turn survives a restart with no separate bookkeeping.
- Iterations count model turns, not tool calls. Tool fan-out inside one turn is free; the cap exists to stop a model that calls tools forever.
- Tool execution is model order, in segments. A tool declares itself concurrent or exclusive; the loop batches consecutive concurrent calls and runs an exclusive call alone as a barrier. Results are committed in model order, not completion order.
A tool that fails does not abort its siblings or end the run. The failure becomes a structured result the model can read and correct, and the loop continues.
The approval invariant
User input never runs ahead of an unresolved turn.
If the transcript ends with tool calls that are not settled, the next thing that
happens settles them, whatever the user typed. The loop runs until it needs a
decision, returns Paused, and waits to be called again. It does not block a
thread on the user and it does not poll. See Approvals.
The four traits
The loop sees only interfaces, never a provider or a concrete store. Model
supplies one turn (async and cancellable from the start, which is what lets a
provider stream behind the same trait). Tool is a name, a description, a JSON
schema, a side-effect-free requires_approval, and an execute. MessageStore
persists the transcript. EventSink emits deltas after the store write, so an
event never describes state the store does not have yet.
Because the loop cannot reach the network or the disk, the whole of robi-core
is tested against a stub model and an in-memory store:
cargo test -p robi-core
Where this is specified
The loop algorithm, the trait signatures, the turn state machine, and the tool
execution phases are in
The agent loop. The crate layout and the
one-way dependency rule are in the repository’s AGENTS.md. The streaming
protocol is in
Providers and streaming.
Approvals
An agent that can edit files and run commands needs a boundary. Robi’s boundary is three independent gates that compose, plus one invariant that ties them to the conversation.
The default build edits through shell, so approval is for a command, not for
a path. One command can touch many paths, which is why the sandbox and the
session path rules are the enforcement point and the prompt hints are
convenience. In Ask and Plan the shell is read-only: the workspace is mounted
read-only and the schema has no write_paths or unsandboxed, so no approval
can widen it.
The three gates
- Per-call approval. Each tool decides from its own arguments, with a
side-effect-free
requires_approval. It returnsAllowImmediatelyorNeedsApproval— never “deny”. This is what makes “read inside the workspace” free and “read outside it” a prompt. - Policy floor. A set of globs the model cannot talk its way past, plus any ignore rules you add. The floor applies to the read tools and to the sandbox.
- OS sandbox. For child processes only. Every
shellcommand starts inside a sandbox; the alternative,unsandboxed: true, is a separate call that always asks.
The gates are independent on purpose: the sandbox bounds a process; it does not
replace the decision to run it. A command that leaves the default profile still
needs your approval, still clears the policy floor, and still runs under the
sandbox unless you approved unsandboxed.
What prompts
| Action | Asks? |
|---|---|
| Read or search inside the workspace | no |
| Read or search a path the policy floor denies | yes |
shell in the default profile (sandboxed, no extra paths, network deny) | no |
shell with read_paths | yes |
shell with write_paths, unsandboxed, or network: "unrestricted" (Agent only) | yes |
shell in Ask or Plan, which has none of those keys | never asked; a write fails inside the sandbox |
| Edit or delete a path the session write rules allow (edit-tools build) | no |
| Edit or delete a path the session write rules deny (edit-tools build) | yes |
web_search | always — each call spends quota |
web_fetch to a host already used this session | no |
web_fetch to a new host | yes |
| MCP tool, first call for that server + tool this session | yes |
| MCP tool already approved this session | no |
grant | always |
| A subagent child call that would need approval | no prompt — it fails closed |
The invariant
User input never runs ahead of an unresolved turn.
If a turn paused for a decision, the next thing that happens settles it, whatever you type. A paused turn is transcript state, so it survives a restart. You can approve or reject each pending call; approving resumes the loop so the model reads the result, and rejecting sends the model a structured rejection rather than silence.
Session grants
A grant appends one read or write allow for a path the session currently
refuses — including a path outside the workspace. The allow is session-scoped:
- it lives on that chat session and dies with it;
- a directory pattern matches the directory and its children;
- the workspace root is a broad allow that still loses to any literal deny, so it
never opens
.env,.git, or key material; - a read grant is inherited read-only by a subagent, and never lets a child widen the parent’s rules.
MCP approvals are a separate list on the session: the first call to a server’s tool asks, and “allow for this session” remembers that pair. See MCP for the current state of that control.
The policy floor
Built into the path filter and always applied, matched case-folded after symlink resolution. Standard denies include:
- anything outside the workspace (
../); .git;.envand.env.*;*.pemand*.key;id_rsa,id_ed25519;credentials.json,secrets.json.
The shell profile adds ~/.ssh, ~/.aws, ~/.kube, ~/.gnupg, the keychain,
and ~/.robi to the denied set, and keeps the workspace’s .git directory
write-denied. An approved write_paths entry for .git opens that path for
one command.
Specificity decides a conflict. The pattern whose match ends furthest into
the path wins; at the same point, the one with more literal characters wins; a
deny wins a remaining tie. So a wildcard allow like src/.* does not outrank a
literal .env deny.
How it surfaces
A call that is pending approval renders as an approval bar: the verb and target, then Reject and Approve. The full arguments are shown — a search shows the query, a fetch shows the URL, an edit shows the diff — not the model’s summary. A call that ran without asking stays a result row. When the desktop window is not in front, the pause raises an OS notification.
Where this is specified
The three gates and the session-grant rules are in
Read tools; the sandbox, its profile, the
constructed PATH, and the network rules are in
Shell tool. The approval lifecycle in the loop
is in The agent loop. A dedicated
docs/src/design/workspace/permissions.md page is queued; until it is written,
those three design docs are the source of truth.
Sessions and persistence
A session is one chat conversation bound to one workspace. Its transcript is the sequence of messages in the conversation, and — as in the loop — that transcript is the state: a session restored from disk is in exactly the state the loop left it, including a turn that was paused for approval.
A workspace is a named canonical directory root. The shell shows one workspace at a time and lists that workspace’s sessions.
What is stored
The session store is SQLite, at the path in ROBI_DATABASE_URL (see
File locations). Migrations run on startup.
The tables a user should know about:
workspaces— each workspace root, plus its MCP trust hash.chat_sessions— the title, mode, per-mode model config, path grants, approved MCP pairs, the plan path, and timestamps.chat_messages— the transcript, in order. A tool call’s result payload is not in this row.session_file_baselines— the file baselines that checkpoints are computed against. Nothing writes them in the default build, because a shell command is opaque; git is the undo.
Tool results, the stored originals of compressed results, and image bytes live in
~/.robi/sessions/<session_id>/blobs.redb, one file per session. The transcript
records an image as an id and a media type. Deleting a session removes that
directory.
Deleting a session cascades to its messages. last_used_at moves when a message
is appended; updated_at moves when metadata or a title changes.
Settings and secrets
Two files under ~/.robi, both read through one settings port so a later
keychain can replace the secret backend without changing callers:
config.toml— ordinary settings;secrets.toml— credentials, mode0600, refused when group or world can read it.
Every key is fixed and whitelisted; see Configuration. A default is written through the store on the first read, so the file and later reads agree.
Model selection
The model and reasoning effort are resolved per session, per mode, in this order:
- a per-session, per-mode override stored on the session;
- the per-mode setting (
model_agent,reasoning_effort_agent, …); - the base setting (
model,reasoning_effort); - the built-in default (
glm-5.3, no effort).
Switching model mid-session is allowed; the transcript is provider-agnostic. The active model is shown where you type, not buried in settings.
The runtime
One tokio actor per session runs that session’s turns. The process holds an
agent factory, not an agent: the actor builds an Agent for a turn and drops
it when idle, so a process with many open sessions is not holding many agents in
memory.
- Sending a message while a turn is running is allowed; the latest instruction wins.
- Sending a message while the turn is paused rejects the calls still waiting on approval, then runs the new instruction (see Approvals).
stopcancels the running turn through the cancellation token. A cancelled turn leaves a transcript that is either resumable or cleanly finished, never a half-written assistant message with dangling tool calls.- A session response carries
has_pending_agent, so the shell knows a turn is in flight without subscribing to that session’s stream. - The same response carries
turn_display(idle,pending,awaiting_approval, orfailed) for the sidebar. The transcript remains the source of truth for approval.
The title is generated by the model after the first completed turn when the client did not supply one.
Where this is specified
The store choice, the schema, the settings port, and the session lifecycle are in Persistence. The per-session actor, the interrupt rules, and the stop path are in Chat runtime.
Skills
A skill is a directory containing a SKILL.md. The file starts with YAML
frontmatter and the body is markdown instructions. Skills are how you give Robi a
reusable procedure — a release checklist, a house style, an interview flow —
without typing it every time.
~/.robi/skills/land-it/SKILL.md
The id is the directory name, and it must be lowercase letters, digits, and
single hyphens (1–64 characters). A category folder is allowed: the skill at
skills/shipping/land-it/SKILL.md still has the id land-it.
Frontmatter
| Field | Effect |
|---|---|
description | The catalog text. When absent, the first non-empty paragraph is used (cut at 1024 characters); if neither exists, the skill is skipped. |
name | The display label in the composer. The id stays the directory name. |
disable-model-invocation: true | Hidden from the model’s catalog but still loadable when you mention it. |
user-invocable: false | Hidden from the / menu but the model can still load it. |
Other frontmatter is ignored. A !`command` line is treated as markdown;
nothing in a skill is executed at load time.
Where skills are found
The scan reads SKILL.md at any depth under these roots, home first and then each
directory on the workspace chain (git root down to the workspace root):
~/.claude/skills,~/.codex/skills,~/.cursor/skills,~/.opencode/skillsand~/.config/opencode/skills,~/.agents/skills,~/.robi/skills— and the same names under each workspace-chain directory.
Later wins, and within one directory .robi beats .agents beats tool-specific
names, so a project skill overrides a home skill with the same id. The scan runs
when a session’s actor starts, so a file you save mid-turn is visible on your
next message.
Using a skill
- You type
/at the start of the composer to open the menu, and pick a skill. The menu stays open only while that first token has no whitespace. Selecting inserts/id. On send, every/idis resolved and loaded; an unknown/wordstays as plain text. A slash inside a path or a URL is not a mention. - The model loads a skill with the
skilltool, taking the id. It is registered in every mode and needs no approval.
A loaded skill appears in the transcript as Using {id}, with the description,
path, and body on the detail view. The provider receives the body in a
<skill name=… directory=…> block.
The catalog
Robi inserts a catalog of model-loadable skills into the prompt — one line per
skill, id: description, descriptions cut to 256 characters and the whole block
capped at 8 KiB (overflow ends with [N skills omitted]). A skill marked
disable-model-invocation is left out of this block. The catalog text is
untrusted, like any loaded content.
Bundled skills
Two skills ship in the binary and appear in the catalog and the / menu on
every session, ahead of the home roots, so a file with the same id replaces
them.
create-skillwrites a new skill for you: it asks whether the model may load it, where to put it (default~/.robi/skills/<id>/SKILL.md, or the workspace’s.robi/skills/), and confirms the id, description, and body before writing.configure-mcpwalks you through adding an MCP server: it asks which tool you want to connect, whether the config is global (~/.robi/mcp.json) or for this workspace (<workspace>/.robi/mcp.json), the transport and its settings, and any secret references, then writes the entry and tells you to restart the app. See MCP.
In ask or plan mode both show the draft and tell you to switch to agent mode, because those modes cannot write.
Where this is specified
Discovery roots, the catalog, the load path, and the bundled skills are in Skills. The reference scan is in Skills discovery.
Subagents
A subagent is a child agent Robi spawns to do a bounded piece of work and report back only an answer. Its value is context isolation: the parent gets the conclusion, not the pile of file bodies and command output that produced it.
You do not call a subagent directly. The model does, through one tool — delegate
— which is registered in agent mode only.
Two child modes
delegate takes mode:
| Mode | What it can do | Model turns | Calls per session |
|---|---|---|---|
explore | Read and search: the read-only shell, plus read_file, list_dir, find, and grep when read-tools is on | subagent_max_iterations, default 50 | 6 |
general | The explore set plus a sandboxed shell (and retrieve) | the same setting | 4 |
Both children share subagent_timeout_seconds (default two minutes) per call; the parent turn
cancelling cancels the child. When a call budget is spent, the tool returns
explore_limit or delegate_limit and the parent continues on its own.
Neither child can edit files, grant, delegate, or call MCP tools. A child
cannot start another child.
Fail closed
A child never prompts you. If a child tool would need your approval, it does not
run: it returns access_denied and the child continues. The child inherits the
parent session’s path rules — including a read grant, read-only — and cannot
widen them. This is deliberate: a subagent that could raise a dialog would let
the model interrupt you from a task you did not start.
What comes back
The parent model reads a small JSON summary:
{ "mode": "explore", "answer": "...", "tool_calls": 3, "denied": [] }
answer is the child’s final message. Every file body and command output stays
in the child’s in-memory transcript and is dropped; the child is not a chat
session and is never persisted.
Each child tool call is also written onto the parent’s tool card as a row — tool
name, a one-line target, and a status (running, ok, denied, failed) — so
you can watch it work. These rows are not part of the model-visible result.
Several delegate calls in one turn may run in parallel.
Where this is specified
The child policy, the prompt construction, the thoroughness knob, and the snapshot surfacing are in Subagents. Which tools each mode registers is in Agent modes.
MCP
The Model Context Protocol (MCP) lets Robi use tools that other programs provide. Robi is an MCP host (client): it connects to servers you configure, and each remote tool becomes a tool the assistant can call. Robi does not accept MCP connections from anyone.
MCP tools are registered in agent mode only. Ask and plan keep their built-in tool sets, and subagents never receive MCP tools.
Configuring a server
Two JSON files share one shape:
~/.robi/mcp.json— your servers.<workspace>/.robi/mcp.json— servers for one project.
A server has a command (stdio) or a url (HTTP), not both. Environment
values and HTTP headers may be a plain string or {"secret": "<name>"}, where
<name> is read from ~/.robi/secrets.toml and never written back.
{
"mcpServers": {
"filesystem": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "."] }
}
}
Details that are enforced:
- A server id matches
^[A-Za-z0-9_-]{1,32}$. enabled: falseskips a server.commandis an executable name or an absolute path; a relative path is a config error.urlmust behttps, orhttpon127.0.0.1orlocalhost.timeout_secondsdefaults to 60; a value over 300 is a config error.toolskeeps only the tools that match its glob orre:patterns. Absent ornullkeeps every tool;[]keeps none.- Unknown fields are ignored.
The config is read when the workspace becomes the open one, and again on an agent-mode turn for a server that is not already connected. An edit applies the next time that workspace is focused, or on the next message if the server is not up yet. Restart the app if you want the change picked up right away.
The bundled configure-mcp skill walks you through adding an entry — ask to add
an MCP server, or type /configure-mcp. It asks which tool you want to connect,
whether the config is global or for this workspace, the transport and its
settings, and any secret references.
Trust
Your user file starts automatically — you wrote it. The project file does not start until you trust the current contents: Robi stores a SHA-256 of the file on the workspace, and a missing file, a changed file, or a fresh workspace leaves project servers off. Changing the file clears the match.
Settings → MCP shows a switch for it, and the terminal app has the same row in
its MCP section: press Enter on Project config and answer the question.
Either one stores the hash of the bytes on disk, and any edit clears it, so a
commit that adds a server asks again.
Transports
- stdio — Robi spawns the server as a child process. The child gets a
scrubbed environment (no
DYLD_*,LD_PRELOAD,LD_LIBRARY_PATH, or any name containingKEY,TOKEN,SECRET,PASSWORD, orCREDENTIAL) and the workspace root as its working directory.commandresolves on your login shell’sPATH(plus thepath_entriessetting), souvxandnpmwork even when Robi is started from Finder. It is not run inside the shell sandbox; connecting to a server is itself a trust decision. - streamable HTTP — Robi connects to the URL. Redirects are followed only while the next host still matches the URL rule. There is no OAuth flow; a 401 fails the server. Static headers authenticate.
One connection per enabled server per workspace is shared across that workspace’s sessions. The servers start when the workspace is the one open in the shell, and they close when you switch to another workspace or remove this one. A server that drops restarts with backoff (1s, 2s, 4s, 8s, then 30s), at most five times in ten minutes.
Tools and approval
Each remote tool is registered as mcp_<server>_<tool>, with client-side
characters outside [A-Za-z0-9_-] replaced by _. Built-in tools register
first, so a name collision with a built-in leaves the built-in in place. A server
may contribute up to 64 tools; a tool whose schema exceeds 16 KiB is skipped.
mcp-tools <server-id> prints what one server publishes without starting the app,
and --kept prints only what its tools filter keeps.
A server entry may also set tools, which limits what that server contributes.
The rest never reach the request, so they cost no context. A glob matches the
whole tool name and a re: entry is a regex, and either may name the server’s
own tool (create_issue) or the registered one (mcp_linear_create_issue).
Every MCP tool asks on its first call in a session. Approving that call runs
it; a later call with the same server and tool runs without asking. The list of
approved pairs lives on the chat session and does not outlive it. A server’s
readOnlyHint and destructiveHint are stored for the approval bar but never
change the decision.
Logs
Each server writes its own log under ~/.robi/logs/mcp/<server_id>/, one file
per connection. A line is an MCP message in either direction, one line of the
server’s stderr, or a lifecycle note; header and env values are never written.
The file is mode 0600, and the same seven-day prune as the process logs
applies. This is where to look when a server connects but misbehaves. The
Settings → MCP page lists each server and the exact directory for its log.
Status
GET /api/v1/workspaces/{id}/mcp reports each configured server’s status —
disconnected until the workspace is open, then starting, connected, or
failed — along with its tool count and icon. Icons are cached in
~/.robi/mcp-icons.json.
Where this is specified
The host, the config files and trust hash, the transports, name sanitizing, and the approval rules are in MCP.
Tools
These are the tools Robi’s assistant can call. Each one is a JSON-schema function
the model sees; its description and schema are the main lever on whether it is
called correctly, so they are treated as reviewed copy. A call that does not
parse returns invalid arguments naming the keys received and any required keys
that were absent. The values are left out.
The default build is shell-first: there is one tool that reads and writes the workspace, and the system prompt teaches the forms that work. Which tools exist depends on the session’s mode:
| Mode | Tools |
|---|---|
| Ask | shell (read-only), retrieve, skill, grant, web_search, web_fetch |
| Plan | the ask set, with a shell that may write only .robi/plans |
| Agent | the ask set plus delegate and MCP tools; the shell writes the workspace |
Ask holds a read-only shell: the sandbox mounts the workspace read-only, so
a command that writes fails inside it. Plan’s shell is read-only too, except for
one directory: .robi/plans. Agent’s shell writes the whole workspace. In Ask
and Plan the schema has no write_paths and no unsandboxed, and network is
restricted to deny. Build and test commands write to target/, so they fail
there too: verify in Agent mode.
Some tools are compiled out and restored by a Cargo feature. See Feature switches.
| Feature | Restores |
|---|---|
read-tools | read_file, list_dir, find, grep |
edit-tools | write_file, edit_file, delete_file |
The semantic index, semantic_search, the five language-server tools, and
read_code are not features: they are deleted (S3 and S4).
Read and search
In the default build the shell is the reader. The prompt gives the forms:
| Job | Command |
|---|---|
| Read a file | cat path, head -n 120 path, sed -n '40,80p' path |
| Count lines | wc -l path |
| Find a file | git ls-files | grep -i name, find . -name '*name*' |
| Search contents | grep -rn 'pattern' . --include='*.rs', or rg |
| Map a source file | grep -nE '^(pub )?(fn|struct|enum|impl|trait) ' path |
| Re-read a folded result | retrieve with the stream id |
retrieve is the one read tool that is always registered: it reads back a shell
stream that was compressed, which is part of the shell’s feedback loop.
With --features read-tools the five read tools come back:
| Tool | Arguments | Behavior | Approval |
|---|---|---|---|
read_file | path, offset, limit | Read a text file, one 32 KB window. Reports where to continue. | none |
list_dir | path | List one directory, non-recursive. | none |
find | pattern, path, glob, hidden, no_ignore | Find files by path substring or glob. | none |
grep | pattern, path, regex, hidden, no_ignore | Content search. Uses ripgrep when available. | none |
grep and find are the retrieval path. There is no search by meaning: the
semantic index is gone.
Verification
Verification is the shell: cargo check, tsc --noEmit, eslint, and the
project’s own test command. The language-server tools are gone too.
Edit
In the default build the shell is the editor. The prompt gives the forms:
| Job | Command |
|---|---|
| Full overwrite | cat > path <<'EOF' … EOF, with the delimiter quoted |
| One exact replacement | a short Python that reads, replaces one occurrence, asserts the count, and writes |
| Append | printf '%s\n' 'line' >> path |
| Delete | ls path, then rm path |
| Verify | git diff -- path, git status --short |
The quoted heredoc matters: an unquoted delimiter expands $VAR and backticks
inside the text being written. sed -i is avoided on purpose: it differs between
GNU and BSD and an unanchored pattern edits more than intended.
With --features edit-tools the three write tools come back. A delete or an edit
to a path the session write rules allow runs immediately; a path they deny
becomes an approval prompt for that call.
| Tool | Arguments | Behavior | Approval |
|---|---|---|---|
write_file | path, content | Create a file or replace its whole contents. | conditional |
edit_file | path, old_string, new_string, replace_all | Replace one exact snippet. Fails closed on a missing or non-unique match. | conditional |
delete_file | path | Delete one text file. Refuses a directory, a missing path, or a non-UTF-8 file. | conditional |
Writes through the shell record no checkpoint: a command is opaque, so the
harness cannot know which paths it touched. git diff is the verification and
git is the undo. See Checkpoints.
Shell
| Tool | Arguments | Behavior | Approval |
|---|---|---|---|
shell | command, cwd, read_paths (and, in Agent mode, unsandboxed, write_paths, network) | Run a command inside an OS sandbox. | conditional |
A command in the default profile (sandboxed, no extra paths, network deny) runs
without a prompt. In Agent mode a prompt appears for any of:
unsandboxed: true,- a non-empty
write_paths, network: "unrestricted".
A non-empty read_paths asks in either mode. Ask and Plan do not offer the first
three at all; a call that sends one anyway is refused with this mode is read-only.
The sandbox is a requirement, not an option: a sandboxed call is refused where no
mechanism exists. macOS uses Seatbelt (/usr/bin/sandbox-exec); Linux uses
bubblewrap; Windows has no sandbox, so only an approved unsandboxed: true call
runs there. A sandboxed child gets a constructed PATH. An approved
unsandboxed child gets the parent PATH unchanged. Both get a scrubbed
environment, and the workspace root as the working directory. Output is a bounded artifact, not a
stream, and is killed at tool_timeout_seconds (default 120) or on cancel.
A read-only call keeps a writable private temp directory: it belongs to the call
and is deleted when the call returns. .git writes are denied in both modes, so
git status, diff, log, and show work and git checkout, restore,
stash, and commit do not.
Plans
There is no plan tool. A plan is a directory in the workspace the agent writes with the shell:
.robi/plans/
.gitignore # one line: *
ship-mode-registry/
PLAN.md # the prose: what changes, why, in what order
TODO.md # the checklist, and nothing else
| Mode | Writes |
|---|---|
| Ask | nothing |
| Plan | only .robi/plans, recursively |
| Agent | the workspace, including .robi/plans |
One directory per plan, named from the plan’s title in kebab case; the prompt
tells the agent to list the directory first and update an existing plan rather
than mint a near-duplicate. TODO.md is one line per step, - [ ] open and
- [x] done, and PLAN.md carries no checkboxes — so ticking a step changes
only the checklist. .robi/plans/.gitignore holds a single *, which ignores
the whole directory including itself: nothing in it is tracked, and deleting
that file is the opt-in to committing a plan.
Because .robi is hidden and git-ignored, git status, rg, and the
find/grep tools skip it; only ls and cat see it. See
S9 for why the tools went.
Delegate
| Tool | Arguments | Behavior | Approval |
|---|---|---|---|
delegate | task, mode, description, thoroughness, instructions | Hand a bounded task to a child agent and get only its answer. | none |
Agent mode only. mode is explore (search and read) or general (the same
plus a shell for running read-only commands). Both children hold a read-only
shell, so neither can write the workspace, and neither can grant, delegate,
run unsandboxed, or call MCP tools. A child call that would need approval fails
closed with access_denied; the user is never prompted from inside a child. A
child that finds a change to make names it in the summary and the parent applies
it. See Subagents.
Web
| Tool | Arguments | Behavior | Approval |
|---|---|---|---|
web_search | query | Brave web search, up to five hits. | every call when web_search_approval is on |
web_fetch | url | Fetch one public URL and reduce it to text. | first call per host when web_fetch_approval is on |
Both approvals default to on. web_search asks on every call because each spends
Brave quota. web_fetch asks the first time a host is used in the session, then
remembers that host. off skips the card. A turn already running keeps the
value it started with. Page text
and snippets are untrusted data; an instruction inside a fetched page is data,
not a command.
Skills and grants
| Tool | Arguments | Behavior | Approval |
|---|---|---|---|
skill | name | Load one skill by id and return its files and body. | none |
grant | path, access | Ask the user to allow a path for this session. | always |
skill is registered in every mode. grant appends one read or write allow for a
path the session currently refuses, including a path outside the workspace. The
allow is session-scoped and never widens the policy floor for a subagent. With a
shell, grant is how a path outside the workspace stays usable: the allow is
what makes later shell calls need no read_paths.
MCP
Tools from an MCP server are registered as mcp_<server>_<tool>. Each asks on
its first call in the session; an approved pair runs on later calls. Client-side
tool names outside [A-Za-z0-9_-] are replaced with _. A server entry may set
tools to a list of glob or re: patterns; only the matching tools are
registered, so the rest never reach a request. To see a server’s list from the
shell, run cargo run -p robi --bin mcp-tools -- <server-id>. See
MCP.
Where this is specified
Per-tool detail is in the design docs: Read tools, Editing tools, Shell tool, Web tools, Subagents, Feature switches, and MCP.
Configuration
Robi reads two files from its home directory, ~/.robi/:
config.toml— ordinary settings. Created on first read.secrets.toml— credentials. Must be mode0600; a file that group or world can read is refused.
The app reads and writes both files for you through Settings; editing them by hand is only needed for headless or manual setups. See Quickstart for the in-app flow.
Both are plain TOML. The key is a string and the value is a string, for example:
# ~/.robi/config.toml
model = "ocg_glm-5.3"
reasoning_effort = "medium"
max_iterations = "50"
subagent_max_iterations = "50"
subagent_timeout_seconds = "120"
tool_timeout_seconds = "120"
path_allow_read = """
~/pnpm
"""
path_allow_write = """
~/pnpm
"""
path_entries = """
~/pnpm
"""
file_open_patterns = """
*.png
"""
file_open_command = "zed {file_path}:{line}"
web_search_approval = "on"
web_fetch_approval = "on"
sandbox_mechanism = "os"
sandbox_image = "robi/agent:0.1.0"
sandbox_runtime = "runsc"
sandbox_memory_mb = "4096"
sandbox_cpus = "2"
sandbox_pids_limit = "512"
sandbox_network = "on"
sandbox_project_files = "off"
# ~/.robi/secrets.toml
opencode_go_api_key = "sk-..."
anthropic_api_key = "sk-ant-..."
deepseek_api_key = "sk-..."
brave_search_api_key = "..."
The same keys are readable and writable over HTTP at /api/v1/settings/{key},
and from the terminal app’s settings surface (Ctrl-, or /settings). The terminal
shows the GUI’s six pages — General, Model providers, Permissions, Sandbox, MCP,
Audit log — and writes one key per Enter. A secret is never read back: the
surface shows •••••••• once one is stored, and an empty field leaves it alone.
An empty field on any other key removes it, so the default takes over again.
GET /api/v1/settings?key= reads several keys in one request; repeat key
for each one. Secret values are never returned by either route.
Settings keys
An empty required-shape value (model_ask, reasoning_effort) inherits from the
key it points at. The default is written to the file on the first read, so the
files and later reads always agree.
| Key | Secret | Default | Notes |
|---|---|---|---|
opencode_go_api_key | yes | none | Bearer credential for OpenCode Go models (ocg_ prefix). |
anthropic_api_key | yes | none | x-api-key credential for Anthropic models (ant_ prefix). |
deepseek_api_key | yes | none | Bearer credential for DeepSeek models (dsk_ prefix). |
provider_opencode_go | no | on | off hides OpenCode Go models from the picker and refuses a turn that needs one. |
provider_anthropic | no | on | off hides Anthropic models from the picker and refuses a turn that needs one. |
provider_deepseek | no | on | off hides DeepSeek models from the picker and refuses a turn that needs one. |
brave_search_api_key | yes | none | Brave Search token for web_search. |
model | no | ocg_glm-5.3 | Default model id. The ocg_/ant_/dsk_ prefix selects the provider. |
model_ask | no | none | Model for ask mode. Empty inherits model. |
model_plan | no | none | Model for plan mode. Empty inherits model. |
model_agent | no | none | Model for agent mode. Empty inherits model. |
reasoning_effort | no | none | low, medium, or high. Unset uses the provider default. |
reasoning_effort_ask | no | none | Effort for ask mode. Empty inherits reasoning_effort. |
reasoning_effort_plan | no | none | Effort for plan mode. Empty inherits reasoning_effort. |
reasoning_effort_agent | no | none | Effort for agent mode. Empty inherits reasoning_effort. |
base_url | no | none | Base URL for OpenCode Go and Anthropic. Unset uses that provider’s default. |
deepseek_base_url | no | none | Base URL for DeepSeek. Unset uses https://api.deepseek.com. |
system_prompt | no | none | Extra system-prompt text. Unset adds no block. |
max_iterations | no | 50 | Model turns in one primary-agent run. A whole number from 1 to 500. Read when the session actor starts. |
subagent_max_iterations | no | 50 | Model turns in one explore or general child. A whole number from 1 to 500. Read when delegate starts that child. |
subagent_timeout_seconds | no | 120 | Seconds before an explore or general child is stopped. A whole number from 1 to 3600. Read when delegate starts that child. |
tool_timeout_seconds | no | 120 | Seconds before a shell command is killed. A whole number from 1 to 3600. Read when that command starts. |
path_allow_read | no | none | Newline-separated paths appended to every session’s read allow list. A line starting with ~/ is that user’s home directory. Read from the store each time a tool builds the path filter or the shell profile. |
path_allow_write | no | none | Newline-separated paths appended to every session’s write allow list. A line starting with ~/ is that user’s home directory. Read from the store each time a tool builds the path filter or the shell profile. |
path_entries | no | none | Newline-separated directories appended to the sandbox PATH and to an MCP stdio child’s PATH. Each directory is also appended to the read allow list. A line starting with ~/ is that user’s home directory. Read from the store each time a shell or an MCP stdio child builds its environment. |
file_open_patterns | no | none | Newline-separated globs. * matches any run of characters, including /, and ? matches one character. A workspace-relative path that matches one opens outside the file viewer when its name is clicked on an edit card. Anything else opens in the file viewer. Absent matches nothing. |
file_open_command | no | none | One line. {file_path} is the absolute path and {line} is the 1-based line of the first change. A click with no line drops {line} and a colon before it. The line is split on whitespace into arguments; double quotes group one argument. It is not a shell command. Absent uses the system app. The desktop app posts the path to POST /api/v1/workspaces/{id}/open and waits up to 10 seconds. A program still running then has started. A failure to start, or a non-zero exit inside that window, is shown on the edit card. |
web_search_approval | no | on | on asks before every web_search. off runs the search without a card. Read when the session actor starts. |
web_fetch_approval | no | on | on asks the first time a host is fetched in the session. off fetches without a card. Read when the session actor starts. |
sandbox_mechanism | no | os | os runs commands under Seatbelt on macOS or bubblewrap on Linux. container runs them in a gVisor container over the Docker API. Read before every shell command. |
sandbox_image | no | robi/agent:0.1.0 | Image the container starts from, as repo/name[:tag]. Whitespace and a leading - are refused. Read when the container is created and re-resolved on every command. |
sandbox_runtime | no | runsc | A runtime name in the daemon’s runtime map, up to 64 characters of [A-Za-z0-9_.-]. |
sandbox_memory_mb | no | 4096 | Container memory limit in MiB, a whole number from 512 to 65536. |
sandbox_cpus | no | 2 | Container CPU limit in whole CPUs, from 1 to the machine’s CPU count. |
sandbox_pids_limit | no | 512 | Most processes the container may run at once, a whole number from 64 to 8192. |
sandbox_network | no | on | on keeps the container’s network sandboxed: no interface unless a single command is approved for egress, or the workspace joins a service network. off gives every sandboxed command full outbound networking through the daemon’s NAT, and no approval card appears for egress because there is nothing left to grant. Global only: a workspace file cannot change it. |
sandbox_project_files | no | off | on lets a workspace’s .robi/sandbox.toml narrow the sandbox values above, and name services and [env] entries that have no global key. off ignores the file. A project file can never choose sandbox_mechanism. |
The container keys are read only when sandbox_mechanism is container; they are
otherwise stored and unused. The Settings → Sandbox screen writes all eight.
Any key not on this list is refused. lsp is gone with the language-server
tools (S4): writing it returns unknown setting: lsp. MCP reads
~/.robi/secrets.toml for a value named by a server’s {"secret": "<name>"}
field; that name is not part of this whitelist.
Environment variables
Set by the user or the shell, not by a settings file.
| Variable | Default | Effect |
|---|---|---|
ROBI_DATABASE_URL | sqlite://robi.db?mode=rwc for robi-api. The packaged app uses robi.db in the app data directory. pnpm tauri dev uses dev/robi.db there | The session database. |
ROBI_BIND | 127.0.0.1:1431, then the next free port through 1450 | Listen address. Must be loopback when set. When unset, a taken 1431 falls through to the next port. When set, that address is used exactly. |
ROBI_EXTERNAL_API | unset | Set to 1 with pnpm tauri dev to skip the in-process API and use make dev-api through the Vite proxy. Ignored in a packaged build. |
HOME | — | Resolves the ~/.robi directory. Required. |
robi-api, the desktop process, and the terminal front end honor RUST_LOG for
tracing output (default robi=info). Each start writes a new file under
~/.robi/logs/ named robi-api-<timestamp>.log. A dev build, including
pnpm tauri dev and robi-api built for debug, uses robi-dev-<timestamp>.log
instead. The terminal front end always uses tui-<timestamp>.log, and each
prefix is pruned on its own. An existing file is never truncated. Debug builds
also print the same events to stderr. A failure starting the in-process API, and
any panic, is appended to that file and flushed before the process exits. The
background logger does not flush when the process aborts.
On startup the process keeps the new file and the newest older log, then deletes the rest when a file is older than 7 days or when more than 8 files would remain. The newest older log is kept either way, so the previous run is still on disk after one reopen. A later start is what drops it. Secret values are not written to these files.
MCP servers log separately, one file per connection under
~/.robi/logs/mcp/<server_id>/ and mode 0600. Each line is a JSON-RPC message
in either direction, one line of the child’s stderr, or a lifecycle note. The
same seven-day and eight-file policy applies, and a server taken out of the
config has its directory pruned on the next start. Header and env values are
never written. See MCP.
An MCP stdio child resolves its command on the user’s login-shell PATH
($SHELL -ilc, falling back to this process’s PATH) with path_entries
appended. That is what lets uvx and npm resolve when Robi is launched from
Finder, where the process PATH is the minimal system one.
The standalone example (cargo run -p robi --example simple) reads ROBI_MODEL,
ROBI_BASE_URL, ROBI_EFFORT, and OPENCODE_GO_API_KEY; those are example-only
and are not read by the API.
Where this is specified
The store choice, the file modes, and the settings port are in Persistence. The provider keys and the base URL are in Providers and streaming.
File locations
Robi keeps everything under one home directory, ~/.robi, unless an environment
variable says otherwise. The directory is created mode 0700 on first use.
| Path | What it holds |
|---|---|
~/.robi/ | The home directory. |
~/.robi/config.toml | Ordinary settings. See Configuration. |
~/.robi/secrets.toml | Credentials. Mode 0600, refused when readable by group or world. |
~/.robi/plans/<session_id>/ | Legacy plan files from before S9. New plans are written to <workspace>/.robi/plans/ and these are no longer read. |
~/.robi/sessions/<session_id>/blobs.redb | Tool results, tool originals, and image bytes for one chat. It is also that chat’s image index: an image id resolves only inside its own session file. |
~/.robi/locks/sessions/<session_id>.lock | Held while a process owns a chat. Contains the holder’s pid and scope. |
~/.robi/locks/paths/<sha256>.lock | One workspace file, held across a read-modify-write. Removed after seven days if nothing holds it. |
~/.robi/locks/startup.lock | Held while a process runs migrations, the blob evacuation, the prune, and the turn-display repair. |
~/.robi/locks/settings.lock | Held across a config.toml or secrets.toml write. |
~/.robi/index/<workspace_id>/ | A legacy semantic index from a build before M11. Nothing writes it now; deleting the workspace still removes the directory. |
~/.robi/mcp.json | User-scoped MCP server config. |
~/.robi/mcp-icons.json | Cached MCP server icons (capped at 256 KiB). |
~/.robi/logs/ | Process logs. One file per start: robi-api-<timestamp>.log, robi-dev-<timestamp>.log, or tui-<timestamp>.log. Each prefix is pruned on its own; the newest prior file is kept, older than seven days is pruned. |
~/.robi/logs/mcp/<server_id>/ | One MCP server’s logs, one mcp-<timestamp>.log per connection. Mode 0600. See MCP. |
The lock files are empty apart from one line naming the holder: pid 4812 scope turn database sqlite://… at …. A refused process reads that line, so the message
it shows names the pid that has the session. There is no TTL and no heartbeat:
the operating system drops a file lock when the holding process exits, including
on kill -9, so a stale lock cannot outlive its owner.
The session database
The session store is SQLite. robi-api uses the path named by
ROBI_DATABASE_URL, which defaults to sqlite://robi.db?mode=rwc — a robi.db
file relative to the working directory you started robi-api in, not under
~/.robi. The desktop app, when that variable is unset, stores robi.db in
the app data directory (~/Library/Application Support/com.github.cgund98.robi
on macOS). pnpm tauri dev uses dev/robi.db in that same directory, so a
migration applied while developing does not change the database the installed
app opens. WAL mode adds the robi.db-wal and robi.db-shm sidecar files, both
gitignored.
The terminal app chooses differently. With ROBI_DATABASE_URL unset,
robi opens the desktop app’s own database —
~/Library/Application Support/com.github.cgund98.robi/robi.db on macOS — rather
than a file relative to the working directory. A debug build, which is what a
cargo run from a checkout is, opens the app’s dev database instead
(.../com.github.cgund98.robi/dev/robi.db), so it shows the same workspaces
pnpm tauri dev shows, and a migration applied while developing does not reach
the installed app’s file. It also opens the workspace named by its first
argument, or the working directory when there is none, and asks before creating a
workspace at a path that has none. See
the terminal shell and
the workspace argument.
Point it at a fixed location if you want the database independent of the shell’s working directory:
ROBI_DATABASE_URL=sqlite:///Users/you/.robi/sessions.db?mode=rwc make api
Workspace files
A workspace is a directory you opened in Robi. Three things may be written into it:
<workspace>/.robi/mcp.json— a project-scoped MCP server config. It does not start until you trust the current file hash. See MCP.<workspace>/.robi/skills/— project skills, found by the skill scan. See Skills.<workspace>/.robi/plans/<name>/PLAN.mdandTODO.md— a plan and its checklist, written by the agent in Plan or Agent mode..robi/plans/.gitignoreholds a single*, so the directory ignores itself and nothing in it is tracked. See Tools.
Where this is specified
The schema and the data directory are in Persistence. The MCP config files are in MCP.
HTTP API
The local API is an Axum server. bootstrap wires the SQLite adapters, the
provider clients, and the agent runtime. The desktop app serves that router in
the Tauri process. robi-api serves the same router for a browser UI and for
headless use.
The desktop app binds 127.0.0.1:1431, then the next ports through 1450 when
1431 is taken, and tells the webview the bound origin. robi-api does the
same unless ROBI_BIND is set, in which case that loopback address is used
exactly and startup fails if it is taken. The browser UI reaches the API through
the Vite proxy on 1431, so leave 1431 free when you use pnpm dev or
ROBI_EXTERNAL_API=1.
Responses include CORS for http://localhost:1430, http://127.0.0.1:1430,
http://tauri.localhost, https://tauri.localhost, and tauri://localhost
(the macOS and Linux packaged window). Other origins are refused.
All routes live under /api/v1. The request and response bodies are described by
the OpenAPI document at openapi/openapi.json, which is served alongside a
Swagger UI at /docs. Every error has one shape: {"error": "..."}, with a
status of 400, 404, 409, or 500. A response outside 2xx is logged at warning. A
handler that takes 2 seconds or longer is logged at warning with its duration.
Health
| Method | Path | Returns |
|---|---|---|
GET | /api/v1/health | 200 "Ok". The shell polls this every 5 seconds and treats a non-200 or a wait past 3 seconds as unreachable. |
Workspaces
| Method | Path | Returns |
|---|---|---|
POST | /api/v1/workspaces | 201 when the root is new, 200 when already stored. |
GET | /api/v1/workspaces | Every workspace. |
GET | /api/v1/workspaces/{id} | One workspace. |
DELETE | /api/v1/workspaces/{id} | 204. |
GET | /api/v1/workspaces/{id}/skills | The user-invocable skills for the workspace. |
GET | /api/v1/workspaces/{id}/mcp | Configured MCP servers and their status. |
POST | /api/v1/workspaces/{id}/mcp | Start this workspace’s MCP servers and close every other workspace’s. |
GET | /api/v1/workspaces/{id}/mcp/config | The user and project MCP config text. |
PUT | /api/v1/workspaces/{id}/mcp/trust | Trust the project MCP file’s current bytes. 400 when there is no project file. Answers with the config. |
DELETE | /api/v1/workspaces/{id}/mcp/trust | Clear the stored hash, so the project servers stay off. Answers with the config. |
GET | /api/v1/workspaces/{id}/path | {"absolute"}. Query path is workspace-relative. A blank path, the workspace root, or a path that resolves outside the root is 400. |
POST | /api/v1/workspaces/{id}/open | Body {"path", "line?"}. Runs file_open_command for that file. 204 when the program is still running after 10 seconds or exits 0 sooner. 400 with {"error"} when it cannot start or exits non-zero inside that window. 404 when the command is unset. |
GET | /api/v1/workspaces/{id}/file | {"path","content"}. UTF-8 text of that file, at most 1 MiB. A directory, a larger file, or a non-UTF-8 file is 400. A missing file is 404. |
Chat sessions
| Method | Path | Returns |
|---|---|---|
POST | /api/v1/chat_sessions | 201 and the new session. |
GET | /api/v1/chat_sessions | Sessions, optionally filtered by workspace_id. |
GET | /api/v1/chat_sessions/{id} | One session. Includes has_pending_agent and turn_display. |
PATCH | /api/v1/chat_sessions/{id} | Update title, mode, model config, or grants. |
DELETE | /api/v1/chat_sessions/{id} | 204. Cascades to the session’s messages. |
Messages and turns
| Method | Path | Returns |
|---|---|---|
GET | /api/v1/chat_sessions/{id}/messages | The transcript, in order. |
POST | /api/v1/chat_sessions/{id}/messages | 202 {"status":"accepted"}. A paused turn rejects the pending calls, then runs this instruction. |
GET | /api/v1/chat_sessions/{id}/messages/{message_id} | One message. |
POST | /api/v1/chat_sessions/{id}/tool_calls/{call_id} | 202; settle one paused call. 409 when the actor is running. |
POST | /api/v1/chat_sessions/{id}/stop | 202 {"status":"stopped"}; cancel the running turn. |
POST | /api/v1/chat_sessions/{id}/compact | 202 {"status":"compacting"}; summarize the older prefix. 409 when the actor is running, the turn is awaiting approval, or nothing is compactable. |
GET | /api/v1/chat_sessions/{id}/tool_originals/{original_id} | A stored original (shell or MCP) of a compressed result. |
Sending a message is asynchronous: the route accepts the turn and returns 202,
then the result arrives on the event stream. If the transcript is paused on
approval, that same submit rejects the waiting calls and then runs the new
instruction. See the approval invariant.
Review
Not served (S2). Review happens in an IDE or with git diff. The inline file peek
on a tool call card reads GET /workspaces/{id}/file instead, so it shows the
current text with no diff. The routes below return when the review Cargo
feature is on; see feature switches.
| Method | Path | Returns |
|---|---|---|
GET | /api/v1/chat_sessions/{id}/review | Changed paths for the session: path, status, and line counts. |
GET | /api/v1/chat_sessions/{id}/review/file?path= | One file’s baseline, current text, lines, and hunks. 404 when that path has no remaining changes. |
POST | /api/v1/chat_sessions/{id}/review | 204; approve or reject a file or one hunk. |
Settings and models
| Method | Path | Returns |
|---|---|---|
GET | /api/v1/settings?key= | 200 array, one entry per repeated key, in request order. Secret values are omitted. |
GET | /api/v1/settings/{key} | 200; secret values are omitted. |
PUT | /api/v1/settings/{key} | 204. |
DELETE | /api/v1/settings/{key} | 204. |
GET | /api/v1/models | The vendored model catalog (id, display_name, context_window). |
Event stream
GET /api/v1/events/stream is a Server-Sent Events stream with
Content-Type: text/event-stream. It carries every state change in the process;
the shell holds one connection and updates from it.
Query parameters. Both optional:
session_id— a UUID; limit the stream to one session. The shell does not send this.workspace_id— a UUID. Every session frame is delivered. Index and MCP frames are limited to this workspace. The shell sends the open workspace.event_types— repeat the parameter to select event types.
Frame shape. Each frame is:
id: <cloudevents id>
event: <cloudevents type>
data: <full envelope JSON>
The envelope is CloudEvents 1.0: specversion is "1.0", id is a UUIDv7,
source is robi/agent, subject is the session id, time is RFC 3339 UTC,
and data is the payload. A keep-alive comment is sent every 15 seconds.
Event types. A type names its source:
| Type | Meaning |
|---|---|
robi.agent.v1.turn_started | A turn began. |
robi.agent.v1.message_added | A message was appended. |
robi.agent.v1.message_updated | A message changed. |
robi.agent.v1.message_delta | A streaming text or reasoning delta. |
robi.agent.v1.tool_call_updated | A tool call changed state. |
robi.agent.v1.awaiting_approval | A turn paused for a decision. |
robi.agent.v1.turn_finished | A turn ended, with an outcome. |
robi.session.v1.created | A session was created. |
robi.session.v1.updated | A session’s metadata changed. |
robi.session.v1.deleted | A session was deleted. |
robi.app.v1.error | A process-level error. |
A session_id filter still delivers session lifecycle events and app.error.
The shell subscribes with workspace_id and leaves transcript fetches to the
session on screen. Opening the stream resolves the workspace and publishes one
MCP status cue; it starts no index scan. A turn outcome in data is one
of complete, paused, cancelled, or failed.
The bus fans out per subscriber with a bounded queue of 1024. On overflow a
queued message_delta is dropped first, and otherwise the oldest event, so a
slow reader loses deltas rather than stalling the server. The front end
reconnects with exponential backoff.
Where this is specified
The event envelope, the fan-out, and the shell’s subscription are in
Events and SSE. The session lifecycle and the
error shape are in Persistence. The route
list is generated from the code into openapi/openapi.json by
make openapi-spec.
Robi Roadmap
Robi is a desktop coding assistant: a Rust core that runs an agent loop against a local workspace, and a Solid front end that renders the conversation.
This page is the plan of record for what Robi ships, in what order, and which
decisions are still open. Each milestone that needs design work links to a
breakout doc under docs/src/design/. Read this page first; then open the breakout
doc for the feature you are about to build.
Where Robi comes from
Robi models its behavior on two existing projects, both of which are Go:
| Project | What it is | What Robi takes |
|---|---|---|
../gopi | A terminal coding agent: a Bubble Tea TUI over gogent | Agent modes, tool set and naming, subagents, plan files, prompt assembly, approval model, session store |
../gogent | The provider and agent-loop library | Loop shape, message model, tool trait, approval lifecycle, event broadcaster |
Robi is Rust + Solid + Tauri, so neither is a dependency. Treat both as a behavioral spec: match the semantics that gopi has already validated, and rewrite the implementation. The mapping is in Porting gopi.
Two consequences follow immediately and shape the whole plan:
- The agent loop is a build, not a dependency.
gogentis a Go module. Robi writes its own core crate. Budget for it in M0. gogenthas no streaming.Model::GenerateResponseis a blocking non-streaming call; gopi’s TUI redraws whole messages on an event. A GUI chat that does not stream tokens feels broken. Streaming is a new requirement, not a port, and it is the largest single risk in M1.
M0 is the exception to the rest of this page: it ships no UI and touches no network. It is done when its tests pass. See docs/src/design/core/agent-loop.md.
Milestones
| # | Milestone | Outcome | Ships |
|---|---|---|---|
| M0 | Core agent loop | A headless, tested loop: model turns, tool calls, approvals | robi-core: transcript, tool trait, registry, the loop, events, cancellation |
| M1 | Providers and streaming | The loop drives a real model and streams tokens | Provider clients, delta protocol, retries, model catalog |
| M2 | Desktop shell and chat | The loop in a Tauri window, with saved sessions | Tauri app, IPC, chat UI, sessions, persistence |
| M3 | Read-only tools | The assistant reads your workspace, with approval | read_file, find, grep, list_dir, approvals, compaction |
| M4 | Editing | The assistant changes your files and runs commands | write_file, edit tools, checkpoints/undo, git awareness, sandboxed shell |
| M5 | Modes and subagents | Ask, plan, and agent modes; read-only exploration | Modes, plan artifacts, tasks, explore, delegate |
| M6 | Code review | Review a diff with the assistant inline | Review sessions, hunks, inline comments. The screen is disabled in M11 |
| M7 | Code intelligence | Symbol-aware navigation and semantic retrieval | LSP client, AST chunking, embeddings, vector search. Removed in M11: the five language-server tools, the semantic index, the LSP client, read_code, and the tree-sitter grammars are deleted |
| M8 | Reach | Integrations and headless use | MCP client, skills, web tools |
| M9 | Tool output compression | Large tool results reach the model smaller, and the original stays retrievable | Content-routed compression, a retrieve tool, savings on the context meter |
| M10 | Docs view | Read and write project documentation | A filtered file tree, and an editor shared by the user and the agent. Disabled in M11 |
| M11 | Streamlining | A smaller shell: a top bar, and fewer surfaces | Streamlining roadmap. S2, S3 (UI), S5, and S6 have shipped |
The line between “usable” and “differentiated” falls after M5. M1–M3 produce a chat app that reads code. M4 makes it an agent. M5 is where Robi stops being a chat window and starts being a coding assistant.
graph LR
M0[M0 Agent loop] --> M1[M1 Providers]
M1 --> M2[M2 Chat]
M2 --> M3[M3 Read tools]
M3 --> M4[M4 Editing]
M4 --> M5[M5 Modes + subagents]
M4 --> M6[M6 Code review]
M5 --> M7[M7 Code intelligence]
M6 --> M7
M7 --> M8[M8 Reach]
M4 --> M9[M9 Output compression]
M5 --> M10[M10 Docs view]
M6 and M7 both need M4 but not each other. M8 needs M5. M9 needs M4: it compresses tool results, and the shell is where those results get large. M10 needs M5, and through it the M4 edit path. Only the M0→M5 spine is strictly serial. M9 and M10 do not gate M5–M8.
What remains
The M0–M8 spine is in the tree: the loop, OpenAI-compatible streaming, the chat shell, read and edit tools, the sandbox, modes, plans, delegate, session review, LSP, the semantic index, MCP, skills, and web tools. These pieces are still open. Delete a row when that piece ships, and update the milestone section that owns it.
M11 removed surfaces without removing code. The streamlining
roadmap turns off the review screen (S2), the index status UI
(S3), and the docs viewer (S5), and replaces the left sidebar with a top bar
(S6). The code, the API routes, and the design pages stay; src/app/surfaces.ts
is the switch. The rows below that belong to M6 and M10 are therefore not
“remaining” in the UI — they are waiting on a decision to restore the surface.
| Milestone | Piece | State |
|---|---|---|
| M3 | Permission and grant design page | Behavior exists in code. docs/src/design/workspace/permissions.md is still needed. |
| M3 | Price display | Deferred. Secrets stay in ~/.robi/secrets.toml. |
| M6 | Inline comments, and sending one to the assistant | Later, in docs/src/design/review/code-review.md. |
| M6 | A tool the assistant uses to read review state | Later. |
| M6 | Git status, a commit range, or a branch as a review source | Later. The screen is the session baseline. |
| M6 | Applying a suggestion through the edit path (F6.3) | Not built. |
| M8 | MCP sampling, elicitation, OAuth, resources, and prompts | Waiting, per docs/src/design/reach/mcp.md. |
| M8 | A trust decision before reading a project AGENTS.md | Later. |
| M9 | Built-in JSON and search-hit compression | Not built. docs/src/design/compression/tool-output-compression.md is later. D12 is settled for shell output. |
| M9 | Learned line model for shell output (phase 4) | Not in the first cut. Feature-gated and last (D11). |
| M9 | Context meter showing tokens saved | Required by the M9 exit criteria. The meter shows usage. |
| M10 | Docs view: filtered tree, shared editor | The read-only viewer (docs/src/design/shell/docs-viewer.md) and the editor with autosave (docs/src/design/shell/docs-mode.md) are built. Widening the filter past markdown is later. |
M0 — Core agent loop
Goal — a headless agent loop that runs model turns, resolves tool calls, pauses for approval, and emits events. No UI, no network, no Tauri.
Build this first, and build it alone. Every later milestone is a variation on this loop: M1 swaps a stub model for a real one, M3 adds tools that touch the filesystem, M5 adds modes that select which tools are visible, M6 and M7 hang off turns. Get the turn lifecycle right here, where a test drives it deterministically, and every later milestone is an addition to a proven core.
gogent is the specification. It is a few hundred lines of loop under roughly
1,700 lines of tests, and that ratio is the point: the loop is small, its state
machine is not obvious, and the tests are what prove it. Port the semantics;
rewrite the implementation in Rust.
F0.1 The core crate
robi-core holds the loop and nothing else. It does no I/O, and depends on no
Tauri, no HTTP client, and no provider SDK:
robi-core— transcript types, the tool trait and registry, the loop, approval state, the event sink. Depends ontokioandserde, and nothing else in the workspace.- Traits, not implementations. The loop sees only
Model,Tool,MessageStore, andEventSink. M1 supplies a realModel, M2 supplies a realMessageStore, and M3 onward supply realTools. The loop never changes when one of those arrives. - One crate for implementations, not one per concern.
crates/robiholds the implementations:providersfirst (M1), then the session API’sdomain,adapters, andweb_api(M2),toolsandworkspace(M3),review(M6) — each a module, split into its own crate only if a module outgrows the crate.docs/src/design/providers/providers-streaming.mdrecords why providers did not becomerobi-providers.
The dependency direction is one-way. Everything depends on robi-core, and
robi-core depends on nothing else in the workspace. That is what makes the next
point possible.
The reason to hold that line is testability. gogent’s entire test suite runs
against a stub model and an in-memory store, and never touches a network or a
filesystem. Robi does the same in M0: the loop cannot reach anything the test did
not hand it, so every behavior below is provable in a unit test.
- Open decision — (D3) in-process loop vs. sidecar binary. It changes nothing in this milestone, because the loop is a library either way, but the trait boundaries are what keep the choice reversible.
F0.2 Transcript model
Port these types from gogent (message.go, tool.go) with the same names and
the same semantics. The shape is load-bearing: the loop reads status off the
transcript instead of keeping a side table, so a resumed session needs no
separate state to reconstruct.
| Type | Fields | Notes |
|---|---|---|
Message | id, role, content, tool_calls, tool_call_id, usage | Roles: user, assistant, tool |
ToolCall | id, name, args, approval_status, execution_status, result, error, provider_call_id | Status enums, not booleans. id is loop identity; provider_call_id is the wire id the provider issued, echoed on the next request (D3) |
Usage | input, output, cached | On the assistant message; drives the context meter in M3 |
Turn | derived, never stored | A user message up to the last assistant message |
Three predicates carry the logic, and each is worth its own unit test:
has_tool_calls— the message describes work that has not been answered yet.can_execute_tools— every call in the turn is approved and unattempted.all_tool_calls_approval_settled— no call is left pending, which is exactly what distinguishes a turn that can resume from one that is paused.
Do not model status as booleans. A call is pending/approved/rejected and
not_started/running/succeeded/failed, and the loop branches on those
states in more combinations than booleans survive.
F0.3 Tool trait and registry
#![allow(unused)]
fn main() {
#[async_trait]
trait Tool: Send + Sync {
fn name(&self) -> &str;
fn description(&self) -> &str;
fn parameters(&self) -> serde_json::Value; // JSON Schema
async fn requires_approval(&self, args: &Args) -> Decision; // side-effect free
async fn execute(&self, args: Args, cancel: CancellationToken) -> Result<ToolOutput>;
}
}
- The registry rejects a duplicate name, lists tools sorted by name so prompt
assembly is byte-stable across runs, and is held behind a shared handle so a
tool registered after the loop is built is still visible to it. gogent passes
the registry by pointer into
NewAgentfor that reason. - Tool definitions are the prompt. A schema
descriptionis the main lever on whether the model calls a tool correctly, so treat it as reviewed copy rather than a doc comment. That is why the description lives on the trait instead of in a side table. requires_approvalis the only subtle method: it decides from that call’s arguments and has no side effects, so the loop can ask “would this need approval?” without doing anything. That property is what lets the loop decide a whole turn’s approvals before executing any of it (F0.5).
F0.4 The loop
The loop is a repeat-until-settled function. Port it from gogent’s agent.run:
fn run(session, invoke_model):
loop:
settle_unresolved_tool_calls(session) # may pause; see F0.5
if paused_awaiting_approval(session): return Paused
if settled_tool_calls: invoke_model = true # the model must read the results
if not invoke_model: return Ok # nothing outstanding, nothing new
if model_turns_this_run >= max_iterations: return Err(MaxIterations)
assistant = model.generate(transcript) # one model turn
append(assistant)
if not assistant.has_tool_calls(): return Ok
process_tool_calls(assistant) # F0.6
invoke_model = true # loop so the model reads results
Three details decide whether this is a good loop:
- Iterations count model turns, not tool calls. Tool fan-out inside one turn is free. The cap exists to stop a model that calls tools forever, so it must count the thing that recurs.
- The transcript is the only state. The loop derives paused, runnable, and done from stored messages. Nothing lives in a local that a restart loses.
- The stop conditions are enumerable, so write them down and test each one.
Settling tool calls is not one of them: the loop continues into a model turn so
the model can read the results, which is where
resumediffers from a settle-only operation.
| Stop condition | Result |
|---|---|
| Assistant message has no tool calls | Turn complete |
Model turns reached max_iterations | Turn ends with an error; transcript intact |
| A tool call awaits approval | Paused, and resumable (F0.5) |
| A tool errored | Recorded as a tool result; the loop continues |
| The model errored | Turn ends with an error |
| Cancellation fired | Turn ends; transcript left resolvable (F0.7) |
| Settling tool results on resume | The loop takes a model turn so it can read them |
Model::generate is async from day one, even though M0 ships only a stub
implementation. Making it async later would touch every call site; leaving it
async now costs nothing, and it is what lets M1 stream behind the same trait.
- The defaults are settled — an iteration cap of 50 and an in-flight tool limit of 5, with a serial debug mode that runs every call alone in model order. A settings layer overrides them; the loop ships the defaults.
F0.5 Approval and the paused turn
This is the invariant the whole design rests on, and the one to test hardest:
User input never runs ahead of an unresolved turn. If the transcript ends with tool calls that are not settled, the next thing that happens settles them, whatever the user typed.
gogent enforces this in RunWithUserInput: it applies unresolved tool calls
first, and returns ErrAwaitingApproval when the outstanding turn still needs a
decision, rather than appending the user’s new message. Port that behavior
exactly. The alternative — appending the user message and letting the model see
an unresolved call — produces a transcript no provider accepts and no user can
reason about.
The approval surface is three operations and no more:
list_pending_tool_calls(session)— what the UI renders as cards.approve_tool_call(session, call_id)— settles one call, then resumes the loop.reject_tool_call(session, call_id, reason)— settles it as rejected, so the model reads a structured rejection rather than silence.
Approval is asynchronous with respect to the loop. The loop runs until it needs a
decision, returns Paused, and waits to be called again. It does not block a
thread on the user, and it does not poll.
Resuming is not a settle-only operation. Once the outstanding calls are settled, the loop takes a model turn so the model reads their results (F0.4). A resume that settles nothing stays a no-op.
- A turn is decided as a whole. gogent evaluates every call’s
requires_approvalup front, and runs the turn only when none of them needs approval. Robi keeps that: no half-decided turn, where some calls ran while others wait on the user (F0.6).
F0.6 Tool execution
gogent runs a turn’s tool calls in three phases, and the order is the design:
- Decide — sequential over every call in the turn, calling
requires_approval. Sequential because a decision must be side-effect free and reproducible; concurrent decisions would make approval order nondeterministic. - Execute — in model order, in segments. A tool declares
ConcurrentorExclusive; the loop walks the turn’s calls in order, batches consecutive concurrent calls into parallel runs bounded by a semaphore (gogent defaults to 5 in-flight calls), and runs an exclusive call alone as a barrier. Reached only when every call in the turn is already approved. - Assemble — results are committed to the transcript in model order, not completion order. A provider matches results by id, but a transcript that reorders across runs is a transcript the model reads differently.
Two passes over a turn — all concurrent calls, then all exclusive — would reorder execution against model order, so a read meant to verify a write could run before that write while the transcript still read correctly. Segments are what keep execution order and transcript order equal. The full algorithm, the barrier rule, and the escalation rule are in docs/src/design/core/agent-loop.md.
Two rules from gogent that look like details and are not:
-
A failing tool does not abort its siblings, and does not end the run. The failure becomes a structured tool-result message the model can read and correct, and the loop continues. gogent deliberately does not derive a cancellable child context for the fan-out, so one tool failing or cancelling cannot take the rest of the turn with it.
-
Tool::executemust be safe to call from several tasks whenever the tool declaresConcurrent, which is the default. Any state a tool keeps goes behind its own synchronisation. The registry carries a snapshot test asserting each tool’s setting, so a new tool fails until its author states one. -
Defaults — 5 in-flight calls, and a serial mode that runs every call alone in model order for reproducible debugging. The serial mode overrides a tool’s concurrency declaration rather than the segment walk, so only the parallelism goes away.
F0.7 Events and cancellation
EventSinkmirrorsgogent::ChatEventBroadcaster: a trait with oneemitmethod,NopandChannelimplementations, and events carrying the session id and message id. The loop emits delta-level events from M0, soMessageDeltaandToolCallUpdatedare exercised by tests with a stub model that streams. M1 adds the providers that produce them.- Emit after persisting. An event reports that state changed, so the store
write happens first. An event that overtakes the write is a UI rendering a
message the store does not have yet. M1 adds delta-level events
(
MessageDelta,ToolCallUpdated,UsageUpdated,AwaitingApproval), but the ordering rule is set here. - Cancellation is a
tokio_util::sync::CancellationTokenthreaded intoModel::generateand everyTool::execute.gogenthas only a Gocontext.Contextand no stop API; a desktop app needs a real Stop button, so cancellation is a first-class path rather than an afterthought. - Cancellation is a state, not an exception. A cancelled turn must leave a transcript that is either resumable or cleanly finished — never a half-written assistant message with dangling tool calls. Decide here what a cancelled turn looks like on disk, because M5’s subagents inherit the answer.
Exit criteria for M0 — robi-core is a library with no UI, and its behavior
is proven by tests: a single turn with no tools; a multi-iteration tool loop;
streamed Text and Reasoning deltas reaching the sink; serial mode producing
the same transcript as concurrent mode for the same turn; an unbounded tool result
hitting the 256 KiB backstop; a tool error that does not end the run; execution
order matching model order when an exclusive call splits a batch; an approval
pause followed by a resume; a rejection that reaches the model as a rejection;
max_iterations tripping; and a cancellation that leaves the transcript
resolvable. No network, no filesystem, no Tauri — a stub Model and an in-memory
store drive every case.
Design doc — docs/src/design/core/agent-loop.md.
M1 — Providers and streaming
Goal — drive the M0 loop with a real model, and stream tokens into it.
M0’s Model trait is already async and already cancellable, so this milestone
is the first implementation that touches a network.
robi-core did change, and the trait was wrong. M1 added three things, all
recorded in design/providers-streaming.md:
Model::generatenow takes theSessionId. The loop already held it, and the provider needs it as a per-conversation routing and cache key. Deriving it inside the adapter from the transcript was rejected: compaction (M3) rewrites the transcript’s first message, which would silently rotate the key (D4).ToolCallgainedprovider_call_id: the id the provider issued, echoed on the next request. Loop identity stays the local UUID, so a provider id that is reused, absent, or malformed cannot confuse approval or lookup (D3).model_turnselects on the cancel token aroundgenerate. Without it, a cancel that fires before the response headers arrive surfaces as a transport failure rather thanCancelled, because the two-variantModelErrorcannot express a cancellation.
A fourth change is a bug fix rather than a design decision: pending_tool_calls
had to stop offering already-executed calls for approval. It is described under
“Where M1 stands” below.
None of these touches the loop’s algorithm. The lesson for later milestones is that a trait is only “fixed” once a real implementation has exercised it.
F1.1 Provider clients
- First provider: OpenCode Go, over the OpenAI-compatible chat-completions wire format. One client serves every endpoint that speaks it: Kimi, DeepSeek, and OpenRouter are the same request shape with a different base URL, credential, and model table.
- Second provider: Anthropic, over its native Messages API. It is a separate
adapter (
providers/anthropic/), because the request shape (top-levelsystem, requiredmax_tokens,input_schematools, content blocks) and the typed SSE event stream differ from chat-completions. The design is A1–A12 in providers-streaming.md. The two constraints that shape it: Haiku 4.5 rejects the effort parameter, and the user never picks a provider — the model id’socg_/ant_prefix does. - What the OpenCode Go endpoint requires, now that it is built and tested:
POST {base}/chat/completionswithstream: trueandstream_options.include_usage. Base URLhttps://opencode.ai/zen/go/v1.Authorization: Bearer <key>, andx-opencode-session: <SessionId>. The header is what the provider keys routing and prompt caching on, so it must be the conversation’s id, stable across turns and restarts (D4).- The model id on the wire is the bare id (
glm-5.3), never theocg_glm-5.3form the catalog and configuration store (A11). - A client that names itself in
User-Agent; the vendor asks for this rather than a library default.
- Port gopi’s model catalog of context windows. They are not decoration: M3’s context meter depends on them. The table is vendored, not fetched, so startup does not need the network — and it lists only tool-capable models, because a model that cannot call tools cannot drive the loop. That catalog rule is the local “D9” in providers-streaming.md, not the sandbox D9. Prices are deferred until something displays them.
- Settled — one HTTP client with per-provider request and response mapping, not a typed SDK per provider, because the delta mapping and tool-call assembly are written either way and no official Rust SDK exists. See D1.
F1.2 Streaming and the delta protocol
- gogent’s
GenerateResponseis a blocking call that returns oneMessagewhen the whole response is done, and gopi’s TUI redraws on whole-message events. A chat window cannot. This is the largest single risk in the plan, because the delta protocol is the boundary the whole UI is built against. - Emit typed deltas, never raw SSE:
Text,Reasoning,ToolCallStart,ToolCallArgs,ToolCallEnd,Usage,Finished,Failed— the M0 variant list, which this milestone fills in rather than extends. - Partial tool arguments matter. A tool card should appear while its arguments are still streaming, so the user sees what is about to happen before it happens. That needs delta-level tool-call events, which gogent’s whole-message broadcaster cannot express.
- Reasoning traces: gopi models this as “effort” and gogent as
WithReasoningEffort. The delta vocabulary is fixed in M0 and includesReasoning, so the loop forwards traces from the start. Whether the UI shows, collapses, or drops them is a chat-UI decision (M2). - Settled — (D2) the delta serialization and its IPC encoding is still open;
SSE is decoded by hand rather than by a crate, because the inter-chunk timeout
and the cancellation path have to live in the same loop as the read (D6); and a
mid-stream provider error arrives as an error object inside the 200 body, which
becomes
Delta::Failed.
F1.3 Reliability
- Retries with backoff on 429 and 5xx, and an explicit statement of what is not retried: a cancellation, and any 4xx that is not a rate limit.
- Neither gogent nor gopi has a retry layer. This is new work.
- Settled — a retry is confined to the window before the first delta reaches
the loop, which is what keeps it from duplicating a partially-rendered message:
the adapter retries the request, never a stream in progress. 429 (honouring
Retry-After, capped at 8 s), 5xx, and connect timeouts are retried; a cancellation and every other 4xx are not. Three attempts, exponential backoff with full jitter (D7).
F1.4 Model and effort selection
- Per-session model and reasoning effort, with provider-level defaults.
- Switching model mid-session is allowed; the transcript is provider-agnostic.
- The active model is visible where the user types, not buried in settings.
- The choice is resolved when a session actor is built. Session override,
then the settings default, then the built-in model.
Agentkeeps holding oneArc<dyn Model>for that execution. The concrete design is under D8 in design/providers-streaming.md.
Exit criteria for M1 — the M0 loop, with only the three core changes listed above, driving a real provider: streaming tokens and partial tool arguments, surviving a rate limit, and cancelling mid-stream without corrupting the transcript.
Where M1 stands. F1.1 through F1.3 are built and tested against a fake
provider that speaks the real wire format — both OpenAI chat-completions and
Anthropic Messages: streaming, tool-call assembly with the provider’s ids, the
Anthropic thinking-block round trip, the retry policy, timeouts, cancellation, and
an Agent turn end-to-end. cargo run -p robi --example simple drives the same
stack by hand against a real endpoint, with one tool that needs no approval and
one that does, and picks the provider from ROBI_MODEL’s prefix. Two things
remain before M1 is done:
- No live turn has been run. Every test uses a scripted loopback server, so each vendor’s exact framing is still an assumption. The example is how to check it; run it once per provider with a real key.
- F1.4 is in the chat shell. Settings hold the default model and effort. A session stores an override, and the next actor reads it. See persistence.md and chat-ui.md.
Running the example by hand already paid for itself: it exposed a core bug where
pending_tool_calls offered an already-executed call for approval, because it
filtered on ApprovalStatus::Pending and the loop only records a decision a user
made. The fix and its tests are in robi-core; see
providers-streaming.md.
Design doc — docs/src/design/providers/providers-streaming.md.
M2 — Desktop shell and chat
Goal — the loop in a Tauri window, with saved sessions.
F2.1 Tauri shell and IPC
- Solid + TypeScript + Vite front end in
src/. Tauri 2.x is the current stable line (Tauri). - Commands in, events out: the UI posts a message or settles an approval over
HTTP, and subscribes to
GET /api/v1/events/streamfor updates. The stream is specified in events-sse.md. - The desktop app runs the API in-process (D3).
robi-apistays the headless andpnpm devprocess, so a UI crash is not the only way to run the loop. Event delivery is HTTP SSE (D1, settled indocs/src/design/shell/events-sse.md).
F2.2 Chat UI
- Message list, composer, streaming render with a caret, and scroll-lock that yields when the user scrolls up.
- Markdown rendering, plus syntax highlighting in code blocks (still open). A
fenced
mermaidblock renders as a diagram in assistant text, on a plan page, and in the markdown file preview. - Copy a message, copy a code block, retry the last turn, edit-and-resend.
- Tool-call cards exist in the layout from day one — collapsed and empty until M3, and they are where approval prompts will live. Retrofitting cards into a text-only message list is a rewrite.
- Open decisions — the collapsed/expanded default for a card, and whether expansion state persists per session.
F2.3 Sessions and persistence
- Session list with titles, last-used time, and workspace. A workspace is a named directory root. The shell shows one workspace at a time and lists that workspace’s sessions. Path confinement stays in M3. The model generates the title after the first turn; creation leaves it unset unless the client supplies one.
MessageStoregets its real implementation here. Nothing inrobi-corechanges.- Secrets go in
~/.robi/secrets.toml, non-secrets in~/.robi/config.toml. The secrets file is written0600and refused when group or world can read it. Callers read both throughSettingsStore, so a later backend can put secrets in the OS keychain. - Open decisions — whether a workspace needs the explicit trust decision
gopi records in
trust.json. The session store is SQLite; seedocs/src/design/persistence/persistence.md. Token-usage history leans toward that same file. Settings live under~/.robi. The database file stays onROBI_DATABASE_URL.
Exit criteria for M2 — send a message in the app, watch it stream, restart, and find the session intact.
Design docs — docs/src/design/shell/visual-style.md, docs/src/design/shell/chat-ui.md,
docs/src/design/persistence/persistence.md, docs/src/design/shell/chat-runtime.md.
M3 — Read-only tools and approval
Goal — the assistant answers questions about your code by actually reading it.
This is where the safety model lands. Build it here, when every tool is read-only, so the approval path is exercised before anything can write.
F3.1 Read tools
Port from gopi’s internal/tools/, keeping names and semantics:
| Tool | Behavior |
|---|---|
read_file | Line ranges, offset/limit, truncation reporting |
find | Path substring or glob walk |
grep | Content search, regex optional |
list_dir | One directory, with the session path rules applied |
Two details from gopi worth copying rather than reinventing:
- Results must report truncation explicitly, with the exact text to continue from. A silently truncated read is how an agent confidently edits the wrong thing.
- Search results cap at a match count and a byte budget, and say so.
Tool arguments, path resolution, the session path filter, and the ripgrep fallback are in docs/src/design/tools/read-tools.md.
F3.2 Workspace confinement
- Resolve one canonical workspace root per session; every path resolves against it and re-checks after symlink resolution.
- Ignore rules:
.gitignoreplus a user ignore file, on by default. - Protected paths that always prompt:
.env, key material, VCS internals, the app’s own config directory.
F3.3 Approval and policy
gopi uses three independent gates. Keep all three; they compose well.
- Per-call approval — the tool decides from its own arguments, with a
side-effect-free
requires_approval(&self, args) -> Decision. This is what makes “read inside the workspace” free and “read outside it” a prompt. - Policy engine — a floor of globs the model cannot talk its way past, plus user ignore rules.
- OS sandbox — for child processes only.
- Approval UI must show the exact arguments and the resolved absolute path, not the model’s summary of them. Approve/deny per call, with “allow for this session” as an explicit, visible grant.
- Read grants are session-scoped and inherited read-only by subagents (M5).
F3.4 Context and compaction
Do this in M3, not later. A session that reads files fills the window quickly, and every feature after this one adds context pressure.
- Token accounting per message; a visible context meter. Shipped.
- Auto-compaction when the window fills, plus a manual trigger. gopi ships
manual-only
/compact; a GUI should do it automatically and say when it did. Settled in context-management.md: a lossy summary of the older prefix, the current turn kept whole, the system prompt left alone because it is not a message. Shipped: auto at 80% of the window, Compact in the meter popover, the summary markedcompaction: true, and thetranscript_compactedevent. - Compaction rewrites older turns once the window fills. Shrinking one result as the tool returns it, and keeping the original retrievable, is M9. The two compose: compression keeps a turn inside the window longer, and compaction still runs when the window fills anyway.
Design doc needed for F3.3 — the approval and grant model.
See docs/src/design/workspace/permissions.md.
M4 — Editing
Goal — the assistant changes files safely and reversibly, and runs commands only inside an OS sandbox. The two arrive together: an edit tool that cannot run a test is half a workflow, and a shell tool without a sandbox is not one to ship.
F4.1 Write and edit tools
write_filefor new files and full rewrites.delete_fileremoves one file.edit_filefor targeted changes, by exact search-and-replace. Settled in D5 and editing-tools.md.- An ambiguous or non-unique match is an error with a diagnostic, never a best-guess write. A path the write rules deny waits for approval on that call.
F4.2 Checkpoints and undo
Every edit is a checkpoint the user can revert, independent of git. The checkpoint is the session’s baseline for that path, specified in checkpoints.md. Putting a hunk back is the review milestone.
F4.3 Verification loop
- After an edit, re-read or re-check the region and report what actually changed rather than what was requested.
- Git awareness: read status/diff, never run history-rewriting commands without approval.
- Diagnostics were LSP’s job in M7. That surface is gone, so verification is
cargo check,tsc --noEmit,eslint, and the project’s tests through the shell tool.
F4.4 Sandboxed shell tool
- The one tool with unbounded blast radius, and the only tool that runs inside an
OS sandbox. Settled in D9 and shell-tool.md:
deny by default, a constructed
PATH, scrubbed environment, workspace-rooted cwd, andunsandboxed: trueonly after approval. - The sandbox is a requirement, not an option. A sandboxed call is refused
where no mechanism exists. An approved
unsandboxed: truecall is the only way that command still runs. macOS uses Seatbelt. Linux uses bubblewrap. Windows has no sandbox in this design. - The sandbox bounds the process; it does not replace approval. A command that
leaves the default profile still needs a decision, still clears the policy
floor, and still runs under the sandbox unless the user approved
unsandboxed. - Output is a bounded artifact, not a stream into the transcript: a build can
produce megabytes, so the tool reports a truncation like every other tool
(
LoopConfig::max_tool_result_bytes) rather than appending all of it.
Design docs needed for F4.1, F4.2, and F4.4.
See docs/src/design/tools/editing-tools.md, docs/src/design/tools/checkpoints.md, and
docs/src/design/tools/shell-tool.md.
M5 — Modes and subagents
Goal — the assistant behaves differently by intent, and explores without polluting the main conversation.
F5.1 Agent modes
Three modes, ported from gopi’s app.Mode*:
| Mode | Tools | Purpose |
|---|---|---|
ask | Read-only, no writes, no shell | Answer from the codebase without changing it |
plan | Read + shell + plan authoring | Produce a plan artifact; do not edit |
agent | Everything | Execute |
A mode selects a tool set and a prompt prefix. Nothing else. Keep the mechanism that narrow — gopi’s implementation is a registry per mode plus a prefix, and that is why switching is instant and stateless.
F5.2 Plan artifacts
- Shipped as S9 and rewritten since: there is no plan tool. A plan is a
directory in the workspace,
.robi/plans/<name>/, holdingPLAN.mdfor the prose andTODO.mdfor the checklist. The agent writes both with the shell. - The name is the plan’s title in kebab case; Plan mode lists the directory first so a second turn updates the existing plan.
.robi/plans/.gitignoreholds a single*, so nothing there is tracked, including the ignore file itself.- Plan mode’s shell may write that one directory and nothing else; Agent mode writes it as part of the workspace. See S9 in streamlining.md.
F5.3 Tasks / todos
- Shipped as S9 and rewritten since:
TODO.mdis the checklist, one line per step,- [ ]open and- [x]done, andPLAN.mdcarries no checkboxes. - Nothing is stored: no session column and no prompt injection. Agent mode reads
the files with
catand ticks a step by rewritingTODO.mdafter reading it.
F5.4 Subagents
One delegate tool, two child modes. See subagents.md.
explore— read-only child (read_file,list_dir,find,grep). Its value is context isolation: the parent gets the answer, not the file bodies.general— the explore tools plus a sandboxed shell. No edits, nogrant, no nesteddelegate.- Caps:
subagent_max_iterationsmodel turns (default 50) for either child, 6 explore calls and 4 general calls per session, andsubagent_timeout_seconds(default two minutes) either way. A spent budget returnsexplore_limitordelegate_limit. - Fail closed. A child call that would need approval returns
access_denied. The user is never prompted from inside a child. - The child’s tool calls render as rows on the parent card while it runs, and stay there after refresh. Children in one turn may run in parallel. The child transcript is in memory and is not a chat session.
M6 — Code review
Goal — review a change with the assistant inline, instead of pasting diffs.
F6.1 Diff engine and review sessions
- A review is a first-class object: a baseline plus a set of hunks, stored per
session. gopi computes diffs for
/reviewand stores baselines keyed by hash. - Sources: uncommitted changes, a commit range, or a branch against its base.
- Keep the diff engine in its own crate (
robi-review) so the editing tools can reuse it for verification.
F6.2 Review UI
- Unified and side-by-side views, file tree with per-file status, hunk navigation.
- Inline comments anchored to lines, and a way to send a whole review or one comment to the assistant as context.
- The assistant must be able to read review state as a tool, so “review my changes” and “what did I get wrong in this hunk” are one turn.
F6.3 Applying suggestions
- A suggested change arrives as a diff against the review baseline and applies through the M4 edit path, so it gets a checkpoint like any other edit.
The review screen is code-review.md. It can approve or reject a file or one hunk, and Reject with reason sends the rejected file or hunk to the assistant as a file attachment with the user’s note, so it can iterate. Inline comments and a review tool for the assistant stay later.
M7 — Code intelligence
Removed in M11. The milestone shipped two tracks — an LSP client and a semantic index — and both are gone. This section records what they were and why they went, so a return starts from a decision rather than a blank page.
The index, the LSP client, the five language-server tools, semantic_search,
read_code, and the tree-sitter grammars were deleted. Nothing is behind a
Cargo feature. grep, find, read_file, and the shell are the retrieval and
verification path.
F7.1 LSP client (removed)
Was: async-lsp with lsp-types. tower-lsp is a server framework and was not
the client. One stdio server per catalog row per workspace root, started on the
first tool call; the disk was the text the server saw. The first cut was five
read-only tools: diagnostics, definition, references, hover, and
workspace_symbol. A missing binary returned available: false and the model
used grep or shell. The catalog was Rust, TypeScript and JavaScript, Python,
Go, and C and C++. Rename, code action, and format never shipped.
Why it went: the tools went unused in practice, and verification through the
shell (cargo check, tsc, eslint, the project’s tests) was both available
and more honest than a diagnostics snapshot. With no tool driving the client,
the client itself was dead weight.
F7.2 Semantic search (removed)
Was: tree-sitter splitting source on symbol boundaries, a local ONNX model
embedding those chunks on device (D6), and sqlite-vec plus FTS5 sharing one
file per workspace (D7). Retrieval fused the two lists, and semantic_search
returned paths and line ranges. The index updated while a workspace had an open
session, and the user could pause it.
Why it went: agents did not call semantic_search often enough to justify an
embedding runtime, a vector store, and a background index task. That is a real
downgrade for “where is this concept handled?” questions, and the prompt says so:
search by identifier and filename first, then read the hits.
read_code was the last user of the tree-sitter outline. It went with the
grammars rather than staying as a second read_file.
M8 — Reach
Lower priority. Sequence by user demand, not by this order.
- MCP client — Robi as an MCP host, so tools come from outside. Settled in
mcp.md. The official Rust SDK is
rmcp(rust-sdk). - Skills — implemented. Markdown instruction files with frontmatter,
catalogued in the prompt and loaded on demand. The user names one with
/id. The model may load one with theskilltool. A bundledcreate-skillwrites a new one. Discovery roots include.robi/skills,.agents/skills, and the Claude, Codex, Cursor, and OpenCode directories, at home and in the workspace. See design/skills.md. - Project instructions — the assembler and the
AGENTS.mdchain are in instructions.md. Skills and a trust decision before reading a project file stay later. - Web tools —
web_searchandweb_fetch, settled in web-tools.md. Every search waits, because each call spends Brave quota. A fetch waits the first time a host is used in the session, then remembers that host. Page text and snippets are untrusted.
M9 — Tool output compression
Goal — a large tool result reaches the model as a smaller, faithful view of itself, and the original stays on disk so the model can read it back. The user still sees the full output.
Headroom is the behavioral reference: it routes each payload by content type, caches the original locally, and gives the model a retrieve tool. Reported savings are large on JSON arrays and logs, and near zero on source and grep hits that are already dense. Robi compresses a result once, in-process, when the tool returns it. Headroom stays a reference, not a dependency. A proxy in front of the provider would rewrite the outgoing request, including history the transcript already stored, and that rewrite is what busts a provider’s prompt-cache prefix.
F3.4 compacts older turns when the window fills. This milestone runs earlier, on a single result, before that result is appended. A tool’s own bound, and the 256 KiB core backstop, discard a tail and say where to continue. Compression keeps a smaller view of the same bytes and a way back to them. A result under the size gate is stored unchanged.
F9.1 The boundary
Compression sits after Tool::execute and after the tool’s own truncation,
and before the result is appended. The original a retrieve call can return is
the bounded result the tool reported, including its truncation notice. It is
not the unbounded stream the tool chose to drop. Order:
- The tool bounds its result and reports where to continue.
- The compressor shrinks that result, if it is large enough and of a shape it knows, and stores the pre-compression bytes with the session.
- The core’s
max_tool_result_bytesbackstop still applies to whatever the compressor returned.
One pipeline covers every tool, including MCP tools when M8 arrives. A tool does not grow its own crusher.
The loop stays free of I/O. robi-core calls a compressor trait and records
that a result was compressed, plus the id of its original. The implementation
and the original store live in crates/robi. Tests keep a pass-through
compressor, so cargo test -p robi-core still touches no file. Originals share
the session’s lifetime: deleting the session deletes them. Redaction runs
first, so the stored original is the scrubbed result.
A compressor that saves nothing, or that fails, returns the original. A compression error never fails the turn.
F9.2 Content-routed compressors
Detect the shape and pick a compressor. The default path is deterministic and makes no model call.
| Content | What the model keeps |
|---|---|
| JSON arrays and objects | The schema, a sample of rows, and counts or aggregates for the rest |
| Logs and shell output | The head, the tail, and collapsed repeated lines. The phases, the store, and the decision to keep a learned model last are in shell-output.md |
| MCP tool results | A JSON array or object keeps a sample, key types, and counts. Other text uses the shell line pass. The row is kind: "mcp". See mcp-output.md |
| Search hits | Paths, line numbers, and a capped set of matching lines |
| Source, short text, errors | The original. These are already dense, and a crushed file is how an agent edits the wrong lines. read_file stays on this row |
The compressed body says that it was compressed, how big the original was, and the id the retrieve tool takes. A silent crush has the same failure mode as a silent truncate.
- Open decisions — (D11) a local learned text model, in the style of
Headroom’s Kompress fallback, versus staying on structural compressors. For
shell output that choice is phased in
shell-output.md: structural passes ship first, and
the learned model is last, feature-gated, and outside
robi-core. Still open for the other shapes: which results always pass through because the model must quote them exactly (edit failures, diagnostics, plan text), and the size gate below which a result is stored byte-identical. Shell’s gate is 4 KiB per stream, in that page.
F9.3 Retrieval
The compressed text is what the next model turn sees. The original is stored
with the session, keyed so a restart can still fetch it. A retrieve tool
returns that original, or a slice of it, when the compressed view is not
enough.
The tool card renders the original. The context meter (F3.4) shows tokens saved on the turn as well as tokens used. A compression the user cannot see will be turned off the first time it hides a bug.
- Open decision — (D12) whether the transcript itself stores only the compressed form, with the original in the session store, or stores both and lets the provider request select the compressed form. Shell output is settled in shell-output.md: the transcript stores the compressed view, and the session blob file holds the bounded streams. The same question is still open for JSON and search hits. M0’s rule is that the transcript is the only state the loop needs to resume. Retrieval has to survive a restart without breaking that rule, and without rewriting earlier turns: stable prefixes stay byte-stable so a provider prompt cache survives.
Exit criteria for M9 — a large JSON or log result is what the model reads in compressed form; the model can retrieve the original after a restart; a short result and a pass-through shape are byte-identical; a compressor failure passes the original through; the tool card shows the full output; the meter shows the saving.
Design doc needed for M9.
Shell and log output is shell-output.md. MCP
results are mcp-output.md. JSON from built-in
tools, search hits, and the other pass-through shapes are still
docs/src/design/compression/tool-output-compression.md.
M10 — Docs view
Goal — read and write project documentation in one place. The window is a filtered file tree and an editor. The user and the agent change the same files.
A view, not an agent mode. The documentation screen is a route (#/docs)
with a toolbar; the mode enum stays ask, plan, and agent. The agent changes docs
with the same edit tools it uses everywhere, so no new registry or prompt prefix
is needed. It needs M4. It does not need review, the index, MCP, or compression.
F10.1 Project navigation
- A file tree of the workspace, filtered to documentation. Markdown and the docs directories are in. Source files, build output, and ignored paths are out.
- Choosing a file opens it. The filter is the default. The user can widen it when a page names a file outside that set.
The read-only viewer is built: see docs/src/design/shell/docs-viewer.md. Widening the filter is still to come.
F10.2 Editing
- The open file is an editor. The user types in it. A save goes through the M4 write path, so a manual edit gets a checkpoint like an agent edit.
- The agent edits the open file, or another doc, with the existing edit tools. The editor shows that change. There is one copy of the file.
Built: see docs-mode.md. The open page mounts a
CodeMirror editor behind a Preview | Edit toolbar. Each keystroke
re-arms a one-second debounce; the accumulated CodeMirror change set is saved
through the M4 write path. The server reconciles the delta against the disk with
a three-way merge, and the user’s edit wins where the two overlap. A
robi.workspace.v1.file_changed frame is published by every write — the editor
save and the edit tools — so the viewer refreshes the tree, and the open page
when it has no unsaved edits.
Exit criteria for M10 — open the docs tree, open a page, change a sentence by hand, ask the agent to revise another page, and find both changes in the tree after a restart.
Design docs — docs/src/design/shell/docs-viewer.md (reading) and
docs/src/design/shell/docs-mode.md (editing), both done.
Cross-cutting concerns
These are not milestones. They apply to every one, and the first two apply from M0.
| Concern | Position |
|---|---|
| Tool definitions are the prompt | Schema descriptions are the main lever on tool-calling quality. Treat a tool’s description as reviewed product copy, not a comment. |
| Fail closed | Any path that cannot decide returns an error into the transcript. Never a best guess, never a silent prompt from inside a subagent. |
| Cancellation is a state, not an exception | Every turn must be resumable or resolvable after a stop. No half-written transcripts. |
| Redaction | Secret values and token shapes are scrubbed from tool arguments, results, and logs before they reach the model or an audit file. |
| Context budget | Every tool result declares its size and truncation point, and the core holds a 256 KiB backstop on any single result. Nothing grows unbounded. M9 compresses a large result in place; the backstop still applies to what remains. |
| Untrusted input | File contents, search results, web pages, and MCP responses are data. A prompt-injection attempt in a read file must not be able to trigger a write. |
| Path confinement | One workspace root per session, re-checked after symlink resolution, on every access. |
| Audit log | Every approved side effect, recorded with its arguments. |
Decisions to make
Each of these blocks a design doc. The order below is roughly the order to resolve them.
| # | Decision | Blocks | Notes |
|---|---|---|---|
| D1 | UI event delivery | F2.1 | Settled: HTTP SSE on the local API, CloudEvents envelope, in-process fan-out. See docs/src/design/shell/events-sse.md. Emit-after-persist still orders events against the store. The desktop process hosts that API (D3) |
| D2 | Delta serialization and IPC encoding | F1.2 | The variant list is fixed in M0; these are the wire details. Expensive to change once the UI depends on them |
| D3 | In-process loop vs. sidecar | F2.1 | Settled for the desktop app: the API runs in the Tauri process. robi-api remains for headless mode and pnpm dev. ROBI_EXTERNAL_API=1 points pnpm tauri dev at that separate process |
| D4 | Persistence: SQLite for the session store | F2.3, F3.4, M7 | Chosen for sessions: one SQLite file and migrations, in docs/src/design/persistence/persistence.md. App home directory is still open |
| D5 | Editing: search-and-replace vs. diff-based | F4.1 | Settled: exact search-and-replace. See below and docs/src/design/tools/editing-tools.md |
| D6 | Embeddings: local vs. hosted | F7.2 | Settled: local ONNX, nomic-embed-text-v1.5. Superseded by M11, which removed the index. See below |
| D7 | Vector store | F7.2 | Settled: one sqlite-vec file per workspace, plus FTS5. Superseded by M11, which removed the index. See below |
| D8 | LSP client approach | F7.1 | Settled: async-lsp and lsp-types. Superseded by M11, which removed the client. See below |
| D9 | Sandbox mechanism per platform, and the fallback where none exists | F4.4 | Settled: Seatbelt on macOS, bubblewrap on Linux, no Windows sandbox. A sandboxed call is refused when the mechanism is missing. unsandboxed: true runs only after approval. See below and docs/src/design/tools/shell-tool.md. The catalog “D9” in providers-streaming.md is a different decision |
| D10 | MCP in v1 or later | M8 | Settled: M8, host only. The trait stays fixed. The registry gains remove. See mcp.md |
| D11 | Learned text compression vs. structural compressors only | M9 | A local model is a heavy optional dependency. The first cut is deterministic compressors for JSON, logs, and search hits |
| D12 | Where a compressed result and its original live | M9 | The model reads the compressed form; retrieval has to survive restart without rewriting earlier turns |
D5: Editing — search-and-replace
Settled. The model edits with exact search-and-replace (edit_file), full-file
writes (write_file), and delete_file. It does not send a unified diff. The
review preview is computed after the write, from the session baseline, so the
model does not author that diff. The schemas, the fail-closed match, and the
approval prompt are in editing-tools.md.
| Approach | Strength | Cost |
|---|---|---|
| Search and replace | Unambiguous, cheap to validate, trivially reversible | Ambiguous on repeated text; large edits become many calls; no natural preview |
| Unified diff / patch | Precise about position and context; one call per file; previewable as a real diff in review UI | Fragile to context drift; models generate malformed patches; needs fuzzy application |
Search-and-replace fails closed when old_string is missing or matches more than
once. A patch the model authors was rejected: it applies to the wrong place
when the file has drifted, and models emit malformed patches. Fuzzy matchers
were rejected for the same reason. A write must not succeed when old_string is not
the bytes in the file. replace_all is the explicit opt-in when every match
should change.
D6: Embeddings stay on device
Settled. Chunks and queries are embedded locally with
nomic-ai/nomic-embed-text-v1.5 on CPU through ONNX. Source stays on this
machine. Weights live under ~/.robi/models/. A different model id rebuilt
the index. M11 removed the index; this records the decision, not live code.
D7: One sqlite-vec file per workspace
Settled. Vectors and an FTS5 index shared
~/.robi/index/<workspace_id>/index.sqlite, separate from the session database.
LanceDB and Qdrant were not used. M11 removed the index; the directory is only
cleaned up now.
D8: LSP client
Settled. The client is async-lsp with lsp-types, in crates/robi. A
hand-rolled JSON-RPC client deadlocks when the server sends
workspace/configuration during startup. tower-lsp builds a server, not a
client. The catalog, the five read-only tools, and the rule that a missing
binary did not fail the turn lived in the client. M11 deleted it.
D9: Sandbox mechanism per platform
Settled. A shell command starts inside an OS sandbox. macOS uses Seatbelt
through /usr/bin/sandbox-exec. Linux uses bubblewrap, and Landlock is not a
second layer. Windows has no sandbox in this design. When the mechanism is
missing or cannot be applied, the sandboxed call is refused and does not run
outside the profile. unsandboxed: true is a separate call, and it runs only
after the user approves that call.
The profile, the constructed PATH, the floor, and the approval rules are in
shell-tool.md.
providers-streaming.md uses its own “D9” heading for the vendored model catalog. That decision is not this one.
D10: MCP client
Settled. MCP is an M8 host, not a change to the loop. rmcp lives in
crates/robi. The Tool trait stays as M0 defined it. The registry gains
remove so a server’s tools can leave when its list changes. Project
servers start only after the user accepts the current file hash. Each
tool asks on its first call in the session. Sampling, elicitation, OAuth,
resources, and prompts wait. The transports, the config files, and the
approval rules are in mcp.md.
Breakout design docs
Write these on demand, immediately before building the milestone that needs them. Statuses: needed, later, done.
| Doc | Covers | Needed before | Status |
|---|---|---|---|
docs/src/design/core/agent-loop.md | Transcript, loop algorithm, turn lifecycle sequence, approval lifecycle, tool execution, events, cancellation, test strategy | M0 | done |
docs/src/design/providers/providers-streaming.md | Delta protocol, SSE, provider quirks, retries/backoff, reasoning tokens | M1 | done |
docs/src/design/core/architecture.md | Crate layout, process model, command IPC | M2 | needed |
docs/src/design/shell/visual-style.md | Dark theme tokens, shell layout, chat chrome look (Claude Code-view reference) | M2 | done |
docs/src/design/shell/chat-ui.md | Draft session, HTTP transcript, activity line, composer lock, scroll-lock. Caret stays open | M2 | done |
docs/src/design/persistence/persistence.md | Store choice, schema, migrations, session lifecycle | M2 | done |
docs/src/design/shell/chat-runtime.md | Per-session actor, agent factory, interrupt, approval refusal | M2 | done |
docs/src/design/shell/events-sse.md | D1, CloudEvents envelope, fan-out, GET /api/v1/events/stream, shell EventSource | M2 | done |
docs/src/design/tools/read-tools.md | Read tools, path resolution, session path filter, ripgrep fallback | M3 | done |
docs/src/design/core/instructions.md | System prompt sources: built-in tool list, user text, global and project AGENTS.md | M3 | done |
docs/src/design/workspace/permissions.md | Approval, policy floor, grants, protected paths | M3 | needed |
docs/src/design/workspace/context-management.md | Token accounting, compaction triggers, what survives compaction | M3 | done |
docs/src/design/tools/editing-tools.md | D5, tool schemas, fail-closed matching, verification | M4 | done |
docs/src/design/tools/checkpoints.md | Edit journal, undo, relation to git | M4 | done |
docs/src/design/tools/shell-tool.md | D9, the sandbox per platform, deny-by-default policy, environment scrubbing, network, output limits | M4 | done |
docs/src/design/tools/container-sandbox.md | A second mechanism: gVisor over the Docker API on macOS and Linux, the settings layering, services and the relay | M4 | started |
docs/src/design/core/agent-modes.md | Mode registry, prompt prefixes, transitions | M5 | done |
docs/src/design/core/subagents.md | Child policy, caps, transcript surfacing | M5 | done |
docs/src/design/review/code-review.md | Read-only session review: strip, file tree, unified diff | M6 | done |
docs/src/design/reach/mcp.md | D10, host, config and trust, registry names, approval | M8 | done |
docs/src/design/compression/tool-output-compression.md | D11, D12 for built-in JSON and search hits, content routing beyond shell and MCP | M9 | later |
docs/src/design/compression/shell-output.md | Shell stdout and stderr compression, in build order: collapse, slice, store, learned model | M9 | done |
docs/src/design/compression/mcp-output.md | MCP result compression: JSON samples and counts, the line pass, kind: "mcp" originals | M9 | done |
docs/src/design/shell/tui.md | Terminal front end: module vs. crate, the TEA loop, the parity map, phases T0–T6. A surface, not a milestone | T6 | done |
docs/src/design/shell/parallel-front-ends.md | Per-session lease, the redb handle invariant it needs, the degraded transcript, and what parallel processes still share | T0 | done |
Every design doc states: the problem, the decision, the rejected alternatives with reasons, the interfaces, and the failure modes. A doc that only describes the chosen design is a summary, not a design doc.
Porting gopi
What to take, what to leave. Names refer to ../gopi.
| gopi | Robi | Note |
|---|---|---|
gogent loop (agent.go, tool_execution.go, tool_turn.go) | robi-core | The spec for M0. Port the state machine and the three-phase tool execution; rewrite in Rust with async traits and a real cancellation path |
gogent Message, Tool, ToolRegistry | robi-core | Port the shapes and the status enums; the trait signatures stay fixed from M0 through M5 |
prompt/ assembly, mode prefixes, skill catalog | robi-core::prompt, crates/robi::agent::prompt | Rendering and the byte cap are in core. File sources are in crates/robi. The skill catalog is design/skills.md |
internal/tools/ (13 tools) | crates/robi::agent::tools | Port names, semantics, and truncation reporting. Rename to Rust idiom |
internal/policy/, internal/secrets/ | crates/robi::agent::workspace, crates/robi::adapters | Port the glob floor and redaction; replace the secrets file with a keychain |
internal/sandbox/ | crates/robi::agent::sandbox, crates/robi::agent::tools::shell | Port the deny-default policy. The profile is Seatbelt on macOS and bubblewrap on Linux. See D9 |
internal/session/ | crates/robi::domain::chat_session, crates/robi::adapters | Port the shape, drop the 50-session cap |
internal/review/ | crates/robi::agent::review | Port the diff; the review object is new |
internal/app/ mode wiring | robi-core::mode | Port the registry-per-mode idea; drop the TUI coupling |
internal/tui/ | src/ (Solid) | Behavior only: what a tool card shows, when approval pauses |
internal/models/ catalog | crates/robi::agent::providers::catalog | Port context windows; they drive the context meter. Prices are deferred to M3’s cost display. Tool-less models are not listed at all. That catalog rule is the local “D9” in providers-streaming.md, not the sandbox D9 |
docs/ (mdbook, 30 pages) | docs/ | Adopt the taxonomy: guides teach, concepts explain, reference states facts. One job per page |
| — | new | Streaming, cancellation API, checkpoints, LSP, index, tool-output compression |
Leave behind: the Bubble Tea update loop, gogent’s blocking GenerateResponse,
manual-only compaction, JSON-file persistence, and the macOS-only sandbox
assumption.
Non-goals
Stated so they do not creep back in:
- Not a code editor. Robi reads, edits, and reviews; the user edits in their own editor. No buffer management, no keybindings, no tabs of open files.
- Not a terminal emulator. Shell runs as a tool, not a pane.
- Not multi-user. No accounts and no shared workspaces. A process may listen on loopback for this machine; that is not a multi-user server.
- Not an autonomous background agent. Every turn starts from a user message, and every side effect is approved or explicitly granted.
Streamlining Roadmap
This page sketches a smaller Robi: one general-purpose tool instead of a suite of specialised ones, fewer surfaces, and a shell that spends its width on the conversation. Nine workstreams have shipped — S1, S2, S3, S4, S5, S6, S7, S8, and S9 — so the roadmap is complete.
Nothing was deleted to get there. Each backend surface sits behind a Cargo
feature, off by default, exactly as the front end has one switch in
src/app/surfaces.ts: feature-switches.md.
The premise is that a minimalist harness can outperform a complex one. A small tool set with good prompts gives the model fewer ways to choose wrong, and a shell is the one interface that already knows how to read, search, edit, and verify a repository. The counter-premise is just as important: every tool we remove is a guarantee we stop enforcing in code and start enforcing in prompt copy. This roadmap exists to test the first claim without losing the second.
Read roadmap.md first for the shipped milestones. This page describes M11, which subtracts from them.
What shipped
Nine workstreams removed a surface, and the backend ones removed their
routes and tools too. The first pass kept each backend surface behind a Cargo
feature in crates/robi/Cargo.toml, off by default, gating the module, its
registration, and its OpenAPI entry together. S3 and S4 are now past that stage:
the index, the language-server client, and the tree-sitter outline are deleted,
and no flag restores them. The front end keeps its own switch in
src/app/surfaces.ts.
| # | What the app lost |
|---|---|
| S1 | read_file, list_dir, find, grep, write_file, edit_file, and delete_file. The shell reads, searches, and edits; the prompt carries the forms |
| S2 | The review screen, its route, its three API routes, and the N files edited strip. git diff is the review path |
| S3 | The index status pill, the robi.index.v1.progress event, the semantic_search tool, IndexHub, the two /index routes, and crates/robi-index |
| S4 | The five language-server tools, the lsp setting, and the LSP client in agent/lsp/ |
| S5 | The #/docs route, the docs screen, the editor, the chat tray, the toggle, and the four docs routes |
| S6 | The permanent left sidebar. Navigation is one bar across the top; the transcript gets the full width |
| S7 | The agent’s ability to write from Ask or Plan. Ask holds a read-only shell; Plan may write only .robi/plans |
| S8 | A subagent’s ability to write. Both child modes are read-only |
| S9 | todos and write_plan. A plan is .robi/plans/<name>/PLAN.md plus TODO.md, written and ticked with the shell |
src/app/surfaces.ts is the front-end switch: docsViewer and reviewScreen
are off, topBarShell is on. topBarShell is a layout flag only — it never
gates a backend call (D5). The indexStatus flag is gone: with the index off
there is nothing for it to show.
crates/robi/Cargo.toml is the backend switch. default = [], and four
features restore one workstream each: read-tools, edit-tools, review,
docs-viewer. S3 and S4 are not flags: their code is deleted. make lint-restore and make test-restore compile and test the remaining restore
path, and CI runs both — a missing feature edge fails only there. See
feature-switches.md.
Two prerequisites grew out of S1. S7 was already required because a shell in
Plan is an editor in Plan. S8 trimmed became required because explore had
only read tools: removing them left it with nothing, so both child modes were
rebuilt on the read-only shell.
Thesis
| Complex harness | Minimal harness |
|---|---|
A tool per operation (read_file, edit_file, write_file, …) | One shell tool, plus a small set of read-only search tools |
| Tool schemas encode safety | The sandbox and approval policy encode safety |
| In-app review, docs, and index panes | The IDE, git, and a file browser do those jobs |
| A permanent navigation column | A top bar that yields width to the transcript |
The bet is that a strong model with grep, cat, git diff, and a shell writes
better code than a weaker model constrained by bespoke tools. If the bet is
wrong, the model burns turns on shell syntax and the harness gets slower, not
simpler. The measurement plan below is how we tell the difference.
What changes
| # | Workstream | Outcome | State |
|---|---|---|---|
| S1 | Shell-first editing | read_file, list_dir, find, grep, write_file, edit_file, and delete_file are disabled. The agent reads, searches, and edits through shell, with prompt hints and git diff verification | Shipped. read-tools and edit-tools restore them |
| S2 | No in-app code review | Review routes and the edited-file strip leave the app. Review happens in an IDE or git diff | Shipped. review restores the routes; the baseline table stays |
| S3 | No semantic index | Indexing, embeddings, the semantic_search tool, and index UI are gone, along with crates/robi-index, tree-sitter, and the embedder | Removed. Nothing restores it |
| S4 | No LSP diagnostics | The five language-server tools, the lsp setting, and the LSP client are gone | Removed. Nothing restores it |
| S5 | No docs viewer | The /docs route, docs screen, docs editor, and the docs routes are removed | Shipped. docs-viewer restores them; agent/docs/ stays |
| S6 | Top-bar shell | The permanent left sidebar is removed; navigation moves into the top bar | Shipped |
| S7 | Read-only shell in Ask and Plan | Ask gets a shell that cannot write; Plan may write only .robi/plans | Shipped |
| S8 | Read-only subagents | No child can write, and none can run unsandboxed | Shipped |
| S9 | No built-in todos | todos and write_plan go. A plan is .robi/plans/<name>/PLAN.md with a checkbox TODO.md beside it, written through the shell | Shipped. Nothing restores the tools |
S1 — Shell-first editing
Shipped as shell-only, which is further than this section first proposed.
The original plan kept find, grep, list_dir, and read_code; the shipped
build removes them too, behind --features read-tools. read_code went further
still: it was the last user of the tree-sitter outline, so it is deleted with
S3’s grammar crates, and read_file is the window into a source file. The shell
is the only interface to the workspace by default, and the prompt teaches the
forms.
That widened the prerequisites. explore had only read tools and no shell, so
removing them would have left it with nothing: both child modes were rebuilt on
the read-only shell (S8 trimmed). And the prompt now covers reading, searching,
editing, and verifying, not just the three write operations.
What the model is told
The prompt is the whole interface now, so the hints are product copy and need the same review as a tool schema. The first cut:
| Job | Hint |
|---|---|
| Read a file | sed -n '1,120p' path, cat path, head/tail; no pager, no less, no vim |
| Read a slice by line | sed -n '40,80p' or awk 'NR>=40 && NR<=80' |
| Full overwrite | cat > path <<'EOF' … EOF — quoted delimiter, so $ and backticks survive |
| Small exact replacement | A short Python script that reads, replaces one occurrence, asserts the count, and writes |
| Delete | rm path, after confirming the path with ls |
| Verify | git diff -- path, git status --short; read the diff before claiming success |
| Avoid | sed -i for multi-line or regex-heavy edits, interactive editors, commands that wait on stdin |
| Search | grep/rg; prefer the tools when they are registered |
Two hints carry most of the risk:
sed -iis the wrong default. It is portable enough to seem safe and subtly different between GNU and BSD, and an unanchored pattern edits more than intended. A Python replace that asserts exactly one match fails closed.cat <<'EOF'is the only reliable full overwrite. An unquoted delimiter expands$VARand backticks inside the file being written, which corrupts shell scripts and templates. The prompt must show the quoted form.
The existing shell tool already returns exit_code, stdout, stderr,
truncated, and sandboxed, plus a blocked-path hint. That is the feedback
loop the agent needs. Shell output compression (M9) becomes more important here,
because a shell-first agent produces more output, not less.
What this costs
- Checkpoints can no longer be recorded automatically. The edit journal in
checkpoints.md relies on
write_fileandedit_fileto capture a baseline before their first write. Ashellcommand is opaque, so the harness cannot know which paths it touched. S1 therefore depends on S2: either review and undo move to git, or a shell-first session has no per-session undo. Pretending to keep checkpoints without intercepting writes would be worse than removing them. - Ask and Plan must be pinned read-only first. Once the shell is the editing interface, a mode that has a shell has an editor. S7 lands before S1 for that reason; without it, the mode policy silently widens.
- Approval granularity changes. A denied path currently becomes a prompt for that call. Under a shell, approval is for the command, and the command can touch many paths. The sandbox and the session path rules must stay the enforcement point; the prompt hints are convenience, not a boundary.
- The prompt gets longer. Deleting three schemas buys some tokens back, but the shell hints spend them. Measure the net change rather than assuming it is a saving.
Exit criteria
A representative edit task — read a file, change one function, run the tests,
and inspect git diff — completes in the same number of turns as today, with no
higher rate of failed commands. If it does not, keep the edit tools.
S2 — No in-app code review
Shipped as a UI change. The route and the screen are gone from the app, and
the strip with them; the API routes and features/review/ stay. Baselines are
still written because the edit tools still write them — S2 coupled the baselines
to S1, and S1 has not shipped, so there is nothing to remove yet. The inline file
peek from a tool call card is not a review surface and stays.
Remove the review screen and the routes behind it:
GET /api/v1/chat_sessions/{id}/reviewGET /api/v1/chat_sessions/{id}/review/filePOST /api/v1/chat_sessions/{id}/review- the
/sessions/:id/reviewroute andsrc/features/review/
The user reviews in an IDE or with git diff, which is where review already
happens for most people. The assistant can be asked to explain a diff, but it
does not own a review surface.
This is coupled to S1 and to checkpoints.md:
- The review screen reads
session_file_baselines, and so does checkpoint undo. Removing review does not automatically remove the table, but a shell-first agent cannot fill it. - Recommendation: remove the baselines with the review screen. Git becomes
the undo mechanism. A session that wants an independent snapshot can ask for
git stashor a branch, under the same approval as any other command. - Keep
crates/robi/src/agent/review/behind the disabled switch until the shell-first path has shipped for a release. If checkpoints return, they will return as a git-backed feature, not a second journal.
Also update guides/code-review.md: either delete the page or turn it into “reviewing changes with git and your editor”. A guide for a removed screen is a broken link with extra steps.
Exit criteria
No route, component, guide, or prompt mentions in-app review. git diff is the
documented verification path, and the S1 prompt hints say so.
S3 — No semantic index
Removed. The first pass gated the workstream behind --features semantic-index. The code is now deleted:
- the
semantic_searchtool (agent/tools/semantic_search.rs); IndexHuband its leases (agent/index.rs);GET/PUT /api/v1/workspaces/{id}/index(web_api/code_index.rs);- the
robi.index.v1.progressevent and its constant; - the semantic engine in docs search, which is now a literal scan;
crates/robi-index, and with itfastembed,sqlite-vec,rusqlite,notify, and the tree-sitter grammars.
The index status pill and the client’s frame handling went in the first pass. A cold start issues no index work and opens no embedding model, because there is no embedder or index task left to start.
Agents did not call semantic_search enough to justify an embedding runtime, a
vector store, and a background index task. grep and find are the retrieval
path, and that is a real downgrade for “where is this concept handled?”
questions. The prompt says so honestly: search by identifier and filename first,
then read the hits.
The last user of the tree-sitter outline was read_code, so it goes with the
grammars rather than staying as a duplicate of read_file. read_file is the
window into a source file, and the shell covers the rest.
~/.robi/index/<workspace_id>/ is no longer written. The workspace asset
cleaner still removes a directory an older install left behind.
Exit criteria
A cold workspace start does no indexing work and opens no embedding model, and
the index status UI is gone. grep/find cover the retrieval in the S1 task
set without a measurable drop in success.
S4 — No LSP diagnostics
Removed. The first pass gated the five tools behind --features lsp-tools
and kept the client. With no tool driving it, the client is dead weight, so the
whole module is deleted: agent/lsp/, agent/tools/lsp.rs, and the async-lsp
and futures-io dependencies. note_lsp goes with it; nothing else invalidated
a server cache.
The two smaller decisions:
- Diagnostics only, or the whole LSP surface? The whole surface. If the agents do not use diagnostics, they do not use symbol navigation either, and five tools sharing one hub is one subsystem, not five.
- What replaces verification? The shell.
cargo check,tsc --noEmit,eslint, and the project’s own test command are already available throughshelland are more honest than a diagnostics snapshot. The prompt hints say so.
docs/src/reference/tools.md has no language-server section, and the design
page for the client is deleted rather than bannered.
Exit criteria
lsp = on is an unknown setting, no language-server tool is registered, and the
S1 task set verifies with cargo check rather than diagnostics.
S5 — No docs viewer
Shipped as a UI change. The route is out of chatRoutePaths, DocsScreen and
ChatTray are out of ChatChrome, and the toggle is out of the bar. The docs
modules and the API routes stay, so a return is a flag flip plus a back link. A
#/docs hash kept from an older build is rewritten to the chat on startup.
Temporarily remove the viewer and editor:
- the
/docsroute andViewToggle; src/features/docs/(screen, tree, toolbar, find bar, editor, autosave);src/api/docs.tsand the docs store.
The backend question is separate. The agent can read and write markdown with the
shell, so web_api/docs.rs is not needed by the model. Recommendation: disable
the docs routes with the UI, and keep agent/docs/ (change reconciliation and
merge) behind the switch. When the viewer returns, it returns with its merge
path intact rather than half-remembered.
Docs search goes with the viewer, and its guide went with it. If search should survive as a standalone surface, it needs its own entry point, which is a different feature.
Temporarily means the removal is reversible and recorded: the design pages design/shell/docs-viewer.md and design/shell/docs-mode.md stay, with the banner and a note on what a return would need.
Exit criteria
No /docs route, no docs components, and the S1 prompt tells the agent to use
the shell for markdown. The user browses docs in an external editor.
S6 — Top-bar shell
Shipped. TopBar renders one row over the window frame’s strip: the workspace
dropdown, back and forward, the session title (which is also the Recents menu),
then New chat, Settings, and an overflow holding MCP marks and the API health
row. Sidebar and ChatHeader remain in the tree as the legacy branch behind
showSurface('topBarShell'); delete them a release after this shipped.
Remove the permanent left sidebar and give the transcript the full window width. Everything the sidebar held moves into the top bar:
| Today (sidebar) | Tomorrow (top bar) |
|---|---|
| Workspace switcher | Workspace dropdown at the leading edge |
| Recents session list | Recents dropdown, with the current session title as the trigger |
| New chat | Icon button |
| Workspaces | Item in the workspace dropdown, not a separate page link |
| Settings | Icon button at the trailing edge |
| Chat/Docs toggle | Gone with S5 |
| History back/forward | Icon pair beside the title |
| Index status | Gone with S3 |
| API status, MCP tray | Stay in the top bar; MCP moves into an overflow icon |
The shell already has two vertical layers to work with: WindowFrame (the
draggable, route-tinted window chrome) and ChatHeader (the session header).
S6 should produce one bar, not two stacked bars. On macOS the leading edge
must leave room for the traffic lights; the existing WindowFrame padding rules
are the place to handle that.
Design constraints:
- One row at the default width. The title truncates before any control does. The primary actions (workspace, recents/new chat, settings) stay visible; the rest collapses into one overflow menu.
- Dropdowns are menus, not panels. Kobalte primitives styled with the tokens in visual-style.md. No new hex values.
- Keyboard and focus still work. Every icon-only button needs an accessible name and a shortcut where the sidebar had one. A hover-only menu is not a replacement for a visible list.
- Recents needs search. A dropdown is worse than a list once a user has more than a screenful of sessions. Ship it with a filter field or cap it and link to the workspaces page.
- State lives where it did.
ChatChromekeeps owning route and session state; only the presentation moves. Do not create a second source of truth for the selected workspace.
Exit criteria
At 1280 px and 900 px wide, the transcript gets the full width, every sidebar
function is reachable in two clicks or fewer, and no control is clipped. The
Sidebar.tsx and Sidebar.module.css files are gone from the render path,
along with AppLayout’s fixed left column.
S7 — Read-only shell in Ask and Plan
Today the mode’s tool set decides who may write, and it does so by withholding
tools: Ask gets no shell, Plan gets a shell that can write anywhere the
sandbox allows, and Agent gets the edit tools too. Under S1 the shell becomes
the editing interface, so “Plan has a shell” quietly becomes “Plan can edit”.
That must not happen.
Make read-only a property of the shell tool instance, not a consequence of
which tools were registered:
| Mode | Today | After S7 |
|---|---|---|
| Ask | No shell | shell, read-only |
| Plan | shell, full write inside the sandbox | shell, read-only |
| Agent | shell, full write inside the sandbox | unchanged |
Implementation shape:
- A flag, not a second tool.
Shell::new(ctx)gains aShellAccess::ReadOnlyorReadWrite. One tool, one schema, two policies; a separateread_shelltool would split the prompt and the tests for no benefit. - Enforce in the sandbox profile, not in the arguments. A read-only call
puts the workspace in
Profile::deny_writesand refuseswrite_pathsoutright. Checking the command string for>,rm, orteeis not enforcement:python -c,cp, andgit checkoutall write without a redirect. The OS profile is the boundary. - Drop the write knobs from the schema. In read-only mode, omit
write_pathsandunsandboxedfromparameters(), and say so indescription(). A property the model can set and the tool then refuses is a wasted turn. - Refuse, then explain. A blocked write returns the sandbox’s blocked-path hint plus “this mode is read-only”, so the model asks the user to switch to Agent rather than retrying the same command.
gitis read-only or it is not.git status,diff,log,show, andgrepare fine.git checkout,restore,stash,commit, and anything that writes.gitare writes. The simplest rule that holds: the read-only profile denies.gitwrites along with the working tree, which makes the whole family fail closed without a command allowlist.
Build caches are the sharp edge. cargo check writes to target/, tsc
and eslint write caches, and a test run writes artifacts. A blanket
deny-writes profile therefore refuses exactly the verification commands S1
tells the agent to use. Two honest options:
- Scope the exception. Let a read-only call write to the known build and
cache directories (
target/,node_modules/.cache/,.gitexcluded), and nothing else. This needs a per-project list, so it is a setting, not a constant. - Verify in Agent only. Ask and Plan read and reason; they do not run the
build. The prompt says so, and a refused
cargo checkis expected.
Prefer the first if the mode prompts promise verification, and the second if they do not. Do not silently allow the whole workspace and call it read-only.
Ask gains a shell it did not have. That is deliberate: with S1 and S3 in place,
grep, ls, and git diff are how the agent answers questions, and Ask needs
them. If Ask should stay tool-free of the shell, drop that row; do not keep the
shell and leave it unconstrained.
Exit criteria
In Ask and Plan, a command that writes fails inside the sandbox with a
read-only refusal and no file changes. git diff still works. The tool schema
in those modes has no write_paths or unsandboxed.
S8 — Read-only subagents
A subagent cannot ask for approval, and the current code already fails closed:
FailClosed turns any NeedsApproval call into an access_denied result. That
is the right shape, but it is not the same as read-only. A sandboxed write
inside the workspace needs no approval, so a general child can still edit
files, run git checkout, and leave the workspace changed after the summary is
returned.
Make the child’s access read-only in the profile, not in the wrapper:
- Every child gets
ShellAccess::ReadOnly.generalkeeps its shell, because command output is what it is for; it loses the ability to write.explorehas no shell and is unaffected. - No child can run unsandboxed. This is already true through
FailClosed, but state it as an invariant and test it directly rather than relying on the wrapper. The child registry must not seeunsandboxed,write_paths, ornetwork: unrestrictedin its schema at all. Removing the key is stronger than rejecting the value. - Keep
FailClosed. It is still what stops a child from reading outside the session’s allowed paths. Read-only narrows writes; fail-closed still bounds reads. - The summary is the only channel out. A child that wants a change makes
it the parent’s job: the summary says what to change, and the parent edits
with its own approval path. That is the same argument as
subagents.md makes for not giving
explorea shell.
Two consequences to write down:
generalsubagents become slower for tasks that assume they can fix what they find, because every fix becomes a parent turn. That is the price of not having an approval channel, and it is better than a silent edit.- A subagent’s transcript is in memory and the parent sees only the summary, so a write made by a child is the hardest kind of change to audit. Removing that path also removes a class of “where did this edit come from?” bugs.
Exit criteria
No child tool schema contains unsandboxed, write_paths, or an unrestricted
network option. A general child asked to write a file returns a refusal and
the file is unchanged. A test asserts the read-only profile for both child
modes, and a second test asserts the schema has no escalation keys.
S9 — No built-in todos
Shipped. The todos and write_plan tools are gone. A plan is a directory
in the workspace, written and ticked with the same shell the agent uses for
everything else (S1).
The layout
.robi/plans/
.gitignore # one line: *
ship-mode-registry/
PLAN.md # the prose: what changes, why, in what order
TODO.md # the checklist, and nothing else
Flat under .robi/plans/, one directory per plan, named from the plan’s title
in kebab case — no session subdirectory and no uuid, so ls .robi/plans reads
as the list of outstanding work. Splitting the prose from the checklist is what
keeps ticking cheap: marking a step done touches only TODO.md, so PLAN.md
stays stable for the whole implementation.
Rules, and no more than these:
- Checkboxes, not frontmatter.
- [ ]and- [x]inTODO.md. Every model writes these without being taught, and the user’s editor renders them. - One ignore file, ignoring itself.
.robi/plans/.gitignoreholds a single*. A bare*covers every entry in that directory recursively, including the.gitignoreitself, sogit statusstays clean andgit addpicks up nothing. A.gitignoreinside a plan directory would be dead weight: an ignored directory’s children are already unreachable to git. - List first, then name. Plan mode
lses.robi/plansand updates an existing plan directory for the same work rather than minting a near-duplicate. - The files are the source of truth. No session column and no prompt
injection. Agent mode lists
TODO.mdandcats both files, which is the same pair of shell calls the user makes.
Plan mode writes one directory
S7 made Plan’s shell read-only, and write_plan was the only write it had.
Removing the tool without a replacement would leave Plan unable to produce a
plan at all, so Plan’s profile gets one writable directory.
Profile::extra_writes is emitted read-write in both modes, on Seatbelt
(allow file-write* (subpath …)) and on bubblewrap (--bind, recursive). Its
position in the policy is the whole design:
- after the credential denies, so a workspace that is
$HOMEstill opens~/.robi/planswhile the rest of~/.robistays closed; - before the floor, the
.gitwrite deny, and the session deny lists, so every one of those still wins inside the directory.
The allow is a directory, not a file, so mkdir -p .robi/plans/<name> and both
files work without a per-plan rule. ShellAccess::PlanReadOnly is the third
variant: read-only schema (no write_paths, no unsandboxed), read-only
workspace, plus that one extra write root. Agent mode is unchanged — its
read-write profile already covers .robi/plans, which is what makes plan files
editable after the plan is built.
What it cost
- No validation.
normalize_todosused to reject duplicate ids, twoin_progressitems, and a 500-character step. A freeform checklist has none of that, and that is accepted: those checks mostly caught the model fighting its own tool schema. - No in-app rendering. With no tool call to render,
PlanPage, the plan card, and the todo rails went with the tools. The plan is two markdown files in the user’s editor, which is where D13 landed. - The plan is invisible to tools.
.robiis hidden and git-ignored, sogit status,rg, and thefind/greptools skip it; onlylsandcatsee it. That is the price of not polluting every diff. - Two sessions can tick the same plan. A shared directory is the feature — the plan is a workspace artifact — and the mitigations are the read-before-write rule and distinct names, not a session scope.
What was deleted, not disabled
Unlike S1–S5 there was nothing worth keeping behind a Cargo feature:
tools/todos.rs,tools/write_plan.rs, andtools/plan_file.rs;- the
todos_promptblock and thePlanChecklistsource in prompt assembly; SessionPrompt.plan_pathand theplan_pathargument onModelSource::model;adapters/session_plans.rsanddomain/chat_session/plans.rs, replaced by aSessionDataCleanerthat removes only session blobs — a workspace plan directory now outlives the session that wrote it;- the
chat_sessions.plan_pathcolumn, dropped by migration0003; PlanPage.tsx,TodoList.tsx,todoProgress.ts, and thewrite_planandtodoscases intoolCallView.ts.
Exit criteria
No todos or write_plan tool is registered in any mode, and a test asserts it
in every feature combination. Plan mode’s shell creates .robi/plans/<name>/
with both files and the .gitignore, and is refused on src/, on a file at the
workspace root, on .git/, and on a sibling that leaves the plans root. Agent
mode’s shell writes the same files. The prompt carries the layout, the checkbox
convention, and the .gitignore.
Sequencing
The order is chosen so the app is usable at every step and each step can be reverted alone.
- S0 — the switch and the banners. Add the single
streamlinedswitch, the disabled banners, and a prompt-hint test that asserts the shell hints are present. No behavior changes. - S6 — the top bar. Pure UI. Do it before removing features so the layout is proven while the surfaces still exist. The sidebar can be hidden first, then deleted.
- S5 — the docs viewer. Smallest backend surface, and its removal frees the top bar of the Chat/Docs toggle.
- S3, S4, and S8 — the intelligence layer and child confinement. All three are backend registrations plus a policy flag. None changes the editing path, and S8 is a small, self-contained narrowing.
- S2 — review and baselines. Remove after the intelligence layer, because it is the only workstream that deletes a safety net.
- S7 — the read-only shell. Land it before S1, so the mode policy exists before the shell becomes the editing interface. S7 on its own is a small behavior fix; it is required only because of S1.
- S1 — shell-first editing. Last, because it is the change that can actually make the product worse. It ships behind the switch and is measured against the current harness.
- S9 — workspace plan directories. Shipped last: after S1, because the replacement writes through the shell, and after S7, because Plan’s write exception is defined against the read-only profile.
S1 depends on S2’s decision about baselines and on S7 being in place. If S1
ships without S7, Plan and Ask become editing modes by accident. S3, S4, and S8
must ship before S1’s measurement run, so the “before” and “after” harnesses
differ only in the editing path. If S1 fails its exit criteria, S2–S8 still
stand on their own. S9 shipped last, and it could have shipped earlier: its
replacement is a plain file write, so it needs only write_file or the shell.
graph LR
S0[S0 Switch] --> S6[S6 Top bar]
S0 --> S5[S5 Docs viewer]
S0 --> S3[S3 Semantic index]
S0 --> S4[S4 LSP]
S0 --> S8[S8 Read-only subagents]
S5 --> S2[S2 Review]
S3 --> S2
S8 --> S1[S1 Shell-first editing]
S2 --> S7[S7 Read-only shell]
S7 --> S1
S4 --> S1
S1 --> S9[S9 Workspace todos]
S7 --> S9
How we will know
The research claim is empirical, so the change is too. Run the same task set against the current harness and the streamlined one, with the same model and the same prompt:
| Metric | Why |
|---|---|
| Task success | The only metric that matters if it moves the wrong way |
| Model turns to done | A shell-first agent that needs ten extra turns is not simpler |
| Tool-call errors | Shell syntax mistakes, bad paths, failed replacements |
| Tokens in and out | The prompt gets longer and the schemas get shorter; measure the net |
| Time to first useful diff | Perceived speed, not wall-clock |
| Approval prompts per task | Fewer prompts is the point; more means the sandbox is doing too much |
Keep the task set in the repository so the comparison is repeatable. A qualitative review of the traces is worth more than a single number: read the turns where the streamlined harness lost, and decide whether the loss is a prompt hint or a missing tool. That distinction is this roadmap’s main open question.
Risks
| Risk | Mitigation |
|---|---|
| Shell-first editing is less safe, not just simpler | The sandbox and approval policy are unchanged. shell stays mandatory-sandboxed; path rules stay the floor. Prompt hints are never described as a boundary. |
| The model writes a broken heredoc and corrupts a file | Quoted delimiter in every example; verify with git diff before claiming success; keep write_file one switch away. |
| No per-session undo | Git is the undo. Say so in the guide and the prompt. |
| Removing review makes the agent’s changes invisible | The chat already streams tool calls; the prompt requires a git diff after edits. |
| The top bar cannot hold the navigation at small widths | Overflow menu for secondary actions, keep the primary three visible, test at 900 px. |
| “Disabled” code rots | One switch, one banner convention, and a checklist in this page. Restore is a tested path, not a hope. |
| We remove a tool the model actually used | Keep a month of tool-call counts before deleting the registration. If a tool is in the top five, it does not qualify. |
A read-only shell blocks cargo check and test runs | Scope writes to build and cache directories, or move verification to Agent mode and say so in the prompt. |
| A read-only shell is enforced by scanning the command string | Do not scan. Use the OS profile’s deny list. A regex on > is defeated by python -c on the first try. |
| Plan mode becomes useless without a writable shell | Plan’s one writable directory is .robi/plans (S9). Anything else is an Agent task. |
| Subagents lose the ability to fix what they find | Expected. The summary names the fix; the parent applies it with its own approval. Measure the extra parent turns in the S1 run. |
| S8 is “already true” and silently regresses | Assert the invariant with tests on the profile and the schema, not on the wrapper’s behavior. |
Plan mode cannot write a plan once write_plan is gone | Plan’s profile gets one writable directory: Profile::extra_writes, emitted before the floor and the .git and session denies. |
| A plan directory is stale, duplicated, or fights the user’s edits | Plan mode lses .robi/plans first, and Agent mode re-reads TODO.md before rewriting it. |
| A plan file pollutes every diff | .robi/plans/.gitignore holds *, so the directory ignores itself. Deleting that file is the opt-in to tracking. |
Open decisions
- D1 — Is
read_filereally redundant? Settled: it went with the rest. The trade is real —read_filereported truncation with an exact continuation offset, andsed/wcis the only substitute.--features read-toolsbrings it back on its own if the S1 run shows repeatedsed/wccalls. - D2 — Do checkpoints return as git-backed? Settled: no automatic
journal. A shell command is opaque, so no baseline is recorded and there is
no in-app undo. The prompt points at
git diff,git stash, and a branch. The baseline table stays because theedit-toolsrestore path writes it. - D3 — Diagnostics only, or all LSP tools? Settled: all five. They share
one hub, and leaving four registered buys nothing. The
lspsetting is gone. - D4 — Do docs routes leave with the UI, or stay for a future client?
Settled: they leave, behind
--features docs-viewer.agent/docs/stays unconditional, so the reconciliation and merge path is intact for a return. - D5 — One switch or two? Settled: one module of front-end flags, and one
Cargo feature per workstream.
src/app/surfaces.tsholdsdocsViewer,reviewScreen, andtopBarShell;indexStatusis gone with the index.topBarShellis a layout flag that gates no backend behavior, which is what S6 shipping on its own required. The backend flags are in feature-switches.md. - D6 — What happens to
read_code? Settled: deleted. It lived behindread-toolswhile the outline was still there. It was the last user of tree-sitter, so it went when the grammar crates did, rather than staying as a secondread_file. A return means a parser and a new outline, not a flag. - D7 — Does Ask get a shell? Settled: a read-only one. With
grepandgit diffgone from the tool set, Ask needs the shell to answer anything. - D8 — Build caches under a read-only profile? Settled: verify in Agent
only. The read-only profile refuses
target/, socargo checkand a test run fail in Ask and Plan, and the mode copy says so. Abuild_write_pathssetting scoped totarget/is the follow-up if those modes ever promise verification. - D9 — Do
generalsubagents keep a shell at all? Settled: yes, read-only. If the traces show it is useless for them, the follow-up is to drop the shell from both child modes and make delegation purely read-and-summarize. - D10 — Where does the checklist live? Settled:
.robi/plans/<name>/TODO.md, with the prose inPLAN.mdbeside it. Not a session directory and not one fixed file: the directory name says what the plan is, and the split keeps stable prose apart from a changing checklist. - D11 — Does Plan mode get a one-path write exception? Settled: yes,
directory-scoped.
Profile::extra_writesopens.robi/plansread-write for Plan’s shell instance and nothing else. The allow is recursive, so the model may name its own directory and files inside it. - D12 — Is the plan file git-tracked? Settled: no.
.robi/plans/.gitignoreholds a single*, which ignores the directory recursively including itself. The user opts in by deleting that file. - D13 — Does anything still render a plan in-app? Settled: no. With S5 and S9 shipped there is no plan surface: the plan is markdown in the user’s editor. A read-only page over the workspace file route is the follow-up if it is ever wanted.
What must be updated when this ships
Done for S1, S2, S3, S4, S5, S6, S7, S8, and S9. A page a shipped workstream touches now says what the app does, not what it used to do.
- roadmap.md: M6, M7, and M10 say “Disabled”. Done.
- reference/tools.md: the tool set after S1, S3, and S4. Done.
- guides/editor.md: the shell-first workflow. Done.
- guides/code-review.md: review with git and an IDE. Done.
- The docs-search guide: removed with S5. Done.
- design/shell/frontend-layout.md, design/shell/visual-style.md, and design/shell/events-sse.md: the top-bar layout and the removed left column. Done.
- design/core/agent-modes.md: the mode table, with a read-only shell in Ask and Plan. Done.
- design/core/subagents.md: both children are read-only, and no child can escalate. Done.
- design/tools/shell-tool.md: the
ShellAccessflag, the read-only profile, andProfile::extra_writes. Done. - design/tools/editing-tools.md, read-tools.md, and checkpoints.md: the shell is the interface and there is no automatic journal. Done.
- The design pages for review and docs: the disabled banner. The LSP, semantic search, and code-outline pages are deleted with their subjects. Done.
- design/core/feature-switches.md: new, and
the backend counterpart of
src/app/surfaces.ts. Done. AGENTS.md: the layout table and the “removed surface is a Cargo feature” rule. Done.- reference/http-api.md,
reference/configuration.md, and
reference/file-locations.md: the removed
routes, the removed
lspkey, and the index directory. Done. openapi/openapi.jsonandsrc/api/schema.d.ts: regenerated, and they now contain no review, docs, or index route. Done.- design/core/agent-modes.md and
reference/tools.md:
todosandwrite_planremoved, Plan’s one writable directory, and the.robi/plansconvention in their place. Done.
Core agent loop
The core agent loop is the component that turns a user message into a settled transcript: it streams a model turn, executes the tools the model asked for, pauses for approval when a tool needs it, and stops.
This page defines that loop: its state machine, its traits, its stop conditions,
and its failure modes. It is the design doc for M0 in the
roadmap. Read it before writing code in robi-core.
What this doc does not cover
| Topic | Where it belongs |
|---|---|
| Provider wire formats, SSE parsing, retries, the delta enum’s full definition | docs/src/design/providers/providers-streaming.md (M1) |
| Which paths need approval, grants, the policy floor | docs/src/design/workspace/permissions.md (M3) |
| Store schema, migrations, how a session is listed and resumed | docs/src/design/persistence/persistence.md (M2) |
Who may call user_input, and how a newer instruction interrupts a running one | chat-runtime.md (M2) |
| UI event stream: CloudEvents envelope, fan-out, SSE | events-sse.md (M2) |
| Process model and command IPC | docs/src/design/core/architecture.md (M2) |
This page defines the shape of the delta and the seams that persistence and the UI plug into. Their contents live in their own docs.
Problem
The loop looks trivial and is not. A provider will accept one shape of transcript and no other; a tool call that is neither approved nor rejected deadlocks the conversation; a tool that fails must not take the run with it; and a user who types while the loop is blocked on a decision will produce a transcript no provider accepts. Each of those is a state the loop must handle explicitly.
gogent already encodes these decisions and has the tests to show it. This design
ports its state machine and deviates in exactly three places, each marked
Deviation below.
The turn state machine
A turn runs from a user message to the last assistant message of that exchange. Everything below is derived from the stored transcript; none of it is kept separately.
stateDiagram-v2
[*] --> Idle
Idle --> Generating: user message appended
Generating --> Generating: assistant has tool calls, all approved
Generating --> Paused: a tool call needs approval
Paused --> Generating: approve all, or reject
Generating --> Complete: assistant has no tool calls
Generating --> Failed: model error, or max iterations
Generating --> Cancelled: cancellation token fires
Complete --> [*]
Failed --> [*]
Cancelled --> [*]
Paused is the only non-terminal state the process can be restarted from, which
is why it must be derivable from the transcript alone. Cancelled and Failed
must leave a transcript that is either resumable or cleanly finished; a
half-written assistant message with dangling tool calls is neither.
Turn lifecycle
One turn, end to end: the user’s message, the model turn, the approval round trip, tool execution, and the loop back to the model. The state diagram above is the state contract; this is the interaction contract.
sequenceDiagram
autonumber
actor U as User
participant UI as Solid UI
participant A as Agent
participant S as MessageStore
participant E as EventSink
participant M as Model
participant T as Tools
U->>UI: type and send
UI->>A: user_input
Note over A,S: Input never runs ahead of an unresolved turn
A->>S: messages
S-->>A: transcript
alt unresolved tool calls remain
A-->>UI: Paused, user text not appended
Note over UI: composer keeps the text<br/>and re-sends once settled
else transcript is clean
A->>S: append user message
A->>E: emit MessageAdded
end
loop until the assistant message has no tool calls
A->>E: emit TurnStarted
A->>M: generate
par streamed text
M-->>A: Delta Text
A->>E: emit MessageDelta
and partial tool arguments
M-->>A: Delta ToolCallStart, ToolCallArgs
A->>E: emit ToolCallUpdated
end
M-->>A: Delta Finished, assembled assistant message
A->>S: append assistant, tool calls pending
A->>E: emit MessageAdded
alt assistant has no tool calls
A->>E: emit TurnFinished Complete
A-->>UI: Complete
else assistant has tool calls
Note over A,T: Phase 1, decide. Sequential, side effect free.
A->>T: requires_approval per call
T-->>A: allow or needs approval
alt a call needs approval
A->>E: emit AwaitingApproval
A-->>UI: Paused, turn ends here
Note over UI: show the exact arguments,<br/>not the model summary
U->>UI: approve or reject
UI->>A: approve or reject a call id
A->>S: update approval status
A->>E: emit ToolCallUpdated
Note over A: a new user_input or resume<br/>settles the turn and continues
end
Note over A,T: Phase 2, execute. Model order, in segments:<br/>concurrent calls batched, exclusive calls alone.
A->>T: execute with cancel token
T-->>A: results
Note over A,S: Phase 3, assemble. Model order,<br/>not completion order.
A->>S: append tool result messages
A->>E: emit MessageAdded
end
end
Note over U,S: Cancellation can fire at any point above.<br/>The transcript is left resumable or cleanly finished.
The diagram commits the implementation to six orderings. Each is testable, and each has a test in Testing.
- Settle before append.
user_inputsettles unresolved calls before it appends the user’s text. That is the invariant in Approval and the paused turn. - Persist before emit. Every event follows its store write, so a consumer that reloads from disk after an event sees at least what the event announced.
- Append before branch. The assistant message is persisted while its tool
calls are still
pending. A crash between the model turn and the tool round therefore leaves a resumable transcript rather than a lost message. - Decide the whole turn before executing any of it. Execution is segmented by concurrency; the decision is not. No half-decided turn, where some calls ran and others are still waiting on the user.
- Assemble in model order. Tool results commit in the order the model asked for them, never in completion order.
- Pausing returns; resuming is a new call. The loop holds no waiter while paused, which is what lets a paused turn survive a restart.
Note what is absent: nothing in the diagram blocks on the user. The approval round trip is two calls with a process boundary between them, and the transcript alone records where it stopped.
Interfaces
robi-core defines four traits and one type that owns the loop. Every later
milestone supplies an implementation; none of them changes a signature here.
Model
#![allow(unused)]
fn main() {
#[async_trait]
pub trait Model: Send + Sync {
/// One model turn. Deltas stream as they arrive; the final item is
/// `Delta::Finished`, carrying the fully assembled assistant message.
///
/// `session` identifies the conversation. The loop already holds it, and an
/// adapter needs it: OpenCode Go takes a per-conversation routing header, and
/// per-session model selection reads it too.
async fn generate(
&self,
session: SessionId,
transcript: &[Message],
cancel: CancellationToken,
) -> Result<ModelStream, ModelError>;
}
}
The loop consumes a stream in M0 even though M0 has no UI and ships only a stub. Making the call blocking and changing it at M1 would touch every call site; draining a one-item stream costs nothing. See Rejected alternative 1.
Delta in M0 carries what the loop needs to act on. This is the vocabulary from
M0 onward: M1 adds emitters, not variants.
#![allow(unused)]
fn main() {
pub enum Delta {
Text(String),
Reasoning(String),
ToolCallStart { index: usize, id: ToolCallId, name: String },
ToolCallArgs { index: usize, fragment: String },
ToolCallEnd { index: usize },
Usage(Usage),
Finished(Message), // assembled by the provider adapter
Failed(ModelError),
}
}
Reasoning is part of the M0 vocabulary, so the loop forwards it to the sink like
text from the start. Whether a UI renders, collapses, or drops traces is a
presentation decision, owned by docs/src/design/shell/chat-ui.md (M2); the protocol carries
them either way.
index is stream-local. Assembling fragments by index, and mapping an index to a
provider-assigned call id, is provider-specific work and belongs in the adapter.
The loop never sees an index.
Transcript fields the adapters set
Message and ToolCall carry three additive, #[serde(default)] fields that an
adapter populates and the loop never reads. Each arrived with a provider
requirement and none changes the loop’s algorithm:
ToolCall.provider_call_id— the id the provider issued, echoed on the next request. The loop keys onid; a reused or absent provider id cannot confuse approval or lookup (providers-streaming D3).Message.images— a user message’s attachment references, never bytes; the adapter resolves them at request build (D10).Message.reasoning— an optionalReasoningTrace { text, signature }. Anthropic requires a tool continuation to echo thethinkingblock back, signature included, so this is where an adapter keeps it. Absent for every other message (A3). Old rows deserialize asNone.
Tool
#![allow(unused)]
fn main() {
#[async_trait]
pub trait Tool: Send + Sync {
fn name(&self) -> &str;
fn description(&self) -> &str;
fn parameters(&self) -> serde_json::Value; // JSON Schema
/// Whether the loop may run this alongside another tool in the same turn.
/// Side-effect free. See "Concurrency".
fn concurrency(&self) -> Concurrency { Concurrency::Concurrent }
/// Side-effect free. The loop calls this before executing anything.
async fn requires_approval(&self, args: &serde_json::Value) -> Decision;
/// Safe to call from several tasks at once when `concurrency()` returns
/// `Concurrent`. See "Concurrency".
async fn execute(
&self,
args: serde_json::Value,
run: ToolRun,
) -> Result<serde_json::Value, ToolError>;
}
pub struct ToolRun {
pub cancel: CancellationToken,
pub report: Arc<dyn ToolReporter>,
}
pub enum Decision { AllowImmediately, NeedsApproval }
pub enum Concurrency { Concurrent, Exclusive }
}
The signature of requires_approval is the load-bearing part: it takes only this
call’s arguments, returns without doing anything, and cannot fail. That is what
lets the loop decide an entire turn before executing any of it.
ToolRun.report is how a tool publishes UI state before it returns. The loop’s
reporter writes a SubagentSnapshot onto that call and emits ToolCallUpdated.
The tool result the model reads stays call.result. Tools that do not delegate
ignore the reporter. See subagents.md.
A tool cannot return Decision::Deny. A denial is a policy outcome (M3), and
policy can only ever escalate AllowImmediately to NeedsApproval, never the
reverse. Keeping the two concepts apart is what makes the security floor
auditable in one place.
MessageStore
#![allow(unused)]
fn main() {
#[async_trait]
pub trait MessageStore: Send + Sync {
async fn messages(&self, session: SessionId) -> Result<Vec<Message>>;
/// One message. `Ok(None)` means the session exists and the id does not.
async fn message(&self, session: SessionId, id: MessageId) -> Result<Option<Message>>;
async fn append(&self, session: SessionId, message: Message) -> Result<()>;
/// Status changes on an existing message: a tool call going from
/// `pending` to `approved`, or gaining its result.
async fn update(&self, session: SessionId, message: Message) -> Result<()>;
}
}
Incremental append/update rather than one snapshot write per turn. A
snapshot-per-turn store cannot express approving one call while another is still
pending, and it rewrites the whole transcript on every tool completion. The M0
implementation is a Vec<Message> behind a mutex. M2’s SQLite implementation
is the same trait: messages reads the transcript in order, and message
reads one row by primary key.
EventSink
#![allow(unused)]
fn main() {
#[async_trait]
pub trait EventSink: Send + Sync {
async fn emit(&self, event: Event);
}
pub enum Event {
TurnStarted { session: SessionId },
MessageAdded { session: SessionId, message: MessageId },
MessageUpdated { session: SessionId, message: MessageId },
MessageDelta { session: SessionId, message: MessageId, delta: Delta },
ToolCallUpdated { session: SessionId, message: MessageId, call: ToolCallId },
AwaitingApproval { session: SessionId, call: ToolCallId },
TurnFinished { session: SessionId, outcome: TurnOutcome },
}
}
The loop emits every variant from M0, including MessageDelta, whenever a model
produces a delta. M0’s stub model streams a single Finished item, so no partial
fires in practice, but the emitter exists and the tests exercise it with a stub
that streams Text and Reasoning. M1 adds emitters for the provider-shaped
deltas rather than changing the type.
Emit after persisting. The store write happens before its event. A consumer of the event stream must never see a message the store cannot produce, which is the property that lets M2’s UI reload from disk and get the same view.
Agent
Agent owns the loop. It holds a MessageStore, an EventSink, a Model, a
ToolRegistry, and a LoopConfig.
#![allow(unused)]
fn main() {
pub struct LoopConfig {
/// Model turns per run. Not tool calls: fan-out inside a turn is free.
pub max_iterations: u32, // default 50
/// In-flight calls within one `Batch`. A `Solo` occupies one slot.
pub max_concurrent_tools: usize, // default 5
/// Debug only: run every call alone, in model order.
pub serial_tools: bool, // default false
/// Backstop on a serialized tool result. See "Tool results".
pub max_tool_result_bytes: usize, // default 256 KiB
}
}
| Setting | Default | Enforced by |
|---|---|---|
max_iterations | 50, or the max_iterations setting when a session actor starts | The loop’s step 3 |
max_concurrent_tools | 5 | The semaphore bounding a Batch |
serial_tools | false | Every call becomes a Solo; see Segments |
max_tool_result_bytes | 256 KiB | The core, after the tool has had its chance |
serial_tools exists so a run is reproducible. It overrides a tool’s concurrency
declaration rather than the segment walk, so execution stays in model order and
only the parallelism goes away. A session running in it should say so, because its
execution semantics differ from a normal run.
All four are defaults. A settings layer overrides them per session or globally, and
docs/src/design/persistence/persistence.md (M2) owns where that configuration lives.
#![allow(unused)]
fn main() {
impl Agent {
pub async fn new_chat(&self, workspace: WorkspaceId) -> Result<SessionId>;
pub async fn user_input(&self, session: SessionId, text: &str,
cancel: CancellationToken) -> Result<TurnOutcome>;
/// `user_input` with skill bodies and images the host
/// already loaded. The loop appends them to the user message; the provider
/// resolves the image ids to bytes at request build (D11). `user_input`
/// forwards empty lists.
pub async fn user_input_with_skills(
&self,
session: SessionId,
text: &str,
skills: Vec<SkillLoad>,
images: Vec<ImageAttachment>, // (D10)
cancel: CancellationToken,
) -> Result<TurnOutcome>;
/// Settles any outstanding turn. If that executed tool calls, the loop
/// continues into a model turn so the model reads their results.
pub async fn resume(&self, session: SessionId,
cancel: CancellationToken) -> Result<TurnOutcome>;
/// The calls waiting on a decision, in transcript order.
///
/// A call that has already run is not waiting on anything. The loop records a
/// decision only when a user makes one, so a call that needed no approval keeps
/// `ApprovalStatus::Pending`; "pending" therefore means pending approval *and*
/// still unexecuted.
pub async fn pending_tool_calls(&self, session: SessionId) -> Result<Vec<ToolCall>>;
pub async fn approve(&self, session: SessionId, call: ToolCallId) -> Result<()>;
pub async fn reject(&self, session: SessionId, call: ToolCallId, reason: &str) -> Result<()>;
pub async fn messages(&self, session: SessionId) -> Result<Vec<Message>>;
}
pub enum TurnOutcome { Complete, Paused, Cancelled, Failed(AgentError) }
}
Deviation 1. gogent reports ErrAwaitingApproval from RunWithUserInput
when the outstanding turn is not settled. I return Ok(TurnOutcome::Paused)
instead. A pause is normal control flow, not a failure: in a GUI it is the
expected result of most tool calls. Modeling it as an error invites ?
propagation that treats a routine pause as a fault, and it makes a caller that
handles pauses correctly read as though it is writing error handling.
AgentError stays for real failures: a model error, a store write failure.
The loop
#![allow(unused)]
fn main() {
async fn run(&self, session: SessionId, invoke_model: bool) -> Result<TurnOutcome> {
let mut invoke = invoke_model;
let mut model_turns = 0u32;
loop {
// 1. Nothing runs ahead of an unresolved turn. Settle it first.
match self.settle_unresolved(session).await? {
Settle::Paused => return Ok(TurnOutcome::Paused),
// Settling ran tools, so the model owes a reading of their results.
Settle::Executed => invoke = true,
Settle::NothingOutstanding => {}
}
// 2. A resume with nothing outstanding and no new user input is done.
if !invoke {
return Ok(TurnOutcome::Complete);
}
// 3. The cap counts model turns, not tool calls.
if model_turns >= self.max_iterations {
return Ok(TurnOutcome::Failed(AgentError::MaxIterations(self.max_iterations)));
}
// 4. One model turn: drains the stream to the sink, appends the message.
let assistant = self.model_turn(session).await?;
model_turns += 1;
// 5. No tool calls means the turn is settled.
if !assistant.has_tool_calls() {
return Ok(TurnOutcome::Complete);
}
// 6. Resolve this turn's calls. May pause; never aborts on a tool error.
if self.process_tool_calls(session, &assistant).await? == Phase::Paused {
return Ok(TurnOutcome::Paused);
}
// 7. Loop so the model can read the results.
invoke = true;
}
}
}
Four properties in that code are worth defending:
- Settling is not terminal. When
settle_unresolvedexecutes tool calls, the loop continues into a model turn instead of returning, because a transcript that ends on unanswered tool results is not settled. See Deviation 2. - The cap counts model turns. Tool fan-out inside one turn is free. The cap exists to stop a model that calls tools forever, so it counts the thing that recurs. Counting tool calls would make a legitimate five-tool turn count against the cap five times.
- State is derived, never cached.
settle_unresolvedre-reads the transcript and asksrequires_approvalagain. A call is storedpendingas soon as the model asks for it, including one the tool would run immediately, so the status alone does not pause the turn. The turn pauses only when a call is still pending and its tool returns needs-approval. A restart between the model turn and the tool round therefore runs the calls that need no decision, and a restart mid-pause still waits on the ones that do. While a sibling pauses the turn, a call that needs no decision is storedapprovedand does not run until the decision is in, so the UI does not offer it. model_turnappends before the loop branches. The assistant message is persisted while its tool calls are stillpending, so a crash between the model turn and the tool round leaves a resumable transcript rather than a lost one.
Deviation 2: settling resumes the model
Decided. When settle_unresolved executes tool calls, the loop sets
invoke = true and takes a model turn so the model reads their results.
gogent returns early instead when the caller did not ask for a model turn, which leaves the transcript ending on unanswered tool results. That is not a settled turn: the model asked for the calls, and nothing has told it what they returned. In a GUI there is also no obvious next event to unstick it — the user already approved the calls, so waiting for another message would strand the turn.
Two consequences:
resumecan take a model turn. It is not a settle-only operation.- A resume that settles nothing stays a no-op, so calling
resumeon a settled session returnsCompleteand changes nothing.
Stop conditions
| Condition | Outcome | Transcript after |
|---|---|---|
| Assistant message has no tool calls | Complete | Settled |
| A tool call needs approval | Paused | Ends on pending calls; resumable |
Model turns reached max_iterations | Failed | Settled, with an error to show |
| The model errored | Failed | Settled; the failed turn is not appended |
| Cancellation fired | Cancelled | Resumable, or cleanly finished |
resume that settled tool calls | Continues into a model turn | Settled once the model reads the results |
resume with nothing outstanding | Complete | Unchanged |
| A tool errored | Loop continues | The error is a tool result |
Every one of these gets a test. The Cancelled row is a design obligation, not a
description: fill in resumable or finished for each cancellation point (before
the model turn, mid-stream, during tool execution) and assert it.
Approval and the paused turn
The invariant:
User input never runs ahead of an unresolved turn. If the transcript ends with tool calls that are not settled, the next thing that happens settles them, whatever the user typed.
user_input implements this by calling settle_unresolved before it appends
anything. If that settle pauses on calls still waiting for a decision, those
calls are rejected with the reason the user sent a new message. The loop
settles the rejections, writing each as a tool result, and only then appends
the user’s text. A turn that is still paused after that returns Paused and
does not append.
Why it matters: providers reject a transcript whose assistant message has unanswered tool calls, and a user cannot reason about an ordering where their message precedes the answer to a question the model asked. Both failures come from appending the user message too early.
The approval surface is three operations:
| Operation | Effect |
|---|---|
pending_tool_calls | Returns the calls the UI must render as prompts |
approve | Sets one call to approved, then resumes the loop |
reject | Sets one call to rejected with a reason, then resumes |
A rejected call becomes a tool result the model reads: a structured rejection payload, not silence and not an absent message. Silence teaches the model nothing and leaves it to guess whether the tool failed or was never run.
Approval is asynchronous with respect to the loop. The loop returns Paused and
waits to be called again; it does not block a thread on a user decision and it
does not poll. That is what makes a paused turn survive an app restart: the pause
is a property of the transcript, and the process holds no waiter.
Tool execution
Three phases, and the order is the design.
#![allow(unused)]
fn main() {
async fn process_tool_calls(&self, session, assistant: &Message) -> Result<Phase> {
// Phase 1 — decide. Sequential, side-effect free, over the whole turn.
for call in &assistant.tool_calls {
let tool = self.registry.get(&call.name); // unknown tool: see below
let decision = tool.requires_approval(&call.args).await;
let decision = self.policy.escalate(decision); // M3; can only escalate
if decision == NeedsApproval && call.approval_status == Pending {
return Ok(Phase::Paused); // whole turn pauses
}
}
// Phase 2 — execute. Model order, in segments. See "Concurrency".
let results = self.execute_segments(&assistant.tool_calls, cancel).await;
// Phase 3 — assemble. Model order, not completion order.
for (call, result) in zip(&assistant.tool_calls, results) {
self.record_tool_result(session, call, result).await?;
}
Ok(Phase::Done)
}
}
- Phase 1 is sequential. Concurrent decisions would make the order of approval prompts nondeterministic, and a decision that cannot be reproduced is not a decision a user can audit.
- A turn is decided as a whole, or paused as a whole. No half-decided turn, where three calls ran and two are waiting on the user.
- Phase 3 commits in model order. The provider matches results by id, but the transcript is also read by the model and by the user, and a transcript that reorders across runs is a transcript that reads differently across runs.
- A failing tool does not abort the rest of the turn. The failure becomes a structured result the model can read and correct. The fan-out deliberately does not derive a cancel-on-first-error context, because a failing tool would then discard sibling work the model asked for and the user already paid for.
- A tool call is logged without its arguments. Start and a normal finish are info. Cancellation is info. A panic is error. Any other tool error is warn. The fan-out logs a stored message, a message update, a tool-call update, and waiting for approval at info. Token deltas are not logged.
Concurrency
A tool declares whether the loop may run it alongside another tool in the same
turn. Concurrent is the default, because reads dominate a coding agent’s tool
set and they are safe to overlap.
Exclusive means nothing else in the turn is in flight at the same time as this
call — not merely that it does not overlap another exclusive call. A writer
overlapping a reader is the conflict the flag exists to prevent, so a single-flight
lane for exclusive calls alone would not be enough.
Concurrent is a claim by the tool author, and the compiler witnesses only part
of it. Send + Sync makes memory safety true. It cannot make logical safety
true, which is what a read-modify-write on a file, a shared counter, or two writes
to one path violate. So the registry carries a snapshot test asserting
name -> concurrency for every registered tool: adding a tool fails the test until
its author states a setting. Omission is visible, and the common case stays
unannotated.
Segments
Phase 2 walks the turn’s calls in model order and partitions them into maximal runs:
#![allow(unused)]
fn main() {
enum Segment { Batch(Vec<ToolCall>), Solo(ToolCall) }
// Walk in model order.
// Concurrent -> push onto the open batch
// Exclusive -> flush the open batch, then emit Solo(call)
for seg in segments(&calls) {
match seg {
Segment::Batch(cs) => join_bounded(cs, self.max_concurrent).await, // parallel
Segment::Solo(c) => c.execute(cancel).await, // alone
}
}
}
An Exclusive call flushes the open batch and then runs alone, so it is a
barrier: nothing is in flight when it starts, and nothing starts until it
finishes. That is what the flag has to mean for the ordering below to hold.
Execution order is model order, always. Two passes over the turn — one for concurrent calls, one for exclusive — would break it. Given
[read A, write B, read C] # read a file, edit another, verify by reading back
two passes would run read A + read C in parallel, then write B. The read of
C would land before the write it was meant to verify, and because phase 3 still
assembles in model order, the transcript would read A, B, C while the filesystem
changed in the order A, C, B. The transcript would look right and the world would
be wrong, with nothing in the log to show it. Segments keep the two orders equal:
| Turn | Segments | Execution |
|---|---|---|
[read A, read C, write B] | Batch(A, C), Solo(B) | A and C together, then B |
[read A, write B, read C] | Batch(A), Solo(B), Batch(C) | A, then B, then C |
Two further rules:
- Deciding stays whole-turn. Segments govern execution only. Phase 1 decides every call before any of it runs, so no side effect lands before the prompt for a later call appears. Executing approved segments and pausing at the first that needs approval would mean approving call 4 after calls 1 through 3 already wrote files, which is the half-decided turn the phase-1 rule exists to prevent.
max_concurrentbounds aBatch. ASolooccupies one slot and runs alone. A slow exclusive call stalls the turn until its timeout. That is inherent: it cannot be overlapped with anything it might depend on.
Escalation
Configuration may escalate Concurrent to Exclusive, never the reverse. The same
rule as approvals: a lower layer adds caution, and none removes it.
Panic isolation
Tool execution runs inside tokio::spawn, so a panicking tool becomes a
JoinError the loop converts into a failed tool call. A panic in an inlined
.await aborts the whole process, which for a coding agent means losing the
session over a malformed regex. The cost is a Send + 'static bound on tool
arguments and results, which is worth paying once at the trait boundary.
Tool results
Two layers, and the tool gets first refusal:
- A tool truncates its own result and reports that it did, in the same shape as a truncated file read: the result is bounded, and it says where to continue. This is the real budget, because only the tool knows which part of its output matters.
- The core enforces
max_tool_result_bytesas a backstop. A result over the ceiling is truncated by the core, with a marker naming the core as the truncator.
The ceiling is 256 KiB on the serialized result — four times the largest legitimate tool result a coding agent produces, and well under a context window. It exists for the tool with a bug or no bound at all. One unbounded result does not only fill the window; it makes the rest of the turn unaffordable and the session’s cost unpredictable.
The two truncation markers differ on purpose. A backstop that fires is a bug report, so seeing the core’s marker means a tool is missing its own bound.
Failure modes
| Failure | Handling | Rationale |
|---|---|---|
| Unknown tool name | Structured “tool not found” result; call failed; loop continues | The model can correct a typo if it is told; killing the turn teaches nothing |
| Tool arguments are not valid JSON | Failed call with a parse error, not {} | See Deviation 3 |
| Duplicate tool call ids in one turn | Reject the turn as a provider fault | Ids key the transcript; duplicates make it ambiguous |
| A tool panics | JoinError → failed call | Panic isolation above |
| A tool exceeds its timeout | Cancelled, recorded as a timeout | A hung tool must not hang the turn |
| The store write fails | Fail the turn | Write-through means continuing would diverge memory from disk |
| Approval arrives for a call already settled | No-op, idempotent | A double-click must not resume twice |
| The model returns an empty message with no tool calls | Complete | Settled, even if useless; retrying here would need a policy the loop cannot infer |
A second user_input while paused | Returns Paused, input not appended | The invariant above |
| A tool result exceeds the ceiling | The core truncates it, with a marker distinct from a tool’s own | A backstop, not a budget; the tool should bound its own output |
Deviation 3
gogent maps tool arguments that fail to parse to {}. I would record a parse
error instead. {} is a valid argument set for many tools, so the failure mode of
gogent’s choice is a tool that silently executes on defaults: a grep with no
pattern, a read_file with no path. A structured parse error is recoverable and
visible.
Cancellation
The loop owns a tokio_util::sync::CancellationToken, passed by reference into
Model::generate and as ToolRun.cancel on every Tool::execute. Three rules:
- Cancellation is a state, not an exception. After a cancel, the transcript is either resumable or finished. Never a partial assistant message that the model did not finish and the loop did not abandon.
- A cancelled model turn does not append. If the stream is cancelled mid-flight, the partial assistant message is not committed, because a partial message with half-assembled tool calls is the exact failure this rule prevents.
- In-flight tools get the token and their results are recorded as cancelled. Dropping them would leave the turn unresolved with no way to settle it.
The model-turn call site selects on the token around generate itself, so a cancel
that fires while the request is in flight returns Cancelled without waiting for
response headers. The adapter cannot express cancellation through ModelError, so
without that select a user-stopped turn would surface as a connection failure. M1
added it; see providers-streaming.md.
Decide per cancellation point what the transcript looks like, and assert it in a test. M5’s subagents inherit whatever this doc decides.
Rejected alternatives
- Blocking
generate(transcript) -> Message, as gogent does. Rejected: the delta stream is the UI’s contract, so the loop would be rewritten at M1, and partial tool arguments are what let the UI show what the model is about to do before it does it. - An explicit persisted state machine, one row per turn. Rejected: derived state needs no separate file, cannot disagree with the transcript, and is already what a restart has to reconstruct. Cost: a transcript scan per iteration, which is not the slow part.
- Concurrent
requires_approvaldecisions. Rejected: nondeterministic approval order. - Cancel-on-first-tool-error fan-out. Rejected: discards sibling work and hides the results the model needs to recover.
- Committing tool results in completion order. Rejected: nondeterministic transcripts, and the model reads the transcript too.
Pausedas an error value. Rejected: see Deviation 1.- The loop waiting on a channel for the user’s decision. Rejected: it makes the loop own a UI concern, and a process-local waiter cannot survive a restart in the paused state.
- Snapshot-per-turn persistence. Rejected: cannot represent a partially settled turn.
- Two passes over a turn: concurrent calls, then exclusive calls. Rejected: it reorders execution against model order, so a read meant to verify a write runs before that write. See Segments.
- A single-flight lane for exclusive calls, with concurrent calls still flowing alongside. Rejected: it lets a writer overlap a reader, which is the conflict the flag exists to prevent.
Testing
M0 has no UI and no network, so its tests are the deliverable. Port gogent’s
agent_test.go scenarios; they are already the right list.
Fakes to build first:
| Fake | Purpose |
|---|---|
StubModel | A scripted queue of model turns, so each test states exactly what the model does |
InMemoryStore | Vec<Message> behind a mutex |
RecordingSink | Asserts event order, including that an event follows its store write |
StreamingStubModel | Emits Text and Reasoning deltas, to assert they reach the sink |
SlowTool, FailingTool, PanickingTool | Per-tool failure modes |
CountingTool | Atomically counts in-flight calls, to assert the concurrency bound |
ExclusiveTool | Declares Exclusive and records its execution interval, to assert the barrier |
HugeTool | Returns a result over the ceiling, to assert the core backstop |
Required cases:
- One turn, no tools: one model call,
Complete, transcript of two messages. - Multi-iteration tool loop: model calls a tool, reads the result, answers.
- The cap trips, and it counted model turns rather than tool calls.
- A tool error does not end the run, and the model sees a structured error.
- An approval pause, then
approve, then completion. - An approval pause, then
reject, and the model sees the rejection. user_inputwhile paused: rejects the pending calls, records those rejections before the new message, and then continues the turn.- Result ordering is model order when the first tool is the slowest.
- The concurrency bound holds: in-flight never exceeds the limit.
- Model order under segments. For a turn of
[read A, exclusive B, read C], the recorded intervals show B overlaps neither A nor C. - Maximal batching. For
[read A, read C, exclusive B], A and C overlap. - The barrier is absolute. No concurrent call is in flight at any point while an exclusive call runs, in a turn that contains both.
- Deciding stays whole-turn. When a late call in the turn needs approval, nothing in the turn has executed when it pauses.
- The registry snapshot. Every registered tool has a stated concurrency.
- Serial mode is transcript-equivalent. The same turn under
serial_toolsproduces the same transcript and the same tool-result order as concurrent mode. - The result ceiling holds. A tool returning an oversized result is truncated by the core, with the core’s marker rather than the tool’s.
- Reasoning reaches the sink. A stub model streaming
Reasoningproduces the matchingMessageDeltaevents in order. - A panicking tool becomes a failed call and the run continues.
- Cancellation before the model turn, mid-stream, and mid-tool-round each leave a resolvable transcript.
- Every outcome leaves a transcript whose last message is settled or whose pending calls are recoverable. Assert this in every test’s teardown rather than in one test of its own.
Implementing it in Rust
async_traitover native async-in-trait. The loop holdsdyn Model,dyn Tool, anddyn MessageStore, and async fn in trait is not dyn-compatible without workarounds.#[async_trait]boxes each call; at one model call and a handful of tool calls per turn that allocation is irrelevant.- Inject the clock. Timeouts, retries (M1), and subagent deadlines need a time source a test can advance. Passing one now costs a parameter; adding one later touches every test.
- Ids: UUIDv7 or ULID, so transcript order and id order agree and a store can sort by id.
- Keep
robi-corefree ofreqwest,tauri, andstd::fs. Enforce it in CI with a dependency check, because this boundary is the milestone’s whole value. Arobi-corethat can read a file has already given up the property that its tests prove the loop.
Decisions
Settled:
| Decision | Value |
|---|---|
Paused is an outcome, not an error | Deviation 1 |
| Settling tool calls resumes the model | Deviation 2 |
| Unparseable arguments fail the call | Deviation 3 |
| A turn is decided as a whole | No half-decided turn |
| Execution walks in model order, in segments | Concurrent batched, exclusive alone |
Concurrent is the declared default | The registry snapshot test keeps an omission visible |
| Iteration cap | 50 |
| In-flight tool limit | 5 |
| Serial debug mode | Every call alone, in model order |
Reasoning deltas | In the M0 vocabulary; rendering is M2’s call |
| Tool result ceiling | 256 KiB, enforced by the core as a backstop |
Still open:
- Does a settings layer let a session override the limits, or are they global? The
settings model in
docs/src/design/persistence/persistence.md(M2) owns the answer. - Whether turn records are persisted alongside the transcript. Deriving turn
structure from the transcript stays the default, because the transcript is
authoritative;
docs/src/design/persistence/persistence.md(M2) owns whether an observations record joins it.
Agent modes
A session runs in one mode. The mode chooses the tool registry and the last
block of the system prompt. It also chooses which model and effort that turn
uses. The loop in robi-core does not know the mode.
What this page does not cover
| Topic | Where it belongs |
|---|---|
| Plan checklist UI | roadmap F5.2 |
| How search and fetch behave | web-tools.md |
delegate | subagents.md |
| How the prompt is assembled aside from the mode block | instructions.md |
Skill files, the catalog, and /id | skills.md |
| Approval and path rules | read-tools.md |
| MCP servers, trust, and remote tool calls | mcp.md. Their tools join Agent when that milestone is built |
Problem
Every session was offered the full tool set and one model. Ask, plan, and agent are different jobs. A mode that can edit will edit. A mode whose shell cannot write will not — which is why the mode’s policy lives in the sandbox profile now, not only in which tools were registered.
Decision
AgentMode is ask, plan, or agent. A new session starts in agent.
The value is a column on chat_sessions. Switching it is a patch. The actor
that is already running keeps the registry, prompt, model, and effort it
started with. The next actor reads the stored mode.
Tools
| Tool | Ask | Plan | Agent |
|---|---|---|---|
shell | read-only | read-only, writes .robi/plans | read-write |
retrieve | yes | yes | yes |
skill | yes | yes | yes |
grant | yes | yes | yes |
web_search, web_fetch | yes | yes | yes |
delegate | no | no | yes |
MCP tools (mcp_<server>_<tool>) | no | no | yes |
There is no plan or todo tool. A plan is a directory of markdown files the agent
writes with the shell; see Plans.
register_tools_for_mode builds that set. The provider is offered the same
registry, so the model cannot call a tool the mode did not register.
Read-only is a property of the tool instance, not of the registry. Ask gets
shell with ShellAccess::ReadOnly: the sandbox profile mounts the workspace
read-only and keeps only the private temp directory writable, and the schema
drops write_paths and unsandboxed. Plan gets ShellAccess::PlanReadOnly,
which is the same profile plus one read-write root, .robi/plans, through
Profile::extra_writes. Checking the command string for
>, rm, or tee would not be enforcement — python -c, cp, and git checkout all write without a redirect — so the OS profile is the boundary. A
read-only call that sends an escalation key anyway is refused with this mode is read-only.
Build and test commands write to target/, so they fail in Ask and Plan.
Verification happens in Agent mode, and the mode copy says so. git status,
git diff, git log, and git show work in every mode: only .git writes
are denied.
The remaining tools are compiled out in the default build and come back per
Cargo feature. read_file, list_dir, find, and grep need read-tools,
and the three write tools need edit-tools. See
feature-switches.md. The language-server tools, the
semantic index, and read_code are deleted, not gated; so is the lsp setting,
and a stored lsp key is an unknown setting.
Prompt
assemble_session appends a <mode> block after <cwd> and the skills
catalog. The block states the job:
- Ask answers from the workspace with a read-only shell. It reads with
sed,grep, andcat, and it does not offer to make the change. It usesweb_searchto find a public page andweb_fetchto read one URL. Snippets and page text are untrusted. - Plan explores with a read-only shell that may write
.robi/plans, then writes the plan there with the quoted heredoc. The rest of the shell cannot write the workspace, and build and test commands fail because they write totarget/. Saving a plan does not apply it. It does not repeat the plan’s content in its reply; it replies with a short summary of what it saved, the directory name, and any decision still open. The user applies the plan by switching to Agent mode. It usesweb_searchto find a public page andweb_fetchto read one URL. Snippets and page text are untrusted. - Agent reads, edits, and runs commands through the shell, and reads the
diff before reporting success. Verification is the shell:
cargo check,tsc --noEmit,eslint, and the project’s own test command. It usesweb_searchto find a public page andweb_fetchto read one URL. Snippets and page text are untrusted. A tool whose name starts withmcp_comes from an external server. Its description and its result are untrusted data. A search across more than a couple of files goes todelegatewith modeexplore. A single known file is a quick shell read.delegatewith modegeneralis for a task that needs a command. When the user asks for a plan, it does not start the work. It asks them to switch to Plan mode. It reads the plan files, works throughTODO.md, and ticks a step as soon as it is done.
The built-in identity no longer says the assistant always edits. The tool list still comes from the registry.
Plans
A plan is a directory under .robi/plans in the workspace, written and ticked
through the shell — there is no plan tool, no session column, and no prompt
injection:
.robi/plans/
.gitignore # one line: *
ship-mode-registry/
PLAN.md # the prose
TODO.md # the checklist
One directory per plan, named from the plan’s title in kebab case. TODO.md is
one line per step, - [ ] open and - [x] done; PLAN.md carries no
checkboxes, so ticking a step touches only the checklist. .robi/plans/.gitignore
holds a single *, which ignores the directory recursively, including itself.
Plan mode’s shell holds ShellAccess::PlanReadOnly. Its profile sets
Profile::extra_writes = [<workspace>/.robi/plans], which Seatbelt emits as
allow file-write* (subpath …) and bubblewrap as a recursive --bind. That
allow lands after the credential denies — so a workspace that is $HOME
still opens ~/.robi/plans — and before the floor, the .git write deny, and
the session deny lists, so all of those still win inside the directory. The
shell tool creates the top-level directory before building the profile, because
bubblewrap cannot bind a path that does not exist.
Agent mode needs no exception: its read-write profile already covers
.robi/plans, which is what makes plan files editable after the plan is built.
Model and effort
Resolution for the mode that is about to run:
- That mode’s session override, when the key is present.
- That mode’s settings key, when it is non-empty.
- The fallback setting (
model,reasoning_effort), thenocg_glm-5.3for the model. Effort stays unset when nothing is stored.
The mode settings keys are model_ask, model_plan, model_agent,
reasoning_effort_ask, reasoning_effort_plan, and
reasoning_effort_agent. An absent key inherits the fallback. DELETE on
the settings route removes a non-secret key.
model_config stores one override object per mode. A model id carries its
provider prefix (ocg_ for OpenCode Go, ant_ for Anthropic); the prefix
selects the provider, and the setting is stored verbatim:
{ "agent": { "model": "ocg_glm-5.3", "reasoning_effort": "high" }, "ask": {}, "plan": {} }
The composer model and effort menus edit only the active mode. Choosing the default clears that mode’s key. Switching mode does not copy the previous mode’s model.
Rejected alternatives
- One registry, and a prompt that asks the model not to edit. The model can still call the tool, and once the shell is the editing interface a prompt cannot stop a redirect. The registry plus the sandbox profile is the constraint, and the profile is the one that holds.
- Rebuilding the running actor when the mode changes. A turn in flight would change tools under a call that already started. The next actor is the same rule a model change already uses.
- A single session model that follows the user across modes. Ask and agent then share one override, and the per-mode settings never show up after the first choice.
Failure modes
- A mode string other than
ask,plan, oragentis400. - A running turn keeps its tools. The composer shows the mode that will apply on the next actor.
- Plan’s shell refuses a write outside
.robi/plansinside the sandbox, and the blocked-path hint names that directory rather than only “switch to Agent”. ShellAccess::ReadOnlyandPlanReadOnlyrefusewrite_paths,unsandboxed, andnetwork: unrestrictedwiththis mode is read-only.- A session
deny_writeon a path inside.robi/plans, the floor, and the.gitwrite deny all still win overProfile::extra_writes. $HOMEunset fails the sandbox profile before any command runs.
Instructions
This page defines the system prompt sent with every model request. Rendering
lives in robi-core::prompt. The sources that fill those blocks live in
crates/robi/src/agent/prompt/. The adapter still injects the finished string, as
providers-streaming.md describes.
What this page does not cover
| Topic | Where it belongs |
|---|---|
| How the request prepends the string | providers-streaming.md |
| Which tools exist | read-tools.md, editing-tools.md |
| Skills | skills.md |
| A trust decision before reading a project file | roadmap M8 |
| Mode prefixes | agent-modes.md |
Problem
The transcript has no system role, so the model only learns what Robi is, which tools this session registered, and which project rules apply if something else says so. That text has several owners: the binary, the user, and the workspace. A later owner is more specific, and a missing file must not block a turn.
Decision
PromptAssembler holds an ordered list of PromptSource values. Each source
returns one block or nothing. render joins the blocks that have text. The
default chain, built by assemble_session when a session actor starts, is:
- Built-in. Identity, rules, an
<access>section, and one line per registered tool (nameanddescription). The access section tells the model how allow and deny rules rank, to callgrantwhen a tool refuses a path, and howshellstays inside the sandbox unless the user approves a wider call. Whendelegateis in the registry, the rules tell the model to usedelegatewith modeexplorefor a search that spans more than a couple of files. Whenrgis on the hostPATH, one rule says to prefer it togrepand to fall back togrepwhen it is missing, which a container image may be. When the mechanism iscontainer, one rule says every command starts in/workspaceand forbids acdthere, and the<cwd>block is dropped because the host path it names is not mounted at that path. An empty registry says that no tools are registered. - User setting. The
system_promptsettings key, when it is non-empty, wrapped in<user_prompt>. ~/.robi/system.md. The same tag, when the file exists.~/.robi/AGENTS.md. Wrapped in<user_agents>.- Project chain. From the git root down to the workspace, root first, in
<project_agents>.AGENTS.override.mdin a directory replacesAGENTS.mdin that directory only.fallback_filesonProjectAgentsadds extra names beside those two. The default chain passes an empty list. - Working directory. The workspace root, in
<cwd>. - Skills. Name and description of each skill the model may load, in
<skills>. The block is omitted when that list is empty. See skills.md. - Mode. The active mode, in
<mode>. See agent-modes.md.
There is no plan-checklist source. Since S9 the plan and its TODO.md are files
in the workspace the shell reads, so nothing is injected from a stored path. See
agent-modes.md.
A source is added with PromptAssembler::source. A new kind of instruction is
another type that implements PromptSource. It does not edit the built-in text.
Each file block is capped at 32 KiB. Over that, the tail is kept and prefixed
with [earlier instructions truncated]. The project chain is one block, so a
short budget drops the root file before the closest one.
SettingsModelSource::model receives the session tool registry, the
workspace root, and the active mode. It assembles this chain and stores it on
ProviderSettings. The provider prepends it as a system message. The transcript
does not store it.
Instruction text cannot add a tool or change a path rule. The built-in rules say so, and the tools do not read the prompt to decide.
Rejected alternatives
- A single string constant. Adding
AGENTS.mdwould mean editing the constant, and the tool list would drift from the registry. - Putting file reads in
robi-core. The core renders blocks. OpeningAGENTS.mdis I/O, so the sources stay incrates/robi. - Replacing the built-in prompt with the user file. The tool list would disappear as soon as someone wrote a preamble.
Failure modes
- A missing file is skipped.
- A file that cannot be read is skipped, and a warning is logged. The turn still starts.
- No workspace root skips the project chain, the working-directory block, and the plan checklist. Tests that build a model without a session take that path.
- A plan file that cannot be read, or whose frontmatter does not parse, skips the checklist. A warning is logged. The turn still starts.
- No home directory skips
~/.robi/system.mdand~/.robi/AGENTS.md.
Feature switches
The streamlining roadmap removed backend surfaces without deleting them. The
front end still has one switch for that, src/app/surfaces.ts. This page
describes its backend counterpart: one Cargo feature per workstream, in
crates/robi/Cargo.toml, all off by default.
Read streamlining.md for what each workstream removes.
The flags
| Feature | Restores | Workstream |
|---|---|---|
read-tools | read_file, list_dir, find, grep | S1 |
review | the /chat_sessions/{id}/review routes and the baseline reader | S2 |
edit-tools | write_file, edit_file, delete_file | S1 |
docs-viewer | /workspaces/{id}/docs and its literal search | S5 |
default = []. The streamlined harness ships; a feature is the return path.
S3 (the semantic index) and S4 (the language-server tools) are past the feature
stage. Their code, crates/robi-index, and the LSP client are deleted, so no
flag restores them. See streamlining.md for what a
return would need.
The edges
One feature edge is left, and it is not decoration:
edit-tools = ["review"]— the edit tools and their tests usereview::{diff, hunks_for_session, reject}to render a change. Writes without the review half would be writes with no diff.
Two dependencies arrive with a feature rather than with the default build:
read-tools = ["dep:ignore"]—findandgrepwalk withignore.globsetis not here: the MCPtoolsfilter needs glob matching in every build, so that dependency is unconditional.docs-viewer = ["dep:ignore"]— the docs listing and its literal search walk withignore.
review/diff.rs is unconditional: agent/docs/merge.rs is kept in the tree
(S5) and needs it. Only review/session.rs is gated.
The rule
Gate three things together, and gate nothing else:
- the module (
#[cfg(feature = "…")] mod …;), - its registration in
tools/mod.rsorweb_api/mod.rs, - its OpenAPI entry — every
paths(...)andschemas(...)it contributes.
Never gate a handler body. Never gate an item in robi-core: the loop learns
nothing about these features. A struct field only a gated module reads goes with
that module, with #[cfg] on the field line itself, in the struct and in every
literal that sets it.
Testing the restore path
The default build compiles no gated module, so a wrong #[cfg] is invisible
until every feature is on:
make lint-restore # cargo clippy --workspace --all-targets --all-features
make test-restore # cargo test --workspace --all-features
CI runs both in the rust-restore job. Treat a change to the feature graph as a
change to that job’s cost, not to its existence.
--all-features is not the old behaviour. With every feature on, Ask has a
read-only shell it never had and subagents cannot write — that is S7 and S8, and
it stays on in both builds.
Subagents
delegate hands one bounded task to a child agent and returns only that child’s
answer. The parent transcript stays small. The card under the call stays
collapsed to Explore or General, with the running spinner while the
child works. Opening it shows the child’s tool calls.
This page is the design for F5.4 in the roadmap. The loop
that runs the child is agent-loop.md. The card is
chat-ui.md. Ask, plan, and agent modes are
agent-modes.md. delegate is registered in agent mode.
What this page does not cover
| Topic | Where it belongs |
|---|---|
| Ask, plan, and agent mode selection | agent-modes.md |
| The sandbox a general child’s shell uses | shell-tool.md |
| A separate explore model | Later. The child uses the session’s current model |
| MCP tools on the child | mcp.md. Neither child mode receives them |
Skill files, /id, and the skill tool | skills.md |
Problem
A search that opens twenty files costs twenty tool results in the parent transcript. The parent model then has to read all of them. A child that can pause for approval has no one to ask: the user is in the parent turn.
Decision
One tool, delegate, with two modes.
explore | general | |
|---|---|---|
| Tools | shell (ShellAccess::ReadOnly) and retrieve | the same |
| Model turns | subagent_max_iterations, default 50 | the same setting |
| Wall clock | subagent_timeout_seconds, default 120 | the same setting |
| Calls per session | 6 | 4 |
Both modes hold a read-only shell. A child cannot ask for approval, and a sandboxed write inside the workspace needs no approval, so a writable child could edit files and leave the workspace changed after its summary came back. Read-only in the profile is what stops that, not the wrapper. A child that finds a change to make names it in the summary; the parent applies it with its own approval path. That is the price of having no approval channel, and it is better than a silent edit.
The child schema has no unsandboxed, no write_paths, and no unrestricted
network option at all — removing the key is stronger than rejecting the value.
Build and test commands fail in a child for the same reason they fail in Ask and
Plan: they write target/.
Neither mode can edit, call grant, call delegate, call skill, call
web_search or web_fetch, or call an MCP tool. A child cannot start another
child. The child prompt does not include the skill catalog and is written for
the shell: what to run to search, how to read a window, and that the parent
makes the change.
With --features read-tools, the corresponding tools join both child
registries too. See feature-switches.md.
The agent-mode prompt, and the built-in rules when delegate is registered,
tell the parent to use explore for a search that spans more than a couple of
files. A single known file stays a direct read.
The child is a normal Agent with a fresh in-memory transcript and NopSink.
It does not see the parent conversation. Its system prompt is the explore
specialist prompt, or a short investigator prompt for general. The task string
is its user message. The model is the session’s current model, built with that
prompt and the child’s tool registry.
The value the parent model reads is:
{ "mode": "explore", "answer": "...", "tool_calls": 7, "denied": [] }
answer is the child’s last assistant message that made no tool calls. File
bodies and command output stay in the child transcript and are dropped when the
child returns.
While the child runs, each of its tool calls is written onto the parent
ToolCall.subagent snapshot and the loop emits ToolCallUpdated. The shell
already refetches that message. The snapshot is summaries: tool name, a one-line
target, and running, ok, denied, or failed. It is not part of the tool
result the model reads. After a refresh the same snapshot is still on the call.
Several delegate calls in one turn may run together. Each snapshot hangs off
its own call. Writes to that assistant message share one lock.
Fail closed
A child tool that would return NeedsApproval does not run. It returns
access_denied and the child continues. The user is never asked from inside a
child. The child uses the parent session’s path rules and cannot widen them.
The parent grants a path first, then delegates.
Read-only narrows writes; fail-closed still bounds reads. A child that asks for
a path outside the session’s rules needs approval for read_paths, so
FailClosed turns that into access_denied rather than a prompt. Both
invariants have a test: one asserts the read-only profile for each child mode,
and one asserts no child tool schema carries an escalation key.
Hitting the session budget returns explore_limit or delegate_limit as the
tool result. The parent continues and does the work itself.
A cancelled parent turn cancels the child. subagent_timeout_seconds (default
two minutes) cancels the child and the tool returns timed out.
Rejected
- Two tools,
exploreanddelegate. The model has one decision, which mode, and the runner is shared. The tool description tells it which mode to pick. - A child chat session in SQLite. The parent card only needs the snapshot. A second session would put file bodies where a later parent turn could load them.
- A new SSE event for child progress.
ToolCallUpdatedalready means the stored call changed. The snapshot is that change. - Letting the child ask for approval. An approval card is a question for the user, and a child has no line to them.
- Giving explore a shell. OpenCode’s explore agent can run bash. The noisy
part of exploration is file bodies, and a command’s output belongs to
general. - Witholding the shell from explore once the read tools went. Removing
read_file,grep,find, andlist_dirwould leave explore with no tools at all, so both modes get the read-only shell. The distinction between the modes is now the prompt and the call budget, not the tool set. - A writable
generalchild. A sandboxed write needs no approval, so the child would edit with nothing to audit it: its transcript is in memory and the parent sees only the summary.
Failure modes
- The child stops at its iteration cap. The parent still receives whatever answer was produced, or “stopped before a final answer”. That cap is logged at warn. A finished child is logged at info with its mode and tool-call count. A timeout is warn. A pause or any other failure is error. Cancellation is info.
- The child pauses. That is a bug in the fail-closed wrapper. The tool returns an error instead of leaving the parent waiting.
- A progress write fails. The in-memory snapshot is still applied when the call finishes, so the card is complete after the tool returns.
- The answer is untrusted. A child that read a file can repeat what the file said. The parent verifies a claim before it edits.
Providers and streaming
This page defines how Robi reaches a model provider: the request it builds, the delta protocol a response becomes, and how it retries, times out, cancels, and reports failure. It is the design doc for M1 in the roadmap.
The first implementation is one OpenAI-compatible chat-completions client, wired
to OpenCode Go. Read this page before writing code in crates/robi::agent::providers.
What this page does not cover
| Topic | Where it belongs |
|---|---|
The Model trait, the Delta enum, and the loop that consumes it | agent-loop.md (M0) |
| The IPC encoding of a delta, and how the UI subscribes | docs/src/design/core/architecture.md (M2) |
| Where the API key lives, and the settings UI that produces it | docs/src/design/persistence/persistence.md (M2) |
| Token accounting and compaction triggers | docs/src/design/workspace/context-management.md (M3) |
This page fixes the in-process provider boundary. The delta vocabulary is already fixed by M0; M1 adds emitters, not variants.
Problem
The M0 loop is frozen: it drives an async, cancellable Model and consumes a
stream of deltas. M1 makes that real, and every hard part sits in the adapter:
- A provider accepts one shape of transcript and no other. Robi’s transcript
has no
systemrole, and its tool-call ids are UUIDs the provider never issued. Both need a mapping rule, and the rules are load-bearing. - A stream can fail after it has already produced output. A retry that fires mid-stream renders a partially duplicated message. The retry boundary has to be a property of the design, not a hope.
- The endpoint is a proxy in front of 33 models from different labs. The fields that carry reasoning are not in OpenAI’s schema, and a strict decoder drops them or fails the turn.
- A cancelled turn must leave a resolvable transcript. Cancellation arrives while a socket is open, so the adapter owns part of that guarantee.
Scope
In scope. One provider family, OpenAI-compatible chat completions, and one instance of it, OpenCode Go. Streaming deltas, tool calling, reasoning traces, retries, cancellation, a model catalog, an SSE decoder, and the tests for each.
Out of scope. The Anthropic client, the OpenAI Responses API, embeddings, structured outputs, per-session model selection in a UI, and the settings and keychain layer. This milestone defines the seam that layer plugs into; it does not build it.
Provider facts
| Fact | Value |
|---|---|
| Base URL | https://opencode.ai/zen/go/v1 |
| Chat endpoint | POST {base}/chat/completions, SSE when streaming |
| Model list | GET {base}/models |
| Model id | Config uses opencode-go/<model-id>; the provider receives <model-id> alone |
| Auth | Authorization: Bearer <api key> |
| Session header | x-opencode-session: <stable id per conversation> |
| User agent | The agent’s own name, robi/0.1 |
| Catalog | 33 models, all with tool calling and reasoning |
Sources: OpenCode Go, OpenCode providers, models.dev: opencode-go.
These facts come from vendor documentation, not from a live probe, and the vendor serves tool-less models elsewhere. The catalog lists only the tool-capable ones, so every entry above is one this loop can drive. The live tests in Testing are what would confirm the framing; they are not written yet.
Decisions
D1 — A hand-written adapter, not an OpenAI SDK
Take no OpenAI SDK. Write one adapter for one wire format, covering only the subset the transcript needs.
- There is no official OpenAI Rust SDK. OpenAI ships Python, Node, .NET, Java,
and Go; Rust is an open feature request
(openai-go #628). “Use the
SDK” therefore means a third-party crate, today
async-openai. - An SDK does not remove the work that carries the risk. The delta vocabulary is Robi’s and frozen from M0. An SDK returns its own types, so the transcript mapping, delta mapping, tool-call assembly, cancellation path, timeouts, and error classification are written either way. The SDK replaces HTTP and SSE plumbing: three files of the module tree below.
- A typed decoder drops exactly the fields this endpoint needs.
reasoning_contentis not in OpenAI’s schema. Reading it throughasync-openaimeans bypassing the typed stream withcreate_stream_byotand a custom chunk type, as in agent-driver-rs #2 onasync-openai0.41.1. That work comes with the dependency, not instead of it, and a strict decoder fails a turn on a line our decoder skips. A proxy fronting 33 models from different labs emits lines no one schema describes. - The costs are concrete. A large transitive tree, a version pin, and an MSRV that may exceed the workspace’s 1.75 pin.
Rejected: async-openai or a comparable crate. It supports a custom base URL,
per-request headers, and SSE streaming, so it would work. This is a judgement
call favouring tolerance and a small dependency tree, not a proven conclusion.
This decision is cheap to reverse. The adapter sits behind
robi_core::Model, and wire.rs, sse.rs, and stream.rs stay separate. Swap
the plumbing in one file. Re-open the decision when a second provider shows the
plumbing duplicating, or when the provider count passes two.
D2 — The adapter injects the system prompt
robi_core::message::Role has User, Assistant, and Tool, and the
transcript holds no system message. Build the request with
{"role":"system","content": settings.system_prompt} prepended.
Rejected: adding Role::System to robi-core. That is a core change for a
provider-shaped concern. robi-core::prompt renders ordered blocks.
crates/robi::agent::prompt loads the sources, including the registered tools, and
the model source stores the result on settings.system_prompt. See
instructions.md.
Consequence, accepted: a session record cannot show what the model was told, because the system prompt never enters the transcript.
D3 — The provider’s tool-call id is the wire id; the UUID stays the loop’s identity
The chat format requires the id in an assistant tool_calls[] entry to equal the
tool_call_id of the answering tool message. The provider mints its own id
(call_abc123); Robi mints a UUID.
Store the provider’s id and send it back:
#![allow(unused)]
fn main() {
// crates/robi-core/src/message.rs
/// The id the provider issued for this call, when it issued one.
///
/// The wire id: a stateless request body must repeat what the provider handed
/// out. Not identity — the loop keys on `id`, so a provider id that is reused,
/// absent, or malformed cannot confuse approval or lookup.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub provider_call_id: Option<String>,
}
Request building sends provider_call_id when present and the ToolCallId string
otherwise. An OpenCode Go turn always provides one, so the fallback covers
fixtures, a replayed transcript, and a server that omits the field.
Keep both ids, because they answer different questions. The wire needs the
provider’s id to accept the request. The loop needs a stable local key: ToolCallId
indexes Message::tool_call_id, Agent::approve, Agent::reject, and the
pending-call scan. A provider id is an opaque string from an endpoint fronting 33
models, nothing guarantees it is unique across turns, and a duplicate would make
two calls indistinguishable to approve.
A single ToolCallId -> wire id map, built by scanning the transcript’s assistant
messages, resolves both the assistant entry and the matching tool result, so the
two always agree. The lookup is needed either way, because a tool-result message
carries only the local id.
Rejected: widening ToolCallId to Uuid | Opaque(String). It changes a type
the loop compares and looks up, in serialization and at every construction site,
to carry a string the loop never reads.
Rejected: an adapter-side ToolCallId -> provider id map. The adapter is
stateless, and the transcript is the only state that survives a restart. After a
restart the map is empty, so a resumed conversation sends a tool result whose id
the provider no longer recognizes. That failure is silent and appears only on
resume.
Why the change is small. The field is additive, so ToolCallId stays a UUID
and #[serde(default)] keeps existing serialized transcripts deserializing.
ToolCall has one construction site, ToolCall::new, and no struct-literal
construction anywhere in the crate. The field follows the args_error precedent:
an optional annotation an adapter sets.
What sets it. Delta::ToolCallStart does not change. The vocabulary is fixed
from M0, and no consumer needs the provider’s internal id mid-stream. The adapter
keeps the provider id in per-index assembly state and stamps it on the ToolCall
inside the Finished message, which the loop appends as it is.
D4 — The session header is the loop’s SessionId, passed to the model
The vendor asks for a stable id per conversation in x-opencode-session, for
routing and prompt caching. The loop already holds exactly that value: Agent
carries a SessionId from MessageStore::create_session through every turn, and
model_turn has it one line above its call to Model::generate. Pass it in and
send it as the header. The adapter treats it as an opaque string.
That means one signature change to Model::generate:
#![allow(unused)]
fn main() {
async fn generate(
&self,
session: SessionId,
transcript: &[Message],
cancel: CancellationToken,
) -> Result<ModelStream, ModelError>;
}
The id is minted once, when the store opens a session, and is persisted with it, so it is identical on every turn of a conversation and identical after a restart.
Send the header on POST /chat/completions and nowhere else: not on a model-list
request, not on a catalog refresh, which is vendored (D9).
This is a deliberate change to a trait the M0 doc froze, and it is the right one. Three reasons:
- It is not a new concept. The id already reaches the call site. Deriving the key from the transcript’s first message would invent a proxy for a value the loop is already holding.
- The proxy is fragile. Compaction (M3) can drop the first message, which silently changes the key and loses the prompt cache the header exists to keep. A design whose own caveat is “the key may change” has the wrong key.
- The trait was incomplete, not merely inconvenient. Per-session model
selection (F1.4) needs a router mapping a session to a configured model, and a
Modelreceived only the transcript and the cancellation token. Without the session id in the signature that router cannot be written; it would have to re-derive the session from the transcript, which is the same fragile trick again.
agent-loop.md owns the Model trait, so it is updated in the same
change, per the working rule that documentation ships with the behavior.
Rejected: deriving the header from the transcript’s first message. It works until compaction, and it makes the key an accident of transcript content rather than a fact about the conversation.
Rejected: an in-memory random id per session. It changes across a process restart, which defeats the caching it exists for.
Rejected: a ModelCallContext struct holding the session. One field today, and
a struct added for a second field that may never arrive is speculative. When a
second per-call input appears — a token budget, a retrieval hint — wrap the
signature then and move the id into it.
D5 — ModelError stays two-variant
robi_core::error::ModelError has Provider(String) and StreamClosed.
Retryability is decided inside the adapter, so the loop never needs it. The adapter
encodes the HTTP status and a stable kind word in the message text, as in
the provider is rate limiting requests (429): ....
The text after the colon is the provider’s own explanation, kept whole. An error
body is the only place a provider says which quota ran out or which key it
refused, so error_detail reads the JSON error.message and keeps its type
and code beside it, as in insufficient_quota. A body that is not JSON is
passed through as it arrived, with an HTML page reduced to its visible text.
Nothing is cut before that sentence: the banner that shows it has room for a
paragraph, and a 512-byte window used to end mid-sentence. A body that is empty
falls back to the status reason.
Deferred: a structured ModelError::Http { status, retryable, body }, when the
M2 UI must render a rate limit differently from a rejected key. Recording the
deferral keeps the loop frozen at M1.
D6 — A hand-written SSE decoder
Decode SSE with about 60 lines over Response::bytes_stream(). That keeps exact
control of the inter-chunk timeout and of cancellation, which a wrapper hides.
The decoder reads a byte stream, not lines, and handles what the spec requires:
- Join multi-line
data:fields into one payload, separated by\n. - Accept both CRLF and LF line endings.
- Ignore
:comment lines, andevent:,id:, andretry:fields. - Dispatch the accumulated payload on a blank line.
- Treat
data: [DONE]as end of stream.
Rejected: reqwest-eventsource, async-sse, and eventsource-stream, which is
effectively unmaintained.
D7 — Retry only before the first delta
Allow a retry only while the adapter has emitted nothing: a connect failure, a
retryable status, a timeout waiting for response headers, or a failure before the
first Delta. After the first delta, a failure is terminal and becomes
Delta::Failed(ModelError::StreamClosed), so the loop ends the turn without
appending.
That boundary is what stops a retry from duplicating a partially rendered message.
flowchart LR
A[build request] --> B[send]
B -- "retryable, nothing emitted" --> B
B -- ok --> C[decode SSE]
C --> D[emit deltas]
D --> E[Finished, the loop appends]
C -- "failure after the first delta" --> F[Failed, terminal]
Policy:
| Response | Retry |
|---|---|
| 429 | Yes, after Retry-After when present, capped at 8 s |
| 5xx | Yes |
| Connect failure, or timeout on response headers | Yes |
| 400, 401, 403, 404, 422 | No |
| Cancellation | No |
Inter-chunk gap over chunk_timeout | No |
| Anything after the first delta | No |
Backoff is exponential with full jitter, 500 ms base, 8 s cap, 3 attempts.
Retry-After accepts both delta-seconds and an HTTP date, and a delay longer
than 8 s waits 8 s. The wait for response headers is 45 s. The gap between
chunks stays 5 min.
D8 — Credentials come from a factory, and the model never looks behind it
An OpenAiCompatibleModel takes a fully-constructed ProviderSettings and reads
no environment variable, no file, and no keychain. SettingsModelSource reads
the settings store when a session actor is built and
passes the result to build_model. A later SettingsStore can keep secrets in
the OS keychain. An actor that has already started keeps the model it was
given; the next actor reads the store again.
providers::factory::build_model owns construction, so the model type stays a leaf
and one place knows how a provider is assembled. It takes the ToolRegistry as well
as the settings, because the request body carries the tool definitions and
Model::generate is handed only the transcript. A live test builds the same way and
reads the key from the environment itself, which keeps this boundary honest.
Switching is resolved when the actor is built, not inside generate.
SettingsModelSource reads the session override, then the settings store, then
the built-in default, and build_model returns one Arc<dyn Model>. Agent
keeps holding that model and never learns that switching exists. A turn calls
generate several times, so resolving again on each call would let a mid-turn
change split one exchange across two models. The next actor, built when the
session goes idle, reads the choice again. One reqwest::Client is still built
per model; the actor’s lifetime is the cache.
Not by swapping the Arc<dyn Model> on the Agent. That produces a global
switch rather than a per-session one, and it needs &mut self or interior
mutability on an agent that several calls already drive concurrently.
Not by a ModelRouter that dispatches inside generate. The actor is
already rebuilt per execution, which is the turn boundary. The picker writes
model_config on the session; see persistence.md and
chat-runtime.md.
D9 — The catalog is vendored, tool-capable models only, and owns the window
Keep a checked-in model table, generated from a models.dev snapshot, plus a loader for user overrides. Fetching at startup makes the app fail without connectivity, and a live desktop tool should not phone home to render a context meter.
Two rules:
- List only models that call tools. A model that cannot call tools cannot drive
this loop, so listing one only invites a session that fails.
build_modelvalidates the configured model against the catalog at construction and fails with an error naming the id, rather than discovering the problem on the first turn. context_windowis the model’s own advertised window, with no plan-tier arithmetic. The vendor’s tiered figures (Grok 4.7 at 200K, GPT 6 Luna at 272K) are pricing boundaries. They belong in the price table M2 uses for cost, never in the window M3’s meter reads.
M1 needs id, display_name, context_window, max_output, and
supports_reasoning. Pricing rides along from the snapshot, unused until M2.
D10 — The transcript stores image references, never bytes
A user attaches images to a message. The transcript records only the reference — an id and a media type — not the bytes:
#![allow(unused)]
fn main() {
// crates/robi-core/src/message.rs
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ImageAttachment {
pub id: String, // the `chat_images` row id
pub media_type: String, // "image/png", "image/jpeg", "image/webp", "image/gif"
}
// Message gains:
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub images: Vec<ImageAttachment>,
}
#[serde(default)] keeps every stored transcript row deserializing, the same as
the provider_call_id and subagent precedents. Only Role::User messages carry
images.
Rejected: a data: URI (or the bytes) inside Message. The transcript is
serialized into the chat_messages.body TEXT column, fanned out on the SSE event
stream, and returned by every GET /messages. Base64 there bloats the database
~33% per image, ships megabytes on every transcript read, and leaks into the DTO
and events. The wire needs the data URI; the transcript does not.
D11 — The adapter resolves bytes at send time, through a provider-side port
Model::generate receives only the transcript, and the adapter is stateless
across restarts. So providers declares its own read port, and an ImageStore
port that also accepts new rows:
#![allow(unused)]
fn main() {
// crates/robi/src/agent/providers/images.rs
#[async_trait]
pub trait ImageSource: Send + Sync {
async fn image(&self, id: &str) -> Result<Option<(String, Vec<u8>)>, ProviderError>;
}
#[async_trait]
pub trait ImageStore: ImageSource {
async fn store(&self, chat_session_id: &str, id: &str, media_type: &str,
bytes: Vec<u8>) -> Result<(), ProviderError>;
}
}
ImageSource is what the model’s request builder sees. ImageStore adds the
write surface the ingestion handler uses, keeping it out of the read-only port the
provider reaches. BlobImageStore implements both over the session blob file;
factory::build_model and the web layer each take Arc<dyn ImageSource>
or Arc<dyn ImageStore> as appropriate, wired the same way the ToolRegistry
already is.
generate resolves every attachment id up front into a
HashMap<String, (String, Vec<u8>)> and passes that into build_request, which
stays pure and golden-testable.
Failure: a missing row fails the turn. image <id> is missing from the store
reaches the loop as a ModelError::Provider. Never send a silently truncated
message and never drop the part: the user attached it, and quiet loss is the one
failure neither the model nor the user can detect.
D12 — Content parts on the wire; text-only bodies stay byte-identical
In wire.rs, ChatMessage.content: String becomes an untagged content enum:
#![allow(unused)]
fn main() {
// providers/openai/wire.rs
#[derive(Serialize)]
#[serde(untagged)]
pub enum WireContent {
Text(String), // a plain string, exactly as before
Parts(Vec<ContentPart>),
}
#[derive(Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ContentPart {
Text { text: String },
ImageUrl { image_url: ImageUrl }, // { url: "data:<media_type>;base64,<b64>" }
}
}
Rules, each with a test:
- Only a
Role::Usermessage with non-emptyimagesusesParts. Every other message — and a text-only user message — serializes byte-for-byte as before, so prompt-cache prefixes and golden tests are unchanged. - A user message with images always emits a text part first (its content, even
when empty), then one
image_urlpart per attachment in attach order. - Assistant, tool, and system messages stay strings. The provider does not need images echoed back beyond the turn that carried them, and chat-completions vision models accept the history either way; we send the parts each relevant turn so multi-turn image questions keep working.
- The
image_urlis adata:URI built from the resolved bytes. No remotehttpsURLs in the first cut — the desktop app has local files, not URLs.
D13 — Vision capability is catalogued, and gating happens in the adapter
ModelInfo gains supports_vision: bool. The vendored table sets it per row;
where the models.dev snapshot does not state it, the default is permissive
(true) so a capable model is never blocked by missing metadata — the provider’s
own 400 is the honest fallback.
Gating happens inside generate at request build: images present and the
configured model !supports_vision → the turn fails with ProviderError::NoVision
naming the model (“visionless does not accept image input”). It surfaces as a
failed turn the UI can show, not a submit-time refusal: the model choice can
change between attach and send (D8), so the actor that builds the request is the
only place that knows. A text-only turn never touches the flag or the store.
D14 — One multipart request ingests images; a side table stores the bytes
POST /api/v1/chat_sessions/{id}/messages accepts multipart/form-data: one
instruction text field plus images file parts. The existing JSON body keeps
working for text-only (the handler dispatches on content type). Limits, enforced
at the handler:
| Limit | Value | On breach |
|---|---|---|
| Per image | 10 MiB | 413 naming the file |
| Per message | 8 images | 400 |
| Media types | image/png, image/jpeg, image/webp, image/gif | 415 |
The media type is validated by magic bytes (PNG/JPEG/WEBP/GIF signatures, a
~30-line matcher). No decode, no re-encode, no image crate: providers handle
large images by tiling or rejecting, and the token cost comes back in Usage.
Bytes go in ~/.robi/sessions/<session_id>/blobs.redb (schema in
persistence.md). They never enter
chat_messages. Session delete removes that directory. A
GET /chat_sessions/{id}/images/{image_id} route serves the bytes for the
UI’s message bubbles.
Rejected: a separate upload endpoint returning an id. It needs orphan cleanup for images attached but never sent, and it splits one user action across two requests that can fail between them.
Anthropic (A1–A12)
M1 also adds Anthropic’s native Messages API as a second provider family. The
constraints that shape it: Haiku 4.5 does not accept the effort parameter, the
user never picks a provider (one flat model list), and every model id carries
a provider prefix (ocg_ for OpenCode Go, ant_ for Anthropic).
A1 — A second hand-written adapter, not a shared abstraction
providers/anthropic/ has its own wire.rs, stream.rs, and mod.rs. Anthropic’s
request shape (top-level system, required max_tokens, input_schema tools,
content blocks) and its typed SSE event stream are different enough from
chat-completions that a shared abstraction would be the lowest common denominator.
The only piece promoted to a shared module is the SSE framing
(providers/sse.rs): blank-line dispatch, CRLF, multi-line data:, and :
comments are protocol-level, and each adapter decodes a payload its own way.
D1’s revisit clause stands: the retry/pump/cancel skeleton is near-duplicated, and
a providers/transport.rs extraction is the follow-up if it proves noisy.
A2 — Per-model effort gating lives in the catalog
ModelInfo gains supports_effort: bool. The Anthropic table sets it true for
ant_claude-fable-5-1, ant_claude-opus-5-5, and ant_claude-sonnet-5-5, and
false for ant_claude-haiku-4-5. Haiku rejects output_config with a 400
(“Extra inputs are not permitted”), so the adapter omits the field when the
flag is false. A configured effort still builds the model: the setting is
global, and switching the session to Haiku must not fail startup. OpenCode Go rides
effort on reasoning_effort and is never gated, so its rows carry true.
A3 — Reasoning without an effort field is thinking, and the trace round-trips
Anthropic’s thinking blocks arrive as thinking_delta events and map to
Delta::Reasoning. A tool continuation must echo the thinking block back,
unmodified, with its signature, so Message gains an additive
reasoning: Option<ReasoningTrace> (text + signature), set by the adapter at
Finished and echoed in wire.rs for the assistant turn whose tool results are
still pending. A trace with no signature is not echoed: the API rejects one. Old
rows deserialize as None.
A4 — provider_call_id is the tool_use_id
Anthropic issues toolu_… ids in tool_use blocks; ToolCall.provider_call_id
stores them, and the tool_result block is keyed by that same id. D3’s pattern,
unchanged — no new core field.
A5 — max_tokens comes from the catalog’s max_output
The Messages API requires max_tokens. The adapter sends the configured model’s
catalog max_output; no new setting, no per-request arithmetic.
A6 — No session header for Anthropic
There is no x-opencode-session equivalent. Model::generate still receives the
loop’s SessionId (D4’s trait is unchanged); the Anthropic adapter simply does not
send a session header. The x-api-key and anthropic-version: 2023-06-01 headers
replace the bearer/session pair.
A7 — Stop reason mapping
message_delta.stop_reason: end_turn/stop_sequence → settled Finished;
tool_use → settled with assembled tool calls; max_tokens → settled but logged
at warn (the same known-gap treatment as finish_reason: "length"); refusal →
Failed.
A8 — Cumulative usage
message_delta.usage is cumulative: it supersedes message_start’s counts.
The assembler replaces rather than adds, so the final Usage delta is correct.
A9 — Error events mid-stream
An event: error inside a 200 stream becomes Delta::Failed, the same as the
OpenAI {"error": …} object. overloaded_error is terminal once deltas have
streamed — the retry boundary stays “before the first delta” (D7). 429/5xx and
Retry-After classification is the shared retry.rs, unchanged.
A10 — Images
A Role::User message with images becomes image content blocks
(source: { type: "base64", media_type, data }). The adapter reuses
resolve_images (D11) unchanged, so vision gating (D13) and the missing-row
failure are identical to OpenCode Go.
A11 — Model ids carry a provider prefix; the prefix resolves the provider
There is no provider picker. The dropdown is one flat list; the id itself
names the provider. Each provider has an on/off setting (provider_opencode_go,
provider_anthropic, provider_deepseek, default on). off drops that catalog from
GET /api/v1/models and makes SettingsModelSource refuse a turn whose resolved
id belongs to it. The prefix is still the dispatch.
- Prefixed ids everywhere. OpenCode Go rows are
ocg_glm-5.3, …; Anthropic rows areant_claude-sonnet-5-5, …; DeepSeek rows aredsk_deepseek-flashanddsk_deepseek-v4-pro. The prefix is part of the id in the settings store, the session’smodel_config, the/api/v1/modelsresponse, the dropdown, and the catalog keys. - The prefix is the dispatch.
SettingsModelSourceruns the existing resolution chain (session override → mode setting →MODEL→ default), then reads the prefix:ant_buildsProviderSettings::anthropic(...)and requiresanthropic_api_key;ocg_buildsProviderSettings::opencode_go(...)and requiresopencode_go_api_key;dsk_buildsProviderSettings::deepseek(...)and requiresdeepseek_api_key. DeepSeek uses the OpenAI-compatible adapter and its own base URL (deepseek_base_url, defaulthttps://api.deepseek.com).build_modeldispatches the same way. - The wire gets the bare id. Both providers want their own id
(
claude-sonnet-5-5,glm-5.3), never the prefix.ModelId::wire_idstrips it, golden-tested. DEFAULT_MODELisocg_glm-5.3.- Legacy bare ids read as OpenCode Go. A settings or session row written
before the prefix existed holds a bare id;
ProviderKind::oftreats an unknown prefix as OpenCode Go,build_modelnormalizes it to the prefixed form, andnormalize_modelrewrites it on store. No stored session breaks. normalize_modelvalidates the union of both catalogs.GET /api/v1/modelslists the enabled catalogs in one flat list. A provider set tooffis omitted. The frontend picker is otherwise unchanged.- The key follows the provider. Switching a session to a Claude model makes the
next actor read
anthropic_api_key; a missing key is the existing “… is not set” refusal naming the key. - Catalog tests assert every id carries its provider’s prefix, the two tables are disjoint, and the free-text ids are unique across the union.
A12 — Effort on Anthropic maps to output_config, not budget_tokens
On the current lineup output_config: { effort } is a stable API field and
controls all token spend, thinking included. Haiku rejects the field outright
(A2). budget_tokens is not used: later models reject it. An unset effort sends
no output_config.
Anthropic request mapping
| Transcript | Messages request |
|---|---|
settings.system_prompt | top-level system (A1), omitted when empty |
Role::User | { "role": "user", "content": msg.content } |
Role::User with images | content: [{type:"text",…}, {type:"image",source:{type:"base64",…}}…] (A10) |
Role::Assistant | plain text when it made no tool call and has no thinking |
Role::Assistant with a tool call | content: [{type:"thinking",…}?, {type:"text",…}?, {type:"tool_use",id,name,input}…] (A3) |
Role::Tool | a user message with one {type:"tool_result",tool_use_id,content} block (A4) |
ToolRegistry::tools() | tools: [{name, description, input_schema}], no function wrapper |
settings.reasoning_effort | output_config: {effort}, only when supports_effort (A2/A12) |
| — | max_tokens: the catalog’s max_output (A5), stream: true |
| — | headers: x-api-key, anthropic-version, User-Agent, Content-Type |
Anthropic response mapping
SSE payload type | Delta |
|---|---|
message_start | seeds Usage from message.usage |
content_block_start (text/thinking) | nothing; the deltas carry the content |
content_block_start (tool_use) | ToolCallStart { index, id: <minted>, name } |
content_block_delta text_delta | Text |
content_block_delta thinking_delta | Reasoning |
content_block_delta input_json_delta | ToolCallArgs |
content_block_delta signature_delta | recorded, not emitted |
content_block_stop | ToolCallEnd for the open tool-use block |
message_delta | Usage (cumulative, A8) and stop_reason |
message_stop | Finished(<assembled Message>) |
error inside a 200 stream | Failed |
an unknown type | skipped (versioning) |
The assembled assistant message carries the thinking trace as Message.reasoning
(A3) and each call’s provider_call_id, which the next request echoes.
Modules
AGENTS.md puts providers in a module of crates/robi, not a crate of its own.
crates/robi-core/src/model.rs # Model::generate takes the session id (D4)
crates/robi-core/src/agent.rs # model_turn passes the id it already holds (D4)
crates/robi-core/src/message.rs # + ToolCall.provider_call_id (D3), + Message.images (D10), + Message.reasoning (A3)
crates/robi/src/agent/providers/
mod.rs # re-exports, ProviderId, ProviderKind, ModelId, the prefixes
config.rs # ProviderSettings, redacting ApiKey, ModelId::wire_id, ProviderSettings::anthropic (A1)
factory.rs # build_model(settings, tools, images), dispatch on the model prefix (A11)
error.rs # ProviderError, and its mapping into ModelError
images.rs # ImageSource (read) and ImageStore (read + write) ports (D11)
retry.rs # RetryPolicy, backoff, classify
sse.rs # the shared SSE framing (A1)
catalog/ # mod.rs, opencode_go.rs (ocg_*), anthropic.rs (ant_*); supports_effort (A2), all() (A11)
openai/ # mod.rs (impl Model), wire.rs (WireContent, D12), stream.rs
anthropic/ # mod.rs (impl Model), wire.rs, stream.rs (A1–A12)
crates/robi/src/adapters/chat_image_store.rs # BlobImageStore (D11), MemoryImageStore (tests)
crates/robi/src/adapters/session_blobs.rs # per-session redb file
crates/robi/src/web_api/chat_message.rs # multipart ingestion + GET image route (D14)
crates/robi/tests/provider.rs # the fake SSE server and its cases, both providers
M1 makes these edits to `robi-core`: the additive `provider_call_id` field (D3),
the `user_input_with_skills`/`Model::generate` signatures (D4), the new
cancellation point at the call site, the additive `Message.images` field with
`Message::user_with_images` (D10), and the additive `Message.reasoning` field with
`ReasoningTrace` (A3). All are recorded in
[agent-loop.md](../core/agent-loop.md), which owns the transcript types and the
`Model` trait. Everything else in the core stays as M0 left it: the turn state
machine, the approval path, the delta vocabulary, and the other three traits.
`docs/src/roadmap.md` F0.1 names `robi-providers` as the M1 crate. `AGENTS.md` is the
layout authority and says `crates/robi`; follow `AGENTS.md`, and fix the roadmap.
## Dependencies
Declare these in the root `[workspace.dependencies]` and reference them from
`crates/robi/Cargo.toml`. Run `cargo add` to resolve versions, and commit the
updated `Cargo.lock`.
| Dependency | Features | Why |
|---|---|---|
| `reqwest` | `json`, `stream`, `rustls-tls`, `default-features = false` | HTTP and streaming; rustls avoids an OpenSSL system dependency in a bundled app |
| `futures-util` | — | `StreamExt` over `bytes_stream()` |
| `bytes` | — | The SSE decoder's input |
| `http` | — | `StatusCode`, `HeaderName` |
| `tracing` | — | Request lifecycle logs, with the key redacted |
Already in the workspace: `async-trait`, `serde`, `serde_json`, `thiserror`,
`tokio` (add the `stream` feature), `tokio-util`, and `uuid`.
Dev only: `axum` for the fake server, and the `net` feature of `tokio` for the
listener.
`robi-core` gains no dependency. `cargo tree -p robi-core` stays short, and that
command is the audit.
## Interfaces
```rust
// crates/robi-core/src/message.rs — core change 1 of 2 (D3)
pub struct ToolCall {
pub id: ToolCallId,
// ...existing fields...
pub provider_call_id: Option<String>, // serde(default, skip_serializing_if)
}
// crates/robi-core/src/model.rs — core change 2 of 2 (D4)
#[async_trait]
pub trait Model: Send + Sync {
async fn generate(
&self,
session: SessionId, // new: the id the loop already holds
transcript: &[Message],
cancel: CancellationToken,
) -> Result<ModelStream, ModelError>;
}
// crates/robi-core/src/agent.rs — core change 3 of 3 (D7, cancellation)
// `model_turn` selects on the cancel token around `generate`, so a cancel before
// the response headers arrive is `Cancelled` rather than a transport failure:
let stream = tokio::select! {
biased;
() = cancel.cancelled() => return Err(TurnError::Cancelled),
stream = self.model.generate(*session, &transcript, cancel.clone()) => stream?,
};
// providers/config.rs
#[derive(Clone)]
pub struct ProviderSettings {
pub id: ProviderId, // "opencode-go"
pub base_url: String,
pub api_key: ApiKey, // Debug and Display print "<redacted>"
pub model: ModelId, // "glm-5.3"
pub system_prompt: String,
pub session_header: Option<HeaderName>, // Some("x-opencode-session")
pub user_agent: String, // "robi/0.1"
pub header_timeout: Duration, // 45 s
pub chunk_timeout: Duration, // 5 min
pub retry: RetryPolicy,
pub reasoning_effort: Option<ReasoningEffort>,
pub session_key_override: Option<String>, // defaults to the SessionId the loop passes (D4)
}
// providers/factory.rs — the seam M2 fills
pub fn build_model(
settings: ProviderSettings,
tools: Arc<ToolRegistry>, // the request carries the tool definitions, and
// `Model::generate` is not given them, so the
// adapter holds the registry
) -> Result<Arc<dyn Model>, ProviderError>;
// No env var, no file, no keychain behind this: the credential is already in `settings`.
// providers/retry.rs
pub struct RetryPolicy { pub max_attempts: u32, pub base: Duration, pub cap: Duration }
pub enum Retry { Yes { after: Option<Duration> }, No }
pub fn classify(status: StatusCode, headers: &HeaderMap) -> Retry;
// providers/openai/wire.rs
/// The id sent on the wire per call: the provider's own id when the transcript
/// carries one, else the `ToolCallId`.
pub fn wire_call_ids(transcript: &[Message]) -> HashMap<ToolCallId, String>;
// providers/openai/mod.rs
#[async_trait]
impl Model for OpenAiCompatibleModel {
async fn generate(
&self,
session: SessionId,
transcript: &[Message],
cancel: CancellationToken,
) -> Result<ModelStream, ModelError>;
}
generate sends the request under header_timeout, then spawns one task that owns
the response body and forwards deltas over an mpsc channel wrapped in
ModelStream. The header wait and that task both select on cancel.cancelled():
around the request, around every chunk read, and around every delta send. The
channel is bounded, so a bare send().await would ignore a stop until the loop
drained the queue. A cancel drops the body and closes the connection instead of
leaving a task parked in chunk().await or send().await. After a cancellation
the task sends no Delta::Failed, because the loop already owns the cancelled
outcome.
Request mapping
| Transcript | Chat-completions request |
|---|---|
settings.system_prompt | prepended {"role":"system","content":…} (D2) |
Role::User | {"role":"user","content": msg.content} |
Role::User with images | {"role":"user","content": [{type:"text",text:…}, {type:"image_url",image_url:{url:"data:…"}}…]} (D12) |
Role::Assistant | content, plus tool_calls when the message has calls |
Role::Assistant with calls | tool_calls: [{ id: wire_id(call), type: "function", function: { name, arguments } }] |
Role::Tool | {"role":"tool","tool_call_id": wire_id_for(msg.tool_call_id), "content": msg.content} |
ToolRegistry::tools() | tools: [{ type: "function", function: { name, description, parameters } }] |
| — | stream: true, stream_options: {"include_usage": true} |
settings.reasoning_effort | reasoning_effort, only when set |
| — | model: settings.model |
| — | headers: Authorization, x-opencode-session, User-Agent, Content-Type |
arguments is serde_json::to_string(&call.args). A call with args_error sends
its stored raw text when the adapter kept it, and "{}" otherwise; the loop fails
that call before execution either way, so the value exists only for the provider to
accept the transcript.
ToolRegistry::tools() sorts by name, so the serialized tools array is
byte-stable across runs. That matters twice: an unstable array breaks prompt
caching, and it makes golden tests noisy.
Response mapping
| SSE payload | Delta |
|---|---|
choices[0].delta.content | Text |
delta.reasoning_content, or delta.reasoning | Reasoning |
tool_calls[i] with an id and name | ToolCallStart { index: i, id: <minted>, name } |
tool_calls[i].function.arguments | ToolCallArgs { index: i, fragment } |
the array index advances, or finish_reason arrives | ToolCallEnd { index: prev } |
a chunk’s usage | Usage |
data: [DONE] | Finished(<assembled Message>) |
{"error": …} inside a 200 stream | Failed |
Read both spellings of the reasoning field, reasoning_content and reasoning.
The field name is provider-specific, and which one arrives varies by model.
The assembled message reuses the ToolCallId minted at ToolCallStart, so the
delta events and the transcript agree, as agent-loop.md requires.
It carries the provider’s own id as provider_call_id, which is what the next
request sends back (D3).
Quirks to handle, each with a test:
- A chunk can split mid-JSON across two TCP reads.
- A server can omit
tool_calls[].index. Assume a single call then, and reject the turn when a second tool name appears. - A server can omit
tool_calls[].id.provider_call_idstaysNone, and the request falls back to the UUID string. - Usage arrives on a chunk whose
choicesarray is empty. choicesordelta.tool_callsmay be JSONnull. That is an empty list. DeepSeek sends"tool_calls": nullon a text chunk.finish_reason: "length"reports a truncated message.Messagehas nowhere to put that, so a truncated turn currently reads asComplete. See Known gaps.- A malformed line is skipped and logged at debug level. One bad keepalive must not kill a turn.
Failure modes
| Failure | Handling | Retry |
|---|---|---|
| 401, 403 | Provider naming a rejected credential, then the provider’s own message. The key is never echoed from the request | No |
| 404, or a model absent from the catalog | Name the model id | No |
| A catalog model without tool support | Refused at build_model, naming the id | No |
| 400, 422 | Surface the provider’s message; the body is deterministic | No |
| 429 | Honour Retry-After up to the 8 s cap, else back off. The last attempt fails the turn with the provider’s message | Yes, before the first delta |
| 5xx | Back off, then fail with the status and the body | Yes, before the first delta |
| Connect failure, or header timeout | Treat as transport | Yes, before the first delta |
Inter-chunk gap over chunk_timeout | Terminal; a stalled stream is not recoverable in place | No |
| Failure after the first delta | Delta::Failed(StreamClosed) | No |
Stream ends with no [DONE] and no finish_reason | StreamClosed; the message is not settled | No |
Anthropic stream ends with no message_stop and no stop_reason | StreamClosed; the message is not settled | No |
Anthropic event: error in a 200 stream | Delta::Failed (A9) | No |
Configuring an effort on a model with supports_effort: false | ProviderError::UnsupportedEffort naming the model, at build_model (A2) | No |
| Malformed SSE line | Skip, log at debug | — |
| Tool arguments that do not parse | ToolCall.args_error, never {} (agent-loop Deviation 3) | — |
| A provider that omits a tool-call id | provider_call_id stays None; fall back to the UUID string | — |
| Images on a non-vision model | ProviderError::NoVision naming the model (D13) | No |
| A transcript that references a missing image row | ProviderError::MissingImage naming the id; the turn fails (D11) | No |
| Cancellation before response headers | Return Err keyed off the token; the loop reports Cancelled | No |
| Cancellation mid-stream | Drop the body; send nothing further | No |
A response whose status is success is logged at info with the model id and
the status code. A finished stream is logged at info. A finish_reason of
length is logged at warn when the message is settled, because that turn
still completes. A stalled stream, a transport error, and a stream that fails
to assemble are logged at warn.
The API key never reaches a log, an error message, an event, or a test fixture.
ApiKey’s Debug and Display both print <redacted>, and request building never
formats a header map.
Testing
cargo test -p robi passes with no live network. A fake server binds 127.0.0.1:0
with axum, returns a scripted SSE body, and delays between chunks, so chunk
splitting, timeouts, and cancellation are deterministic.
Link loopback access to run it inside the sandbox, or run the suite unsandboxed.
| Test | Asserts |
|---|---|
| Core field round trip | provider_call_id: None serializes without the field, and a transcript written before the field existed still deserializes |
| Core field is not identity | approve, reject, and the pending-call scan resolve by id; two calls sharing a provider_call_id stay distinct |
| Request body | Transcript order, the injected system prompt, the tool array, and stream_options serialize as expected; two builds produce an identical tools array, so prompt caching and golden tests hold |
| Provider id on the wire | The stream’s provider ids are stored, and the next request carries them on both the assistant entry and the tool result |
| Provider id absent | Deltas that omit tool_calls[].id leave provider_call_id None, and both halves of the request still agree on the local id |
| Session id reaches the model | A stub records the SessionId it was given, and it equals the session the turn ran in, across every turn of one conversation |
| Session header | Every chat request carries x-opencode-session equal to that SessionId, plus the bearer credential and a robi/ user agent |
| Model validation | build_model rejects an unknown id and a tool-less model, each naming the id |
| Image wire shape | A user message with images emits content parts — text first, then one image_url per attachment with a data: URI from the resolved bytes, in attach order |
| Text-only bytes | A body without images serializes byte-identical with an empty resolution map, so prompt-cache prefixes hold |
| Missing image reference | A transcript referencing an unresolved id fails the build naming the id, rather than dropping the part |
| Vision gating | A non-vision model rejects the turn naming itself; a vision model resolves the bytes; a text-only turn skips both the store and the flag |
| Vision | ModelInfo.supports_vision is explicit on every vendored row |
| Text and reasoning | Chunks become Text and Reasoning deltas, both field spellings are read, and reasoning stays out of the message |
| Tool-call assembly | Interleaved fragments assemble in order, with ids that match the ToolCallStart deltas, and a second call at one index is refused rather than merged |
| SSE edge cases | A chunk boundary inside a data: line, a split multi-byte character, CRLF endings, a : comment, multi-line data:, and a final event with no blank line all parse |
| Usage chunk | A final chunk with an empty choices array yields Usage, reaches the finished message, and is not lost when it follows finish_reason |
| Malformed tool args | A truncated argument string sets args_error, not {} |
| Mid-stream error | An {"error": …} object in a 200 stream becomes Failed, not a panic |
| Retry | Retry-After is honoured; 429 then success sends two requests with exactly one Finished; 401 sends one; 500 sends max_attempts naming the status; backoff never exceeds its exponential ceiling (asserted directly, since full jitter is random) |
| No retry after a delta | A failure after the first delta sends no second request, and a stall past chunk_timeout ends the turn as Failed rather than being retried |
| Cancel | Cancelling while the request is in flight and while awaiting a chunk both give Cancelled, and neither appends a message |
| End to end | Agent::user_input with a real OpenAiCompatibleModel streams a turn, appends the assistant message, and completes |
Live text, #[ignore] | Not written. A real turn streams text; needs ROBI_LIVE_OPENCODE=1 and a key, read by the test |
Live tool call, #[ignore] | Not written. A real turn calls a tool, and the stored provider id round-trips and is accepted back |
The last two are not written. Every pass above is against a server this repository controls, so the vendor’s exact framing stays an assumption until something talks to the real endpoint. Trying it by hand is the shorter route to that: run the example once with a real key, and check streaming, a tool call, and the approval pause in one run.
Known gap
Recorded rather than papered over:
- No live turn has been run. The framing, the header names, and the model ids
come from vendor documentation, not from a response. The fake server in
tests/provider.rsencodes the same assumptions, so it cannot catch a wrong one. - No live image turn has been run either (D12–D14). The
data:URI content part, the vision flag source, and which models genuinely accept images come from vendor documentation and models.dev, not from a response. The catalog defaults vision permissive where the snapshot is silent, so the provider’s own 400 is what actually reports a wrong flag. - A truncated message reads as
Complete.finish_reason: "length"has nowhere to go inMessage, so the transcript cannot distinguish a finished answer from one the output limit cut off. The adapter logs that finish at warn. Add a field toMessagewhen a UI needs to show it. - The catalog’s figures are not verified against the endpoint. A window that is larger than the provider enforces means a context meter that under-reports.
- The system prompt is invisible to a session record (D2).
- A model switch applies to the next actor (D8). The one already running keeps the model it was built with, including an interrupt that only replaces the pending instruction.
- A tool-call id can outlive the model that issued it.
provider_call_idis recorded from whichever model answered, so after a switch a stored id was issued by a different model. A stateless endpoint only needs internal consistency, so this is normally fine; decide when the router lands whether to send the stored id anyway or fall back to the local UUID, since M1 has one provider. - One provider family had been wired. The OpenAI-compatible adapter generalizes to any chat-completions endpoint, but Kimi, DeepSeek, and OpenRouter need their own base URL, auth, and catalog entries. Anthropic now ships alongside it (A1–A12).
- Anthropic’s framing is unverified too. The
input_schematool shape, theoutput_configgating, and the thinking-block round trip come from vendor documentation, not a live response; the fake server intests/provider.rsencodes the same assumptions. Run the example with a realANTHROPIC_API_KEYto confirm.
Where this landed
Built, in the order the plan called for:
robi-corefirst, because everything compiles against it: theToolCall.provider_call_idfield (D3), thesessionparameter onModel::generate(D4), the cancellation select at themodel_turncall site, the additiveMessage.imagesfield (D10), the additiveMessage.reasoningfield withReasoningTrace(A3), and theStubModelupdate intestkit.rs.robi-coregained no dependency.crates/robi, withprovidersas its first module —config,error,retry,sse,catalog(opencode_goandanthropic),factory, and theopenaiadapter (wire,stream, and theModelimpl). Dependencies stay off the core:reqwestwithrustls-tlsand no default features, plusfutures-util,bytes,http, andtracing. Anthropic’s adapter addedanthropic/(wire,stream, and theModelimpl) beside it (A1–A12).- Tests — unit tests across
robi(includingagent::providers::anthropic) and 24 incrates/robi/tests/provider.rsagainst a scriptedaxumSSE server, covering both wire formats.cargo test --workspaceruns offline. - An entrypoint —
crates/robi/examples/simple.rs, which drives the whole stack by hand and picks the provider fromROBI_MODEL’s prefix. See Trying it by hand.
To run the full check:
cargo test --workspace
cargo clippy --workspace --all-targets -- -D warnings
Next, in order: run one real turn against each provider with the entrypoint below. F1.4’s selection is the actor-start chain in D8.
Trying it by hand
cargo run -p robi --example simple builds a model and an agent, registers two
tools, and runs a conversation. It is the smallest program that exercises the
adapter, the transcript, the registry, and the approval path together, and it is
the quickest way to check a change against a real endpoint.
export OPENCODE_GO_API_KEY=...
cargo run -p robi --example simple # the scripted two turns
cargo run -p robi --example simple -- "Add 40 and 2" # one prompt instead
# Anthropic: the prefix on ROBI_MODEL selects the provider and the key.
export ANTHROPIC_API_KEY=...
ROBI_MODEL=ant_claude-sonnet-5-5 cargo run -p robi --example simple
| Variable | Required | Default | Meaning |
|---|---|---|---|
OPENCODE_GO_API_KEY | for an ocg_ model | — | The OpenCode Go bearer credential |
ANTHROPIC_API_KEY | for an ant_ model | — | The Anthropic x-api-key credential |
ROBI_MODEL | no | ocg_glm-5.3 | Prefixed model id; the prefix picks the provider (A11) |
ROBI_BASE_URL | no | the vendor’s | Point at another endpoint, including a local fake |
ROBI_EFFORT | no | unset | low, medium, or high; refused on Haiku (A2) |
The system prompt is fixed in the file rather than read from the environment, and it forbids mental arithmetic on purpose. A model that answers from memory produces a correct number without calling a tool, which leaves the tool path, the approval pause, and the provider’s tool-call id round trip all untested.
It runs two turns unless you pass a prompt:
Add 2 and 3.— the tool needs no approval, so the turn completes on its own.Now multiply 454 by 543.— the tool needs approval, so the turn pauses. The pending call is printed, andyornon the terminal approves or rejects it. Answering nothing, or closing stdin, counts as a rejection: a call that asked for a decision fails closed.
Then it prints the transcript, each call’s approval and execution status, and the
token counts. Both answers are worth running: approving exercises
approve + resume, and rejecting exercises the rejection the model reads.
What it found. The first run listed an addition call for approval that turn
one had already run to completion. Agent::pending_tool_calls filtered on
ApprovalStatus::Pending alone, and the loop records a decision only when a user
makes one, so a call that needed no approval keeps Pending for its whole life.
The filter now also requires needs_execution, which is the same predicate the
rest of the loop already used. Two robi-core tests cover it.
Still open. An executed auto-approved call reads back as
approval_status: Pending, which is now harmless but will render oddly in a UI.
Decide in M3, when the first no-approval tools ship, whether the loop should mark
an auto-approved call Approved at plan time instead.
Frontend layout
The Solid app under src/ is organized by feature. A feature owns the screens
and small components for one product area. Shared chrome and primitives stay
outside those slices so a feature can be split further without pulling shell
code with it.
Layout
src/
main.tsx # Solid entry
app/ # Shell: router host, window chrome, startup route, surface flags
api/ # openapi-fetch client and generated types
features/ # Vertical slices (chat, docs, review, settings, workspaces)
components/
ui/ # Shared primitives (icons)
layout/ # Window frame, top bar, recents menu, chat chrome
state/ # Stores read by more than one feature
infra/ # Tauri invoke boundary
styles/ # Global CSS and tokens
mock/ # Fixtures for tests
Add product UI under src/features/<name>/. Keep components/ generic. A
screen that is one feature lives in that feature and is mounted from
app/SolidApp.tsx. Add pages/ only when a route composes several features
and has no logic of its own.
What goes where
| Path | Holds |
|---|---|
features/<name>/ | Screens, the small components they are built from, and hooks only that feature uses |
components/layout/ | Chrome every screen shares: frame, top bar, trays |
components/ui/ | Primitives with no product meaning |
app/ | The router host and hooks that belong to the window, not to one feature |
state/ | Client stores shared across features |
api/ | Typed HTTP. No feature UI |
infra/ | OS calls through @tauri-apps/api |
A hook that only one feature calls lives next to that feature
(features/chat/useAgentEvents.ts, features/docs/useWorkspaceDocs.ts). A
store that two features read stays in state/.
Split a screen into smaller components inside its feature directory. Do not
park those pieces in components/ unless a second feature uses them with no
feature-specific behavior.
Current features
| Feature | Role |
|---|---|
chat | Transcript, composer, tray, and the agent event hook |
docs | Workspace documentation viewer. Disabled in M11 (showSurface('docsViewer')); docLink.ts still resolves chat markdown links |
review | Session diff review. Disabled in M11 (showSurface('reviewScreen')); the inline file peek from a tool card still uses its dialog and highlighter |
settings | Settings routes |
workspaces | Workspace list |
Removing a surface
src/app/surfaces.ts is the one switch. A surface that is off keeps its route out
of chatRoutePaths, its components out of ChatChrome, and its data calls
unmade, while the modules, stores, and tests stay in the tree. showSurface is a
plain function so a render site, a route list, and an event handler all read the
same answer. topBarShell is a layout flag only: it chooses the chrome, never a
backend call.
Visual style
Robi’s desktop UI is a dark, two-column coding-agent shell. Color, density, and layout follow Claude’s desktop Code view; product behavior (tool cards, approvals, modes) stays Robi’s.
This page is the design doc for the look: tokens, shell layout, and the visual treatment of chat chrome. Interaction details — the draft session, activity line, and composer lock — live in chat-ui.md. Streaming caret and tool-card expand defaults are still open there.
What this doc does not cover
| Topic | Where it belongs |
|---|---|
| Streaming render, scroll-lock, message list mechanics, tool-card state | docs/src/design/shell/chat-ui.md (M2) |
| IPC, event ordering, window lifecycle | docs/src/design/core/architecture.md (M2) |
| Approval policy and grant UX copy | docs/src/design/workspace/permissions.md (M3) |
| Mode names and transitions | docs/src/design/core/agent-modes.md (M5) |
| Full review window (diff views, hunk nav, inline comments) | docs/src/design/review/code-review.md (M6) |
Problem
M2 ships a chat window before Robi has a visual identity. Without a written palette and shell layout, every screen invents its own grays, and the UI drifts toward either a generic dark dashboard or a light marketing shell.
Claude’s desktop Code view already solves the composition we need: a narrow session rail, a quiet transcript on near-black, a user bubble slightly lighter than the canvas, warm muted ink, and a bottom composer with model controls. Steal that surface language. Do not steal Claude product features that Robi has not decided to ship.
Decision
Adopt Claude Code-view color and shell layout as Robi’s default (and only) theme for M2. Dark-only. No light mode until product schedules one.
| Steal | Defer | Reject for now |
|---|---|---|
| Near-black canvas + charcoal sidebar/composer surfaces | Home / Code product toggle | Marketing light theme |
| User bubble slightly lighter than the canvas | Routines / Scheduled lists | Card-heavy dashboard chrome |
| Warm off-white body ink (not pure white) | Voice / mic control | Purple accent stacks |
| Soft radii on bubbles, composer, sidebar pills | Pinned section as a first-class store | Floating badges over the transcript |
| Session rail + main transcript + bottom composer | Breadcrumb as editable project switcher | Multi-column agent canvases (Devin-style) |
| Muted activity lines between turns, and a context ring as a meter |
Rejected alternatives:
- Light-first / dual theme. The reference is dark; a light theme doubles token work before any real chat UI exists.
- Sync with Synchroni instrument tokens. Different product; do not import hairline-rule / health-axis language here.
- Terminal-green / CRT aesthetic. Reads as novelty, not as a durable shell.
Shell layout
One composition: a single bar, then the transcript across the whole window.
┌──────────────────────────────────────────────────────────┐
│ ‹ › Workspace ▾ Session title ▾ + ⚙ ⋯ │
├──────────────────────────────────────────────────────────┤
│ │
│ Transcript │
│ user bubble │
│ assistant prose + inline code │
│ muted activity lines │
│ (tool cards — see chat-ui) │
│ │
├──────────────────────────────────────────────────────────┤
│ Composer + mode / model / effort row │
└──────────────────────────────────────────────────────────┘
The top row is the window bar. It is the same height on every page, and it is the
drag region. On the chat shell the whole row is --bg-canvas; on Settings the
split follows the settings rail; on Workspaces the whole row is --bg-canvas.
macOS window buttons sit in that row, inset from the window corner, so the bar’s
leading edge starts after them: --traffic-light-inset is 84px on macOS and
0px elsewhere. The desktop window uses an overlay title bar so those buttons
draw on the app fill instead of a separate system bar.
There is no permanent left column (streamlining S6). The legacy two-column
layout — a --bg-sidebar column with the chat header in that same row — is still
in the tree behind showSurface('topBarShell') in src/app/surfaces.ts, and the
references to --sidebar-width in this page describe it.
| Region | Role | Content |
|---|---|---|
| Window bar | Drag region and navigation | macOS window controls, inset from the corner. Then the workspace dropdown, back and forward, and the session title — which is also the Recents menu. At the trailing edge: New chat, Settings, and an overflow holding MCP marks and the API health row |
| Transcript | The work | User bubbles, assistant text, activity lines, tool-call cards |
| Composer | Primary input | Multiline field, send, mode, model, effort; stop when a turn is running |
Nothing but the text column is capped. After the first message, the composer stays at the
bottom of the main column and the transcript scrolls underneath it. The
scrollbar runs to the bottom of that column. A scrim over the bottom of the
transcript fades into --bg-canvas and is solid halfway down the composer,
so the rows behind the lower half are gone. The fade reaches 1rem above
the dock. Padding under the last row is the dock height plus --space-4, so
the last row sits just above the composer when the list is scrolled to the end. Before the first
message, the composer sits under the greeting in the center of the column.
Bar rules
- One row at the default width. The title truncates before any control does. The primary actions (workspace, title/Recents, New chat, Settings) stay visible; MCP marks and the API health row fold into one overflow menu, and that button is absent while there is nothing to show.
- The workspace name stays visible at every width. The top bar names the workspace beside its folder icon, so the user knows which one is open without opening the menu. Below 1040 px the name shortens and truncates rather than disappearing.
- The overflow is the only home for secondary chrome. It is a Kobalte dropdown, styled with these tokens.
Color tokens
Values sampled from Claude’s desktop Code view and rounded to a small token set.
Implement as CSS custom properties on :root (and later a single theme file).
Do not sprinkle raw hex in components.
| Token | Value | Use |
|---|---|---|
--bg-canvas | #0b0b0b | Main transcript background |
--bg-sidebar | #1f1f1e | Sidebar fill. The legacy layout only |
--bg-surface | #1f1f1e | Composer field, elevated chips |
--bg-surface-hover | #282827 | Row / control hover |
--bg-surface-active | #333333 | Selected session, pressed toggle |
--bg-user | #181817 | User message bubble, a dark gray lighter than --bg-canvas |
--ink | #c3c2b8 | Primary body text (warm, not pure white) |
--ink-strong | #ecece8 | Titles, emphasis |
--ink-bright | #f7f6f2 | Assistant prose |
--ink-muted | #8a8983 | Labels, timestamps, activity lines |
--ink-faint | #5c5c57 | Placeholders, disabled |
--accent | #55a2fb | Focus ring, send/active status, links |
--accent-muted | #3a6fa8 | Accent on dark fills (icons in quiet states) |
--code-bg | #1a1a19 | Inline code chip background |
--code-ink | #d4d3cb | Inline code text |
--rule | #2a2a28 | Hairline separators (use sparingly) |
--danger | #e56767 | Destructive / failed tool |
--success | #6fbf7a | Completed tool / applied edit |
--warn | #e8c547 | Yellow text for the review Reject with reason menu item and its Reject and send button |
--mode-ask | #6fbf7a | Ask mode in the composer |
--mode-plan | #e39a3c | Plan mode, and the plan Build and View Plan buttons |
--attention | #4ec9d6 | A tool call waiting on a decision: the card’s left rail. Cyan rather than a mode’s ink, because a message’s rail is its mode’s colour: a plan-mode turn is orange from the user band to the composer, so “this needs you” has to be its own value or the question is the least visible thing in the frame |
--diff-add | #5db27b | +N line counts in edit summaries |
--diff-del | #c46b6b | -N line counts in edit summaries |
--find-hit | #6b5416 | Find-in-document match background |
--find-hit-current | #e39a3c | Active find-in-document match |
--bg-row | #303030 | File rows inside the edit-summary widget |
color-scheme: dark on the document. Form controls follow the dark scheme.
Scrollbar thumbs are --bg-surface-active, thin, with a transparent track.
Accent discipline
--accent is for state and focus, not decoration. Do not tint large panels
blue. User messages stay a dark gray (--bg-user); assistant messages stay unbubbled on
--bg-canvas.
A user message’s left rail is its mode’s ink — --accent for agent, --mode-ask
for ask, --mode-plan for plan — and the composer’s rail matches what it will send.
Nothing else wears a mode colour: a mode is what a person asked for, so it stops at
what they typed. Assistant prose is railed too, for the aligned column, but its rail is
--ink-faint in every mode; the reply is the model’s output. --attention is
deliberately outside the mode set.
Typography
| Role | Stack | Notes |
|---|---|---|
| UI / body | ui-sans-serif, system-ui, sans-serif | Match the OS; no Inter/Roboto package |
| Code / paths | ui-monospace, SFMono-Regular, Menlo, monospace | Inline chips and fenced blocks |
| Body size | ~14–15px | Comfortable reading; avoid 12px transcript |
| Activity line | ~12–13px, --ink-muted | Quieter than assistant prose |
| Sidebar item | ~13–14px | Truncate with ellipsis; full title on hover |
| Empty greeting | ~32px, UI sans, weight 560 | Same type as the workspaces page title |
Line height ~1.5 for assistant prose. The empty-chat greeting uses the same sans title as the workspaces page. The rest of the shell stays on the UI sans.
Shape and spacing
| Token | Value | Use |
|---|---|---|
--radius-sm | 6px | Inline code chips, small buttons |
--radius-md | 10px | Session pills, toggles |
--radius-lg | 14px | User bubble, composer |
--radius-xl | 16px | Large floating surfaces. The sidebar does not use it |
--space-1 … --space-6 | 4 / 8 / 12 / 16 / 24 / 32 px | Padding scale |
The reference uses generous dark space, not dense packing. Prefer padding
over borders. When a border is needed, use --rule at 1px — never a heavy
outline stack.
Visual elements
These are the chrome pieces the style owns. Behavior of each is specified in
chat-ui.md; this page locks how they look.
User message
- Bubble on
--bg-user, aligned to the chat column’s right edge. It is only as wide as its text, and never wider than 85% of the column. Text is--ink-brightso it matches the brightness of assistant prose. - Large radius (
--radius-lg). - The chat column itself caps at
--chat-column-width(48rem) and stays centered in the main pane when the window is wider. User bubbles, assistant prose, and the composer share that bound.
Assistant message
- No bubble. Prose sits on
--bg-canvasin--ink-bright. - Inline code:
--code-bgchip,--radius-sm, mono stack. - Fenced code blocks: same surface family, slightly taller padding; syntax
highlighting comes later and must stay readable on
#0b0b0b.
Mermaid diagrams
- A fenced
mermaidblock renders on--bg-canvas, the same ground as the transcript, with--radius-mdand--space-3padding. The diagram sits centered in it. The ground is the SVG’s ownbackground/edgeLabelBackgroundvalue, so the diagram’s--bg-surfacenodes and--code-bgcontainers step up from it. On--code-bgthe containers were the same color as the block and the nodes barely differed, so the diagram read as a flat patch. - The surface scrolls horizontally and caps at
max-width: 100%, so a diagram wider than the chat column scrolls like a wide code block instead of stretching the column. - The SVG uses the same tokens as the shell, not mermaid’s default palette:
node fill
--bg-surface, borders and edges--rule, node text--ink-bright, container fill--code-bg, on the--bg-canvasbackground. Sequence diagrams use the same tokens: actor boxes--bg-surfaceon--ruleborders, lifelines and messages--ruleand--ink, notes on--code-bg. State composites (a state that contains states) fill with--code-bgon both the title and the body. The diagram uses mermaid’s classic look, which is a flat fill. Mermaid’s default neo look adds a light gray drop shadow, and on this ground that shadow reads as a second fill where a box sits inside a box. - Diagram text is the UI sans stack at 14px, a little smaller than body copy, matching the fenced code block it replaces.
- While the render is in flight, and when mermaid cannot parse the source, the block is an ordinary fenced code block, not a placeholder surface. Mermaid’s error diagram is suppressed; the failure is logged.
Activity lines
Muted one-liners between turns (e.g. “Read 3 files…”). Icon + --ink-muted
text. Not cards. Tool results that need inspection become tool cards
(chat-ui.md); activity lines are the collapsed summary strip.
Recents menu
The session title in the window bar is the trigger: a quiet line with a chevron,
--ink at 13px, a --bg-surface-hover fill on hover and while open, and
--ink-strong then. Its accessible name is <title> — recents.
- The panel is
--bg-canvason a 1px--ink-faintedge,--radius-md, and the same shadow the workspace menu uses. It is a menu, not a panel: no header bar, no footer. - First row is the filter field,
--bg-surface-hoverwith a--bg-surface-activeborder, and focus moves that border to--ink-faint. It takes focus when the menu opens, and the query clears when the menu closes. - Rows are 13px,
--bg-surface-hoverunder the pointer or the keyboard, and--bg-surface-activefor the open session. The title truncates with an ellipsis and carries the full text on hover. - Marks sit at the start of a row and match the transcript’s: a running agent is
a 12px spinning ring,
--ink-faintwith an--inkleading edge; an approval is an 8px--accentdot. Reduced motion leaves the ring still. - Rename (✎) and Delete (×) appear at the trailing edge of a row on hover or focus, and open the same dialogs the sidebar used. Their space is reserved whether or not they show, so revealing them never changes a row’s height or shifts the list.
- The list caps at 20 rows. A line under it says how many are hidden and asks the
user to type:
N more sessions — type to narrow the list.
Composer
- Tall rounded field on
--bg-surface, placeholder--ink-faint. - Send control on the right inside the field (arrow / return affordance). While a turn is running, that control is a filled circle with a rounded square cut out of it, in the same slot.
- Below the field: mode on the left, and model, effort, and the context meter on the right. Controls are quiet
text + a Lucide
ChevronDown, not colored pills. The meter is a 14px ring. The track is--ink-faintand the filled share is--ink-muted. Clicking it opens a popover. No attach control in the shell mock. - An empty chat lifts that same field into one bordered card under the greeting. The model row sits inside the card, without the context meter. The greeting is the workspaces title type, with no mark beside it.
Settings
A full-page shell, not a dialog. Left rail: back to the chat, then the section
list. Right pane: a title, then one or more sections, in the same centered
column as the chat (--chat-column-width). Each section is a muted
heading and a bordered card of rows. General starts with Display: one row
with the UI scale stepper (−, the percentage, +, and Reset) and the Cmd/Ctrl +,
-, and 0 shortcuts beside it. The level scales the whole window and is
remembered per device. Then Model Defaults
(one row per Global, Agent, Ask, and Plan: mode name, model menu on the left,
effort menu on the same row). An unset mode shows Global Default
in those menus, and that item clears the override. Global effort stays a
segmented control. OpenCode Go and Anthropic are each their own card:
an enabled switch, on by default, then that provider’s API key. OpenCode Go also
has the optional base URL. A switch that is off disables that card’s key field. Permissions is a single card: switches for
web search approval and web fetch approval, both on by default. Below model
defaults, General has the workspace, Files (newline-separated globs for paths that open outside the viewer, and an optional command such as zed {file_path}:{line}; an empty command uses the system app; a command that fails shows its error on the edit card; everything else opens in the file viewer), a language-server switch, then max
iterations and subagent max iterations, a subagent timeout, and a tool timeout.
Audit log
lists the last 250 API calls in a table (time, method, path, status, duration), 50 per page. Clicking a row shows that response body. Errors from this run of the app follow, newest first. Health checks are omitted. It is not saved. Use the same tokens;
active nav is --bg-surface-active, the selected effort pill may use --accent.
Text fields, including secrets, sit one step above the card (--bg-surface-hover)
with a --bg-surface-active border. Focus moves that border to --ink-faint.
They are not canvas wells.
Header
One bar holds the navigation. From the leading edge: back and forward, then the
workspace dropdown, then the session title centred over the transcript — and that
title is the Recents menu’s trigger. Back and forward walk the same history as
the side mouse buttons: each chat and the draft. A button is quiet when that
direction has no entry. At the trailing edge sit New chat (SquarePen) and
Settings, then the overflow if anything lives in it: one row per MCP
server, and a row for a failing API health check. The index pill used to sit
here while the workspace index was not ready; S3 removed it with the index.
The transcript starts on the next row. Every icon-only control carries an
accessible name and a title, and tab order runs leading, centre, trailing. The
first time a session is opened, the main column shows a spinner and “Loading
conversation” until that transcript arrives. Opening it again uses the copy
already in memory and does not show that spinner.
The workspace dropdown sits after the history pair. The workspace menu is a Kobalte dropdown, and the rename, delete, and clear-composer dialogs are Kobalte dialogs. Both are styled with these tokens. The active workspace uses an open folder. The others use a closed folder. The closed control is an inline chip — icon, name, chevron — with no border until hover. The open list is the darker canvas color, with a stronger edge. The chevron opens the list of workspaces, most recently selected first. The menu shows at most eight workspaces, and one Manage workspaces… item under a rule links to the Workspaces page. A workspace with no recorded selection stays in the order the API returned it. Adding a workspace happens on that page, not in this menu.
Overflow menu
One row per MCP server: the server’s icon, then name · status · N tools on one
line, where the status is connected, starting, failed, or disconnected
and the tool count appears only when connected. Each row links to MCP settings.
A failing API health check adds a line under them in --danger. The rows match
the Servers list on the MCP settings page, in the same order.
Workspaces page
A full-page list at /workspaces, in the same role as a projects home. The
page content sits in the same centered column as the chat (--chat-column-width). The
title sits on the left of that column. Search and New workspace sit on the right. With no workspaces, the column center holds a short prompt
and the same create action. With some, the cards stack in that column, each as
wide as the column. The name and Open / Remove share the top line. The path sits
below on a darker strip in mono. Opening a card selects it and returns to the
chat. The chat shell sends you here when the list is empty. Chat returns
when one is already selected.
Edited-file strip — removed
The line above the composer that read N files edited with a Review button is
gone with the review screen (streamlining S2). The implementation
(src/features/chat/EditReviewStrip.tsx) stays behind
showSurface('reviewScreen'). Reviewing a change means git diff
(Reviewing changes with git).
Do not paste diffs into the transcript instead. The inline file peek from a tool card is the one in-app diff, and it shows a single file on demand.
Icons
Interface icons come from Lucide (lucide-react). Pick an existing Lucide icon instead of drawing a new SVG. Size and stroke stay with the control: sidebar nav is 18px at stroke 1.75, and smaller chrome is 12–14px. Color is currentColor, so the icon inherits the text token. The context meter is a usage ring, and Mermaid output is a diagram. Neither is an icon.
CSS architecture (when implementing)
- Put tokens in
src/styles/tokens.css(or:rootinglobal.cssuntil a split is needed). - One CSS Module per component / region (
Sidebar,Transcript,Composer). - Do not add Tailwind or a component kit. Tokens + modules only. Icons are Lucide, not a second icon set.
- Delete a module when its component goes away.
Open decisions
| # | Decision | Notes |
|---|---|---|
| V1 | Sidebar flush to the window edge vs. inset floating rail | Moot: there is no sidebar. The bar spans the window |
| V2 | Sidebar width and whether it is resizable | Only the legacy layout has one (~260px, --sidebar-width) |
| V3 | Whether assistant ever gets a bubble | Default no; revisit only if contrast testing fails |
| V4 | Brand mark in the sidebar | There is no sidebar and no mark; the workspace dropdown leads the bar |
| V5 | File-row chevron: expand inline snippet vs. jump to that file in review | The inline file peek is the destination. No surface lists edited files |
| V6 | Aggregate counts: lines changed vs. files touched | Reference uses line counts (+123 -42); keep that unless editing tools report only file-level stats |
Failure modes
- Pure white body text on
#0b0b0bwill look harsher than the reference; stick to--ink. - Blue-tinted panels break the quiet canvas; keep
--accentfor controls. - Light mode sneak-in via
color-scheme: lightor system form defaults — set dark explicitly. - Porting Synchroni / shadcn patterns will fight this palette; do not.
Relationship to later docs
chat-ui.md assumes these tokens and regions. code-review.md
describes the removed review screen. When a component needs a new color, add a
token here first — do not invent a one-off hex in the module. Syntax colors on a
diff line come from the highlighter theme, not from a new token.
Chat UI
This page is how the shell shows a chat with no tools. It covers the draft session, the transcript the window stores, the activity line, and the composer lock. Look and tokens stay in visual-style.md. Event delivery stays in events-sse.md.
What this page does not cover
| Topic | Where it belongs |
|---|---|
Streaming caret and painting message_delta text | Later on this page. The assistant row is stored only when the model stream finishes, so this cut does not paint tokens |
| Syntax highlighting, copy, retry, edit-and-resend | Later on this page. Assistant text is Markdown; highlighting is not |
| Mermaid diagrams | This page. A fenced mermaid block renders as a diagram in assistant text, on a plan page, and in the markdown file preview |
| Grant and session-allow editing | docs/src/design/workspace/permissions.md (M3) |
| Creating the session row | persistence.md. The shell delays that call |
/id skill mentions and the Using row | skills.md |
| A shell card showing the uncompressed command output | shell-output.md. The transcript body the model sees may be the compressed view |
| An MCP card showing the bounded server text | mcp-output.md. The transcript body the model sees may be the compressed view |
Draft session
New session does not POST /chat_sessions. It selects a client-only draft:
no database row, no Recents row, bar title “New chat”. Choosing it
again while it is already open does nothing. While that draft is selected,
New chat is the open state.
The first send creates the session, then POST /chat_sessions/{id}/messages
with { "instruction" }. On 202 the shell selects that session, marks it
thinking, and keeps a local echo of the user text until a fetched user message
with that text is new in the list. If create succeeds and submit fails, the
session stays and the draft text stays in the composer so the retry is only
the message post.
App load lists sessions and selects the most recent. An empty list opens the draft.
Each chat has its own route. A session is #/sessions/{id}; the draft is
the index route. Choosing a session pushes its route, so the window’s back and
forward controls — and the side mouse buttons — walk the chats in the order
they were opened. A forward entry is dropped once a new chat is pushed. Back or
forward selects whatever session the route names. App load opens the most
recent session on its own route; the draft route stays the draft. The route is
restored on reload, so a reload returns to the same chat.
The window bar shows “New chat” on the draft and the session title once a row exists. MCP server marks sit on the right of that line in both cases. To their right, a mark appears when GET /api/v1/health fails or does not answer within 3 seconds. Hovering the mark says whether the check timed out, which HTTP status came back, or the error message. The shell checks every 5 seconds and removes the mark after a successful check. The first click on a session that has not been opened in this window shows a spinner and “Loading conversation” until its transcript loads. A later click on the same session does not. Until a prompt is submitted, a greeting
sits in the center — Good morning, Good afternoon, or Good evening,
from the local hour — with the composer in a card under it. The first echo or
stored message returns the title, the transcript, and the bottom composer.
The pencil on a session opens a rename dialog with the stored title. The dialog
is a Radix dialog. An unset title starts the field empty. Save sends PATCH
with the trimmed title. Cancel and Escape leave the title as it is. An empty
title is refused in the dialog and is not sent.
The × on a session opens a delete confirm dialog, also a Radix dialog, in
place of a native window.confirm. It names the session and says the delete
cannot be undone. When that session’s agent is running it adds a muted line,
A running turn will be stopped. Delete sends DELETE; the server stops
the running actor first, so the request can take a moment. While that request
is in flight, Delete carries a spinner and both buttons are disabled, and
Escape and an outside click do not close the dialog. A failure shows the error
line and keeps the dialog open. Success closes it and the session leaves the
list.
Transcript
Zustand holds the session list, the active id, messages keyed by session, and
a per-session phase: idle, thinking, or responding.
The list keeps the latest row in view while the reader is at the bottom.
Scrolling up, including a trackpad or wheel gesture upward, releases that
follow so a message update does not pull the view back down. A tool request
or other growth at the end does not release it: the view moves to the new
bottom, including when that block is taller than the screen. Returning to
the bottom resumes it. Switching chats starts at the bottom again. A repeated
message_delta that does not change the phase does not render the list again.
The transcript is HTTP, not the event stream.
| Trigger | Request |
|---|---|
| Select a session, or the event stream opens | GET /chat_sessions and GET /chat_sessions/{id}/messages. The two transcript reads share one request while one is in flight |
message_added, message_updated, tool_call_updated | GET /chat_sessions/{id}/messages/{message_id}, then upsert that row. One GET is in flight per message, and a newer frame schedules one more. A list reload keeps a row upserted after the list started |
turn_finished | The session and the message list again |
robi.session.v1.created, robi.session.v1.updated | That session again, unless the frame already carried the new title. A fetch that started earlier keeps a local title and a session inserted after it started. The message list is left as it is |
robi.session.v1.deleted | Drop that session from the list |
robi.app.v1.error | Record message and show it at the top of the shell until it is dismissed |
Phase is thinking or responding, and no frame for that session has arrived for 2 seconds | The session and the message list again |
message_delta does not change message text. kind: "reasoning" sets
Thinking. kind: "text" sets Responding. Other delta kinds are
ignored. turn_started sets Thinking. turn_finished sets idle, then
refetches the session and the message list without taking the phase from
has_pending_agent. The actor clears that flag after the event. A
turn_started during the refetch stays Thinking. A reload while a turn
is already running still restores the phase from has_pending_agent. A failed turn draws its message in --danger on a surface card under the last row of
that session’s transcript. It stays until the next instruction is sent for that
session. Because the message is stored per session, opening a chat whose turn failed
later shows it. The message, and every other shell error, is also kept in memory and
listed under Settings → Audit log until Robi restarts. That page also lists the last 250 API calls, newest first, 50 per page, with method, OpenAPI path, status, and duration. Clicking a row shows that response body. GET /api/v1/health is left out. An API response outside 2xx, and a request that throws, is written to the error list too,
without a second notice. A fetch this page aborted, including the 10-second
timeout, is not. Several can be open at once. Each one sits under the window title and names
the chat when it has one. Dismiss hides it. The audit log keeps it. The 2-second refetch is what paints a stored turn when the frame that
would have loaded it was dropped. A frame for the session on screen resets that wait. A frame for another session does not.
Opening the stream refetches even on the first connect. A frame published before the socket existed is recovered from the store. Reconnect does not replay deltas.
Tool calls
An assistant message renders its text as Markdown, then one row per tool
call. Headings, lists, tables, links, and fenced code are elements. Syntax
highlighting is not applied. A tool message is not shown again; the result
lives on the call. User text stays plain. The bottom of a finished turn is one row: Worked for Ns on the left, and a copy
icon on the right when that turn has assistant text. Hovering it says Copy markdown.
After a click the tooltip says Copied. The button copies that message’s
Markdown as stored. A finished turn ends with a muted line, Worked for
Ns, measured from the user message to the last message in that turn.
A turn that is still running, or waiting on approval, does not show it.
Tool rows from later iterations of the same turn sit in that same stack, with
no extra gap between quiet rows. An edit card has a little space above and
below it. A shell card has a little space above and below it, so two panels do not touch.
It opens itself while its command runs, and collapses when the command finishes,
so a finished call defaults to closed. That auto-open is not a user choice and is
not remembered. A click is: opening or closing a card sticks across transcript
refreshes. A closed shell card is still a bordered panel: the row, then the
command on one truncated line, then the last four lines of output, which is what
a command’s failure is usually about. It does not scroll. An open shell card
shows the whole command and output in a body that scrolls, eight lines tall. A finished read is a quiet line: an icon, a verb (Read, Grepped, Found,
Listed), and the path or pattern. A read_file call that names offset and
limit adds the inclusive window after the path, in --ink-faint, as L240-299.
limit alone is L1-N. offset alone is L240. A call that reads the whole file
shows no window. A finished write_file, edit_file, or
delete_file is a bordered card: the path the tool was called with
(scratch/test.md, ../gopi/test.md, /tmp/test.md), the + / − counts beside
it, and 4 diff lines starting at the first added or removed line. Context above that change stays out of the closed card. Added and removed lines carry a left accent in
--diff-add or --diff-del. Clicking the + / − counts while the card is closed opens the rest, at most 24
lines, then N more lines when the change is longer. Clicking the name follows Open externally in General (file_open_patterns), whether the card is open or closed. A workspace-relative path that matches one line opens outside the viewer. Open command (file_open_command), when set, is POST /api/v1/workspaces/{id}/open with the first changed line. The request waits up to 10 seconds. A program that fails to start, or exits non-zero inside that window, shows the API error on the card. An empty command opens in the system app, in the desktop window, through GET /api/v1/workspaces/{id}/path. Any other path opens in the file viewer on Current. Diff and Previous are there when this session still has a change for that path. A path with no change is the file on disk, from GET /api/v1/workspaces/{id}/file, and those two controls stay off. A running call shows a spinner.
A failed call shows the verb and target in --danger. Clicking a row that has a result or an error opens
the body: numbered file text, match lines, paths, or the error. The row stays
closed until that click. Every opened body is a bordered panel, the same shape as a shell card: the header sits
on the panel, and a rule divides it from the body — numbered file text, match lines, paths, or the error.
There is no plan card and no todo rail. Since S9 a plan is a file the agent
writes with the shell — .robi/plans/<name>/PLAN.md plus TODO.md — so a plan
turn streams ordinary shell cards and the checklist is read in the user’s
editor. See tools.md.
A delegate call is one collapsed row. Explore reads Exploring, then the
counts it has so far: unique read_file paths as files, and grep or find
calls as searches, as in Exploring 9 files, 5 searches. A count of zero is
left off. The line uses --ink-muted. General reads General, and shows the
running spinner while the call is running. Clicking the row opens the panel:
the description and one row per child tool. General also shows a tool-call
count. A spinner sits on a child step that is still running. A denied or failed step
uses --danger. The answer the parent model received is behind an Answer
control inside that panel and stays closed until that click. Closing the row
hides the panel. The rows update when tool_call_updated refetches the
assistant message. Those refetches collapse to one in flight and one trailing
GET. With the review screen off there is no strip to refresh; the Recents menu
reads the phase map, and turn_finished clears the running mark there.
A call that is still pending approval and not_started, while the session
phase is idle, is the approval bar. It shows the same verb and target, then
Reject and Approve. A pending web_search keeps Search and the
web on that line, and puts the full query under it so a long query wraps
instead of clipping. A pending web_fetch keeps Fetch and the host on
that line, and puts the full URL under it the same way. A pending MCP call
keeps Call and server / tool on that line, puts the arguments under it,
and adds Allow for this session beside Approve. The labels and the
session list are in mcp.md. Each approval bar has --space-2 under it, the same
space as an edit or shell card, so parallel requests do not touch. A pending edit_file uses the same diff card as a
finished edit, built from old_string and new_string: that same path, the counts, the
first 4 lines, and the same 24-line cap. Reject and Approve sit on that
card. Approve posts approve. It uses --accent with dark text. Reject posts
reject. Either button lightens on hover. The phase
becomes Thinking until the resumed turn reports back. If that post fails,
the shell loads the assistant message again. A call that is still pending
and not_started keeps the bar and returns the phase to idle. A call that is
no longer waiting stays as the fetched row and keeps the thinking phase. A call that ran
without asking stays a result row: pending approval with succeeded
execution is not a prompt.
When the desktop window is not in front, that pause also posts one OS
notification: Robi needs approval, and the verb and target of the first
waiting call. A click focuses the window and selects the session. The bar is
still where the call is approved or rejected. The next turn_started clears
that notice so a later pause can post again. A failed turn posts Robi
with the failure message the same way, and the in-app notice keeps that
message either way. The browser shell does not post one.
Mermaid diagrams
A fenced ```mermaid block renders as a diagram, not as source, everywhere
assistant Markdown is shown: an assistant message in the transcript, a plan
page body, and the markdown file preview in the review file inspector. One
renderer, AssistantMarkdown, backs all three, so the fence behaves
identically in each. The file inspector’s Diff, Current, and Previous views
still show the raw file lines.
The diagram is drawn client-side, and the mermaid package is dynamically
imported, so it loads only the first time a fence renders and never sits in
the main bundle. While the render is in flight the fence shows as an ordinary
code block; when the SVG is ready it replaces the source in a centered,
horizontally scrollable surface (see
visual-style.md). Mermaid writes
width="100%" and no height. WebKit then paints the SVG at its 150px default
and clips the rest, which cuts a sequence diagram off under the participant
boxes. The renderer copies the viewBox width and height onto the root so the
diagram keeps its aspect ratio, and the stylesheet still shrinks it to the
column. A source mermaid cannot
parse keeps the code fence. Mermaid’s own error diagram is suppressed, so a
bad diagram does not paint a wide error into the page; the failure is logged.
The theme is the same dark token set as the shell, mapped to mermaid’s
themeVariables, so diagrams do not fall back to its default palette. The
look is classic. Mermaid’s default neo look adds a light gray drop shadow
that reads as a second fill on the dark shell, worst when a box contains a box.
securityLevel stays strict: the source is model output, so mermaid keeps
its sanitization.
Both fenced flowchart blocks and sequenceDiagram blocks use that theme. A
sequence diagram reads its own variable groups — actor* for the participant
boxes and lifelines, signal* for messages, note* for notes, and labelBox*
/ activation* for the loop/alt frames and the bars inside them — so those are
set explicitly rather than left to mermaid’s light defaults. A semicolon ends
a sequence statement, so a semicolon inside a note or message (for example
unknown;<br/>) makes the rest of the line fail to parse and the fence stay
on screen as source. A semicolon that begins the next statement is kept. One
that sits in the prose is drawn as a fullwidth semicolon, which is not a
statement break. An actor id that is a sequence keyword is quoted before
render. Loop is one of those: the lexer matches loop without regard to
case, so API->>Loop is read as the start of a loop and the diagram stays
source. The alias after as and the message after : are unchanged.
Diagram text is the shell’s UI sans at 14px, matching the fenced code block it
replaces. The font comes from the top-level fontFamily key rather than a
theme variable: sequence diagrams read their own actorFontFamily /
noteFontFamily / messageFontFamily, and mermaid fills those in from the
top-level value.
Activity and the composer
While the phase is not idle, the transcript shows a muted line, Thinking
or Responding, then for Ns counted from the latest message, with
dots that step ., .., ... beside it. The count waits until one second
has passed. Reduced motion shows ... and does not step. That line is the
busy signal.
The ring at the right of that row is the context meter. It is a button.
The arc is the share of the model’s context window the next request would
use. The latest assistant usage.input is the prompt size through the
request that reported it. Each report is cumulative, so the meter does not
sum them. Characters of that message, every later message, the unstored
echo, and the composer draft, divided by four, estimate what the provider
has not counted yet. The track is --ink-faint and the arc is --ink-muted.
An empty chat, or a turn that has not reported usage, leaves
the arc empty. A model with no advertised window leaves it empty too.
Clicking the ring opens a popover: used against the window and the percent,
the last turn’s input, output, and cached tokens, and the uncounted
estimate when it is not zero. Compact in that popover runs the manual
rewrite in context-management.md. It is
disabled while a turn runs or a compact is in flight; while the request is out
the label reads Compacting…. Cached is omitted when it is zero. The ring
holds its fill while a turn runs.
A compaction summary is a user message the API flags compaction: true. The
transcript does not draw it as a user bubble; it paints a Context compacted
divider — a hairline rule with the label between it — on that row instead. The
summary text is not shown. The rows it replaced are gone, so a client that
receives robi.agent.v1.transcript_compacted refetches the message list.
Unsent text stays with the chat it was typed in. Switching sessions, or moving between the greeting card and the bottom field, restores that chat’s draft. A successful send clears it. The new-chat draft is its own slot until the first send creates a row.
Cmd+Shift+K on a Mac, Ctrl+Shift+K elsewhere, asks before it empties the
field. The confirm says Clear composer, names what goes — the text, plus the
attachments when there are any — and says it cannot be undone. Cancel,
Escape, and an outside click leave the text and the attachments alone.
Clear empties the field, that chat’s draft, and every attachment, then puts
the caret back in the field. A composer with no text and no attachments ignores
the chord. The listener sits on the mounted composer, so the shortcut does
nothing while no chat is on screen, and a chord pressed inside an open dialog
belongs to that dialog.
The textarea stays editable while a turn runs and while a send is in flight.
Enter does not submit during session load, while a stop has not returned, or
while a send has not returned. Until that send returns, the send slot is a
spinner when the phase is idle. After it returns and the phase is not
idle, the control is Stop while the field is empty, and the return mark
when there is text or an attachment to send. Sending then posts the
instruction. The runtime cancels the in-flight turn and runs this one next.
A transcript read already in flight does not clear that phase: the read
started before the local running mark. Stop is a filled circle with a
rounded square cut out, in the same slot as the return mark. Stop posts
POST /chat_sessions/{id}/stop and stays in that slot until the call returns,
which is after the actor has exited.
Another session can still be running; the lock follows the session on screen.
Selecting it again refetches, and has_pending_agent restores the phase when
the actor is still running.
Recents lists the 20 most recently used sessions behind the title in the bar, with a filter field above them. A search narrows the list before the cap applies, and a line under it says how many rows are hidden. Switching workspace clears the filter.
A session whose agent is still running shows a grayscale spinner on its row
in the Recents menu. That is the phase when it is not idle, has_pending_agent
when the list was loaded with the actor already running, or turn_display of
pending. Leaving that chat does not drop the spinner. turn_finished for
that session still arrives on the open stream and clears the running mark,
without refetching its transcript. turn_started sets the mark the same way.
A robi.session.v1.updated frame that carries turn_display applies that
value to the row, then refetches the session. The actor publishes that frame
after it has gone idle, so the refetch does not report the actor as running.
awaiting_approval shows a filled --accent dot in the spinner’s slot, with
an accessible name that the session is waiting on approval. A fetch that
started before that frame does not put the spinner back. failed is returned
and not painted. Message frames for a session that is not on screen
are not applied, so the row does not update on each token. A session refetch
replaces the row when the title, mode, model, grants, running flag, or
turn_display change. Reduced motion keeps the ring still.
Mode and the model menu are quiet dropdowns on the left of that row, and
inside the welcome card. The context meter sits on the right of an open
session’s row. The welcome card does not show it. Mode is ask,
plan, or agent. The selected mode, and each row in its menu, uses that
mode’s color: ask is --mode-ask, plan is --mode-plan, and agent stays
--ink-muted. The model menu’s label is the model and effort in effect,
such as Grok 4.7 Low. An OpenCode Go model is prefixed OCG - , such as
OCG - Grok 4.7 Low, so it stays distinct from the same name on another
provider. The same prefix appears in the model menus on General.
Opening it shows a Model row and an Effort row, and
each opens its own list. Model and effort show the value in effect for that
mode: the session override when one is stored, otherwise that mode’s
setting, then the fallback setting. Use default clears that mode’s
session key. A saved session writes the choice with
PATCH. A draft keeps it in the client until the first send, which stores
it on POST /chat_sessions before the instruction. The dropdowns stay
usable while a turn is running. The actor already built keeps its mode,
model, and tools; the next one reads the new choice. The catalog comes from
GET /api/v1/models, and each model includes context_window. Settings
hold the fallback model and effort, and an optional model and effort per
mode. The mode rules are in agent-modes.md.
Attached images sit as 32px thumbnails in a row at the top left of the field,
above the text. Text files sit in that same row as filename (1-10) chips. The
chip is the same AttachmentChip the transcript and the pending echo use.
Hovering a thumbnail shows its remove control; a chip carries its own remove
control. The paperclip accepts PNG, JPEG, WebP, and GIF, plus common source and
text extensions. Pasting those files, or dropping them on the field, adds them
the same way. A screenshot paste with no filename is named pasted.png. A
message holds at most eight attachments. A text file larger than 64 KB, one that
contains a NUL byte, or one that would push the attachments past 256 KB in
total, stays in the field and the composer reports why. On send, an image still
travels as a multipart file part; a text file travels in the request’s files
array as a FileAttachment. The paperclip sits in the control row beside the
context meter. A chip can also arrive without a picker: the docs viewer’s
line attach hands the composer a ranged FileAttachment through a keyed request
queue, which the composer drains into the same list and then focuses the field.
The two paths share appendAttachments, so the caps above apply to both. See
file-attachments.md for the attachment model.
A sent message shows images as a row of 32px thumbnails above the message
text. Each thumbnail loads from
GET /api/v1/chat_sessions/{id}/images/{image_id} on the API origin. In the
desktop app that origin is http://127.0.0.1:<port>, not the webview, so the
src is absolute. A sent message’s text attachments show as chips above the
text, from the message’s files metadata. The message before it is stored shows
the same chips through the pending echo.
In the desktop app the paperclip opens the OS file dialog, so a picked file
carries an absolute path and the server can mark it in-workspace or outside. In a
browser the <input> yields only a name, so a picked file is treated as outside.
The chip’s tooltip names the workspace path, or says the file came from outside
the workspace. See file-attachments.md.
Chat runtime
This page defines how a submitted instruction becomes one turn of the agent
loop, and how a newer instruction interrupts the one already running. It is
the design doc for the chat-instruction half of M2 in the
roadmap. Read it before writing code in
crates/robi::domain::chat_message or crates/robi::adapters::chat_runtime.
What this page does not cover
| Topic | Where it belongs |
|---|---|
| The turn state machine, cancellation inside a model turn, and how a tool call is settled | agent-loop.md (M0) |
| Schema, migrations, chat-session CRUD, and the message route table | persistence.md (M2) |
| Provider wire format, retries, and the delta stream | providers-streaming.md (M1) |
| Streaming those deltas to the window | docs/src/design/core/architecture.md and docs/src/design/shell/chat-ui.md (M2). This slice has no SSE |
| Which tools need approval | docs/src/design/workspace/permissions.md (M3) |
| The model writing a title after a completed turn | Session title on this page |
Problem
Agent::user_input is safe for one caller. Two overlapping calls on one chat
session both append and both drive the model, and the transcript those calls
leave is not one a provider will accept.
The HTTP handler has to return before the model finishes. A second instruction
typed while the first is in flight has to replace it, not run beside it. An
instruction typed while the transcript is waiting on a tool decision must not
be appended ahead of that decision. The loop already enforces that last rule
inside user_input; the runtime has to surface it before it starts a turn.
The agent is not process state. One Agent kept for the life of the server
would be shared across chat sessions and would outlive the turn it was driving.
Decision
ChatRuntime is a domain port. SerializedChatRuntime implements it. HTTP
talks only to ChatMessageService, which checks the chat session and the
instruction, then calls the port. GET of the transcript reads MessageStore
and does not take the actor lock.
One actor per chat session. That actor is the only user_input caller for the
session. Two chat sessions each have an actor, and those actors run at the
same time. They share the factory, not an agent.
The process stores an AgentFactory: the message store, the event sink, a
ModelSource, the tool registry, and LoopConfig. Building the actor calls
Agent::new from those pieces. The source is read when the actor starts, so
the agent receives the model and effort that are current then. Each field
resolves on its own: the active mode’s session override, then that mode’s
setting, then the fallback setting (model, reasoning_effort), then the
built-in default (ocg_glm-5.3, and no effort). The model id’s ocg_/ant_
prefix selects the provider. The agent is moved into
the actor task and dropped when the actor goes idle. The next instruction for
that session builds another actor and another agent from the same factory. One
agent serves every instruction that actor drains before it goes idle.
robi-api fills the factory with SqliteMessageStore, BusEventSink, a
SettingsModelSource over the settings store, an empty ToolRegistry, and
LoopConfig::default(). The empty registry is the fallback for a factory
with no chat session service. When the service is present, the actor builds
a session registry for the stored mode and passes that same registry, the
workspace root, and the mode to ModelSource::model. The provider is offered
those tools, and the system prompt is assembled for them at the same time. See
instructions.md and agent-modes.md.
The sink publishes each loop event on the in-process bus. The window
follows that stream and still reads the transcript with GET. A tool name the
model emits that is not in that registry fails as NotFound inside the loop;
the runtime’s approval check still reads whatever the transcript already
contains. The tools themselves are in read-tools.md.
Slot
Per session, under one tokio::sync::Mutex over a map of SessionId to slot:
| Field | Meaning |
|---|---|
running | An actor task exists for this session |
pending | The newest instruction the actor has not taken. A later submit replaces it |
cancel | The token of the user_input the actor has entered. None until that call starts |
The lock is held across the idle-to-running transition, and across taking
pending and storing the new token. It is not held across user_input or
across the transcript read. Slots are not removed. One slot per session that
has been submitted to, for the life of the process.
Submit
stateDiagram-v2
[*] --> Idle
Idle --> Running: submit
Running --> Running: newer instruction cancels and replaces pending
Running --> Idle: actor finishes and pending is empty
submit does this, in order:
- If
runningis set, cancel the stored token when there is one, replacependingwith this instruction, and returnAccepted. The transcript is not read. - Otherwise take the lock. If
runningbecame set while the session registry was being built, interrupt as in step 1. If it is still idle, setrunning, store the instruction aspending, drop the lock, spawn the actor, and returnAccepted.
Accepted means the slot holds the instruction. The model has not run.
A transcript that is paused on approval is accepted the same way. user_input
rejects each call still waiting, settles those rejections, and then appends
the instruction. An unfinished call the tool would run immediately is settled
the same way, then the instruction is appended.
A blank or whitespace instruction never reaches submit.
ChatMessageService returns BadRequest first, and it also returns
NotFound when the chat session row is missing. The web layer maps
Accepted to 202 { "status": "accepted" }, BadRequest to 400, and
NotFound to 404. AwaitingApproval is still a SubmitOutcome, mapped to
409 with { "error": "chat session is awaiting approval" }. submit does
not return it.
Actor
sequenceDiagram
participant H as HTTP
participant R as Runtime
participant A as Actor
participant G as Agent
H->>R: submit "first"
R->>R: running, pending = first
R->>A: spawn, Agent::new
R-->>H: Accepted
A->>A: take pending, mint token
A->>G: user_input "first"
H->>R: submit "second"
R->>R: cancel token, pending = second
R-->>H: Accepted
G-->>A: Cancelled
A->>G: user_input "second"
G-->>A: Complete
A->>A: pending empty, exit
Note over A,G: Agent drops with the task
The actor loops:
- Take the lock. If
pendingis empty, clearrunningandcanceland return. The agent drops with the task. - Take
pending, mint aCancellationToken, store it on the slot, and drop the lock. - Call
user_inputwith that token. - Log
Failedat warn and any otherTurnOutcomeat debug. When the outcome isComplete, spawn the title task from Session title, then loop. The actor does not wait for that task.
Because the token is stored before the lock is dropped, a submit that arrives
during user_input cancels that call. A submit that arrives before step 2
finds cancel still empty and only replaces pending. The replaced text is
never passed to user_input.
What an interrupt leaves in the transcript
The loop owns these outcomes. The runtime depends on them.
- An instruction still sitting in
pendingis replaced. It is never appended. - Once
user_inputhas appended the user message, cancellation during the model turn returnsCancelledand does not append a partial assistant message. The actor then runs the replacement, which appends the newer user message. The model’s second transcript contains both user messages. user_inputrejects calls that are still waiting on approval, settles those rejections, and then appends. Settle maps cancellation during tool execution toPaused. The actor has already taken the instruction out ofpending, so that text is not retried. The HTTP call already returned202if the slot wasrunningwhen it was submitted.
The idle path and the running path both accept the instruction. A turn that is still in flight is cancelled first; the replacement then runs.
Stop
stop cancels the in-flight turn and drops any instruction that has not
started. It does not queue a replacement.
- If the slot is missing or
runningis false, return. The session is already idle. - Cancel the stored token when there is one, and clear
pending. - Wait until that actor has cleared
running. The wait is for the generation that was running whenstopwas called. A later actor does not hold this call.
The HTTP handler returns after that wait. POST /chat_sessions/{id}/stop
is 202 { "status": "stopped" }. A missing session is 404. Stopping an
idle session is the same 202.
A user message already appended stays. A partial assistant message is not
appended. An instruction still in pending is discarded and is never
appended. The composer stays locked until this call returns.
Session title
When user_input returns Complete and the chat session’s title is still
null, the actor spawns a task that asks the same model for a short title and
writes it. A title set at create or by rename is left as it is. A cancelled,
paused, or failed turn does not name the session. If the title is still null
after that, the next completed turn tries again.
The call is Model::generate with one user message: a naming instruction plus
an excerpt of the latest user text and the latest assistant text. It uses a
fresh session id, so the provider conversation header is not the chat’s id.
The prompt and the reply are not appended to the transcript. The reply’s first
line is the title, with wrapping quotes and a trailing period removed, and it
is cut at 200 characters. An empty reply is not written.
The write is UPDATE ... WHERE title IS NULL. It moves updated_at and leaves
last_used_at alone. A rename that lands while the model is answering keeps
the renamed title.
After the row is stored, the task publishes robi.session.v1.updated
on the bus. The shell refetches that session. The actor has already been
free to take the next instruction; the title task does not hold the slot.
Interfaces
ChatRuntime (crates/robi/src/domain/chat_message/runtime.rs):
submit(session, instruction) -> Result<SubmitOutcome, ServiceError>
running_session_ids() -> Vec<SessionId>
decide(session, call, reject) -> Result<(), ServiceError>
stop(session) -> Result<(), ServiceError>
SubmitOutcome is Accepted or AwaitingApproval.
running_session_ids is the sessions whose slot has running set. Idle
slots stay in the map and are left out. Nothing about this list is written
to the database.
ChatMessageService checks the instruction and the chat session, then calls
submit, stop, MessageStore::messages, or MessageStore::message.
list_messages and get_message do not call the runtime. get_message
loads that id through MessageStore::message.
Chat session responses copy running_session_ids into has_pending_agent on
each returned session. Get and list are the reads the window uses; create and
rename return the same field from the same snapshot. The same responses carry
turn_display. Accepting a message or a tool decision stores pending and
publishes robi.session.v1.updated with that value. When the actor goes idle,
Complete and Cancelled store idle, Paused stores awaiting_approval,
and Failed stores failed. That write happens after the actor clears its
running slot, and it publishes the same event. The
loop does not read the column.
Each of those writes also settles the row, since pending is the only display
written while a turn runs. That is what keeps the startup repair down to the
sessions a killed process was mid-turn in. See
parallel-front-ends.md and
persistence.md.
AgentFactory (crates/robi/src/adapters/chat_runtime.rs) holds:
| Field | Role |
|---|---|
store | Arc<dyn MessageStore> shared by every actor |
events | Arc<dyn EventSink> |
models | Arc<dyn ModelSource>, read when an actor starts |
tools | Arc<ToolRegistry>. Used when sessions is absent. A session actor builds its own registry for the stored mode |
config | LoopConfig, copied into each agent |
sessions | Option<Arc<ChatSessionService>>. The title task reads and writes the row. Absent in tests that do not name sessions |
bus | Option<Arc<EventBus>>. Publishes core agent events; the session service publishes robi.session.v1.updated with the new title after a rename is stored |
submit builds the session tool registry for the stored mode and reads that
mode’s override, then asks models for a model with that registry, mode, and
choice, before it marks the session running. build receives both. A missing
session, a missing key, an unknown model, or a bad effort returns the error
and leaves the slot idle. An actor that is already running keeps its model
and its tools; the instruction replaces the pending one. A mode or choice
changed while it runs applies to the next actor. Path rules are
reloaded on each tool call, so a PATCH applies to the next call without
starting a new actor.
SerializedChatRuntime stores the factory and the slot map. It does not store
an Agent.
The composition root is robi-api. It loads the settings store from
persistence.md and passes a SettingsModelSource
to the factory.
Rejected alternatives
- One
Agenton the process, shared by every session. Rejected. Sessions would share a turn, and the agent would outlive the actor that should own it. The factory is the process state. - A new
Agenton everyuser_inputinside a busy actor. Rejected. The agent is ephemeral to the actor. The actor builds one when it starts and drops it when it goes idle. - A queue of every instruction. Rejected. Latest wins. An instruction that has not started is replaced, and the replaced text is not run.
- The actor inside
robi-core. Rejected. Core stays the loop and its four traits. The runtime is an adapter overuser_input. - Holding the HTTP request until the turn finishes. Rejected.
202means the actor has the instruction. - SSE as the transcript read. Rejected.
GETreads the persisted transcript, including while a turn is writing it. Live updates are the stream in events-sse.md. - One actor for the whole process. Rejected. Serialization is per chat session. Two sessions run concurrently.
Failure modes
- Two idle submits that both pass the approval read: the lock lets one set
runningand spawn. The other seesrunningand becomespending. One actor, oneuser_inputat a time. - A submit that lands before the actor stores a token replaces
pendingand has nothing to cancel. The actor then takes the newer text. The older text never starts. - A submit while a turn is in flight returns
202, cancels that turn, and leaves the replacement inpending. The user message already appended stays. - A stop while a turn is in flight cancels that turn, drops
pending, and returns after the actor exits. The user message already appended stays. Stopping an idle session returns202and changes nothing. decidewhile the actor is running returns409. While idle, it approves or rejects that call and resumes the turn.- A submit while idle and awaiting approval is
202. The actor rejects the pending calls, records those rejections, and then appends the instruction. - A submit whose
user_inputthen returnsPausedwas already accepted. The text is not appended and is not put back inpending. - A store error while reading the transcript for the approval check is
NotFoundorUnknown. The instruction is not stored. A SQL failure is logged; the client sees the fixedUnknownmessage. - Starting an actor, starting or resuming a turn, and the actor going idle are logged at info. Replacing a pending instruction is logged at info. The instruction text is not logged. Stopping a running actor is logged at info when the stop is requested and again when that actor has exited.
- A tool decision is logged at info with the call id and whether it was an approval. The rejection reason is not logged. A decision while the actor is running is logged at warn. A settle that fails is logged at error.
- Building the session model is logged at error when it fails. Preparing the actor is logged at info with the mode.
user_inputreturningComplete,Paused, orCancelledis logged at info.Failedis logged at error. The actor then takes the nextpendinginstruction, or exits if there is none. The HTTP response was already202. A failed turn is not titled.- An accepted instruction is logged at info with the session id. The instruction text is not logged.
- A title that is stored is logged at info. A title estimate that fails, or an empty reply, is logged or ignored. The turn’s outcome is unchanged and the title stays null.
- A title that is already stored is not replaced, and the model is not asked.
- The actor is a detached task. Process shutdown drops it. A restart has no slots. The next submit builds a new actor. A transcript that is waiting on approval is rejected by that submit and then the new instruction runs.
GETduring a write is a normal SQLite read. It does not wait on the actor.
Testing
SerializedChatRuntimewith a model that blocks until released: two overlapping submits run oneuser_inputat a time, the first turn observes cancel, and the second transcript contains both the original user message and the newer instruction.stopon that same blocked model returns only after the actor is idle. The transcript keeps the user message and has no assistant message. A secondstopon the idle session returns immediately.- A transcript with a pending tool call whose tool needs approval is accepted. The call is rejected, that rejection is stored before the instruction, and the tool does not run. A pending call the tool would run immediately is accepted; the tool runs, then the instruction is appended.
ChatMessageServicewith a fakeChatRuntime: a blank instruction isBadRequestand the runtime is not called; a missing chat session isNotFoundfor submit, list, and get; a real instruction is passed through and list reads the store. Get returns the message with that id, and a missing message id isNotFound.- A completed turn on an unnamed session stores the model’s title and publishes
robi.session.v1.updated. A session that already has a title does not ask the model again. A failed turn leaves the title null.
Events and SSE
The UI learns what the loop did through one Server-Sent Events stream. The loop
emits a core Event on EventSink. crates/robi wraps that event in a
CloudEvents envelope, fans it out in process, and writes the envelope as JSON
on GET /api/v1/events/stream. The Solid shell opens one EventSource.
This page is the design for event delivery in M2 of the
roadmap. It settles the “events out” half of decision D1:
the desktop shell receives loop events over HTTP SSE on robi-api, not over
Tauri events. Commands (send a message, settle an approval) stay HTTP as
chat-runtime.md and persistence.md already
describe them. Process placement of the loop (in-process vs. sidecar) stays
D3 and belongs in docs/src/design/core/architecture.md when that page is written.
What this page does not cover
| Topic | Where it belongs |
|---|---|
The Event enum and emit-after-persist | agent-loop.md (M0) |
| Provider SSE into the model client | providers-streaming.md (M1) |
Who may call user_input, interrupt, approval refusal | chat-runtime.md (M2) |
| Message REST and the transcript snapshot | persistence.md (M2) |
| Streaming caret, scroll-lock, tool-card layout | docs/src/design/shell/chat-ui.md (M2) |
| In-process loop vs. sidecar, command IPC | docs/src/design/core/architecture.md (M2) |
flowchart LR
Agent[Agent loop] -->|emit Event| Sink[BusEventSink]
Sink --> Hub[EventBus]
Hub --> Sse["GET /api/v1/events/stream"]
Sse -->|CloudEvents JSON| ES[EventSource in shell]
ES --> Store[Session and transcript UI]
Problem
EventSink is a single consumer. The UI needs many subscribers (tabs, a
reconnect) and a stable wire format that is not the Rust enum. Tauri events
would only reach the desktop webview. The web UI already talks to robi-api
through the Vite /api proxy, so the same process should push events.
A raw dump of Event also cannot grow. Later producers (session renamed,
review ready) need a common envelope. CloudEvents 1.0 is that envelope.
Decision
One in-process bus under domain/events/, one SSE route, one shell
EventSource.
robi-core keeps Event and EventSink unchanged. domain depends on
robi-core and on neither web_api nor adapters. Fan-out is queues, not a
socket and not a file.
| Module | Role |
|---|---|
domain/events/envelope.rs | EventEnvelope, from_payload, and from_core_event |
domain/events/bus.rs | EventBus: publish and subscribe |
domain/events/sink.rs | BusEventSink implements EventSink |
domain/events/mod.rs | Re-exports for the composition root |
web_api/events.rs | Axum handler only: subscribe, filter, write frames |
AppState holds event_bus: Arc<EventBus>. The agent runtime receives
BusEventSink. The endpoint is also testable with a publisher that calls
publish directly.
Rejected alternatives:
- Tauri events as the only UI stream. Rejected for event delivery.
pnpm devhas no Tauri process. SSE on the API the shell already proxies covers web and desktop the same way. - A second
EventSinkmethod that speaks JSON. Rejected. Core must not know CloudEvents or HTTP. - Per-feature EventSources. Rejected. Browsers cap HTTP/1.1 connections. One shell connection carries every agent type.
- Replay of
message_deltaon reconnect. Rejected. Deltas are ephemeral. Reconnect refetches the transcript over HTTP, then follows the live stream. - An unbounded subscriber queue. Rejected. A slow tab must not stall the
loop or grow without bound. When the queue is full, drop a
message_deltaif one is queued. Otherwise drop the oldest frame.
Wire contract
Endpoint
GET /api/v1/events/stream
| Query | Rule |
|---|---|
event_types | Repeated. Optional. When present, only envelopes whose type is in the list. When absent, every agent type. |
session_id | Optional UUID. When present, only envelopes whose subject equals that session id, plus index progress and MCP status whose subject is that session’s workspace, session create/update/delete, robi.app.v1.error, and turn_started / turn_finished for any session. Message and tool frames for another session stay off this stream. |
workspace_id | Optional UUID. The shell always sets this and does not set session_id. Every session frame is delivered. Index progress, MCP status, and file changes are limited to this workspace. |
Response headers:
Content-Type: text/event-streamCache-Control: no-cacheX-Accel-Buffering: no
An idle stream sends an SSE comment every 15 seconds so a proxy does not treat
it as finished. EventSource ignores comments.
Vite proxies /api to 127.0.0.1:1431 for pnpm dev and for
ROBI_EXTERNAL_API=1. Those modes use a same-origin URL:
/api/v1/events/stream?.... The desktop app asks the shell for the bound origin
and opens the stream on that host.
OpenAPI may describe the path and query parameters. The body is an SSE stream, not a JSON schema the client generator can call. The contract of record is this page.
SSE frame
id: <cloudevents id>
event: <cloudevents type>
data: <full EventEnvelope JSON>
event and data.type are the same string. The client may dispatch on either.
EventEnvelope
CloudEvents 1.0.
| Field | Value |
|---|---|
specversion | "1.0" |
id | New UUIDv7 per emit |
source | "robi/agent" |
type | Table below |
time | RFC 3339 UTC |
subject | Session id. Always set for agent events |
data | JSON object for that type |
Type map
Source enum: crates/robi-core/src/event.rs.
Core Event | type | data |
|---|---|---|
TurnStarted | robi.agent.v1.turn_started | { "session_id" } |
MessageAdded | robi.agent.v1.message_added | { "session_id", "message_id" } |
MessageUpdated | robi.agent.v1.message_updated | { "session_id", "message_id" } |
MessageDelta | robi.agent.v1.message_delta | { "session_id", "message_id", "delta" } |
ToolCallUpdated | robi.agent.v1.tool_call_updated | { "session_id", "message_id", "tool_call_id" } |
AwaitingApproval | robi.agent.v1.awaiting_approval | { "session_id", "tool_call_id" } |
TurnFinished | robi.agent.v1.turn_finished | { "session_id", "outcome" } |
These are not core Events. Build them with EventEnvelope::from_payload.
data is a cue, not the stored row.
type | source | subject | data | When |
|---|---|---|---|---|
robi.session.v1.created | robi/session | session id | { "session_id" } | After a session row is stored |
robi.session.v1.updated | robi/session | session id | { "session_id", "title"?, "turn_display"? } | After any stored field changes, including a generated title. title is set when the change is a rename. turn_display is set when the display summary changes |
robi.session.v1.deleted | robi/session | session id | { "session_id" } | After the session row is removed |
robi.app.v1.error | robi/app | app | { "message" } | A failure the user should see. message is short text. The first publisher is an MCP server that failed to start |
robi.mcp.v1.status | robi/mcp | workspace id | { "workspace_id" } | After an MCP server is marked starting, connected, or failed, and once when the stream opens. The shell refetches GET /workspaces/{id}/mcp |
robi.workspace.v1.file_changed | robi/workspace | workspace id | { "workspace_id", "path", "source", "session_id", "outcome" } | After a file is written: a docs-editor save or an edit-tool write. source is user or agent; outcome is applied, merged, created, deleted, or unchanged; session_id is null for a save with no open session. The viewer refreshes the tree, and the open page, from this frame — see docs-mode.md |
A session_id query still delivers these four types, plus turn_started and
turn_finished for every session. The four are the session list and
process-wide failures. The turn pair updates a Recents row that is not on
screen. Message frames for another session stay filtered out.
outcome is one of:
Core TurnOutcome | JSON |
|---|---|
Complete | { "kind": "complete" } |
Paused | { "kind": "paused" } |
Cancelled | { "kind": "cancelled" } |
Failed | { "kind": "failed", "message": "<short text>" } |
delta is tagged with kind. Serialization lives in domain/events, not in
robi-core.
Core Delta | JSON |
|---|---|
Text | { "kind": "text", "text" } |
Reasoning | { "kind": "reasoning", "text" } |
ToolCallStart | { "kind": "tool_call_start", "index", "id", "name" } |
ToolCallArgs | { "kind": "tool_call_args", "index", "fragment" } |
ToolCallEnd | { "kind": "tool_call_end", "index" } |
Usage | { "kind": "usage", "usage": { ... } } |
Finished | { "kind": "finished" } — no message body; the shell waits for message_added |
Failed | { "kind": "failed", "message" } |
Emit-after-persist still holds. message_added and message_updated name ids
the store can return. message_delta names the message the model stream
already fixed, before the finished row exists. The shell does not append that
text. Those two events are the cue to GET the row. See Solid.
A reconnect does not replay deltas. On EventSource open, including the
first connect, the shell refetches the session list and the active transcript.
A frame published before the socket existed is recovered from the store.
Bus
EventBus::subscribe returns that subscriber’s own bounded queue (capacity
1024) and a drop handle that unsubscribes. publish clones the envelope
into every queue.
When a queue is full, drop a message_delta if one is queued, and otherwise
drop the oldest frame. The loop’s emit must not wait on a slow client. A
dropped delta is recovered by the next stored message, not by blocking the
agent. A stored-message frame is what the shell refetches, so it stays ahead
of a token burst.
BusEventSink::emit maps Event to EventEnvelope and publishes. A
subscriber that has disconnected is removed; that is not an error for the loop.
Solid
One connection for the shell, mounted from ChatChrome.
| Piece | Role |
|---|---|
src/features/chat/useAgentEvents.ts | One EventSource on /api/v1/events/stream, with the open workspace’s workspace_id and the agent event_types. It does not set session_id. Reconnects on error, with an epoch so a stale handler cannot apply |
| Envelope parse | JSON.parse(event.data) as EventEnvelope; dispatch on type |
Handlers stay thin. They refetch HTTP and update the activity phase. They do
not write message text from a frame. Two refetches of the same URL can be in
flight together; only the one that started later is applied. A slower earlier
GET of that message, session, or session list is dropped. The
behavior is specified in chat-ui.md.
type | Shell |
|---|---|
robi.agent.v1.turn_started | Phase thinking when that session is on screen. Otherwise the Recents menu marks that row running, and does not fetch its transcript |
robi.agent.v1.message_delta | When that session is on screen: reasoning keeps Thinking, text switches to Responding. Other kinds are ignored. The text field is not stored. A frame for another session does not change the phase and does not fetch |
robi.agent.v1.message_added, robi.agent.v1.message_updated, robi.agent.v1.tool_call_updated | When that session is on screen: GET /chat_sessions/{id}/messages/{message_id} and upsert that row. One GET is in flight per message; a newer frame schedules one trailing GET. A full transcript reload merges with any row upserted after that reload started. With the review screen off, tool_call_updated starts no review fetch. A frame for another session does not fetch |
robi.agent.v1.awaiting_approval | When the desktop window is not in front, one OS notification for that pause. A click focuses the window and selects the session. See chat-ui.md |
robi.agent.v1.turn_finished | When that session is on screen: phase idle, then refetch the session and the message list. A failed outcome is recorded and drawn under the last row of that transcript until the next instruction is sent. The banner follows the session: it is there when that chat is opened later. When the desktop window is not in front, the same message is one OS notification; a click focuses the window and selects the session. The refetch does not put the phase back on thinking when has_pending_agent is still set: the actor clears that flag after this event. A turn_started that arrives during the refetch, including the next piece of work, sets thinking and the refetch leaves it. When another session is on screen: clear that row’s running mark. A failed outcome is still recorded for that session and drawn under its transcript the next time the chat is opened, and posted as that same notification when the window is not in front. No transcript fetch |
robi.session.v1.created, robi.session.v1.updated | GET /chat_sessions/{id} and replace that session in the list. A title carried on the frame is applied immediately. A frame that carries turn_display applies that value to the row immediately and still refetches. A fetch that started before the frame does not overwrite turn_display or put the running spinner back on an awaiting_approval row. A title-only frame does not refetch. A fetch that started before a title, or before a local insert, does not wipe them. The phase is unchanged |
robi.session.v1.deleted | Drop that session from the list. The phase is unchanged |
robi.app.v1.error | Record message and show it at the top of the shell until it is dismissed |
robi.index.v1.progress | Dropped. The default build publishes none, because nothing takes an index lease, and no client reads it. --features semantic-index restores the frames; a client that wants them must add its own reader |
robi.mcp.v1.status | GET /workspaces/{id}/mcp for subject when that workspace is active. The stream publishes once when it opens, then again as a server’s status changes. The tray does not poll |
robi.workspace.v1.file_changed | Record the path, source, and outcome in the docs store. The viewer refreshes the tree, and refetches the open page unless it holds unsaved edits — see docs-mode.md. No fetch of its own |
Do not open a second EventSource per feature.
On every successful open, refetch the session list and the transcript for
the session on screen. Selecting a session and that open share one in-flight
transcript read. The list merge keeps a row inserted locally after the fetch
started. The stream stays open across session switches. Changing workspace
closes it and opens a URL with the new workspace_id. A frame for another
session does not reset the 2-second catch-up wait, and it does not fetch that
session’s transcript.
Failure modes
- Slow subscriber. A queued
message_deltadrops first. Otherwise the oldest frame drops. The agent keeps running. While the phase isthinkingorrespondingand no frame for the session on screen has arrived for 2 seconds, the shell refetches the session and the message list. A frame for that session resets the wait. A frame for another session does not. - Malformed
data. The client ignores that frame and stays connected. - Filter mismatch. A client that asks for
event_typesit does not handle still receives them; unknowntypevalues are ignored. - API down. The reconnecting hook backs off and retries. Session list
refetch runs on the next successful
open. - Publish before any subscriber. The event is discarded. That matches
ChannelSink: nobody listening is not the loop’s problem. The transcript is already written. Finisheddelta without a body. The UI must not invent message content from that variant. It waits formessage_addedand the transcript GET.
Testing
domain/events:from_core_eventcovers everyEventvariant;from_payloadfills the envelope; the bus delivers to two subscribers; a full queue drops amessage_deltabefore a stored-message frame, and otherwise drops the oldest and keeps the newest; unsubscribe stops delivery.web_api: an Axum test publishes one envelope and reads one SSE frame with theid,event, and JSONdatalines. Asession_idquery drops a different subject.- Frontend: the reconnecting hook against a fake
EventSourceapplies one envelope and ignores a frame from a previous epoch. A full browser pass waits until the agent runtime publishes real events.
Implementation order
domain/events(EventEnvelope,EventBus,BusEventSink) and unit tests.GET /api/v1/events/streamand a synthetic publish test.useReconnectingEventSourceanduseAgentEventsSSEin the shell. Handlers may no-op until the transcript state is real.
Docs viewer
Disabled in M11. Kept for reference. The
#/docsroute, the docs screen, the chat tray, and the chat/documentation toggle are all off, and the front end modules behind them (src/features/docs/,src/api/docs.ts,src/state/docsStore.ts) are deleted. The user reads and writes markdown in an external editor, or asks the agent to with the shell.The API routes are off too:
web_api/docs.rsis compiled only with thedocs-viewerCargo feature. Its search is a literal markdown scan; the semantic index it used to read is deleted.agent/docs/stays unconditional, so the reconciliation and merge path is intact. A return needs:--features docs-viewer, the four routes and nine schemas inweb_api/mod.rs, thesrc/features/docs/tree,src/api/docs.ts,src/state/docsStore.ts, the route inchatRoutePaths, theDocsScreenandChatTraybranches inChatChrome, and theViewTogglein the bar. See feature switches and Streamlining roadmap.
This page is the workspace Markdown viewer: a file tree of the workspace’s markdown pages on the left and the rendered document on the right. It is the read-only half of M10’s project navigation. Editing the open page — CodeMirror, debounced autosave, and the reconciliation with an agent edit — is docs-mode.md.
What this page does not cover
| Topic | Where it belongs |
|---|---|
| Editing the open page, autosave, and the save protocol | docs-mode.md |
The file_changed event | docs-mode.md and events-sse.md |
| Widening the filter past markdown and the docs directories | M10 F10.1. This page shows markdown only |
| The shared path filter and grants | roadmap (M3) |
| Markdown rendering itself (GFM, mermaid, headings) | chat-ui.md |
Problem
The workspace already holds its own documentation — README.md, AGENTS.md,
docs/. Reading it means opening an editor outside the app. The review screen
already shows a two-column tree-plus-body layout for a set of changed files;
documentation wants the same shape over a different file set.
Decision
Two workspace routes, one screen. GET /api/v1/workspaces/{id}/docs lists
the markdown files; GET /api/v1/workspaces/{id}/docs/{path} returns one
file’s text. The shell opens #/docs, which keeps the session sidebar like the
review route. In the window bar, at the right edge of the sidebar and above
the workspace menu, the sidebar holds back and forward, then a pair of
icons, Chat and Documentation. The pressed icon follows
the route. Documentation goes to #/docs; Chat goes back to the active
chat’s route — #/sessions/{id}, or #/ on the draft, so a chat reopened from
documentation keeps its session. A
hover names the icon. Docs starts off: a fresh launch lands on the chat route, and
a #/docs hash kept from the last launch is cleared before the router mounts, so
the viewer never reopens on its own. The window bar uses the same split as chat: sidebar fill
over the sidebar column, canvas over the rest, so the sidebar color
reaches the window buttons.
The scan is a gitignore walk, with ignored directories left closed.
GET /api/v1/workspaces/{id}/docs takes path (workspace-relative; absent is
the workspace root) and recursive (true by default). A recursive listing
walks the scannable tree with the same ignore::WalkBuilder defaults as
grep: hidden entries are skipped, and .gitignore, .git/info/exclude, and
parent ignore files are respected. node_modules/, target/, and dist/
therefore stay out of that walk without a special case when they are ignored.
Symlinks are not followed. A file counts when its extension is md or
markdown, case-insensitively. The walk stops at 500 files. Paths come back
workspace-relative with / separators, sorted.
Each entry is a file or a directory. A directory carries children_fetched:
true when this response includes that directory’s children. A recursive
listing includes every ignored directory it did not enter as
children_fetched: false and ignored: true, with no descendants. Ignored
files inside a directory the walk entered stay omitted, so the scannable tree
is unchanged aside from those closed directories. recursive=false lists one
level of path: markdown files, including gitignored ones, and real
directories, including gitignored ones. Every child directory is
children_fetched: false. Hidden names stay omitted. A path outside the
workspace is 404.
The listing is paths only. The client fetches content per selection, so opening
one page does not pull the whole set over the wire. Opening a closed directory
requests that path with recursive=false.
The content route confines itself. The handler joins the relative path
against the canonical root, then canonicalizes and checks the result is still
inside the root and is a file. A path that escapes is 404, the same as a
missing file. A non-markdown name is 400. A file that is not UTF-8 is 400,
matching the review route. The text is capped at 512 KiB; a larger file ends
with [The tail of this file was cut.].
The tree is cached per workspace. The merged listing is remembered by
workspace id across visits. The first visit for a workspace shows the loading
state; a later visit paints the cached tree straight away and refreshes in the
background. A refresh does not clear the listing: the last children stay on
screen until the new response arrives, and the signal keeps the same array
when nothing changed. A one-level response replaces that directory’s direct
children. A child directory the response marks unfetched keeps grandchildren
already cached, so refreshing one level cannot wipe a deeper tree. A root
refresh leaves a directory expanded when the user had opened it and it is still
in the listing. That open set is remembered for the workspace, so leaving the
docs view and coming back does not fold those directories. A directory the
listing no longer contains is removed with its descendants. A failed
refresh keeps the cached tree rather than replacing it with an error. The
file_changed tick refreshes the root listing and each directory the user has
opened, the same way.
The tree is collapsible. The left pane is built from the listing entries,
so a directory appears when it contains a page or when it is an unfetched
ignored directory. Directories sort before files, each group alphabetical and
case-insensitive. A directory row is a button that folds its children. A fetched directory
starts expanded when a markdown file was found under it. It starts closed when
the scan found none, so a package that only contains an ignored directory such
as __pycache__ is folded until opened. Unfetched directories start closed,
and opening one fetches that level. The open state is held by the screen, not the tree, so
fetching the next document does not fold the tree. An open directory name is
--ink and a closed one is --ink-muted, with ▾ and ▸. An ignored
directory uses --ink-faint either way. A file row selects that path and
highlights while it is open.
The document has a measure. The right pane scrolls, and the sheet inside it
is min-width: 640px and max-width: 880px, pinned to the left of the pane.
The floor keeps tables and code blocks readable when the window is narrow; the
pane scrolls horizontally rather than crushing the text. Left rather than
centered: the chat tray overlays the right edge, so a left-aligned sheet is
occluded less while the tray is open. At wide sizes the sheet keeps its max
width and does not stretch to a hard-to-read line length.
The pane is the only scroller on that side of the screen. It is
position: relative, so the hidden source label on a diagram stays inside
it and does not extend the window. The screen title stays in the window
bar, which sits above this column, so this column does not clip it.
The selected document renders with the same AssistantMarkdown component as
assistant text, in its document mode: GFM, headings stepped down by level,
tables, and fenced mermaid diagrams. A relative link whose path ends in
.md or .markdown resolves against the open file and selects that page in
the viewer. A link that would leave the workspace stays a link. Absolute
URLs and in-page fragments still open as links. No document opens on page load: the
viewer starts with a centered Select a document to open it., and the tree
waits for a click. Choosing another session, or New chat, keeps the viewer
open and shows that chat in the tray (below).
Each open page is a history entry. Selecting a file, a search hit, or a
document link sets file on #/docs and pushes a history entry. The back
and forward buttons in the window bar walk that history, and so do the side
mouse buttons: button 3 goes back, button 4 goes forward. On macOS the webview
never delivers those buttons, so the desktop process watches for them and
sends the same step. They walk through pages and
then through the routes that led here. The page remembered
from the last visit is written with replace, so returning to the viewer does
not add an extra step. Backing up to an entry with no file shows the empty
prompt again.
Chat tray
The viewer and a chat share the screen. A tray on the right holds the currently selected session’s transcript and composer, so a page can be read and revised with the agent in one place.
The tray is an overlay, and its width is adjustable. It is position: absolute against the main column, pinned to the top, right, and bottom. It
opens at min(420px, 42vw), clamped to 300–900 px and to a maximum that always
leaves 320 px of the main column visible on the left. That width is the column
beside the sidebar, so the file tree stays outside the tray and can still be
clicked. A drag handle runs down its left
edge: dragging left widens it and dragging right narrows it, the cursor over it
is col-resize, and the handle lights up in --accent while hovered or
dragged. The handle is focusable (role="separator",
aria-orientation="vertical"), and Left/Right step the width by 24 px
while Home and End jump to the minimum and maximum. The width is
remembered in localStorage under robi.docsTrayWidth, so it survives a
reopen, and it is re-clamped when the window shrinks. It does not push the
document: the sheet keeps its measure and does not gain a horizontal
scrollbar. The window bar, the sidebar, and the docs search header are
unchanged, and the bar’s title stays Documentation.
It starts closed. With no tray open, a slim handle sits on the right edge
of the main column (a Show chat button, aria-expanded="false",
aria-controls the tray). Clicking it, choosing a session, or New chat,
opens the tray; the two later actions no longer leave #/docs, so the page
stays open and the tray shows the chat. The panel header carries the session
title and a Close chat button, and Escape closes it. Leaving #/docs
closes it, so the next visit starts closed again.
The tray body is the same chat surface as the main column — the transcript, the mode and model controls, and the composer — with no pending-edit review strip. A session that is still running shows the same activity line and Stop control as it does in the main column.
A plan opens over the sheet. The transcript’s View Plan button opens the plan page in the main column, over the document sheet, with the tray still beside it, so a plan can be read while the chat stays in reach. Back returns to the sheet at the page that was open: the viewer stays mounted while the plan is shown, so its tree, its open page, and its search are kept. A plan opened from the main column’s chat is still cleared when the route changes to the viewer, so the sheet is not hidden behind a plan left open in another view.
An agent edit refreshes the page. The store bumps a per-session review tick
when a tool call lands and when a turn finishes, and the file_changed frame
(docs-mode.md) refreshes the tree on any write. The viewer reads
the active session’s tick and re-fetches the open document and the tree listing
on each change. While the page is open in Edit mode with unsaved changes, the
buffer is kept and the refetch is skipped, so an agent edit is merged by the next
autosave rather than clobbering the editor. A fetch that returns the same text
leaves the state object alone, so a no-op tick does not reset the rendered
document or its scroll position. A page the agent created appears in the tree on
the same tick.
Hover actions on a block
A line of the open page can be sent to the agent, or edited, without retyping it. Hovering a rendered block — a paragraph, a heading, a list item, a table row, a code fence, a blockquote, a rule — shows an ellipsis button at the right of that block. It opens a menu:
- Add to chat adds the block’s raw markdown lines to the composer as a file attachment and opens the tray. Offered only when the screen has a tray.
- Open in editor switches the toolbar to Edit and puts the cursor at the end of the block’s first source line.
The unit is a rendered block, but the range is a source range.
AssistantMarkdown’s document mode stamps each block’s element with
data-md-lines, taken from the mdast position react-markdown already carries
on every component. That is the line in the file the page was rendered from,
never a count of rendered elements or wrapped visual lines. The hover reads that
attribute (target.closest('[data-md-lines]')), so the innermost block under the
pointer wins: a paragraph inside a list item carries the paragraph’s tighter
range, and a tight list item falls back to its own. A paragraph that wraps over
several source lines spans all of them (40-44); a heading, a table row, or a
single-line paragraph is one line.
Open in editor uses the block’s first line. The pointer’s exact visual line
is not recoverable without character-offset reconciliation through markdown
rendering, which the viewer deliberately avoids, so a multi-line block reveals
start, not the line the pointer is closest to. The cursor lands at the end of
that line and the editor takes focus. The reveal is queued and applied when the
editor mounts, because switching the mode creates the view.
The button is pinned to the hovered block’s top inside the sheet
(data-md-attach, data-find-ignore), so the hover tracking and the find bar
both ignore it. The menu renders in a portal; while it is open the viewer does
not retarget the hover on pointer move, and does not clear it on the viewer’s
mouseleave or on scroll, so reaching into the menu cannot dismiss the block it
belongs to. It clears on the next pointer move that is not over a block, and on
any scroll once the menu is closed.
The attachment is built client-side, like the paperclip’s. The viewer slices
the raw lines (attachmentFromDocument), sets the chip’s start_line /
end_line, and hands the composer a ready FileAttachment with
content_base64. The document’s workspace root becomes the absolute_path, so
the server stores the workspace-relative path and the model can re-read the
page with read_file. A slice over the 64 KiB per-file cap is refused with a
notice in the viewer rather than silently dropped. See
file-attachments.md.
A request outlives the closed tray. Attaching a line opens the tray
(setTrayOpen(true)), which mounts a composer that was not there a moment ago,
and the request must survive that gap. So AppLayout does not pass the
attachment down as a prop: it calls requestComposerAttachment(draftKey, file),
a keyed one-shot queue (src/state/composerAttachments.ts), and the composer
drains it on mount and on each request. The key is the composer’s draftKey —
the selected session id, or draft when no session is selected, so a line
attached with no chat open lands in a new chat and the first send creates the
row. The drained attachment goes through the same count and total-size caps as a
picker or a drop (appendAttachments); anything dropped sets the composer’s
error, and the field takes focus so the user can write about the line.
Search
A query field sits in the screen header. The search starts half a second after the last keystroke. Another keystroke clears that wait and aborts a request already in flight, so only one search is open and only the latest text is sent. While that pause or the request is still open, a spinner sits in the field and the results pane says Searching…. Ranked hits then replace the tree; the viewer on the right still shows whichever document is open, and clicking a hit opens it. Clearing the field brings the tree back.
One route, one engine. GET /api/v1/workspaces/{id}/docs/search?q={query}&limit={n} runs a
case-insensitive literal scan of markdown. limit defaults to 10 and may not
exceed 20; a blank or missing q, or a limit outside 1 to 20, is 400.
Text search runs rg when that binary is on PATH (--fixed-strings,
--ignore-case, markdown globs, ripgrep’s own hidden and gitignore defaults). If
rg is missing or fails to launch, the handler scans the same markdown set the
tree lists. Each file appears once, at its first matching line, and files are
ordered by how many lines matched. start_line and end_line are that line,
title is the file name, snippet is the line cut at 500 bytes, and score is
the match count.
There is no semantic engine and no index status: the semantic index is gone (S3). A search is always complete over the files on disk at the moment it runs.
{
"query": "paused turn",
"hits": [
{
"path": "docs/src/design/core/agent-loop.md",
"start_line": 40,
"end_line": 40,
"title": "agent-loop.md",
"snippet": "The invariant the whole design rests on…",
"score": 1.0
}
]
}
Find in the document
The header’s Search documentation… field searches across files. A second,
separate search finds text inside the document that is open on the right. It is
opened with Cmd+F on macOS and Ctrl+F elsewhere — the platform is read
from navigator.platform, falling back to the user agent — and closes on
Escape or the bar’s close button.
Scope is the open document. The search walks the text nodes under the
viewer element only: the tree, the cross-file results pane, and the header are
not searched. The shortcut is intercepted only while a document is rendered
(selected and content both set), so Cmd+F keeps its default behaviour
everywhere else in the app.
The bar. A text field (a literal substring, not a pattern), a match count,
previous and next buttons, a Match case toggle (aria-pressed), and a
close button. The count reads N of M one-based, says No results for a
query with no matches, and shows nothing for an empty field. Enter steps
forward and Shift+Enter steps back while the field has focus. The step buttons
wrap: next from the last match goes to the first, and previous from the first
goes to the last. They are disabled when there are no matches. Every match is
painted; the active one is scrolled to the middle of the pane.
Matching is per text node. A query is matched against each text node in
turn, so a phrase broken by an inline element — a word wrapped in emphasis, say
— is two text nodes and does not match as one hit. Case-insensitive by default;
the toggle makes it case-sensitive. The offsets are kept in original-string
coordinates by escaping the query and walking a gi/gu regular expression, so
case folding never shifts a match.
Highlighting does not touch the DOM. Matches are held as Range objects and
registered with the CSS Custom Highlight API (CSS.highlights), styled by
::highlight(robi-doc-find) and ::highlight(robi-doc-find-current) in the
screen’s stylesheet. The rendered document is never mutated, so a re-render
of AssistantMarkdown — which happens on every screen render, because
onDocLink is a new function each time — cannot corrupt the search state. The
active-match registry entry is set after the all-matches one, so it paints on
top.
The API is feature-detected (typeof Highlight === 'function' and
'highlights' in CSS). It ships in Chrome/Edge 105+, Safari 17.2+ (the macOS
WKWebView tracks Safari), and Firefox 140+. Where it is missing — a pre-17.2
WKWebView, or the happy-dom test environment — the bar still counts, steps,
and scrolls; only the color highlight is absent.
Skipped regions. The walk ignores script, style, svg, and
[aria-hidden="true"] subtrees, plus [data-find-ignore]. Diagram SVG text is
therefore out, and MermaidDiagram marks its visually-hidden copy of the source
with data-find-ignore so that copy is out too; the visible fence before a
diagram resolves stays searchable.
Late DOM changes re-run the search. A mermaid fence that resolves into an
SVG changes the text under the viewer after the first pass. While the bar is
open, a MutationObserver on the viewer (child list, subtree, and character
data) re-runs the search, debounced to one pass per animation frame, so the
ranges and the count stay correct.
Rejected alternatives
- Wrapping matches in
<mark>. Injecting nodes fights a re-render:AssistantMarkdownre-renders on every parent render, so the injected nodes would be clobbered or would break the tree. - A rehype plugin that rewrites the tree before render. It cannot report a total count and a current index back to the bar cleanly, and it still cannot match across inline nodes.
- A search box that also filters the tree. The tree is a different scope. Keeping find to the open document matches the reader’s mental model and the browser’s own Cmd+F.
Rejected alternatives
- One route returning every page’s content. A docs set is opened one page at a time; shipping all of it makes the first paint wait on the largest file.
- A new markdown parser or renderer.
AssistantMarkdownalready renders GFM and mermaid; a second renderer would drift. - Reusing the review path tree for docs.
buildFileTreeonly knows file paths. The docs tree is built from listing entries so an ignored directory can sit closed before any of its pages have been fetched. The review tree stays a path list. - Persisting the collapsed set. The default-open tree is small after the ignore filter; a stored fold state is a setting nobody asked for.
- Injecting the attach button into each rendered block. It fights the same
re-render the find feature avoids (the viewer never mutates the
rendered DOM), it is clipped by a
preor a diagram’soverflow, and it cannot sit on a table row. One overlay button positioned from the hovered block is simpler. - Mapping the hover to a single visual line. Turning a wrapped line back into a source line needs character-offset reconciliation through markdown rendering, and inline emphasis and entity rewriting shift those offsets. The block’s source range is exact and always a coherent slice.
Failure modes
- A scan error is not fatal: an entry that cannot be read is skipped, not the request.
- A failed listing shows the error in place of the tree. A workspace with no markdown shows No markdown files in this workspace.
- A failed content fetch shows the error in the viewer. The previous document stays on screen while the next one loads.
Docs editing
Disabled in M11. Kept for reference. With the docs viewer off, there is no editor in the app. The agent edits markdown with the shell and the user edits it in an external editor. The save route (
PUT /api/v1/workspaces/{id}/docs/{path}) is compiled only with thedocs-viewerCargo feature;agent/docs/, the change reconciliation and merge that the route calls, stays in the tree and stays tested. See feature switches and Streamlining roadmap.
This page is the editing half of the docs viewer: CodeMirror over the open page, debounced autosave, and the reconciliation that keeps a manual edit and an agent edit from losing each other. It is F10.2 in the roadmap.
“Docs mode” here means the documentation view — the #/docs route and its
toolbar. It is not an agent mode, and no docs agent mode is planned.
What this page does not cover
| Topic | Where it belongs |
|---|---|
| The read-only tree, search, and find bar | docs-viewer.md |
| The three edit tools and their approval cards | editing-tools.md |
| The session baseline a save records | checkpoints.md |
| The SSE envelope and reconnect | events-sse.md |
| Markdown rendering (GFM, mermaid) | chat-ui.md |
Problem
The viewer reads a page; a change means leaving the app. The obvious save is a
whole-buffer PUT, but the agent edits the same files, and a whole-buffer write
silently discards an agent edit that landed while the reader was typing. Two
copies of the file cannot be the answer either: the agent reads the disk.
Decision
The editor sends deltas, and the server reconciles. The open page mounts a
CodeMirror 6 EditorView. Each transaction’s ChangeSet is accumulated. One
second after the last keystroke the accumulated set goes to PUT /api/v1/workspaces/{id}/docs/{path}. The server applies it to the base version
the client names; if the disk has moved on, a three-way merge folds the two
together.
A version is a content hash. GET .../docs/{path} returns version, the
sha256: hash of the bytes it just returned, and stores those bytes in a
bounded per-process cache. A save names the version it was built from. The cache
is not session state and not per client: the request carries everything needed
except the base text, and the cache is only how the server recovers that.
Only the base text has to be remembered. A client that never fetched a page
has no version to name, and a base older than the cache is gone. Either is a
409 carrying the current {content, version}; the client re-sends the whole
buffer against the new version, and the user’s text wins outright.
Overlapping hunks go to the client; disjoint hunks both apply. merge3
diffs the base against the disk and against the client’s target, then walks the
hunks in order. A hunk that does not touch the other side applies. Where they
overlap the client wins, because the save is the later edit. An insert that only
touches the boundary of a replaced region composes rather than conflicts.
The save is the M4 write path. Confinement, the per-path lock, the baseline, and the atomic write are the same helpers the edit tools use, so a manual edit gets a checkpoint like an agent edit. The baseline is per path per session and the first write wins, so a 1-second autosave cadence does not mint a checkpoint per keystroke burst — the session’s revert point stays the bytes from before the first save. A save is a user action and does not go through the approval card.
A write announces itself, whoever wrote it. Every successful save and every
edit-tool write publishes robi.workspace.v1.file_changed, subject the workspace
id, with source (user or agent), path, session_id, and outcome
(applied, merged, created, deleted, or unchanged). The viewer refreshes
the tree on any frame. With autosave there is no Save click, so this frame and
the save’s own status line are how the reader learns an update went through.
Autosave
State per open document:
base— the version the pending changes were built from.pending— theChangeSetaccumulated sincebase.full— send the whole buffer next (a create, or after a409).inflight— one request at a time.
Rules:
- On a user change, compose it into
pendingand re-arm the 1000 ms timer. - On the timer, or on a flush, send. If a request is already open, do nothing;
the response re-arms when
pendingis non-empty. - On
200, adopt the response’s version. Input that arrived during the flight re-accumulated and goes out on the next debounce. Anoutcomeofmergedreplaces the buffer with the server’s text. - On
409, adopt the response’s version and re-send the whole buffer. - On an error, keep
pending, show it, and retry — one debounce, then doubling to an 8-second cap.
Flush points beyond the timer. Cmd/Ctrl+S, leaving Edit mode, choosing another document, the window losing focus, and unmount. The flush ignores the debounce.
The buffer is not clobbered. The viewer already refetches the open page on a
review tick. It also refetches on a file_changed frame, but skips the open
document while pending is non-empty and shows Agent changed this file —
saving will merge.; the next autosave merges. When the buffer is clean the
page is adopted in place, and only while the editor is unfocused, so a remote
change does not move the caret. A clean buffer always adopts the new base
version.
Toolbar
A bar sits at the top of the document pane with a Preview | Edit segmented
control — an eye then Preview, a code bracket then Edit — a
Save button (a manual flush), a dirty dot while pending is non-empty, and
a status line: Saving…, Saved, Saved — merged with an agent edit,
Out of sync — re-sending, or the error. The choice is remembered per
workspace.
The editor is created once against a ref when Edit is enabled, and destroyed when
the mode or the document changes — never rebuilt on render. Its theme and its
syntax highlighting are built from the shell tokens; there is no second
palette. Headings, emphasis, links, inline code, quotes, rules, and list markers
are colored, so the source and the Preview read as the same document. The editor
draws its own cursor (drawSelection) rather than leaning on the browser’s
native caret, which the production WebKit webview does not render reliably; the
theme’s accent color reaches both the native caret-color and the .cm-cursor.
Edit can open at a line. A hovered block’s Open in editor action flips
the mode and asks the editor to revealLine, which puts the cursor at the end of
that source line, scrolls it into view, and focuses the view. The cursor move is
not an undo step. The request is queued on the screen and applied by the mount
effect, because the editor does not exist yet at the moment the mode changes. See
docs-viewer.md.
Rejected alternatives
- A whole-buffer
PUT. Simple, and it discards an agent edit that landed during the debounce window. The delta plus merge keeps both. - A per-connection buffer the server owns. Buffers would need eviction, reconnection handling, and a rule for two windows on one page. A content hash is stateless and survives a reload.
- Line-based deltas. CodeMirror works in character offsets; converting to and from lines costs more than the merge saves.
- Applying a delta to the disk text instead of the cached base. The offsets are the base’s, so the delta would land in the wrong place. The cache is what makes a delta meaningful.
- A merge conflict the user resolves. Reserved for a gone base version. The common case is one agent hunk and one user hunk, which compose.
- A WYSIWYG editor. It needs a faithful DOM-to-markdown serializer, and it fights the viewer’s rule that the rendered DOM is never mutated. A source-buffer editor with the existing renderer beside it keeps one source of truth.
- Blocking the save on a clean buffer. Autosave has no Save click; refusing to write because the user is “still typing” leaves the file stale.
Failure modes
- A
409recovers with one full-buffer resend. Another409repeats it. - A save error keeps the buffer and the pending set; a status line reports it and the retry backs off. Closing the view flushes what it can.
- A
file_changedframe for a deleted page leaves the tree without the path; the next selection is a new document. - Saving with no open chat session writes without a baseline. The setting is not required to edit.
File attachments
A user can attach text files to one message. Each attachment has a display name
and an optional line range, and may come from inside or outside the workspace.
The composer and the transcript draw each one as a filename (1-10) chip.
What this page does not cover
| Topic | Where it belongs |
|---|---|
| Uploaded images | persistence.md, the image store |
/id skill loads | skills.md |
The read_file tool and its path rules | read-tools.md |
| The composer and transcript chrome | chat-ui.md |
Problem
A user often wants the model to read a file, or part of one, without the model spending a tool call to find it. The old paperclip read a text file in the browser and folded it into the prompt string. That worked, but the transcript bubble then carried the file’s bytes, there was nothing to render as a chip, and the model’s input was not reconstructable from the message.
Decision
An attachment is a sibling field on the message. Message.files is a
Vec<FileAttachment>, beside skills and images. Each entry is:
{ "name": "error.rs", "path": "src/error.rs",
"start_line": 29, "end_line": 34, "text": "…the slice…" }
textis the attached slice: the whole file, or the selected range.pathand the range are display metadata.pathisNonefor an upload, which has no workspace location; the range is absent for a whole-file attach.start_lineandend_lineare 1-based and inclusive, matchingread_file.
Because the text is stored on the message, a later request rebuilds the same prompt from the transcript. Nothing re-reads the file at request time.
The client reads the bytes; the server never opens path. The composer
reads the file and sends the slice. The server measures the text the client sent
and never dereferences the path. That is the whole reason an attachment outside
the workspace is safe with no grant: there is no server-side read to confine.
An explicit attach is the consent.
Never trust the client for size. The handler re-checks the caps.
Wire to the model
Each provider adapter appends one block per attachment to the text of the user
turn, in user_text (Anthropic) and user_content (OpenAI-compatible), right
after the skill blocks. crates/robi/src/agent/files.rs renders it:
<file name="error.rs" path="src/error.rs" lines="29-34">
…text…
</file>
path is omitted for an upload; lines is omitted for a whole-file attach. The
model reads the block as text, so it can widen the read with
read_file(path, offset, limit) — offset is start_line, limit is
end_line - start_line + 1.
The terminal’s producers
The terminal has no picker, so it has two commands. /attach <path> reads one
file into the composer and /detach [name] takes one — or every one — off.
Every rule above is shared, not restated. domain::chat_message::attachment
holds the caps, the NUL-and-UTF-8 text rule, the base64 decode, and the
in-workspace decision; the HTTP handler and the terminal both call it. The
handler keeps FileAttachmentInput as its wire DTO and maps AttachmentError to
its statuses; the terminal calls text_attachment with the text it already read.
Two differences, both about where the bytes come from:
- The terminal reads the path it was given, so
/attachresolves a relative path against the workspace root and also accepts~and an absolute one. A file outside the workspace attaches withpath: None, exactly as a browser upload does — the explicit attach is the consent, and there is no server-side read of the stored path to confine. - A path may carry
:start-end, and:40is one line. The suffix is recognised only when everything after the last:is digits or digits-dash- digits, soa:b.rsandC:\src\x.rskeep their colons. The cap applies to what is attached rather than to the file, which is what lets a file larger than 64 KiB in at all; a range past the end clamps and the chip reports the lines actually taken. This is the one piece of the model the GUI does not have — its range producer is the docs viewer, in TypeScript — so it lives in the domain module beside the caps.
An image’s bytes wait in the composer until a session exists, because the image
store is keyed by session and the landing page has none. ImageAttachment stays
an id and a media type: the name and the weight are the composer’s chip, and the
transcript can only say [image, image/png].
Transport
POST /api/v1/chat_sessions/{id}/messages takes a files array. A JSON body
carries it directly. A multipart body (used only when images are also present)
carries it as one files field whose value is the JSON array, because a
multipart part cannot hold a nested object.
The caps, enforced server-side in build_files:
| Cap | Value | Response |
|---|---|---|
| Files per message | 8 | 400 |
| One attachment’s bytes | 64 KiB | 413 |
| All attachments’ bytes | 256 KiB | 400 |
A file with a blank name is 400.
GET /chat_sessions/{id}/messages returns ChatMessage.files as metadata
only — name, path, start_line, end_line. The attached text is not
returned, so a transcript read does not carry every attachment’s bytes. The chip
is the affordance; the source file is still on disk.
The chip
src/features/chat/AttachmentChip.tsx is the one widget, used in three
places: the composer (with a remove button), the transcript, and the pending
echo. It reads filename (start-end), or just filename when there is no
range.
The echo. A message that has been sent but not yet stored shows as a pending
echo. The echo carries the attachment metadata (PendingEcho.files) so the chip
appears immediately, before the stored row exists.
Where a range comes from. The composer never sets one: the OS file picker and
a drop have no notion of a source line, so the composer only ever produces
whole-file attachments (filename, no range). A range is a producer concern, and
both built producers are currently removed from the app (streamlining S5 and S2):
- The docs viewer’s add-to-chat button slices a hovered block’s raw markdown
lines (
attachmentFromDocumentinsrc/features/docs/docAttachment.ts) and hands the composer a readyFileAttachmentwithstart_lineandend_line. The block’s source range comes fromdata-md-lines, whichAssistantMarkdown’s document mode takes from the mdastpositionreact-markdown carries on every element — the file line, not a rendered one. See docs-viewer.md. - The review screen’s Reject with reason sends directly rather than handing
off to the composer. It builds one attachment from the hunk’s
new_start/new_countrange (src/features/review/reviewAttachment.ts), or a whole-file attachment, then decides the reject, returns to the chat, and callssendInstruction. See code-review.md.
Both stay in the tree behind showSurface('docsViewer') and
showSurface('reviewScreen'). The tray handoff below is what a restored producer
would call.
The producer does not pass the attachment down as a prop, because attaching a
line opens the chat tray and the composer is not mounted until it does. It calls
requestComposerAttachment(draftKey, file) (src/state/composerAttachments.ts),
a keyed one-shot queue, and the composer drains it on mount and on each request.
The key is the composer’s draftKey — the selected session id, or draft when no
session is selected, so a line attached with no chat open lands in a new chat. The
drained attachment goes through the same caps as a picker or a drop
(appendAttachments). A future code viewer on the M10 shared editor is the next
producer, and it uses the same handoff.
Prefix caching
Storing the text protects the prefix cache. Prefix caching keys on a
byte-identical token prefix, so a frozen message never moves when the source
file changes on disk. The design that would invalidate the cache is the rejected
one — storing only a path and re-resolving at request time, where editing the
file changes an earlier turn’s tokens and breaks the prefix from that point on.
The tradeoff is a straight swap: freeze keeps the cache stable but can go
stale. The transcript holds what the user attached, not what the file says
now. If the file changes, the model reasons about the old bytes until it calls
read_file.
The paperclip
The composer’s paperclip keeps its image/text split. Images are unchanged: they
go out as ImageAttachment and the bytes live in the image store. Anything that
is not an image becomes a FileAttachment through the path above. The old
instructionWithTextFiles fold is gone; the size and NUL checks moved into the
attachment builder.
What counts as text is decided from content, on the server. The client sends
each file’s raw bytes, base64-encoded, as content_base64; the server
base64-decodes them and applies the same rule the read tools use (read_code,
grep): a NUL byte marks binary, and the bytes must be valid UTF-8. Anything
else is 415. No file name or extension is consulted, so .log, .conf, and
extensionless files are text when their bytes are. The client sniffs the same
rule (looksLikeText) for feedback at attach time, but the server is the
authority and re-checks.
Also on attach: a file over 64 KB per file or 256 KB total is refused, and the
server re-checks both caps after decoding (an oversized base64 body is rejected
before decode). A blank name is 400; invalid base64 is 400.
In-workspace vs outside is also decided on the server. The client sends the
file’s absolute_path when its picker provides one; the server canonicalizes it
and the session’s workspace root, and a path under the root becomes the stored
workspace-relative path (so the model can re-read it with read_file). A path
that is outside, or that cannot be resolved because the server cannot see it,
keeps only its name and is treated as outside; the provider block then carries
origin="outside-workspace". The server canonicalizes to compare — that
resolves symlinks, so a link out of the workspace is outside — but it never reads
the file’s contents.
The absolute path only exists in the desktop app: the paperclip opens the OS
dialog through a Tauri command (pick_attachment_files) that returns each file’s
absolute path and bytes. The webview’s <input type="file"> exposes only the
basename, so a browser upload — or any drop or paste — has no absolute_path and
is treated as outside. path is never stored for an outside file and is never
opened by the server.
Rejected alternatives
- Fold the text into
content. The old paperclip. The bubble then carries the bytes, the chip needs separate metadata anyway, and the model’s input is no longer a field. Rejected. - Store only
path+ range and re-resolve at request time. Always fresh, but it invalidates the provider prefix cache on every file edit and routes a hidden server-side read of a user-named path. Rejected. - Keep the fold beside the new system. Two paths for one thing, two renderings. Rejected: one path.
Failure modes
- A file over a cap is refused before the message is stored; the composer shows the error. In the terminal that is the footer, and nothing is attached.
- A file that is not UTF-8, or that contains a NUL, is refused by the client before send.
- A missing
filesfield deserializes as an empty list, so an older client and an older stored row both load.
Terminal shell
A second front end: the same agent, sessions, and tools, rendered in a terminal
instead of a webview. The robi-api HTTP surface stays exactly as it is; the TUI
does not call it. It links crates/robi, builds the same AppState the API
builds, and drives the same services.
This is a surface page, like frontend-layout.md, not a
milestone. It adds no capability to the loop and changes nothing in robi-core.
It exists because the domain layer already separates a service from a controller,
so a second front end is a rendering problem and not a rewrite.
Phases are numbered T0–T6 rather than M-numbers, because they do not gate any M-milestone and no M-milestone gates them.
Scope is the chat surface only. Review and docs are not planned here. Both
are already off in the GUI — reviewScreen and docsViewer in
src/app/surfaces.ts, shipped as S2 and S5 in streamlining.md
— so a terminal copy would resurrect a surface the product has decided against.
git diff and the user’s own editor are the review path; the docs screen is not
replaced at all. The backend routes stay served, as they do for the web shell.
What this page does not cover
| Topic | Where it belongs |
|---|---|
| The turn lifecycle, approvals, tool execution order | agent-loop.md |
| The CloudEvents envelope, the bus, and the SSE route | events-sse.md |
The per-session actor and ChatRuntime | chat-runtime.md |
| Store, schema, migrations | persistence.md |
| What a tool card shows, and when approval pauses | chat-ui.md — the TUI reaches parity with it, and does not restate it |
| Theme tokens | visual-style.md. tui/theme.rs is its terminal peer |
| Crate layout and the process model | docs/src/design/core/architecture.md, still unwritten |
Problem
The agent is reachable only through a Tauri window. That costs a webview, a window manager, and a display for work that is mostly text: a transcript, a diff, a list of sessions. A terminal front end reaches the same sessions from a shell, over SSH, and inside an editor pane.
The naive implementations are both wrong:
- A TUI that speaks HTTP. It re-introduces the whole wire layer between two
processes on one machine, replaces
robi_core::message::Messagewith theChatMessageDTO, and stops working when the API is not running. - A TUI that re-implements the domain. A copy of the session lifecycle in a second binary, drifting from the first.
The reason neither is necessary: bootstrap::build_app_state is HTTP-free.
bootstrap::router is the optional half, and only robi-api and src-tauri
call it.
Decision
A module in crates/robi, a binary in the same package, behind a cargo
feature. In-process. Elm-shaped. One event subscription. Refetch, never append.
flowchart LR
subgraph P["one process"]
T[robi<br/>tui::app] --> S[bootstrap::build_app_state]
S --> D[domain services]
R[SerializedChatRuntime] --> A[Agent loop]
D --- R
A -->|BusEventSink| B[(EventBus)]
B -->|EventSubscription| T
end
AppState is the whole contract. Its fields — workspace_service,
chat_session_service, chat_message_service, settings_service, event_bus,
file_changes, mcp, originals, image_source — are the same handles
the Axum handlers take. A controller is State<AppState> plus Path plus Json;
the TUI is an Arc<AppState> plus a keymap.
One of those it never reads: docs_edits (no docs surface; see Deliberately
not planned). It stays in AppState because build_app_state is shared and
the HTTP routes still serve it.
Where it lives
A module, not a crate.
crates/robi/
src/tui/
mod.rs # run(): terminal lifecycle, the feature gate
app.rs # App, Msg, update()
action.rs # Action: the effect update() asks for
effects.rs # Action -> service call, on the runtime
keys.rs # (Mode, KeyEvent) -> Msg
command.rs # the built-in `/` commands, `/open` today
lifecycle.rs # init/restore and the panic hook
theme.rs # Style constants; the peer of visual-style.md
persist.rs # ~/.robi/tui.json
state/ # transcript, sessions, workspaces, composer,
# approval, prompt, confirm, status, detail
view/ # header, transcript, detail, composer, prompt,
# strip, sessions, workspaces
src/bin/robi.rs
Cargo.toml gains a feature and a binary:
[features]
tui = ["dep:ratatui"]
[dependencies]
ratatui = { workspace = true, optional = true }
[[bin]]
name = "robi"
path = "src/bin/robi.rs"
required-features = ["tui"]
ratatui and crossterm are declared once in [workspace.dependencies], per
the existing rule that versions cannot drift. Take crossterm from
ratatui::crossterm, not as a second direct dependency: ratatui 0.30 pins its
own and a second version in the tree fails to typecheck on KeyEvent.
Why not a crate
The rule in AGENTS.md is to add a module and split only for one of four
reasons. Only the second applies — a heavy, optional dependency — and a cargo
feature isolates it just as well without moving code:
robi-apiandsrc-taurido not compile ratatui, because they do not enabletui.cargo tree -p robi-coreis unchanged. That is the audit that matters.- No item becomes
pubonly so a second crate can reach it.tuiispubso the binary can calltui::run, which is a real entry point.
Promote to crates/robi-tui when one of these is true, and not before: the M8
headless robi-cli needs the same module (the split AGENTS.md already
anticipates, “a new binary with no code moved”); the TUI’s tests need to run
without the web stack; or a measured build cost appears. The promotion is a move
plus a manifest, because the module is already shaped like one.
Rejected instead of a new crate now: robi-index and robi-lsp were the
splits with a real dependency argument, and both are deleted with M7. A crate
for one binary that depends on crates/robi in both directions is the “split
that happened too early” anti-signal.
Process model
In-process, no listener, no port. robi shares ROBI_DATABASE_URL with
robi-api and src-tauri, so all three see the same sessions. With that
variable unset it opens the desktop app’s database — the app’s own in a release
build, the dev one in a debug build, which is the condition
src-tauri’s is_dev() applies. The rule is in bootstrap::desktop_database_url,
and file-locations.md states it for users.
Distribution
Each release carries a tarball per target, beside the desktop bundles:
| Asset | Target | Runner |
|---|---|---|
robi-v<X.Y.Z>-aarch64-apple-darwin.tar.gz | arm64 macOS | macos-latest |
robi-v<X.Y.Z>-x86_64-unknown-linux-gnu.tar.gz | x86_64 Linux | ubuntu-22.04 |
Each holds one directory, robi-v<X.Y.Z>-<target>/, with robi and LICENSE.
checksums.txt on the release covers them with the bundles.
The Linux tarball is built on 22.04, which sets its glibc floor at 2.35, so one
file runs on 22.04 and 24.04 both. Nothing in crates/robi needs more: SQLite is
bundled, reqwest is rustls, and bollard is pure Rust. The desktop bundles
still build on 24.04, and a binary that needs the system’s WebKitGTK is why they
are separate.
Only tui is enabled: the gated workstreams are the restore path, so the shipped
binary is the default harness. The binary is stripped, and on macOS re-signed
ad-hoc after stripping, because strip voids the signature ld64 wrote and an
arm64 binary without one does not run. Nothing is notarised, so a downloaded
macOS binary needs xattr -d com.apple.quarantine.
--version on the packaged binary is the release smoke test: it proves the
tarball runs and that the tag and CARGO_PKG_VERSION agree.
The workspace argument
robi [PATH]
PATH is the workspace the process opens, and it is the answer to which
sessions the reader starts with: the remembered workspace from tui.json is not
a fallback. Without an argument the path is the working directory, so
cd ~/code/pocket && robi and robi ~/code/pocket are the same session
list. The argument is canonicalised before it is compared, because the store keeps
a canonical root and one directory has many spellings.
A path with no workspace row behind it is a prompt, not a silent fallback to
some other workspace: No workspace at this path. with the path under it, and two
answers — y creates the workspace there (open_workspace, the same call the
POST /workspaces route makes), n opens the switcher so an existing workspace
can be chosen. Opening anything else on the reader’s behalf would show them a
session list that is not the one they asked about.
The switcher opens over the question, not instead of it. n pushes the
workspaces overlay on the mode stack above workspace-missing, so the question
stays the page: the panel draws over it, dimmed, without its y/n line because
the panel owns the keyboard. Esc closes the panel and returns to the question;
choosing a row — or creating one from the panel’s create screen — pops both. The
first cut left the question first and opened the overlay in the chat, so
Esc-ing the overlay landed the reader in a chat frame with no workspace, no
session, and no way to answer.
Two flags and one path, not a flag set:
-h, --help Print the help and exit.
-V, --version Print `robi <version>` and exit.
-- Treat every later argument as a path.
-- exists so a directory whose name starts with a dash has a spelling. A second
path is a mistake worth naming on stderr before the alternate screen, because a
terminal that ignores an argument opens the wrong chat. Everything is parsed
before the terminal is taken raw, and before the TTY check, so robi --version | cat works. A usage error exits 2, to tell it apart from a run that started and
failed.
args::parse in tui/args.rs returns the decision; bin/robi.rs owns the TTY
check, the logger, and the exit code. The split is what makes the flags a unit
test rather than a terminal session.
SerializedChatRuntime is per-process and in memory: running_session_ids is
not persisted, and an actor belongs to the process that started it. Two front
ends on one database therefore mean two runtimes, which can drive two turns on
one session.
Ownership across processes is a per-session lease, not a database lock: the TUI
takes Open on the session it displays and Turn through the runtime, so a
second process may read that session and may not submit to it. The lease, the
redb handle invariant it depends on, and what parallel processes still share
are in parallel-front-ends.md.
Two terminals in one workspace are allowed. There is no ~/.robi/tui.lock:
the whole-home lock is gone. A session another process owns still renders — its
transcript, tool names, arguments, and statuses come from the chat database —
and each tool result it holds is replaced by open in another process (pid N),
with the same sentence in the footer. A submit to that session is refused with
Conflict, which reads as a footer notice naming the pid, and the draft stays in
the composer.
The loop
self.view(&App) is a pure function of state. update() is a pure function
(State, Msg) -> (State, Vec<Action>). Effects run on the runtime and report
back as a Msg. The four sources feed one select!:
#![allow(unused)]
fn main() {
loop {
tokio::select! {
Some(msg) = input.recv() => app.update(msg),
Some(env) = events.recv() => app.update(Msg::Agent(env)),
_ = tick.tick() => app.update(Msg::Tick),
Some(done) = results.recv() => app.update(Msg::Done(done)),
}
for action in app.take_actions() { effects::run(&state, action, &results); }
terminal.draw(|frame| app.view(frame))?;
if app.should_quit() { break; }
}
}
ratatui::crossterm::event::read blocks. It cannot run on the runtime: it would
hold a worker for as long as the user takes to press a key. A dedicated
std::thread reads events and sends them into a bounded(64) mpsc. A resize
event arrives on the same channel.
Interfaces
#![allow(unused)]
fn main() {
pub fn run(state: AppState, options: Options) -> std::io::Result<()>;
pub struct App { /* AppState, view state, mode stack, actions */ }
pub enum Msg {
Key(KeyEvent),
Agent(EventEnvelope), // what the bus carries
Tick, // 250 ms: spinners, elapsed, catch-up
Done(ActionOutcome), // one effect finished
Resize,
}
pub enum Action {
Submit { session: SessionId, text: String, files: Vec<FileAttachment> },
StartSession { workspace: WorkspaceId, text: String, files: Vec<FileAttachment> },
Decide { session: SessionId, call: ToolCallId, decision: Decision },
Stop(SessionId),
Compact(SessionId),
Reload(SessionId), // refetch the transcript
LoadMessage { session: SessionId, message: MessageId },
Rename { session: SessionId, title: String },
Delete(SessionId),
Create,
LoadSettings { generation: u64 },
SaveSetting { key: &'static str, value: Option<String> }, // from the surface's table
LoadMcpConfig { workspace: WorkspaceId },
OpenFile { path: String, line: Option<u32> },
}
impl App {
pub fn update(&mut self, msg: Msg);
pub fn take_actions(&mut self) -> Vec<Action>;
pub fn view(&self, frame: &mut Frame);
pub fn should_quit(&self) -> bool;
}
}
Every Action names a service call. effects::run is the only module that
touches AppState, and it is the only place a .await exists:
Action | Call |
|---|---|
Submit | chat_message_service.submit_instruction, after image_source.store for each pending image |
Decide | chat_message_service.decide_tool_call |
Stop / Compact | chat_message_service.stop / .compact |
Reload | chat_message_service.list_messages |
LoadMessage | chat_message_service.get_message |
RenameSession / DeleteSession / StartSession | chat_session_service.*; StartSession creates the row and submits the first message in one effect, and a delete stops the turn first, as the route does |
LoadWorkspaces / CreateWorkspace / DeleteWorkspace | workspace_service.*; a delete closes that workspace’s MCP connections |
LoadSessions | list_chat_sessions plus running_session_ids |
LoadMcp / FocusMcp | mcp.status / mcp.focus, the peer of GET/POST /workspaces/{id}/mcp |
Probe | list_workspaces inside a three-second timeout: the strip’s health mark |
CompletePath | the tools’ resolver, then one read_dir, directories only |
LoadSettings | settings_service.get_many, with each secret reduced to configured |
SaveSetting | settings_service.set / .remove; the secret flag is re-read from known_setting, never carried on the action |
LoadMcpConfig | workspace_service.get_workspace, then McpHub::config_files on blocking::call; the file text is dropped |
Attach | resolve, read, sniff, slice, and classify one file the reader named |
OpenFile | the lifted file opener: configured file_open_command only |
SubmitOutcome::AwaitingApproval is unreachable from the real runtime — nothing
constructs it outside web_api’s mapping, which turns it into a Conflict — so
the terminal keeps the arm as a defensive no-op. A paused turn is answered on the
selected card, not by a modal.
State ownership
The transcript is not built from deltas. message_delta moves the phase to
Responding and no more; message_added, message_updated, and
tool_call_updated mean refetch that row. This is the rule the web shell already
follows, and in a TUI it is load-bearing rather than tidy: the bus drops a queued
message_delta when a subscriber falls behind (make_room in domain/events),
so a transcript rendered from deltas silently loses tokens.
Two refetches of one URL can be in flight together, so each Action carries the
generation it was issued at, and a Done whose generation is stale is dropped.
The GUI solves the same problem with an epoch in useAgentEvents; the mechanism
is the same and the reason is not obvious, so it is written here.
State lives in one of three places, and nothing is duplicated between them:
| Where | Holds | Survives |
|---|---|---|
AppState services | every domain fact | restart |
App | the mode stack, scroll offset, composer buffer, expansion flags | the process |
~/.robi/tui.json | workspace, open session, expansion flags, layout | restart |
Parity map
Every GUI surface that is on today, its TUI form, and the phase that lands it.
The two surfaces the GUI has switched off — reviewScreen and docsViewer in
src/app/surfaces.ts — are out of scope here as well, so a TUI flag is not
needed for them; see Deliberately not planned. The index status is gone with
the index itself, so nothing in the frame carries an index line.
| GUI surface | TUI form | Phase |
|---|---|---|
Transcript + AssistantMarkdown | scrollable buffer, turn-grouped, styled spans; every message railed in the ink of the mode that produced its turn | T1, T4 |
Composer textarea, drafts per session | text area, draft kept per session in App, in memory | T1 |
| Send / Stop button | Enter / Esc (Ctrl-C also stops) | T1, T2 |
ActivityLine, streaming | status strip above the composer: Thinking for 4s and animated dots, at the end of the transcript | T1 |
Turn footer Worked for … | one gray row under each closed turn, from the turn’s first and last message ids | T3 |
ToolCallCard and its six variants | one background band per call, no border, muted heading and $; the per-variant bodies, and Enter on the selected card opens the whole body in a scrollable detail view | T2 |
| Approval buttons on a card | in-transcript: a / r / A act on the selected card, with the reason as a one-line prompt | T2 |
RecentsMenu (filter, rename, delete) | sessions overlay: filter-as-you-type, running spinner, waiting dot, Ctrl-R rename, Ctrl-D delete behind a confirm; New session… is the first row | T3 |
WorkspaceSwitcher | workspace overlay: the eight most recent, then Manage workspaces… and New workspace… | T3 |
WorkspacesPage | manage view: every workspace with its own filter and remove, Ctrl-N to create; the create screen’s typed path with directory completion | T3 |
robi workspace argument | robi [PATH], the working directory by default; a path with no workspace is a prompt, not a fallback | T3 |
ErrorNotices, ApiStatus | status strip above the composer: ! <error>, ! health: …, sending…, stopping… | T3 |
| MCP marks in the tray | one word at the header’s right edge: MCP Online / MCP Failed (per-server detail later) | T3 |
| New chat | Ctrl-N: the landing page, and no session until the first message | T3 |
EmptyGreeting + welcome composer | the landing page: the greeting centred in green, the composer under it | T3 |
Mode ChoiceMenu | Ctrl-T cycles, /mode names one; the word and the rail colour are the state | T4 |
ModelEffortMenu | Ctrl-M: one overlay with a model group and an effort group, Use default in each | T4 |
SkillMenu | @ completion over the composer, with · manual and scope; accepting leaves @id | T4 |
ContextMeter | the token count at the right edge of the composer’s facts row | T4 |
| Compact | Ctrl-L or /compact, behind a confirmation; divider row on transcript_compacted | T4 |
| Composer command surface | /models, /sessions, /workspaces, /new, /rename, /mode, /compact, /help — each a keybinding’s twin | T4 |
Nothing (the design promised ?) | ? from the transcript, or /help: a page of every key and command | T4 |
| General settings | settings surface, section rail | T4, T5 |
| Model provider settings | settings surface, secrets masked | T5 |
| Permissions settings | settings surface, two toggles | T5 |
| Sandbox settings | settings surface, six fields and two choices | T5 |
| MCP settings | settings surface: servers, the two config paths, trust, logs | T5 |
| Audit log | settings surface: a paged service-call table, Enter expands a body | T5 |
Composer attachments | /attach and /detach; images by path | T6 |
MermaidDiagram | source fence | T6 |
OpenedFile, openWorkspaceFile | /open <file>, configured program only | T6 |
Phases
T0 — Skeleton and the pump
Goal — a terminal app that renders a real transcript and nothing else.
-
tui/mod.rs::runowns the terminal:ratatui::init, a panic hook that restores before the message prints,ratatui::restoreon every exit path. -
bootstrap::build_app_statefor state. Nologs::init()as-is: a debug build writes tracing to stderr, which corrupts the frame.logs::init_tuiis the same file layer with no stderr layer in any build, and its files are namedtui-<timestamp>.logso a TUI run is distinguishable from the app’srobi-api-/robi-dev-files in the same directory. Pruning is per prefix, so a TUI start never deletes the app’s logs. -
The four-source
select!, the input thread,Msg,Action,effects::run. -
state/transcript.rs: turn grouping, follow-the-bottom with a scroll lock that yields onPageUpand re-arms at the bottom. -
theme.rsfromvisual-style.md’s tokens, so the two front ends stay one product. -
A
TestBackendharness: renderApp::viewinto a buffer and assert on a string. This is the TUI’s test strategy from the first commit. -
Every message and every tool call is a band: a raised surface with a one-cell rail on its left edge, one cell of horizontal padding, and one row of padding above and below. The rail is the only vertical rule in the transcript itself; the scrollbar, when there is one, sits in the gutter beside it. — there is no drawn border, so the band contrast plus the rail is the whole affordance. The rail’s colour is what identifies the block. The rail cell itself is
\u{258d}(left three-eighths block) rather than the hairline│: one box-drawing line is nearly invisible at a normal cell size, and the rail is what a reader scans for. A block glyph costs the same one cell, so the wrap width, the band width, and the scroll arithmetic are unchanged, and the colour is still the whole signal — the glyph only decides how much ink it carries.Block Band Rail User message --bg-user--accent(blue)Tool call --code-bg--ink-faint(gray)Composer --bg-surface--accent(blue)A user message is therefore a full-width band with the text left-aligned, not a right-aligned capsule. The blue is the transcript’s one piece of state: the user’s own turn. Machinery is gray. The composer wears the blue rail too, because it is the user’s turn before it is sent — the same column, the same accent, so the two read as one thing at either end of the transcript — and one row of canvas separates it from the transcript above, so the last row of prose never reads as part of the band.
-
A tool call’s card reads, in order:
│ │ # shell │ │ $ cd /pocket && php artisan migrate --no-interaction │ │ INFO Running migrations. │The heading is
#then the call’sdescriptionargument or the tool’s name, in--ink-muted. A shell call withunsandboxed: trueappends· unsandboxed, so the one property that changes what the command can touch shows without opening the card:# shell · unsandboxed. A blank row separates it from the contents; the subject line is$ command, with the$muted too and the command in the card’s ink; a second blank row precedes the output. The output is not indented past#or$— all three start in the same column, so the card reads as one block rather than a nested list. At mostMAX_TOOL_OUTPUT_LINES(6) lines of the result show, the cut counted as… (+N more lines). One blank row also separates every block, and that one comes frombuild_rowsalone, so inter-block spacing is uniform no matter what a block does inside its own band. T2 replaces the output per variant and adds expansion.
Exit — cargo run -p robi --features tui --bin robi shows the most recent
session of the active workspace, scrolls, and quits cleanly. One snapshot test
renders a two-message transcript.
T1 — Send, stream, stop
Goal — the M2 exit criteria, in a terminal.
- Composer:
ratatui-textareaon a--bg-surfaceband wearing the same blue rail as a user message, two cells of horizontal padding inside the field, and one blank row of canvas above the band.Entersends,Ctrl-Jinserts a newline (Alt-Entertoo, where a terminal reports it as one key — T2 bindsEsc, so theEsc,Enterambiguity is whyCtrl-Jis the documented one). Draft per session, in memory, keyed the waycomposerDrafts.tskeys it. A failed send restores the buffer and attachments. message_delta→ phase;message_added/message_updated/tool_call_updated→LoadMessagefor that row;turn_finished→ reload, then idle. Deltas never write text.Ctrl-CsendsStop(T2 addsEscas the same interrupt); a cancelled turn leaves a resolvable transcript, so the view reloads rather than truncating.- Phase, elapsed, and a caret at the end of streaming text. The phase is the
status strip above the composer —
Thinking for 4swith the webview’sThinkingDots— not a header segment; T3 moved it there with every other status. - Assistant prose rendered as markdown — headings, lists, tables, fenced code,
links, quotes, GFM alerts — through
tui-markdown, styled fromtheme.rs. - Scrolling:
↑/↓(when the composer is empty or the transcript has focus),PageUp/PageDown,Ctrl-U/Ctrl-D,Home/End, and the mouse wheel. The wheel is enabled next to raw mode and turned off before the alternate screen goes. - The status strip’s progress widget: eight cells with one moving head, at the right edge of the strip above the composer, shown only while a turn runs or a stop is in flight. T3 moved it there with the rest of the status.
- The 2-second catch-up: while a turn is busy and no frame for the open session
has arrived, reload. Elapsed time and the quiet stretch are counted in 250 ms
ticks, not wall clock, so
updatestays a pure function. - A send while a turn is running interrupts and queues, as it does in the
GUI. T1 refused it, on the theory that
Entermid-stream more often means “newline” in a terminal; T2 reversed that, because refusing made the terminal disagree with the product in a way the user had to discover.ChatRuntime::submitalready replaces a pending instruction, so nothing had to be built.
Exit — send a message, watch it stream, stop it, quit, restart, find the
session intact. The turn ran through SerializedChatRuntime and the real
provider.
T2 — Approval and tool cards
Goal — the loop’s pause invariant, made visible and unmissable.
- A pause takes the keyboard, off an empty composer. When a call starts
waiting, the card is selected and focus moves to the transcript, so the first
aanswers the question instead of landing in a message. It only does that when the composer is empty: a draft is the reader’s work in progress, and an arriving pause is no reason to take the caret out of it. With a draft the card is still selected and its rail still says it needs an answer, and the keyboard is oneTabaway. A detail view or a reason field the reader opened is never interrupted, and a second call in the same batch follows the same rule. - A waiting card wears an orange rail and moving dots. The rail column every
card row shares is
--attention(#e39a3c, the same value as--mode-plan, under its own name) while the call ispending,not_started, and the turn is idle, and the quiet--ink-faintotherwise. The idle half is the peer ofneedsDecisionintoolCallView.ts, and without it the rail was wrong for every call between the model’s response and its own execution: that is exactly thepending+not_startedstate, because that is how a model’s request arrives. A shell command that runs without asking wore the rail and the label of a question for the whole of that window. The label row reads waiting for approval followed by one, two, or three dots, advancing once a second — four 250 ms ticks a step, so a full cycle is three seconds. A quarter-second flicker reads as machinery waiting on itself; a slow, even beat reads as a prompt. That is what makes a pause visible when it is not the selected card: the selection only ever marks one block, and a pause can be anywhere in the transcript. A card in the running window says running… instead, and its heading readsshell · runningrather thanshell · not started: the turn is what the reader is watching, and a call that is next in line is not a call that has stalled. The phase is what tells those two apart, so a session switch has to rebuild it: an opening session whose actor is still live opens atThinking, fromApp::running— the same set the list read fills — rather than at idle. The frames that would have set it belong to the session that was on screen, and a phase left at idle drew the in-flight call of a running turn as a question. For the same reasonturn_startedandturn_finishedkeepApp::runningcurrent for a session that is not on screen, so a switch does not have to wait for a list read to learn whether the actor is still there. - The dots are painted, not stored. A row whose text changed every second would
rebuild and rewrap the transcript once a second, and the scroll offset would
twitch. The dots play into the band’s own padding instead: the view rebuilds the
label from
WAITING_LABELplus a fixed three-cell dot field, andband_linepads the result to the content width. Fixed field, not appended dots, for one reason: the first dot has to stay in its column, so growing to two and three extends rightwards instead of shifting what is already on screen. Editing the padded row text in place — the first attempt — made the rowwidth + dotscells long, and the band’s fill saturated to nothing. The clock is a tick counter onApp, never the wall clock, soupdatestays a pure function of the messages it has seen andviewa pure function of the state. - The activity line’s dots sit in the same fixed field.
Thinking for 4s .keeps its column as the marker advances, for the same reason as the waiting card’s: a fixed three-cell field after the text, never appended dots. The line used to be a right-aligned header segment; T3 moved it to the strip above the composer, where the webview puts it, and the header’s right edge now carries the one-word MCP summary instead. - A selected block is lighter than the rest. Every row of it is painted on
--surface-hoverand filled to the frame’s content width, so a message, a paragraph, and a card all read the same way. This replaced a▸on a card’s heading, which was too quiet and left prose with no mark at all. The foreground is kept — a heading stays muted, a diff stays green and red — because only the background is saying “this is the one the keys act on”. - The arrows select; a key acts on the selection. With the transcript
focused,
↑/↓(andj/k) move a selection over the transcript’s blocks. A block is a user message, an assistant prose run, or one tool call — so every card, pending or finished, is addressable. The selection is aBlockRef(message, optionalcall), keyed on the message id rather than a row offset, so it survives a rewrap, a reload, and a row arriving underneath it. - There is no modal. T2 shipped one because the GUI can disable a composer and
a terminal cannot. Selecting in the transcript replaces it: the pause is state
(
Approval), not a mode, and nothing covers the frame. What replaces the modal’s visibility is that a pause takes the selection to the waiting card — without that, a pause arriving mid-transcript would be invisible. - The footer hint is contextual, because the actions are: a selected pending
card offers
a approve · r reject · A approve all · Enter open · Ctrl-C decline, a finished card offersEnter open, and nothing selected shows the composer’s keys. A hint that offered approval on a card that already ran would be a lie the user has to test. Enteropens a card in a detail view: the whole body, uncapped (the band stops at forty lines and an edit at twenty-four), its own scroll,Escback with the selection where it was. On a prose block it does nothing — a message has no second view. The body is wrapped toview::content_widthwhen the view opens and again onMsg::Resize, because aParagraphwithout.wrap()truncates: one long shell command ran off the right edge and its tail was unreachable. Rows are built in the state, sooffsetcounts rows and the1-22 of 83position stays honest.- In-card expansion is dormant. The detail view replaced it: growing the band
in place could push the turn it belonged to off the screen.
Render.expanded, thetui.jsonkey, the expanded branch and the expanded shell/MCP original fetch stay in the code behind#[allow(dead_code)], so re-enabling is deleting a marker. Nothing toggles them, so the set stays empty and no original is fetched for them. - A send interrupts and rejects, like the webview. There is no busy refusal
and there is no pause protection:
ChatRuntime::submitreplaces a queued instruction (interrupt_if_running), andAgent::user_inputrejects a paused turn’s waiting calls with “the user sent a new message” before appending. The terminal now inherits both rather than disagreeing with them, and clears its own pause state as soon as the send is taken. - Card variants, matching
ToolCallCard: edit diff, shell, MCP, retrieve, delegate steps, generic. An edit shows the four changed lines it is asking about, or the result’s patch once it has run. A shell or MCP card shows six lines; the detail view is what shows the rest, so an opened card no longer fetches anything by itself — opening the view does, throughOriginalStore::lookup, the same bodygetToolOriginalserves the GUI. - A card’s line stops at two frame widths. Lines are wrapped, not counted, so
a cap on lines said nothing about a result that is one enormous line: a JSON
body, a minified bundle, or a base64 blob arrived as a single line of thousands
of cells and wrapped into dozens of rows of one band, pushing the rest of the
turn a page away. Every line the band draws — heading, subject, and body —
is cut to
CARD_LINE_FACTOR(2) times the frame width, with…as the mark, and the cut is measured in cells so a run of wide characters cannot overflow the frame. Two widths is long enough to read the shape of the line and short enough that one result cannot own the transcript. The cut belongs to the collapsed card only:Enteropens the detail view, which builds its own lines fromtool_card::full_bodyand draws them whole, so the full context is always one key away. - A retrieve card shows no output at all. Its body is a page of another
call’s log, so the transcript is the wrong place for it: the card keeps the
window —
# retrieveover> 0193a1b2 stdout, the id and the stream — and one muted… Enter opens the output. The page is built only bytool_card::full_body, the uncapped form the detail view calls, so the two cannot drift apart, and the transcript pays nothing for a log it would have had to truncate anyway. awaiting_approvalwhile the window is unfocused → terminal bell, and the title becomes robi — approval needed either way. No OS notification; that is Tauri-only. Focus reporting is optional (DECSET 1004), so a terminal that does not implement it simply never rings.- A pause is not the end of a turn. The loop emits
awaiting_approvaland thenturn_finishedwith outcomepaused, because the actor really does exit. That frame must not close the pause: the transcript is parked, not finished. - A pause is entered from the transcript as well as from the frame. Reopening
a session paused by an earlier run — a restart, or a switch back to it — selects
the waiting card the same way a live pause does, from the loaded transcript.
Without that, a pause on screen had no way in from the keyboard, and the only
remaining answer was “send a message to clear it”. The list is
pendingapproval withnot_startedexecution, which is the same predicate the loop uses, so a call that ran without asking is never a prompt. Idle only: after a decision the phase isThinking, so a reload still in flight cannot re-list a settled call.
Exit — a turn that needs approval selects its waiting card, a or r on it
decides, and the turn resumes; a refusal reaches the model as a structured
rejection. That is Event::AwaitingApproval →
ChatMessageService::decide_tool_call → Event::ToolCallUpdated in
agent-loop.md.
T3 — Sessions and workspaces
Goal — you can get to any session without the mouse. Done.
- Sessions overlay on
Ctrl-S: a filter field with the keyboard, arrows over the rows,Enterto open,Ctrl-Rto rename,Ctrl-DorDelto delete behind a one-line confirmation. Each row carries one cell of state: a braille spinner while the actor runs, an--accentdot while the turn waits on approval.New session…is the first row, so a fresh chat is the first thing under the cursor when nothing is open, andEnteron it creates one.Enteron the session that is already open still issues a read: “open” always means “show me this transcript”. - Workspace overlay on
Ctrl-W: the eight most recently selected workspaces followed byManage workspaces…andNew workspace…. The create screen is a typed path with directory completion onTab. The GUI’s folder dialog has no terminal equivalent, so the path is resolved with the tools’ own resolver (~, relative, absolute) and handed toopen_workspace, which still refuses a path that is not a directory. - Managing workspaces is a view (
modemanage), not a screen of the switcher: every workspace, filtered, with remove behind the confirmation, andCtrl-Nto create. A menu is a thing you leave in one keystroke; reading paths and deleting rows is a place you stay. - Panels erase what is under them. A
Blockpaints a background colour but leaves the characters, so an empty transcript’s centred sentence read through the switcher. Every panel clears its rectangle first, and every list row is painted with its background applied after the text style, so a selected row is one unbroken band — including the two action rows, which the theme helpers were silently cancelling to canvas. robi [PATH]— the process opens the workspace atPATH, or the working directory. A path with no workspace is a prompt (ycreate,nswitcher over the question), not a fallback to whichever workspace an earlier run left open; see The workspace argument.Ctrl-Nopens the landing page and creates nothing. A workspace with no session open shows the webview’s welcome: the time-of-day greeting (Good morning/afternoon/evening, in--mode-askgreen) centred above the composer. The session row is created when the first message is sent —Action::StartSessioncreates and submits in one step — so opening a workspace, reading the list, and leaving never leaves an empty chat behind. A failed first send keeps the row and puts the text back in the field.Ctrl-Rrenames the open one.- A status strip above the composer:
! <app error>,! health: <reason>from alist_workspacesprobe every five seconds, and the turn’s own activity. The HTTP health route is not called: the terminal does not speak HTTP, and a store that answers is the fact the route is standing in for. - The frame keeps one blank row above the header and one below the hint
(
view::FRAME_PAD), and one between the composer’s underside and the hint. Chrome that touches the terminal’s edge reads as cut off rather than placed; the transcript pays for those rows out ofbody_height. - One faint row of
\u{2500}under the header, exactly the content width: the frame draws no other border, so a single line is enough to say the bar above is chrome and the page below is the conversation. - A one-word MCP summary at the header’s right edge —
MCP Online,MCP Failed,MCP Starting,MCP Offline— because a terminal tray would cost cells and say less; a status surface can carry the per-server detail later. - A gray
Worked for 2m 5sunder every closed turn, the webview’s turn footer, computed from the turn’s first and last message ids. robi.session.v1.*frames refetch the list and never the transcript;robi.mcp.v1.statusrefetches the marks for the active workspace.- Choosing a workspace also focuses its MCP servers once, the peer of
focusOpenWorkspaceinworkspaceStore.ts, so the marks have something to report without waiting for a turn.
Exit — create a workspace by path from inside the TUI, create and rename a session, delete one, and see a second one marked running while a turn is in flight.
T4 — Modes, model, effort, skills, context
Goal — everything the composer carries, minus attachments. Done.
- The facts row is the composer band’s last row:
Agent · GLM-5.3 · OpenCode Go · Highon the left, the token meter on the right. It is the rowview/composer.rsalready reserved as the band’s bottom padding, so the band does not grow and T3’s layout is untouched. See The composer band. - The rail is the mode. Agent
--accent, ask--mode-ask, plan--mode-plan, on the user band and the composer — not on the assistant’s reply, which is the model’s output rather than a statement of mode. The colour follows the mode a message was submitted under, so a plan-mode message keeps its orange afterCtrl-T; see The mode on the rail. Ctrl-Tcycles ask → plan → agent, writingmodeon the session row or the draft when there is no row yet.Ctrl-Mopens one picker overpickable_models—tool_capable()filtered by the provider-enabled settings, the same function/api/v1/modelscalls. That helper is lifted, not copied; see Gaps. Effort comes first: three fixed rows should not sit below thirty models.- Two sigils.
@completes this workspace’s skills (· manualand scope) and leaves@id;/completes commands, and each one is a keybinding’s twin. See The two sigils and Composer commands. - A leading
@or/that names nothing is refused without being sent, and the field keeps its text. - The meter is
contextUsage.ts’s estimate, ported;Ctrl-Lcompacts behind a confirmation, and the divider appears ontranscript_compacted. ?from the transcript, or/help: a page of every key and command, sectioned, with its own scroll. The key was documented since T0 and never mapped.
Exit — cycle the mode mid-session and watch the band and the new turn’s rail
change colour while the earlier turns keep theirs; pick another model and put it
back with Use default; type @ and accept a skill; send, press Ctrl-L, answer
y, and see the divider and a smaller meter; type /nope and get a refusal with
the text still in the field.
T5 — Settings
Goal — configure the app without leaving the terminal. Done.
- One surface, six sections, in the GUI’s row order: General, Model
providers, Permissions, Sandbox, MCP, Audit log. The rail is the nav;
h/l(or←/→) move it andj/kmove the row. See The settings surface. - A field is explicit, because a terminal has no blur.
Enteropens an editor band,Enterapplies,Escreverts. A toggle flips and a choice advances onEnterat once, since there is nothing to type. An empty buffer clears the key — except on a secret, where the service refuses to remove one, so an empty buffer leaves the stored credential alone. - A secret is one bit.
effectsreduces a credential read toconfigured: boolbefore the outcome exists, so the plaintext never entersApp; the row draws••••••••, and the editor band starts empty. - The audit log is the TUI’s own, not a lift: the webview records HTTP with an
openapi-fetchmiddleware, and the terminal records service calls ineffects::dispatch. See The audit log. - A write is followed by a read.
saved · Modelappears over the surface, and bothLoadSettingsandLoadModelsare re-issued; a refusal reverts the row and shows the service’s own sentence.
Exit — set an API key from the TUI, press Ctrl-C twice (Esc out of the
surface first, or let the second press leave the process), start a turn that uses
it. Then set max_iterations to abc and watch the row revert with the service’s
own sentence under the table.
T6 — Attachments and the graphical remainder
Goal — close the parity gap on the chat surface, and name what is permanently out. Done.
- Attachments are two commands, not a menu.
/attach <path>reads one file into the composer;/detachtakes every one off and/detach <name>takes one. An@file picker was the plan and was dropped: a command takes the path the reader meant without a per-workspace file index, a relaxed@token rule, or anignorewalk behind the menu — and the line they typed is its own record of what was attached.@stays skills-only. - A path may be relative,
~, or absolute. Relative resolves against the workspace root; an attach outside it lands aspath: None, name only, because an explicit attach is the consent and the GUI’s picker does the same. - Text or image is decided by the bytes. An image signature is an image
(10 MiB) with its bytes still bound for the model; otherwise the NUL-and-UTF-8
rule makes it text (64 KiB).
MAX_ATTACHMENTS,MAX_TEXT_FILE_BYTESandMAX_TEXT_TOTAL_BYTESare the GUI’s numbers, now shared throughdomain::chat_message::attachmentrather than restated. - A path may carry
:start-end./attach src/app.rs:40-80attaches those lines, which is how a file over the text cap gets in at all; the chip says(40-80)and the model’s block sayslines="40-80". A clamped tail reports the lines it actually took. - Images by path: no thumbnail, a
[image name, 1.2 MB]chip in the composer. The bytes still travel to the model, and the transcript shows[image, image/png]— the stored attachment is an id and a media type, so the name and weight are the composer’s. Backspaceon an empty field takes the last attachment off, the peer of the GUI chip’s×;/detachis the spelling that names one.- Mermaid fences render as source with the language on the fence line, never as a diagram.
- Opening a file is
/open <path>and nothing else. The command resolves the path inside the workspace and hands it to the configuredfile_open_command. It never falls back to$EDITOR, never suspends the terminal, and never opens anything in-process: when no command is configured it says so and stops, which is the same refusalPOST /workspaces/{id}/openreturns. A terminal user sees the file in the editor they already chose for the GUI. - Both lifted, in the same change, with the
web_apicallers switched over — see Gaps to lift out ofweb_api.
Exit — /attach src/error.rs, send it, see it in the user message and in the
model’s context; /attach shot.png and see [shot.png, 1.2 MB] with the bytes
reaching the provider; /detach src/error.rs leave the image and /detach leave
nothing; render an assistant message containing a mermaid fence without
panicking; /open src/error.rs land in the configured program and get a clear
message rather than a fallback when none is set.
Deliberately not planned
| Not built | Why |
|---|---|
| Review surface — diff list, file tree, approve/reject, reject-with-reason | Off in the GUI as S2, and there is no terminal equivalent worth writing. git diff is the review path, and the edit tools already write session baselines for it. A TUI copy would put a surface the product removed back in front of the user |
| Docs surface — tree, viewer, find, search, editor | Off in the GUI as S5. Not replaced. The agent still reads and edits docs through the existing tools; a human reads them in their editor |
In-app file peek (OpenedFile dialog) | The GUI needs a second destination so a path can render inside the app. /open has one destination — the configured program — so there is no dialog and no fileOpenPatterns split to reproduce |
| In-terminal markdown editor | Roadmap non-goal: “not a code editor” |
| Clipboard image paste, drag-and-drop | No terminal protocol worth the complexity. Paths only, through /attach. Pasting text does work: see the keyboard model |
| Image and diagram rendering | No portable cell-accurate graphics; the source is shown, and an image is a [name, 1.2 MB] chip |
An @ file picker over the workspace | Dropped for /attach: a menu over a per-workspace index needs an ignore walk, a relaxed @ token rule and a Cargo feature edge, and a path typed after a command is the same gesture with none of that |
| OS notifications | Tauri-only. Bell and title change instead |
| UI scale, pointer resize | Terminal-owned layout |
A second EventSource-style reconnect | The subscription is in-process and does not disconnect |
Keyboard model
A mode stack, so Esc unwinds one level and is predictable. Exactly one mode
owns the keyboard; chat is the base.
| Mode | Enter from | Leave with |
|---|---|---|
chat | startup; also the landing page when no session is open | Ctrl-C when idle, or q when idle |
workspace-missing | the first listing, when the path has no workspace | y creates it; n or Esc opens the switcher above it, and closing that returns here |
sessions | Ctrl-S | Esc; Ctrl-W replaces it |
workspaces | Ctrl-W | Esc, which steps back a screen before closing; Ctrl-S replaces it |
manage | the switcher’s Manage workspaces… row | Esc, back to the chat; Ctrl-S and Ctrl-W replace it |
models | Ctrl-M, or /models | Enter writes and closes; Esc closes |
help | ? from the transcript, or /help | Esc, back to the chat |
complete (the / and @ menu) | typing the sigil in the composer | Enter/Tab accept; Esc closes the menu alone; it closes itself when nothing matches |
settings | Ctrl-, | Esc |
detail | Enter on a card | Esc, back to the transcript |
prompt (reject reason, rename) | r on a pending card, Ctrl-R | Enter, or Esc which keeps the text where that matters |
confirm (delete a session or workspace, compact) | Ctrl-D / Del in a list, Ctrl-L, /compact | y accepts; n or Esc cancels back to the list |
The confirmation is its own mode rather than a flag on the list because the list’s
field owns printable keys: y would otherwise be a character in a filter and an
answer to a question at once. One overlay at a time, also by design: Ctrl-S and
Ctrl-W replace rather than stack, so one Esc always closes what is on top.
Managing workspaces is a view, not a screen of the switcher. The switcher is a
menu — eight rows, two actions, gone in one keystroke — and a full list stacked on
it read as the same thing twice, with the menu’s frame still visible around it.
manage owns the frame the way detail does: a title with its position, a filter,
the list, and its own hint row. Enter opens, Ctrl-N creates, Ctrl-D removes
behind the confirmation, Esc returns to the chat.
There is no approval mode. A pause is state, answered on whichever card is
selected, so it does not need the keyboard to itself — the design’s own
“a terminal has no disabled composer” problem is solved by the selection instead
of by covering the frame.
Global bindings, checked before the mode’s own map:
| Key | Does |
|---|---|
Ctrl-C | Decline a paused batch. Otherwise: cancel a confirmation, stop the running turn, close an overlay. Idle: quit |
Esc | Unwind one level: the reason prompt, then the detail view, then the selection (handing the keyboard back to the composer), then stop the turn. Never quits |
q | Quit, idle only and transcript focus only |
Ctrl-N | New chat: the landing page, with no session created until the first message. A new workspace from inside the workspace overlay |
Ctrl-R | Rename: the open session from chat, the selected one from the sessions overlay |
Ctrl-S / Ctrl-W / Ctrl-M | Sessions / workspaces / model + effort |
Ctrl-, | Settings |
Ctrl-L | Compact |
Tab / Shift-Tab | Move focus between the transcript and the composer |
↑ / ↓, j / k | Move the selection block to block. The selected block is painted on --surface-hover, every row of it; a card waiting on a decision — idle turn, pending, not_started — has an --attention rail and animated dots after waiting for approval |
| Mouse wheel | Scroll the transcript (three rows a notch) |
PageUp / PageDown | Scroll by a screen, and release the follow lock |
Ctrl-U / Ctrl-D | Half a screen |
Home / End | The first row / the last, which re-arms the follow lock |
Ctrl-T | Cycle the mode: ask → plan → agent |
Ctrl-M | The model and effort picker |
Ctrl-L | Compact, behind a confirmation |
? | The help page — transcript focus only, because ? typed in the field is a character |
/ | Commands, and @ skills, as completion over the field |
Focus is part of the keymap, not a check inside a handler. From T1 the
composer is on screen for the whole life of the process, so q cannot mean
“quit” while it may be a character someone is typing. The map is
(Mode, Focus, Key) -> Command, and the composer holds focus by default
because typing is what a chat is for. The composer’s own bindings:
| Key | Does |
|---|---|
Enter | Send |
Ctrl-J (and Alt-Enter) | Newline, without sending |
Tab / Shift-Tab | Give the keyboard to the transcript, and back |
Esc | Stop the running turn |
Ctrl-J is named first for a reason: some terminals deliver Alt-Enter as
Esc, Enter, and with Esc bound as the interrupt that sequence would stop
the turn and then send the draft. Alt-Enter stays bound where a terminal
reports it as one key.
A paste is text, never keystrokes. The app asks the terminal for bracketed
paste (DECSET 2004) at startup and releases it on the way out, so a pasted block
arrives as one Msg::Paste instead of being typed at the field. Anything else is
a bug with a message attached: typed one character at a time, the first newline
in a pasted block is Enter, so a pasted message was sent a line at a time. The
block goes to the field a keystroke would reach — the composer, the prompt, a
filter, the path field, a settings value — and no character in it is a binding,
so a paste cannot send, stop, turn, or quit however it is spelled. A field that
holds one line gets the block flattened, with each break a space, and the
composer keeps the breaks as breaks and normalises \r\n and a bare \r to
\n. A terminal that ignores the request degrades to the old behaviour; the
key path is still the one that submits.
With the transcript focused, the keys act on the selected block:
| Key | Does |
|---|---|
↑ / ↓, j / k | Select the previous / next block |
Enter | Open the selected card in the detail view. Nothing on a paragraph |
a / r / A | On a selected pending card: approve, reject with a reason, approve all |
Esc | Clear the selection, and put the keyboard back in the composer |
The arrows select rather than scroll, and that is a real cost: one-row scrolling
is gone, and what is left is the wheel, PageUp/PageDown, Ctrl-U/Ctrl-D
and Home/End. ↑ on an empty composer hands the keyboard to the
transcript and selects the last block, so the gesture still works from the field
people start in.
An overlay’s field owns printable keys, exactly as the composer does, so its
actions are control keys and j/k are text:
| Mode | Keys |
|---|---|
sessions | typing filters; ↑/↓ and PageUp/PageDown select, starting on the open session with New session… one Up above it; Enter opens, or goes to the landing page on the action row; Ctrl-N does the same; Ctrl-R renames; Ctrl-D or Del deletes; Esc closes |
workspaces (recent) | ↑/↓ select; Enter opens the row, or the screen the action row names; Ctrl-N opens the create screen; Esc closes |
workspaces (new) | typing is the path; Tab accepts the highlighted directory; ↑/↓ pick a candidate; Enter opens the path as typed; Esc goes back |
manage | typing filters; ↑/↓ select; Enter opens; Ctrl-N creates; Ctrl-D or Del removes; Esc closes |
workspace-missing | y creates the path’s workspace; n or Esc opens the switcher |
confirm | y accepts; n or Esc cancels |
Esc | Drop the selection |
The arrows scroll, and the field keeps them while it holds text. ↑/↓ map
to a one-row scroll from either focus, and app::update hands the key back to
the text area when the composer is non-empty — a multi-line draft is navigated
with arrows, and taking the caret away would make the field unusable. An empty
field has no caret to move, so there the arrows scroll the transcript, which is
the gesture people try first. ←/→ always belong to the caret.
The wheel goes through the same scroll_by call as the keys, so the follow lock
behaves identically however the reader scrolled. Mouse reporting is enabled by
tui::lifecycle next to raw mode and disabled before the alternate screen goes;
only wheel events are read, so text selection still works the usual way.
The trade is PageUp/PageDown: with the composer focused they reach the text
area’s own scrolling, not the transcript. Tab moves focus to the transcript
first.
There is no editor mode and no key that opens a file. The screen belongs to the
TUI for its whole life: an external program is started and left to its own
window, so there is nothing to suspend for. Opening a file is /open, a
composer command, which is why it does not appear in this table.
The landing page
A workspace with no session open — Ctrl-N, a fresh workspace, or the moment after
the last session is deleted — is the terminal’s peer of the webview’s welcome: one
centred group, the greeting and the composer together, with the header above and
the hint below.
robi · workspace · New chat
Good morning
│
│ Message robi…
│
Enter send · Esc stop · Ctrl-J newline · Tab focus · ↑↓ select
- The greeting is
greeting.ts’s three words, in--mode-askgreen. The clock is read once at startup and carried onApp, soupdateandviewstay pure functions of state and a frame test is not a clock test. - The header names the chat
New chat, which is whatsessionDisplayTitlereturns for a chat with no row.no sessionstays for the frame with no workspace at all. - No session exists yet.
Ctrl-Nused to create the row immediately, which meant a workspace opened, skimmed, and left collected an untitled session every time. NowAction::StartSessioncreates the row and submits the first message in one effect, and the outcome carries both: the session is selected and the transcript shown as soon as it exists. A create that succeeds and a send that is refused still leaves the row — the text goes back into the field and oneEnterretries it. - The composer keeps its per-session draft, so text typed on the landing page is
parked under the draft key the GUI’s
composerDrafts.tsuses for a chat with no row yet. A send that is taken drops that draft with the field. The row exists before the send is reported, so opening the new session parks the message under the landing page’s key a moment beforeComposer::take_sent(None)runs; taking the draft as well as the buffer is what keeps a sent message from coming back on the nextCtrl-N.
The composer band
The webview puts the mode, model and effort controls inside the composer, and the terminal does the same: the band’s last row carries them, on the band’s own surface, with the rail unbroken beside.
┃ src/app.rs (40-80) [shot.png, 1.2 MB]
┃ Message robi…
┃
┃ Agent · GLM-5.3 · OpenCode Go · High 214k / 1.0M · 21%
┃
The attachments row is the band’s first content row, and only when there is
something on it. A chip is what the message carries and the text is what it
says, so the chips sit above it — the same order the transcript’s user band uses,
so a sent attachment stays where the reader last saw it. name (1-10) for a text
file, [name, 1.2 MB] for an image: the weight is there because a terminal cannot
show the picture, so the number is the only evidence the bytes are real. The row
is cut with an ellipsis rather than wrapped, because a second row would move the
text being typed, and it costs Composer::height exactly one row.
Backspace on an empty field takes the last attachment off, which is the peer of
the GUI chip’s ×; /detach <name> is the spelling that takes one you name, and
/detach alone takes them all.
The facts row is boxed in by a blank row on each side. The facts say what the
next send will carry; the text is what is being typed, so a gap above stops the mode
line reading as part of the message. The gap below keeps it off the band’s bottom
edge, so it is a caption on the band rather than the field’s last line. The band is
four rows taller than the text — a padding row, the text, a blank row, the facts row,
a blank row — and App::body_height follows Composer::height.
Every span on the row carries the band’s background. The theme’s text helpers are
built for the canvas, so a theme::faint() separator here paints --bg-canvas in the
middle of a --surface band, which reads as a dark dot. The background is patched
last, the same rule rows::row follows and for the same reason: a colour helper must
not be able to punch a hole in a band.
- Clipping order: the meter goes first, then the provider, then the effort, then
the model. The mode word is never cut — it is the one fact the row exists to state
and the one
Ctrl-Tchanges. - The provider name is derived from the id’s prefix (
ProviderKind::display_name), never stored: one less field to fall out of step with the model. - Before the first settings read the row names the mode and nothing else. A guessed model id would be the band lying about what the next send carries.
- The model’s name is the catalog’s, with the
OCG -prefix where the webview’smodelDisplayNameadds one, so the two front ends label a model the same way.
The mode on the rail
| Mode | Token | Ink |
|---|---|---|
| Agent | --accent | #55a2fb |
| Ask | --mode-ask | #6fbf7a |
| Plan | --mode-plan | #e39a3c |
Two surfaces wear it: the composer’s rail and a user message’s band. A mode is what a person asked for, so it colours what they typed and what they are about to type, and it stops there. A reply is the model’s output, not a statement of mode.
Assistant prose gained a rail in T4, and that is the phase’s one layout change: it
wraps one rail and one pad narrower and starts in the same column as a user message.
Its rail is --ink-faint — the quiet tone a tool card’s rail wears — in every mode.
Per message, not per session. The band says which mode that message was typed
under, so a session cycled from plan into agent keeps a readable history. Nothing else
remembers that: the session row holds only the mode in force now. So the mode is
stamped on the user message itself (Message::mode, an opaque label
robi-core’s loop writes and never reads back). A message with no stamp — everything
written before the label existed — follows the session’s current mode, so an old
transcript is one coherent colour rather than a bare one.
Tool cards keep their own rail. A card is machinery inside the turn, not the
turn’s voice. Its waiting rail is --attention, which is now cyan (#4ec9d6)
rather than --mode-plan’s orange: with the mode’s ink on the band and the composer,
a card asking a question in a plan-mode turn would otherwise share the one colour the
turn already wears, and the question would be the least visible thing in the frame. The palette documented
--attention as a second name for that value “so ‘this needs you’ can diverge”; T4
is when it does. The animated waiting for approval dots stay --ink-muted: the cyan
is one cell and the word does the rest.
One overlay style
Every panel over the frame — the sessions list, the workspaces switcher, the manage
view, the model picker, the / and @ menu, and a confirmation — is drawn by
rows::panel and rows::row. That is not tidiness: it is what stops one surface
having a background the next one lacks.
rows::panelerases the rect (Clear, then a canvasBlock), draws oneBlock::bordered()with--ink-faintsides and a strong title, and hands back the inner rect. A panel that forgot the clear let the transcript’s empty state read through it; a panel that built its own background painted a darker rectangle than the one beside it. One function, one answer.rows::rowpaints each row’s background last, over the span’s own style, and pads to the panel’s width. A theme helper carries--bg-canvas; composed in the other order it replaces a selection with the canvas, which is the bug that made the first cut of these panels look wrong on screen.- A heading is a row too. A group label in the picker is painted on the same band as any other row, so the label does not end in a ragged darker patch.
- The completion menu is the one panel that places itself instead of centring: it belongs at the caret, one keystroke above the field. It uses the same border and fill, so the difference is its position alone.
A confirmation is a panel, in view/confirm.rs. A question that takes the keyboard
should look like it takes the keyboard, and the row it used to occupy came out of the
transcript — so asking about a compaction moved the transcript under the reader’s eyes.
It takes no layout row: App::prompt_rows counts the one-line prompt only.
The two sigils
| Prefix | Kind | Source | On submit |
|---|---|---|---|
/ | built-in command | tui/command.rs, a fixed table | the terminal acts, and the field clears |
@ | skill mention | list_skills for this workspace | sent as text, unchanged |
/lists commands and nothing else. Each one is a keybinding’s twin, or — for/attach,/detachand/open— a command whose whole value is a path no keystroke could carry; those print no key and the menu omits the separator rather than leaving one dangling. See Composer commands. A/token that names a skill is refused with the sigil to use instead:"/create-skill is a skill — type @create-skill". Two prefixes only stay distinct if each one holds its side.@lists this workspace’s user-invocable skills, marked· manualwhen the model may not invoke them and with their scope. Accepting rewrites the token in place and adds a space; the message is then sent as typed, and the runtime loads the skill from the mention.- A leading token that names nothing is refused, and the text stays exactly as it
was typed.
/nopeis never sent to the model as prose, because the terminal acting as though a command ran is worse than saying it does not exist. - Only the first token of the first line decides.
either/ormid-message, a path, and a mention the domain cannot resolve are prose;agent::skills::loads_for_textalready ignores an unknown mention, and refusing a message for what it says in the middle would be the terminal reading over the user’s shoulder. - A refusal is a
Notice::errorin the footer — an answer to a keystroke — while a failure the app observed stays on the strip. - The domain reads both sigils.
agent::skills::mention_idsmatches[ @/ ]after whitespace, so the webview keeps/and the terminal adds@, with one loader behind both.
The menu is Mode::Complete while it is open, because keys::command is a pure
function of (Mode, Focus, KeyEvent) and cannot see whether a menu is up: ↑/↓
move, Enter/Tab accept, Esc closes the menu alone (so it never becomes the
interrupt, and a running turn is not stopped by dismissing a menu), and every other
printable key goes to the field, after which the query is recomputed and the menu
closes itself when nothing matches. A picked command takes one more Enter to run,
which is why a reader typing /detach and pressing Enter twice is the documented
gesture and not a quirk: the first Enter accepts the row.
The status strip
One row between the transcript and the composer, and it is the only place a
status is shown: T3 moved sending…, stopping…, and the activity line here
from under the band, because a reader looks in one place or the terminal makes
them hunt. A blank row sits between it and the band’s top edge
(view::STRIP_GAP), so the activity line reads as a caption over the field
rather than as its first row; the row is not kept when the strip is idle, and
App::body_height adds it only while there is something to say. One thing is said at a time, in this order — the first true one wins:
| Row says | When |
|---|---|
! <message> in --danger | a robi.app.v1.error frame, or a read that failed |
! health: <reason> in --danger | the five-second store probe did not answer |
stopping… | a stop is in flight |
sending… | the submit itself has not come back yet |
Thinking for 4s / Responding for 4s + dots | a turn is running |
| nothing — the row is not drawn | idle, nothing failed |
The activity line is the webview’s ActivityLine: its words (Thinking for 4s),
its dots, and its place at the end of the transcript — which in a terminal is the
row directly above the composer. The dots sit in a fixed three-cell field, so the
text before them never shifts. An error outlives a turn and outranks it, so the
error is what stays on the row.
A notice is not a status. The footer under the band keeps the hint and the
answer to the last keystroke — nothing to send, a title is required,
stopped, one call decided — the next one is waiting — because those answer
something the reader just did and belong next to what they did it in. A failure
the app observed — a failed read, a refused decision, a turn that ended
Failed, a rename the service refused — is not an answer to a keystroke: it goes
on this strip and stays there until a read succeeds.
The progress widget
At the right edge of the same strip, a row of eight ▪ cells: the track in
--ink-faint, one head in --ink — the same leading-edge rule visual-style.md
gives the desktop shell’s running spinner. The head advances one cell every two
ticks, so a pass takes four seconds.
It is an indeterminate marquee, not a bar: a model turn reports no percentage, and a widget that filled would claim to know how much is left. It shows while a turn runs or a stop is in flight, and disappears when idle. The status is clipped to make room for it, never the other way round.
The turn footer
A closed turn ends with one gray row, Worked for 2m 5s, in --ink-muted — the
webview’s turnDuration.ts label, from the same two facts: the turn’s first
message id and its last. Both are UUIDv7s, so the timestamp leads the bytes and
the gap is the turn’s duration without the store keeping one.
A turn is open while the phase is busy or a call is still waiting on a decision, and an open turn has no footer; it gets one when it closes. A single-message turn has no gap to report, and a compaction divider is not a turn’s work, so neither gets one. The row is not a block: the arrow keys step over it. One blank row separates it from the turn — the same gap the transcript keeps between blocks — so it reads as the turn’s footnote rather than its last sentence.
The scrollbar
When the transcript is taller than its viewport, the first column of the right
gutter carries a scrollbar: a full-height track in --rule and a proportional
thumb in --ink-faint, both │ (\u{2502}) and ┃ (\u{2503}) — two weights
of the same box-drawing line, so the cells line up and a moving thumb changes
only how much ink one column carries. The thumb is at least one cell long, so a
transcript a hundred screens long still shows where it is; its position is
offset / max_offset of the travel, so the bottom row of the frame is the last
row of the transcript while following.
It is chrome in the gutter, not a column of the text. The transcript is
wrapped to content_width, so the bar costs no wrap width and no row, and the
scroll arithmetic stays exactly what state::transcript computed. Nothing is
drawn when every row fits: a bar is a statement that there is more, and a
full-height thumb on a short conversation is a lie. Nothing is drawn either when
the frame runs to the terminal’s edge, because there is no gutter to draw in.
It never brightens with focus or scroll, unlike the desktop shell’s webview scrollbar: the transcript already spends its one piece of state on the user’s blue rail, and a second thing that lights up would be a second answer to the same question.
Assistant markdown
Assistant prose is rendered as markdown, not as its source characters. The
terminal’s peer of AssistantMarkdown.tsx is tui/state/markdown.rs, which
feeds the text to tui-markdown — a
pulldown-cmark front end that returns a ratatui Text — and then wraps it into
the transcript’s own rows.
- The palette is a
StyleSheet, not a post-pass. The renderer asks for aStyleper construct and every answer is a token fromtui/theme.rs, so the desktop and the terminal cannot drift. Headings drop their#marker and carry weight instead; level 1 also underlines. Code, links, quotes, list markers, table boxes and GFM alerts each get a token. - Rows stay row-exact. A
Rowcarries styled byte ranges, so wrapping a marked-up paragraph is the samesplit_cellsthe plain path uses, and the scroll offset is still one row per visual line. - A table is cut, not wrapped. The renderer draws its box to its own width; wrapping would tear the borders apart, so an over-wide table is truncated with an ellipsis, which keeps the columns aligned.
- Syntax highlighting is off. The
highlight-codefeature pulls insyntect, which is a large build cost for one view; fenced code renders in--code-inkon--code-bgwith its language tag intact. Turning it on later is one manifest line and oneOptionscall. - Images render as their alt text, and a mermaid fence renders as its source —
T6’s rule, unchanged. There is no portable cell-accurate way to draw a diagram,
so the fence keeps its
mermaidtag and shows the source under it, and a test instate/markdown.rspins that rather than a reader discovering it.
A selected card is answered in place: a approve, r reject with a reason, A
approve every call still waiting, Ctrl-C decline them all, and Enter to read
the whole body. Where the reason field is open every printable key is text, so
Enter refuses the selected card with what was typed and Esc closes the field
and keeps the text. A card that already ran takes only Enter: an approval key on
it is answered with a notice rather than a decision.
Composer commands
/ and @ are the two prefixes, and each one is honest about what it does: see
The two sigils. A command never reaches the model; a skill mention always does.
| Command | Argument | Key | Does |
|---|---|---|---|
/models | none | Ctrl-M | the model and effort picker |
/sessions | none | Ctrl-S | the sessions overlay |
/workspaces | none | Ctrl-W | the workspace switcher |
/new | none | Ctrl-N | the landing page |
/rename | optional title | Ctrl-R | the rename prompt, or the title outright |
/mode | optional ask|plan|agent | Ctrl-T | cycle, or set that mode |
/compact | none | Ctrl-L | the confirmation, then the compact |
/help | none | ? | the help page |
/settings | none | Ctrl-, | the settings surface |
/attach | <path> | — | put a file or an image on this message |
/detach | optional name | — | take that attachment off, or every one |
/open | <path> | — | open a workspace file in the configured program |
Every command is a keybinding’s twin, or takes an argument no key could carry.
A twin is the discoverable spelling of a key a reader may not know yet, and
state/help.rs prints the pair. The three commands with a — in the Key column
are the second kind: what they need is a path, and a keystroke has nowhere to put
one. They print no key in the menu, because · with nothing after it reads as a
column that failed to render.
Arg is None, Optional or Required in the table, so /open <path>,
/attach <path> and /detach [name] are three entries and no new parser. A
command given an argument it does not take is refused by name rather than ignored.
/attach reads, /open launches, and that is the whole difference between
their path rules: /attach resolves a relative path against the workspace and
also accepts ~ and an absolute one, because reading a file the reader named is
what they asked for and the caps bound what comes back; /open refuses both,
because it hands the path to a program that will show it in the workspace the
reader is working in, and the route it mirrors refuses the same three.
/attach path:40-80 attaches those lines. The suffix is recognised only when
everything after the last : is digits or digits-dash-digits, so a:b.rs and
C:\src\x.rs keep their colons. The cap applies to what is attached rather than
to the file, which is what makes a range the answer to the 64 KiB limit on a file
that cannot be attached whole — and a range past the end clamps and reports the
lines it actually took, so a chip never claims lines the file does not have.
The help page
/help, or ? from the transcript, opens a dedicated view — the shape manage and
detail use, because a reader who opened it went somewhere on purpose. Sections, in
the order a reader meets them: Sending, Moving, Approvals, Overlays and
views, Composing, Commands, Leaving.
The list is data, and it fails the build rather than drifting. state/help.rs
holds SECTIONS of Entry { keys, what, command }, and section_of(Command) is an
exhaustive match over Command: a new keybinding is a new Command variant, so the
crate does not compile until the binding is classified. Two tests close the rest — no
key is listed twice in one section, and every entry is filed in a section
section_of gives it. A command genuinely in two places says so: Ctrl-C stops a
turn, declines a paused batch and leaves from idle, and Alt-Enter/Ctrl-J are two
spellings of one Newline.
The Commands section is generated from command::BUILT_INS, so a new command
appears on the page the moment it exists. /help is also the one command whose key
was documented and missing: the global bindings table has promised ? since T0, and
T4 finally maps it.
The guard’s honest scope: it catches an unclassified or misfiled command, not a
stale key string. keys is prose, so rebinding Ctrl-T and leaving the row alone
would pass every test. Documenting every binding is enforced; keeping every string
true is a review duty.
The settings surface
Ctrl-,, or /settings: a dedicated view like manage and help, because six
sections and thirty-six rows do not fit a panel over a chat and a reader who is
changing a credential stays a while.
The rail is the GUI’s nav. General, Model providers, Permissions, Sandbox,
MCP, Audit log — in the order src/features/settings/ lists them, so the two
front ends configure the same things in the same order. Below 60 columns the rail
is not drawn and the section rides on the title row (settings · Sandbox); h/l
still move it, so no key changes with the width. At MIN_WIDTH (40) an eighteen
column rail would leave the pane nothing to show.
Four kinds, and each answers a question the terminal cannot ask.
| Kind | Keys | Enter sends |
|---|---|---|
Text | models, numbers, URLs, the three path lists, the container’s image and runtime | the buffer, or remove(key) when it is empty |
Secret | the four credentials | the buffer, and nothing when it is empty |
Toggle | the five on/off keys plus sandbox_project_files | the flipped word |
Choice | the four effort keys (optional), sandbox_mechanism, sandbox_network (fixed) | the next value, wrapping |
Choice exists because a stored value is not always a word a reader recognises —
sandbox_network is on and means Sandboxed — and because it makes a mistake
unrepresentable: reasoning_effort is stored unvalidated and parse_effort then
fails the turn. Its optional flavour starts by leaving inherit and wraps back
to it last, which is where the delete lives. Toggle does the same job for the six
keys the service would otherwise answer with a 400.
An empty value deletes, and the default returns. SettingsService::set
refuses an empty string, so “clear this” is remove(key); the read that follows
writes the key’s default back through the store. For the container’s five fields
that is robi/agent:0.1.0, runsc, 4096, 2, 512. The GUI cannot do this:
its onBlur cannot tell “cleared” from “unchanged”, so it reverts. A terminal has
an explicit Enter, which can.
Sandbox is one section, not four. SandboxSettings.tsx has four headings; a
rail already says which page you are on, and four dividers would cost rows a
24-row terminal does not have. Its ranges are not copied here — 256–65536 MiB,
64–8192 processes, and sandbox_cpus’s ceiling is available_parallelism() on the
machine the terminal is running on. A copy would drift and would be wrong on the
host that matters, so the fields are Text and the service’s own sentence is what
a refused write shows.
A secret is one bit. The read returns its value over HTTP unless the controller
omits it; the terminal omits it one step earlier, in effects, so App never
holds a credential and no Debug of one can appear in a log. The row draws eight
bullets, the band starts empty, and re-sending a value is the only way to change
one.
A write is followed by a read. SettingSaved shows saved · <label>, then
re-issues LoadSettings and LoadModels: the surface, the facts row, and the
picker all read one store, so there is no second copy to drift. A SettingFailed
puts the service’s message in the surface’s own footer row — the status strip is
behind this view — and the re-read is what reverts the row.
The MCP section is read-only. One row per server (title, status, tool count,
from the status already loaded for the header), the two config paths, not trusted
on the project file when its hash does not match, and where each server’s log
lands. The file text is not read into the app: the terminal never becomes an
editor, and a config file is one cat away.
Two surfaces are deliberately absent. Display is a webview UI scale with no
terminal meaning; file_open_patterns and file_open_command configure /open,
which is T6. A row whose feature has not shipped is a row that lies.
The audit log
The webview’s audit log is client state: src/state/requestLog.ts, fed by the
auditRequests.ts middleware over openapi-fetch, 250 entries, memory only. The
terminal makes no HTTP at all, so its peer boundary is effects::dispatch — one
row per service call, with the call’s name, whether it failed, its duration, and
the outcome’s own one-line summary as the body.
The names are exhaustive. Action::label and ActionOutcome::summary are
matches with no _ arm, so a new effect states what it is called and what it is
worth saying before it can ship.
Three calls are skipped, for the reason the webview skips /api/v1/health:
Probe is a heartbeat, CompletePath runs once per keystroke, and SaveView
happens while the process is leaving. A table of those would be noise around the
calls a reader opened the page to see. /attach and /open are not skipped:
one reads a file the reader named and one starts a program, which is exactly what
a reader opens the table to check.
The table has no cursor of its own. The surface already has one row cursor and
one page size; a second cursor inside one section would be a mode within a mode.
Enter expands the row under the cursor, and an expansion is keyed by the row’s
sequence number, so a call arriving at the front moves the expansion down with the
row it belongs to rather than onto its neighbour.
Gaps to lift out of web_api
Four pieces of logic a controller owned and the TUI also needs. Each one is
lifted into domain (or agent), never copied: two front ends reading one
implementation is the point of the module boundary. Three landed in T4 with their
callers switched over.
| Logic | Today | Needed by | Action |
|---|---|---|---|
Attachment ingestion — build_files, classify_path, decode_base64, decode_text, matches_media_type | web_api/chat_message.rs | T6 | Done, as domain::chat_message::attachment; the handler maps AttachmentError to its statuses and keeps FileAttachmentInput as the wire DTO |
Provider-enabled model filter — provider_on + tool_capable | web_api/models.rs | T4 | Done, as adapters::model_source::pickable_models; the route calls it |
User-invocable skill list — scan + the filter | web_api/workspace.rs | T4 | Done, as agent::skills::user_invocable; the handler also moved its scan onto spawn_blocking |
| Model and effort resolution — override → mode key → fallback → default | adapters/model_source.rs::provider_settings | T4 | Done, as effective_choice; the builder and the facts row both read it |
File opener — spawn_opener, template rendering, the 10-second wait | web_api/workspace.rs | T6 (/open) | Done, as agent::workspace::{argv_for, open} with absolute_inside in agent::workspace::paths; both callers keep the same refusal when the command is unset |
The audit log is the one row T5 did not lift: the webview’s lives in the client, over HTTP, and the terminal makes no HTTP. It is a port at a different boundary — see The audit log — and there is no shared implementation to want, because the thing being recorded is different.
The docs merge (merge3, version_hash, docs_edits, the 409 path) and the
review reader stay where they are: with no docs or review surface, the TUI never
calls them, and two front ends do not need one implementation of something only
one of them uses.
Eradicated on sight: #[utoipa::path], status codes, Json wrappers,
parse_session_id, CORS, the multipart body limit, the SSE keep-alive.
ingest_multipart is the interesting one. It is not HTTP logic — it is “turn a
name and bytes into an ImageAttachment or a FileAttachment within the size
caps”. It belongs in domain/chat_message, and the controller keeps only the
multipart parse.
Persisted UI state
~/.robi/tui.json, written atomically on quit and on a change to the open
workspace or session. Not the settings store: settings are product
configuration, this is view state, and a scroll offset does not belong in a
settings screen.
Keys mirror the GUI’s client state so the two can be compared: active workspace,
open session, tool-card expansion, and the workspace recents (the GUI keeps
robi.recentWorkspaceIds in local storage for the same reason — the switcher
lists the eight most recently selected, and the service only knows creation
order). Recents are unbounded, like the GUI’s list; an id whose workspace has gone
is skipped when the list is read. Version 3 added them; an older file loads with
an empty list. Expansion is one key per call id, not
the GUI’s id, id:diff, id:answer: a terminal card is one band, so there is
nothing for the extra keys to address. Scroll position and the last mode are not
written — a rewrap invalidates a row offset, and a mode is where the reader is
rather than a fact about the session. Composer drafts are not here:
they are held in memory per session, keyed the way composerDrafts.ts keys them,
because typed text can be a secret and the GUI does not persist it either. Never
a secret otherwise. Nothing in the file is required to start: a missing or
malformed file starts at the defaults, because a bad scroll offset must not stop
the app from opening.
Dropped because the surface is gone or terminal-owned: per-document scroll, collapsed directories, docs-tray width, UI scale.
Rejected alternatives
- A TUI that calls the HTTP API. Rejected. It needs
robi-apirunning to be useful, moves every message through JSON and theChatMessageDTO, and losesrobi_core::message::Message— a strictly better type with the approval and execution status enums intact. Nothing about a same-machine second front end justifies a socket. - A TUI as a Tauri-managed sidecar. Rejected for T0–T6. Same cost as 1, plus process lifecycle. Process placement stays D3 and this page does not reopen it.
- A new crate now. Rejected, above. A feature gate isolates the dependency without moving code, and the promotion path is intact when the M8 binary arrives.
- Component architecture, with a trait per widget holding its own state.
Rejected. Immediate-mode rendering wants a pure
view; interior mutability per component is how a transcript ends up with two sources of truth. TEA is also what the roadmap calls “the Bubble Tea update loop” when it says to leave it behind — that entry is about the desktop shell, where a webview needs a reactive store. In a terminal, immediate mode plus a pureupdateis the idiomatic shape, and it is closer togopi’s behavior than the rewrites. - Rendering the transcript from
message_delta. Rejected. The bus drops a queued delta under backpressure by design, so the transcript would lose tokens. Deltas move the phase; stored rows refetch. - An in-terminal editor for the docs screen. Rejected twice over. There is
no docs screen here, and a terminal cannot match cursor, selection, and undo
without becoming an editor, which the roadmap names as a non-goal. The one
handoff is
/open, which starts the user’s own program and keeps the screen. - A TUI-only settings file. Rejected. Settings are already
SettingsServiceover~/.robi/config.tomlandsecrets.toml; a second store would fork the meaning of “default model”. tui-realmor a retained-mode framework. Rejected. It solves a problem this app does not have (reusable widgets with lifecycle) and puts a small corpus between a maintainer and a fix.
Failure modes
- Panic while the terminal is raw. Half-drawn frame, echo off, shell prompt
invisible.
ratatui::initinstalls its own panic hook;tui::lifecyclewraps it so the process log line is written first.restoreruns on the error path and onSIGTERM. - Debug tracing on stderr.
logs::init()adds a stderr layer underdebug_assertions, which overwrites the frame. The TUI initializes the file layer only. - Two front ends on one database. Two
SerializedChatRuntimes can drive two turns on one session and interleave the transcript. The per-session lease in parallel-front-ends.md is the answer:Turnrefuses a second submit and names the holder in aConflict. It also keeps the per-sessionredbhandle exclusive, which is the failure that would otherwise come first — an unreadable transcript, not an interleaved one. - A slow service call. It runs in
effects::runon the runtime and cannot block the pump. Filesystem and SQLite work is already insideagent::blocking::call; the TUI adds no new blocking path. - A drop of a burst of frames. Deliberate. The catch-up reload recovers what the render missed, and the phase does not advance past an unstored row.
- A stale
Done. Two reloads of one session land out of order. Every action carries a generation; a lower one is discarded. The GUI’s epoch rule. - An approval for a session that is not on screen. Bell, and a notice naming it. The turn is paused either way, so it cannot be missed indefinitely; T3’s session list is where it is answered.
- A decision that lands while the actor is running. The runtime refuses it
with a
Conflict, so only one decision is ever in flight:AandCtrl-Cwhile paused queue the rest, and only anawaiting_approvalframe releases the next. A refusal keeps the call listed and shows the message. - A pause restored from the database. The actor belonged to the process that
started it, so a pause found by a later process is decided by a new one: the
decision settles the call in the store and resumes the turn here. The lease in
parallel-front-ends.md narrows it rather than removing
it: a paused turn keeps its
Turnuntil the call is answered or the process exits, so a second process cannot resume it, but a crash mid-pause releases the lease and the next process may. turn_finishedclosing a live pause. The worst failure in this phase, because it degrades into the previous one: the pause opens onawaiting_approvaland a pausedturn_finishedtears it down a frame later, so a live pause is reported as a stale one.turn_pausedreads the outcome before closing anything, and one test feeds the real pause sequence — built fromEvent::AwaitingApprovalandEvent::TurnFinished { Paused }, not from hand-written JSON — and asserts the pause is still up afterwards.- A pause with nothing selected. A pause takes the selection to the waiting card, so the keys are on the thing that needs an answer. If the row has not loaded yet the selection waits for the reload, and the bell and the title have already said something is waiting.
- A send during a pause or a running turn. Both are allowed, and both do what
the webview does: the pending calls are rejected and a running turn is
interrupted with its instruction replaced. That is
ChatRuntime::submit’s behaviour, inherited rather than re-implemented. The one thing the terminal adds is clearing its own pause state as soon as the send is taken. - The selection and the follow lock. A turn streaming while the reader has
selected an older block must not yank the view to the bottom.
revealruns on selection only; growth still follows the end while nothing is selected. - The open session is deleted. The next session in the list is opened, and an
empty list lands on the greeting rather than on a dead composer: the landing page
is what “no session” looks like, and its composer creates the next row when a
message is sent. A
robi.session.v1.deletedframe takes the same path. - A list refresh that keeps the open session. A rename in another window refetches the rows and not the transcript: a refresh is not a selection change, or the reader’s scroll position would be thrown away by someone else’s edit.
- A failed probe while the store is wedged. The mark says so after three seconds; the query keeps its connection until it returns, so the timeout bounds the report and not the query. The frame stays live throughout.
- A workspace removed out from under a running session. Its rows cascade away and the actor keeps running against them: the HTTP handler has the same hole, and closing it is a domain change, not a surface one.
- A path completion on a huge directory. One
read_dirper keystroke, cut to eight candidates. The read is onspawn_blocking, so it cannot stall the pump. - A stale completion or list answer. Each carries the generation it was issued at; a lower one is dropped. Two keystrokes can be in flight together.
- A remembered session that is still listed.
tui.jsonnames the open session, so the first session listing is not a “selection change” and used to skip the read: the frame stayed empty andEnteron that row seemed to do nothing until another session had been opened and come back from. The first listing now always opens a session and reads it, andEnteron the open session issues a read of its own. - An abandoned new chat.
Ctrl-Ncreates nothing, so a reader who opens a workspace, opens a new chat, and leaves without typing has left no row behind. The session appears with the first message, in the same effect that sends it. - A first send that fails. The row exists by then, so it is kept: the session opens with its empty transcript, the text is back in the field, and the failure is on the status strip.
- A path with no workspace. The startup prompt, not a fallback. Starting the
terminal in a directory nobody opened before is the ordinary case: opening some
other workspace would show a session list the reader did not ask about, and
silently creating one would leave a row they did not want.
yandnare the two answers, and the prompt returns on the next start because the path is still the path. - Declining the prompt and then closing the switcher. The question is still
the page underneath, so
Esccomes back to it rather than to a chat frame with nothing open. Only a chosen workspace — or a created one — answers it;Ctrl-Cstill leaves. - A panel over an empty transcript. The empty state is centred exactly where
a panel lands, so a
Blockthat only tints its background left the sentence legible behind the list. The panel clears its rectangle first; the same call is the reason a list row’s highlight is a band and not just font colour. - Terminal too small. Below 40×12 render one centered message instead of a broken layout.
- No TTY (
robiin a pipe or CI). Refuse to start with a line on stderr, rather than drawing escape codes into a file. - Quit with a turn running. Confirm; on confirm,
Stopthen exit, so the transcript is left resolvable. Never drop the process mid-turn. /openwith no configured program, or a program that hangs. An unsetfile_open_commandis one message under the composer, never a fallback to another program. A configured program is waited on for at most 10 seconds and then left running, so a hanging editor cannot freeze the frame; the TUI never suspends its own terminal for it.
Testing
-
update()is a pure function, so it is tested without a terminal, without a database, and without a network — the same discipline asrobi-core. -
A
TestBackendframe test is for a notable bug, not for coverage. The UI is not snapshot-tested per view: a golden frame fails on every cosmetic change and says nothing about behaviour, and the interesting logic — grouping, wrapping, the follow lock, the card’s geometry, the keymap — lives in pure functions that are cheaper to test and fail more precisely. A frame test earns its place when a bug was visible only on screen:- an empty workspace list claimed there was no workspace when the process had opened a different database;
- a tool card needed to be a band, not a bordered box;
- user and tool bands needed rails in different colours, from the buffer, not from a glyph;
- the frame needed one gutter, which also caught the footer padding twice;
- an assistant heading and table painted their own
##and|characters instead of rendering as a document. - the transcript’s scrollbar: absent while the rows fit, one track-or-thumb cell on every body row once they do not, and a thumb that ends on the last row while following and starts on the first at the top. Frames assert on substrings and on cell colours, never on a golden file, so a token change that does not move the layout does not fail.
-
Keymap:
(Mode, Focus, Key)is a table, and one test walks it —qquits only with transcript focus,Entersends whereCtrl-JandAlt-Enterinsert a newline, no key means two things in one mode, andEscfrom each mode returns tochat. Not one test per binding. -
The lists: one test each for the filter (case-insensitive on the title the row shows), the marks (
awaitingoverrunningover idle), the recent order (a stale id skipped, a duplicate not listed twice),split_pathon~, an absolute path, a trailing separator and a bare name, and the selection clamp. -
The sessions rows: row zero is the action and names no session; the gaps around it bound the selection; a session that vanishes takes its row with it; an empty list still has the action row.
-
The landing page:
Ctrl-Ncreates nothing and shows the greeting focused on the composer;Enterissues exactly oneStartSessioncarrying the typed text and keeps it until the actor takes it; the outcome opens the session, clears the field and goes busy; a refused send keeps the row, restores the text and puts the error on the strip; a fresh workspace with no sessions and the delete-the-last case both land here; the greeting’s three bands each draw their own word, from a fixed greeting rather than the wall clock; the greeting isMODE_ASKand sits above the composer, centred. -
The startup path: a typed path with no workspace shows the prompt (
yissues oneCreateWorkspacefor that exact path,nopens the switcher and creates nothing); a path that is a workspace becomes active and leads the recents; a refresh after startup does not re-prompt.nthenEscreturns to the question with its key line,nopens it again, and choosing a row or creating one from the panel answers the question for good. A remembered session is read on the first listing,Enteron the open session still reads it, and a later refresh still does not. -
Panels and bands: the switcher’s
Manage workspaces…andNew workspace…rows are highlighted from their first cell to the panel’s inner edge (asserted on cell backgrounds, not glyphs); the panel leaves no transcript text behind it; the manage view draws its own title, list and hint with no composer; the sessions panel putsNew session…above the sessions and highlights it the same way. -
The overlays: a session frame issues exactly one
LoadSessionsand noReload; a refresh that keeps the open session selects nothing and a refresh that loses it opens the next;Ctrl-Dthennissues nothing and keeps the selection, thenyissues one delete; a rename prompt is pre-filled and sends oneRenameSession, and an empty title stays in the field with a reason; the create screen issues oneCreateWorkspacewith the typed path and keeps it on a refusal; a completion answer for text the field no longer holds is dropped by its generation. -
The strip: a failure sets
! <message>inDANGER, a successful reload clears it while a successful probe does not, the probe fires once per twenty ticks and never while one is in flight,sending…/stopping…outrank the activity line, and an error outranks both. A frame test asserts the strip is two rows above the composer band with a blank row between, that an idle app has no strip row at all and no gap for it, and that the prompt takes a row off the transcript. A blank row above the header and one under the hint are asserted too. -
The header: one word on the right, absent with no servers, and
MCP Failedwhen any server has failed; frame tests assert the label and the cell colour. A frame test asserts the row under it is one unbroken rule that starts at the gutter and ends at the header’s right edge. -
A retrieve card: the page text is absent from the frame, the hint is there, and the detail view opened from the card holds both paged lines. The card builder’s own test pins the same two facts against
cardandfull_body. -
The turn footer:
Worked for 12m 42sfrom two ids 12m 42s apart, none while a turn is open, one per closed turn when the last is still going, none for a single-message turn or a compaction divider, and a rebuild only when the last turn opens or closes — aThinking→Respondingdelta leaves the rows untouched. A test pins the one blank row between a closed turn and its footer, and another pins the blank row between the last message and the strip’s activity line. -
The composer and the pump, one test each: a send records one
Submitand keeps its text until the actor takes it; the two refusals (blank, no session) each say why inside that same test;Escstops a running turn andCtrl-Cstops or quits; and a realEventBuspublishingturn_started→message_delta→message_added→turn_finishedends idle with exactly oneLoadMessagefor the stored row and oneReloadat the end. -
Reopening a paused session: a transcript that loads with a
pending+not_startedcall selects that call’s card, andathen issues oneDecide; a call that ran without asking selects nothing; a session switch drops the previous session’s pause. A switch back to a session whose turn is still running keeps that turn busy, so its in-flight call comes back as running… and no approval opens for it. -
Selection: the arrows walk the prose and then each card; a selection survives an upsert of its own row and is dropped when its block goes;
Enteropens the detail view on a card and does nothing on a paragraph. Frames assert the background of a cell, not a glyph: a selected band, paragraph, and card are allBG_SELECTED, the fill reaches the end of the row, and the unselected rows keep their own tone. A waiting card’s rail cell isATTENTION, and a settled one goes back toINK_FAINT. The dots cycle1, 2, 3over six ticks, and the row count and scroll offset are asserted unchanged across them — the marker must not move the layout. Clearing a selection withEscreturns focus to the composer: the keys that acted on the block mean nothing once it is gone, and typing is what a chat is for. -
A pause takes the keyboard off an empty composer and leaves it alone when there is a draft: the card is selected either way, and only an empty field hands the focus over.
-
The approval keys:
ain the composer is a character andaon the transcript approves the selected card; an approval key off target says so rather than deciding; one decision in flight at a time;Aqueues the rest and the nextawaiting_approvalreleases exactly one;Ctrl-Cdeclines the batch and does notStop; and a call from a later iteration is never swept into the queue. -
EscandCtrl-C:Escunwinds the prompt, then the detail view, then the selection, then stops the turn, and never quits;Ctrl-Ckeeps stop-or-quit and gains decline-the-batch while paused. -
A send while a turn runs, and a send while a turn is paused, are both taken and recorded as one
Submit: the runtime decides what they mean. -
A tool call’s two states: a
pending+not_startedcall in a running turn isrunning…with no attention rail, no approval list and no overlay; the same call in an idle turn iswaiting for approvalwith the rail, and the two are asserted on the same fixture so a predicate that loses the phase fails both. -
The detail view renders the whole body — a two-hundred-line shell result is 203 lines, past the band’s forty-line cap — and
Escreturns with the selection where it was. -
The
/command surface:/openon a path inside the workspace issues oneOpenFile; an absolute path, a~path, and a blank argument each produce a footer error and no action. An unset command comes back asOpenFailedwith no program started, so the fallback this design rules out is a test failure, not a code review. -
Attachments:
/attach src/app.rs:40-80issues one read carrying the whole argument, because the range is the effect’s to split; a blank argument and a two-line one refuse with no read; a file already attached refuses by its source; a read that lands after a session switch is dropped; the count and the text total are enforced against what is already on the message. -
/detach: a unique basename removes one, an unknown name removes none and says so, and no argument removes all and counts them back.Backspacein an empty field removes the last; with text it still deletes a character. -
A message carrying only an attachment is sendable, and a refused send keeps both the text and the chips. The band grows one row for the chips row, and a sent attachment reads as
app.rs (40-80)in the user band beside[image, image/png]. A send that is taken drops the draft it came from: the first message of a new chat leaves nothing behind for the nextCtrl-Nto restore. -
Paste:
Event::Pastebecomes one message and never a run of keys. A block with newlines lands in the composer with its newlines, and issues nothing — no send, no stop, no quit — so a pasted message cannot be sent a line at a time. A one-line field gets the block flattened, with each break a space. The landing page gets text and creates no session. -
A card’s long line: a 4800-cell result costs a handful of rows in the transcript, its cut marked with
…, and the same call in the detail view shows all of it, wrapped to the frame with no cells lost. The heading and the subject are cut the same way, and a cut is measured in cells so a wide run cannot overflow the frame. -
A mermaid fence renders as its own source with the language on the fence line and does not panic.
-
A skill whose id collides with a built-in is listed but not selectable, and typing it still resolves to the built-in.
-
Persistence:
tui.jsonround-trips; a malformed file starts at defaults; a secret-looking key is never written. -
The debug-build stderr regression: a unit test asserts the TUI’s log initializer installs no stderr layer.
-
cargo test -p robi --features tuijoinsmake test, and clippy runs--all-featuresso the feature-gated module is still linted. -
The overlay panels and the status row are checked by frames for position and colour, not by a golden file: the MCP summary sits at the header’s right edge, a
!isDANGER,MCP OnlineisSUCCESS, and aWorked forrow isINK_MUTED. -
T4, the two sigils: prose sends; a leading
@idsends unchanged;/nope,@nope, a lone sigil,/create-skilland an argument where none is taken each refuse with their own sentence; a sigil mid-line and a command on a second line are prose. A refusal leaves the field exactly as it was and sets aDANGERfooter notice. -
T4, the two menus: the trigger (line start, after a space, inside a word, a second line, a bare sigil), the rows a query matches,
· manualand scope, and the replacement length on a multibyte line — with a test that the rewrite replaces the token, becausedelete_strruns forward from the cursor. -
T4, the rail:
mode_ink‘s three values are the tokens’; a stamped user band keeps the mode’s ink after the session has moved on, an unstamped one follows the session, and the reply under it is--ink-faintin every mode — the reply is the model’s output, so a mode colour there was the transcript claiming the assistant was in ask or plan mode. A waiting card in a plan-mode turn is cyan and notMODE_PLAN— the case the old shared value made invisible. -
T4, the keys:
Ctrl-Tcycles and issues oneSetSessionMode, and on the landing page changes the draft and issues nothing;Ctrl-Mopens the picker on the row in force;Ctrl-Lis refused while a turn runs and opens the confirmation when idle, wherensends nothing andyis oneCompact. -
T4, the help page: every entry is filed where
section_ofputs it, no key is listed twice in a section, everyBuiltInappears in the generated Commands section,/helpnames?, and the scroll stops at both ends./helpopens with no session at all;?from the composer is a character and from the transcript opens the page;PageDowninside it moves the page and leaves the transcript’s offset alone. -
T4, the band: the facts row is the band’s last row with a blank row above it — both asserted on cell contents, the rail glyph trimmed before the gap is judged empty — and a cell test pins the separator’s background to
--surface, because a--bg-canvasdot in a band is invisible to a glyph assertion. The row drops the meter, then the provider, then the effort as the band narrows, never the mode. -
T4, one overlay style: the picker and the completion menu both draw a bordered panel with a title, a panel row’s cell background is the panel’s own, and a confirmation reports
prompt_rows() == 0— it is a panel, so the transcript keeps its rows. The picker’s groups put effort first, and the test walks to the first model by kind rather than by counting rows, so a reorder fails only where it is wrong. -
T5, the table: four tests hold it against the store — every key is one
known_settingreturns, aSecretfield is exactly a secret key, everyChoiceoption is a value the service accepts, and no key appears twice. A fifth pins the six section titles toSettingsLayout.tsx’s pages. -
T5, the surface:
Ctrl-,and/settingsland on General with the rail’s six titles; the Sandbox page shows the defaults the first read wrote (OS,robi/agent:0.1.0,4096,Sandboxed,off); a 50-column frame folds the rail and names the section in the title. A stored credential draws bullets andplain(key)isNone, which is the reduction asserted rather than assumed. -
T5, the writes: the second
Entersends exactly oneSaveSettingwith the buffer appended to the stored value; an empty buffer on a secret sends nothing and on a plain key sendsNone; a toggle sends the other word and the row follows the keystroke before the store answers; aChoiceadvanceson→off; aSettingFailedputs the service’s sentence in the footer and issues oneLoadSettings; aSettingSavednames the field and re-reads models and settings.Esccloses the band, and the secondEscleaves. -
T5, the keys:
j/kmove the row,PageDownmoves a page,qdoes nothing, and the audit table’sEnterexpands the selected row, draws its body, and folds it again.Ctrl-Ccloses the settings, help, and detail views instead of quitting, which it had done from all three.
Implementation order
- Workspace dependency, feature,
[[bin]],tui/mod.rs::run, terminal lifecycle, and aTestBackendharness that renders oneParagraph. Proves the plumbing before any state exists. Msg/Action/effects::runand the input thread.state/transcript.rsandview/transcript.rsreadinglist_messages. This is T0.- Composer,
Submit, the event pump, phases and catch-up. T1, done. - The card variants, then approvals on the selected card and the detail view. T2, done. The modal shipped first and was replaced: covering the frame was the wrong answer to “a terminal has no disabled composer”, and selecting a card answers it without taking the keyboard away.
- Sessions and workspaces overlays, then the status surface. T3, done. The
confirmation and the visible prompt came with it: the reject reason had keys
but no view from T2, and one shared one-row prompt fixes both. The status
surface is a strip above the composer rather than a bar below it, plus the
header’s MCP word and the per-turn
Worked forfooter. The phase’s last pass took the startup path (robi [PATH]and the missing-workspace prompt), lifted managing workspaces out of the switcher into its own view, putNew session…first in the sessions overlay, and fixed two things only the screen showed: a highlighted action row that was not, and an empty state reading through a panel. - Lift the model-filter helper and the model/effort resolution; the mode label
and the mode-coloured rail; modes, the picker, the two sigils, the confirmation,
and the help page. T4, done. The phase shipped the facts row inside the
composer band rather than above it, added a rail to assistant prose (the one
layout change), stamped the mode on each turn’s user message so history keeps
its colour, took
--attentionto cyan now that a plan-mode turn is orange throughout, and implemented?— the one key the global bindings table had promised since T0 and nothing had mapped. - Settings surface. T5, done. Six sections in the GUI’s order, four field
kinds, and the audit table ported from the webview’s client-side request log onto
effects::dispatch, since the terminal makes no HTTP. The phase also corrected the parity map, which had never listed the GUI’s Sandbox page, and gaveCtrl-Cthe branch the keyboard table had always promised: it closes the settings, help, and detail views rather than quitting from them. - Lift the file opener and the attachment ingestion together;
/attach,/detachand/open; the chips row; the mermaid pin. T6, done. The phase replaced the planned@file picker with two commands — a menu over a per-workspace index needed anignorewalk, a relaxed@token rule, and a Cargo feature edge, and a path typed after a command is the same gesture with none of that. It also added a:start-endsuffix, without which a text file over 64 KiB could not be attached at all, andfile_open_commandto the General settings page, so a terminal-only install can configure/open.
Parallel front ends
Several Robi processes on one machine: one database, one ~/.robi. Two front
ends now run at once. Ownership is a lease per resource, plus the
handle-ownership rule that makes a session’s redb file safe to open from a
second process.
The blast radius was small. One data variant in robi-core (ToolError::Locked),
nothing moved between blobs and the chat database, and the alarming part turned
out not to be corruption but where the refusal lands: it used to arrive as
Internal server error at startup.
What this page does not cover
| Topic | Where it belongs |
|---|---|
| The turn lifecycle, approvals, tool execution order | agent-loop.md |
The per-session actor, AgentFactory, interrupt | chat-runtime.md |
| Schema, migrations, session lifecycle | persistence.md |
| The terminal front end, phases T0–T8 | tui.md |
| Session rows and what survives a restart | sessions-and-persistence.md |
| The shared read-modify-write guard | editing-tools.md |
Problem
Two processes is a normal thing to want: the desktop window open, and a terminal over SSH on the same machine.
Most of it already works. Every process builds its own AppState from
bootstrap::build_app_state, the session store is SQLite in WAL mode with a
10-second busy_timeout (adapters/sqlite/mod.rs), and startup is idempotent —
evacuate_sqlite returns early once the blob tables are gone. Concurrent reads
are fine and concurrent writers queue.
What is missing is ownership. Every guard that decides who may do what to a session lives inside one process:
| Guard | Where | Sees another process? |
|---|---|---|
Slots — one actor per session | adapters/chat_runtime.rs:291 | no |
EventBus — the front end’s event stream | domain/events/bus.rs | no |
path_lock — one lock per absolute path | agent/tools/path_lock.rs:13 | no |
So two processes can drive one session and interleave its transcript. That is the hazard tui.md names. It is not the first thing that happens.
The first failure is a read, not a write
Loading a transcript needs an exclusive open of that session’s blob file:
SqliteMessageStore::messages adapters/chat_message/store.rs:82
-> fill adapters/chat_message/store.rs:43
-> SessionBlobs::fill_results adapters/session_blobs.rs:161
-> session_db_if_present adapters/session_blobs.rs:313
-> session_db adapters/session_blobs.rs:293
-> redb Database::create adapters/session_blobs.rs:306
Database::create takes a whole-file exclusive lock, and the second process fails
it with DatabaseAlreadyOpen before reading a byte. That becomes
StoreError::Backend, then ServiceError::Unknown — reported as an internal
error, not as “that session is open elsewhere”.
Three details make it worse than it sounds:
- It hits almost every session.
fill_resultsreturns early only when a message has no tool calls, so any session that has ever stored a result fails. - The handle is never closed.
dbs(session_blobs.rs:34) is evicted only byremove_session(:245), so the first process holds the file from its first render until it exits — not just while that session is on screen. image-index.redbis not per session at all (:321,:332). It maps an image id to a session id, so no per-session rule covers it. The decision below removes it rather than deriving a lease for it.
None of this invalidates anything. redb is MVCC with atomic commits, and a failed
open leaves the last commit intact. It is a refusal, in the wrong place, with
the wrong message.
Decision
A per-session lease file, declared in domain, with two scopes; and a rule
that a session’s redb file may only be open while this process holds it.
The lease
One OS lock file per resource under ~/.robi/locks/, through
std::fs::File::try_lock (stable since Rust 1.89; the workspace floor is 1.90).
Acquiring truncates the file and writes the holder: pid, scope, database url, and
the time. A refusal reads that back and reports it.
| Resource | File | Held by | Wait |
|---|---|---|---|
Session S | locks/sessions/<S>.lock | every process with S’s blobs.redb open | none |
Workspace file P | locks/paths/<sha256(P)>.lock | an edit’s read-modify-write | 10 s |
| Startup work | locks/startup.lock | migrations, evacuation, prune, repair | 10 s |
| Settings write | locks/settings.lock | a config.toml or secrets.toml write | 10 s |
Two kinds of wait, on purpose. Ownership (a session) refuses at once: the
holder is mid-turn, so waiting only delays a decision already made. Edits wait
LOCK_TIMEOUT, ten seconds, the same order as the pool’s busy_timeout: losing a
race to another process should not fail a turn over a write that takes
milliseconds. A tool that waits out the window returns ToolError::Locked, and
the refusal is a sentence naming the path and the pid.
An acquire timeout is not a lease TTL. The wait bounds how long a caller
retries; nothing expires a held lock. The OS drops a file lock when the descriptor
closes, including on kill -9, so there is no heartbeat and no stale-lease sweep.
Two scopes, one lock:
| Scope | Held by | Covers |
|---|---|---|
Open | a front end, while a session is on screen | transcript reads and refetches, tool results, originals |
Turn | SerializedChatRuntime, from submit / decide / compact | driving a turn |
Both mean the same thing to storage — this process owns this session — so one process refcounts them onto a single OS lock. A background turn does not conflict with the window that started it.
Turn is exclusion; Open is ownership.
Turnrefuses. Submitting, deciding, compacting and deleting are rejected withServiceError::Conflict, whichweb_apialready maps to 409 (web_api/error.rs:15).Opennever refuses a transcript.ChatMessageService::list_messagestakes it best effort: when another process has the session, the read goes throughMessageStore::messages_without_results, which leavescall.resultempty, and the card rendersopen in another process (pid N). Calls that need the bytes themselves — originals, images — have no degraded form, so they are the one placeOpenproduces an error.
A paused turn keeps its Turn lease. The actor goes idle when a turn pauses
for approval, so releasing on actor exit would let a second process resume a call
the first is still showing as pending. Release when the transcript has no
unfinished tool call (robi_core::message::unresolved_turn), or when the process
exits, whichever comes first. That ordering is what makes closing a window with a
paused turn transfer ownership cleanly instead of stranding it.
The invariant
A session’s
blobs.redbmay be open only while this process holds that session’s lease.
That is what turns the lower exclusive lock from an obstacle into a check.
It needs one new operation: SessionBlobs::close_session, which drops the cached
Arc<Database> without deleting the directory — the eviction at
session_blobs.rs:245-249, without the remove_dir_all. Release the lease, call
it. Ownership then ends with the lease rather than with the process.
Enforcement sits in the service layer, not in MessageStore: the store documents
that its caller holds the lease, because a turn reads through it under Turn
while a window reads through it under Open.
Who takes what
| Caller | Scope | On refusal |
|---|---|---|
| TUI: a session is on screen | Open, for as long as it is | the degraded render, plus one footer notice |
ChatRuntime::submit / decide / compact | Turn, held in the slot | Conflict with the pid |
ChatMessageService::stop | Turn already held by the runtime | Conflict; the owner stops its own turn |
delete_chat_session | Turn | Conflict, before the unlink |
prune_excess_sessions | through delete_chat_session | the session is kept, startup continues |
reconcile_turn_displays | Turn per session, no wait | the session is skipped |
ChatMessageService::list_messages | Open, best effort | messages_without_results |
| the edit tools, the docs editor, the review reader | a path lock, 10 s | ToolError::Locked, and the card says so |
robi-api | nothing of its own; it is not a window | — |
prune_excess_sessions matches the Conflict rather than propagating it: one
session in use must not abort startup for the rest, and the workspace is only one
over its limit until a later start.
reconcile_turn_displays is the rule this page learned the hard way. A session
another process is driving must not be repaired underneath it, or startup writes
idle over a running turn. So the Turn is taken before the read and a refusal
skips the session. The owner writes its own display, and the next start repairs
the row if the owner exited first.
The walk is scoped by turn_settled, which the same write as turn_display
stores: only a pending display, written while a turn runs, leaves a row for the
next start to read. It used to read every session, and that read reached
fill_results and opened each session’s blob file; the second process then exited
1 on the first session it did not own, reporting a corrupt database. The read is
now messages_without_results, since every field the repair looks at is in the
message body, so no blob file is opened and no handle is left behind.
delete_chat_session is not cosmetic. Deleting runs remove_session_plans →
SessionBlobs::remove_session (adapters/session_plans.rs:69,
session_blobs.rs:245), which unlinks a directory another process may have open.
The lease makes that ordering explicit instead of accidental.
robi-api takes no Open of its own, which is open decision P1: the API
serves whatever session is asked for and has no window, so it cannot know what a
GUI is displaying. It inherits the transient Open inside list_messages, so a
shared database still gets the degraded transcript rather than a raw redb
refusal.
Known gap: originals and images. Those reads go straight to SessionBlobs
and take no lease, so a second process asking for one gets redb’s own
DatabaseAlreadyOpen rather than a sentence naming the pid. Both are only reached
from an expanded card in a session the other process has, so the honest fix is to
give BlobImageStore and BlobOriginals the Locks handle and take Open the
way list_messages does. Not done here.
The degraded transcript
A session another process has open still renders. MessageStore keeps the whole
message in chat_messages.body except one field: persist_results writes results
into blobs, then take_results (session_blobs.rs:515) strips call.result
before the body is serialized (chat_message/store.rs:157, :218). Content,
tool name, arguments, approval status, execution status, error, truncation and the
subagent snapshot all stay in the row.
So a read that cannot take Open renders user and assistant text plus one line
per tool call, its result replaced by open in another process (pid 1234). No
schema change and no second open. The uncontended case is unchanged: taking an
unheld Open is immediate.
That read goes through MessageStore::messages_without_results, a defaulted trait
method: SqliteMessageStore overrides it to skip fill, and every other store is
right to inherit messages because it keeps results inline.
Locks::holder(resource) reads the pid without taking the lock, for that line and
for the refusal message.
Where a refusal surfaces
Two surfaces in the terminal, and they mean different things.
Status::set_error is for a fact about the process — a failed probe, an
APP_ERROR frame. Notice is for the last thing the reader asked for, and it
sits in the footer next to the composer.
| Refusal | Surfaces as |
|---|---|
submit / decide / delete hits a held Turn | footer notice and the strip: both that chat is open in another process (pid 4812), with the draft left in the composer |
| a tool times out on a path lock | the tool card, and the strip once per call, both src/lib.rs is held by another process (turn 4812) |
a session is Open elsewhere | one footer notice on selection, and the card line above |
ServiceError::user_message drops the Conflict: prefix on the way to the
footer, so the sentence reads as prose rather than as a display impl.
The path-lock refusal is typed rather than matched by text. ToolError::Locked
is a variant whose kind() is "locked", so the TUI reads the same field the
model does and the payload the model receives is one it can branch on: wait and
retry, or choose another file. No app-level error event is published for it: the
tool result is already on screen in both front ends, and a global banner for one
contended file would be louder than the event warrants.
The image index
image-index.redb was the one redb file no session owned: it mapped an image id
to a session id, so two processes on two different sessions that both contained
images could collide on a file no session lease covered. It is also why the file
had to be held open for the whole process life, which is the exclusion this page
removes.
It is deleted, and the pointer moves nowhere: images and image_types are
already keyed by image id inside sessions/<id>/blobs.redb, so the session file
is its own index. The map existed only because the read had no session id, and
every caller has one — Message’s images list, or the route’s path.
So the ports take the session:
#![allow(unused)]
fn main() {
async fn image(&self, session: SessionId, id: &str)
-> Result<Option<(String, Vec<u8>)>, ProviderError>;
async fn store(&self, session: SessionId, id: &str, media_type: &str, bytes: Vec<u8>)
-> Result<(), ProviderError>;
}
Both are in agent/providers/images.rs. SessionBlobs::get_image takes the
session and stops looking anything up; put_image loses its second write;
IMAGE_INDEX, Inner::image_index, image_index() and forget_images are
deleted. SessionBlobs::remove_session already unlinks the directory, so cleanup
needs nothing new.
A pleasant consequence: an image id belonging to another chat now reads as
missing rather than resolving. The route used to discard the session with
let _ = session; and a comment saying no check was needed.
This breaks old images. See Compatibility.
Compatibility
Robi is used experimentally, so this page takes the break instead of writing a
migration. There is no shim for image-index.redb, no import, and no
compatibility reader.
What breaks, precisely:
| Data | After this change |
|---|---|
| Images attached to sessions created before it | Lost. The pointer that resolved GET /chat_sessions/{id}/images/{image_id} is gone, so an old bubble’s image URL 404s. |
| Tool results and tool originals in those sessions | Still work. They are keyed by {message_id}/{tool_call_id} and originals_by_sha inside the per-session file, so nothing about them depends on the global index. |
| Transcripts, titles, settings, workspaces | Unaffected. |
~/.robi/sessions/image-index.redb is left inert on disk (decision P6).
Nothing reads or writes it, and deleting it by hand is harmless. Do not
rm -rf ~/.robi/sessions to tidy up — that discards tool results for every
existing chat, which this change does not require.
No schema change: the lease is a file per session, and the image pointer is the session file itself.
Interfaces
#![allow(unused)]
fn main() {
// domain/chat_session/lease.rs — declared here, implemented in `adapters/locks.rs`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Resource {
Session(SessionId),
Path(PathBuf),
Startup,
Settings,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Scope { Open, Turn }
/// Whether to wait for a held lock. `None` for ownership, `UpTo` for an edit.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Wait { None, UpTo(Duration) }
pub struct LeaseHolder { pub pid: u32, pub scope: Scope }
pub enum LeaseError { Held { resource: String, holder: LeaseHolder }, Io(String) }
pub trait Locks: Send + Sync {
fn try_acquire(&self, resource: &Resource, scope: Scope) -> Result<LeaseGuard, LeaseError>;
fn holder(&self, resource: &Resource) -> Option<LeaseHolder>;
}
/// Take the lock, sleeping on the runtime rather than the thread.
pub async fn acquire_waiting(
locks: &dyn Locks,
resource: &Resource,
scope: Scope,
wait: Wait,
) -> Result<LeaseGuard, LeaseError>;
/// `~/.robi/locks/<relative>`; `path_key` hashes the absolute path.
pub fn lock_path(settings_dir: &Path, resource: &Resource) -> PathBuf;
// adapters/session_blobs.rs
impl SessionBlobs {
/// Drop the cached handle without touching the directory.
pub fn close_session(&self, session: SessionId) -> Result<(), String>;
}
}
Locks is sync because SessionBlobs is sync and calls it from
spawn_blocking; the waiting loop is async and sits beside it. LeaseError::conflict
is the one place a refusal becomes ServiceError::Conflict, so the TUI footer and
the 409 body are the same sentence. MemoryLocks grants everything and is what a
test passes; FileLocks is the real one.
adapters::locks::FileLocks holds Mutex<HashMap<Resource, Entry>> for the
in-process refcount, one Arc<File> per held resource, and a release hook the
composition root supplies, so the last drop calls SessionBlobs::close_session
before the kernel unlocks the file.
bootstrap::build_app_state builds one Arc<dyn Locks> and hands it to
ChatSessionService (delete, prune, reconcile), to ChatMessageService (the
best-effort Open), to SerializedChatRuntime (the Turn and the paused-turn
rule), to web_api::AppState, to the TUI, and to path_lock::init for the edit
tools.
Rejected alternatives
- A whole-database advisory lock, one process total. Today’s plan of record in tui.md. Honest, and 30 lines, but it forbids the case we want and hides the blob bug: the second process dies at startup instead of failing on its first transcript read. A fine stopgap, a wrong design.
- Move the blob tables back into the chat database. This is the change that would let reads proceed with no lease at all — WAL gives concurrent readers, leaving only “one appender per transcript”. Rejected because the adapter deliberately keeps per-session bytes out of the shared file, so a write in one session does not take the chat database lock, and because it is a rewrite of a 600-line adapter plus a migration for a property the lease already provides.
- A
redbfile per process. Two copies drift, and merging them is a worse problem than a lock. - redb’s own multi-process support. Does not exist, and upstream says there are no plans to add it (cberner/redb#932).
- A lease row with a TTL and a heartbeat. Right answer across machines, wrong one here: it needs a heartbeat task, a reclamation path and a clock. A file lock is released by the OS on crash.
- One owning server process, front ends as clients. The socket tui.md rejects, plus a process lifecycle to manage on top.
- A process-local lock (
path_lock-stylestatic). Invisible to the other process, so it prevents nothing that is not already prevented. - A lease table with
BEGIN EXCLUSIVE. Works, but a transaction held across a whole turn is a long writer on the file every other query needs, and it dies differently on restart.
Failure modes
- The holder is killed. The descriptor closes, the OS drops the lock, the next process acquires. No cleanup, no zombie lease.
- You submit to a session another process has open.
Conflictnaming the pid. The draft survives; the send is refused. - You read a session another process has open. It renders from the chat
database, with each tool result replaced by
open in another process (pid N). No error, and one footer notice when the session is selected. Opening such a card’s original output, or an image in it, reportsredb’s refusal instead: see Known gap. - You delete a session another process has open. Refused, before the unlink.
- Another process tries to resume your paused turn. Refused: the paused turn
keeps
Turnuntil it is resolved or the process exits. - redb on a filesystem where locking does not work — a network home, some FUSE mounts. redb warns and opens anyway, and that is the one path to real corruption. Probe for it at startup and refuse rather than discovering it when two processes write.
- Two processes with different
ROBI_DATABASE_URL. Per file-locations.md the default issqlite://robi.dbrelative to the working directory, so two terminals started in different directories are two different session sets. Lease files are shared but never contended. This is not “the same app twice”; say so instead of implying it is safe. - A background turn in a process whose window shows another session. The
TurnandOpenscopes refcount onto one OS lock, so it is the same owner. EventBusis per process. A rename in one window appears in the other only when that window re-lists. Stale, not wrong.path_lockis per process. Two sessions in two processes can interleave a read-modify-write on one file and lose a write, silently. Out of scope here; the fix is the sametry_lockpattern atagent/tools/path_lock.rs:13.McpHubis per process. Two processes mean two sets of MCP children. The hubs that used to sit beside it,LspHubandIndexHub, are deleted with M7.config.tomlandsecrets.tomlare last-write-wins through an atomic rename: no corruption, but two settings screens overwrite each other.- An old chat’s image 404s. Deliberate, once, per Compatibility: the pointer that resolved it was in the file this change deletes. Tool results in the same chat still render.
- A restart reconciles turn display.
ChatSessionService::reconcile_turn_displaysrepairs a session leftpending, and skips one another process holds. Display only; the owning actor rewrites it.
Build order
All six steps are in. Each landed with its tests and its page.
domain/chat_session/lease.rs+adapters/locks.rs: the resources, the refcount, the holder line, the path hash, the startup prune, the filesystem probe, and the bounded wait.SessionBlobs::close_sessionand the release hook in bootstrap, so the handle’s lifetime is the lock’s.TurninSerializedChatRuntimeincluding the paused-turn rule;delete_chat_sessionand prune behind it;reconcile_turn_displaystakingTurnper session and skipping what it cannot take. This is the step that stopped a second process failing at boot.- The global image index deleted and
BlobImageStorereading through the session file. - The degraded transcript and the
open in another process (pid N)line. path_lockacross processes, withToolError::Locked.
Documentation
| Page | Change |
|---|---|
| persistence.md | The session file is the image index; no shared image-index.redb. |
| file-locations.md | The locks/ tree replaces image-index.redb. |
| tui.md | The one-front-end rule is gone; a refusal surfaces as a notice and a card line. |
| terminal.md | Two terminals, in place of One at a time. |
| AGENTS.md | The command table no longer says one at a time. |
Open decisions
| # | Decision | Notes |
|---|---|---|
| P1 | Does robi-api take Open? | No: it serves whatever session it is asked about. The GUI therefore gets turn-level protection only until a client id or a “viewing” call exists. |
| P2 | Where the lock file lives | ~/.robi/locks/sessions/<id>.lock, not inside sessions/<id>/, so a session that stores nothing grows no blob directory and a delete never unlinks a held file. |
| P3 | Does the refusal name the scope? | The file records it; the user-facing sentence is the same either way, because a user does not distinguish Open from Turn. |
| P4 | May a second process steal an idle lease? | No. Stealing needs liveness detection, which holding the file already gives. |
| P5 | Two views of one session inside one process? | Nothing to do: one owner, so tabs and splits need no lease at all. |
| P6 | Delete the stale image-index.redb on start, or leave it? | Leave it inert is zero risk and zero code; deleting it is one line and stops it being mistaken for live state. It holds no bytes either way. |
Relationship to the terminal shell
tui.md assumed a whole-database lock and called a second front end “a
documented hazard”. The terminal now takes Open on the session it displays and
Turn through the runtime, and the hazard is a Conflict with a pid in it, or a
transcript whose tool results say which process has them. ~/.robi/tui.lock is
deleted with the code that took it.
Persistence
This page defines how Robi stores chat sessions and their messages, and how a
local HTTP API lists and edits chat sessions. It is the design doc for the
chat-session half of M2
in the roadmap. Read it before writing code in
crates/robi::{domain,adapters,web_api}.
What this page does not cover
| Topic | Where it belongs |
|---|---|
The MessageStore trait, and emit-after-persist | agent-loop.md (M0) |
| How a submitted instruction is serialized and interrupted | chat-runtime.md (M2) |
| IPC between the loop and the desktop UI | docs/src/design/core/architecture.md (M2) |
| Chat rendering | docs/src/design/shell/chat-ui.md (M2) |
| API keys and other settings | This page, under Settings. They do not go in this database. A later SettingsStore can keep secrets in the OS keychain |
| Where the app’s home directory lives | Settings use ~/.robi. The database file stays on ROBI_DATABASE_URL |
| Auto-title after a completed turn | chat-runtime.md. This page fixes that the title starts unset, and that a later write does not replace one already stored |
| The original a compressed result points at, the tool result payload, and image bytes | ~/.robi/sessions/<session_id>/blobs.redb. shell-output.md for a shell call. mcp-output.md for an MCP call. Deleting the session deletes the directory |
Problem
A chat session has to survive a process restart, and the loop has to rebuild a
turn from the transcript alone. That transcript is a sequence of Message
values. The desktop shell also needs a list — title, workspace, last used —
and those fields are not methods on MessageStore.
The HTTP API and the loop share one database. They are different ports: the
API edits chat session metadata, and the loop appends chat messages through
MessageStore.
Decision
One SQLite file, applied with sqlx migrations, behind three modules in
crates/robi. robi-core stays the loop. It gains no HTTP stack and no
database driver.
graph LR
tauri[src-tauri]
bin[robi-api]
boot[bootstrap]
web[web_api]
domain[domain]
adapters[adapters]
core[robi-core]
tauri --> boot
bin --> boot
boot --> web
boot --> adapters
web --> domain
adapters --> domain
domain --> core
adapters --> core
domain/holds the chat session model,ChatSessionRepository,ChatSessionService, the workspace model,WorkspaceRepository,WorkspaceService,ChatMessageService,ChatRuntime,SettingsStore,SettingsService, andServiceError. It performs no I/O. It may useSessionId,WorkspaceId, andMessagefromrobi-core. Canonicalizing a workspace root is I/O, so that call is a method onWorkspaceRepository.adapters/holds the pool, the migrations,SqliteChatSessionRepository,SqliteWorkspaceRepository,SqliteMessageStore,SerializedChatRuntime, andTomlSettingsStore.web_api/holds Axum routes, DTOs, and OpenAPI. A response outside 2xx is logged with its method, path, and status.AppStatecarries the workspace service, the chat session service, the chat message service, and the settings service. Handlers do not see the pool or anAgent. Blocking work — filesystem calls, synchronous SQLite, and directory walks — runs on Tokio’s blocking pool viaspawn_blocking(agent::blocking::callin the agent). A blocking call on an async worker stalls every other request onrobi-api. New tools and routes follow the same rule.bootstrap(crates/robi/src/bootstrap.rs) is the composition root. It builds the factory the runtime uses, stores that factory on the runtime, and returns the router.robi-apiand the Tauri process both call it.export-openapiprints the spec.
ChatSessionRepository is the metadata port. SqliteMessageStore is
MessageStore on the same pool. The trait keeps the two synchronous methods
from M0. Those two call block_in_place and block_on on the multi-thread
runtime. message is a keyed read of one row.
The process is single-user and binds a loopback address. There is no account
and no user_id.
Schema
Migration crates/robi/migrations/0001_chat_sessions.sql creates workspaces,
chat sessions, chat messages, and file baselines. Three migrations follow it in
the same directory: 0002 adds turn_display, 0003 drops plan_path, and
0004 adds turn_settled.
Tool originals and image bytes are not in this file. Their record shape is in
shell-output.md.
The four path-rule columns default to [].
They store session additions. The built-in secret and .git patterns are
applied in code and are not written on the row.
workspaces:
| Column | Type | Notes |
|---|---|---|
id | TEXT PRIMARY KEY | WorkspaceId, UUIDv7, minted in the adapter |
name | TEXT NOT NULL | Final path component of root. The workspace dropdown shows this |
root | TEXT NOT NULL UNIQUE | Canonical absolute directory. Opening the same directory again returns this row |
mcp_project_sha256 | TEXT | SHA-256 of <workspace>/.robi/mcp.json after the user enables that file. Null until then. See mcp.md |
created_at | TEXT NOT NULL | RFC 3339 |
Index: (created_at DESC, id DESC).
chat_sessions:
| Column | Type | Notes |
|---|---|---|
id | TEXT PRIMARY KEY | SessionId, UUIDv7, minted in the adapter |
workspace_id | TEXT NOT NULL | WorkspaceId. References workspaces(id) ON DELETE CASCADE. A chat session does not move workspaces |
title | TEXT | Null until set. At most 200 characters. The model writes it after the first turn when it is still null |
path_allow_read | TEXT NOT NULL | JSON array of regexes. [] on create. Appended to the empty built-in allow list. A more specific match lets that read through a deny |
path_allow_write | TEXT NOT NULL | JSON array of regexes. [] on create. Appended to the empty built-in allow list. A more specific match lets that write through a deny |
path_deny_read | TEXT NOT NULL | JSON array of regexes. [] on create. Appended after the built-in read denies |
path_deny_write | TEXT NOT NULL | JSON array of regexes. [] on create. Appended after the built-in write denies |
allow_hosts | TEXT NOT NULL | JSON array of hostnames. [] on create. web_fetch appends a host after the user approves that call. See web-tools.md |
mcp_allows | TEXT NOT NULL | JSON array of { "server", "tool" }. [] on create. An MCP approval that allows the tool for this session appends one pair. See mcp.md |
mode | TEXT NOT NULL | ask, plan, or agent. agent on create. Selects the tool registry and the prompt prefix |
model_config | TEXT NOT NULL | JSON object. {} on create. Optional agent, ask, and plan objects, each with optional model and reasoning_effort. An absent key inherits that mode’s setting, then the fallback setting, then the built-in model |
created_at | TEXT NOT NULL | RFC 3339 |
updated_at | TEXT NOT NULL | RFC 3339. Moves on a title change, a path-rule edit, a host-allow edit, or a model-config edit |
last_used_at | TEXT NOT NULL | RFC 3339. Set at create. Moves when a chat message is appended. A title edit and an in-place transcript update leave it alone |
turn_display | TEXT NOT NULL | idle, pending, awaiting_approval, or failed. A display summary, not a source of truth. 0 on create and written by the runtime; see below |
turn_settled | INTEGER NOT NULL | 1 when turn_display is known to match the transcript. Stored by the same write as turn_display, from whether that display is pending. Scopes the startup repair |
Index: (workspace_id, last_used_at DESC, id DESC).
chat_messages is the transcript. SqliteMessageStore reads and writes it.
GET /chat_sessions/{id}/messages reads it without taking the session actor:
| Column | Type | Notes |
|---|---|---|
id | TEXT PRIMARY KEY | MessageId |
chat_session_id | TEXT NOT NULL | References chat_sessions(id) ON DELETE CASCADE |
position | INTEGER NOT NULL | Insertion order. UUIDv7 is not a total order within one millisecond |
body | TEXT NOT NULL | serde_json of robi_core::Message without tool-call result payloads. Status, errors, and original_id stay here. The result is filled back from the session blob file on read |
Unique (chat_session_id, position).
Compaction rewrites the transcript once, after its summary call has finished:
MessageStore::replace_prefix deletes the summarized prefix rows and inserts
the summary at min(position) - 1 in a single transaction. A failure leaves the
transcript unchanged.
Image bytes, tool results, and tool originals are not SQLite rows. Each session
has ~/.robi/sessions/<session_id>/blobs.redb. Tables inside that file:
| Table | Key | Value |
|---|---|---|
originals | original id | tool call id, sha256, body, created_at |
originals_by_sha | {sha256}/{id} | original id, so a 16-hex sha prefix still resolves |
results | {message_id}/{tool_call_id} | the tool result JSON |
images | image id | raw bytes |
image_types | image id | media type |
The session file is also that session’s image index. images and image_types
are keyed by image id inside sessions/<id>/blobs.redb, so image id → session
is answered by the file the bytes already sit in, and a read takes the session id
from its caller: Message’s images list, or the route’s path.
GET /chat_sessions/{id}/images/{image_id} serves the bytes for the UI’s message
bubbles, and an id belonging to another chat reads as missing. There is no DTO,
because the transcript’s images list already carries the reference.
There used to be a shared ~/.robi/sessions/image-index.redb holding that
mapping, because the read had no session id. It was the only redb file no
session owned, so no per-session lock covered it and two processes could collide
on it while either stored an image. Images attached before it was removed 404;
tool results in the same sessions are unaffected, because they are keyed inside
the session file.
session_file_baselines is the pre-edit body of each path a chat session has
written or deleted. The edit tools insert it, so in the default build — where the
shell is the editor — nothing writes it and nothing reads it. The table stays
because the edit-tools restore path still uses it, and because dropping it is a
migration that should ride with the code that stopped reading it. See
checkpoints.md and
feature-switches.md.
| Column | Type | Notes |
|---|---|---|
chat_session_id | TEXT NOT NULL | References chat_sessions(id) ON DELETE CASCADE |
path | TEXT NOT NULL | Workspace-relative, / separators. A path outside the workspace starts with .. |
baseline | TEXT NOT NULL | UTF-8 body before this session’s first change. '' when the file did not exist |
created | INTEGER NOT NULL | 1 when the file did not exist. 0 when it did |
Primary key (chat_session_id, path). A second change of the same path does not replace the row.
Every connection sets the pragmas a local file needs: journal_mode=WAL
(skipped for in-memory databases, which refuse WAL), synchronous=NORMAL,
foreign_keys=ON, temp_store=MEMORY, cache_size=-20000,
busy_timeout=10000. foreign_keys is per connection; without it the cascade
does not run. A pool acquire timeout and a busy-lock timeout are logged on
their own: sqlite pool acquire timed out and sqlite database lock timed out.
Timestamps and ids are text. Queries use runtime sqlx::query, not the
compile-time macros.
HTTP API
Base path /api/v1. One error body, { "error": "..." }.
| Method | Path | Success | Failure |
|---|---|---|---|
GET | /health | 200 Ok | |
GET | /workspaces | 200 list | |
POST | /workspaces | 201 when the root is new, 200 when that canonical directory is already stored | 400 if root is empty, missing, or not a directory |
GET | /workspaces/{id} | 200 workspace | 404 if missing, 400 if id is not a UUID |
DELETE | /workspaces/{id} | 204 | 404 if missing, 400 if id is not a UUID. Sessions and their messages go with it |
GET | /models | 200 catalog | The tool-capable models, each { "id", "display_name", "context_window" } |
POST | /chat_sessions | 201 chat session | 400 if workspace_id is not a UUID, title is longer than 200 characters, mode is not ask, plan, or agent, model is unknown, or reasoning_effort is not low, medium, or high. 404 if that workspace does not exist |
GET | /chat_sessions | 200 list | 400 if workspace_id is present and not a UUID |
GET | /chat_sessions/{id} | 200 chat session | 404 if missing, 400 if id is not a UUID |
PATCH | /chat_sessions/{id} | 200 chat session | 404 if missing, 400 if id is not a UUID, title is invalid, a path pattern is not a regex, a host is empty or includes a scheme, port, or user info, mode is not ask, plan, or agent, model is unknown, or reasoning_effort is not low, medium, or high |
DELETE | /chat_sessions/{id} | 204 | 404 if missing, 400 if id is not a UUID. A running turn is stopped first, and the request returns after that session’s actor has exited. The session’s blobs are removed too |
POST /workspaces body is { "root" }. The adapter canonicalizes the path,
so a symlink and its target are one workspace. name is the last path
component. GET /workspaces orders by created_at DESC, id DESC.
POST body for a chat session is { "workspace_id", "title"?, "mode"?, "model_config"? }. Omitted, null, and "" are stored
as null. After a turn completes, the model writes a title when the column is
still null. A title passed on create is kept, and the model does not replace
it. That call is specified in chat-runtime.md.
mode is ask, plan, or agent. Omitted stores agent.
model_config is { "agent"?, "ask"?, "plan"? }. Each mode object is
{ "model"?, "reasoning_effort"? }. Omitted stores {}.
model must be a catalog id. reasoning_effort is low, medium, or high.
PATCH body is { "title"?, "path_allow_read"?, "path_allow_write"?, "path_deny_read"?, "path_deny_write"?, "allow_hosts"?, "mode"?, "model_config"? }.
Each field is optional. An omitted field stays as stored. A present path list
replaces that list. A present allow_hosts replaces that list. Each entry is
a hostname with no scheme, port, or user info. Inside one mode object, an
omitted key stays, a string sets that override, and null clears it. An
omitted mode object stays. updated_at moves when any field is present.
last_used_at and workspace_id stay put. An empty body returns the session
unchanged. A body Axum cannot deserialize is rejected by Axum (422), which is
separate from a title, a pattern, or a host the service refuses. Path lists
and how tools match them are in read-tools.md. Host matching
is in web-tools.md.
GET /chat_sessions orders by last_used_at DESC, id DESC. An optional
workspace_id query parameter limits the list to one workspace. There is no
cursor. Startup keeps at most 50 sessions per workspace and deletes the rest,
least recently used first. A tie keeps the newer id. Messages, baselines,
tool originals, and plan files go with each deleted session.
DTOs use strings for ids and timestamps. The domain keeps SessionId,
WorkspaceId, and DateTime<Utc>. Every chat session response also carries
has_pending_agent. It is true while that session’s actor is running, and it
is read from the runtime’s in-memory slots. It is not a column. Every response
also carries turn_display: idle, pending, awaiting_approval, or
failed. That column is a display summary. PATCH cannot set it. The runtime
writes pending when a message or a tool decision is accepted, and writes
idle, awaiting_approval, or failed when the turn finishes. Startup
recomputes it from the transcript: a waiting tool call becomes
awaiting_approval, a stored failed stays when nothing is waiting, and a
leftover pending becomes idle.
That repair only reads sessions with turn_settled = 0. Every write to
turn_display stores both columns, so a finished turn settles its own row and a
turn in flight is the only thing that leaves one to repair. 0004 backfills
turn_settled from turn_display for the same reason: only a pending row
needed repair when the migration ran. The repair reads the transcript without
tool results, so it never opens a session’s blob file.
Chat messages and the runtime
| Method | Path | Success | Failure |
|---|---|---|---|
POST | /chat_sessions/{id}/messages | 202 { "status": "accepted" } | 400 if id is not a UUID or instruction is empty or whitespace, 404 if the chat session is missing |
GET | /chat_sessions/{id}/messages | 200 transcript, in order | 404 if the chat session is missing, 400 if id is not a UUID |
GET | /chat_sessions/{id}/messages/{message_id} | 200 one message | 404 if the chat session or the message is missing, 400 if either id is not a UUID |
POST | /chat_sessions/{id}/tool_calls/{call_id} | 202 { "status": "accepted" } | 400 if an id is not a UUID or decision is not approve or reject, 404 if the chat session is missing, 409 if the actor is running |
POST | /chat_sessions/{id}/stop | 202 { "status": "stopped" } | 400 if id is not a UUID, 404 if the chat session is missing |
POST | /chat_sessions/{id}/compact | 202 { "status": "compacting" } | 400 if id is not a UUID, 404 if the chat session is missing, 409 if the actor is running, the turn is awaiting approval, or nothing is compactable |
POST of a message body is { "instruction" }. The handler returns once the
session actor has taken the instruction. POST of a tool call body is
{ "decision": "approve" | "reject", "reason"?: string }. approve runs the
call. reject refuses it; an empty reason becomes rejected by the user. The
actor then resumes the paused turn. POST /chat_sessions/{id}/stop cancels
the in-flight turn, drops any instruction that has not started, and returns
after that session’s actor has exited. An idle session is the same 202.
The actor, the factory, and the interrupt rules are in
chat-runtime.md.
GET of the list and GET of one message return each message’s id, role,
content, tool calls, and tool-call id. When the provider reported tokens for
that turn, the message also includes usage: { "input", "output", "cached" }.
input is that request’s prompt size. The list calls MessageStore::messages.
The single-message read calls MessageStore::message, which loads that row
by id. Neither takes the actor lock. A message id that is absent from that
session is 404.
ServiceError is BadRequest, NotFound, Conflict, or Unknown. The web
layer maps those to 400, 404, 409, and 500. A SQL failure, a failed settings
sync, or a provider error (including a failed image write) is logged with its
text and returned as Unknown with a fixed message, so the client never sees
driver text. Opening a workspace and creating a chat session are
logged at info with their ids. A successful settings write is logged at info
with the key and without the value.
Settings
String settings live in memory and are read on every query. ~/.robi is the
directory, from HOME. Non-secrets are config.toml. Secrets are
secrets.toml. Both are a flat table of strings. A missing file loads as
empty. The directory is created 0700, and both files are written 0600.
secrets.toml is refused when group or world can read it. A key that appears
in both files keeps the secrets copy.
SettingsStore is the port. get returns the in-memory value. set updates
that map, then rewrites both files, and restores the previous value when the
write fails. TomlSettingsStore is the first implementation. A later one can
keep secrets in the OS keychain without changing callers.
The API reads and writes only these keys. Each has a fixed secret flag. A key
that is not in this list is 400.
| Key | Secret | Default |
|---|---|---|
opencode_go_api_key | yes | None. A chat turn is 400 until this is set, when the model id carries the ocg_ prefix |
anthropic_api_key | yes | None. A chat turn is 400 until this is set, when the model id carries the ant_ prefix |
deepseek_api_key | yes | None. A chat turn is 400 until this is set, when the model id carries the dsk_ prefix |
provider_opencode_go | no | on, written on the first read when the key is absent. off leaves OpenCode Go models out of GET /api/v1/models and makes a turn that resolves an ocg_ model 400 |
provider_anthropic | no | on, written on the first read when the key is absent. off leaves Anthropic models out of GET /api/v1/models and makes a turn that resolves an ant_ model 400 |
provider_deepseek | no | on, written on the first read when the key is absent. off leaves DeepSeek models out of GET /api/v1/models and makes a turn that resolves a dsk_ model 400 |
model | no | ocg_glm-5.3, written on the first read when the key is absent. The ocg_/ant_/dsk_ prefix selects the provider (see providers-streaming.md) |
reasoning_effort | no | None. Optional low, medium, or high. Fallback when a mode has no effort |
model_ask, model_plan, model_agent | no | None. Optional model id for that mode. Empty inherits model |
reasoning_effort_ask, reasoning_effort_plan, reasoning_effort_agent | no | None. Optional effort for that mode. Empty inherits reasoning_effort |
base_url | no | None. Optional base URL for OpenCode Go and Anthropic |
deepseek_base_url | no | None. Optional DeepSeek base URL. Unset uses https://api.deepseek.com |
system_prompt | no | None. Optional text added to the system prompt after the built-in block |
max_iterations | no | 50, written on the first read when the key is absent. Model turns in one primary-agent run, from 1 to 500. Read when the session actor starts |
subagent_max_iterations | no | 50, written on the first read when the key is absent. Model turns in one explore or general child, from 1 to 500. Read when delegate starts that child |
subagent_timeout_seconds | no | 120, written on the first read when the key is absent. Seconds before an explore or general child is stopped, from 1 to 3600 |
tool_timeout_seconds | no | 120, written on the first read when the key is absent. Seconds before a shell command is killed, from 1 to 3600 |
web_search_approval | no | on, written on the first read when the key is absent. off lets web_search run without an approval card. See web-tools.md |
web_fetch_approval | no | on, written on the first read when the key is absent. off lets web_fetch run without an approval card. See web-tools.md |
brave_search_api_key | yes | None. web_search returns a tool error until this is set. See web-tools.md |
A read of an absent key that has a default calls the same write as PUT: the
value is stored in memory and both files are rewritten, then the read returns
that value. A read of an absent key with no default returns value: null and
does not write a file. An empty value is rejected. DELETE removes a
non-secret key so the next read inherits. A secret key cannot be removed.
SettingsModelSource reads these keys when a session actor starts and passes
the result to build_model. A turn that is already running keeps its model.
The server starts without an API key: health and these routes work, and the
first chat turn fails until the key the resolved provider needs is set
(opencode_go_api_key for an ocg_ model, anthropic_api_key for an ant_ one, deepseek_api_key for a dsk_ one).
| Method | Path | Success | Failure |
|---|---|---|---|
GET | /settings?key= | 200 array of settings, one per repeated key, in request order | 400 if key is missing, empty, or not in the whitelist |
GET | /settings/{key} | 200 setting | 400 if key is not in the whitelist |
PUT | /settings/{key} | 204 | 400 if key is not in the whitelist, value is empty, or the secret flag does not match the key. 500 if the files could not be written |
DELETE | /settings/{key} | 204 | 400 if key is not in the whitelist or the key is a secret. 500 if the files could not be written |
PUT body is { "value", "secret" }. GET of a stored secret returns
{ "key", "secret": true } and omits value. GET of an unset key with no
default returns { "key", "secret", "value": null }.
Configuration
Read by robi-api and, for bind and the database URL, by the Tauri process.
| Variable | Default | Meaning |
|---|---|---|
ROBI_DATABASE_URL | sqlite://robi.db?mode=rwc for robi-api. The packaged app uses robi.db in the app data directory when this is unset. pnpm tauri dev uses dev/robi.db there | sqlx SQLite URL |
ROBI_BIND | 127.0.0.1:1431, then the next free port through 1450 | Listen address. Must be loopback when set. 1430 stays with Vite. An explicit value is not scanned |
ROBI_EXTERNAL_API | unset | 1 during pnpm tauri dev skips the in-process server. The webview uses the Vite proxy. A packaged build ignores it |
Provider credentials and model choices are settings, not
environment variables. examples/simple.rs still reads OPENCODE_GO_API_KEY,
ROBI_MODEL, ROBI_BASE_URL, and ROBI_EFFORT for that one program.
make api runs the server. make dev-api restarts it when crates/robi or
crates/robi-core change, and needs cargo-watch. Swagger UI is at /docs.
make openapi-spec writes openapi/openapi.json. cargo run -p robi --bin export-openapi prints the same document.
Frontend client
The Solid shell talks to this API with openapi-fetch over types generated
from openapi/openapi.json. Every fetch aborts after 10 seconds. The event
stream is an EventSource and stays open.
| Piece | Location |
|---|---|
| Spec | openapi/openapi.json (make openapi-spec) |
| Generated types | src/api/schema.d.ts (pnpm run generate:api) |
| Client | src/api/client.ts |
| Session wrappers | src/api/sessions.ts |
| Workspace wrappers | src/api/workspaces.ts |
Web-only Vite (pnpm dev on 1430) proxies /api to 127.0.0.1:1431, so
VITE_API_BASE_URL stays empty in that mode. Run robi-api beside the UI.
pnpm tauri dev starts the API in-process and the webview asks the shell for
the bound origin before the first request. ROBI_EXTERNAL_API=1 leaves that
origin empty, so the same Vite proxy is used. The router allows CORS from the
Vite origin and from http://tauri.localhost, https://tauri.localhost, and
tauri://localhost.
The shell shows one workspace at a time. The active id is
localStorage key robi.activeWorkspaceId. /workspaces is the list: search,
sort, create, and open. An empty list
opens that page instead of the chat. The workspace dropdown in the window bar
still switches the active workspace without leaving the chat, and its
Manage workspaces… item opens that page. Adding a workspace lives there, not
in the dropdown: New workspace opens the system folder dialog in the desktop
window, and asks for a path in a normal browser.
List and create of chat sessions use that active id. Switching workspaces
clears the open session and shows the draft composer for the newly selected
workspace. Null titles render as New session.
Loop events are not REST. The shell opens one EventSource on
/api/v1/events/stream through the same proxy. Envelope, fan-out, and reconnect
rules are in events-sse.md.
Rejected alternatives
- JSON files, as gopi writes under
~/.gopi/. Rejected for the chat session store: a list query, a cascade delete, and a later index want one file with migrations. Token-usage history can share that file when it exists. - A new crate for the HTTP stack. Rejected for now. The modules are already shaped like a crate. Split when Tauri should stop compiling Axum and sqlx, or when build time says so.
- Chat session CRUD traits on
robi-core. Rejected. Core holds the four traits the loop calls.ChatSessionRepositoryis the API’s port.MessageStoreremains the loop’s port over the same tables. - Accounts, and a
user_idcolumn. Rejected. One person, one machine. CREATE TABLE IF NOT EXISTSplus column backfill. Rejected. The schema starts here, so a migration is the record of it.- A normalized tool-call table. Rejected for the transcript. The loop’s
Messagevalue is already the document. A JSONbodykeeps approval and execution status in the one structure a restart reads back. - Copying the first user message into the title. Rejected. The model writes a short title after the first turn. The stored title stays null until that write, or until create or a rename supplies one.
- Cursor pagination. Rejected for this list. Add it if a workspace grows past what one response should carry.
Failure modes
- A missing chat session is
404. The message names the id and does not distinguish “never existed” from “deleted”. - A missing workspace is
404. Creating a chat session for an unknown workspace is the same. Deleting a workspace removes its sessions and, because foreign keys are on, their messages. After the row is gone, derived files are removed: a legacy index directory under~/.robi/index/<workspace_id>/, if an older build left one. That removal is best effort: a failure is logged and the request still returns204. - A workspace root that is empty, missing, or a file is
400and is not written. - A title over 200 characters is
400and is not written. A missing title is null, not an empty string, so a later turn can tell that the model has not named the chat session yet. - Delete removes the chat session and, because foreign keys are on, its chat messages.
- Deleting a session stops its running actor first, so the
DELETErequest blocks until that actor has exited. An idle session is a no-op. The session’s blobs are removed after the row. That removal is best effort: a failure is logged and the request still returns204. Plan directories are not session data: since S9 they live in the workspace at.robi/plans/<name>/and outlive the session that wrote them. last_used_atdoes not move on rename. A title edit is not use.- In-memory pools (tests) skip WAL. File pools set it. Shared-cache memory is how adapter tests share one database across pooled connections.
- The loop’s
InMemoryStoreis whatrobi-coretests use.robi-apidrives the loop throughSqliteMessageStoreon this database. - An instruction submitted while a tool call is waiting on approval is
202. Those calls are rejected, and the instruction is appended after the rejections. - An empty or whitespace instruction is
400and is not handed to the actor.
Testing
WorkspaceServicetests use a fakeWorkspaceRepository: create stores the directory name, a second open of the same canonical root does not insert, a missing path is rejected before insert, an empty root never canonicalizes, a duplicate insert returns the existing row, list order, delete of a missing id, and a fakeWorkspaceAssetCleanerthat runs for the deleted workspace, is skipped when the row is missing, and whose failure does not fail the delete.- Workspace adapter tests use a shared-cache in-memory pool: canonical root round trip,
one row for a repeated open and for a symlink to that directory, rejection
of a missing path and of a file, list order, and delete cascading to
chat_sessionsandchat_messages. ChatSessionServicetests use a fakeChatSessionRepository: create with and without a title, empty path lists on create, a path pattern that does not compile, missing get, list filter, missing update, a null title written once and not replaced, an empty or oversized generated title refused, delete, create against an unknown workspace, and a fakeSessionDataCleanerthat is called for the deleted session, skipped for a missing one, and whose failure does not fail the delete.- Migration
0003dropsplan_path: a plan is a workspace file now, so a session no longer points at one.FilesystemSessionDatawrapsSessionBlobs::remove_session, which has its own tests over a throwaway blob root under the temp directory. SqliteChatSessionRepositorytests use a shared-cache in-memory pool: round trip, list order, title update leavinglast_used_atin place, empty path lists on create, a patch of one list leaving the others, a null title written once and not replaced, delete of a missing row, create when the workspace row is absent, and cascade fromchat_sessionstochat_messages.SqliteMessageStoretests cover append order, update in place,last_used_atmoving only on append, a single-message lookup, and a missing session.- Runtime and instruction-service tests are in chat-runtime.md.
- Settings service tests reject a key outside the whitelist, an empty value,
and a known key stored with the wrong secret flag. A read of an unset
modelwritesocg_glm-5.3through the store. A read of an unset key with no default returns an empty value and leaves the store unchanged. The TOML adapter tests round-trip both files, refuse a group-readablesecrets.toml, and check that a failed write leaves the previous value in memory.SettingsModelSourcetests check that a write between two builds is what the second build uses. cargo test -p robi-coredoes not link sqlx and does not open a socket.
Read tools
Disabled in M11. Kept for reference.
read_file,list_dir,find, andgrepare not registered; the shell reads and searches.grantandretrievestay:grantpersists an outside-workspace allow the sandbox honours, andretrievereads back a folded shell stream. The tools and the path filter below still exist behind theread-toolsCargo feature.read_codeand its tree-sitter outline are deleted; see streamlining.md.
This page defines the read-only workspace tools and the session path
filter they share. It is the design for F3.1 in the
roadmap. Approval cards stay in docs/src/design/workspace/permissions.md.
The shell sandbox stays in docs/src/design/tools/shell-tool.md. Schema and PATCH
stay in persistence.md.
What this page does not cover
| Topic | Where it belongs |
|---|---|
| Per-call approval and session grants | docs/src/design/workspace/permissions.md (M3) |
| OS sandbox for a shell tool | docs/src/design/tools/shell-tool.md (M4) |
| Compaction when a read fills the window | docs/src/design/workspace/context-management.md (M3) |
| How the actor is built | chat-runtime.md |
| Folding a source file down to its symbols | Deleted with S3. read_file is an exact window; the shell covers the rest |
Problem
The model has to read the workspace, and a read has to stay inside that
workspace. Secret files and .git should be left out unless the session
says otherwise. Those exceptions differ per chat, so they belong on the
session row. Content search should use ripgrep when it is installed, and
still work when it is not.
Decision
read_file, list_dir, find, grep, and grant live in
crates/robi/src/agent/tools/. Each read resolves its path, then asks a
PathFilter compiled from that session’s rules. The std::fs reads, and the
find and fallback grep walks, run on Tokio’s blocking pool so a slow disk
does not occupy an async worker. The same rule covers every blocking call in
robi-api; see persistence.md. grant is exclusive and
always needs approval. It appends one allow for the refused path, read or
write, including a path outside the workspace such as ../gopi. A directory
pattern matches that directory and its children. The workspace root is ^.*$,
which loses to any deny that names literals. The outside-workspace deny is
^\.\.(/|$), so ../gopi reaches further and a sibling stays denied.
The filter is four lists of Rust regexes, matched against the
workspace-relative path (/ separators, no leading slash):
| List | Effect |
|---|---|
deny_read | A matching read deny. Loses to a more specific read allow |
allow_read | A matching read allow. Outranks a deny that reaches less far, or the same point with fewer literals |
deny_write | A matching write deny. Loses to a more specific write allow |
allow_write | A matching write allow. Ranked the same way as allow_read |
When several patterns match one path, the match that ends furthest into
the path wins. If two matches end on the same byte, the pattern with more
literal characters wins. Wildcards, anchors, and groups do not add to that
count. A deny wins a remaining tie. Allowing gopi leaves gopi/.git
denied, because the .git rule reaches further. Allowing gopi/.git
reaches the same point and names more of the path, so that directory and
its children are readable. A wildcard such as ^src/.*$ does not outrank
the literal .env deny. An empty allow list means there are no exceptions.
A write allow that beats a write deny also permits the read. An open write
with no matching write deny does not. allows_read and allows_write
are the methods a later shell sandbox calls. skip_dir is true when a
non-root directory fails allows_read, so a walk does not descend into
.git.
The built-in deny patterns live in source and are always applied. Create
stores [] for all four lists. A stored list is appended after that built-in
list. Allow lists have no stored built-in patterns. path_allow_read and
path_allow_write in ~/.robi/config.toml are newline-separated paths.
The factory gives each new agent the settings store, and the filter reads
those two keys from it on every call. path_entries is appended to the
read allow list the same way. A line starting with ~/ expands to
the home directory. Each path is appended to that session’s allow list: a
file is an exact allow, and any other path is that directory and its
children. Compiling a filter for a
session adds one read allow for ~/.robi/plans/<session_id>, matched on the
workspace-relative path, including a path that starts with ... That allow
covers the directory and the markdown files in it. It does not cover another
session’s plans, the rest of ~/.robi, or writes. edit_file still cannot
change a plan. Both deny lists start from:
^\.\.(/|$)— a workspace-relative path that starts with..(^|/)\.git(/|$)(^|/)\.env$and(^|/)\.env\.[^/]+$(^|/)[^/]+\.(pem|key)$(^|/)id_rsa$and(^|/)id_ed25519$(^|/)credentials\.json$and(^|/)secrets\.json$
PATCH replaces the stored addition. Clearing a deny list leaves the
built-in patterns in place. A more specific allow still overrides a built-in
deny. A pattern that does not compile is 400 and is not stored.
Tool::execute does not receive a session id, and the trait stays as M0
fixed it. The actor builds a registry whose tools close over the session.
Each call reloads the lists, so a PATCH applies on the next tool call.
The same registry is what ModelSource::model offers the provider.
requires_approval returns allow immediately for the read tools. grant
always needs approval. A denied path, including one outside the workspace,
is a tool error on read_file, list_dir, and the start path of find and
grep. A denied file under an allowed directory is omitted from find and
grep. After grant saves an allow such as ../gopi, later calls may read
that tree. A more specific deny, such as .git, still wins.
Path arguments
Every path argument goes through workspace::resolve_path before a tool
reads it.
- A leading
~or~/expands to$HOME.~otheruseris not expanded. It is a relative path whose first component is the literal~otheruser. - A relative argument, including
./and../, joins the workspace root. - An absolute argument is used as given.
.,.., and symlinks are resolved. A path outside the canonical workspace root is kept. Its relative form starts with.., which the built-in deny matches until a more specific allow does.
A search pattern or a glob is not a path and is not expanded. The same helper is what a later shell uses for its working directory and path arguments.
Tools
| Tool | Arguments | Result |
|---|---|---|
read_file | path, optional 1-based offset, optional limit | content, start_line, end_line, total_lines. At most 32 KB. When truncated is true, next_offset is the line to pass next |
list_dir | optional path, defaulting to the workspace root | One level of name and kind (file, dir, or symlink). Denied children are omitted. .gitignore is not applied |
find | optional pattern, optional path, optional glob, optional hidden, optional no_ignore | Workspace-relative files. glob false matches a substring. glob true matches a glob. At most 50 files. Honors .gitignore and skips hidden files unless no_ignore or hidden is set. Symlinks are not followed |
grep | pattern, optional path, optional regex, optional hidden, optional no_ignore | matches of path, line, and text, plus backend |
find walks with the ignore crate using ripgrep’s defaults: .gitignore,
global gitignore, .ignore, and hidden files. hidden and no_ignore
mean the same thing they do for grep. A denied path is still omitted
when those toggles are on.
grep looks for rg on PATH. When it is there, the process is
--json, with -F unless regex is true, and -e so a pattern that
starts with - is not a flag. Ripgrep’s own defaults stay on, including
.gitignore, hidden files, and binary files. hidden adds --hidden.
no_ignore adds --no-ignore. The model cannot pass a raw argument
string.
A deny-read pattern of the form (^|/)name(/|$) becomes an rg --glob
exclusion (!**/.git/** for the default .git rule) so ripgrep does not
walk that directory. The glob is omitted when an allow_read pattern
matches a path inside that directory. Every match is still checked with
allows_read, including when no_ignore is true, so a gitignored .env
stays out of the result.
When rg is missing, or the process fails to spawn, grep walks with
the ignore crate and sets fallback_reason. The same two booleans
apply. A non-zero ripgrep status other than “no matches” is a tool error
and does not fall back. The walker skips a directory skip_dir rejects,
skips a file that contains a NUL in its first 8 KB, and clips a long line
to about 300 characters around the match.
Both backends stop at 50 matches or 32 KB of match text. truncated is
then true, and hint says to narrow the path or pattern and call again.
backend is ripgrep or builtin.
All four tools are Concurrent.
Rejected alternatives
- One allow list for both directions. A path that may be read is not the same decision as a path that may be written. The shell and the edit tools need the split.
- An immutable deny floor under the session lists. The lists are the
policy the user edits. A floor that survives
PATCHwould make “saved and modified” mean something else. Approval for protected paths is a later gate, not a second copy of these lists. - Forcing
--hiddenand--no-ignore. That throws away ripgrep’s.gitignorebehavior. The two flags are opt-in booleans instead. - A free-form
rgargument string. The model could pass a flag that reads outside the workspace. The schema exposes the two booleans. - The
ignorecrate as the only search engine. Ripgrep is faster on a large tree. The crate is the fallback so a machine withoutrgstill searches, and so that fallback honors.gitignorethe same way. - Putting the tools in
robi-core. They read the filesystem. The loop crate stays free of I/O. The trait signatures stay fixed, and the session is closed over at the actor.
Failure modes
- A path outside the workspace, including one reached through a symlink, is
path is not alloweduntil a grant allow matches it. The relative form starts with... - A denied start path is
path is not allowed, plus the workspace-relative path. Contents are not returned. - A missing file is
file not found. A directory passed toread_fileispath is a directory. A non-UTF-8 file isfile is not utf-8. - An empty
greppattern, a regex that does not compile, or a glob that does not compile isinvalid arguments. The tool does not run. $HOMEunset makes a~/argument fail before any read.- Cancellation drops the ripgrep child (
kill_on_drop) and returnscancelled. - A stored list that no longer compiles (a row written by something other
than
PATCH) fails the tool call.PATCHis what keeps new lists valid.
Editing tools
Disabled in M11. Kept for reference.
write_file,edit_file, anddelete_fileare not registered; the shell is the editing interface. The code below still runs behind theedit-toolsCargo feature. Because a shell command is opaque, no automatic baseline or checkpoint is recorded:git diffis the verification and git is the undo. See shell-tool.md, checkpoints.md, and feature-switches.md.
This page settles D5 and defines the three write tools. It is the design for F4.1 in the roadmap. The session baseline those writes record is checkpoints.md. Path rules are in read-tools.md. The approval card the loop already shows is in chat-ui.md.
What this page does not cover
| Topic | Where it belongs |
|---|---|
| Putting a hunk back, and the review window | docs/src/design/review/code-review.md (M6) |
| The shell sandbox | docs/src/design/tools/shell-tool.md (M4) |
| A saved allow for the rest of the session | grant, in read-tools.md |
Refusing a compressed shell marker in old_string, new_string, or content | shell-output.md |
Problem
The model has to change files, and a wrong change has to be visible and
reversible. A unified diff the model authors looks like a review, but it
applies to the wrong place when the file has drifted, and models emit
malformed patches. A fuzzy match has the same failure in a quieter form: the
write succeeds when old_string was not the bytes in the file.
Decision
Three tools, write_file, edit_file, and delete_file, live in
crates/robi/src/agent/tools/. Each call resolves its path the same way a read
does. All three are Exclusive.
The model edits with exact text. edit_file replaces old_string with new_string. It
does not accept a patch. write_file creates a file or replaces its whole
body. delete_file removes one file. After a successful change, the tool
returns a file diff of that change: the workspace-relative path, a unified
patch, additions, deletions, and added, deleted, or modified. The
patch tells the model what landed. It is not the edit instruction.
old_string is matched exactly, after the model’s \n is converted to the file’s
line ending (\n or \r\n). A UTF-8 BOM already on the file is kept.
replace_all defaults to false. Set, it replaces every exact match. Unset,
more than one match is an error. old_string and new_string must differ. An empty old_string
is an error that names write_file.
A path allows_write accepts runs immediately. A path the filter denies
returns NeedsApproval. That includes a built-in deny such as .env or
.git, and a path outside the workspace. The loop pauses and the existing
approval card shows Write or Delete with the path. A pending edit_file
shows the same diff card as a finished edit, from old_string and new_string, with the
same line cap. Approval is for
this call. It does not append an allow rule. The next write to that path
asks again. A lasting exception stays on grant.
execute does not receive the decision. The loop calls it only after
approval, or immediately when the filter allows the path. The write then
proceeds even though the filter still denies the path. Every other check
still applies. An argument that does not parse, or a path that does not
resolve, returns AllowImmediately so execute reports the error and the
user is not prompted.
A process-wide lock, keyed by the canonical path, is held for the whole read-modify-write. The session actor already serializes one session. The lock covers two sessions editing one file. The bytes are written to a temporary file in the same directory, then renamed.
| Tool | Arguments | Behavior |
|---|---|---|
write_file | path, content | Create the file, or replace its whole body. Parent directories under the resolved path are created |
edit_file | path, old_string, new_string, optional replace_all | Replace one exact occurrence, or every occurrence when replace_all is true |
delete_file | path | Remove one file. A directory is refused. Parent directories stay |
Rejected alternatives
- A unified diff as the edit instruction. The review preview is computed from the session baseline. The model does not have to author it. A patch applies to the wrong place when the context has drifted.
- Fuzzy replacement. Trimmed lines, folded whitespace, flexible
indentation, and similarity scoring all succeed when
old_stringwas not the bytes in the file. A miss stays an error. When the text matches only after trimming each line, the error says so. - One tool that both creates and edits. An empty
old_stringis how a model accidentally overwrites a file. Creation and full replacement arewrite_file. - Refusing a denied path with no prompt. The user can allow one write
without saving a session rule.
grantremains the way to keep the path allowed. - Saving an allow when the user approves a write. That would make one
approval a lasting exception. The next call asks again unless the model
calls
grant.
Failure modes
- An argument object that does not parse names the keys it received and any
required keys that were absent. The values stay out of the message. Every
tool uses that parser. For
edit_filethe required keys arepath,old_string, andnew_string. An emptynew_stringis a deletion and is valid; omitting the key is not. old_stringandnew_stringare identical:old_string and new_string are identical.old_stringis empty:old_string is empty; use write_file to create or replace the file.old_stringmatches nothing:old_string was not found, and a second sentence when the text matches only after trimming each line.old_stringmatches more than once andreplace_allis false:old_string matched N times.- A missing file on
edit_fileordelete_fileisfile not found. A directory ispath is a directory. A non-UTF-8 file isfile is not utf-8. - A path that resolves fails before any write, with the argument the model
passed.
$HOMEunset makes a~/argument fail the same way. - Cancellation before the read returns
cancelledand does not write. - Rejecting the approval card does not call
execute. The file stays as it was.
Checkpoints
Not recorded in M11. A shell-first session produces no automatic journal: a
shellcommand is opaque, so the harness cannot know which paths it touched, and pretending to keep a journal without intercepting writes would be worse than removing it. Git is the undo: the prompt tells the agent to verify withgit diffand offersgit stashor a branch as the way to keep a snapshot. The baseline table stays because theedit-toolsrestore path still writes it. This page describes that path. See streamlining.md and feature-switches.md.
This page defines the edit journal for F4.2 in the
roadmap. The tools that write the journal are in
editing-tools.md. The table is in
persistence.md. Putting a hunk back is
docs/src/design/review/code-review.md (M6), which is also off: review happens
in an editor or with git diff.
What this page does not cover
| Topic | Where it belongs |
|---|---|
| Approve and revert in the review window | docs/src/design/review/code-review.md (M6) |
| Git status, commit, and history | Later, with the shell tool |
| The approval card for a denied path | editing-tools.md |
Problem
An agent that can write needs a way back that does not depend on git. The
working tree may be dirty before the session starts, and a revert has to
restore what this session changed, not whatever git checkout would do.
Decision
Each chat session stores one baseline per path it changes. The baseline is
the file’s UTF-8 body before this session’s first write_file, edit_file,
or delete_file of that path. A file that did not exist stores '' and
created. The row is inserted before the rename or the remove, and a later
change of the same path does not replace it.
crates/robi/src/agent/review/ diffs that baseline against the file now on disk.
hunks_for_session returns one file diff per path: status, additions,
deletions, a unified patch, and the hunks inside it. A hunk is an id, the
baseline line start, the current line start, the old lines, and the new
lines. Line starts are 0-based. The id is the first 8 bytes of SHA-256 over
the baseline start and both line lists, hex encoded. A missing file is
status deleted: one hunk whose new lines are empty. reject puts that
hunk’s old lines back and fails when the current lines no longer match.
GET /api/v1/chat_sessions/{id}/review calls review_summaries, which
uses the same baseline read and drops a path whose additions and deletions
are both zero. That response is counts only.
GET /api/v1/chat_sessions/{id}/review/file loads one path. Its lines are a
separate list: three lines of context around each change, and a gap where
unchanged lines were skipped.
POST /api/v1/chat_sessions/{id}/review calls it. decision is approve
or reject. hunk_id limits that to one hunk; omitted, it covers the file.
Approve folds the current lines into the baseline and leaves the file.
Reject writes the baseline lines back. A created file that is fully rejected
is removed, and its baseline row goes with it.
delete_file keeps the original baseline, so a later restore writes that
text rather than an intermediate edit. If this session created the file,
delete removes it and drops the baseline row. The path leaves the session
diff. A created row whose file is already gone is omitted, so a drop that
did not land still shows no change.
Git is not read or written. Two sessions keep two baselines for the same path. Restoring one does not know about the other.
Rejected alternatives
- A shadow git repository. Revert would be
git checkoutof a snapshot. That couples the journal to git, touches files the session did not change when the snapshot is restored wholesale, and fails in a tree that is not a repository. - Storing each search-and-replace as the hunk. Overlapping edits and a change made outside the tool do not compose back to the original bytes. The baseline is the original. Hunks are computed when something asks.
- Replacing the baseline on every write. The second edit would forget the bytes from before the session started, and review could not restore them.
Failure modes
- A write that fails after the baseline row is inserted leaves the original bytes stored. The next successful write of that path keeps them.
- A non-UTF-8 file is refused before a baseline is stored, so a delete always has text to put back.
rejectreturnshunk no longer matcheswhen the current lines differ. It does not write.- Deleting the chat session deletes its baseline rows.
Shell tool
This page settles D9 and defines the shell tool. It is the design for
F4.4 in the roadmap. Path rules the file tools share are
in read-tools.md. The approval card the loop already shows is
in chat-ui.md. The roadmap’s D9 is this sandbox. The “D9” heading
in providers-streaming.md is a separate decision about
the model catalog.
What this page does not cover
| Topic | Where it belongs |
|---|---|
| Session grants and the path filter | read-tools.md |
| A host allowlist and its loopback proxy | A later mode on the same profile. The first shell has deny and unrestricted |
| Subagent shells | docs/src/design/core/subagents.md (M5) |
| A dedicated audit file beyond the transcript | Later. The tool result is the record of what ran |
| Collapsing a large stdout or stderr before the model sees it | shell-output.md. The tool still returns the capped streams |
Problem
The model has to run builds and tests. A command is the one tool that can
cat a file the read tools refused, write outside the workspace, or reach
the network. Checking the command string cannot stop that. git status and
npm test also have to work without an approval card on every call, or the
user learns to approve without reading.
Decision
One shell tool lives in crates/robi/src/agent/tools/. The OS profile it builds
lives in crates/robi/src/agent/sandbox/. robi-core does not spawn a process.
The tool is Exclusive.
Every command starts sandboxed. unsandboxed: true is the opt-out, and that
call always returns NeedsApproval. A sandboxed command that stays inside
the default profile runs immediately. There is no silent fallback, and a
denied command is not retried outside the sandbox.
ShellAccess
One tool, one schema shape, three policies. Shell::new(ctx, access) takes:
ShellAccess | Modes | Workspace | Schema |
|---|---|---|---|
ReadWrite | Agent | writable | unsandboxed, write_paths, network |
ReadOnly | Ask | read-only | read_paths only; network is deny |
PlanReadOnly | Plan | read-only, plus .robi/plans | read_paths only; network is deny |
A read-only instance sets Profile.write = WriteAccess::ReadOnly. Seatbelt
emits (allow file-read* (subpath workspace)) instead of the read-write pair,
and bubblewrap --ro-binds the workspace instead of --bind. wide_writes and
the protected_write_* lists degrade to reads. .git writes stay denied. The
private temp directory stays writable in both modes: it belongs to the call and
is deleted when it returns, and a read-only /tmp breaks innocuous tools.
PlanReadOnly adds exactly one writable root through Profile::extra_writes:
<workspace>/.robi/plans. Seatbelt emits (allow file-write* (subpath …)) for
it, and bubblewrap a recursive --bind. Its position in the policy is the
design: after the credential denies, so a workspace that is $HOME still
opens ~/.robi/plans while the rest of ~/.robi stays closed, and before
the floor, the .git write deny, and the session deny lists, so every one of
those still wins inside the directory. The allow is a directory rather than a
file, so the model may mkdir -p .robi/plans/<name> and name both files
inside it. The tool creates the top-level .robi/plans before building the
profile, because bubblewrap cannot bind a path that does not exist.
Agent mode needs no exception: WriteAccess::ReadWrite already covers
.robi/plans, so plan files stay editable after the mode switch.
The schema drops the escalation keys in read-only mode, and execute refuses
one that arrives anyway (this mode is read-only). A refused write also appends
“this mode is read-only: ask the user to switch to Agent for a change” to the
sandbox’s blocked-path hint, so the model asks rather than retrying.
The sharp edge is the build cache: cargo check, tsc, and eslint write
target/ and cache directories, so a read-only profile refuses exactly the
verification commands the prompt recommends. The decision is that Ask and Plan
do not run the build; verification is an Agent task, and the mode copy says so.
A build_write_paths setting scoped to target/ is the follow-up if those
modes ever promise verification.
The host process is the trust root. It holds API keys and computes each profile. It is not sandboxed.
flowchart TD
call["shell call"] --> flag{"unsandboxed, extra paths, or unrestricted network"}
flag -->|no| run["Seatbelt or bubblewrap"]
flag -->|yes| card["Existing approval card"]
card -->|approve| wide["That call only"]
card -->|reject| stop["Rejection result"]
run --> fail{"sandbox applied"}
wide --> fail
fail -->|no| denied["Tool error, command does not run"]
fail -->|yes| child["/bin/sh -c, own process group"]
Platform
| OS | Mechanism | When it cannot be applied |
|---|---|---|
| macOS | /usr/bin/sandbox-exec -p with a generated Seatbelt profile | The sandboxed call is refused |
| Linux | bwrap. Landlock does not hide a directory or drop the network namespace, so it is not a second layer | The sandboxed call is refused when bwrap is missing |
| Windows | No sandbox in this design | A sandboxed call is refused. unsandboxed: true still runs after approval |
This table describes the default os mechanism, which ships and stays the
default. A second mechanism runs the command in a gVisor container over the
Docker API, on macOS as well as Linux; sandbox_mechanism selects it. See
container-sandbox.md.
Filesystem
Seatbelt is last-match-wins, and the bubblewrap mounts follow the same
order: a later rule beats an earlier one. A directory grant is applied, then
the floor is applied again, so the grant cannot open an .env inside it.
Reads start allowed on /. Then these trees are denied: $HOME, /Users,
/private, /var, /tmp, and /Volumes. Then these are allowed again:
- The canonical workspace, for read and write.
- A private temp directory created for that command, for read and write.
Shared
/tmpstays denied, so the command cannot rendezvous with an unsandboxed process through a temp file. Each ancestor of an allowed path, including/privateand/Users, allows metadata reads sorealpathcan walk to that path. Those ancestors are not readable as files. /private/var/selectand/var/select, so/bin/shcan read its locale file andxcode-selectcan read thedeveloper_dirsymlink./varand/tmpthemselves may be read as symlinks, so those paths resolve. Their other children stay denied./var/selectholds only those symlinks.- The system CA bundle, which the
*.pemfloor would otherwise hide. /dev/null, for read and write.- These home trees, read-only, when the directory exists. Each mount is the
canonical absolute path, after symlink and firmlink resolution, and the
home deny uses that same resolved home:
~/.cargo/bin,~/.rustup,~/.local/bin,~/.pyenv,~/.local/share/uv,~/go/bin,~/sdk/go,~/.nvm,~/.volta,~/.fnm,~/.local/share/fnm,~/.bun,~/.local/share/pnpm, and~/Library/pnpm. - Session
allow_readgrants that resolve outside the workspace. A write grant does not become a shell write root. path_allow_readandpath_allow_writefrom general settings, read from the settings store when the profile is built. A line starting with~/is the home directory, resolved to an absolute path. Read paths open for read. Write paths open for read and write. A session write grant still does not.
Writes are the workspace and the private temp directory, and the workspace is
read-only for a ReadOnly instance. write_paths adds paths for that call
only, after approval, and the command stays sandboxed. A read-only instance does
not offer write_paths at all. Profile::extra_writes adds a read-write root
that is not the workspace: today the only user is Plan mode’s .robi/plans.
Inside the workspace, .git stays readable and write-denied. git status
works. A commit, an index update, or any other write under .git does not,
until the user approves that call. Approving write_paths that names .git
or a path inside it opens that path for the command. Approving a write of
the rest of the workspace does not. File tools already ask before they
change a path the filter denies, and .git is one of those denies. The
shell is wider than the read tools, which omit .git from the transcript.
The floor matches the read tools, and the OS profile enforces it. Case is folded. The path is canonical after symlink resolution.
.envand.env.**.pemand*.keyid_rsaandid_ed25519credentials.jsonandsecrets.json~/.ssh,~/.aws,~/.kube,~/.gnupg,~/Library/Keychains, and~/.robi
.gitignore says what git tracks. It is not copied into the floor.
Network
deny is the default, including DNS. network: "unrestricted" keeps the
filesystem profile and needs approval. Any other value is an error. A host
allowlist through a loopback proxy is a later mode on this profile. The
first shell does not start that proxy.
Environment
The child does not inherit the parent environment. These names are never
copied: DYLD_*, LD_PRELOAD, LD_LIBRARY_PATH, and any name containing
KEY, TOKEN, SECRET, PASSWORD, or CREDENTIAL.
A sandboxed command has HOME set to the real home directory so programs
can resolve os.homedir(). The filesystem profile still denies that tree.
A CLI that reads login state from the home directory cannot see it unless a
read allow covers the path. unsandboxed: true is how that command runs
with the home directory readable.
PATH is built for the call:
- These prefixes, when the directory exists:
/usr/bin,/bin,/usr/sbin,/sbin,/usr/local/bin,/opt/homebrew/bin. - Entries from the parent
PATHwhose canonical path is outside$HOMEand outside the workspace, plus entries under the toolchain trees above.., a relative entry, and anything else inside the workspace or home are dropped, so a repo cannot place its ownlsfirst. ~/.cargo/bin,~/.local/bin,~/go/bin, and~/.pyenv/shimswhen they exist, so those bins are present even when the parentPATHomitted them. Versioned Node, fnm, Volta, Bun, and pnpm bins stay onPATHonly when the parent process already listed them, and only because their tree is a read root.- Directories from
path_entries, when they exist. A line starting with~/is the home directory. Each one is also a read allow, so the sandbox can open it. Each executable in those directories is reached through a wrapper in the private temp directory. The wrapper runs the binary with its absolute path as the command name, so a packaged program that opens its own file finds that path instead of a name in the workspace.
Also set:
TMPDIR,TMP, andTEMPto the private temp directory.HOME,USER, andLOGNAME.HOMEis the real home directory. The profile still denies that tree except for the toolchain roots and the read allows.CARGO_HOMEandRUSTUP_HOMEwhen those trees were opened.GIT_CONFIG_GLOBALandGIT_CONFIG_SYSTEMare/dev/null, so Git does not open~/.gitconfigor the system config. An unsandboxed command does not set these, and Git reads the user’s files.- The parent
LANGwhen it matches a locale token. OtherwiseC.UTF-8.
An approved unsandboxed command copies the parent PATH unchanged,
including relative entries and directories inside the workspace or home,
then appends directories from path_entries that exist. The filesystem and
network profile are not applied. Credential files are then reachable
because the user approved that call. Secret names are still dropped.
Arguments
requires_approval looks only at this call. A value that does not parse, or
a cwd that does not resolve, returns AllowImmediately so execute
reports the error and the user is not prompted. The trait has no reason
channel. The summary line shows the command’s first argument, such as curl or
find. The command and its output sit in one bordered panel,
the same shape as an edit card. Closed, the panel shows the last four lines
of output. A shadow on the top edge means earlier lines were left out. Open, it shows the full command as a $ prompt, then the whole
output, wrapped, and after approval that open panel is at most four lines
tall. Earlier lines scroll. An approval starts open without that cap: the
title and buttons on the first row, and the command under them.
| Argument | Default | When it asks |
|---|---|---|
command | required | It does not ask on its own |
cwd | workspace root | It must resolve inside the workspace, sandboxed or not |
unsandboxed | false | Always, when true |
read_paths, write_paths | empty | When either list is non-empty. The command stays sandboxed |
network | deny | When unrestricted |
cwd uses the same resolution as a read: ~ expands to $HOME, a relative
path joins the workspace, and symlinks are resolved. A result outside the
canonical workspace root is an error.
The child is /bin/sh -c with the command, in its own process group, with
cwd as the working directory. The group is killed at tool_timeout_seconds
(default 120). Cancellation kills the same group.
The result is exit_code, stdout, stderr, truncated, and sandboxed.
Output is capped by LoopConfig::max_tool_result_bytes (256 KiB). When
truncated is true, the result says so. When a sandboxed command’s stderr
shows that a path was blocked, the result adds hint naming that path and
telling the model to call again.
A sandbox denial names the blocked path and tells the model to call again
with read_paths, write_paths, or unsandboxed. That call is a new
approval. The refused command is not run again. A stored path rule that is
not a literal prefix, an exact file, or ^.*$ refuses the sandboxed
command. The four allow and deny lists stay as they are. The profile is
emitted in Seatbelt’s last-match order from those lists.
Rejected alternatives
- An approval card on every command. The sandbox already bounds an ordinary build. Prompting on each one trains the user to approve without reading. The card is for the call that leaves the default profile.
- Retrying a denied command unsandboxed. OpenCode can ask for
bash:unsandboxedand run the same command again. Robi returns the denial. The model asks withunsandboxed: true, and the user sees that flag before the command runs. - Allowing commands by pattern (
git *,npm *). A pattern is not an OS boundary.cat ~/.ssh/id_rsabypasses a denied read. - A fixed
PATHof system directories only. Gopi’s list missescargo,rustup, and~/.local/bin. The constructedPATHadds those roots and still drops a workspace entry. - Inheriting the parent environment. That copies API keys and
DYLD_INSERT_LIBRARIESinto a process the model controls. - Leaving the rest of
$HOMEreadable. Codex and Claude’s sandbox-runtime read most of the home directory and deny a list. A missed credential directory is then readable. Robi denies the home directory and re-allows the workspace and a short toolchain list. - Shared
/tmpas a write root. Another process can plant a file there for the command to run. The command gets a private temp directory. - Bubblewrap plus Landlock. Landlock does not hide a path or remove the
network namespace.
bwrapis the Linux mechanism. - A Windows sandbox in this design. There is no Seatbelt equivalent to ship here. A sandboxed call is refused. An approved unsandboxed call is the path that still runs.
- Running unsandboxed when the sandbox cannot be applied. That path is the bypass. The command does not run.
Failure modes
- An empty
commandiscommand is required. unsandboxedis not a boolean, ornetworkis notdenyorunrestricted: the argument is invalid and the command does not run.cwddoes not resolve, or it resolves outside the workspace: the command does not run, and the error names the argument the model passed.- A path rule on the session that the sandbox cannot order is
path rule cannot be enforced by the sandbox, and the command does not run. - On a platform with no sandbox, or when
sandbox-execorbwrapfails, a sandboxed call is refused. It is not run outside the profile. tool_timeout_seconds(default 120), or cancellation, kills the process group. The result says the command was killed.- Output past
max_tool_result_bytessetstruncatedand keeps the prefix. - Rejecting the approval card does not call
execute.
Container sandbox
The container sandbox runs a shell command inside a long-lived gVisor
container that the harness manages over the Docker API. It is an alternative to
the OS sandbox, not a replacement for it: bubblewrap on Linux and Seatbelt on
macOS stay, and a setting chooses between the two mechanisms. Both mechanisms
run on both platforms. This page defines the runtime, the container lifecycle,
the path mapping, the settings that select a mechanism, and the retrieve
integration. It is a design for the container milestone, not a description of
shipped code.
The tool contract, its arguments, and its approval rules are in shell-tool.md. The output pipeline that collapses a long log is in shell-output.md. Path rules and the file floor are in read-tools.md.
What this page does not cover
| Topic | Where it belongs |
|---|---|
ShellAccess, read_paths, write_paths, unsandboxed | shell-tool.md. This page adds a mechanism, not an argument |
| The bubblewrap and Seatbelt profiles | shell-tool.md. Both stay and both keep working |
| What the image installs | resources/docker/agent-base.Dockerfile, versioned with the repository |
| Settings for other subsystems | persistence.md, which owns the store |
| Session grants and the path filter for file tools | read-tools.md |
| Keeping more than 256 KiB of a command’s output | A later change to the compressor. See Output and retrieve |
| Remote or multi-tenant execution | Later. This container runs on the user’s machine and trusts that machine |
Problem
The OS sandbox builds an argv from host paths: a Seatbelt policy string on macOS,
a bwrap command on Linux. It is fast, it needs no daemon, and it ships today.
It also has three costs that lead some users to want a different mechanism:
- The host is the toolchain. A sandboxed command sees the host’s
cargo,node, and Python because the profile binds~/.cargo/bin,~/.rustup, and the rest read-only. A tool installed on the host but outside those trees fails with a permission error, and a tool that is present leaks a host binary and its libraries into the command. The container puts the toolchain in the image instead, at the cost of a much larger download. - Every grant is another host mount. A session allow, a
write_pathsentry, and a settings allow each become another bind. The profile describes the user’s machine, so it differs per machine and is hard to reproduce. The container mounts only what the profile names, and starts from an empty host view. - Unprivileged user namespaces are not universal. Some Linux distributions
block them, so
bwrapfails for a reason unrelated to the command. A container runtime uses the daemon’s privileges instead.
The build caches are also per-machine. target/ survives in the workspace, but
~/.cargo/registry and ~/.cache/pip are host state that the profile does not
cover, so a fresh sandbox re-downloads crates and wheels. The container gets named
volumes for those.
None of that makes the OS sandbox wrong. It is the default because it is free, parse-free, and already working. The container is for the user who would rather install Docker once than keep a host toolchain that matches the agent’s profile, and who is willing to pay a slower, larger sandbox for a smaller host surface.
Decision
The sandbox mechanism is a setting with two values:
sandbox_mechanism | Linux | macOS |
|---|---|---|
os, the default | bwrap | sandbox-exec with a Seatbelt policy |
container | gVisor container over the Docker API | gVisor container over the Docker API, inside the daemon’s Linux VM |
Both values run on both platforms. unsandboxed: true still runs on the host
after approval, and it is the same escape hatch under either mechanism.
The container path adds no fallback. When the configured mechanism cannot be
applied, that call is refused. The error names the setting, so the user can
switch to os or fix the runtime; the command is never retried on the host.
One container serves one chat session. It is created on the first sandboxed command, reused by every later command in that session, and removed when the session is deleted, when no command has run in it for ten minutes, or when the process exits. The workspace and the cache volumes outlive it. Container lifetime records why the container is preserved rather than created per call, and Reaping when it goes.
Settings resolve per workspace: a .robi/sandbox.toml in the workspace
overrides the global settings in ~/.robi/config.toml, field by field. The
next section defines that layering.
flowchart TD
call["shell call"] --> mech{"sandbox_mechanism"}
mech -->|os| os["Seatbelt or bubblewrap argv"]
mech -->|container| pre{"preflight: daemon, runtime, image, uid"}
pre -->|no| refuse["Tool error, command does not run"]
pre -->|yes| find{"container for this session?"}
find -->|running| reuse["Reuse"]
find -->|stopped| recreate["Remove, create, start, prepare volumes"]
find -->|missing| create["Create, start, prepare volumes"]
create --> exec
reuse --> fresh{"masks or config changed?"}
fresh -->|yes| recreate
fresh -->|no| exec["create_exec + start_exec"]
recreate --> exec
exec --> stream["Demux stdout and stderr, cap each"]
stream --> done{"stream ended?"}
done -->|timeout or cancel| kill["SIGKILL the container, mark for recreate"]
done -->|yes| code["inspect_exec for the exit code"]
kill --> code
code --> out["CommandOutput"]
os --> out
Settings
Container settings follow the two-file pattern that MCP config already uses:
global settings in ~/.robi/config.toml, project settings in
<workspace>/.robi/sandbox.toml. A project file is typed TOML, not a flat string
key, because a user writes it by hand and checks it into the repository.
# <workspace>/.robi/sandbox.toml
mechanism = "container"
image = "robi/agent:1"
runtime = "runsc"
memory_mb = 8192
cpus = 4
pids_limit = 1024
network = "deny"
Every field is optional. A field that is absent inherits the next layer up, and a
field that is present replaces only itself. There is no whole-file override, so a
project that changes memory_mb keeps the user’s image.
| Field | Global key | Global default | Range |
|---|---|---|---|
mechanism | sandbox_mechanism | os | os, container |
image | sandbox_image | robi/agent:1 | repo/name[:tag] |
runtime | sandbox_runtime | runsc | a name in the daemon’s runtime map |
memory_mb | sandbox_memory_mb | 4096 | 512 to 65536 |
cpus | sandbox_cpus | 2 | 1 to the host CPU count |
pids_limit | sandbox_pids_limit | 512 | 64 to 8192 |
services | — | empty | name:port pairs; workspace file only |
service_network | — | unset | an existing Docker network; workspace file only |
env | — | empty | KEY = "value"; workspace file only |
The global keys join the existing whitelist in
domain/settings/keys.rs; the values are strings there, so they reuse
SettingsService, parse_bounded, and the on/off-style validator that
provider_* already uses. sandbox_mechanism and sandbox_project_files take
the same two-value check as web_search_approval.
sandbox_network is global only, and it is the one setting that trades the
container’s network boundary for convenience. on, the default, keeps the
sandbox: no interface unless a call is approved for egress or the workspace
declares a service. off gives every sandboxed command full outbound networking.
A workspace file cannot reach it, so a repository cannot open its own network.
services, service_network, and env have no global key. They name a specific
project’s dependencies, and a machine-wide default would be wrong for every other
workspace. They are workspace fields, and the acknowledgement below is what lets
them apply.
The workspace file is read through agent::blocking::call and cached against the
file’s modification time, so a settings read does not touch the disk on every
exec.
A project file is written by whoever wrote the repository, so it is gated: until
sandbox_project_files is on, the file is shown with the values it would apply
and none of it takes effect. The gate is not ceremony — image names a container
the harness will pull and run, and network = "unrestricted" would otherwise let a
cloned repository widen its own egress. A per-file hash acknowledgement, so one
workspace can trust a file without trusting every other, is a later refinement;
the machine-wide switch is the first version.
mechanism is the exception: it is absent from the workspace file entirely. A
repository does not get to decide whether its own code is containerised.
Resolution happens once per call, in this order:
default < global settings < workspace sandbox.toml (when sandbox_project_files is on)
Sandbox stores the resolved Config it was created with. exec
re-resolves and compares; a changed Config marks the container for recreation,
the same way a changed mask set does. A memory_mb raised mid-session therefore
applies to the next command, not to the running container.
On macOS only the mechanism differs. The settings mean the same thing; the
runtime value has to exist in the Linux VM that hosts the daemon.
The settings screen
Settings → Sandbox is a tab in src/features/settings/SandboxSettings.tsx,
registered in SettingsLayout.tsx (ITEMS) and routed at /settings/sandbox in
src/app/SolidApp.tsx. It reads and writes the eight keys through the generic
/api/v1/settings routes, so there is no sandbox-specific endpoint and no DTO:
SETTING_KEYS in src/api/settings.ts names them and getSettings loads all
eight in one request.
The tab has four sections, in the order a user meets the decision:
| Section | Control | Keys |
|---|---|---|
| Mechanism | segmented OS / Container | sandbox_mechanism |
| Container | image and runtime text fields, memory, CPU, and process-limit number fields | sandbox_image, sandbox_runtime, sandbox_memory_mb, sandbox_cpus, sandbox_pids_limit |
| Network | segmented Sandboxed / Open | sandbox_network |
| Project files | switch | sandbox_project_files |
The container fields stay editable when the mechanism is OS, so a user can
stage a configuration before switching. A segmented control and the switch write
on click and revert if the write fails; a text or number field writes on blur, and
an empty or unchanged value restores what is stored rather than clearing the key,
because the service refuses an empty value for all five.
The tab does not yet show which layer a value came from. A workspace file’s pending values, and the resolved value per layer, are still a follow-up.
Container lifetime
The container is preserved for the session. It is not created per tool call, and it is not shared across sessions.
A per-call container looks simpler and is wrong for real work. A session is a sequence of steps that build on each other: install the dependencies, then run the tests, then reproduce the failure with a debugger, then re-run the tests. Most of those steps only make sense on top of the state the earlier step created.
Two costs decide it:
- State that has no other home.
pip install requests,apt-get install jq, andnpm install -gwrite inside the container. Nothing mounts those paths, so a per-call container discards them and the next call installs them again. The same applies to generated code outside the workspace, a warmed database, and a background watcher the agent started on purpose. - Iteration speed. A dependency install plus a cold start is minutes. Repeating
it on every
shellcall turns a five-step debugging session into a half-hour one, and it burns the model’s context on output the agent already read.
Preserving the container makes the session reproducible in the wrong direction: two commands that ran ten minutes apart saw different environments. That is the tradeoff, and it is bounded — the writable layer belongs to one container, one session, and it is destroyed when the container is.
The root filesystem is therefore writable, through the container’s own overlay
layer. readonly_rootfs: true would make pip install fail with Read-only file system, which is the opposite of the goal. The image stays immutable — a write
lands in the container’s layer, not in the image — and the layer is discarded
with the container, so a package installed to a system path is absent in the
next session.
| State | Next exec, same session | Container recreated | New session |
|---|---|---|---|
| Workspace files | kept (bind mount) | kept | kept |
Package caches under ~/.cargo and ~/.cache | kept (volumes) | kept | kept |
| Installed packages, system library changes | kept (container layer) | lost | lost |
/tmp contents, running background processes | kept (tmpfs, live) | lost | lost |
cd, exported variables, shell history | lost — every exec is a new /bin/sh | lost | lost |
The last row is the one that surprises people. “Container state” means the
filesystem and long-running processes, not the shell. An exec is a new process
with the constructed environment each time, so a command that does cd ../elsewhere affects nothing after it returns. A workflow that needs shell state
writes a script into the workspace and runs it, or starts one background process
and talks to it.
The container is recreated, and the layer with it, when three things change:
- the path mask set, because a new secret file must be hidden;
- the resolved
Config, because memory, cpus, and the image are create-time properties; - the container is gone, because the daemon restarted or the reaper removed it.
The first two are cheap to trigger by accident: adding a .env, or bumping
memory_mb in sandbox.toml, throws away the installed packages and costs a
reinstall. The cache volumes make that reinstall offline and fast — pip install
reads ~/.cache/pip and cargo build reads ~/.cargo/registry — which is why
the caches are separate volumes rather than part of the layer.
To get a clean environment mid-session, remove the container. The next exec
creates a fresh one from the image; the workspace and the cache volumes survive.
Broker and preflight
The sandbox talks to the Docker daemon through bollard over
/var/run/docker.sock. It does not spawn docker, runsc, or any other CLI.
The daemon is reached with Docker::connect_with_local_defaults.
new fails before a command runs when any of these is false:
| Check | Call | Failure |
|---|---|---|
| The daemon answers | docker.info() | SandboxError::Daemon |
| The configured runtime is registered | the Runtimes map in SystemInfo | SandboxError::RuntimeMissing |
| The agent image exists | docker.inspect_image(config.image) | Pull it with create_image, then fail on a pull error |
| The workspace is a directory | canonicalize | SandboxError::Workspace |
The egress network and the named volumes are created on first use. A failure
in any check becomes sandbox could not be applied: <reason>, and the command
does not run.
Container specification
HostConfig field | Value | Reason |
|---|---|---|
runtime | config.runtime, runsc by default | gVisor handles the container’s syscalls in user space instead of passing them to the host kernel |
memory, memory_swap | config.memory_mb, 4 GiB by default | A build that exceeds the limit is OOM-killed instead of taking the host down |
nano_cpus | config.cpus, 2 by default | Bounds a runaway parallel build |
pids_limit | config.pids_limit, 512 by default | Bounds a fork bomb |
cap_drop | ["ALL"] | A sandboxed command needs no Linux capability |
cap_add | ["CHOWN"] | The one-time setup exec hands the root-owned cache volumes to the host user, and cap_drop: ALL would take CAP_CHOWN from it too. A non-root exec gains nothing: no-new-privileges blocks the setuid and file-capability routes |
security_opt | ["no-new-privileges:true"] | A setuid binary in the image cannot raise privilege |
readonly_rootfs | false | The container’s own overlay layer accepts pip install and apt-get; the image is untouched, and the layer dies with the container. See Container lifetime |
network_mode | "none", or "bridge" when sandbox_network is off | none means no interface and no DNS. bridge is the default bridge plus the daemon’s NAT, which is what “fully networked” means |
init | true | Reaps orphans left by an exec, so the container does not accumulate zombies |
tmpfs | /tmp, nosuid,size=1g | A private temp directory that is not a host bind |
log_config | driver none | The stream is the record; the daemon keeps no second copy |
restart_policy | no | A killed container is recreated deliberately, not restarted under the same state |
user | <uid>:<gid> | See User mapping |
The four settings-backed fields are the ones a project may tune. Everything else
is fixed: a sandbox.toml cannot add a capability, mount the host, or reach the
network outside the egress approval. In particular it cannot add CHOWN to a
setting: the capability set is code, not configuration.
A writable root filesystem is not a way out of the sandbox:
no-new-privileges, UID mapping, and the read-only mounts are unchanged. It only
lets a command change the environment that later commands in the same session
see.
The container command is sleep infinity. The container exists to hold the
mounts, the namespaces, and the home volume; every command arrives through
exec.
User mapping
Run the container as the invoking user, not as root:
#![allow(unused)]
fn main() {
let uid = nix::unistd::getuid().as_raw();
let gid = nix::unistd::getgid().as_raw();
let user = format!("{uid}:{gid}");
}
Set ContainerCreateBody.user and each CreateExecOptions.user to that string.
A bind-mounted workspace is owned by the host user, so a file the command
creates is owned by that user and the user can delete it without sudo. Under
runsc, the container’s UID maps to the same numeric UID on the host for a bind
mount; gVisor isolates the kernel, not the file owner.
Named volumes are the exception. Docker creates a new volume owned by
root:root, and a container running as the host UID cannot write it. After
creating the container, run one preparation exec as 0:0:
chown -R <uid>:<gid> /home/agent
The workspace is deliberately outside that chown: it is the user’s directory
and the preparation step must not change its ownership.
On macOS the daemon shares its files into the VM instead of bind-mounting them,
and the shared filesystem presents them as owned by the macOS user. The chown
above still applies to the volumes, which are native filesystems inside the VM.
Mounts
A container starts from the image’s filesystem. The host is not visible unless
it is mounted, so a deny outside every mount needs no rule: the path is absent.
This is the main simplification over bwrap, which starts from the host
filesystem and hides most of it.
| Profile field | Container path | Mode |
|---|---|---|
workspace | /workspace | rw for every mode. Ask and Plan are meant to be read-only; see the limitation below |
workspace/.git | /workspace/.git | ro. A nested mount over the workspace; Docker applies the longer destination last |
temp_dir | not mounted; /tmp is a tmpfs | rw, private to the container |
extra_writes, wide_writes, protected_write_*, session write grants | /workspace/<relative> inside the workspace, the same absolute path outside | rw. A nested mount over a read-only workspace, used by Plan mode’s .robi/plans |
wide_reads, protected_read_*, session read grants | /workspace/<relative> inside the workspace, the same absolute path outside | ro |
toolchain_reads | not mounted | The image supplies the toolchain |
deny_reads, deny_writes inside a mounted tree | masked | See below |
| Everything else on the host | absent | No mount, no path |
Limitation. Ask and Plan are read-only on the OS sandbox. The container
mounts /workspace read-write for those modes too. The mount table is fixed
at container creation, and a mode switch in the same session reuses that
container, so a Plan-mode mount left Agent mode unable to delete ordinary
source files (Read-only file system). Until the container is recreated when
WriteAccess changes, every mode gets the Agent write grant. .git and the
secret-file masks stay read-only.
Absolute paths outside the workspace are mounted at the same path so a command
that names one still resolves. Inside the workspace the path changes: the host
repository is /workspace, not its host path.
cwd is rebased the same way, so the tool’s existing cwd argument keeps
working: cwd: "crates/robi" runs in /workspace/crates/robi. A command that
names no cwd runs at the mount root, which is why a session never needs
cd /workspace — the prompt states that once and forbids the cd, and the tool
result reports cwd so the model can see where it ran rather than guess.
The two rules differ by mechanism. The <cwd> prompt block carries the host
path, which the container does not have, so the container prompt omits it and the
built-in rules state /workspace instead. Under Seatbelt and bubblewrap the host
path is correct and the block stays.
toolchain_reads is intentionally dropped. Mounting ~/.cargo/bin into a
different image gives a binary that links against host libraries the image does
not have, and it reintroduces the host-toolchain problem. If a project needs a
tool, it belongs in the image or in the project’s own dependencies.
The floor and the .git write deny are the one place a deny needs a mount. The
host walks the workspace with the same floor_files function bwrap uses, and
emits one read-only /dev/null bind per match:
source: /dev/null target: /workspace/.env read_only: true
A directory deny uses an empty read-only tmpfs at the target instead. The walk
skips target, node_modules, dist, and vendor, as it does today.
Two limits apply:
- Count. More than 2,000 masks makes container creation slow and is almost
always a mistake. Above the limit the command is refused with
workspace needs N path masks, above the 2000 limit; the user can delete the files, add an explicit allow, or switch the workspace tomechanism = "os". - Time. The mask set is captured when the container is created.
execrecomputes it with a cheap walk and compares the result. If a.envappeared since the last call, the container is recreated before the command runs, so a file created mid-session is not readable through a stale mount.
On macOS a mask still works, because the workspace is inside a shared root by definition. An allow outside every shared root cannot be mounted, so it is refused rather than dropped; see macOS.
A deny that falls outside every mounted tree is already unreachable and is skipped.
Caches
Three concerns drive the volume layout: the container runs as the host UID, the
caches must survive the container, and a reinstall after a recreation must not hit
the network. The paths in the original sketch
(/usr/local/cargo/registry, /root/.cache) assume a root container and do not
work with user mapping. Use a writable home volume instead:
| Volume | Container path | Environment |
|---|---|---|
agent_home | /home/agent | HOME |
agent_cargo_registry | /home/agent/.cargo/registry | CARGO_HOME=/home/agent/.cargo |
agent_cargo_git | /home/agent/.cargo/git | CARGO_HOME=/home/agent/.cargo |
agent_pip_cache | /home/agent/.cache/pip | PIP_CACHE_DIR |
agent_uv_cache | /home/agent/.cache/uv | UV_CACHE_DIR |
agent_npm_cache | /home/agent/.npm | npm_config_cache |
Declare every volume with nocopy, because the image has no content at those
paths. The nested volumes sit on top of the home volume; Docker orders mounts by
destination length, so the more specific path wins.
The caches and the container layer cover different things, and the split is the point. A cache holds inputs — downloaded crates and wheels — so it survives every recreation. The layer holds the result of an install, so it survives only until the container is recreated. Together they mean a reinstall is fast and offline, even though it is not free.
The first cargo build in a new session fills the registry volume. Later
sessions reuse it. target/ is not a volume: it belongs to the workspace, so
two sessions on the same repository share it exactly as they share the files.
pip install --user is the case worth calling out. It writes to
/home/agent/.local/lib, which is inside the home volume rather than the
container layer, so it survives a recreation and a new session. A package
installed that way is available to every later session until the volume is
removed. That is convenient and it is also a hidden dependency: a fresh machine
does not have it. Prefer a project-local venv in the workspace, which is visible
and reproducible from the repository.
The volumes are global, not per session. Two sessions may read the same registry
concurrently; Cargo’s registry cache is safe for that. Remove a volume only when
the user asks, with docker volume rm.
Network
network_mode: none is fixed at creation, and the shell argument is per call.
The two are reconciled with a dedicated bridge network:
- Create the container with
none. It has loopback and nothing else. - For an approved
network: "unrestricted"call,connect_networkthe container torobi-egress, run the exec, thendisconnect_network. - Disconnect in a guard, so a timeout or a dropped future still removes the interface before the next call.
The shell tool is Exclusive, so no other exec overlaps the window in which the
interface exists. DNS resolution works only inside that window.
A workspace that declares services is the exception: its container is created
attached to the service network instead of none, because the connection has to
exist for the whole session, not for one approved call. See Reaching a dev
database.
robi-egress is a user-defined bridge, created on first use. It is not the
default bridge, so the disconnect is unconditional and does not depend on the
daemon’s default-network behaviour.
sandbox_network = "off" is the exception, and it is machine-wide. The container
is created on the default bridge, which reaches the outside through the daemon’s
NAT, so every sandboxed command has egress. A per-call network: "unrestricted" then asks for nothing and gets no card, because the interface is
already there.
Reaching a dev database
A workspace usually needs a service that is already running: a Postgres in compose, a Redis, a local API. The agent runs the test inside the sandbox, and the test connects to that service. Three things break before it works.
The sandbox has no network. network_mode: none is the default, so the
connection fails with Network is unreachable, not a timeout.
localhost means the sandbox. A test that hardcodes
postgres://localhost:5432 connects to the sandbox’s own loopback. The service
is not there, and the error is Connection refused. No network setup changes
this; the address has to come from the environment.
A port published to 127.0.0.1 is not reachable from any container. This is
the one that wastes an afternoon:
| Host publish | Container reaches it | Why |
|---|---|---|
-p 5432:5432 | yes, at the gateway address | binds 0.0.0.0, so the bridge interface accepts |
-p 127.0.0.1:5432:5432 | no | the packet arrives on the bridge interface, and the socket only listens on loopback |
ports: ["127.0.0.1:5432:5432"] in compose | no | same |
The decision is a services list in sandbox.toml, and every entry needs the
Docker network it lives on:
services = ["postgres:5432"]
service_network = "myproj_default"
services is an allowlist, not a blanket. The sandbox joins one network that
holds those endpoints: it cannot resolve or reach anything the list does not
name. This is not unrestricted, and a workspace that sets no services keeps
network_mode: none.
A containerized service
When service_network names a Docker network, the sandbox joins it for the life
of the session. Docker’s embedded DNS then resolves postgres on that network, and
no host port is involved at all — which is why this is the preferred shape. It
removes the 127.0.0.1 binding problem entirely and the port collision on 5432
between two projects.
The blast radius is the network, not the port: joining myproj_default lets the
sandboxed command reach every container on it, not only postgres:5432. Put the
database on its own network if that matters.
A host process, or a loopback-bound port
There is no relay, and that is a deliberate MVP boundary.
A service published with -p 127.0.0.1:5432:5432 listens only on the host’s
loopback. Reaching it from a bridge container needs a process inside the host’s
network namespace — a socat container with network_mode: host, which was two
extra moving parts and a standing host-network grant for a case the approval card
already covers. So this case escalates instead:
| The service is | You can | Cost |
|---|---|---|
| On a Docker network | service_network = "<network>" and services | The blast radius of that network |
Published on all interfaces (-p 5432:5432) | network: "unrestricted" on the call, approved | Egress for that one command |
Bound to 127.0.0.1 | unsandboxed: true, approved | The command runs on the host |
The second row is the usual fix and needs no new machinery: config.network_mode
is bridge only when services is non-empty, and an approved call is otherwise
attached to robi-egress for its own duration. The sandbox then reaches the
service at the bridge gateway address.
Declaring services without a service_network is refused rather than silently
starting a container that cannot connect: the error names the escalation. That is
the whole point of dropping the relay — a workspace either has a path to its
service or it is told why it does not, instead of discovering Connection refused
inside a test run.
The address the test sees
The sandbox sets one environment variable per service, so a test reads the address instead of hardcoding it:
| Service | Variable | Value |
|---|---|---|
postgres:5432 | DATABASE_URL | postgres://postgres:5432 |
postgres:5432 | POSTGRES_HOST, POSTGRES_PORT | postgres, 5432 |
Set these in sandbox.toml as literals when the test needs something the harness
cannot guess:
[env]
DATABASE_URL = "postgres://app@postgres:5432/app"
REDIS_URL = "redis://redis:6379"
[env] goes through the same secret filter as the rest of the environment, so a
DATABASE_URL containing a password is not written to a log.
Two things on the service side have to be true, and neither is the sandbox’s to
fix: Postgres must listen on an interface the connection arrives on
(listen_addresses), and pg_hba.conf must accept the source subnet. A stock
postgres image with POSTGRES_HOST_AUTH_METHOD=trust and a published port
satisfies both; a hand-written pg_hba.conf that only allows 127.0.0.1/32 does
not, and the error is no pg_hba.conf entry for host "172.x.x.x".
What this deliberately does not allow
A test may not start the database itself. testcontainers, a docker compose up
in a setup hook, and anything else that talks to the Docker socket need the socket
mounted into the sandbox, and that is root on the host behind a path — the
standard container escape, rejected below. The project provides the service; the
sandbox connects to it.
Environment
The container does not inherit the host environment. command_env stays the
builder for bwrap and Seatbelt; the container path uses container_env, which
constructs a smaller list:
| Name | Value |
|---|---|
HOME | /home/agent |
USER, LOGNAME | agent |
CARGO_HOME | /home/agent/.cargo |
RUSTUP_HOME | /usr/local/rustup, from the image |
TMPDIR | /tmp |
XDG_CACHE_HOME | /home/agent/.cache |
GIT_CONFIG_GLOBAL, GIT_CONFIG_SYSTEM | /dev/null |
LANG | the parent’s value when it is a locale token, otherwise C.UTF-8 |
The secret filter still applies. Any name containing KEY, TOKEN, SECRET,
PASSWORD, or CREDENTIAL, and any DYLD_*, LD_PRELOAD, or
LD_LIBRARY_PATH, is not copied.
PATH is not in the list. The image sets it in its own ENV, and Docker applies
the image value to both run and exec, so neither the host PATH nor a second
copy of the image’s reaches the command. A directory in the workspace cannot
place its own ls first.
The image is the PATH contract. Add a toolchain to
resources/docker/agent-base.Dockerfile, not to the profile. A profile env
setting may still set PATH, because that is the user’s deliberate choice.
Execution
exec creates one exec per command with attach_stdout and attach_stderr,
tty: false, the rebased working_dir, and the container user and environment.
The container is also created with /workspace as its own workdir, so an exec that
somehow arrives without one still starts there.
start_exec returns StartExecResults::Attached { output, .. }, where output
is one multiplexed stream. LogOutput::StdOut and LogOutput::Console go to the
stdout buffer, LogOutput::StdErr to the stderr buffer, and LogOutput::StdIn
is ignored. One stream, two buffers: no second task is needed to read stderr,
and the relative order of bytes inside each stream is preserved.
Each buffer is capped at OUTPUT_LIMIT / 2 (128 KiB), matching
launch::run_command. A frame that crosses the cap is truncated at the cap and
sets truncated. Bytes after the cap are read and discarded, so the socket
drains and the exec cannot block on a full pipe.
start_exec does not carry the exit code. After the stream ends, inspect_exec
returns exit_code, which becomes CommandOutput.exit_code.
Timeout and cancellation
An exec has no cancel API. The container is the cancellable unit:
select {
stream ends -> normal
cancel.cancelled() -> kill
sleep(timeout) -> kill
}
kill: docker.kill_container(name, SIGKILL)
drain the remaining frames
mark the container for recreation
The result has exit_code: -1, killed: true, and command was killed
appended to stderr, the same shape launch::run_command returns today. The next
exec sees the dirty flag and recreates the container. Workspace files and the
cache volumes persist; installed packages, running processes, and the tmpfs do
not.
Killing the container rather than one process is deliberate. runsc runs the
container’s processes in one sandbox; signalling a single exec’s PID from the
host is not reliable across runtimes, while killing the container is defined by
the Docker API. The cost is that a timed-out build loses its warm process tree
and the container layer, so packages installed earlier in the session have to be
installed again. The cache volumes make that reinstall offline, and Container
lifetime lists exactly what survives.
The workspace is shared, so a killed command may leave a partial file. That is
the same outcome as SIGKILL on a host process, and it is why the timeout is a
safeguard rather than a normal path.
Output and retrieve
The tool result does not change. exec returns the existing CommandOutput,
shell.rs serialises the same five fields, and the compressor and retrieve
need no sandbox-specific branch.
| Stage | Owner | Result |
|---|---|---|
| Stream and cap | container::exec | At most 128 KiB per stream, truncated: true past the cap |
| Tool result | tools/shell.rs | {exit_code, stdout, stderr, truncated, sandboxed} |
| Collapse and store | ShellCompressor | Above 4 KiB, and when it saves 1 KiB, the original is stored and stdout or stderr becomes a ROBI_LOG header (id, sha256, exit) plus collapsed lines |
| Page | retrieve | stream, offset, limit, or raw over the stored original |
The sandbox does not mint the retrieve id. It has no SessionId and no
OriginalStore, and the compressor sees the tool result after the loop has
attached the call id. Keeping that seam where it is means the container path and
the bwrap path share one truncation implementation.
The stored original is the capped text, not the full 1 GiB a noisy command printed. That is existing behaviour and it stays. A session that needs every byte of a build log should redirect it to a file in the workspace, which is a plain file the read tools can page. Full-fidelity capture is a follow-up, listed below.
Reaping
Every container carries labels:
robi.sandbox=container
robi.session=<session id>
robi.workspace=<canonical workspace path>
A container is removed three ways, and all of them keep the workspace mount and the cache volumes:
| Trigger | Owner | Effect |
|---|---|---|
| The chat session is deleted | SessionCleanup, as the session’s session_cleaner | The container goes with the row, under the registry lock |
| No command for ten minutes | the reaper task | The container goes; the registry entry stays, marked for recreation |
| The process exits | each surface, through bootstrap::shutdown_sandboxes | Every entry goes, with its container |
SessionCleanup (adapters/session_data.rs) composes the container release with
the blob removal, so all three delete paths — DELETE /api/v1/chat_sessions/{id}, the TUI’s delete, and the startup prune — release
the container without each handler remembering to. The release runs first, so a
blob failure cannot strand a container.
The reaper (container/reaper.rs) is one task started by
bootstrap::build_app_state, so robi-api, robi, and the desktop app all
get it from the one place they share. It ticks every REAP_INTERVAL (120 s) and
removes a container whose last_used is at least IDLE_TIMEOUT (600 s) old. Both
are constants for now; Registry::sweep_idle takes the timeout as an argument, so
turning it into a setting is one call site.
Three details keep the sweep out of the way of a running command:
last_usedis stamped when a command finishes, not when it starts, so a build that outlives the timeout is not reaped the moment it ends.- The sweep takes each sandbox’s state lock with
try_lock. That lock is held for the whole command, so a held lock means work is in flight and the container is skipped rather than queued behind it. - The remove is bounded by
REMOVE_TIMEOUT(30 s), and both the sweep andreleaseremove while holding the registry lock. A wedged daemon therefore costs one slow sweep, not a permanently stuckshellcall.
An exec already waiting on that state lock wakes to find no container, and
ensure_ready_locked creates one. The call succeeds and loses only the
installed-package layer, which is exactly what an idle removal costs.
The sweep removes the container and leaves the registry entry, marked dirty.
Only release drops an entry, and only for a session that no longer exists. That
ordering matters: a caller holding the Arc but not yet having taken the state
lock would otherwise recreate a container that no entry names, which nothing would
ever reap again. The dirty flag also stops one reap from being logged on every
tick while the session stays idle, because an already-dirty sandbox is skipped.
On exit
A container is a label in a daemon, not a file the process holds, so nothing removes it when the process goes. Each surface therefore removes its own on the way out, and each does it on the runtime that built the Docker client:
| Surface | Where the cleanup runs |
|---|---|
robi-api | After axum::serve returns from with_graceful_shutdown, which resolves on Ctrl-C or SIGTERM |
robi | After tui::run returns, which already turns SIGTERM into a quit |
| Desktop app | On RunEvent::Exit, which asks the API thread to stop and waits up to 10 s for its cleanup |
Registry::shutdown_all drains the registry under its lock and removes each
container with the same REMOVE_TIMEOUT budget as any other remove. A command
still running in one of them holds its state lock; that container is logged and
skipped rather than allowed to hang the quit.
tokio/signal is a dependency of the crate, not of the tui feature, because
robi-api needs it for the same reason the terminal app does.
A container left by a crash, SIGKILL, or a failed shutdown is not covered. It belongs to no live process, so
no in-process registry knows it exists, and neither the sweep, a session delete,
nor the exit cleanup can reach it. Closing that gap needs a signal that outlives
the process — a create-time owner label plus an owner-PID liveness check, so a
later process can prove the owner is gone before removing anything — and it is not
built. Removing by label alone is wrong: two processes can share a daemon, and
that would delete a container the other one is using.
Module layout
The code lives under crates/robi/src/agent/sandbox/. bollard is an ordinary
dependency: the container sandbox is selected at run time by sandbox_mechanism,
not by a Cargo feature. One switch, not two, and no way for a build to accept the
setting and quietly do something else with it.
| File | Role |
|---|---|
sandbox/masks.rs | The workspace floor. Every mechanism emits this one list, so bwrap, Seatbelt, and the container cannot drift apart |
sandbox/container/config.rs | The settings layers: Config, Mechanism, resolve, parse_service, and the per-command environment |
sandbox/container/host.rs | The HostConfig, its mounts, the UID/GID, and the base environment. Pure construction, so it is testable without a daemon |
sandbox/container/mod.rs | The lifecycle: preflight, create, exec, streaming, timeout, shutdown, and the per-session registry |
sandbox/container/reaper.rs | The idle sweep: REAP_INTERVAL, IDLE_TIMEOUT, the tick loop |
The split is by what needs a daemon. config and host are functions of the
profile and the settings, so their tests run with no Docker at all. Only mod.rs
talks to the socket, and its logic that is worth testing is StreamBuffer and
is_reapable, both unit-tested directly. reaper is a clock and a call.
Each module’s tests cover the behaviour its doc comment claims:
masks— the floor finds a secret file and skipstarget/; an explicit grant wins over the floor.config— the defaults areoswith no network; a workspace file overrides only the fields it sets; an unacknowledged file contributes nothing; a project file cannot name a mechanism; out-of-range values are refused; a service entry needs a name and a port; a service withoutservice_networkis refused.host— the workspace mounts where the container expects it, read-write even for a read-only profile; a grant inside the workspace is rebased and one outside keeps its host path; the floor becomes a/dev/nullbind; the cache volumes are present; the security posture is fixed while the settings-backed fields follow the config.mod— the two streams stay apart, each gets its own cap, a frame crossing the cap is cut, stdin frames are ignored, and invalid UTF-8 does not panic.reaper— a container is reapable at the timeout and not one second before; the interval is shorter than the timeout.session_data— deleting a session with no container still removes its blobs, which is the common case on theosmechanism; an inner failure is reported rather than skipping the work.
Dispatching from sandbox::launch
launch takes a [Launch] request. The mechanism decides the branch, and the
os branch is byte-for-byte what shipped: launch_argv keeps its
cfg!(target_os) branches.
#![allow(unused)]
fn main() {
pub struct Launch<'a> {
pub profile: &'a Profile,
pub command: &'a str,
pub cancel: CancellationToken,
pub timeout: Duration,
pub session: SessionId,
pub mechanism: Mechanism,
pub settings: Option<&'a dyn SettingsStore>,
pub project_trusted: bool,
pub registry: Option<&'a container::Registry>,
}
pub async fn launch(request: Launch<'_>) -> Result<CommandOutput, String> {
let profile = request.profile;
if !profile.sandboxed {
return launch_host(profile, request.command, request.cancel, request.timeout).await;
}
match request.mechanism {
Mechanism::Os => launch_os(profile, request.command, request.cancel, request.timeout).await,
Mechanism::Container => launch_container(request).await,
}
}
}
container::Registry::global() is the only shared state. One daemon, one process,
one map keyed by session id: a process-wide map keeps the sandbox out of every
AgentFactory and ToolContext literal, and it is what lets the container survive
the per-turn rebuild of the tool registry. get returns the cached sandbox without
comparing config, because exec compares it and recreates the container, so one
place decides whether the container goes.
shutdown removes the container, bounded by REMOVE_TIMEOUT. The workspace and
the cache volumes are left alone. release drops the entry and calls it under the
registry lock, and sweep_idle walks the same map at the end of each reaper tick;
see Reaping.
Integration guide
The shell tool builds one Launch instead of calling launch with four
arguments:
#![allow(unused)]
fn main() {
let request = crate::agent::sandbox::Launch::new(
&profile,
command,
run.cancel,
timeout,
self.ctx.session_id,
);
let request = {
let settings = self.ctx.settings.clone();
let mechanism = container::config::mechanism(settings.as_deref()).await;
let project_files_on = self
.ctx
.setting_value(keys::SANDBOX_PROJECT_FILES)
.await
== keys::PROJECT_FILES_ON;
request
.with_settings(self.ctx.settings.as_deref(), project_files_on)
.with_mechanism(mechanism)
.with_registry(container::Registry::global())
};
let output = launch(request).await.map_err(ToolError::Failed)?;
}
The mechanism is read once, before the profile is built, because os skips the
container preflight entirely. A workspace that keeps the default pays one settings
read for this, not a daemon round trip. resolve repeats the read when the
container path is taken; it is cheap and it keeps the mechanism decision in one
place.
Nothing after that line changes. The result payload is still:
{
"exit_code": 0,
"stdout": " Compiling robi v0.1.0\n Finished `dev` profile\n",
"stderr": "",
"truncated": false,
"sandboxed": true
}
A long build produces the same payload with truncated: true; the compressor
then stores the capped text and replaces each stream with a header. The model
pages it with the existing tool:
{ "id": "0190f3f2-...", "stream": "stdout", "offset": 120, "limit": 200 }
retrieve needs no container awareness. It reads the per-session redb store,
which the compressor wrote.
A denial is still detected from stderr. The container’s errors name the missing
path (/workspace/.env: Permission denied), so the existing blocked_hint path
continues to work. Add one case for the container-specific messages: exec failed: container is not running and no such container mean the container
died between calls; the next exec recreates it, and the model should retry
once rather than ask for unsandboxed.
Operational setup
The user performs these steps once per machine. The harness does the rest.
Linux
-
Install Docker Engine and
runscfor the host architecture. -
Register the runtime in
/etc/docker/daemon.json, then restart the daemon:{ "runtimes": { "runsc": { "path": "/usr/local/bin/runsc" } } } -
Verify both:
$ docker info --format '{{json .Runtimes}}' {"runc":{"path":"runc"},"runsc":{"path":"/usr/local/bin/runsc"}} $ runsc --version runsc version release-20240916.0 -
Build the agent image, or let the first call pull
robi/agent:1:$ docker build -t robi/agent:1 \ -f resources/docker/agent-base.Dockerfile resources/docker
macOS
The daemon runs on a Linux VM, and the container runs in that VM. Everything in this design applies; three details differ.
- The runtime lives in the VM.
runschas to be installed inside the Linux VM, not on macOS. Colima and Lima let you install it as you would on a Linux host. Docker Desktop also runs it once installed in its own VM, but a Docker Desktop upgrade replaces that VM, so the runtime has to be reinstalled. - The workspace crosses a filesystem boundary. The projects directory is
shared into the VM, which is correct but slower than a native bind mount.
Many small files pay the most, so a
cargo buildthat writes thousands of files undertarget/is the slowest case. - Only shared paths can be mounted. A
read_pathsorwide_readsentry outside the paths the daemon shares cannot become a mount. Docker Desktop shares/Users,/Volumes,/private, and/tmpby default; Colima shares the paths it was started with. A grant outside those roots is refused with the path named, rather than silently dropped.
A Linux daemon is one package and one daemon.json entry, so the setup is
shorter there than on macOS. The mechanism itself is the same on both.
Choosing the mechanism
Set sandbox_mechanism once:
$ curl -X PUT http://127.0.0.1:1431/api/v1/settings/sandbox_mechanism \
-H 'content-type: application/json' -d '{"value":"container"}'
The setting is global, not per workspace: mechanism is absent from
.robi/sandbox.toml, so a repository cannot decide whether its own code is
containerised. A workspace file tunes the container — image, limits, services,
environment — for a machine that already runs one.
The harness creates robi-egress and the cache volumes on first use. Remove them
only when the user asks, with docker network rm or docker volume rm.
Rejected alternatives
- Replacing
bwrapand Seatbelt with this. They are the default, they need no daemon, and they already work. Deleting them would make a working machine depend on Docker for everyshellcall. The mechanism is a setting, andosstays the default. - A container mode that only builds on Linux. The daemon already runs on a Linux VM on macOS, so the same code path serves both. Gating it to Linux would duplicate the mechanism choice for no gain.
- Shelling out to
docker. A subprocess is another process to supervise, its output needs parsing, and an argument with a newline or a quote changes the command.bollardspeaks the API directly. - A fresh container per command. It discards the installed packages and any
other in-container state the previous command created, so
pip installandapt-get installhave to run again on the next call. It also gives up the warm process tree. The per-session container keeps both and still isolates sessions from each other. See Container lifetime. - One container shared by every session. Two sessions would see each other’s
installed packages and background processes, and the second session’s
pkillwould hit the first. The workspace is already shared; the environment should not be. - Root inside the container with a
chownon exit. Root-owned files appear in the workspace the moment a command creates one, and a crash skips the cleanup. Matching the host UID removes the class of bug. - Mounting
~and denying a list. That is the model the sandbox already rejects forbwrap: one missed credential directory is readable. The container mounts only what the profile names. - Mounting host toolchains at the same paths. The binary would run against image libraries it was not linked with, and the host toolchain would leak back into the sandbox. The image owns the toolchain.
/usr/local/cargoand/root/.cacheas volume targets. They assume a root container. With UID mapping they are not writable; the home volume is.- Using the default
bridgenetwork for egress. The container is created withnone, and the default bridge is not a network the harness can rely on disconnecting cleanly.robi-egressis created and removed on the harness’s terms. docker exec --privilegedfor toolchains that need it. It restores the capabilities the profile drops. A tool that needs privilege does not belong in the sandbox.- Mounting the Docker socket into the container. That is root on the host behind a socket path, and it is the standard container escape. The sandbox never mounts it.
- Kata or Firecracker instead of gVisor. A microVM gives a stronger kernel
boundary and needs hardware virtualisation, a guest kernel, and a second
image pipeline. gVisor is one runtime name in
HostConfig. - Retrying a refused container call on the host. That is the bypass the
current design already rejects. A refusal names the
osmechanism instead. network_mode: hostfor the sandbox, so it can reachlocalhost. That is the whole host network namespace, and it removes the boundary this page exists for. An approvednetwork: "unrestricted"call reaches egress without it.- A
socatrelay container for a loopback-bound port. Two extra containers and a standingnetwork_mode: hostgrant to solve a case the approval card already covers.unsandboxed: trueis the escalation, and the user sees it. - A per-workspace network toggle. The switch is global, so a repository
cannot open its own network. It is also named for what it does (
Open, notunrestricted) and sits beside the mechanism it affects. - An approval card on every command when the network is open. There is nothing left to grant, so the card would only train the user to approve without reading. The toggle is the one place the decision is made.
- Declaring a service by port only, with no allowlist. That is unrestricted
egress under another name.
servicesnames the endpoints the workspace needs. - Mounting the Docker socket so the test can start its own database. That is root on the host behind a path, and it is the standard container escape. The project provides the service.
- One flat settings file with no workspace layer. A team that needs 16 GB for
one repository would edit the global
config.tomlper project, or passunsandboxed. The project file is the narrower tool. - A project file that can set
mechanism. The repository would decide whether its own code is containerised. That choice belongs to the machine’s owner.
Failure modes
- The daemon socket is missing or the user is not in the
dockergroup:sandbox could not be applied: the Docker daemon is not reachable, and the command does not run. Settingsandbox_mechanismtoosrestores the host sandbox. - The configured runtime is not registered: the error names it and says to
register it or set
sandbox_mechanismtoos. - The image is missing and the pull fails: the error names the image and the pull failure. An offline machine fails here rather than running on the host.
- The workspace is not a directory after canonicalisation:
the workspace <path> is not a directory. - The workspace has more than 2,000 floor masks:
the workspace needs N path masks, above the 2000 limit. sandbox.tomldoes not parse, or sets a field outside its range: the sandboxed call is refused withsandbox.toml did not parseor the field’s range message, and the command does not run. A project file that breaks the build is loud, not silently ignored.sandbox.tomlis present but not acknowledged: it has no effect, and the settings screen shows the values it would apply.- A mounted path on macOS is outside the daemon’s shared roots: the error names the path, and the command does not run.
service_networknames a network that does not exist, or the daemon refuses the attach: the sandboxed call is refused with the network name, and the command does not run.- A
servicesentry is notname:port: the error isservices entry <entry> must look like name:port. - A test that connects to
localhostreportsConnection refused, or to an undeclared service reportsNetwork is unreachable. Neither is a sandbox bug; name the service insandbox.tomland read the address from the environment. servicesis declared withoutservice_network: the sandboxed call is refused with the escalation named, and the command does not run.sandbox_network = "off"and a command cannot reach a host port anyway: the default bridge still cannot see the host’s loopback. Publish on all interfaces or useunsandboxed: true.- A service published to
127.0.0.1is not reachable from the sandbox even withservice_network. Publish it on all interfaces, or approvenetwork: "unrestricted"for the call, or run that command withunsandboxed: true. - The setup exec fails:
setup command exited N: <its output>, with a hint when the output names a known cause.chown: ...: Operation not permittedmeans the container lostCAP_CHOWN, which is whatcap_drop: ["ALL"]does on its own.No such file or directorymeans the image lacks the path. - A volume cannot be written after a successful setup: the first command fails
with
Permission deniedon a path under/home/agent. Setup skips a volume root whose owner already matches, so a root left root-owned by a failure stays that way until the container is recreated. - A command exceeds
tool_timeout_secondsor the call is cancelled: the container is killed, the result isexit_code: -1,killed: true, and stderr ends withcommand was killed. The next command recreates the container. - The kernel OOM-kills the command: the container exits 137 and the result
carries
exit_code: 137. The container is marked dirty and recreated. - Output passes 128 KiB on either stream:
truncated: true, the prefix is kept, and the compressor stores that prefix forretrieve. - The container is removed by the user between calls: the next
execreportsno such container, recreates, and retries the lifecycle once. - The daemon restarts while a command runs: the stream ends with an error, the
call returns
the Docker daemon is not reachable, and the command does not produce an exit code.
Follow-ups
- Read-only Ask and Plan mounts. The container mounts
/workspaceread-write for every mode, because the mount table is fixed at creation and a mode switch reuses the container. Recreate whenWriteAccesschanges, then mount Ask and Plan read-only again, with Plan’s nested.robi/plansgrant. - Full-fidelity logs. The original stored for
retrieveis capped at 256 KiB. Afull_logfield onCommandOutput, written by the sandbox to the session directory and read by the compressor, would keep a 1 GiB build log without raising the tool-result ceiling. - A project-pinned image.
robi/agent:1is one image for every repository. A.robi/agent.Dockerfilein the workspace would let a project pin its toolchain without touching the global image. - Rootless Docker and Podman.
bollardcan reach a rootless socket. The user-mapping step and the volume ownership change; the rest of this design is unchanged. - GPU and device access. The profile drops all capabilities and mounts no devices. A project that needs a GPU needs a new, explicit grant, not a privileged container.
- A resolved-value view. The Settings → Sandbox tab writes the eight
global keys, but it shows what is stored, not what will apply. A form that
shows the value each layer contributes — the default, the global key, and the
workspace file — and the project file’s pending values before acknowledgement,
would make the layering visible. It needs a read route that returns the
resolved
Config, which does not exist yet. - Measured overhead. gVisor intercepts syscalls, so a
cargo buildis slower than the same build underbwrap, and on macOS it also crosses the VM boundary. Publish the number for a reference build so the choice betweenosandcontaineris informed.osstays the default until then.
Web tools
This page defines web_search and web_fetch. It is the design for the web
tools in M8 of the roadmap. Which modes register them is in
agent-modes.md. The approval card the loop already shows is
in chat-ui.md. The session column that remembers a fetch host is
in persistence.md.
What this page does not cover
| Topic | Where it belongs |
|---|---|
| Path grants and the file filter | read-tools.md |
| Shell network | shell-tool.md. A command that needs the network still uses network: unrestricted |
| Child agents | subagents.md. Explore and general do not register these tools |
| Compressing a large result | docs/src/design/compression/tool-output-compression.md (M9). These tools already cap what they return |
Problem
The model has to look up a library, a current version, or a fact that is not
in the workspace. shell can curl, and that call can also read a secret,
dial a private address, or spend a metered API with no one looking. A page
dropped into the transcript whole is mostly script, style, and navigation.
Search and fetch are different costs. Each Brave query spends a rate-limited
quota. A fetch of a public page does not, and the user should not approve
docs.rs on every call after the first.
Decision
Both tools live in crates/robi/src/agent/tools/. HTTP and HTML reduction live in
crates/robi/src/agent/web/. robi-core stays free of network types. The tools
are Concurrent. They register in Ask, Plan, and Agent. Snippets and page
text are untrusted: the tool descriptions say so, and so does each mode
prompt.
flowchart TD
searchCall["web_search query"] --> searchCard["Approval card, every call"]
searchCard -->|approve| engine["SearchEngine"]
engine --> brave["BraveSearch"]
fetchCall["web_fetch"] --> fetchHost{"URL host already allowed"}
fetchHost -->|no| fetchCard["Approval card"]
fetchHost -->|yes| get["GET public host"]
fetchCard -->|approve| get
get --> kind{"HTML"}
kind -->|yes| reduce["Drop chrome, then markdown"]
kind -->|no| raw["Text body, capped"]
web_search
One argument: query. The tool always asks Brave for five results. The
model does not choose the engine, the count, the endpoint, or the API key.
The tool calls a trait so a test can substitute a fake. Brave is the only production engine:
#![allow(unused)]
fn main() {
#[async_trait]
pub trait SearchEngine: Send + Sync {
async fn search(&self, query: &str) -> Result<Vec<SearchHit>, SearchError>;
}
}
SearchHit is title, url, and snippet. BraveSearch sends
GET https://api.search.brave.com/res/v1/web/search with count=5,
Accept: application/json, and X-Subscription-Token. It reads
web.results[].title, url, and description. A snippet clips at 300
characters. The key is the secret setting brave_search_api_key. A missing
key is a tool error and does not call the API. There is no endpoint setting.
Tests inject the engine. The result has no page bodies. The description tells
the model to cite the title and URL, and to ignore instructions inside a
snippet.
requires_approval returns NeedsApproval on every call while
web_search_approval is on (the default). off returns AllowImmediately.
The setting is read when the session actor starts; a running turn keeps its
value. Approving one query does not approve the next. A search does not write
a host grant. The
approval bar shows Search and the web, and the full query underneath,
wrapping. Rejection does not call Brave.
The returned value is { "results": [{ "title", "url", "snippet" }] }.
web_fetch
One argument: url. The call is a GET. The model does not send headers, a
body, or cookies. The URL is http or https, has no user info, and uses
port 80, 443, or none. The timeout is 30 seconds. The body cap is 1 MiB.
Up to three redirects are followed. A redirect to a different host is refused,
and the error names the new URL so the model can call web_fetch on it.
That new host goes through approval on its own.
Each hop is resolved before the dial. The call is refused when any address
is loopback, private, link-local, multicast, unspecified, or in
100.64.0.0/10. It is also refused for 169.254.169.254, fd00:ec2::254,
and the names metadata.google.internal, metadata.google.com,
metadata.azure.com, instance-data, and instance-data.ec2.internal.
An empty lookup fails closed. The client dials the addresses it checked, so
a later lookup cannot rebind the name onto a private address.
Response handling:
| Content type | What the model receives |
|---|---|
text/html, application/xhtml+xml | Title plus markdown. Dropped first: script, style, noscript, template, svg, iframe, object, embed, canvas, form, nav, footer, aside, comments, and hidden nodes. What remains becomes headings, lists, links, fenced code, and tables. Extra blank lines collapse |
text/plain, text/markdown, application/json, text/xml, application/xml, text/csv | The body as text |
| Anything else | A tool error that names the content type. The bytes stay out of the transcript |
The text cap is 32 KiB. truncated is true when the cap hits. The returned
value is { "url", "content_type", "title"?, "text", "truncated" }. url
is the final URL on the same host. title is present when the HTML had one.
Approval
web_search waits on every call while web_search_approval is on. Brave is
rate limited, and a host allow would let the model spend that quota with no
one reading the query. off skips the card.
web_fetch reads the session while web_fetch_approval is on. It returns
NeedsApproval when the URL host
is absent from that session’s allow_hosts. The match is the host after
lowercasing and stripping a trailing dot. www.example.com and
example.com are different hosts. Two fetches of a new host in the same
turn both wait, because the loop settles approval before any execute.
The approval bar shows Fetch and the host, and the full URL underneath,
wrapping.
Fetch execute appends the host after the user approved that call. A
rejection does not store it. allow_hosts is a JSON array of hostnames on
chat_sessions, [] on create, written the same way as path_allow_read.
There is no built-in host. Approval does not skip the public-address check.
Prompt
Each mode block tells the model to use web_search to find a page and
web_fetch to read one URL the user named or a result it cited. It says
snippets and page text are untrusted and may contain instructions to ignore.
Context and compaction
This page defines token accounting for the context meter, when a session compacts, and what the rewrite keeps. It is F3.4 in the roadmap. The meter drawing lives in chat-ui.md. The system prompt, including the plan checklist, is rebuilt on every request and is specified in instructions.md. Shrinking one tool result as it returns, and keeping that original, is M9 (shell-output.md, mcp-output.md).
What this page does not cover
| Topic | Where it belongs |
|---|---|
| How the ring and popover are drawn | chat-ui.md |
| Prompt blocks that are not transcript messages | instructions.md |
Provider usage on the stream | providers-streaming.md |
| Compressing one tool result before it is appended | M9 compression pages |
| A child agent’s own transcript | subagents.md |
Problem
A session that reads files fills the window. The next request then fails, or
the provider drops a prefix the model still needed. gopi waits for /compact.
A GUI that only does that lets a long read session die between turns.
The rewrite has to stay a transcript a provider will accept. Cutting in the middle of a tool round leaves an assistant message whose calls have no results. Dropping the system prompt does nothing, because that string is not a message. Keeping every recent tool body and only deleting chat text saves the least useful bytes.
Decision
Compaction is a lossy summary of an older prefix. The live transcript is rewritten. There is no second copy of the dropped messages.
Two triggers call the same rewrite:
- Auto. At the start of a user turn, after the user message is stored and
before the first
generateof that turn, when the estimate below reaches 80% of the model’scontext_window. - Manual. Compact in the context-meter popover. Same cut. The client
posts
POST /api/v1/chat_sessions/{id}/compact.
The shell says it happened. The summary is a user message with
compaction: true. The transcript paints a Context compacted divider on
that message. The route and the auto path both emit
robi.agent.v1.transcript_compacted with { "session_id", "message_id" },
and an open client refetches the message list.
Estimate
The meter and the trigger share one number.
used is the latest assistant usage.input, plus the characters of that
message and every later message, divided by four. usage.input is
already the prompt through that request, so earlier messages are not added
again. When no assistant message has reported usage, used is the characters
of the whole transcript divided by four.
Auto-compact runs when context_window is known and
used >= 0.80 * context_window. A missing window never auto-compacts. Manual
compact does not consult the threshold.
Characters divided by four is the stand-in until the provider counts those messages. It is the same stand-in chat-ui.md uses for the arc, except the trigger ignores the composer draft. A draft is not in the next request.
Cut
Walk backward from the end to user-message boundaries. The tail is every message from a chosen user message through the end. The prefix is everything before it.
The chosen boundary is the oldest user message such that the tail’s character
estimate is at most 50% of context_window. The current turn is never
in the prefix: the boundary is at or before the last user message, and the
tail always includes that message and everything after it. If that tail alone
is already over half the window, it is still kept whole.
A boundary is illegal when it would separate an assistant message that has tool calls from the tool messages that answer them. The walk steps back to the next older user message.
Nothing to compact means the prefix is empty: the transcript is only the
current turn. Manual compact returns 409 with {"error":"nothing to compact"}.
Auto compact skips.
When the model advertises no context_window, a manual compact still runs:
there is no figure to target, so it cuts at the newest legal user boundary and
keeps only the current turn. That is plan_last_turn.
Summary
One model call, no tools, on the session’s current model. The prompt is the
prefix rendered as role: content lines, then an instruction to write a
summary the next turn can continue from: decisions made, files read or
changed, tool outcomes that still matter, and constraints the user set. The
call’s output is the summary message’s content.
The rendered prefix is bounded below the model’s window: the newest prefix messages are kept whole and the oldest are dropped with an omitted-count line, leaving headroom for the reply. A model that advertises no window caps the render at a fixed size.
That message is role user, so the tail can still start with the user’s real
turn. compaction: true is how the UI and a later compact tell it from a
person. A later compact may include an older summary in a new prefix; the
flag does not protect it.
The system prompt and the plan checklist are not in the prefix and are not summarized. The next request sends them again.
Rewrite
The summary call finishes before any row is deleted. One SQLite transaction then deletes the prefix rows and inserts the summary at the front of what remains. A failed summary, a cancel, or a provider error leaves the transcript as it was.
The cut and the estimate are pure functions in robi-core. The summary call,
the transaction, and the route live in crates/robi. The loop does not
compact in the middle of a tool round.
When auto does not run
- The turn is already inside
generateor tool execution. - The transcript has a pending approval. Compact waits. A new instruction rejects those calls instead, which is a different path.
context_windowis absent.- The prefix is empty.
- This turn already compacted once. If the tail is still over 80%, the turn proceeds and the next user message may compact again.
Manual compact is refused with 409 while the actor is running or the
transcript is waiting on approval, same as POST .../messages.
Rejected alternatives
Manual only, as in gopi. A read-heavy session hits the window between turns, and the GUI has no slash command the user is expected to remember. Manual stays, as the popover action, for a compact the user wants early.
Structured truncation of old tool results. Keeps the shape of the transcript and spends no model call. It also keeps the turns that caused those calls, and it drops the bodies the model would need to avoid repeating the work. M9 already truncates and compresses a single result. Compaction runs because the window is full anyway.
An archive of the dropped messages. The UI would show a transcript the model cannot see, and a later retrieve would undo the compact. The divider and the summary are the record. M9 originals for compressed tool results are a different store; compact does not read or delete them. A summary that needs a dropped body says so in prose, and the model reads the file again.
Compacting mid tool-loop. Frees tokens sooner. It also races the append of tool results and can cut a call from its result. The check stays at turn start.
Putting the summary in the system prompt. Hides it from the transcript and from the meter. The next edit to the assembler would drop it. A user message is stored, visible, and counted.
Interfaces
#![allow(unused)]
fn main() {
/// Where a compact may cut. `prefix` is summarized. `tail` is kept.
pub struct Cut {
pub prefix: Vec<Message>,
pub tail: Vec<Message>,
}
/// `None` when the prefix would be empty.
pub fn plan_cut(messages: &[Message], context_window: u64) -> Option<Cut>;
/// Cut at the newest user boundary, keeping only the current turn. Used for a
/// manual compact when the model advertises no window.
pub fn plan_last_turn(messages: &[Message]) -> Option<Cut>;
/// Same figure the meter uses, without the composer draft.
pub fn estimate_tokens(messages: &[Message]) -> u64;
}
The pure functions live in robi-core. The summary call, the transactional
rewrite, and the route live in crates/robi behind the Compactor trait,
which the loop calls at the start of a user turn:
#![allow(unused)]
fn main() {
#[async_trait]
pub trait Compactor: Send + Sync {
async fn compact(
&self,
session: SessionId,
window: Option<u64>,
trigger: CompactTrigger,
cancel: &CancellationToken,
) -> Result<CompactOutcome, CompactError>;
}
}
CompactOutcome is Compacted { message }, BelowThreshold (auto only,
below 80%), or Nothing (empty prefix). CompactError means the transcript
was left unchanged.
POST /api/v1/chat_sessions/{id}/compact returns 202
{"status":"compacting"} once the actor has accepted the job. Completion is
the transcript_compacted event. Failures on the request itself:
| Status | When |
|---|---|
400 | id is not a UUID |
404 | No such session |
409 | Actor running, approval pending, or nothing to compact |
A summary that fails after 202 emits robi.app.v1.error for that session
and does not rewrite.
The message DTO gains compaction: true only on a summary. Other messages
omit the field.
Failure modes
| What happened | Result |
|---|---|
| Summary call errors or is cancelled | Transcript unchanged. Manual surfaces the error. Auto leaves a trace on the session error event and still runs the user turn |
| Transaction fails after a successful summary | Transcript unchanged. The summary text is discarded |
| Tail is already most of the window | Prefix is summarized if any exists. The turn is not refused |
No usage yet | Character estimate only. Auto may run early or late by that error |
Model has no context_window | No auto. Manual still runs |
| Summary is longer than the prefix | Still stored. The next turn can compact again. No second call in the same turn |
Code review
Disabled in M11. Kept for reference. The review routes are not served and the app has no review screen or edited-file strip. The user reviews with
git diffand their editor. The backend stays incrates/robi/src/web_api/review.rsandagent/review/session.rsbehind thereviewCargo feature;agent/review/diff.rsstays unconditional because the docs merge path uses it. The session baseline table is still written by theedit-toolsrestore path only. See feature-switches.md and Streamlining roadmap.
This page is the review of files a chat session has changed. The baselines it reads are in checkpoints.md. The chat strip that opens it is in visual-style.md.
Two pieces still ship: the session review routes stay on the API, and the
inline file peek from a tool call card uses GET …/review/file to show a
file’s diff in the chat.
What this page does not cover
| Topic | Where it belongs |
|---|---|
| Inline comments anchored to lines | Later in M6 |
| A tool the assistant uses to read review state | Later in M6 |
| Git status, a commit range, or a branch | Later. This screen is the session baseline only |
| Side-by-side columns | Later. This screen is one unified column, with a control that hides one side |
Problem
After write_file, edit_file, or delete_file, the transcript should not
become a pile of patches. The user needs a stable place, tied to this chat
session, that lists the paths and shows what changed.
Decision
GET /api/v1/chat_sessions/{id}/review loads the session, its workspace
root, and the baselines for that session. Each file is diffed against the
bytes on disk. A path with zero additions and zero deletions is left out. A
file this session created that is already gone is left out, the same way
hunks_for_session omits it.
The response is { files }. Each file is a summary: path, status
(added, deleted, or modified), additions, and deletions. Bodies
and lines stay off this response so the list stays small.
GET /api/v1/chat_sessions/{id}/review/file?path= returns one file:
baseline, current, lines, and hunks. A path with nothing left to
review is 404. A line is context, delete, insert, or gap. old_line
and new_line are 1-based, and both are null on a gap. Context is three
lines. A gap is the unchanged stretch between two hunks that did not merge.
baseline and current are the full texts, so the client can highlight
them. Deletions are painted from the baseline. Context and insertions are
painted from the current text.
The chat shell keeps one line above the composer when files is not empty:
N file(s) edited, and Review. It refetches when the session is
selected, when tool_call_updated or turn_finished arrives, and again
after that turn’s transcript is stored. The same check runs when the event
stream opens and when the two-second catch-up reloads a turn, so a frame
that never arrived still reveals the strip. Review
goes to #/sessions/:id/review. That route keeps the session sidebar. The
main column is the review. Back returns to the chat for that session.
Choosing another session, or New chat, leaves the review.
The left pane is a tree of the changed paths. At each level, directories come first, then files. Each group is alphabetical, without regard to case. A click loads that file in the right pane. Only the selected file is fetched and painted. Switching files leaves the others unloaded.
The file header shows the path, then +N and -N. Reject and Approve
sit on the right. A click on the path opens that file in a dialog. The dialog has
Diff, Current, and Previous, and it opens on Diff. Diff
is the whole file, with deletions and insertions in place. Unchanged
lines stay in the list. Current is the whole current text.
Previous is the whole baseline. A markdown file also has Preview,
which renders the current text. Headings step down by level. A deleted
markdown file renders the baseline. An added file on Previous, or a
deleted file on Current, shows File added or File deleted. Approve keeps the file as it is and folds that text
into the baseline, so the path leaves the review. The path leaves the list
as soon as Approve is clicked. If that request fails, the file comes
back and the error is shown. A hunk decision reloads that file only.
Reject writes the
baseline back. A file this session created, fully rejected, is removed.
Each block between gaps can hold more than one logical hunk, because the
backend only inserts a gap where two changes are more than two context
runs (six lines) apart. Every hunk in a block gets its own Reject and Approve
on the top right of that hunk’s first changed line, except on a file this
session created: that file only has the buttons on its header. Hovering a
block reveals one pair per hunk it holds. Approve folds that hunk’s
current lines into the baseline. Reject puts that hunk’s baseline lines
back on disk. Either one decides only that hunk and leaves the rest of the
file in review. A hunk that no longer matches the file is 409. The header
pair is the only whole-file decision.
Reject carries an inline chevron. The chevron opens a menu with Reject with reason, on the file header and on every hunk. Choosing it opens a modal for a short note; Reject and send decides that reject, then returns to the chat for this session and sends a message telling the model to iterate on the file, with the reason. The reason’s target — the whole file, or the one hunk — is decided first, so the model never races a revert.
The message carries the rejected change as an API file attachment, so the model
reads the exact bytes the user rejected. A whole-file reject attaches the file’s
current body with no line range, or the baseline for a file this session
deleted. A hunk reject attaches that hunk’s current lines, start_line to
end_line from new_start and new_count; a pure deletion attaches the
deletion point, and a file emptied by the deletion falls back to the baseline
lines the hunk removed. The attachment builder is
src/features/review/reviewAttachment.ts. The transport is file-attachments:
see file-attachments.md.
The right pane shows the selected file. The default is the
unified diff: context, deletions, and insertions. Current hides
deletions. Previous hides insertions. An added file on Previous, or a
deleted file on Current, shows one line — File added or File deleted —
instead of an empty block. A long line scrolls with the whole file, in
one horizontal scroll. The line numbers stay put. Copying lines leaves
the numbers and the + / − marks out.
Known extensions (ts, tsx, js, jsx, rs, py, go, json, css,
md, html, toml, yaml, yml, sql) are highlighted with the
github-dark theme. Anything else stays in --code-ink.
Rejected alternatives
- A per-file card in the transcript. The strip would grow with the session, and the diffs would scroll away with the messages. The count stays put. The diffs live on the review route.
- Putting review lines on
FileDiff. The edit tools already return a patch and hunks to the model. Review lines, with context and gaps, are a separate type so that tool result does not change. - Highlighting each diff line on its own. A comment or a string that crosses a line would be wrong. The full baseline and the full current text are tokenized, then each visible line takes the tokens for its number.
Failure modes
- A non-UTF-8 file is
400, the same ashunks_for_session. - A missing session is
404. - A failed review fetch leaves the strip hidden when it has no files yet. The review screen shows the error.
- Hiding both sides is not a state. Current and Previous each hide one side.
MCP
This page settles D10 and defines how Robi hosts MCP servers so their tools join the agent registry. It is the design for the MCP client in M8. Modes are in agent-modes.md. The approval bar is in chat-ui.md. Child agents are in subagents.md.
What this page does not cover
| Topic | Where it belongs |
|---|---|
| Built-in read, edit, and shell tools | read-tools.md, editing-tools.md, shell-tool.md |
| How a large MCP result is crushed | mcp-output.md |
| Robi as an MCP server | Later. This page is the host: Robi connects to servers other people run |
| A skill file | skills.md. A server prompt template is not a skill |
Problem
The model can already read the workspace, edit it, and run a command. It cannot open Linear, query a database, or call a service the user already runs as an MCP server for another agent. Those servers speak one protocol and publish a tool list. Rebuilding each of them as a Robi tool does not scale, and it puts every integration in this repository.
A server is also a process the user did not write, started with the user’s credentials, free to talk to the network. Its tool descriptions and its results are text from outside the workspace. Treating that text as instructions, or starting a server because a repository committed a config file, is how a project takes over the session.
Decision
Robi is an MCP host. rmcp speaks the protocol. It lives in crates/robi.
robi-core does not spawn a process, open a socket, or name the protocol.
The client is crates/robi/src/agent/mcp/. Each remote tool is a Tool in the
existing registry.
D10: MCP stays out of the loop
MCP ships in M8. The Tool trait does not grow a dynamic-registration
method. The registry already accepts a tool after the agent is built, and
it gains remove so a server’s tools can leave when the server disconnects
or its list changes. A duplicate name is still refused. The loop looks
tools up by name at execution time, which is what makes a late add visible
on the next model call and invisible to a request already sent.
The trait stays fixed. A server that wants sampling, elicitation, or a
long-running task does not get a new method on Tool.
What the first cut speaks
rmcp negotiates the protocol version. The client accepts 2026-07-28
and the earlier versions that crate still speaks, including 2025-11-25
and 2025-03-26.
The client advertises roots and tools. It lists tools, calls a tool,
and honours notifications/cancelled and notifications/tools/list_changed.
tools/list is followed to the end of its cursor.
The client does not advertise sampling, elicitation, resources, prompts,
tasks, or completions. A server that offers only those still connects and
contributes no tools. A tools/call result that is a task handle, rather
than content, is a tool error. The client does not poll it.
Server instructions from initialize are logged and left out of the
system prompt. The tool list is the channel the model sees.
Configuration
Two JSON files, same shape. The user file is ~/.robi/mcp.json. The
project file is <workspace>/.robi/mcp.json. A missing file is an empty
server list. The files are read when an agent-mode actor starts. Editing
one during a turn applies on the next user message.
{
"mcpServers": {
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_PERSONAL_ACCESS_TOKEN": { "secret": "github_token" }
}
},
"linear": {
"url": "https://mcp.linear.app/mcp",
"headers": {
"Authorization": { "secret": "linear_token" }
}
}
}
}
A server id matches ^[A-Za-z0-9_-]{1,32}$. Any other key is skipped and
logged. A server has command or url, and not both. enabled: false
skips that server. Other unknown fields are ignored so a config copied
from another host still parses.
| Field | Stdio | HTTP |
|---|---|---|
command | Executable name, or an absolute path. A relative path is a config error | Absent |
args | Array of strings. Default [] | Absent |
env | Map overlaid on the scrubbed environment | Absent |
url | Absent | https, or http on 127.0.0.1 or localhost |
headers | Absent | Map of header values |
timeout_seconds | Whole call budget. Default 60. Above 300 is a config error | Same |
tools | Array of glob or re: patterns naming the tools to keep. Absent or null keeps every tool | Same |
An env or header value is either a string or { "secret": "<name>" }.
A string is passed through, which is how an existing config pastes in.
A secret object is read from secrets.toml and never written back. A
missing secret, or any other shape, skips that server and is logged.
Resolved values are not logged.
The same id in both files: the project entry replaces the user entry, and only after the project file is trusted. Until then the user entry stays.
Tool filter
A server that publishes 40 tools spends context on 40 schemas and 40
descriptions on every request. tools limits which of them reach the
session. Absent or null keeps every tool, which is what an entry without
the field did before. An array keeps only the tools that match, and []
keeps none.
{
"mcpServers": {
"linear": {
"url": "https://mcp.linear.app/mcp",
"tools": ["get_*", "create_issue", "re:^search_[a-z]+$"]
}
}
}
Each entry is a glob, or a regex when it starts with re:. A glob matches
the whole name and uses globset syntax: *, ?, [abc], {a,b}. A
re: entry is unanchored, so it matches a substring; anchor it with ^
and $ to pin the whole name. Matching is case-sensitive. Each pattern is
tried against the name the server lists (create_issue) and against the
registered name (mcp_linear_create_issue), so a name copied from a tool
card and a name copied from the server’s docs both work.
The filter runs at registration, not at connect. The connection still
lists every tool, and the status count and the omission log read that same
list. attach re-reads both files before every model call, so an edited
tools array applies on the next user message. A tool that stops passing
fails as an unknown tool, the same as one from a server that dropped.
The filter runs before the 64-tool cap, so it picks which 64 a server may contribute.
A pattern that does not compile skips that server and is logged, the same
as a relative command. A pattern that compiles and matches nothing is
logged once per connection and changes nothing else; a typo loads fewer
tools without an error.
Listing tools from a shell
mcp-tools is the diagnostic binary. It takes a server id, reads the same two
JSON files, the same secrets, and the same path_entries setting, connects
through RmcpOpener, and prints tools/list. It opens no database, so it runs
while the app does.
config::load is the one read path: the hub starts servers from it, reports
status from it, and the binary lists from it. The project hash rule holds in all
three. The binary has no workspace row to compare against, so its --trust flag
is the user saying yes to the bytes in front of them, which is what the Enable
control will do. Without the flag the project file is read, reported, and
contributes nothing.
The binary prints every tool a server lists, and says on stderr how many the
entry’s tools filter keeps. --kept prints that subset instead, which is the
shortest way to check a filter. It does not call a tool: execute needs an
approval decision, and that needs a session.
Trust
The user file starts when the workspace is focused. The user wrote it.
The project file does not start until this workspace has stored the
SHA-256 of that file. The hash lives on the workspace row, mcp_project_sha256,
null until the user enables the current contents. A missing file, a hash
mismatch, or a null column means the project servers are off. Changing
the file clears the match, so a newly committed server does not start on
the next message.
Two surfaces write that column, and both go through
agent::mcp::set_project_trust, which reads the file, hashes it, and calls
WorkspaceService::set_mcp_project_sha256. The service stays free of I/O; the
hash is computed by the caller.
PUT /api/v1/workspaces/{id}/mcp/truststores the hash and answers with the config as it now stands.400when the workspace has no project file. The shell’s Settings → MCP page renders this as a switch, with the ids and targets from the file beside it, so the reader approves what starts rather than a path. Env and header values are left out of the list.DELETEon the same path clears the column and closes that workspace’s servers, so a distrust takes effect without waiting for the next message. Leaving them running would mean a config the user just turned off kept answering.
The terminal app raises Confirm::mcp_trust from the Enter on its Project
config row and queues Action::SetMcpProjectTrust. A landed write re-focuses
the hub and re-reads both status lists.
Trust is a stored hash, not a stored yes: one edited byte stops the servers and the surface shows the file as untrusted again. There is no timer and no “remember this repository” — the bytes are the subject.
Process and HTTP
Stdio uses rmcp’s child-process transport. HTTP uses the streamable
HTTP client. One connection per enabled server per workspace, shared by
the sessions of that workspace. The shell starts them when that workspace
becomes the open one (POST /api/v1/workspaces/{id}/mcp). Switching to
another workspace closes the previous servers. Deleting the workspace
closes them too. An agent-mode turn reuses the open connections and
registers their tools; if the shell has not focused a workspace yet, that
turn starts them. Process exit kills any children still running.
The child does not inherit the parent environment. The scrub is the one
in shell-tool.md: no DYLD_*, LD_PRELOAD,
LD_LIBRARY_PATH, or any name containing KEY, TOKEN, SECRET,
PASSWORD, or CREDENTIAL. PATH is the user’s login-shell PATH,
read once with $SHELL -ilc 'printf %s "$PATH"' and falling back to
this process’s PATH, with the path_entries setting appended. That is
what lets a uvx or npm server resolve when Robi is launched from
Finder, where the process PATH is the minimal system one. HOME,
USER, LOGNAME, and LANG are set. The config env map is
applied after that scrub, so a token the user named is present and a
token they did not name is not. The working directory is the workspace
root. There is no cwd field.
The child is not put in the shell sandbox. An MCP server is an
integration the user enabled, and it needs the network and the
credentials its config names. The sandbox that wraps npm test would
make that server fail closed on the first call. Enabling the server is
the consent. stderr goes to that server’s log, and stays out of the
transcript.
command is resolved on that constructed PATH. An absolute path is
used as written. A name that does not resolve skips the server.
HTTP redirects are followed only when the next URL still matches the
url rule. A redirect to any other host or scheme fails the connection.
The client does not run the MCP OAuth flow. A 401 fails the server.
Static headers are how a remote server authenticates in this cut.
Initialize has 15 seconds. A process that exits is restarted at 1s, 2s,
4s, then 8s, and then 30s, and at most five times in ten minutes. After
that the server is failed until the user retries or the config changes.
A crashing server does not respawn forever.
The actor waits up to that initialize budget, in parallel, before its first model call. A server that is still down is omitted from that call. Tools that arrive later are registered before the next model call.
Logging
Every connection writes a log under ~/.robi/logs/mcp/<server_id>/, one
file per connection named mcp-<timestamp>.log. The directory is the
server id from the config, so two servers never share a file. The file is
mode 0600: its protocol lines can carry tool arguments and results.
Each line is the JSON-RPC message in one direction (-> sent, <-
received), one line of the child’s stderr, or a lifecycle note. Both
transports pass through the same point, so the streamable HTTP client and
the stdio child log initialize, tools/list, tools/call, the
notifications, and the errors the same way. The first line of a
connection names the target: the resolved command and args for stdio, the
URL and whether an authorization header is present for HTTP. Header and
env values never reach the file, so a token stays out.
The policy matches the rest of ~/.robi/logs/: the newest prior file is
kept, a file older than seven days is deleted, and a directory keeps at
most eight. It runs when a server opens and once at process start, which
sweeps every server directory and removes one left empty after its server
was taken out of the config. No line exceeds 32 KiB; a longer protocol
message is cut with a note.
The process log still carries the summary — mcp server starting, mcp server connected, mcp server failed, and the config errors — so the
per-server file is where one server is debugged.
Tools in the registry
tools/list becomes one Tool per entry that passed the server’s tools
filter. The registered name is
mcp_<server>_<tool>, with every character outside [A-Za-z0-9_-]
replaced by _. A name longer than 64 characters keeps the mcp_<server>_
prefix, cuts the tool portion, and appends _ plus six hex characters of
the SHA-256 of the original tool name. Two entries that sanitize to the
same name: the first in the server’s list is kept, the rest are logged
and skipped. A name that collides with a built-in is skipped. Built-ins
are registered first.
Each server may contribute 64 tools. The rest are logged and omitted.
list_changed removes that server’s previous names and registers the new
list. The swap is remove then register. A call already running finishes
on the connection it started on. A call that has not started, whose name
was removed, fails as an unknown tool.
The description the model sees is the server’s description, trimmed, cut
at 1,024 characters, prefixed with MCP server <id>. The description and the result are untrusted data. A missing inputSchema becomes
{ "type": "object", "additionalProperties": true }. A schema whose
JSON exceeds 16 KiB skips that tool.
Every MCP tool declares Concurrent. The client runs one tools/call
at a time per server and queues the rest on that server. A call to
read_file still overlaps. Exclusive would stall the whole turn on
one remote call, which is the wrong grain.
requires_approval is side-effect free. It returns NeedsApproval
unless this session’s allow list contains that server id and tool name.
The allow list is mcp_allows on chat_sessions, a JSON array of
{ "server", "tool" }, [] on create. The migration that adds
mcp_allows and mcp_project_sha256 updates
persistence.md in the same change.
Annotations (readOnlyHint, destructiveHint, openWorldHint, title)
are stored for the approval bar. They do not change requires_approval.
The server writes them.
Calling a tool
execute sends tools/call with the arguments the model supplied. The
client checks that the arguments are a JSON object and otherwise returns
InvalidArgs. ToolRun.cancel sends notifications/cancelled and
returns cancelled.
The result the model reads is the text content blocks, joined. An image,
audio, or binary block is replaced with a one-line placeholder that names
the type and omits the bytes. A resource link becomes its URI. isError: true is a tool error whose message is that text. Empty content is a tool
error. The tool’s own bound is 256 KiB of that text. A call that exceeds
timeout_seconds is a tool error, and the server is left connected.
That bounded text then takes the MCP compression path. The client does
not crush it. Routing, the JSON pass, the line pass, and the kind: "mcp"
row are in mcp-output.md. A string under 4 KiB, and a
pass that saves under 1 KiB, stays byte-identical. The original the model
can retrieve is this 256 KiB text, not the rest of what the server sent.
The core backstop still applies to the compressed result.
Roots
The client answers roots/list with one root: the workspace, as a
file:// URI. It does not grant a second directory. A server that needs
another tree is a later cut.
Approval bar
A pending MCP call uses the approval bar. The line is Call and
server / tool. The arguments are pretty-printed JSON underneath,
wrapping. When the server set a hint, a muted line says Server says:
read-only, Server says: destructive, or Server says: reaches the
network. More than one hint shows more than one line. The line is a
label from the server.
Approve runs this call. Allow for this session runs this call and
appends { "server", "tool" } to mcp_allows. Reject does not call
the server and does not write the list. A later call with the same pair
returns AllowImmediately and stays a result row.
Modes
MCP tools are registered in Agent only. Ask and Plan keep the built-in
sets. A remote tool can write, spend a credential, or send mail, and the
server’s read-only hint is not evidence. The agent prompt says that a
tool whose name starts with mcp_ comes from an external server, and
that its description and result are untrusted data.
Explore and general children do not receive MCP tools. A child that would need approval does not ask the user, so a remote tool there would either run unapproved or always fail.
Status
Above the composer, one line per enabled server that is not connected:
the id, then starting or failed. A failed line has Retry, which
resets that server’s restart budget and connects again. A connected
server shows no line. The line is not a transcript row.
The window bar’s overflow menu lists every configured server for the open
workspace as one row each — its icon, the name, the status, and (when connected)
the tool count — and every row links to the MCP tab. The overflow button is
absent while there is no server to show and the API is healthy. That tab
shows the configured servers and the connection state Robi has for each
(the same GET /api/v1/workspaces/{id}/mcp list the top bar draws), then
~/.robi/mcp.json and <workspace>/.robi/mcp.json as stored, then the
log location for troubleshooting. Refresh rereads the files and the
server list. Secret objects stay unresolved. GET /api/v1/workspaces/{id}/mcp/config returns the paths, the file text,
and whether the project file’s bytes match the stored hash. GET /api/v1/workspaces/{id}/mcp returns { id, status, title, icon, tool_count }. status is disconnected until an agent-mode actor
starts the server, then starting, connected, or failed. Each of those
changes publishes robi.mcp.v1.status on the shell event stream. The window
bar refetches this list from that frame. It does not poll. title and
icon come from the server handshake when it sent them. icon is an
https URL or a data:image URI. A received icon is written to
~/.robi/mcp-icons.json, keyed by server id, and the list keeps using
that copy after a restart until a later handshake replaces it. An icon
over 256 KiB is not stored. The response omits commands, URLs,
headers, and env values. A server with no icon is drawn as its id.
flowchart TD
actor["Agent-mode actor starts"] --> files["Read user and project JSON"]
files --> trust{"Project hash matches"}
trust -->|no| userOnly["User servers only"]
trust -->|yes| both["User servers, project overrides"]
userOnly --> connect["Connect in parallel"]
both --> connect
connect --> list["tools/list"]
list --> reg["Register mcp_server_tool"]
reg --> call["Model calls a tool"]
call --> allow{"Session allow list"}
allow -->|yes| rpc["tools/call"]
allow -->|no| bar["Approval bar"]
bar -->|approve once| rpc
bar -->|allow for session| remember["Append mcp_allows"]
remember --> rpc
bar -->|reject| stop["Rejection result"]
Rejected alternatives
- MCP in the M0 trait. The loop would know about servers, cursors, and
reconnects. Those are I/O.
removeon the registry is the whole core change. - One dispatcher tool,
mcp, with a server and a name argument. The model would not see each tool’s schema. The schema is the prompt. - Trusting
readOnlyHint. The server chooses the hint. A hint that skips approval is a server that skips approval. Hints are labels on the bar. - Allowing every tool once the server is enabled. Enabling starts the process. It does not review a particular call. The first call to each tool still asks. The session list is how the user stops being asked.
- Remembering an allow across sessions, or for the whole workspace.
A grant that outlives the chat is easy to forget. The list is a column
on this session, the same way
web_fetchremembers a host. - Putting the child in the shell sandbox. The profile hides
$HOMEand the network. Most servers would fail, and the user would learn to bypass it. The config is the explicit credential grant. The shell sandbox stays onshell. - Inheriting the parent environment. That copies the provider key into every server. The scrub runs first. The config map is the only way a secret name reaches the child.
- Loading project servers because the file exists. The file is in the repository. The hash on the workspace row is the user’s decision, and a changed file asks again.
- Injecting server
instructionsinto the system prompt. That text is untrusted and paid for on every turn. Tool descriptions already reach the model, attached to the tool they describe. - Sampling and elicitation. Sampling lets the server spend the model and read a prompt. Elicitation is a second question channel beside the approval bar. Neither is advertised.
- OAuth in the first cut. The browser flow, refresh, and storage are
a separate design. A header from
secrets.tomlcovers a server the user can mint a token for. - Resources and prompts in the first cut. Skills already load instruction files. A resource reader is a second read path with its own trust rules. Tools are the reason to connect.
Exclusivefor every MCP tool. One remote call would blockread_file. The per-server queue is inside the client.- A compressor inside the MCP client. The server’s text is the tool
result. Crushing it here would skip the session store, and a second
client would copy the line walker. The pipeline after
executeis the one pass. - A file watcher. The next actor rereads the JSON. A watcher duplicates that for the interval between messages.
- Robi as a server in the same cut. Exporting the built-in tools is a different trust boundary. This page only connects outward.
Failure modes
- The JSON does not parse, or a server has both
commandandurl, or neither. That server is skipped. Other servers still start. The turn starts. - The secret named in the file is absent. That server is skipped.
commandis not on the constructedPATH. The server isfailed. The model does not see its tools.- Initialize exceeds 15 seconds, or the restart budget is spent. The
server is
failed. The composer line says so. The turn starts with the servers that listed. - The project file changed. Its servers stop. The dialog asks again. User servers are unaffected.
tools/listreturns more than 64 tools, or a schema over 16 KiB, or two names that sanitize to one. The extras are logged and omitted.- A
toolspattern does not compile. That server is skipped and logged. A pattern that compiles and matches nothing is logged and the server contributes fewer tools than it publishes. - The model calls a name that was removed mid-turn. The tool error says the tool is gone. The turn continues.
- The server sets
isError, returns no content, or exceeds the timeout. The tool error is the text,empty tool result, ortimeout. The connection stays up on a timeout and onisError. - The process dies during a call. The call fails. The supervisor
restarts within the budget. The next model call sees tools only after
the new
tools/list. - Cancellation mid-call returns
cancelledand does not spend a restart. - A result over 256 KiB is cut by the tool’s own bound before compression.
retrievereturns that prefix, not the rest of the server’s payload. The core backstop still applies to the compressed result. - Ask, Plan, explore, and general never see the tools. A model that names one gets an unknown tool.
- Redirects off the allowed URL, and HTTP to a non-loopback host, fail the connection. No request is sent to the other host.
- stderr goes to the server’s own log, never the transcript, the approval bar, or the process log line. Header and env values reach no log.
- A server whose log file cannot be opened still starts; logging is disabled for that connection.
- A line longer than 32 KiB is cut in the log with a note. The tool result the model sees is unaffected.
Testing
cargo test -p robi-core stays free of sockets and processes. It covers
remove, and that a tool registered after the agent is built is the one
execute finds.
The trust path has its own tests: the hash stored for a file, the column cleared without reading anything, a workspace with no project file naming the path, one edited byte changing the hash, the terminal’s row raising the right question and queueing the write, and the route documented with both methods.
The mcp-tools tests live beside it. They cover the parser, a server entry with
no filter and one with a filter, --remote and --long, an unknown id naming
the configured ones, an untrusted project file reported and ignored, and
--trust reading it.
The client tests live in crates/robi and use an in-memory transport.
They cover: a scrubbed environment with the config secret overlaid and
the parent provider key absent; a project file ignored until the stored
hash matches and ignored again after a one-byte change; the 64-tool cap;
a tools filter that keeps one listed tool and drops another, and a
tools array that matches nothing; name sanitizing and a built-in
collision skipped; NeedsApproval before
the session list contains the pair and AllowImmediately after;
annotations present on the tool and absent from the decision; a
cancelled call sending notifications/cancelled; an isError result
becoming a tool error; initialize instructions absent from the assembled
prompt.
Skills
A skill is a directory with a SKILL.md. The prompt lists the name and
description. The body loads when the user names it with /id in the composer,
or when the model calls the skill tool. A bundled create-skill procedure
interviews the user and writes the directory. This page is the design for skills
in M8. The research behind it is
discovery/skills.md.
What this page does not cover
| Topic | Where it belongs |
|---|---|
| The rest of the system prompt | instructions.md |
| Which modes register the tool | agent-modes.md. This page names the set |
| Child agents | subagents.md. They do not receive the catalog or the tool |
| Path grants for ordinary workspace reads | read-tools.md |
| A settings screen, an installer, or a skill editor | Later. Files are the store |
Problem
The same procedure gets pasted into chat, or it grows inside AGENTS.md and
is then paid for on every turn. A release checklist, a test recipe, a review
pass. Those belong in a file the model can open when the task matches, and
that the user can name when they already know which one applies.
People already keep those files for other agents, under .claude/skills,
.codex/skills, .agents/skills, and the directories those tools share.
Robi has to read those trees, at home and in the workspace, and its own
.robi/skills beside them.
Decision
Where skills are read
A skill is a directory whose direct file is SKILL.md. Roots are scanned for
that filename at any depth, so a category folder such as
skills/shipping/land-it/SKILL.md counts. The id is the directory that
contains SKILL.md (land-it), not the category above it.
Each scope has the same root names. Home is ~/. The workspace chain is the
git root down to the workspace root, the same walk as project AGENTS.md.
No git root scans the workspace directory only.
| Order | Home | Each directory on the workspace chain |
|---|---|---|
| 1 | ~/.claude/skills | .claude/skills |
| 2 | ~/.codex/skills | .codex/skills |
| 3 | ~/.cursor/skills | .cursor/skills |
| 4 | ~/.opencode/skills, then ~/.config/opencode/skills | .opencode/skills |
| 5 | ~/.agents/skills | .agents/skills |
| 6 | ~/.robi/skills | .robi/skills |
Later wins. Home is applied first, then each directory from the git root
toward the workspace. A project skill overrides a home skill with the same
id. Inside one directory, .robi/skills overrides .agents/skills, which
overrides the tool-specific roots. Two ids in the same root: the shallower
path wins, and the other is skipped with a warning.
A direct child of a root may be a symlink to a directory. SKILL.md is read
from that target. Supporting files are listed from the target and must stay
inside it after canonicalization. A symlink that leaves the target is left
out of the file list.
The scan runs when a session actor starts, which is every user message. A file saved during a turn is visible on the next message.
What makes a valid skill
SKILL.md starts with YAML frontmatter. The id is the directory name. It
must match ^[a-z0-9]+(-[a-z0-9]+)*$ and be 1–64 characters. A directory that
fails that check is skipped.
| Field | Effect |
|---|---|
description | Catalog text. Required in the usual file. When it is absent, the first non-empty markdown paragraph is used, cut at 1,024 characters. A file with neither is skipped |
name | Display label in the composer menu. The id stays the directory name. / uses the id |
disable-model-invocation: true | Left out of the model catalog. /id still loads it |
metadata.opencode/autoinvoke: false | Same as disable-model-invocation: true. Either one is enough |
user-invocable: false | Left out of the composer menu. The model can still load it. A typed /id still loads it |
Other frontmatter is kept in the file and ignored. That includes
allowed-tools, disallowed-tools, hooks, context, model, effort,
paths, license, and compatibility. A !`command` line in the body
is markdown. Robi does not run it while loading the skill.
A skipped file is logged. The turn still starts.
The catalog
SkillCatalog implements PromptSource. assemble_session inserts it after
<cwd> and before <mode>. The block is omitted when the model has nothing
to choose.
<skills>
git-release: Create consistent releases and changelogs
go-tests: Run and interpret Go tests in this module.
</skills>
One line per skill the model may load: id: description. Descriptions are
cut at 256 characters. The block stops at 8 KiB. Skills past the budget are
dropped from the end of the precedence order (home and broader roots first)
and the block ends with [N skills omitted].
The text is untrusted, the same way a project AGENTS.md is untrusted.
Loading a skill does not add a tool, change a path rule, or approve a later
call.
The skill tool description says to call skill before following a listed
id, and that an /id already in the user message is loaded.
The skill tool
Registered in ask, plan, and agent. Concurrent. It does not ask for
approval. Explore and general children do not get it, and their prompts do
not include the catalog.
The argument is name, the id.
A known, model-invocable id returns:
{
"name": "git-release",
"description": "Create consistent releases and changelogs",
"directory": "/abs/path/to/git-release",
"files": ["scripts/changelog.ts", "references/release-policy.md"],
"body": "markdown without frontmatter"
}
files is at most ten paths relative to the skill directory, files only,
plus "truncated": true when more exist. body is capped at 32 KiB. Over
that, the head is kept and the result says the tail was cut.
An unknown id, or an id with disable-model-invocation, is a tool error.
The error for a manual-only id tells the model to ask the user to mention
/id, and not to carry the procedure out on its own.
Supporting reads use read_file. Each scanned skill directory is a read
allow for the session, including a directory outside the workspace. The
allow covers that directory and its children. It does not cover writes, and
it does not cover a sibling of the directory. The .. deny still applies
everywhere else.
/id in the composer
/ at the start of the composer opens a menu of user-invocable skills, and
only while the caret is still in that first token. A / after any text, or
after whitespace, does not open it. The filter is the text after /, matched against the
id, the display label, and the description. A row shows the label (or the id
when they are the same), the description, and whether it comes from home or
this workspace. A manual-only skill is in that menu and marked so. Choosing a
row inserts /id and a trailing space. The draft is plain text. A slash
inside a path or a URL does not open the menu and does not load a skill. The menu is
a Kobalte popover, styled with the same tokens as the mode menu. Opening it
does not move focus, so the composer keeps the caret and the filter updates
as the user types.
The list comes from GET /api/v1/workspaces/{id}/skills. Each entry is id,
label, description, scope (user or project), model_invocable, and
path. The scan is the same one the actor uses.
On send, the instruction string is unchanged. The handler resolves every
/id token that names a skill, including one hidden from the menu. Each
match is loaded once, in order of appearance. The user message stores the
typed text in content and the loads on skills:
{
"id": "git-release",
"description": "Create consistent releases and changelogs",
"directory": "/abs/path/to/git-release",
"files": ["scripts/changelog.ts"],
"body": "markdown without frontmatter"
}
Message.skills defaults to empty. Old rows still deserialize. The body
column is already the JSON of Message, so this needs no migration.
The provider sends the user text, then one block per load:
<skill name="git-release" directory="/abs/path/to/git-release">
markdown body
Files: scripts/changelog.ts
</skill>
The transcript shows the typed text, then one quiet row per load: Using
git-release. The row opens onto the description, the path, and the body.
An unknown /word stays in the text. The send still succeeds. A skill that
fails to read is omitted from skills and a warning is logged. The mention
stays in the text.
Headless input is the same string. There is no menu. /id still loads.
Creating a skill
Robi ships two bundled skills, create-skill and configure-mcp. Both are in
the catalog and in the / menu on every session, ahead of the home roots, so a
file with the same id in ~/.robi/skills or the workspace replaces one. Their
bodies are compiled into the binary. Nothing is written until the user agrees to
a draft.
The user starts create-skill with /create-skill, or by asking for a skill. The
description tells the model to load it when the user wants to create or
update one. The procedure is:
- If this conversation already contains the workflow, take the steps, the commands, and the corrections from it. Otherwise ask what the skill should do, when it should trigger, and what the result looks like.
- Ask whether the model may load it on its own. The default is yes. A no
sets
disable-model-invocation: true. - Ask where it lives. The default is home,
~/.robi/skills/<id>/SKILL.md. This workspace is<workspace>/.robi/skills/<id>/SKILL.md. The id is the directory name, and it has to match the id rule above. - Confirm the id, the description, and the body before writing. The description states what the skill does and the phrases that should trigger it. The body is the steps. Scripts, references, and assets are added only when the user asked for them.
- Write
SKILL.md. An id that already exists is left in place until the user agrees to replace it. Ask and plan cannot write files, so those modes show the draft and tell the user to switch to agent. A home path is outside the workspace, so the write pauses on the approval card the edit tools already use. A workspace path follows the same write rules as any other project file.
The reply names the path and says /id works on the next message. The scan
for the current turn already ran.
Updating a skill is the same procedure. The model reads the existing
SKILL.md, applies the change, and writes it back after the user confirms.
configure-mcp
configure-mcp is the second bundled skill. The description tells the model
to load it when the user wants to add, configure, or set up an MCP server. It
is an interview with the same write rule as create-skill: the entry is shown
and confirmed before anything is written. The procedure is:
- Ask which tool or service to connect. This names the server id and settles
the transport:
command(stdio) for a local server,url(HTTP) for a hosted one. - Ask where the config goes: global
~/.robi/mcp.json, or this workspace<workspace>/.robi/mcp.json. Both share the"mcpServers"shape, and a project id replaces the same id in the user file. - Ask for the transport fields: stdio
command,args, andenv; HTTPurlandheaders. - Ask about secrets, and write a token or key as
{ "secret": "<name>" }against an entry in~/.robi/secrets.tomlrather than inline. - Ask whether to set
timeout_secondsorenabled: false. - Ask whether to limit the tool list with
tools, which is a list of globs orre:regexes. Only a match is registered, so the rest cost no context. The skill says this only when the server publishes more than the user needs. - Show the JSON and the path, then write the entry into the existing
"mcpServers"object. - Tell the user to restart the app for the change to take effect.
The body notes the id rule, the project trust hash and where to approve it, and links the MCP servers guide. Details are in MCP.
Rejected alternatives
- Catalog only, and
read_filefor the body. gopi does this. The load is a generic read, the path has to be in the prompt, and/idcannot load a manual-only skill the model is forbidden to open. @as the mention. OpenCode and ChatGPT use it. This composer uses/, which is the mention Claude and Cursor already teach. The menu opens only for a/that starts the message, so a path or a URL later in the draft is left alone.- Hoping the model calls
skillwhen it sees/id. A mention the model ignores never loads. The host loads it while accepting the message. - Putting the body into
content. The stored user text would no longer be what was typed, and copying the message would copy the skill. - A synthetic assistant tool call. The transcript would claim the model asked for a load the user asked for.
- Personal skills overriding project skills. Claude Code does this. A home copy would hide the skill the repository committed. The instruction chain already lets the closer file win.
- Showing both copies to the model. Codex keeps duplicate names in the
picker. The catalog would not say which body
skillreturns. - Running
allowed-toolsor!`command`at load time. Those grant authority and execute shell before anyone has read the skill. A command in the body goes throughshelland its approval rules. - A file watcher. The next actor rescans. A watcher duplicates that for the interval between messages.
- Flat
skills/review.mdand.claude/commands/*.md. Those are command files. This page loadsSKILL.mddirectories. - A settings form that creates the file. The interview is a skill, the same way Codex, Claude, Cursor, and Gemini do it. A form would be a second editor for the same directory.
- Recording the screen. Codex drafts a skill from a captured workflow. That needs a recorder. The conversation is the source this procedure has.
- An eval harness inside
create-skill. Claude’s plugin runs the new skill against test prompts and tunes the description. The first procedure stops at a file the user has confirmed.
Failure modes
- No home directory skips the home roots. The workspace chain still runs.
- A root that does not exist is skipped.
- A
SKILL.mdthat cannot be read or whose frontmatter does not parse is skipped. A warning is logged. The turn still starts. - A catalog over 8 KiB drops entries and says how many.
/idcan still name a dropped skill, andskillcan still load it. The budget limits the prompt, not the set of ids. - A body over 32 KiB is cut. The tool result and the
<skill>block both say so. - A mention of an id that lost a precedence fight loads the winner.
- A child agent does not see the parent’s
<skill>blocks. The parent copies what matters into thedelegatetask. create-skillin ask or plan does not write. The draft stays in the reply.- A rejected approval card leaves the skill directory unwritten. The user can approve a later attempt.
Testing
cargo test -p robi-core stays free of disk. The catalog source and the
scanner live in crates/robi and use a temporary directory. Tests cover
precedence (home loses to the workspace, .claude loses to .agents,
.agents loses to .robi), a manual-only id absent from <skills> and
present for /, a user-invocable: false id absent from the menu route and
present in <skills>, a typed /id stored on Message.skills, an
unknown /word left as text, and a bundled create-skill that a home or
workspace file of the same id replaces.
Shell output
This page defines how a large shell result reaches the model smaller, and
how the model gets the capped stdout and stderr back. It is the log row of
M9 in the roadmap. The command, the sandbox, and the
256 KiB stream cap stay in shell-tool.md. The session
database that holds the original stays in persistence.md.
JSON arrays and search hits are not this page. They remain
docs/src/design/compression/tool-output-compression.md.
What this page does not cover
| Topic | Where it belongs |
|---|---|
| Whether the command runs, and the 256 KiB cap on each stream | shell-tool.md |
| Which MCP result uses this collapser | mcp-output.md. The line pass calls this collapser. JSON takes that page’s own pass |
Crushing JSON or a grep result | docs/src/design/compression/tool-output-compression.md |
| The context meter drawing the saving | roadmap F3.4. This page says the compressor reports bytes in and bytes out |
Problem
cargo test, pnpm test, and a failed build write the same line shape
hundreds of times, then put the useful part in the exit code, one summary
line, and a short diagnostic. The model pays for every repeated ... ok
on later turns. Cutting the stream at 256 KiB keeps a prefix of setup and
drops the summary that landed at the end.
A substring search for "error" is not a compressor. It keeps lines that
merely contain the letters, it repeats the head inside every window, and it
still has no copy of the bytes it dropped. A passing suite and a failing
build need different cuts. A learned model is a third cut, and it is the
expensive one.
Build order
Four phases, cheapest useful cut first. The store is not the last piece of work. A collapsed view with no way back is the silent truncate M9 forbids, so the store ships in the same change as phase 1.
| Order | Phase | What it costs | What it saves |
|---|---|---|---|
| 1 | Line collapsing | A state machine over lines. No I/O | A green cargo test or Compiling run, often down to a handful of lines |
| 2 | Head, tail, and error windows | Range merge on the collapsed lines | A failed build whose middle is still large after collapsing |
| 3 | Session store and retrieve | One table, written beside phase 1 | Nothing by itself. It is what makes 1 and 2 safe to show the model |
| 4 | A local line model | An ONNX runtime, feature-gated | Only the residue phases 1 and 2 still leave. Measure that residue before writing this |
Phases 1 and 2 are pure functions of one &str. They live in
crates/robi/src/agent/compress/shell.rs. robi-core does not take a regex
dependency and does not open the database. The loop calls a compressor
trait. The shell implementation and the table live in crates/robi. A
failing compressor returns the tool result unchanged and does not fail the
turn.
shell does not compress its own result. The pipeline below runs for a
shell result, on both streams. Line-oriented MCP text calls the same
collapser; which MCP shapes do that, and how the original is stored, is
in mcp-output.md. Every other tool is unchanged until
its own compressor exists.
Pipeline
Compression runs after Tool::execute and after the shell’s own cap, and
before enforce_result_ceiling. Each of stdout and stderr is already capped
at max_tool_result_bytes (256 KiB) inside the launcher. The original a
later retrieve returns is those capped strings, including truncated when
the launcher dropped a tail. It is not the rest of the pipe.
shell execute
|
| each stream already <= 256 KiB
v
redact the tool result
|
v
per stream:
under 4 KiB ---------> unchanged, no row
|
phase 1 collapse runs
phase 2 slice, only if the collapse is still over 4 KiB
savings under 1 KiB -> unchanged, no row
|
v
one tool_originals row for the call (both capped streams)
marker lines carry that row's id
|
v
transcript stores the compressed result
core ceiling still applies to that JSON
|
v
tool card reads the row and shows the capped streams
The trait the loop calls:
#![allow(unused)]
fn main() {
pub struct CompressRequest<'a> {
pub tool: &'a str,
pub result: &'a serde_json::Value,
}
pub struct CompressOutcome {
/// Replaces `result` in the transcript. Equal to the input when this
/// call was a no-op.
pub result: serde_json::Value,
pub original_id: Option<String>,
pub original_bytes: Option<Vec<u8>>,
}
}
original_bytes is the JSON object {"stdout","stderr","exit_code","truncated"}
from the tool result, before either stream was replaced. The core records
original_id on the tool call and does not write the blob. The crates/robi
implementation writes the blob in compress, or returns the bytes and lets
the adapter write them in the same transaction as the transcript append.
Either way robi-core does not name SQLite. Tests pass a compressor that
returns the input and original_id: None.
A stream shorter than 4 KiB is returned byte-identical. Phase 1 still runs on a longer stream. If the rendered stream is not at least 1 KiB smaller than the input, the stream is returned byte-identical and no row is written. A call where both streams take that path stores nothing.
Phase 1 — collapsing repeated lines
This is the whole compressor for a green test run. Phase 2 does not run when phase 1 already fits.
Preparing lines
Split on \n. Inside each line, if the line contains \r, keep only the
segment after the last \r. A progress bar is one line, not the history of
the bar. The stored original keeps the raw stream, carriage returns
included. Line numbers in markers count these reduced lines, and retrieve
documents that its offset counts the same way: split on \n, then last
\r segment. A caller that needs the raw bytes uses retrieve with
raw: true (phase 3).
A line is pinned when it matches an error pattern from phase 2. A pinned
line is never absorbed into a run. It is emitted as itself. That is what
keeps test tests::auth ... FAILED out of a passing collapse.
Runs
Walk the lines once. A run is contiguous lines with the same kind and the same template. A pinned line, a blank line, and a kind change all flush the open run.
| Kind | Match | Template | Flush at |
|---|---|---|---|
cargo-test | ^test \S.* \.\.\. (ok|ignored)$ | The status word only. Names may differ | 3 lines |
cargo-progress | ^\s*(Compiling|Checking|Downloading|Downloaded|Documenting|Finished)\b | The verb | 3 lines |
generic | Anything else unpinned | Numerics, hex, and UUIDs replaced, below | 4 lines |
FAILED is not in the cargo-test kind. Those lines are pinned by the error
table, so a failing test breaks the run and stays verbatim.
The generic template is one compiled regex, not a fresh pattern per line:
#![allow(unused)]
fn main() {
static SLOT: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(
r"(?x)
[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}
| \b[0-9a-fA-F]{8,}\b
| \b\d+(?:\.\d+)?(?:ms|s|us|µs|KiB|MiB|GiB|KB|MB)?\b
",
)
.expect("slot regex")
});
fn template_of(line: &str) -> String {
SLOT.replace_all(line.trim_end(), "0").into_owned()
}
}
test tests::test_auth_1 ... ok and test tests::test_auth_2 ... ok share
the cargo-test kind and the status ok, so they are one run even though
the names differ. Downloading crate A v1.0.0 and Downloading crate B v1.2.3 share the verb. Two unrelated lines share a generic template only
when they match after slots are replaced, for example the same sentence
with a different count. A digit run that sits against a letter or _
(v1.2.3, test_auth_1) is not a slot: \b does not split it. Those
lines collapse only when a kind above already grouped them.
The walk keeps the first line, the last line, the count, and the original
line range. It does not allocate a String per line of a generic run. A
cargo-test run also keeps the captured name of the first line and of the
last line, which is enough for the star pattern below. Names are the \S.*
between test and ....
#![allow(unused)]
fn main() {
struct OpenRun {
kind: Kind,
template: String,
first: String,
last: String,
first_name: String,
last_name: String,
start: usize, // 1-based reduced line
end: usize,
count: usize,
/// Present only while `count` is still under the flush threshold.
buffered: Vec<String>,
}
}
A short run is copied through verbatim from buffered. Once count
crosses the threshold the buffer is cleared and the run keeps the two
endpoint lines plus the count. Flushing a long run writes the summary and
a <<<ROBI_LOG repeated=… lines=…>>> marker. Flushing a short run writes
buffered. A line is never discarded because a run ended.
What a run becomes
Cargo test, shared name prefix at least 8 bytes and ending on :: or _:
test tests::test_auth_* (48 tests passed) ... ok
<<<ROBI_LOG repeated=48 lines=20-67>>>
ignored uses ignored instead of passed. The prefix is the shared
bytes of first_name and last_name only. That is a sample of the run,
not a proof that every middle name shared the prefix. When the two ends do
not share such a prefix, the star is the whole name:
test * (48 tests passed) ... ok
<<<ROBI_LOG repeated=48 lines=20-67>>>
Cargo progress:
Compiling ... (36 crates)
<<<ROBI_LOG repeated=36 lines=4-39>>>
The first line of the run is not repeated beside that summary. The summary
is the verb from the template (Compiling, Checking, Downloading,
Downloaded, Documenting, Finished) plus the count. Finished rarely
repeats; the threshold of 3 leaves a normal single Finished line alone.
Generic:
<<<ROBI_LOG repeated=12 lines=40-51>>>
<first line, truncated to 200 bytes on a char boundary>
The first line is real output, so the model can see the shape. The other eleven are not copied.
<<<ROBI_LOG is the marker prefix. It is not a comment and it is not
source. edit_file and write_file reject <<<ROBI_ in old_string, new_string, and
content, as editing-tools.md specifies.
A green cargo test of a few hundred tests becomes the progress summaries,
one test summary, and the real test result: line. That result is under
4 KiB. Phase 2 does not look at it.
Phase 2 — head, tail, and error windows
Run this only when phase 1’s text is still over 4 KiB. The input is the phase 1 text, whose collapse lines and pinned error lines are already one each. Line numbers in the markers are translated back to the reduced original through the ranges phase 1 recorded. A marker never cites a line number in the collapsed text.
Pinned events, which phase 2 must not drop:
- Every phase 1 summary line.
- Every line that matched the error table, and the window around it.
Everything else is eligible to be omitted outside the head and the tail.
Keep the first 12 reduced lines and the last 20. On a stream shorter than 32 lines those two ranges cover it, so phase 2 returns the phase 1 text.
Error lines
Match per line, anchored. Do not search for the substring error,
failed, or panic. Those match test tests::error_path ... ok,
0 errors, and panic_handler.
| Pattern | Window after the hit |
|---|---|
^error(\[E\d+\])?: | 2 lines |
^Error: | 2 lines |
^panic: or panicked at | 40 lines |
^stack backtrace: | 40 lines |
^Traceback \(most recent call last\): | 40 lines |
^thread '.*' panicked | 40 lines |
\.\.\. FAILED$ | 2 lines |
^FAIL\b | 2 lines |
^npm ERR! | 2 lines |
^error TS\d+: | 2 lines |
^E\s{2,}\S | 2 lines |
The window is 2 lines before the hit and the after-count above, clamped to
the stream. A 40-line stack window is how a panic stays intact. A 2-line
window around error[E0308]: keeps the rustc span lines that follow it.
Overlapping windows merge into one range.
warning: is absent on purpose. A build can emit hundreds of them. They
collapse in phase 1 when they share a template, and phase 2 may omit the
rest. The first warnings that sit in the head are still there.
At most 200 lines of error windows are kept, earliest hits first. A log that is 400 panics keeps the first windows and the tail. The omission marker says how many error hits were not given a window. The tail is still kept.
Rendering a gap
Walk the merged keep-ranges in order. Copy the kept text. Between two ranges, one marker:
<<<ROBI_LOG omitted=4200 lines=120-4319>>>
omitted is the number of reduced original lines in the gap. lines is
the 1-based inclusive range in that same numbering. Adjacent gaps do not
occur: merging the keep-ranges makes every gap one span.
Head and tail that overlap become one range. No marker is inserted in an
empty gap. The sketch that always pushes "... [middle logs omitted] ..."
is not this renderer.
Exit code stays the exit_code field on the tool result. Phase 2 does not
parse a summary and does not invent Passed: 142. When the real
test result: line is in the tail, it is copied because it is in the last
20 lines. When a non-zero exit code’s stderr is under 4 KiB, phase 2 never
sees it and the model gets that stderr whole.
Phase 3 — the original, and retrieve
This ships with phase 1. It is listed third because it does not shrink a log. It is the reason a shrunk log is allowed into the transcript.
What is stored
One row per shell call that actually replaced a stream. The blob is the
capped stdout, the capped stderr, the exit code, and the tool’s truncated
flag, as JSON. Redaction has already run. Deleting the session deletes the
row.
The transcript stores the compressed result only. The tool card loads the
row and renders the capped streams, which is the output the user already
sees today. A missing row shows the transcript text. The turn does not
fail. Restart loads the transcript as stored, so a provider prompt-cache
prefix is not rewritten, and retrieve still resolves the id.
robi-core records the id on the tool call. The bytes go in that session’s
~/.robi/sessions/<session_id>/blobs.redb, table originals, keyed by id.
originals_by_sha keys {sha256}/{id} so the 16-hex check digit still
resolves. Deleting the session deletes the directory. The body is not a row
in the shared SQLite file, so a large original does not hold that writer lock.
id is a UUIDv7, the same shape as a message id. sha256 is the hex
SHA-256 of body. body is the JSON above, not a second compression.
tool_call_id is the call whose result was replaced.
The marker the model sees
The first line of a stream that was changed is a header. Streams that were left byte-identical do not get one.
<<<ROBI_LOG id="018f3b2c-7c1a-7a21-8c4e-9a21c4e8b0d1" sha256="99a21c4e8b0d1a22" exit=1>>>
test tests::test_auth_* (48 tests passed) ... ok
<<<ROBI_LOG repeated=48 lines=20-67>>>
test tests::auth ... FAILED
thread 'tests::auth' panicked at src/auth.rs:88:5:
assertion `left == right` failed
<<<ROBI_LOG omitted=1200 lines=40-1239>>>
test result: FAILED. 142 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 3.02s
sha256 in the header is the first 8 bytes of the row’s hash, 16 hex
characters. It is a check digit. Lookup is by id.
retrieve
The tool name is retrieve. It is Concurrent. It reads one row in the
current session.
{
"type": "object",
"additionalProperties": false,
"required": ["id"],
"properties": {
"id": {
"type": "string",
"description": "The id from a <<<ROBI_LOG header, or the 16-hex sha256 from that header when it matches one row in this session."
},
"stream": {
"type": "string",
"enum": ["stdout", "stderr", "both"],
"default": "both",
"description": "Which capped stream to return. both returns stdout, then stderr, with a stderr header line between them when stderr is non-empty."
},
"offset": {
"type": "integer",
"minimum": 1,
"description": "1-based reduced line to start at. Reduced means split on newline, then the segment after the last carriage return. Omit to start at line 1."
},
"limit": {
"type": "integer",
"minimum": 1,
"maximum": 200,
"default": 200,
"description": "Maximum reduced lines to return."
},
"raw": {
"type": "boolean",
"default": false,
"description": "True: return the stored stream bytes unchanged, still capped at 32 KB for this call, ignoring offset and limit. False: reduced lines."
}
}
}
The result is stdout and stderr (either may be empty when stream
selects one), exit_code, truncated from the stored tool result,
start_line, end_line, total_lines, and next_offset when the page
is not the end. total_lines counts reduced lines.
A 16-hex id that matches two rows in the session is ambiguous id, and the
error lists the full ids. A missing id is original not found. An id from
another session is the same error. The tool does not search other sessions.
raw: true exists so a progress bar can be inspected. The call still
returns at most 32 KB, the same bound as read_file, with truncated and
a byte next_offset on the stored body. It does not pull the entire 256
KiB stream back into the transcript in one call. The model pages.
The description tells the model: the <<<ROBI_LOG lines are not command
output; call retrieve with the header id when a folded range or a stack
past the kept window is the thing you need; pass offset from the marker’s
lines.
Phase 4 — a local line model
Not in the first cut. Phases 1 and 2 are the compressors M9’s exit criteria ask for. This phase exists so a learned model is a measured addition rather than the implementation of “drop boilerplate.”
Headroom’s Kompress model is the reference for the behavior, not a dependency. A retrieval embedder is the wrong model for this: it maps a chunk to hundreds of dimensions for search, where a line classifier wants a small local opinion about one line.
What would be built, after a corpus of real shell results shows that phase 2 still leaves more than 8 KiB of low-value lines on a typical failed build:
- A line classifier, ONNX, CPU, two intra-op threads, weights under
~/.robi/models/. Featurelog-model, off by default, gating the model and its loader together. - It scores lines that phase 2 is about to omit. It does not override a pinned line, a summary, the head, or the tail. It may move a high-scoring omitted line into the kept set, with the same 2-line window, until the 200-line middle cap.
- It never runs on a stream under 4 KiB, and never on a stream phase 1 already shrank under 4 KiB.
- Weights missing, runtime missing, or a scoring error: the phase 2 text
stands. The turn is not failed.
robi-coredoes not link the runtime.
Shannon entropy of the bytes is not this phase. A repeated ... ok line
and a unique short identifier can share a low score, and a minified or
base64 dump scores as high as a stack trace. The error table already keeps
the stack. An entropy threshold would be a second, less predictable copy of
phase 1.
Rejected alternatives
- Compressing inside
shell. Every tool would grow its own crusher. MCP results would miss it. The trait runs once, after execute. - The 100-line sketch that searches for
error,failed, andpanic.test tests::error_path ... okis kept as a diagnostic. Head lines are appended again inside each window. The middle marker is pushed even when the head and the tail already cover the stream.exit_codeis unused. Nothing stores the dropped lines. - Collapsing
... FAILEDinto the passing run. The failure is the line the model needs verbatim, including the test name. - Slicing before collapsing. The 12-line head is spent on
Compilinglines that phase 1 would have turned into one summary. - Truncating a kept stack at 2 lines.
panicked atwithout the frames is how the model guesses the wrong frame. Stack-shaped hits keep 40 lines. - Inventing
PassedandFailedcounts. A wrong parse of the summary is worse than copying the realtest result:line from the tail. - A
retrieve_raw_outputtool. It isretrievewith an id. A second name is a second schema for one read. - Putting the original only in the transcript, and also sending it to the model. The model then pays for the full stream, which is the problem. The card reads the row. The model reads the compressed result.
- Recovering bytes the 256 KiB cap already dropped. Those bytes were
never the tool result.
truncatedon the stored object says so. - Running the line model in phase 1. It is a large optional dependency, it is not deterministic, and the structural passes are the ones that shrink a test log. Measure a residue first.
Failure modes
- A stream under 4 KiB is byte-identical. No row. No marker.
- Phase 1 and phase 2 together save less than 1 KiB: the stream is byte-identical. No row.
- A regex that fails to compile is a programming error. The patterns are
constants. If
compressreturns an error anyway, the loop keeps the tool result and records no id. - The database write fails: the loop keeps the uncompressed tool result. The model does not see a marker whose id will not resolve.
retrievewith an unknown id, or an id from another session:original not found.retrievewith a 16-hex prefix that matches two rows in this session:ambiguous id, and the full ids.offsetpast the end: empty page,total_linesset, no error.- The launcher set
truncatedbecause a stream passed 256 KiB. The stored body is that prefix. The compressed view still says the tool result was truncated.retrievecannot return the dropped tail. - The tool card cannot load the row. It shows the transcript text.
- Cancellation before the row is committed leaves no marker in the transcript, because the result is not appended either.
- Phase 4 weights or runtime fail: the phase 2 text is the result. The turn succeeds.
MCP tool output
This page defines how a large MCP tool result reaches the model smaller, and how the model gets the bounded text back. It is the MCP row of M9 in the roadmap. Connecting a server, the 256 KiB bound, and the content-block rendering stay in mcp.md. The line collapser the text pass calls stays in shell-output.md. The session table stays in persistence.md.
Turn compaction, which summarizes older messages when the window fills, is roadmap F3.4. This page runs earlier, on one result, before that result is appended.
What this page does not cover
| Topic | Where it belongs |
|---|---|
| Whether the server is called, and the 256 KiB bound on the joined text | mcp.md |
Collapsing a shell log, and the <<<ROBI_LOG marker grammar | shell-output.md |
Crushing a grep result or a built-in JSON tool | docs/src/design/compression/tool-output-compression.md |
| Summarizing older turns | roadmap F3.4, docs/src/design/workspace/context-management.md |
Problem
An MCP tool returns one string: the text blocks of tools/call, joined,
already cut at 256 KiB. list_issues, a GitHub search, and a SQL client
return a JSON array of the same object hundreds of times. A log-shaped
server returns the same line hundreds of times. The model pays for every
repeated field on later turns.
The shell collapser is the wrong store for that string. Stuffing the text
into stdout with an empty stderr and exit_code: 0 invents a command
that did not run, and retrieve then describes the original as a shell
stream. Skipping every string that starts with { or [ leaves the array
in the transcript whole, which is the result that is actually large.
A model call that summarizes the payload was rejected with the rest of M9. The server’s text is untrusted, and a summary spends a turn to do what a walk of the JSON already does.
Decision
Names that start with mcp_ take one branch of the compressor the loop
already calls, after redaction and after the client’s 256 KiB bound, and
before enforce_result_ceiling. The client does not crush the text. A
tool error never enters this branch: isError is an error string on the
tool call, and errors stay verbatim.
The result is a JSON string. Routing looks at that string:
| Shape | Pass |
|---|---|
| Parses as a JSON array or object | The JSON pass below |
| Anything else at least 4 KiB | The shell line collapser, then head, tail, and error windows when the collapse is still over 4 KiB |
| Under 4 KiB, or a pass that saves under 1 KiB | Byte-identical. No row |
A top-level JSON string, number, boolean, or null is dense. It takes the line pass only when the raw text is at least 4 KiB, which a scalar almost never is.
The original a later retrieve returns is this bounded string, including
the [truncated at N bytes] line when the client cut a tail. It is not
the rest of what the server sent, and it is not a shell stream.
mcp execute
|
| joined text already <= 256 KiB
v
redact
|
v
under 4 KiB -----------------> unchanged, no row
|
parses as array or object -> JSON pass
otherwise -----------------> line collapser, then slice
|
savings under 1 KiB -------> unchanged, no row
|
v
one originals entry in the session blob file, kind "mcp"
header line carries that row's id
|
v
transcript stores the compressed string
core ceiling still applies
|
v
tool card reads the row and shows the bounded text
The walk lives in crates/robi/src/agent/compress/mcp.rs. It calls
compress_stream from the shell pass for the line shape. robi-core does
not parse JSON to decide a shape and does not open the database. A failing
insert returns the tool result unchanged and does not fail the turn.
What is stored
One row per call that actually replaced the string. Same table as a shell original. The blob is JSON:
{
"kind": "mcp",
"text": "<bounded tool result>",
"truncated": false
}
truncated is true when the client’s bound appended [truncated at N bytes]. text is the string the tool returned, redacted, including that
line. Deleting the session deletes the row.
A shell row stays {"stdout","stderr","exit_code","truncated"} and has no
kind. retrieve and the originals route tell the two apart by kind.
The transcript stores the compressed string only. Restart loads that
string, so a provider prompt-cache prefix is not rewritten, and retrieve
still resolves the id.
JSON pass
Parse with serde_json. A string that only starts with { or [ and does
not parse is the line pass. NDJSON and two values concatenated are the
line pass.
The rendered body is one JSON object the model can parse, after a header line. The header is not part of that object.
An array of objects
This is the common server payload.
Walk every element. An element that is not an object sends the whole array to the generic array rule below.
Collect keys in the order they are first seen, at most 64. Past 64, the
object records keys_omitted. For each key, record the JSON types seen
(string, number, boolean, null, object, array).
Keep the first 3 elements as the sample. An element whose serialized form
is over 4 KiB is shrunk before it joins the sample: each array value
becomes {"_items": N}, each nested object becomes {"_keys": ["..."]}
with at most 32 keys, and each string over 200 characters becomes its
first 200 characters plus …. A sample that is still over 4 KiB after
that shrink is dropped from the sample, and sample_omitted counts it.
When at least 80% of elements have a string or number at id, then
identifier, then name — first key in that list that qualifies — the
remaining elements contribute that value. Keep the first 40. rest_omitted
is how many elements are neither in the sample nor in that id list.
{
"compressed": "mcp-json",
"items": 240,
"keys": ["id", "title", "state"],
"types": {"id": ["string"], "title": ["string"], "state": ["string"]},
"sample": [],
"rest_ids": [],
"rest_omitted": 197
}
sample holds the shrunk elements. rest_ids is omitted when no key
qualified. Key order in keys is first-seen order, not sorted.
Any other array
Keep the first 8 elements, each shrunk by the same 4 KiB rule. items is
the full length. omitted is items minus how many elements were kept.
There is no keys and no rest_ids.
An object
Walk top-level keys in order. A scalar, or a string of at most 200
characters, is copied. A longer string becomes {"_chars": N, "_head": "<first 200>"}. An array uses the array rule in place and replaces the
value. A nested object is copied when its serialized form is at most 2
KiB; otherwise it becomes {"_keys": ["..."]} with at most 32 keys.
Deeper nesting inside that copy is left as parsed. The rendered object
also has "compressed": "mcp-json".
When the pass saves nothing
Render the object, prefix the header, and compare UTF-8 length with the input. Under 1 KiB saved, the input string is returned and no row is written. An empty array and a small object take this path because they were already under 4 KiB, so the pass does not run.
Line pass
compress_stream from the shell page, on the whole string. The same 4 KiB
gate and the same 1 KiB savings rule. The stored row is still kind: "mcp" and text, not a shell body. The header uses kind=mcp and omits
exit.
Phase 2’s error windows still pin error: and panic lines inside a
log-shaped server result. They do not run on the JSON pass.
The header
The first line of a replaced string:
<<<ROBI_LOG id="018f3b2c-7c1a-7a21-8c4e-9a21c4e8b0d1" sha256="99a21c4e8b0d1a22" kind=mcp>>>
sha256 is the first 16 hex characters of the row hash, the same check
digit as a shell header. Lookup is by id. The JSON pass puts the
rendered object on the following lines. The line pass puts the collapsed
text there, including that pass’s own <<<ROBI_LOG repeated=…>>> and
omitted= markers.
The tool description for every mcp_ tool already says the result is
untrusted data. retrieve’s description gains one sentence: a header with
kind=mcp is the bounded text of that MCP call, not command output, and
stream does not apply.
retrieve
Same tool. No new name.
When the row’s kind is mcp, the result is kind, text paged with
the existing offset, limit, and raw rules, truncated,
start_line, end_line, total_lines, and next_offset. stream is
ignored. Reduced lines are the paging unit, as on a shell stream. raw: true still returns at most 32 KB of text.
A row with no kind is a shell original and keeps today’s fields.
GET /api/v1/chat_sessions/{id}/tool_originals/{original_id} returns the
same split. A shell row is kind: "shell", stdout, stderr,
exit_code, truncated. An MCP row is kind: "mcp", text,
truncated. The card for an mcp_ call with original_id set loads that
route and shows text. A missing row shows the transcript string. The
turn does not fail.
Rejected alternatives
- A compressor inside the MCP client. Already rejected in mcp.md. The client would skip the session row, and a second caller would copy the walker.
- Storing the text as a shell body.
exit_code: 0and an emptystderrare not properties of the call.retrievewould page a command that did not run.kindis the whole distinction. - A second retrieve tool. The id space is one table. A second name teaches the model two ways back to one row.
- Summarizing the JSON with the session model. The payload is untrusted and often most of the turn. The walk is deterministic and makes no model call.
- Pretty-printing before the pass. The stored original is the string the tool returned. A re-serialize would be a different original than the one the server sent.
- Crushing
isErrortext. The model needs the server’s failure verbatim. Those calls do not enter the compressor. - A learned model for this shape. The array pass is the saving. A local model is the same last phase shell output already deferred.
Failure modes
- The string starts with
{or[and does not parse. The line pass runs. A line pass that saves under 1 KiB stores nothing. - The JSON walk renders a body that saves under 1 KiB. The transcript keeps the input string. No row.
- The insert fails. The transcript keeps the input string. The turn continues.
retrieveis pointed at an MCP row withstreamset. The text is returned andstreamis ignored.- The originals route is missing the row. The card shows the transcript string, header included.
- The client truncated at 256 KiB.
truncatedis true andtextends with the truncation line.retrievecannot see past that cut. - A header line is not server content. Editing tools already reject a
<<<ROBI_LOGline inold_stringornew_stringwhen that line is not file text. The MCP result is not a file.
Testing
cargo test -p robi-core stays free of the walker and the table.
compress/mcp.rs covers: an array of 200 objects keeps 3 samples, the
id list, and items; a 4 KiB nested object inside a sample becomes
_keys; a non-object array keeps 8 elements; a { prefix that does not
parse is not the JSON pass; a body that saves under 1 KiB returns none.
The compressor covers: a large mcp_ string stores kind: "mcp" and
replaces the transcript value with a string whose first line is the
header; a string under 4 KiB is byte-identical and writes no row; an
insert error returns the input; a tool name that does not start with
mcp_ is unchanged by this branch.
retrieve covers: paging an MCP row ignores stream and returns text;
a shell row still returns stdout and stderr.
Skills discovery
Notes for the skills work in M8. This page is the research.
The decisions are in design/skills.md: which directories
are read, how /id loads a skill, and how the model loads one with the
skill tool.
Sources were read on 2 October 2026: the Agent Skills specification, OpenCode and OpenCode v2, Claude Code, Codex, Cursor, and Gemini CLI.
What this page does not cover
| Topic | Where it belongs |
|---|---|
| The instruction chain Robi already sends | instructions.md |
| Modes and which tools they register | agent-modes.md |
| MCP servers | mcp.md |
| Plugins | roadmap M8, still open |
The settled format, tool, and /id behavior | design/skills.md |
What a skill is, across these products
A skill is a directory with a SKILL.md. The file starts with YAML
frontmatter, then markdown instructions. Optional files sit beside it:
scripts/, references/, assets/. The agent sees a short catalog (name
and description) on every turn. It loads the body only when a skill applies.
Supporting files load later, if the body points at them.
The specification requires name and description. name is 1–64
characters, lowercase letters, digits, and single hyphens, and it matches the
directory name. description is 1–1024 characters and says what the skill
does and when to use it. Optional spec fields are license, compatibility,
metadata, and an experimental allowed-tools. The body has no required
shape. The spec recommends keeping SKILL.md under 500 lines and moving
detail into referenced files.
That split is the whole point. AGENTS.md is always in the prompt. A skill
is a procedure that would be wasteful to send on every turn: how to cut a
release, how to review a diff, how this repo’s tests are run.
A skill is not a plugin. In every product that stays close to the spec, the skill adds no tools and grants no extra authority. Scripts run through the agent’s existing shell. gopi states this outright, and Robi’s instruction page already says instruction text cannot add a tool or change a path rule.
How each product lets someone define one
| Product | Where the user writes it | How they invoke it | How the model loads the body |
|---|---|---|---|
| gopi | ~/.gopi/skills/<name>/SKILL.md, <workspace>/.gopi/skills/, or instructions.skill_dirs | No slash command. The model decides, or the user asks in prose | Catalog in the prompt (name, description, path). The model calls read_file |
| OpenCode | .opencode/skills/, plus .claude/skills/ and .agents/skills/, project and global. v2 also takes extra directories and an HTTP catalog | v2: mention @skill-id. The model may also load it | A skill tool. The description lists id, name, and description. The result is the body, the base directory, and up to ten supporting paths |
| Claude Code | ~/.claude/skills/, .claude/skills/, enterprise managed settings, plugins, and skills synced from claude.ai. Legacy .claude/commands/*.md still works | /skill-name, with optional arguments. The model may also load it | The slash command injects the body. Automatic use is a separate load. The directory name is the command; frontmatter name is a label, except inside a plugin |
| Codex | .agents/skills/ from the working directory up to the repo root, ~/.agents/skills/, /etc/codex/skills, and skills bundled with Codex | $skill-name, or /skills. The model may also load it | Catalog of name, description, and path, capped at 2% of the context window (or 8,000 characters). The full body loads when selected |
| Cursor | .agents/skills/, .cursor/skills/, the same two under ~/, and for compatibility .claude/skills/ and .codex/skills/ | /skill-name in the agent chat. Option-Enter (Alt-Enter) pins the skill as a custom mode for the session | Catalog at startup. The agent decides. A slash attaches the skill to one message |
| Gemini CLI | ~/.gemini/skills/ or ~/.agents/skills/, and .gemini/skills/ or .agents/skills/ in the workspace. Extensions can ship skills | The model calls activate_skill. /skills lists, enables, disables, links, and reloads. There is no per-skill slash | Name and description in the system prompt. Activation asks the user, then injects the body and the folder listing, and adds the skill directory to the readable paths |
Codex and Cursor also ship a creator the user invokes ($skill-creator,
/create-skill). The creator asks what the skill does, when it should
trigger, and whether it needs scripts, then writes the directory. Codex adds
Record & Replay: the user demonstrates the workflow and Codex drafts a skill
from the recording. Claude Code’s /run-skill-generator is a narrower
version of that idea, for how to launch the current project.
Where they disagree
Precedence
gopi, OpenCode, and Gemini let the closer, more specific root win. A project
skill overrides a user skill with the same name. Claude Code does the
opposite across levels: enterprise overrides personal, and personal overrides
project. A deploy in ~/.claude/skills/ silently beats the one the repo
checked in.
Codex does not override. Two skills with the same name both appear in the picker.
Robi’s instruction chain already treats a later, closer owner as more specific. A project skill overriding a personal one matches that. A personal skill quietly hiding the repo’s skill does not.
Who is allowed to invoke
Claude Code splits this into two switches, and Cursor and OpenCode v2 copied the first:
| Frontmatter | User can type it | Model can load it | Typical use |
|---|---|---|---|
| Default | Yes | Yes | A procedure either side might start |
disable-model-invocation: true | Yes | No | Deploy, commit, send a message. The user picks the moment |
user-invocable: false | No | Yes | Background knowledge. Not a command |
OpenCode v2 uses metadata.opencode/autoinvoke: false for the same effect as
disable-model-invocation, and that key wins when both are set. Codex puts
the same idea in agents/openai.yaml as policy.allow_implicit_invocation.
gopi has neither switch: every valid skill is in the catalog.
Cursor and Claude also accept paths (globs). The skill is offered only
while the agent is working on matching files. A nested .cursor/skills/ or
.claude/skills/ inside a monorepo package is scoped to that directory
without a glob.
Permission to load
OpenCode treats skill names like other permissions: allow, deny, or
ask, with wildcard patterns, overridable per agent. deny hides the skill.
ask shows an approval before the body enters the conversation.
Gemini asks on every activation, because activation also grants read access to the skill directory.
gopi does not ask. It adds the skill roots to the session’s read grants, so reading a body does not raise a card. The body is still untrusted data, the same as a file or a web page. Project skills are scanned only after the workspace is trusted.
Claude Code’s allowed-tools is a different thing: for the turn that invoked
the skill, listed tools skip the permission prompt. That is a skill granting
authority, which the spec marks experimental. Combined with !command``
lines, which run a shell command and inline its output before the model sees
the body, a skill can act before anyone reads it.
Finding and fixing a skill that did not load
gopi skips a file that lacks name or description and does not say so. The
catalog is built at startup, so a new skill needs a restart.
Claude Code watches the skill directories and picks up SKILL.md edits in
the current session. Codex detects changes and falls back to a restart.
Gemini has /skills reload.
OpenCode’s troubleshooting list is the practical one: exact filename
SKILL.md, both frontmatter fields, unique names, and a permission that is
not deny. v2 adds a sharper footgun: the id comes from the path, and the
frontmatter name is only a display label, so @git-release fails when the
folder is release.
Sharing
Local folders are enough for one person and for a repo. Distribution is a
second product in the larger tools: Claude plugins and claude.ai sync, Codex
plugins plus $skill-installer, Cursor’s team marketplace and “sync skills
for cloud agents”, Gemini’s gemini skills install from a git URL, OpenCode
v2’s HTTP catalog. None of that is required to author or use a skill.
What Robi already has
The prompt assembler is an ordered list of sources. A skill catalog is another source, the same way gopi inserts one. The roadmap puts that source in M8, after the instruction chain. Project files still need a trust decision that does not exist yet; instructions.md leaves that beside skills.
The composer has mode, model, and effort. It has no slash menu, no mention picker, and no skills section in settings. Settings is a full page with a section rail and rows inside bordered cards, described in visual-style.md.
The loop already renders tool calls as cards. A load that is a tool call shows up in the transcript with no new chrome. A load that is a hidden prompt injection does not.
A solid UX for Robi
The design in design/skills.md takes the directory list,
the /id mention, and a bundled create-skill procedure from this section.
It leaves the settings page for later.
Four surfaces, with files as the only store. A form that becomes the source of truth will drift from the directory the agent reads, and it will not round-trip a skill written for another tool.
1. Directories people already know
Read the Agent Skills layout, and read the portable directory other tools already share.
| Scope | Path | When it applies |
|---|---|---|
| User | ~/.robi/skills/<name>/SKILL.md | Every workspace |
| User, shared | ~/.agents/skills/<name>/SKILL.md | Every workspace. The directory Codex, Cursor, Gemini, OpenCode, and Goose already use |
| Project | <workspace>/.agents/skills/<name>/SKILL.md, walked from the git root down to the workspace | This workspace, after it is trusted |
| Project, Robi-only | <workspace>/.robi/skills/<name>/SKILL.md | Same, and wins over .agents so a Robi-specific copy can override a shared one |
Also read .claude/skills/ and .codex/skills/, project and user, so a repo
that already has Claude or Codex skills works without a copy. Skip
.cursor/skills/ unless someone asks: Cursor’s paths, icon, and color
fields are harmless to ignore, but its directory is the least shared.
Closer wins, same as the instruction chain. User, then project from the root
downward, then .robi over .agents in the same directory. The loser stays
visible in settings, marked as overridden, with the path of the winner.
Codex’s “show both to the model” makes the catalog lie about which body will
load. Claude’s “personal beats the repo” hides the skill the team committed.
A file missing name or description, or whose name does not match its
directory, is listed in settings with the reason. It is absent from the
catalog. gopi’s silent skip is acceptable in a terminal and poor in a window
that can show the row.
Watch the directories. The next turn sees an edit. gopi’s restart is a consequence of building the catalog once at process start, not a property of skills.
2. A skill tool, and a short catalog
Put name, description, and scope in the prompt. Leave the body out. Cap the catalog the way Codex does: a fixed budget, shorten descriptions before dropping entries, and say in the prompt how many were omitted. Settings shows the same omission, so a missing skill is explainable.
The model loads a body by calling skill with the name. The tool result is
the markdown without frontmatter, the skill directory, and the names of
supporting files, not their contents. The model reads those with read_file
when the body says to. That is OpenCode’s load, and it is a better fit than
gopi’s read_file on a path buried in the catalog:
- The transcript already has a card for a tool call. The card is the receipt: the name, the one-line description, and the path. The body stays in the model context and out of the default row.
- The tool can refuse a name the catalog does not list, including one the user marked manual-only.
- The tool does not grant new paths. Supporting reads use the grants the session already has. Skill roots are readable without a card, as in gopi, and nothing outside them opens because a skill said so.
Recognize disable-model-invocation: true (and OpenCode’s
metadata.opencode/autoinvoke: false) so an imported skill does not start
running on its own. Those skills stay in the / menu and out of the catalog.
Ignore, and do not implement, the fields that turn a skill into a policy
change: allowed-tools, disallowed-tools, hooks, context: fork,
model, effort, and Claude’s !command`` shell injection. A skill that
needs a command says so in the body, and shell applies the sandbox and the
approval rules it already has. Document that in the skill page when it
exists, so a Claude skill that depends on those fields fails in an obvious
way rather than half-running.
user-invocable: false is worth honoring if the field is present: hide it
from the menu, keep it in the catalog. It is a small behavior and it matches
skills written as reference rather than as commands.
paths can wait. Scoping a nested .agents/skills/ to its directory, the
way Cursor and Claude scope a nested skill, covers the monorepo case without
a glob language. Glob scoping is a later addition if directory scope is not
enough.
3. The composer menu
/ in the composer opens a filterable list: name, description, and a scope
mark (yours, or this workspace). Choosing one inserts /name into the draft.
Sending that message invokes the skill as a user action: the body is loaded
for that turn, and the transcript shows the same card the tool would. Text
after the name is the argument, appended to the loaded body. Named
placeholders and $ARGUMENTS[N] can wait; Claude’s substitution table is
larger than the feature.
The menu is also where manual-only skills live, since the model cannot see them. An empty menu says where a skill file goes and links to the settings section. That is the gap in gopi: the only way to learn the catalog is to ask the model or read the prompt.
Pinning a skill for the whole session, Cursor’s custom-mode gesture, is a later choice. One-shot invocation matches “this message is a release” better than “every message is a release”. A pin duplicates modes, which Robi already has.
4. Settings, as a list of files
A Skills section on the existing settings page, in the same row-and-card layout as the other sections. Two groups, This workspace and Yours.
Each row shows the name, the description, the scope, and the path. An
overridden or invalid skill says why. A switch disables a skill without
deleting it; Codex does this in config.toml, Gemini does it with
/skills disable. The switch is per skill name and scope, stored in Robi’s
settings, and it applies on the next turn.
New skill asks for a name, a description, and a scope, writes a stub
SKILL.md, and reveals the file. The stub is the spec’s minimum, plus a
short “when to use this” section. Editing stays in the user’s editor. Robi
does not grow a markdown IDE for this.
Open reveals the directory. There is no installer, catalog URL, or
marketplace in the first version. Someone who wants a shared skill commits
.agents/skills/ or copies a directory into ~/.agents/skills/.
A built-in create-skill, invocable from the menu and hidden from automatic
use, is the in-chat path Codex and Cursor already taught people. It writes
the same stub the button writes, after asking what the skill does and when
it should trigger. Record & Replay is a different feature: it needs a trace
of the session and a judgment about which steps were the procedure. Leave it
until skills themselves are in use.
Trust and the transcript
Project skills are repository content. They stay out of the catalog until the
workspace is trusted, the same gate instructions.md already defers. Until
that gate exists, settings lists them as present and not loaded, with the
reason. User skills under ~/.robi and ~/.agents load without that gate;
they are the user’s own files.
Loading a skill does not approve a later shell or write_file. The card
for the load and the card for the command stay separate, so a skill that says
“run this installer” still looks like an installer.
Subagents get the catalog only if their mode is allowed to call skill.
Explore should not: it is a search, and a project skill is a prompt. That
choice belongs in the modes page when skills are designed.
Headless mode has no menu. The catalog and the skill tool are the feature
there. The menu and the settings list are the desktop presentation of the
same list.
What to leave for later
- Plugin marketplaces, HTTP catalogs, and install-from-git.
- Shell injection and tool pre-approval inside a skill.
- Per-skill model and effort overrides.
- Glob
paths, session pinning, and argument templates beyond “the rest of the line”. - Record & Replay.
- A skill changing the sandbox, the protected paths, or the tool registry.
Open questions
- Is
.claude/skills/plus.codex/skills/enough compatibility, or do people also keep skills only under.opencode/skills/and.cursor/skills/? - Does disabling a skill hide it from the menu, or only from the model?
- When the catalog budget drops a skill, is the settings row enough, or does the composer menu need the same warning?
- Should
create-skillbe allowed to write~/.robi/skills/from a chat without an approval card? Writing outside the workspace is exactly what the editing tools pause for. - Do nested project skills (a package’s
.agents/skills/) enter the catalog at session start, or only after a tool touches that directory, as Claude Code does?
S1 task set
The streamlining bet is empirical: a minimalist harness with a good prompt outperforms a complex one. This page is the run that decides it. It is the exit criterion for S1 in streamlining.md, and it runs against two builds of the same commit:
# The before: the tools the roadmap kept.
cargo run -p robi --bin robi-api --features read-tools,edit-tools
# The after: shell only, which is the default build.
cargo run -p robi --bin robi-api
Everything else is held equal: the same model, the same model settings, the same
AGENTS.md, the same workspace at the same commit, and the same user
instruction. Do not tune the prompt between runs. The point is to compare the
harnesses, not to make the new one win.
The tasks
Each is one session, started from a clean tree, in this repository. Together they cover the four jobs the tools used to own: read, search, edit, verify.
| # | Task | What it is testing |
|---|---|---|
| T1 | “Read crates/robi/src/agent/tools/shell.rs and tell me what Shell::execute does when the command fails” | A read of a known file. read_file versus sed/cat. |
| T2 | “Where is ShellAccess decided for each mode, and what else would need to change to add a mode?” | A search across files. grep/find versus grep -rn. |
| T3 | “In crates/robi/src/agent/tools/shell.rs, add a hint to the payload when the command exits non-zero but the sandbox did not block anything. Do not change the blocked-path hint.” | A small exact edit in a known file, plus verification. |
| T4 | “Add a --verbose note to docs/src/guides/editor.md’s ‘See what changed’ section, then confirm the markdown still builds” | An edit plus a real verification command. |
| T5 | “Why does a read-only shell refuse cargo check, and what would it take to allow it?” | Reasoning over the sandbox profile, with no edit. |
| T6 | “Rename the WriteAccess::ReadWrite variant to ReadWrite … “ — pick a task from your own backlog | An unfamiliar edit, so the result is not memorised. |
T6 exists because the first five are in a repository the model has seen. Choose a one-file change in a workspace the model has not been trained on, keep it identical across both runs, and discard the task if either run touches a second file.
The metrics
Record one row per task per build. Six numbers, because one is not enough:
| Metric | Why it matters | Where it comes from |
|---|---|---|
| Task success | The only one that matters if it moves the wrong way | Did the edit land, and does it do what was asked? Read the diff. |
| Model turns to done | A shell-first agent that needs ten extra turns is not simpler | The loop records an iteration per turn |
| Tool-call errors | Shell syntax mistakes, bad paths, failed replacements | tool failed and invalid arguments in the log |
| Tokens in and out | The prompt gets longer and the schemas get shorter; measure the net | Provider usage on the turn |
| Time to first useful diff | Perceived speed, not wall-clock | First file_changed or git diff in the trace |
| Approval prompts per task | Fewer prompts is the point; more means the sandbox is doing too much | awaiting_approval frames |
The roadmap’s exit criterion is stated against the first three: the same
number of turns as today, with no higher rate of failed commands. If the
shell-only build does not clear that, the answer is not to rewrite the prompt
first — it is --features read-tools, which restores the read half alone and
leaves editing on the shell.
Reading the traces
A single number will not decide this. Read the turns where the shell-only build lost, and classify each loss:
| Loss | Fix |
|---|---|
| The model does not know a command form | A prompt hint in agent/prompt/editing.rs |
| The model knows the form and needs three calls to do what one tool did | A missing tool; consider read-tools |
| The command is refused by the sandbox | A policy question, not a prompt question |
| The model gives up and asks the user | A prompt ordering problem, usually |
That distinction — prompt hint versus missing tool — is the roadmap’s main open question, and it is a judgement call over traces, not a score.
What was already measured without running this
Two things are facts rather than measurements, and they are in the plan:
- The default build drops
tree-sitter,fastembed, andsqlite-vecfrom the dependency graph.cargo tree -p robi | grep -E 'tree-sitter|fastembed|sqlite-vec'prints nothing. A later change deleted the crates outright, so no feature brings them back. - A cold workspace start issues no index work, because there is no
IndexHuband no index task left in the tree.
The task set above is what still needs a human at the keyboard.