Skip to content

feat(serve): gentle-shell serve — server-owned sessions behind device pairing (RFC #3527 phase 1) - #3529

Draft
ismaelosuna7824 wants to merge 50 commits into
Gentleman-Programming:mainfrom
ismaelosuna7824:feat/serve-phase1
Draft

ismaelosuna7824 wants to merge 50 commits into
Gentleman-Programming:mainfrom
ismaelosuna7824:feat/serve-phase1

Conversation

@ismaelosuna7824

@ismaelosuna7824 ismaelosuna7824 commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

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, or serve itself 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:

  • Project access: files, git, uploads, one-shot prompts, and persistent terminals over a native terminal host.
  • Forwarded pages: authenticated forwards for pages on the server's loopback, such as dev servers, the design canvas, Gentle Tower and Engram.
  • Host tools: tools a device registers and runs itself, like a screenshot of the laptop, while the agent runs on the server.
  • Remote administration: sign-in, API keys, packages, model defaults, custom models, MCP servers, Setup and Upgrade, all from the client.

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 serve or gentle-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), and mcp and pi_settings become 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" --> L
Loading

Pairing 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 token
Loading

A 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
    end
Loading

Host 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 continues
Loading

More 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)

  • Commands: gentle-shell [home selectors] serve [--listen host:port] [--allow-host name]… [--forward-ports a-b] [--no-tls] [--relay gsr://…] [--foreground], plus serve status | stop [--sessions] | pair [--scope …] | devices [--revoke].
  • Process: one server per agent home, with a single-instance lock and an owner-only <home>/serve/ folder. It runs in the background by default; use --foreground for service managers. Loopback on a random port is the default.
  • Server id: a stable serverId (<home>/serve/server-id) that survives restarts and upgrades. GET /.well-known/gentle-shell returns serverId, name, protocol, version, tls and fp without a token.
  • Protocol gentle-shell.serve/v1:
    • POST /api/sessions/:id/rpc sends one Pi RPC command; the client's id is restored.
    • POST /api/sessions/:id/desktop sends a Desktop RPC request, correlated to its answer.
    • GET /api/sessions/:id/events is SSE with seq, Last-Event-ID/after resume, snapshot-required, dialog replay (first answer wins), resync for slow subscribers, and a 20 s heartbeat.
  • Hardening: bearer tokens (never cookies), a Host allowlist (DNS rebinding, 421), an Origin check before auth (403), bounded bodies, CSP default-src 'none', nosniff, no-store and no-referrer.
  • Resuming by id: --session-id resumes 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)

  • Codes and tokens:
    • Pairing codes are 40 bits, single use, valid 5 minutes, at most 16 live, with a global pause after 10 failures per minute.
    • They are exchanged for gss_ device tokens, which are stored as sha256 only and compared in constant time.
    • Scopes are sessions:read, sessions:operate, terminal and admin.
  • serve share:
    • Starts (or reuses, or reopens) a network server on 8787 or the next free port, with forwards on 8800-8899.
    • Prints the short code and a gsc1. connection code (base64url JSON: v, id, n, p, a[], c, fp, r?), plus the exact ufw/firewall-cmd line on Linux.
    • --always installs a systemd user unit (KillMode=process) or a macOS LaunchAgent; --off removes it.
  • LAN discovery: UDP on the HTTP port with a fixed JSON query and reply, unicast replies, a 512-byte cap, and rate limits of 20/s overall and 4/s per source. It carries no secrets.
  • TLS:
    • A self-signed ECDSA P-256 certificate is built with a minimal DER encoder (no dependency), stored owner-only in <home>/serve/tls/, and pinned by fingerprint.
    • POST /api/pair/proof { nonce } returns HMAC(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.
    • Plain HTTP from another machine gets 400 tls_required. --no-tls is opt-in and prints a warning.
  • Relay (gentle-shell relay): a self-hostable rendezvous.
    • The server keeps an outbound control connection, authenticated by a shared secret.
    • A client asks for a server by fingerprint; the relay asks the server for one more outbound connection and splices the two.
    • TLS runs end to end, so the relay sees ciphertext only and logs byte counts.
  • Device lifecycle:
    • 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)

  • Keepers:
    • Each session runs under a small detached keeper process. The keeper owns Pi's stdio, numbers records (seq), and keeps the replay ring (2000 records or 8 MiB), pending dialogs and open host tool calls.
    • serve attaches over an owner-only Unix socket (a named pipe on Windows) and proves itself with a per-session token from a 0600 record file.
  • Server restarts:
    • A restart or upgrade stops only serve. The next server reattaches every keeper before it answers: same ids, seq continuing, dialogs and host tool calls still pending, and 30 s for a device that owes a host tool call to reconnect.
    • serve stop --sessions ends 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.
  • Desktop RPC epoch: every Desktop RPC event and get_snapshot carries epoch, a random id minted whenever the router starts (session start, reload, switch), which is exactly when seq restarts 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 in lib/serve-server.ts)

  • New Desktop RPC methods: set_host_tools, host_tool_result (with optional details), host_tool_progress, host_message, set_host_context and set_host_activity (sent by serve only). New events: host_tool_call and host_tool_cancel.
  • Registration: tools register as real Pi tools (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.
  • Routing:
    • serve forces provider to the calling device, so no device registers tools or hidden context as another.
    • Each call goes to the most recently active connected provider.
    • A call for a device with no open stream is answered at once with an error the model reads. After a device's last stream closes it has a 10 s grace (none on revoke), and a reconnecting device gets its waiting calls again.
    • Only the provider may answer (403 otherwise).
  • Timeouts: a call ends after 10 minutes without a result, and each host_tool_progress restarts that clock.
  • Host messages and context:
    • host_message adds a client's custom message through pi.sendMessage. It starts a run when idle and steers while streaming.
    • set_host_context keeps one hidden context message per provider, injected before each run.

Forwards, local origin rules, Tower (lib/serve-forward.ts)

  • Forwards:
    • Session forwards (/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.
    • A forward link carries a single-use 60 s ticket that becomes a per-forward HttpOnly; SameSite=Strict cookie. Tickets and every gs_fwd_* cookie are stripped before the page sees them.
    • The Host and Origin rules apply per forward, so one forwarded page cannot drive another.
    • A forward closes on DELETE, with its session, on revoke, on server stop, or after 12 h idle.
  • Services and Tower: GET /api/services lists Engram and Tower. POST /api/tower starts 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

  • Files (/api/fs/*):
    • list, stat, read (8 MiB chunks, ETag/If-Modified-Since), atomic write with If-Match and create_only, mkdir, rename, remove, ranked search, and a debounced watch over SSE.
    • remove/rename refuse the root, the home and folders above it (symlink-aware).
  • git (POST /api/git):
    • No shell, no prompts, no pager or editor.
    • Read-only subcommands are classified explicitly (sessions:read); everything else needs sessions:operate.
    • Options and config that make git run programs are refused for every scope (core.sshCommand, core.fsmonitor, core.hooksPath, alias.*, --upload-pack, --exec, …).
    • The GIT_* environment is an allowlist. Timeouts are 120 s (600 s for network commands), with output caps.
  • Uploads (POST /api/uploads): owner-only folders per device, 64 MiB, removed after 7 days.
  • Terminals (/api/terminals*):
    • A separate native gentle-term-host owns the PTYs over an owner-only Unix socket; on Windows it uses loopback TCP with a token from an owner-only file.
    • A client reattaches by byte offset, or gets a snapshot drawn by the host's headless emulator.
    • Each terminal belongs to the device that opened it, behind the new terminal scope.
    • PUT /api/term-host (admin, sha256-checked) installs the host binary; GET /api/term-host names the release asset for this server.
  • One-shot prompts (POST /api/print): runs this launcher with --print --no-session --no-tools in 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_complete and login_cancel, with login_prompt (open_url with redirectPrefix, device_code, input, progress) and login_finished events, over Pi's own ModelRuntime.login.
    • get_auth_status rows gain loginKinds (oauth, device, api_key).
    • One sign-in per provider, capped at 15 minutes.
  • API keys: set_api_key saves through the provider's key setup into Pi's owner-only auth.json and never echoes the key. remove_credentials does what /logout does.

  • Packages (lib/desktop-packages-service.ts):

    • list_packages lists local packages by an absolute path that remove_package accepts.
    • install_package and remove_package run the same gentle-shell install|remove CLI as a job with package_progress and package_finished, then /reload once idle.
    • A source starting with - is refused.
  • list_available_models: the models Pi can use and the current model's thinking levels, from the same registry as Pi's get_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:

    Store Scope Writable value set_config data
    mcp global+project (project only for a trusted project) yes { servers: [{ name, transport, enabled }], truncated, omitted, documents: { global?, project? } } — each document is the whole mcp.json with env/headers values, oauth.clientSecret, and a url with userinfo or a query replaced by "•••" { source: "global" | "project", document }; "•••" keeps the stored value; project while untrusted → project_untrusted; checked by Pi's own validateMcpServerConfig and loader rules; the session reloads once idle
    pi_settings global+project yes (4 keys) Pi's merged display view { defaultProvider, defaultModel, defaultThinkingLevel, enabledModels, extensions, truncated } a patch of defaultProvider, defaultModel, defaultThinkingLevel and enabledModels in the global settings.json (null removes, omitted keeps); waits for apply_profile
    custom_models global yes the whole models.json, apiKey and header values as "•••" the whole document, checked against Pi's published models schema; the model registry refreshes before the answer
    claude_bridge global no { plan } read_only

    Every write keeps the existing contract: expectedRevision per write target, owner-validated atomic writes, config_changed for outside edits, no paths in answers, and revisions that digest the real content so a secret changed elsewhere still moves them.

/api/desktop without a session

  • POST /api/desktop and GET /api/desktop/events answer Desktop RPC (configuration, models, sign-in, packages, update status) from a hidden control session that serve keeps itself.
  • The control session starts on first use in the server user's home and is never prompted. It is hidden from listings (admin sees it with ?includeControl=1) and stops after 10 idle minutes. It is taken back across restarts through its keeper.
  • Scopes are per method, as for /desktop. Host tool methods are refused (use_session_desktop).
  • GET /api/server lists the desktop capability. It no longer names config file paths: clients reach configuration only through the stores.

Upgrade, setup, unpair and replace

  • POST /api/upgrade { channel? } (admin):
    • Runs this launcher's gentle-shell upgrade as a job, streamed at /api/upgrade/:jobId/stream; a second one gets 409 upgrade_running.
    • On success the server stops as serve stop does, so keepers and the terminal host keep running.
    • It then restarts on the installed version at the same address and identity: a detached serve --foreground, or exit 75 for systemd or launchd.
  • POST /api/setup (admin): runs gentle-shell setup for the home on the same runner, without a restart.
  • Unpair and replace: see Pairing.

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, an orchestrate scope, send-and-wait, structured replies, and an MCP server.
  • Also updated: docs/readme-reference.md and the README docs table.

Design decisions

Decision Chosen Alternatives considered Why
Transport HTTP requests + SSE streams One WebSocket per client, as the RFC sketches No dependency: Node has no WebSocket server built in. SSE works from browsers, phones and curl, resumes natively with Last-Event-ID, and passes through proxies. The contract (seq, replay, snapshot-required, tickets) is transport-independent, so a WebSocket transport can be added later.
Session hosting One gentle-shell --mode rpc per session Sessions in-process (Pi SDK); one shared child It reuses exactly the launcher, Pi resolution, extensions and Desktop RPC of a local launch, so remote cannot drift from local. A crash or a hung tool takes down one session, not the server.
Surviving restarts A detached keeper per session Sessions as children of serve (lost on restart); a supervisor daemon for all sessions An upgrade or a service-manager restart must not kill running turns. One keeper per session keeps the failure domain as small as the session. The keeper is small, needs no new dependency, and is authenticated per session.
Encryption on the LAN Self-signed TLS + fingerprint pinning + pairing proof Plain HTTP with a warning; a CA or ACME certificate; SSH only A home LAN has no DNS name for ACME. Pinning at pairing gives the same guarantees as SSH host keys. The pairing proof closes the gap left by untrusted UDP discovery: the code goes only to a server that already knows it. --no-tls stays for tailnets.
Outside the LAN Self-hostable relay that splices TCP Port forwarding on the router; a hosted service; WebRTC Nothing to open on the home router, no third party, no new dependency. TLS stays end to end, so the relay is untrusted by design.
Finding the server UDP discovery on the HTTP port + identity check mDNS/Bonjour; QR code; typing an IP Only Node's dgram is needed (no Avahi on Linux), one firewall rule covers TCP and UDP, and the reply reveals nothing /.well-known does not. The gsc1. code covers subnets and tailnets. QR stays for mobile.
Device-side tools Host tools: the client declares tools, calls are relayed Ship client extensions or MCP servers to the server The tool needs the client's device. With host tools the server never runs client code and nothing is installed on it.
Forwarded pages One listener per forward, ticket → cookie A path prefix on the API port; a generic tunnel Real pages use absolute paths and their own WebSocket URLs, which break under a prefix. An origin per forward isolates pages from the API and from each other.
Terminals A separate native host (Rust) owns the PTYs node-pty in serve; tmux PTYs must outlive a serve restart. node-pty is 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.
Config without a session A hidden control session per server Re-implement config, sign-in and packages in serve Every Desktop RPC rule (validation, redaction, revisions, Pi's own login and package code) is reused unchanged, with one owner per file.
Config stores after #3547 One mcp store (upstream shape + documents, writable per layer); pi_settings writable as a patch of its four model keys Keep parallel mcp_servers / model_defaults stores One store per file. mcp keeps upstream's display summary (servers) and adds the documents an editor needs. pi_settings writes 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 serve or gentle-shell relay runs, except for the additive Desktop RPC surface. Shared code touched:

  • bin/gentle-shell.mjs:
    • serve and relay branches import their runtime modules only when used.
    • The launcher now sets 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: serve and relay become commands, recognized after the home selectors as setup is. Before, gentle-shell serve … was sent to the model as a prompt; now it is the command.
  • lib/desktop-rpc.ts:
    • Every event and get_snapshot gains epoch.
    • setRequestLimits() sets per-method request caps: only set_host_tools (1 MiB), host_message/set_host_context (2 MiB) and host_tool_result (10 MiB) get more than 64 KiB.
  • extensions/gentle-desktop-rpc.ts:
    • capabilities gains the host tools, sign-in, packages and list_available_models methods and their events.
    • The new bridges do nothing until a client calls them and reset on session change. No tool is registered by default.
  • lib/desktop-rpc-config.ts:
    • Adds custom_models.
    • mcp and pi_settings become writable, and mcp gains documents.
    • A client that relied on mcp/pi_settings answering read_only gets a real write instead (both still require expectedRevision).
  • lib/desktop-auth-service.ts / lib/desktop-rpc-auth.ts: get_auth_status rows gain loginKinds, plus list_available_models.
  • lib/profiles-orchestrator.ts: model-defaults helpers that the pi_settings write uses. The existing orchestrator write is unchanged.
  • Tests: existing Desktop RPC suites update only their expected capabilities and store lists.
  • Packaging: scripts/build-runtime-modules.mjs generates the serve-*, rpc-host and relay runtime modules (46 generated modules in total). scripts/verify-package-files.mjs requires them plus docs/serve.md and docs/remote.md.
  • Merge with main: main is merged in (not rebased: the branch is published). The merge resolved the Desktop RPC config conflict with feat(desktop): add read-only mcp, pi_settings, and claude_bridge config stores #3547 as described in Design decisions.

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:

  1. MCP validator by path:
    • lib/pi-user-config.ts loads validateMcpServerConfig from <pi>/dist/core/mcp-servers.js.
    • If it moves, every mcp write answers invalid_data ("Pi's MCP server validator is not available") instead of writing unchecked.
    • The mcp read summary uses upstream's lib/mcp-config.ts mirror, which tests/desktop-rpc-config-mcp-fidelity.test.ts compares 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.
  2. Models schema by path:
    • custom_models validates against <pi>/schemas/models.schema.json, which Pi publishes in its package.
    • If it is absent the validator is null and writes are refused.
  3. OAuth flow kinds:
    • lib/desktop-rpc-auth.ts keeps 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.
    • A new provider defaults to a browser sign-in.
  4. Pi's --session-id: resuming by exact id relies on Pi's flag.
  5. Login callback: sign-in from a client completes Pi's own loopback callback by passing the redirect URL through login_complete. That depends on Pi's flow accepting a pasted redirect, which its manual-input path does.

Security review checklist

  • No unauthenticated surface besides GET /.well-known/gentle-shell, POST /api/pair/proof (rate-limited, returns HMACs only) and POST /api/pair. Loopback bind by default.
  • Network binds are TLS with a pinned self-signed certificate. Plain HTTP from another machine gets 400 tls_required. --no-tls is explicit and warned. --relay refuses --no-tls.
  • Pairing proof: scrypt (N=32768, r=8) + HMAC over fingerprint and a client nonce. A forged discovery reply cannot obtain the code. Offline guessing of a 40-bit code costs scrypt per guess and expires with the code (5 minutes).
  • Pairing codes are 40 bits, single use, valid 5 minutes, at most 16 live, with a global pause after 10 failures per minute.
  • Device tokens are 32 random bytes, shown once, stored as sha256, and compared in constant time. Revocation ends tokens, tickets, streams, forwards, terminals and pending host tool calls at once. DELETE /api/devices/self lets a client unpair cleanly. replace revokes the earlier device after moving its terminals.
  • Scopes are checked per request, and per command or method on /rpc, /desktop and /api/desktop. Read-only methods are listed explicitly; everything else needs sessions:operate.
  • Host allowlist (421) and Origin (http(s)://<Host>) checked before auth. No cookies or CORS on the API. Strict security headers.
  • Long-lived tokens never go in URLs. SSE and forwards use 60 s single-use tickets bound to one stream or forward.
  • Forwards: loopback targets only, a per-forward cookie name, per-forward Origin, and tickets and cookies stripped before the page.
  • Keepers: an owner-only socket per session, a per-session token in a 0600 record, the socket path kept inside the Unix limit, and the config (with the environment) passed on stdin, never argv.
  • Host tools: provider is forced to the calling device, only the provider answers, set_host_activity is server-only, and the server never runs client code.
  • Files run as the server user with no folder jail (documented). remove/rename refuse root, home and ancestors. Writes are atomic.
  • git: no shell, no prompts, an environment allowlist, and program-running options and config refused for every scope.
  • Terminals: a separate terminal scope, an owner-only socket (or loopback TCP + token on Windows), per-device ownership, and a sha256-checked binary install for admin only.
  • Config stores: no paths in answers. Secrets (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 project mcp.json is read and written only for a trusted project.
  • Sign-in: keys are never echoed, one flow per provider, 15-minute cap, and Pi's own state check on the OAuth callback.
  • Upgrade and setup are admin only and one job at a time. A restart keeps sessions and terminals.
  • Relay: shared-secret registration, fingerprint lookup, TLS end to end, byte counts only in logs.
  • Everything is bounded: bodies, replay rings, subscriber buffers, stdin backlog, records, sessions, devices, tickets, forwards, watchers, git, print, uploads and terminal streams.
  • Remote authority never exceeds the terminal's. Pi and Desktop RPC checks still apply inside each session, and provider consent stays terminal-only.

Tests and live evidence

Automated

Branch head after the merge, macOS arm64, Node v26.13.0:

Check Command Result
Serve suites (19 files, 5 of them ending in a leftover-process guard) node --experimental-strip-types --test tests/serve-*.test.ts 154 tests, 154 pass, 0 fail
Desktop RPC suites (incl. host tools, sign-in, packages, config stores, upstream's mcp fidelity and display-store tests) node --experimental-strip-types --test tests/desktop-rpc*.test.ts 572 tests, 572 pass, 0 fail
Typecheck pnpm typecheck 0 diagnostics, no regressions
Runtime modules pnpm check:runtime-modules runtime matches TypeScript sources (46 generated modules)
Package files node scripts/verify-package-files.mjs passed (325 files)
Full suite, unit stage node scripts/run-test-suite.mjs (tests/*.test.ts) 12171 tests: 12064 pass, 99 skipped, 8 fail. None of the 8 come from this branch: 7 fail the same way on an unmodified main checkout on this machine, and 1 is a timing flake (see the note below).
Provider contract node scripts/check-provider-contract.mjs passed (contract 1.7.0)
Runtime harness node --experimental-strip-types tests/runtime-harness.mjs exit 0
Leftover processes ps after the serve suites no session keeper or fake Pi left running

The 8 unit-stage failures, all outside this branch. Each file was run on the branch and on an unmodified main worktree, on the same machine with the same node_modules:

Test file Branch main
tests/gentle-shell-bin.test.ts: four "on a TTY …" resume-line tests 4 fail 4 fail
tests/session-profile-extension.test.ts: two "A3 foreign launch …" tests (repository_root must select a canonical independent Git repository) 2 fail 2 fail
tests/verifier-preparation.test.ts: "#3009: the documented Bash call creates its own scratch …" 1 fail 1 fail
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) 0 fail 0 fail

In the full run, the provider-contract and runtime-harness stages failed only because pnpm was not on PATH. 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 unmodified main worktree fails the same way. Its store list is updated for this branch.

How the tests work:

  • The serve tests run real servers on loopback, with a fake Pi (tests/fixtures/serve-fake-pi.mjs) and a fake terminal host.
  • They cover pairing and the pairing proof, TLS, the relay, scopes per endpoint, tickets, revocation, Host/Origin, replay, resume and 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.
  • The sign-in tests drive fake OAuth, device and key providers through Pi's real model runtime and credential store in a temporary agent home.
  • No test makes a model call.

About the earlier red CI runs:

  • The CI runs for b173ec67f, 48ba3b6c5 and 8ae6528d0 failed only in tests/codegraph-readiness.test.ts: runCodegraph timeout and process-group kill timing.
  • The same test failed on several main runs 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.
  • e5f4c2753 passed.

Test hygiene:

  • A serve test used to leave a session keeper and its fake Pi running after every run (a keeper with no server waits 24 h).
  • Tests that start sessions now stop them in teardown.
  • Every serve suite that starts servers or sessions ends with a guard test asserting that no keeper, fake Pi or daemon for its temporary homes outlived it.

Live: macOS, GPUI as the client

  • Setup: an isolated server home, serve share with a relay, and pairing by short code over TLS (fingerprint pinned).
  • Project: Files, open file, the Changes diff and Branches worked against a server repo, and a server terminal ran top.
  • Restart and relaunch:
    • Across serve stop + share, the session id was unchanged (seq 44, "reattached (seq 44, running)") and the terminal id was unchanged, with top still updating.
    • After ⌘Q and relaunch, the session (seq 46 → 74) and the terminal came back.
  • Forwards: a forwarded page (/web http://127.0.0.1:18920/) loaded through a local proxy.
  • Relay: pairing through the relay used a gsc1. code whose LAN addresses were decoys. The relay log shows spliced connections.
  • Packages: install and remove of a local package. The remove bug found here is fixed in 3bebba589.
  • Upgrade button: shown for the admin device only.

Bugs found on this run and fixed on the branch:

  • Event numbering restarting after a reload is fixed by epoch (8d7f04211).
  • Re-pairing at another address orphaning terminals is fixed by replace (94635c528).
  • An unpair that did not reach the server is fixed by devices/self (70d39571a).

Live: a real Arch Linux (Omarchy, x86_64) server, GPUI on macOS over the LAN

  • Pairing: paired over TLS (https://192.168.100.92:8787), with the identity fingerprint matching the pin. The device had sessions:read, sessions:operate and terminal, so /api/devices correctly answered 403.
  • Folders and git: opened a server folder and started a session. Created and edited a file, ran git init and a commit from the server terminal, then saw the Changes diff (M hello.txt +2 −1) and Branches.
  • Terminal: uname -a printed Linux … 7.2.15-1-omarchy … x86_64, and top updated live.
  • Upload and download: a drag-and-drop upload landed with the right content, and a download matched the server file byte for byte.
  • Agent: the agent tab listed models, and a prompt listed the folder (3 prompts in total over the run).
  • Host tools:
    • open_page created a server forward (8765 → 8800) and a local proxy, and the page loaded.
    • The checklist UI's "Send to agent" reached the agent.
    • Two client bugs found here (the page not shown at once, and closing it leaving the forward open) were fixed in the GPUI PR and re-verified: /api/forwards was empty within 2 s of closing.
  • App relaunch: same session id and same terminal ids, the transcript restored, and top still updating.
  • Server configuration over the stores: home, version, model defaults, sign-ins with their kinds, the models.json and mcp.json editors (opened and reloaded, nothing saved), and packages.
  • serve restart on that machine: serve stop then serve share with the app open. The server's start time changed (04:53:45 → 05:14:39) while its id stayed srv_0727f76e…; the agent session ses_427e64d8… came back running at the same seq (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).
  • Not run on that machine: Setup, Upgrade, and any sign-in or package install.

Screenshots: omarchy-00…68 and mm-00…44 from these runs can be attached on request.

Review questions

  1. Permission elevation from a remote device. sessions:operate can call Desktop RPC set_permission_mode, including super-yolo with persist: true, exactly like the Desktop app's stdin. Is that acceptable, or should elevation from serve need its own scope?
  2. sessions:read reads 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 an fs:read scope out of the default pairing?
  3. What the mcp documents expose. Upstream's mcp summary deliberately hides command, args, cwd and url. The editable documents return them, because an editor needs them, with secrets redacted, including credential-bearing URLs. Secrets placed directly in args (--api-key=…) are not redacted. Is that acceptable for sessions:read, or should documents require sessions:operate?
  4. Revisions over hidden content. The mcp, custom_models (and notifications) revisions digest the real content, so an outside change to a secret moves them. With pi_settings and claude_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?
  5. pi_settings as 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?
  6. Pi internals loaded by path (see Fragile points). Would Pi export validateMcpServerConfig, loadMcpConfig and the OAuth flow kinds, so these become imports?
  7. Where gentle-term-host comes 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?
  8. Keepers as detached processes. A keeper outlives serve by design. Is the 24 h orphan stop the right bound? Should serve status list orphaned keepers?
  9. Self-signed only. Is pin-at-pairing enough for phase 1, or is a rotation command (re-pair on rotate) needed first?

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", or docs/remote-test-runbook.md):

corepack pnpm install
node bin/gentle-shell.mjs serve share     # HTTPS on 8787, prints the short code and the gsc1.… code
sudo ufw allow 8787 && sudo ufw allow 8800:8899/tcp   # if ufw is on

Then type the code in Gentle Shell GPUI (gentle-shell-gpui#255) under Configuration → Where agents run → Gentle Shell server.

By hand:

node bin/gentle-shell.mjs serve pair --json        # a code for a loopback server
curl -s -X POST http://127.0.0.1:<port>/api/pair -H 'content-type: application/json' -d '{"code":"ABCD-EFGH","name":"curl"}'
curl -s http://127.0.0.1:<port>/api/sessions -H "authorization: Bearer gss_…"

Other options:

  • Outside the LAN: run gentle-shell relay --listen 0.0.0.0:7700 on a VPS, put its secret in <home>/serve/relay-secret, and run serve share --relay gsr://host:7700.
  • Terminals: need a gentle-term-host build (GENTLE_TERM_HOST=…), or let the app install one.
  • Stop everything: node bin/gentle-shell.mjs serve stop --sessions.

Commits

Grouped by area (oldest first within each group).

  • Serve core: 46459aa5f session host with seq and dialog replay · ef7290794 pairing, scoped tokens, stream tickets · dbf454900 hardened HTTP + SSE API · 7767ca5fd command, daemon, server file and lock · e078ee56c --allow-host · 164f20c54 resume by exact id · 39f2df55f stable server id
  • Pairing and reach: fa9e84b36 /.well-known identity · ee9e4a126 serve share and the connection code · fd25173af LAN discovery · 2056aa028 keeper, TLS with pairing proof, relay · 70d39571a unpair self · 94635c528 replace an earlier pairing
  • Sessions: e150bb9c9 keeper socket inside the Unix path limit · c807c5e0b impostor socket test · 8d7f04211 Desktop RPC epoch
  • Host tools: 80f64084c host tools · 9e83ea6a6 routing to the provider device · 2a73098b3 host messages, context, result details · c91ad9d68 several providers per tool · f561ca285 host_tool_progress
  • Forwards and Tower: b0d376273 authenticated forwards · 7ea9eaa3a Gentle Tower · e9c80dbbd server-level forwards and services
  • Files, git, uploads, terminals, print: 6c933a18b files · 55c8a8e0a git · 98bb21475 uploads · 858b3b40d terminals over a native host · 1742d1652 term host over TCP on Windows · e5f7e19e1 one-shot prompts · 27a466201 print model typing
  • Desktop RPC: b3cd72c02 sign-in and API keys · cc4c78806 packages · 3bebba589 local package paths · 6d629be80 model defaults (now in pi_settings) · aa294a381 custom models and MCP stores (now mcp) · 8ae6528d0 /api/desktop and list_available_models
  • Upgrade and setup: b173ec67f upgrade from a client · 9f83acc50 setup from a client · 48ba3b6c5 no config paths in server info
  • Docs: 9f36f4913 protocol and security model · 11c517cc7 try from source on Linux · 9e7e219de docs/remote.md · 16ef9bda5 Linux guide refresh · e5f4c2753 HTTPS · 66817e1cf Linux test runbook · e653924d9 orchestration plan (Phase 5) · 5e27aa695 remote.md: TLS and the relay
  • Merge and hygiene: fd8276e5d merge main (config stores reconciled with feat(desktop): add read-only mcp, pi_settings, and claude_bridge config stores #3547) · 200a3df96 tests stop the session keepers they start

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.
@coderabbitai

coderabbitai Bot commented Nov 24, 2026

Copy link
Copy Markdown

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

…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.
- 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).
@ismaelosuna7824 ismaelosuna7824 changed the title feat(serve): gentle-shell serve, server-owned sessions behind device pairing (RFC #3527 phase 1) feat(serve): gentle-shell serve — server-owned sessions behind device pairing (RFC #3527 phase 1) Nov 26, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant