The preview tool could only name a port, so a static build needed a server the terminal had to keep alive. `preview` now accepts a path: the app reads the file or folder over the room's ssh sandbox and serves it from a signed host, with `..` and dotfiles refused and a 16 MiB cap. The target is stored with the room and replayed as a durable event. The pane shows a static path with a reload control and keeps the port field as a local fallback.
28 KiB
rhema-together
Status: v1 implemented in this repository. The sections below are the design; §12 records where v1 differs. 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::stepprimitive. - 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 | 12-character base32, used in URLs |
| name | display name, editable by the owner |
| owner | the account that created it |
| workspace | the sandbox directory the room lives in |
| 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 48 |
| created_at, archived_at |
The workspace can hold several git checkouts. The agent starts at the
workspace root, and the file tree and preview start there too. Seeding is
a git clone into the workspace on first use, or a README seed 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
steprunsclose_orphaned_callsfirst, 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:
- The harness generates an ed25519 keypair per account and shows the public key.
- The account holder appends it to
authorized_keyson their machine, or pastes it into their provider's console. - A "test connection" runs
uname -aand 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:
- A shell on top. The harness keeps a cwd and sends each entered
line as
ecrou run ... -- sh -c <line>, 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. - A live machine per room.
ecrou upboots 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'sbashand every terminal tab can run at once. The natural shape isrhema-sandboxdinside 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 withrequest_ptyandrequest_shell, resize throughwindow_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 withfindtoday. SFTP is the better long-term route and would also replace thecatandteefile transfers.
The ssh backend implements pty and forward; list lands as a find
call in v1.
Workspace layout
<workspace>/ the room's root
<checkout>/ one or more git checkouts
.together/ room files the harness owns (prompt additions,
preview ports, uploads)
The agent starts 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 <name>, 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
The pane shows one target per room, either a port inside the sandbox or a
static file or folder. The agent sets it with the preview tool. The target
is stored and written to the room log as a durable preview event, so every
open pane updates and a reconnecting viewer gets it with the room detail.
The port field remains as a local fallback.
Port targets tunnel each request over ssh direct-tcpip to the sandbox. The
ssh connection is opened once per sandbox target and reused by every room and
port on it.
Static targets are read over ssh and served by the app. No server process is
started, so a preview does not depend on what a terminal is doing. A static
path is workspace-relative. A folder must contain index.html; a file is
served as itself and its parent becomes the asset root. Requests map onto that
root, and / serves the entry file. .., NUL bytes, and dotfiles are refused
in requests, and a target path that names a hidden file or folder is refused.
Files above 16 MiB are refused. The read uses the same ssh target as the
agent, so it adds no network path or permission.
Layout, one wildcard record:
app https://together.<domain>/room/<id>/
preview https://r<room>-p<port>-<expiry>-<sig>.preview.<domain>/
https://r<room>-s<hash>-<expiry>-<sig>.preview.<domain>/
hash is 12 hex characters over the static root and entry file. A link
minted for one static target stops matching when the agent points the preview
somewhere else. The room, target, expiry, and a 24-hex HMAC signature form
the first label. The signature is minted by the app when the pane requests a
URL and checked by the proxy, so the URL is not guessable from a room id. It
expires after 24 hours, and loading the room mints a fresh one. Treat a copied
preview URL as a read capability for that target until it expires.
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.<domain>.
The iframe carries sandbox="allow-scripts allow-same-origin allow-forms allow-popups".
Each room and target gets its own hostname, so root-absolute asset URLs
(/assets/app.js), JS-constructed URLs, and Location headers need no
rewriting. Vite's HMR WebSocket is not proxied in v1. Static previews ignore
HMR; port previews can disable it and use the reload button.
Auth: the preview host carries no app cookie, and the signed label is the
whole capability. Preview responses carry Referrer-Policy: no-referrer so
the signed host does not leak to third-party resources. The app's CSP names
*.<preview host> in frame-src.
Refresh: the pane reloads when a preview event arrives, and the button
reloads the current target.
Terminal
One PTY per browser connection, created inside the room's sandbox over the same ssh target and key the agent uses. v1 has one visible terminal per room; opening a second tab creates a second live shell with its own scrollback. Nothing is shared into the room log.
Transport: raw bytes over a WebSocket. Output arrives as binary frames;
input may be binary, or JSON {"data": "..."}; resize is JSON
{"type":"resize","cols":N,"rows":N}. The server sends
{"type":"ready"} once the PTY is up, and {"type":"exit","code":N}
when the shell ends. There is no server-side ring buffer; a reconnect
starts a fresh shell. Closing the socket closes the channel, which
hangs up the remote shell.
The emulator is xterm.js in the browser. The server parses no escape
sequences. 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=<last seq> 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:
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:
HostAgent::stepplus the turn setup around it, so a frontend can own the loop and drop one step.rhema-codesteers 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 assemblingAgentdirectly 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.Sandbox::pty,Sandbox::forward,Sandbox::list, each with a defaultUnavailable, the SSH backend implementing the first two.- 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:
- Sandbox: SSH only in v1. ecrou waits for a live mode, with the shell-on-top runner as a possible degraded mode.
- Provider and model: the room owner picks both, and only the owner changes them. Every turn spends from that config.
- Interrupts: any member. v1 has no rate limit.
- Preview auth: a per-room, per-port signed host label with a 24-hour expiry. A copied preview URL is a read capability for that port until it expires.
- Terminal sharing: private shells, one per browser connection. The room log does not record terminal contents.
Still open:
- Guest lifetime: cookie forever, or an account required after N days?
- Does the agent get tools to read the terminal and the preview later?
- Email: skip in v1 with operator password resets, or add SMTP from day one?
14. What v1 ships
This repository, as committed:
- Axum server, SQLite, and the built Nuxt client served from the same listener.
- Accounts (first account through
/setup), password login, guest accounts through single-use invite links with a display name. - Rooms with members, a per-room provider config, a sandbox target, a workspace, an optional repository URL, and an owner-only model and provider switch.
- One conversation per room, a
@rhemamention starts a turn, human messages are stamped with their author's name, and only themessagetool puts agent text in the room. - Turn-level steering: a new mention drops the running turn (status
interrupted) and starts a fresh one over the committed session.HostAgent::stepis not in the framework; the turn-level pattern fromrhema-codeis copied here. - SSH sandboxes through
rhema-sandbox-ssh, with the account's key encrypted at rest, host key learned on first connect. The agent, the files pane, and the terminal share one target. - The
messagetool, a prompt with room rules, per-turn usage recorded inturn_end. - SSE event feed with durable replay (
?since=) and transient deltas; a WS presence socket with online and typing state. - Read-only files tree and file view,
git statusandgit diff. - xterm.js terminal over a WebSocket PTY.
- Preview proxy over ssh
direct-tcpip, signed wildcard hosts, no rewriting. - No approval prompts: the sandbox is the boundary, so
AllowAll.
Not in v1: ecrou, multiple checkouts in the UI, port discovery, HMR through the preview proxy, a terminal ring buffer, editor cursors, co-editing, email, account recovery, rate limits, and desktop windows.
The schema is created by src/db.rs; the routes are in
src/api/mod.rs; the environment variables are in src/config.rs and
README.md.