Repository navigation
feat(serve): gentle-shell serve — server-owned sessions behind device pairing (RFC #3527 phase 1) - #3529
Draft
ismaelosuna7824 wants to merge 50 commits into
Draft
feat(serve): gentle-shell serve — server-owned sessions behind device pairing (RFC #3527 phase 1)#3529ismaelosuna7824 wants to merge 50 commits into
gentle-shell serve — server-owned sessions behind device pairing (RFC #3527 phase 1)#3529ismaelosuna7824 wants to merge 50 commits into
Conversation
One `--mode rpc` child per session (RFC Gentleman-Programming#3527 option A): - LF-only JSONL framing (CR stripped, U+2028/U+2029 kept, oversize records dropped with a marker), stdout read continuously, stdin kept open - a monotonic seq over every record, a replay ring bounded by count and bytes, and snapshot-required for cursors outside it - pending extension_ui_request dialogs replayed to late subscribers; the first extension_ui_response wins - per-subscriber bounded buffers: a slow client is dropped with a resync marker instead of stalling the child - Pi RPC commands under server ids (the caller's id restored) and Desktop RPC requests matched to their gentle-desktop-rpc widget answer Tests use a fake JSONL child; no Pi or model.
- one-time pairing codes (single use, 5 min TTL, rate-limited failures) - per-device bearer tokens stored only as sha256 in an owner-only file, constant-time compares, scopes sessions:read / sessions:operate / admin - immediate revocation with listeners (open streams close) - short-lived single-use stream tickets bound to one session, for EventSource clients that cannot send headers
Zero-dependency transport hardened like the Tower server: bearer tokens (no cookies), foreign Origin and unexpected Host refused, bounded bodies, CSP/no-store, per-request scope checks (per Pi RPC command and Desktop RPC method), SSE with Last-Event-ID resume and a 20 s heartbeat. Endpoints: pair, server info/stop, pairing codes, devices, tickets, sessions list/start/stop, /rpc, /desktop and /events.
`gentle-shell [home selectors] serve [--listen <host>:<port>] [--foreground]` plus `serve status|stop|pair|devices`. One server per agent home under an exclusive lock, registered in an owner-only <home>/serve/server.json (url, pid, protocol, started-at, a per-run local admin token). Loopback on a random port by default; a non-loopback --listen warns about plain HTTP. Sessions spawn this same launcher with the same home in --mode rpc with GENTLE_SHELL_INTERACTIVE_HOST=1. A new home is bootstrapped like a first launch so its sessions still treat it as Gentle Shell's own.
docs/serve.md documents the endpoints, the SSE event stream (seq, replay, snapshot-required, dialog replay, resync), pairing and scopes, stream tickets, the security model and what later phases add (WebSocket, terminals, SSH/LAN reach, mobile). README and the launcher reference link it.
|
Important Draft PR not reviewedDraft PRs are not automatically reviewed by default.
To automatically review draft PRs, update your CodeRabbit configuration: reviews:
auto_review:
drafts: true
|
This was referenced Nov 24, 2026
…DNS name - `serve --allow-host <name>` (repeatable, exact DNS name, no port) adds names the Host check accepts on top of those the listen address allows; the daemon forwards it. - A full MagicDNS name (box.tailnet.ts.net) was otherwise refused with 421 bad_host on 0.0.0.0. - Help, docs/serve.md and docs/readme-reference.md list the flag; tests cover parsing and the allowlist.
…chine - Install the checkout (Node, corepack/pnpm, what postinstall writes), the gsdev helper, and how the checkout's home relates to an installed Gentle Shell (reuse providers safely with GENTLE_SHELL_NO_AUTO_SETUP=1, or a separate --home). - Start/status/pair/devices/stop, logs, lifetime, and an optional systemd user unit. - Reaching it from a Mac: SSH tunnel (same port on both ends) or 0.0.0.0 on a LAN/tailnet with the Host rules, --allow-host and ufw; curl pairing flow; pointer to gentle-shell-gpui#247. - Troubleshooting table.
A sessionId whose conversation Pi never wrote (no messages yet) made '--session <id>' exit with 'No session found matching', so clients could not resume an empty tab after a restart. '--session-id' opens the folder's session with that exact id or creates one with it, and never stops to ask about forking another project's session.
… token
- Public identity { schema: gentle-shell.serve.identity/v1, serverId, name, protocol, version }:
a client holding a connection code probes each advertised address and pairs only where
the serverId matches. No secrets; Host and Origin checks still apply.
- `gentle-shell serve share [--port <n>] [--always] [--json]` opens this home's server to the
local network (starts it on 0.0.0.0:8787 or the next free port, reopens a loopback one
that runs no sessions, reuses one already there), mints a pairing code and prints
gsc1.<base64url JSON {v,id,n,p,a,c}> for Gentle Shell GPUI to paste.
- Addresses: non-loopback, non-link-local IPv4 (LAN first, bridges last), then the
hostname and <hostname>.local; at most 8.
- Linux firewall hint (ufw / firewall-cmd) without running sudo.
- --always hands the server to a systemd user unit or a macOS LaunchAgent running the same
launcher, home flags and kept environment; `serve share --off` removes it. Windows: refused.
- Docs: quick start for GPUI at the top of docs/serve.md, connection code and autostart
reference, readme-reference and help text.
A server listening on the network also binds UDP 0.0.0.0:<HTTP port> and answers {"t":"gentle-shell/discover","v":1} with {"t":"gentle-shell/here","v":1,id,n,p} by unicast (512-byte cap, 20/s global and 4/s per source). A failed UDP bind is logged and the server runs without discovery.
serve share now prints the short pairing code first and the gsc1. code as the fallback, notes when discovery is off, and its firewall hint opens TCP and UDP. --json adds pairingCode and discovery.
- set_host_tools registers a client's tools as real Pi tools (pi.registerTool after startup, exposure direct, guidelines as promptGuidelines); a new set replaces the provider's old one and unregistered tools are re-registered hidden. Names held by a built-in, an extension or another provider are rejected per tool. - A call emits host_tool_call and waits for host_tool_result (8 MiB content cap); an aborted turn or 10 minutes without an answer ends it with host_tool_cancel. Late answers are already_answered, strangers unknown_call. - The router accepts larger requests for these two methods only (1 MiB / 9 MiB). - Tests over a fake registry plus a real Pi SDK session with an offline scripted provider.
- set_host_tools through /desktop registers under the calling device's id; /rpc refuses /gentle:desktop prompts naming set_host_tools or host_tool_result (use_desktop_endpoint). - Only the provider's device may answer its call (403 otherwise); /desktop accepts up to 9 MiB for these two methods and keeps 80 KiB for the rest. - A call for a device with no open stream is answered at once with an error result the model reads; after the device's last stream closes, its calls fail after a 10 s grace (at once on revoke). A reconnecting device gets its waiting calls re-sent. - Fake child gains fake_host_call / fake_host_cancel for the tests.
- host_tool_result takes optional details (JSON object, 1 MiB) that become the Pi tool result's details. - host_message sends a client's custom message through pi.sendMessage (auto: start a run when idle, steer while streaming; steer/followUp/nextTurn pass through); persisted as a custom_message entry. - set_host_context keeps one hidden host.context.<provider> message per provider, added by a before_agent_start handler before each run; empty content clears; a session change clears all. - serve: both go through /desktop only (sessions:operate); set_host_context's provider is the device. - Tests over the fake registry plus the real Pi SDK session with the offline provider.
- set_host_tools rejects only built-in/extension names; a name may have several providers. The model sees the most recently registered provider's definition; when it drops the tool the next one's takes over. - Calls go to the most recently active connected provider (new set_host_activity, sent by serve only), else the newest registration; host_tool_call.provider names who must answer. - serve tracks per-device activity per session (start, any operate request), tells the session the connected host providers in that order when it changes, and shows lastActiveDevice in the session view. Clients cannot send set_host_activity (403 via /desktop, use_desktop_endpoint via /rpc).
- POST/GET/DELETE /api/sessions/:id/forwards: one listener per forward on the server's listen address, proxying only to 127.0.0.1/[::1]:<port>; HTTP and SSE streamed, WebSocket upgrades piped, Host/Origin checked, 64 connections each. - Single-use 60 s gs_ticket, then a per-forward HttpOnly SameSite=Strict cookie; the ticket and every gs_fwd_* cookie are stripped before the page sees them. - Forwards close with their session, on device revoke, on DELETE, and after 12 h idle. - --forward-ports <from>-<to>; serve share uses 8800-8899 and its firewall hint opens it. - GET /api/server returns the server user's home for sessions:operate tokens.
- POST /api/tower (sessions:operate) starts Gentle Tower in the server process (127.0.0.1, fresh token, no browser) when it is not running and answers with a forward whose link keeps Tower's token path; GET reports it, DELETE stops it and closes its forwards; it also stops with the server. - The forward's own Origin reads as Tower's, so Tower's origin check passes.
…ame, remove, search and watch Absolute server paths under /api/fs/*, sessions:read for reads and sessions:operate for writes (the server user's authority). Atomic writes with If-Match and create_only, 8 MiB reads with ETag/If-Modified-Since, ranked filename search, debounced change streams. remove/rename refuse the root, the home and folders above it. /api/server also names platform, arch and pathSeparator. Shared HTTP helpers move to lib/serve-http.ts.
POST /api/git runs git without a shell and answers { code, signal, stdout, stderr (base64), truncated, timedOut }. Read-only subcommands need sessions:read (GIT_OPTIONAL_LOCKS=0), the rest sessions:operate. No prompts, pager or editor; 120 s (600 s for network commands), 32 MiB stdout. Configuration and options that make git run another program (core.sshCommand, core.fsmonitor, core.hooksPath, uploadpack.*, alias.*, --upload-pack, --exec, ...) are refused, and env takes an allow-list of GIT_* names.
POST /api/uploads?name= (sessions:operate) stores up to 64 MiB under <home>/serve/uploads/<device>/<random>/<name> (owner-only) and answers its path for the prompt; uploads are removed after 7 days. The CLI now passes the serve folder and its environment to the server.
POST/GET/DELETE /api/forwards open, list and close forwards that belong to no session (kind "server", sessionId null), with the same tickets, cookies and rules as session forwards; they close on DELETE, revoke, idle or server stop. Every Forward now carries its kind. GET /api/services lists Engram (ENGRAM_URL or 127.0.0.1:7437, probed on /health) and Gentle Tower while it runs.
Persistent terminals live in gentle-term-host ($GENTLE_TERM_HOST, <home>/serve/bin or PATH), which serve starts detached on first use and reaches over the owner-only <home>/serve/term.sock (JSON Lines). /api/terminals opens, lists, drives, resizes and closes them; /api/terminals/:t/stream is SSE (attached with snapshot or resume from an offset, output with id = offset, title, resized, exit, overflow). Terminals belong to the device that opened them (kept in terminals.json, since they outlive serve), admin sees all, revoking closes them. New scope terminal (in the default pairing scopes). PUT /api/term-host (admin) installs a host binary checked against x-sha256. Tests use a Node fake host speaking the same protocol.
Add docs/remote.md: what runs on the server and on each client, mermaid
diagrams for the architecture, short-code pairing, session lifecycle,
host tool routing across devices, port forwarding and terminals; the
security model (threat model, scopes, credential lifetimes, Host/Origin,
LAN plain HTTP); reference tables into serve.md and desktop-rpc.md; and
known limits with next steps.
Align serve.md and desktop-rpc.md with the code: the capabilities
example lists the host tool methods and events, POST /api/server/stop
answers { stopping: true }, POST /api/tower may answer 200 and its 501/503
errors, default pairing scopes include terminal, terminal input is capped
at 4 MiB, and mermaid messages no longer carry ';' or '<...>' that break
rendering. Link remote.md from the README docs table and
readme-reference, and require it in the package file check.
The server id is minted once per agent home in <home>/serve/server-id (0600) and reused on every run, so identity, discovery replies, GET /api/server, server.json and connection codes keep naming the same server after a restart or upgrade.
POST /api/print { cwd, prompt, model? } (sessions:operate) runs this machine's launcher the way the app writes commit messages locally (--print --no-session --no-tools [--model], prompt on stdin, no interactive host) in cwd and answers { text }. 120 s timeout, 1 MiB answer, 4 at once; the run's process group is stopped on timeout, oversize output or a client that leaves. Capability: print.
On Windows (or with GENTLE_TERM_HOST_TRANSPORT=tcp) serve starts gentle-term-host with --tcp --state-dir <serve>/term and reaches it on 127.0.0.1 at the port in term/term-host.json, authenticating each connection with the token there first; a port file nobody answers (or that refuses the token) is removed and a new host started. GET /api/term-host adds asset (the GPUI release binary for this server, gentle-term-host-<os>-<arch>[.exe], or null) and transport. PUT /api/term-host on Windows renames a running .exe aside before moving the new one in.
Sessions run under a detached keeper so they outlive a server restart; on a network bind serve speaks TLS with its own certificate, proves a pairing code against the certificate before a client sends it, and can be reached through a self-hostable relay that only ever sees ciphertext.
17 tasks done
- get_auth_status rows gain loginKinds (oauth, device, api_key) from Pi's provider definitions. - DesktopLoginBridge drives Pi's own ModelRuntime.login/logout: login_start, login_complete, login_cancel with login_prompt (open_url, device_code, input, progress; redirectPrefix for loopback callbacks, options for choices, secret for keys) and login_finished events. - set_api_key saves a key through the provider's key setup (owner-only auth.json, never echoed); remove_credentials is /logout. Each success reloads the registry offline. - One sign-in per provider, 15-minute cap, cancelled with the session. Wired into the Desktop RPC extension with the packages slice in the next commit.
- list_packages reads Pi's settings (with installed versions); install_package/remove_package run the same `gentle-shell install|remove <source> [-l]` CLI as a job with package_progress lines and package_finished, then /reload the session once idle. - The launcher hands Pi its own command and home (GENTLE_SHELL_LAUNCH), so a client's job runs the CLI with the session's home; a source starting with '-' is refused. - Wires the sign-in and packages slices into the Desktop RPC extension and advertises login_start, login_complete, login_cancel, set_api_key, remove_credentials, list_packages, install_package, remove_package and the login_prompt, login_finished, package_progress, package_finished events; documents both slices. - Tests drive fake OAuth, device and key providers through Pi's real model runtime and credential store in a temporary agent home, and package jobs over a fake installer and CLI.
- POST /api/upgrade { channel? } (admin) runs this launcher's `gentle-shell upgrade` and answers
202 { jobId }; GET /api/upgrade/:jobId/stream is SSE `line` { line } then `finished`
{ ok, error?, version? }. 409 upgrade_running while one runs; GET /api/server lists `upgrade`.
- On success the server stops as `serve stop` does (keepers and the terminal host keep running)
and restarts on the installed version at the same address: a detached `serve --foreground`,
or exit 75 for systemd/launchd to restart it. The systemd unit gets KillMode=process.
- Tests: a fake upgrade command, a restart that reattaches a running session, the CLI's own
relaunch with the same address and identity, and the supervised exit.
Pi's settings keep a local package path relative to the settings folder, while install/remove resolve a typed path against the session's folder, so removing a listed local package from a client failed with 'No matching package found'. list_packages now lists local paths absolute.
- `DELETE /api/devices/self` revokes the calling device whatever its scopes (capability `unpair`), so a client's Unpair removes it from the server too; the server's own token gets `400 not_a_device`. - Documented in serve.md; tested.
- Every Desktop RPC event and every `get_snapshot` answer carries `epoch`, a random id the router mints each time it starts (session start, reload, switch), exactly when `seq` restarts at 1. `session_snapshot` events carry it like every other event. - A client that followed one epoch reads an event or snapshot of another as a new numbering, not a replay: after a reload (a package install) the app no longer drops every event. - docs/desktop-rpc.md documents the field and the rules; tests cover a stable epoch within a session and a new one on restart, reload and switch.
- `POST /api/devices/self/replace { token }`: the caller, shown an earlier pairing's token, takes over that device's terminals, then the earlier device is revoked. A client pairing a known server again (at another address) keeps its terminals and leaves one device listed.
- Documented in serve.md; tested with the fake term host.
A model_defaults config store over the agent home's settings.json: defaultProvider, defaultModel, defaultThinkingLevel and enabledModels, read and written (whole-set, other keys kept, unreadable file never replaced, waits for a profile apply).
POST /api/setup (admin) runs gentle-shell [home] setup as a job on the upgrade runner, streamed at /api/setup/:jobId/stream; one job at a time with the upgrade, no restart; capability setup. GET /api/server names the agent home and its settings/models/mcp paths for operating devices.
custom_models (Pi's <agentHome>/models.json, checked against Pi's published models schema) and mcp_servers (<agentHome>/mcp.json and <cwd>/.pi/mcp.json, every server through Pi's validateMcpServerConfig and its loader rules) are read and written whole through get_config/set_config, with expectedRevision, atomic replacement and config_changed on outside edits. Secrets (apiKey, headers, env, oauth.clientSecret) read as "•••"; sending the marker back keeps the stored value. A models write refreshes the session's registry before answering (an outside one when seen); an MCP write reloads the session once idle.
GET /api/server no longer names the agent home or the paths of settings.json, models.json and mcp.json: clients reach Gentle Shell's and Pi's configuration only through the Desktop RPC config stores (model_defaults, custom_models, mcp_servers). home stays, as the default folder for new sessions.
POST /api/desktop and GET /api/desktop/events answer Desktop RPC from a hidden control session serve keeps itself (started on first use in the server user's home, never prompted, hidden from GET /api/sessions unless ?includeControl=1 for admin, stopped after 10 idle minutes, taken back across serve restarts through its keeper). Scopes per method as /desktop; host tool methods are refused with use_session_desktop. Stream tickets take { stream: "desktop" }. GET /api/server lists the capability desktop. New Desktop RPC method list_available_models (sessions:read): the models Pi can use and the current model's thinking levels, from the same registry as get_available_models.
Reconcile the config stores with upstream's mcp, pi_settings and claude_bridge (Gentleman-Programming#3547) instead of keeping parallel ones: - mcp: one store. Upstream's servers summary (name, transport, enabled, truncated, omitted) plus documents.global/project, each layer Pi reads as its whole document with secrets redacted (env, headers, oauth.clientSecret, and a URL with userinfo or a query). Writable per layer as {source, document}, checked by Pi's MCP validator; the project layer is read and written only for a trusted project (project_untrusted otherwise). Replaces mcp_servers. - pi_settings: upstream's merged display view, now writable: a patch of the four model keys in the global settings.json (null removes a key). Replaces model_defaults. - claude_bridge stays read-only; custom_models stays as it was.
"serve share leaves a loopback server with running sessions alone" ended its in-process server without its sessions, so every run left a keeper and its fake Pi running (a keeper with no server waits a day before it stops its session). The test now asks the server to stop with its sessions, as `serve stop --sessions` does. serve-test-client gains serveLeftovers/endServeLeftovers: the keepers a test's session records name (matched by pid and entry point, so a reused pid is never killed), the Pi each runs, and any process whose command line names a test root. The serve suites that start servers or sessions end them in their after hook instead of tracking pids by hand, and each ends with a guard test asserting nothing outlived it.
…rom outside remote.md still described the network server as plain HTTP with TLS and a relay as next steps. The pairing diagram now shows the identity over HTTPS and the pairing proof before the code is sent; the security model describes the pinned certificate, --no-tls, the relay, and the https Origin; known limits name what is left (certificate rotation, push notifications).
gentle-shell serve — server-owned sessions behind device pairing (RFC #3527 phase 1)
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Refs #3527
Summary
This PR adds
gentle-shell serve. It is one long-lived server per agent home. It owns Gentle Shell sessions, and paired devices follow and drive them over HTTPS and Server-Sent Events. A session belongs to the server, not to the window that started it. It keeps running when the laptop sleeps, the Wi-Fi drops, the app quits, orserveitself restarts or upgrades. A client that comes back picks up exactly where it left off.Around the sessions, it adds what a thin client needs to work on a project that lives on the server:
Pairing takes one 8-character code. The app finds the server by itself on the LAN, checks a pairing proof bound to the server's TLS certificate, and pins that certificate. A self-hostable relay reaches the server from outside its network and only ever sees ciphertext.
There is no new runtime dependency. For anyone who never runs
gentle-shell serveorgentle-shell relay, behavior only changes in a few small places, all listed under Impact on existing users: the Desktop RPC surface grows (new methods and stores, all additive), andmcpandpi_settingsbecome writable.The client is Gentle Shell GPUI (Gentleman-Programming/gentle-shell-gpui#255, issue #247). It was used for the live runs below, on macOS and against a real Arch Linux (Omarchy) server.
Contents
Motivation
Today a Gentle Shell session lives and dies with the terminal or desktop window that started it, on the machine in front of you. People want something else: run the agents on the machine that has the project and the compute (a Linux PC at home, a workstation), and drive them from a laptop, and later a phone. A running turn should survive a sleeping laptop, a dropped connection or an app restart.
RFC #3527 proposes a server that owns sessions. This PR is its phase 1, plus what the desktop client needed to be a real thin client. That means files, git, terminals, forwarded pages, host tools, pairing by code, and managing the server's own configuration remotely.
Diagrams
What runs where
flowchart LR subgraph Clients["Paired devices"] A["Gentle Shell GPUI on a laptop"] B["Another device"] end subgraph Relay["Optional relay (VPS)"] R["gentle-shell relay<br/>splices TCP, sees ciphertext only"] end subgraph Server["Server machine: one agent home"] S["gentle-shell serve<br/>HTTPS + SSE API, auth, routing"] K1["Session keeper<br/>seq, replay ring, outlives serve"] P1["Session: gentle-shell --mode rpc (Pi)"] C["Control session<br/>hidden, for /api/desktop"] H["gentle-term-host<br/>PTYs, outlives serve"] F["Forward listeners<br/>one port per forward"] L["Pages on loopback"] FS[("Project files and git")] end A -- "TLS, pinned cert, Bearer token" --> S B -- "TLS via relay" --> R R -- "outbound from serve" --> S A -- "cookie per forward" --> F S -- "owner-only socket + token" --> K1 K1 -- "stdin / stdout JSON lines" --> P1 S -- "via its keeper" --> C S -- "term.sock (Windows: loopback TCP + token)" --> H S -- "files, git, uploads" --> FS F -- "proxy to 127.0.0.1" --> LPairing with the short code
sequenceDiagram autonumber actor U as Person participant S as gentle-shell serve participant App as Client app U->>S: gentle-shell serve share S-->>U: Code: 7PH3-DM9V (5 min, single use) + gsc1.… fallback U->>App: types 7PH3-DM9V App->>App: UDP broadcast discover, ports 8787-8796 S-->>App: unicast here { id, name, port } App->>S: GET https://IP:8787/.well-known/gentle-shell S-->>App: { serverId, tls: true, fp } Note over App: serverId and certificate fingerprint must match App->>S: POST /api/pair/proof { nonce } S-->>App: { proofs: HMAC per live code, keyed by scrypt of code and fp } Note over App: send the code only if a proof matches App->>S: POST /api/pair { code, name } S-->>App: 201 { token: gss_… } (shown once) Note over App: pins fp, stores URL and tokenA session across a client disconnect and a server restart
sequenceDiagram participant App as Client app participant S as serve participant K as Keeper participant P as Pi App->>S: POST /api/sessions { cwd } S->>K: spawn keeper (detached), config on stdin K->>P: gentle-shell --mode rpc App->>S: GET /api/sessions/ID/events P-->>K: records K-->>S: seq-numbered records S-->>App: id: 41 / data: … Note over App: app quits Note over S: serve stop or upgrade: keepers keep running P-->>K: records keep coming into the replay ring S->>K: next serve reattaches (token), same seq App->>S: GET …/events?after=41 alt 41 still in the ring S-->>App: 42…N, then live else ring moved past it S-->>App: snapshot-required, client rebuilds from get_state / get_snapshot endHost tool routing across devices
sequenceDiagram participant Mac as Laptop (dev_A) participant Phone as Phone (dev_B) participant S as serve participant P as Session (Pi) Mac->>S: /desktop set_host_tools [device_screenshot] S->>P: provider = dev_A (forced) Phone->>S: /desktop set_host_tools [device_screenshot] S->>P: provider = dev_B (forced) Mac->>S: /rpc prompt S->>P: set_host_activity [dev_A, dev_B] P-->>S: host_tool_call { provider: dev_A } S-->>Mac: event Mac->>S: host_tool_progress (every 60 s while working) Mac->>S: host_tool_result { callId, content } Note over S: only dev_A may answer (403 otherwise) S->>P: result, the turn continuesMore diagrams (forwarding, terminals, sign-in from a client, clients without sessions) are in
docs/remote.md.What ships, by area
Serve core (
lib/serve-server.ts,lib/serve-session.ts,lib/serve-cli.ts,lib/serve-http.ts)gentle-shell [home selectors] serve [--listen host:port] [--allow-host name]… [--forward-ports a-b] [--no-tls] [--relay gsr://…] [--foreground], plusserve status | stop [--sessions] | pair [--scope …] | devices [--revoke].<home>/serve/folder. It runs in the background by default; use--foregroundfor service managers. Loopback on a random port is the default.serverId(<home>/serve/server-id) that survives restarts and upgrades.GET /.well-known/gentle-shellreturnsserverId,name,protocol,version,tlsandfpwithout a token.gentle-shell.serve/v1:POST /api/sessions/:id/rpcsends one Pi RPC command; the client's id is restored.POST /api/sessions/:id/desktopsends a Desktop RPC request, correlated to its answer.GET /api/sessions/:id/eventsis SSE withseq,Last-Event-ID/afterresume,snapshot-required, dialog replay (first answer wins),resyncfor slow subscribers, and a 20 s heartbeat.Hostallowlist (DNS rebinding,421), anOrigincheck before auth (403), bounded bodies, CSPdefault-src 'none',nosniff,no-storeandno-referrer.--session-idresumes a session by its exact id, even one Pi never wrote to disk.Pairing (
lib/serve-auth.ts,lib/serve-share.ts,lib/serve-discovery.ts,lib/serve-tls.ts,lib/serve-relay.ts)gss_device tokens, which are stored as sha256 only and compared in constant time.sessions:read,sessions:operate,terminalandadmin.serve share:gsc1.connection code (base64url JSON:v, id, n, p, a[], c, fp, r?), plus the exactufw/firewall-cmdline on Linux.--alwaysinstalls a systemd user unit (KillMode=process) or a macOS LaunchAgent;--offremoves it.<home>/serve/tls/, and pinned by fingerprint.POST /api/pair/proof { nonce }returnsHMAC(scrypt(code, salt ‖ fp), fp ‖ nonce)for every live code. With the short code, the client sends its code only to a server that proves it knows it for the certificate the client saw.400 tls_required.--no-tlsis opt-in and prints a warning.gentle-shell relay): a self-hostable rendezvous.DELETE /api/devices/self: a device unpairs itself, whatever its scopes.POST /api/devices/self/replace { token }: a device paired again (for example at another address) takes over the earlier pairing's terminals, then the earlier device is revoked.Sessions, keepers and epoch (
lib/serve-session-keeper.ts)seq), and keeps the replay ring (2000 records or 8 MiB), pending dialogs and open host tool calls.serveattaches over an owner-only Unix socket (a named pipe on Windows) and proves itself with a per-session token from a0600record file.serve. The next server reattaches every keeper before it answers: same ids,seqcontinuing, dialogs and host tool calls still pending, and 30 s for a device that owes a host tool call to reconnect.serve stop --sessionsends the sessions too. An orphaned keeper stops its session after 24 h; an exited one lingers 60 s for a server to collect the end of its stream.epoch: every Desktop RPC event andget_snapshotcarriesepoch, a random id minted whenever the router starts (session start, reload, switch), which is exactly whenseqrestarts at 1. A client reads another epoch as a new numbering, not a replay. Before this, the app dropped every event after a reload, for example after a package install.Host tools (
lib/desktop-rpc-host-tools.ts,lib/desktop-host-tools-service.ts, routing inlib/serve-server.ts)set_host_tools,host_tool_result(with optionaldetails),host_tool_progress,host_message,set_host_contextandset_host_activity(sent by serve only). New events:host_tool_callandhost_tool_cancel.pi.registerTool). Built-in and extension names are refused. Several providers may offer the same name, and the model sees the newest registration's definition.providerto the calling device, so no device registers tools or hidden context as another.403otherwise).host_tool_progressrestarts that clock.host_messageadds a client's custom message throughpi.sendMessage. It starts a run when idle and steers while streaming.set_host_contextkeeps one hidden context message per provider, injected before each run.Forwards, local origin rules, Tower (
lib/serve-forward.ts)/api/sessions/:id/forwards) and server-level forwards (/api/forwards) get one listener per forward, proxy to loopback targets only, and stream HTTP, SSE and WebSocket upgrades.HttpOnly; SameSite=Strictcookie. Tickets and everygs_fwd_*cookie are stripped before the page sees them.HostandOriginrules apply per forward, so one forwarded page cannot drive another.DELETE, with its session, on revoke, on server stop, or after 12 h idle.GET /api/serviceslists Engram and Tower.POST /api/towerstarts Gentle Tower inside serve on demand and forwards it, keeping Tower's token path; the forward's own origin passes Tower's origin check.Files, git, uploads, terminals, one-shot prompts
/api/fs/*):If-Matchandcreate_only, mkdir, rename, remove, ranked search, and a debounced watch over SSE.remove/renamerefuse the root, the home and folders above it (symlink-aware).POST /api/git):sessions:read); everything else needssessions:operate.core.sshCommand,core.fsmonitor,core.hooksPath,alias.*,--upload-pack,--exec, …).GIT_*environment is an allowlist. Timeouts are 120 s (600 s for network commands), with output caps.POST /api/uploads): owner-only folders per device, 64 MiB, removed after 7 days./api/terminals*):gentle-term-hostowns the PTYs over an owner-only Unix socket; on Windows it uses loopback TCP with a token from an owner-only file.terminalscope.PUT /api/term-host(admin, sha256-checked) installs the host binary;GET /api/term-hostnames the release asset for this server.POST /api/print): runs this launcher with--print --no-session --no-toolsin a folder, with a 120 s timeout, a 1 MiB answer cap and 4 at once. The process group is killed on timeout, oversize output or client disconnect.Desktop RPC additions
Sign-in (
lib/desktop-login-service.ts,lib/desktop-rpc-login.ts):login_start,login_completeandlogin_cancel, withlogin_prompt(open_url withredirectPrefix, device_code, input, progress) andlogin_finishedevents, over Pi's ownModelRuntime.login.get_auth_statusrows gainloginKinds(oauth,device,api_key).API keys:
set_api_keysaves through the provider's key setup into Pi's owner-onlyauth.jsonand never echoes the key.remove_credentialsdoes what/logoutdoes.Packages (
lib/desktop-packages-service.ts):list_packageslists local packages by an absolute path thatremove_packageaccepts.install_packageandremove_packagerun the samegentle-shell install|removeCLI as a job withpackage_progressandpackage_finished, then/reloadonce idle.-is refused.list_available_models: the models Pi can use and the current model's thinking levels, from the same registry as Pi'sget_available_models.Config stores: after merging main (feat(desktop): add read-only mcp, pi_settings, and claude_bridge config stores #3547), the final shapes are:
valueset_configdatamcp{ servers: [{ name, transport, enabled }], truncated, omitted, documents: { global?, project? } }— each document is the wholemcp.jsonwithenv/headersvalues,oauth.clientSecret, and aurlwith userinfo or a query replaced by"•••"{ source: "global" | "project", document };"•••"keeps the stored value;projectwhile untrusted →project_untrusted; checked by Pi's ownvalidateMcpServerConfigand loader rules; the session reloads once idlepi_settings{ defaultProvider, defaultModel, defaultThinkingLevel, enabledModels, extensions, truncated }defaultProvider,defaultModel,defaultThinkingLevelandenabledModelsin the globalsettings.json(nullremoves, omitted keeps); waits forapply_profilecustom_modelsmodels.json,apiKeyand header values as"•••"claude_bridge{ plan }read_onlyEvery write keeps the existing contract:
expectedRevisionper write target, owner-validated atomic writes,config_changedfor outside edits, no paths in answers, and revisions that digest the real content so a secret changed elsewhere still moves them./api/desktopwithout a sessionPOST /api/desktopandGET /api/desktop/eventsanswer Desktop RPC (configuration, models, sign-in, packages, update status) from a hidden control session that serve keeps itself.?includeControl=1) and stops after 10 idle minutes. It is taken back across restarts through its keeper./desktop. Host tool methods are refused (use_session_desktop).GET /api/serverlists thedesktopcapability. It no longer names config file paths: clients reach configuration only through the stores.Upgrade, setup, unpair and replace
POST /api/upgrade { channel? }(admin):gentle-shell upgradeas a job, streamed at/api/upgrade/:jobId/stream; a second one gets409 upgrade_running.serve stopdoes, so keepers and the terminal host keep running.serve --foreground, or exit 75 for systemd or launchd.POST /api/setup(admin): runsgentle-shell setupfor the home on the same runner, without a restart.Docs
docs/remote.md(new): what runs where, diagrams, the security model (threat model, scopes, credentials, Host/Origin, TLS and the relay), reference tables, and known limits.docs/serve.md(new): endpoint reference, process model, limits, and "Try it from source on Linux".docs/desktop-rpc.md: host tools, sign-in, packages,list_available_models,epoch, and the config stores above.docs/remote-test-runbook.md(new): a step-by-step runbook for testing serve on a Linux machine. It is the one used for the Omarchy run.docs/orchestration-plan.md(new): a plan only, nothing implemented. It covers multi-repo orchestration (Phase 5): threads as sessions, anorchestratescope, send-and-wait, structured replies, and an MCP server.docs/readme-reference.mdand the README docs table.Design decisions
curl, resumes natively withLast-Event-ID, and passes through proxies. The contract (seq, replay,snapshot-required, tickets) is transport-independent, so a WebSocket transport can be added later.gentle-shell --mode rpcper session--no-tlsstays for tailnets.dgramis needed (no Avahi on Linux), one firewall rule covers TCP and UDP, and the reply reveals nothing/.well-knowndoes not. Thegsc1.code covers subnets and tailnets. QR stays for mobile.node-ptyin serve; tmuxnode-ptyis a native addon to build per platform, and tmux is not everywhere. The host's headless emulator draws an exact snapshot for a late reattach.mcpstore (upstream shape +documents, writable per layer);pi_settingswritable as a patch of its four model keysmcp_servers/model_defaultsstoresmcpkeeps upstream's display summary (servers) and adds the documents an editor needs.pi_settingswrites are a patch, because its value is a merged, display-filtered view: a full replacement would make clients write back values they only saw through the merge.Impact on existing users
Nothing changes unless
gentle-shell serveorgentle-shell relayruns, except for the additive Desktop RPC surface. Shared code touched:bin/gentle-shell.mjs:serveandrelaybranches import their runtime modules only when used.GENTLE_SHELL_LAUNCH(its own command and home flags) in Pi's environment, so a package job runs the same CLI with the same home.lib/gentle-shell-launcher.ts:serveandrelaybecome commands, recognized after the home selectors assetupis. Before,gentle-shell serve …was sent to the model as a prompt; now it is the command.lib/desktop-rpc.ts:get_snapshotgainsepoch.setRequestLimits()sets per-method request caps: onlyset_host_tools(1 MiB),host_message/set_host_context(2 MiB) andhost_tool_result(10 MiB) get more than 64 KiB.extensions/gentle-desktop-rpc.ts:capabilitiesgains the host tools, sign-in, packages andlist_available_modelsmethods and their events.lib/desktop-rpc-config.ts:custom_models.mcpandpi_settingsbecome writable, andmcpgainsdocuments.mcp/pi_settingsansweringread_onlygets a real write instead (both still requireexpectedRevision).lib/desktop-auth-service.ts/lib/desktop-rpc-auth.ts:get_auth_statusrows gainloginKinds, pluslist_available_models.lib/profiles-orchestrator.ts: model-defaults helpers that thepi_settingswrite uses. The existing orchestrator write is unchanged.capabilitiesand store lists.scripts/build-runtime-modules.mjsgenerates theserve-*,rpc-hostand relay runtime modules (46 generated modules in total).scripts/verify-package-files.mjsrequires them plusdocs/serve.mdanddocs/remote.md.Fragile points
These depend on Pi internals that are not part of its package exports. Each one fails closed and is covered by a test that breaks loudly on a Pi update:
lib/pi-user-config.tsloadsvalidateMcpServerConfigfrom<pi>/dist/core/mcp-servers.js.mcpwrite answersinvalid_data("Pi's MCP server validator is not available") instead of writing unchecked.mcpread summary uses upstream'slib/mcp-config.tsmirror, whichtests/desktop-rpc-config-mcp-fidelity.test.tscompares with Pi's real loader. A write test also loads Pi's loader (dist/extensions/mcp/config.js) to confirm Pi loads what was written.custom_modelsvalidates against<pi>/schemas/models.schema.json, which Pi publishes in its package.nulland writes are refused.lib/desktop-rpc-auth.tskeeps a small table of which Pi OAuth providers use a device code (four providers) or offer both a device code and a browser sign-in (two). It is read from Pi's own flows, because Pi's provider definitions do not say.--session-id: resuming by exact id relies on Pi's flag.login_complete. That depends on Pi's flow accepting a pasted redirect, which its manual-input path does.Security review checklist
GET /.well-known/gentle-shell,POST /api/pair/proof(rate-limited, returns HMACs only) andPOST /api/pair. Loopback bind by default.400 tls_required.--no-tlsis explicit and warned.--relayrefuses--no-tls.DELETE /api/devices/selflets a client unpair cleanly.replacerevokes the earlier device after moving its terminals./rpc,/desktopand/api/desktop. Read-only methods are listed explicitly; everything else needssessions:operate.Hostallowlist (421) andOrigin(http(s)://<Host>) checked before auth. No cookies or CORS on the API. Strict security headers.0600record, the socket path kept inside the Unix limit, and the config (with the environment) passed on stdin, never argv.provideris forced to the calling device, only the provider answers,set_host_activityis server-only, and the server never runs client code.remove/renamerefuse root, home and ancestors. Writes are atomic.terminalscope, an owner-only socket (or loopback TCP + token on Windows), per-device ownership, and a sha256-checked binary install foradminonly.apiKey, header and env values,oauth.clientSecret, credential-bearing MCP URLs) read as"•••", and the marker keeps the stored value on write. Pi's own validators run before any write. A projectmcp.jsonis read and written only for a trusted project.Tests and live evidence
Automated
Branch head after the merge, macOS arm64, Node v26.13.0:
node --experimental-strip-types --test tests/serve-*.test.tsnode --experimental-strip-types --test tests/desktop-rpc*.test.tspnpm typecheckpnpm check:runtime-modulesnode scripts/verify-package-files.mjsnode scripts/run-test-suite.mjs(tests/*.test.ts)maincheckout on this machine, and 1 is a timing flake (see the note below).node scripts/check-provider-contract.mjsnode --experimental-strip-types tests/runtime-harness.mjspsafter the serve suitesThe 8 unit-stage failures, all outside this branch. Each file was run on the branch and on an unmodified
mainworktree, on the same machine with the samenode_modules:maintests/gentle-shell-bin.test.ts: four "on a TTY …" resume-line teststests/session-profile-extension.test.ts: two "A3 foreign launch …" tests (repository_root must select a canonical independent Git repository)tests/verifier-preparation.test.ts: "#3009: the documented Bash call creates its own scratch …"tests/desktop-rpc-config-watch.test.ts: "the real directory watcher closes itself …" (a timing flake under full-suite load; this branch does not touch the file)In the full run, the provider-contract and runtime-harness stages failed only because
pnpmwas not onPATH. Run directly, both pass (the rows above).The maintainer probe
tests/maintainer/desktop-rpc.maintest.ts(installed Pi, no provider) fails all 13 of its tests on this machine. Pi 1.6.0 prints "Warning: No models available" on stderr, and the probe expects an empty stderr. The one test checked on an unmodifiedmainworktree fails the same way. Its store list is updated for this branch.How the tests work:
tests/fixtures/serve-fake-pi.mjs) and a fake terminal host.snapshot-required, dialogs, backpressure, keepers across restarts and orphans, host tool routing and offline answers, forwards (cookie flow, SSE, WebSocket, Origin), files, git classification, uploads, real-UDP discovery,share, the CLI daemon, upgrade and setup.About the earlier red CI runs:
CIruns forb173ec67f,48ba3b6c5and8ae6528d0failed only intests/codegraph-readiness.test.ts:runCodegraphtimeout and process-group kill timing.mainruns that day, and main has since removed the native CodeGraph integration (refactor(codegraph): remove the native CodeGraph integration from gentle-shell #3553). The merge brings that removal in, so the test no longer exists on this branch.e5f4c2753passed.Test hygiene:
Live: macOS, GPUI as the client
serve sharewith a relay, and pairing by short code over TLS (fingerprint pinned).top.serve stop+share, the session id was unchanged (seq 44, "reattached (seq 44, running)") and the terminal id was unchanged, withtopstill updating./web http://127.0.0.1:18920/) loaded through a local proxy.gsc1.code whose LAN addresses were decoys. The relay log shows spliced connections.3bebba589.Bugs found on this run and fixed on the branch:
epoch(8d7f04211).replace(94635c528).devices/self(70d39571a).Live: a real Arch Linux (Omarchy, x86_64) server, GPUI on macOS over the LAN
https://192.168.100.92:8787), with the identity fingerprint matching the pin. The device hadsessions:read,sessions:operateandterminal, so/api/devicescorrectly answered 403.git initand a commit from the server terminal, then saw the Changes diff (M hello.txt +2 −1) and Branches.uname -aprintedLinux … 7.2.15-1-omarchy … x86_64, andtopupdated live.open_pagecreated a server forward (8765 → 8800) and a local proxy, and the page loaded./api/forwardswas empty within 2 s of closing.topstill updating.models.jsonandmcp.jsoneditors (opened and reloaded, nothing saved), and packages.serverestart on that machine:serve stopthenserve sharewith the app open. The server's start time changed (04:53:45→05:14:39) while its id stayedsrv_0727f76e…; the agent sessionses_427e64d8…came back running at the sameseq(331) with its subscriber, and both terminals kept their ids,top's output offset still growing (1,250,928 → 1,266,898 bytes in 5 s).Screenshots:
omarchy-00…68andmm-00…44from these runs can be attached on request.Review questions
sessions:operatecan call Desktop RPCset_permission_mode, includingsuper-yolowithpersist: true, exactly like the Desktop app's stdin. Is that acceptable, or should elevation from serve need its own scope?sessions:readreads files. File reads run as the server user with no folder jail, so a read-only device can read~/.ssh. Should we keep that (it is documented), jail reads to session folders, or split anfs:readscope out of the default pairing?mcpdocuments expose. Upstream'smcpsummary deliberately hidescommand,args,cwdandurl. The editabledocumentsreturn them, because an editor needs them, with secrets redacted, including credential-bearing URLs. Secrets placed directly inargs(--api-key=…) are not redacted. Is that acceptable forsessions:read, or shoulddocumentsrequiresessions:operate?mcp,custom_models(andnotifications) revisions digest the real content, so an outside change to a secret moves them. Withpi_settingsandclaude_bridge, upstream chose to digest only the returned value. A 128-bit digest of a document whose other fields the client sees could let a client confirm a guessed low-entropy secret offline. Should we keep that, or digest a per-run salted value?pi_settingsas a patch. Writes patch the four model keys of the global file, while the value is the merged view. Is a patch acceptable here, given that every other store takes a full replacement?validateMcpServerConfig,loadMcpConfigand the OAuth flow kinds, so these become imports?gentle-term-hostcomes from. Today it comes from$GENTLE_TERM_HOST,PATH, a client upload (PUT /api/term-host, admin, sha256), or the GPUI release assets. Should Gentle Shell releases ship it per platform?serveby design. Is the 24 h orphan stop the right bound? Shouldserve statuslist orphaned keepers?How to try
On the machine that should run the agents, from a checkout of this branch (see
docs/serve.md→ "Try it from source on Linux", ordocs/remote-test-runbook.md):Then type the code in Gentle Shell GPUI (gentle-shell-gpui#255) under Configuration → Where agents run → Gentle Shell server.
By hand:
Other options:
gentle-shell relay --listen 0.0.0.0:7700on a VPS, put its secret in<home>/serve/relay-secret, and runserve share --relay gsr://host:7700.gentle-term-hostbuild (GENTLE_TERM_HOST=…), or let the app install one.node bin/gentle-shell.mjs serve stop --sessions.Commits
Grouped by area (oldest first within each group).
46459aa5fsession host with seq and dialog replay ·ef7290794pairing, scoped tokens, stream tickets ·dbf454900hardened HTTP + SSE API ·7767ca5fdcommand, daemon, server file and lock ·e078ee56c--allow-host·164f20c54resume by exact id ·39f2df55fstable server idfa9e84b36/.well-knownidentity ·ee9e4a126serve shareand the connection code ·fd25173afLAN discovery ·2056aa028keeper, TLS with pairing proof, relay ·70d39571aunpair self ·94635c528replace an earlier pairinge150bb9c9keeper socket inside the Unix path limit ·c807c5e0bimpostor socket test ·8d7f04211Desktop RPCepoch80f64084chost tools ·9e83ea6a6routing to the provider device ·2a73098b3host messages, context, result details ·c91ad9d68several providers per tool ·f561ca285host_tool_progressb0d376273authenticated forwards ·7ea9eaa3aGentle Tower ·e9c80dbbdserver-level forwards and services6c933a18bfiles ·55c8a8e0agit ·98bb21475uploads ·858b3b40dterminals over a native host ·1742d1652term host over TCP on Windows ·e5f7e19e1one-shot prompts ·27a466201print model typingb3cd72c02sign-in and API keys ·cc4c78806packages ·3bebba589local package paths ·6d629be80model defaults (now inpi_settings) ·aa294a381custom models and MCP stores (nowmcp) ·8ae6528d0/api/desktopandlist_available_modelsb173ec67fupgrade from a client ·9f83acc50setup from a client ·48ba3b6c5no config paths in server info9f36f4913protocol and security model ·11c517cc7try from source on Linux ·9e7e219dedocs/remote.md·16ef9bda5Linux guide refresh ·e5f4c2753HTTPS ·66817e1cfLinux test runbook ·e653924d9orchestration plan (Phase 5) ·5e27aa695remote.md: TLS and the relayfd8276e5dmerge main (config stores reconciled with feat(desktop): add read-only mcp, pi_settings, and claude_bridge config stores #3547) ·200a3df96tests stop the session keepers they start