From 04dd63c4cacc700ac19e7da2defd6d9f51311f26 Mon Sep 17 00:00:00 2001 From: Valentin Haudiquet Date: Sat, 28 Nov 2026 00:36:45 +0100 Subject: [PATCH] docs: add the rhema-together spec --- specs/rhema-together.md | 638 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 638 insertions(+) create mode 100644 specs/rhema-together.md diff --git a/specs/rhema-together.md b/specs/rhema-together.md new file mode 100644 index 0000000..0811896 --- /dev/null +++ b/specs/rhema-together.md @@ -0,0 +1,638 @@ +# rhema-together + +> **Status:** draft, discussed with the author. No code yet. +> **Framework:** consumes the Rhema crates at the workspace-pinned +> version. Adds nothing to `rhema-core`. + +## 1. What it is + +rhema-together is a multiplayer ADE in the browser. An account holder +creates a room, points it at a machine they own, and invites people. +Everyone in the room shares one conversation with one coding agent and +sees the same workspace: the chat, a preview of whatever the room +serves, a terminal, and a read-only editor. + +It is another frontend, after `rhema-code`, `rhema-acp`, and the +cloud frontends. It assembles `rhema-host-agent` for the turn, +`rhema-sandbox` for the machine, `rhema-session-store-sqlite` for the +model's memory, `rhema-transcript` for long rooms, and a provider crate +for the model. + +It is not `rhema-claw`. The claw is resident, single-owner, and keyed by +one bearer token. This is a room with many people, many sandboxes, and +accounts. They share crates, not code. If a piece turns out identical +later, it can move into a crate the way `rhema-cloud-agent` did. + +## 2. Vocabulary + +- **Account:** a person with credentials, provider configs, and sandbox + targets. +- **Guest:** a person who joined by invite link with a display name and + has no account yet. +- **Room:** the shared thing. A workspace, a sandbox, a model, a + conversation, and its members. +- **Member:** an account or guest inside a room, with a role. +- **Message:** one line in the room log, written by a human or the + agent. +- **Turn:** one agent run, started by a mention, made of steps. +- **Step:** one model exchange, the `Agent::step` primitive. +- **Sandbox target:** an account's remote machine, reached over ssh. +- **Provider config:** an account's model backend, model id, and key. + +"Room" is the product word. "Session" stays reserved for +`rhema_core::Session`, the model's memory, and for the login session. +Three meanings of one word is one too many. + +## 3. The room + +A room holds: + +| field | meaning | +|---|---| +| id | ULID, used in URLs | +| name | display name, editable by the owner | +| owner | the account that created it | +| workspace | the sandbox directory the room lives in | +| cwd | the checkout the agent starts in, relative to workspace | +| sandbox_target | the owner's ssh target | +| provider_config | whose model key pays | +| model | model id, may change per room | +| max_turn_steps | runaway guard, default 2048 | +| created_at, archived_at | | + +The workspace can hold several git checkouts. The agent's `cwd` is one of +them, and the file tree and preview show the workspace root. Seeding is a +`git clone` into the workspace on first use, or an empty directory the +first member fills. + +The owner picks the provider and the model, and only the owner changes +them. Every member's turns spend from that config, so a member never +needs a key of their own to talk in someone else's room. + +A room is persistent. It survives restarts, weeks of idleness, and +archival. Archiving hides it from the list and stops its sandbox handle; +nothing is deleted. + +## 4. Conversation + +### Two records + +The room log is the transcript the UI renders: append-only, one sequence +number per room, written by everyone, paged backwards, kept forever. + +The `Session` is the model's memory: assistant messages, tool calls, +tool results, the transcript view's compaction state, checkpointed by the +commit hook. + +This is the claw's split and it works. The log answers "what happened". +The session answers "what does the model know". The log is authoritative +for the UI and for replay; the session is authoritative for the next +request. + +### Attribution + +`Session` history has two roles. Five people and one agent collapse into +`User` and `Assistant`. The author therefore rides inside the content the +model reads: + +``` +alice: can we drop the cache layer? +bob: +1, the tests cover the read path +rhema: The cache is only used by the exporter. I will remove it and run the exporter tests. +``` + +The room log keeps `author` as a structured field and the UI renders a +label. The session gets the flattened line. This survives compaction, +export, replay, and reordering, because nothing is keyed by index. + +Rules for the model, stated in the room section of the system prompt: +every user message starts with the speaker's name; the agent does not +prefix its own messages; the agent addresses people by name. + +The agent's own messages reach the session as the `message` tool call and +its result, so the model remembers what it said without a second copy. + +### Mentions + +Only a message mentioning `@rhema` starts a turn. Everything else is for +the humans. The mention token is stripped before the model sees the line. + +`@name` mentions a person. They produce a notification, never a turn. + +### The agent speaks through a tool + +The agent's `TextDelta` is not chat. It is draft and reasoning, shown +collapsed or hidden. Chat lines come from a `message` tool: + +``` +message(text) -> "delivered" +``` + +The tool posts to the room log immediately, with author `rhema`, the +turn id, and parsed mentions. It is called zero or more times per turn, +and the prompt requires at least one at the end, even a bare "ack". + +Tool description rules: + +- Send one message when starting something that takes more than a + moment, when finding something the room should know, and at the end. +- Write to the room. Keep code to a screenful and point at files. +- Address the person you answer. +- Do not narrate tool calls one at a time. + +The tool is `ReplaySafety::Unsafe`. A crash after the post but before the +result revives as interrupted, and the message stands. It must not be +re-run. + +Fallback when a turn ends with no message: post the final assistant text +if it is non-empty, otherwise a system line saying the turn ended +without one. The prompt rule does the work; the fallback only catches a +missed call. + +### Turn rules + +One turn per room. The room owns the loop: + +``` +loop { + select! { + step = agent.step(session, sink, ctx) => { ... } + msg = inbox.recv() => { drop(step); append(msg); } + } +} +``` + +A mention that arrives while a step runs drops the step future at its +current await, appends the message to the session tail, and starts the +next step. The turn continues. Only the step dies. This is step-level +interruption, not the claw's turn-level steering: the turn keeps its +history, its step count, and its event stream. + +What the drop leaves behind: + +- The provider stream dies with the future. Tokens already streamed are + billed and lost. +- A running shell command dies with the future (`kill_on_drop`). A + remote command's process may outlive its channel; the model is told so. +- When the drop lands during tool execution, the assistant message and + its tool calls were already committed. The next `step` runs + `close_orphaned_calls` first, which writes one failure result per + unanswered call. The history stays valid and the model reads + "interrupted, the effect may have partially applied, verify state + before retrying". +- The new human message is appended after those results, in arrival + order. + +A message without a mention never interrupts. It is written to the room +log at once and appended to the session at the next boundary: the start +of the next turn, or the next step of the running turn. Each room keeps +an `absorbed_seq` cursor, so nothing is appended twice. The cursor +advances on every append, whatever the path, so the boundary pass and +the interrupt path cannot both write the same line. + +A burst of mentions that lands before the first drop completes all goes +into the same restart, in order, one message each. Nothing is folded. + +Interrupt permissions: any member may interrupt, because any member can +already run shell. The log records who did it, and the UI marks the +aborted segment as interrupted rather than letting a half sentence read +as final. Rate-limit a member who interrupts more than a few times a +minute. + +### Approval + +None. The sandbox is the boundary, the room trusts its members, and every +gated call would otherwise stop a turn nobody owns. The agent runs +`AllowAll`. + +What replaces the gate is the audit trail: every tool call appears in the +room log as a card with its command and output, visible to every member, +kept for the room's life. Abort is the control. A per-room confirm policy +can come later if rooms ever hold people who should not have a shell. + +## 5. The sandbox + +### Bring your own compute + +The harness runs on the author's server. The machine that executes +commands belongs to the account holder. + +Onboarding for a sandbox target: + +1. The harness generates an ed25519 keypair per account and shows the + public key. +2. The account holder appends it to `authorized_keys` on their machine, + or pastes it into their provider's console. +3. A "test connection" runs `uname -a` and stores the host key. + +The private key is encrypted at rest. Host keys use `accept-new` on first +contact and refuse a mismatch after that. + +The room holds one sandbox handle, opened on first use and dropped after +an idle period or when the owner changes the target. A room whose target +is unreachable keeps its chat: messages post, a turn fails with a room +message, and the panes show the error instead of a spinner. + +### Why ssh first + +The ssh backend already runs commands on a remote box with no daemon on +the far end. It can offer the three things the panes need: a pty for +the terminal, long-lived processes for a dev server, and file reads for +the editor. + +### What ecrou needs for a terminal + +The ecrou backend is one microVM per command. It boots, runs the command +with the workspace shared in, and powers off. Its stdin is null, it +exposes no pty, and nothing outlives the command. `--persist` keeps disk +state across boots, not processes. + +A web terminal needs a byte stream into a live process. Two ways to get +one from ecrou: + +1. **A shell on top.** The harness keeps a cwd and sends each entered + line as `ecrou run ... -- sh -c `, printing the captured output. + The isolation is exactly the agent's, because it is the same one-shot + machine, which is the attractive part. But it is a command runner, not + a terminal: no interactive program, no pty, no job control, no shell + state across lines, and a microVM boot per line. An emulator over it + would be decoration on a REPL. +2. **A live machine per room.** `ecrou up` boots a machine and keeps it + alive with stdio attached, one process per channel. This needs more + than parallel exec: a lifecycle (`up`, `attach`, `down`), a byte + stream in and out, and a supervisor inside the guest so the agent's + `bash` and every terminal tab can run at once. The natural shape is + `rhema-sandboxd` inside the machine and the harness speaking the + sandbox protocol to it, which then gives pty, parallel exec, files, + and forwarding from one place. That is an ecrou feature, not a + framework one. + +For v1 the sandbox is SSH to a machine or VM the account holder owns. The +VM is the isolation boundary, and one handle serves the agent, terminal, +files, and preview. Option 1 stays a candidate as a degraded mode for +accounts that only have ecrou, if a command runner is acceptable. Option +2 is the one to design when ecrou grows sessions. + +### Seam additions + +The `Sandbox` trait gets three capabilities. Each has a default method +returning `Unavailable`, so every existing backend compiles unchanged. +That is the family's falsification rule: a new capability must not edit +the backends that cannot offer it. + +- `pty(shell, cols, rows)` opens a bidirectional byte channel inside the + sandbox. SSH: a session channel with `request_pty` and `request_shell`, + resize through `window_change`. Local: `openpty`. Ecrou: unavailable + until it has live machines. +- `forward(host, port)` opens a local TCP listener that tunnels to an + address inside the sandbox. SSH: `direct-tcpip`, one channel per + connection. HTTP: needs a forward op in the sandbox protocol, or a + proxy on the sandbox host. +- `list(path)` lists a directory under the workspace. SSH can do this + with `find` today. SFTP is the better long-term route and would also + replace the `cat` and `tee` file transfers. + +The ssh backend implements `pty` and `forward`; `list` lands as a `find` +call in v1. + +### Workspace layout + +``` +/ the room's root + / one or more git checkouts + .together/ room files the harness owns (prompt additions, + preview ports, uploads) +``` + +The agent is started with `cwd` set to one checkout. The file tree and +preview start at the workspace root, so a room that grows a second +checkout shows it without a new room. + +## 6. The panes + +### Chat (the main view) + +Left rail: rooms, members, presence. Main column: the log, oldest at top, +paged backwards. Composer at the bottom with `@` completion for the +agent and for people. Each message carries author, colour, time, and, +for agent messages, the turn. Images and pastes ride the message row; +the bytes are served from a room route, and vision models get inline +image blocks the way the claw already sends them. + +Tool calls render as collapsed cards inside the turn: the command, the +exit code, and the output tail. The agent's draft text renders as a +collapsed "working" strip and is marked interrupted when a step dies. + +A turn is a visual block: started by ``, a spinner while running, +the agent's messages inside it, and a footer with steps, tokens, and +cost. The footer is per turn, not per message. + +### Preview + +Iframe at a preview URL. Discovery is a manual port field plus a scrape +of `bash` output for `localhost:` and `127.0.0.1:` shown as +suggestions. No heuristics beyond that. + +Serving: a harness listener per (room, port) tunnels through ssh +`direct-tcpip` to the sandbox. TLS and routing happen in the reverse +proxy. + +Layout, one domain and one certificate: + +``` +app https://together./room// +preview https://preview.together./room//port// +``` + +The preview needs its own hostname. It is repo code, and on the app's +origin it could call the API with the viewer's cookie, which turns every +opened preview into an account-stealer for the other members. A separate +`preview.` host has no app cookie (the cookie is `__Host-`, no `Domain`), +and preview responses carry +`Content-Security-Policy: frame-ancestors https://together.`. +The iframe carries `sandbox="allow-scripts allow-same-origin allow-forms +allow-popups"`. + +The path prefix is the fragile part. Apps that emit root-absolute URLs +(`/assets/app.js`) escape it, and JS-constructed URLs escape any rewrite. +The proxy strips the prefix, rewrites HTML `src`/`href`/`action`, CSS +`url()`, and `Location`, and passes `X-Forwarded-Prefix`. Vite and Next +still need their `base` configured. The preview pane shows a hint with +the port's URL when the page looks broken. + +If the prefix proves too fragile, move to +`https://-.preview./` with a wildcard DNS record and +on-demand certificates. That swaps a proxy route, not app code. + +Auth: the preview host carries no session cookie, so the proxy needs +another answer. The app mints a short-lived signed token when the pane +opens (`?k=`, or a path segment); the proxy checks it, strips it, +and forwards. One hour, bound to the room and the member. An unguessable +per-room token with no expiry is the simpler fallback, at the cost of a +link that works for anyone who holds it, forever. + +Refresh: a button, plus a reload when a turn ends, plus the dev server's +own HMR. + +### Terminal + +One PTY per tab, created by a member inside the room's sandbox. Tabs are +private by default; a share toggle lets others watch, and typing stays +with the owner until someone flips it. + +Transport: raw bytes over a WebSocket, binary frames for output, JSON +control frames for resize, close, and title. The server keeps a 1 MB ring +per tab and replays it on reconnect. Killing the tab closes the channel, +which SIGHUPs the remote shell. + +The emulator runs in the browser, from bytes. Ghostty's WASM build if its +API fits, xterm.js otherwise. The server parses no escape sequences in +v1. A server-side libghostty-vt is a later option: it gives screen +snapshots on reconnect and a way to let the model read the terminal, and +it costs an FFI crate that allows `unsafe`. That crate would live in this +project, not in the framework. + +### Editor (read-only) + +Tree from `list`, file from `read_file`, capped at 1 MB, binary files +shown as a notice. Syntax highlighting client-side. Refresh when the tab +is opened, when a turn ends, and on demand. When the file's hash differs +from the open copy, show "changed on disk" and offer a reload. + +Editing comes later, and only with a hash check on save. Co-editing is a +separate product decision, not a UI toggle. + +### Presence + +WebSocket frames: join, leave, typing, open file and selection, active +terminal tab, preview port. TTL plus heartbeat. Presence is never written +to the room log, and join and leave do not enter the model's history. + +Cursors are the end goal. With a read-only editor they start as +selection highlights, which needs no editing protocol. + +## 7. Wire + +HTTP for reads and writes, SSE for the room's event stream, WebSocket for +terminal, presence, and later editor cursors. + +``` +POST /api/rooms create, account only +GET /api/rooms list my rooms +GET /api/rooms/{id} +PATCH /api/rooms/{id} owner +DELETE /api/rooms/{id} owner, archives + +GET /api/rooms/{id}/messages?before=&limit= +POST /api/rooms/{id}/messages {text, mentions} +GET /api/rooms/{id}/events?since= SSE, turn events +GET /api/rooms/{id}/history?before= older turn events + +GET /api/rooms/{id}/files?path= +GET /api/rooms/{id}/file?path= +GET /api/rooms/{id}/git/status +GET /api/rooms/{id}/git/diff?path= + +POST /api/rooms/{id}/invites owner +DELETE /api/rooms/{id}/invites/{token} +POST /join/{token} redeem, display name + +POST /api/rooms/{id}/turns/{turn}/interrupt +GET /api/rooms/{id}/preview/ports +POST /api/rooms/{id}/preview/ports +WS /api/rooms/{id}/live presence, terminal, cursors +``` + +Turn events reuse the engine's shapes: step start, deltas, tool call and +result, usage, stop reason. Room frames wrap them with `turn_id` and +`seq`, and add `message`, `turn_started`, `step_aborted`, and +`turn_finished`. `rhema-cloud-agent`'s `wire` module is the closest +existing enum; it lacks authorship and chat, so this project defines its +own event type and copies the `Event` mapping. + +Every stream is resumable by sequence number. A reconnect asks for +`since=` and gets the gap, then live frames. The hub's +record-under-one-lock trick is the shape to copy: no gap, no overlap. + +## 8. Auth and trust + +### Accounts + +Email and password, argon2id. No email verification and no password +reset in v1; the operator resets by CLI. Email delivery is a dependency +worth adding only when the product needs it. + +Login session: 256-bit token in a `__Host-` cookie, HttpOnly, Secure, +SameSite=Lax, hashed at rest, 30-day sliding expiry. + +CSRF: a token in a readable cookie plus an `X-CSRF-Token` header on every +mutating request. Same-origin app, so this is enough. + +### Invites + +256-bit token in the URL, hashed at rest, single use by default, seven +days, role guest. Redeeming asks for a display name and sets a guest +cookie bound to the member row. + +The join page sends `Referrer-Policy: no-referrer`, so the token does not +leak through a click. Login and redemption are rate-limited by source +address. + +A guest who creates an account claims their member row, so their past +messages keep their name. A guest who never does keeps the cookie-bound +identity until the owner removes them. + +### Roles + +| role | may | +|---|---| +| owner | everything: invite, remove, config, sandbox, provider, delete | +| member | chat, interrupt, terminal, preview, files, git | +| guest | same as member, minus invites and room config | + +The difference is administration, not capability. Every member already +has a shell on the owner's machine through the agent. + +### The trust statement + +Joining a room is shell access on the room owner's machine, with +`AllowAll` and no approval gate. Invite only people you would give an ssh +login. The room log is the audit trail, and abort is the control. + +### Outbound connections + +The server dials addresses that users supply. Block loopback, link-local, +and multicast destinations by default, so a sandbox target cannot turn +the harness into a probe of its own network. An operator can allow a +private range in the config when every user is on the same network. + +### Secrets + +Provider keys and sandbox private keys are encrypted at rest with a key +from the environment or a 0600 file. The server refuses to start without +it. No route, log line, or event carries a key. + +## 9. Storage + +One SQLite file in WAL mode. + +``` +accounts(id, handle, display_name, email, password_hash, created_at) +auth_sessions(token_hash, account_id, created_at, expires_at, last_seen) +provider_configs(id, account_id, kind, model, base_url, key_ciphertext) +sandbox_targets(id, account_id, name, host, user, port, key_ciphertext, + workspace_root, host_key, created_at) +rooms(id, name, owner_id, workspace, cwd, sandbox_target_id, + provider_config_id, model, max_turn_steps, absorbed_seq, + created_at, archived_at) +members(room_id, id, account_id, display_name, role, color, guest_token_hash, + joined_at) +invites(token_hash, room_id, role, created_by, expires_at, max_uses, uses) +messages(room_id, seq, id, author_kind, author_id, text, mentions_json, + turn_id, created_at) +turn_events(room_id, seq, turn_id, kind, body_json, created_at) +turns(room_id, id, status, started_by, started_at, ended_at, steps, + usage_json, cost_usd) +``` + +The `Session` blob goes through `rhema-session-store-sqlite`, keyed by +room id, in the same file if the two schemas do not collide. + +Paging: messages and turn events are read backwards by sequence, one page +at a time. The log is unbounded; the model's view is bounded by +`rhema-transcript`, which already summarizes old messages and gives the +agent `zoom`. No manual `/compact`. + +## 10. Deployment + +One binary, `rhema-together`, plus a static web client embedded at build +time. Config file: + +```yaml +listen: 127.0.0.1:7800 +public_url: https://together.example.com +preview_origin: https://preview.together.example.com +database: /var/lib/rhema-together/together.db +secret_key_file: /etc/rhema-together/secret +max_rooms_per_account: 10 +max_terminals_per_room: 4 +``` + +Reverse proxy in front for TLS, the preview certificate, HTTP/2, and +WebSocket upgrade. Caddy or nginx; the binary does not terminate TLS. + +Refuse to start on a non-loopback `listen` without a `public_url`, a +secret key, and at least one account. First run prints a one-time setup +token that creates the first account. + +Backups: the SQLite file, the secret key, and the attachment directory. + +## 11. Framework changes + +Small and additive, in the framework's own terms: + +1. `HostAgent::step` plus the turn setup around it, so a frontend can own + the loop and drop one step. `rhema-code` steers at turn level: it + drops the whole turn future and starts a new turn with the nudge on + the same agent and session (`turn.rs`). That is enough for a + single-user TUI, where a turn boundary is a ledger row. A room wants + one continuous turn: dropping it resets the step budget and splits the + log into two turns with two footers. Owning the loop needs the turn + setup (approval install, revive, turn counter), `Agent::step`, and the + teardown; the loop body is fifteen lines. The alternative is + assembling `Agent` directly and duplicating prompt stamping, skills, + and transcript wiring, which is more code and more drift. Without the + change the room can copy the turn-level pattern today, and should not. +2. `Sandbox::pty`, `Sandbox::forward`, `Sandbox::list`, each with a + default `Unavailable`, the SSH backend implementing the first two. +3. Optionally SFTP in the ssh backend for file reads and listing. + +Not in the framework: the `message` tool, the room model, the wire, the +storage, the UI. The room section of the system prompt is passed through +`system` or `base_system`, so `rhema-prompt` does not change. + +## 12. Phases + +**Phase 0, the room talks.** Accounts, rooms, invites, chat, `@rhema` +turns, the `message` tool, ssh sandbox, SSE, audit cards. Chat only, no +preview, terminal, or editor. +Demo: a friend joins a link, asks the agent to scaffold a project, and +watches it happen. + +**Phase 1, the room sees.** PTY, terminal tabs, presence, WS transport. +Demo: two people watch one shell install dependencies. + +**Phase 2, the room runs.** Port discovery, ssh tunnel, preview host, +origin isolation. Demo: the agent starts a dev server and the room opens +it. + +**Phase 3, the room reads.** File tree, read-only viewer, change +detection, git status and diff. Demo: the agent edits a file and the room +reads the diff without opening a terminal. + +**Phase 4, later.** Save with hash checks, cursors, co-editing, multiple +checkouts in the UI, ecrou live mode, streamed desktop windows. + +Each phase should end with something a friend can use without an +explanation. + +## 13. Decisions + +Settled: + +1. Sandbox: SSH only in v1. ecrou waits for a live mode, with the + shell-on-top runner as a possible degraded mode. +2. Provider and model: the room owner picks both, and only the owner + changes them. Every turn spends from that config. +3. Interrupts: any member, rate-limited. + +Still open: + +4. Preview auth: a short-lived signed token minted per pane open + (recommended), or an unguessable per-room token with no expiry? +5. Guest lifetime: cookie forever, or an account required after N days? +6. Terminal sharing: private tabs with an opt-in watcher, or one shared + shell per room? +7. Does the agent get tools to read the terminal and the preview later? +8. Email: skip in v1 with operator password resets, or add SMTP from day + one?