Skip to content

Latest commit

 

History

History
1711 lines (1509 loc) · 114 KB

SERVER.md

File metadata and controls

1711 lines (1509 loc) · 114 KB

Server mode (candy-code serve)

candy-code serve runs an HTTP + WebSocket server that a browser (the candy-code-web UI), a terminal (candy-code attach) or a script drives candy-code through. It runs in the foreground until Ctrl+C or SIGTERM — or in the background with --detach — on the same ReactPHP loop the engine's forked turns use, and serves one project root — the current directory or --root.

This page covers the transport — binding, authentication, the WebSocket endpoint and the security model — and the candy-code.v1 protocol spoken over it: sessions, turns, events, permission answers (The candy-code.v1 protocol). Background mode and the verbs that manage a running server (serve status|stop|logs|url|token) are below.

Starting it

candy-code serve                       # 127.0.0.1:7420
candy-code serve --port 0              # any free port; the startup lines say which
candy-code --root ~/src/app serve      # serve another project
candy-code serve --output-format json  # one JSON document with the URL on stdout
candy-code serve --detach              # in the background; prints the URL and pid, then returns

On start it prints, on stderr, the address, the project root, the permission mode its sessions start in, where the web UI is served from, and a sign-in URL:

candy-code serve: listening on http://127.0.0.1:7420 (pid 4242)
  root:            /home/me/src/app
  permission mode: default
  web UI:          /…/vendor/sugarcraft/candy-code-web/dist
  sign in:         http://127.0.0.1:7420/#code=3f9c…
                   (one-time code, valid 120 s; Ctrl+C stops the server)

Open the sign-in URL in a browser on the same machine. The code rides in the URL fragment, so it never reaches a request line, a server log, a proxy or a Referer; the page posts it to /api/login and receives a session cookie. The login response body also carries loginSecret, a 64-hex per-login secret the client must echo in the header X-Candy-Code-Auth on every ticket mint and every cookie-authenticated /api/* POST; a request without the matching secret is refused 401 and burns a lockout strike.

Flag Default Meaning
--host <ip> 127.0.0.1 Address to bind. localhost and ::1 are loopback too. Anything else is refused without --allow-remote.
--port <n> 7420 Port to bind; 0 picks a free one.
--allow-remote off Permit a non-loopback --host. Prints a warning on every non-loopback bind — the cleartext row unless built-in TLS is on (--tls-cert + --tls-key), the over-TLS credential row with it, and an extra row when no --allowed-ips roster pins who may connect. Flag-only by design: a persisted allow-remote would silently re-widen the next unattended launch. On a wildcard bind (0.0.0.0, ::) the server also answers to this machine's own addresses and its sign-in URLs name them (Remote access).
--tls-cert <file> none Built-in TLS): the PEM certificate the public listener serves with, given together with --tls-key. The sign-in URLs then read https://, the session cookie carries Secure, and a plaintext http:// client gets no answer at all. A bad, unreadable or half pair refuses startup (exit 2) rather than serving cleartext quietly.
--tls-key <file> none The PEM private key for --tls-cert. It must be a readable file with no group- or world-readable mode bits, and it must match the certificate.
--allowed-host <list> none Comma-separated extra host names (or host:port; an IPv6 address in brackets) the server answers to beside the loopback names and its own addresses — e.g. a DNS name for this machine. Repeats accumulate.
--allowed-ips <list> none — every address Comma-separated client IPs or CIDR ranges (1.2.3.4,10.0.0.0/8,2001:db8::/32) allowed to connect. Any other client is refused 403 ip_refused before the Host check, sign-in or any credential; loopback is always allowed. Repeats accumulate (Remote access).
--allowed-origin <list> none Comma-separated extra browser origins (http(s)://host[:port]) accepted beside the server's own. Repeats accumulate.
--allow-dir-browse off Let signed-in clients choose the directory a new session starts in: fs.listDirs lists directory names (never files) under --browse-root, and the web UI's "New session" opens a folder picker (Choosing a new session's directory).
--browse-root <dir> your home directory The directory --allow-dir-browse is confined to. Resolved at start; one that does not exist refuses startup. Has no effect without --allow-dir-browse.
--web-root <dir> the installed sugarcraft/candy-code-web build Serve the UI from <dir>.
--no-web off API and WebSocket only.
--allow-bypass off Let sessions run in bypass-permissions or dont-ask.
--allow-root off Permit running as root.
--detach off Run in the background (Background mode).
--parent-pid <pid> none Stop when process <pid> exits (Parent-pid watchdog).
--permission-mode <mode> default The global flag: the mode server sessions start in.

The flags belong to the verb: candy-code --port 1 serve is an unknown option (exit 2), exactly like session's flags.

Each setting resolves flag → environment variable → user config key → default; the highest source that is set wins outright, and lists are not merged across sources. The permission mode resolves --permission-mode → CANDY_CODE_PERMISSION_MODE → default; the persisted permissionMode key is the TUI's and does not apply here.

Variable Settings key Meaning
CANDY_CODE_SERVER_HOST server.host Bind address.
CANDY_CODE_SERVER_PORT server.port Bind port.
CANDY_CODE_SERVER_ALLOWED_ORIGINS server.allowedOrigins Extra origins (a comma-separated string; the key is a JSON list).
CANDY_CODE_SERVER_ALLOWED_HOSTS server.allowedHosts Host names (or host:port) answered beside the loopback names and the server's own addresses — a reverse proxy's public name (a comma-separated string; the key is a JSON list).
CANDY_CODE_SERVER_ALLOWED_IPS server.allowedIps Client IPs or CIDRs allowed to connect beside loopback; unset or empty admits every address (a comma-separated string; the key is a JSON list).
CANDY_CODE_SERVER_WEB_ROOT — UI directory.
CANDY_CODE_SERVER_TOKEN — The owner token, instead of the stored one (≥ 32 characters; for containers).
CANDY_CODE_SERVER_DIR — State directory, default ~/.candy-code/server.
CANDY_CODE_SERVER_PARENT_PID — The parent pid to watch, like --parent-pid.
— server.trustedProxies IPs or CIDRs whose X-Forwarded-For / X-Forwarded-Proto are believed.
— server.allowBypass true is the same as --allow-bypass.
— server.dirBrowse true is the same as --allow-dir-browse.
— server.browseRoot The browse root, like --browse-root.

Every server.* key is read from ~/.candy-code/config.json only — never from a project file, because a cloned repository must not be able to open a port, widen the origins a browser may drive the agent from, or hand out the bypass modes. A non-loopback server.host still needs --allow-remote on each launch.

Refusals and exit codes

serve refuses to start, at exit 2 before binding anything, when:

  • an operand follows the verb that is not one of status, stop, logs, url or token, a flag belongs to a different action (serve stop --detach), or a flag value is malformed (a port that is not 0–65535, an origin that is not http(s)://host[:port], an allowed host that is not host[:port], an allowed IP that is not an address or CIDR range, a --parent-pid that is not a pid, or — with --allow-dir-browse — a browse root that is not a directory);
  • --host is not loopback and --allow-remote was not given;
  • the permission mode is bypass-permissions or dont-ask and neither --allow-bypass nor server.allowBypass permits it;
  • it runs as root without --allow-root;
  • ext-pcntl, ext-posix or ext-ffi is missing (or FFI is disabled by ffi.enable) — see Why pcntl, posix and FFI;
  • the state directory is unsafe (a symlink, someone else's, or not exactly 0700), or CANDY_CODE_SERVER_TOKEN is shorter than 32 characters;
  • --parent-pid names a process that is not running.

A port that is already taken is exit 1: it ran, failed, and may succeed once the port is free. So is a second server on the same state directory — the first one holds its lock — and a --detach whose background server failed to bind (its reason is printed; the detail is in server.log). Under --output-format json that failure is still one document on stdout, carried like doctor's failing report — as the answer, not as a new error.type: {"result": {"listening": false, "address": "…", "reason": "…"}}. A refusal is the usual usage error document. candy-code doctor reports the three extensions as its server mode check (a WARN, never a FAIL — the TUI does not need them).

Background mode

candy-code serve --detach        # background: prints the URL + pid once bound, exits 0
candy-code serve status          # pid, URL, root, uptime, and whether /api/health answers
candy-code serve stop [--force]  # SIGTERM, time to drain, then SIGKILL (--force: SIGKILL now)
candy-code serve logs [-f]       # the end of server.log; -f follows it until the server stops
candy-code serve url [--qr]    # a sign-in URL with a fresh one-time code (--qr: also a scannable terminal QR code, text output only)
candy-code serve token [--rotate]

--detach daemonizes the way background (/bg) sessions do — the same sequence, in one place (Support\Daemonize): umask 077, fork, setsid(), fork again, so the server has no controlling terminal and outlives the shell that started it. Its stdin is /dev/null and its stdout and stderr append to server.log. The command you ran waits until the server has bound its port and then prints the same startup lines a foreground server does (one JSON document under --output-format json, with "detached": true and the log path), so the URL it prints is one that already answers. The sign-in code itself is never written to the log.

The state directory (~/.candy-code/server/, or CANDY_CODE_SERVER_DIR) is 0700 — refused if it is a symlink, someone else's, or any other mode — and holds:

File What
token the owner token, 0600
server.json the discovery record: {pid, procStartTime, version, protocol: {min, max}, url, host, port, root, startedAt, detached, log}, 0600, replaced atomically. Never the token.
server.lock the singleton lock: flock() held for the server's whole life, so the kernel releases it however the server dies
control.sock the local socket serve url and serve token --rotate reach the running server on; every request carries the owner token
server.log a detached server's stdout and stderr, rotated past 10 MiB into server.log.1 and server.log.2

One server runs per state directory: a second serve finds the lock held and exits 1, naming the running one. A foreground server keeps the same record, lock and control socket, so status, stop and url work on it too.

A record is checked, not believed. status and stop act on the pid in server.json only while that pid is still the process that started at the recorded procStartTime (/proc/<pid>/stat), so a pid the kernel has handed to something else is never signalled. A record that fails the check — a server that was SIGKILLed cannot remove its own — is reported as stale, and stop removes it.

Stopping. SIGTERM or SIGINT (what serve stop and Ctrl+C send) — or a client's server.shutdown — drains the server. First it admits no new turn or session (busy / draining), tells every client how long it will wait (server.shutdown with graceSeconds), and waits for the turns already running to settle, up to server.drainSeconds (10 s; 0 skips the wait); a second signal stops it at once. Then it closes every WebSocket with 1001, cancels any turn still running and releases every session, removes server.json and control.sock and releases the lock. serve stop waits 30 s for that — or the configured drain plus 5 s, when that is longer — then sends SIGKILL; --force skips straight to SIGKILL. SIGCHLD is never handled — the turn children are reaped by the engine's own sweep.

Verb Exit 0 Exit 1
serve status a server runs (health is ok, or unreachable when it does not answer /api/health) none runs (a stale record is reported as such)
serve stop it stopped none was running, or it did not exit
serve logs the log was printed there is no server.log (only a detached server writes one)
serve url a fresh sign-in URL was printed (--qr: each URL also as a terminal QR code) no server runs, or it refused the token
serve token the token was printed and a server runs (--rotate: replaced first, a running server reloads it; rotating needs no server and exits 0) no server runs: the stored token is still printed on stdout, with a stderr warning (no server is running (stored token shown)) — refused at 2 while CANDY_CODE_SERVER_TOKEN is set

Under --output-format json each prints one {"result": …} document — the "no server" answers included, as results rather than errors; logs -f streams text and does not combine with it, and neither does serve url --qr (the code is text). The management verbs read the state directory without creating it.

Parent-pid watchdog

--parent-pid <pid> (or CANDY_CODE_SERVER_PARENT_PID) makes the server stop, exactly as SIGTERM would, once that process has exited — for an editor or a TUI that starts a private server and may crash without stopping it. The parent is checked every second by pid and start time, so a recycled pid reads as gone; a pid that is not running at startup is refused. It combines with --detach.

systemd

Under a service manager run the server in the foreground — the manager is the supervisor, and --detach would only hide the process from it. examples/candy-code.service is a user unit:

cp docs/examples/candy-code.service ~/.config/systemd/user/
systemctl --user daemon-reload
systemctl --user enable --now candy-code
journalctl --user -u candy-code -f   # the server's log; candy-code serve url for a sign-in link

Authentication

Every request that can read or change anything carries a credential — on loopback too. Anything that can send a prompt can run code as you, and 127.0.0.1 is reachable by every other account on the machine and, by DNS rebinding or a cross-site WebSocket, by any page your browser opens.

The owner token. 32 random bytes (64 hex characters), minted on the first serve into <state dir>/token — mode 0600 in a 0700 directory this user owns. CANDY_CODE_SERVER_TOKEN replaces it. It is compared with hash_equals and never printed by serve itself; candy-code serve token prints it on request for a script that needs a bearer credential, and serve token --rotate replaces it. A running server is told at once over its control socket: it re-reads the file and signs every client out — every browser cookie, unspent ticket and login code is revoked and every open WebSocket is closed with 4001 — so the old token stops working now, not at the next restart (--output-format json reports serverReloaded). A server that cannot be reached keeps the old token until it restarts, and serve token says so.

Browsers never hold the token:

  1. serve prints a sign-in URL with a one-time login code (single use, valid 120 s) in its fragment.
  2. The page posts {"code": "…"} to POST /api/login and receives an HttpOnly, SameSite=Strict cookie plus the loginSecret body field. The cookie is port-scoped — candy_code_session_<port> — so two serve instances on one host never share ambient sign-ins (7-day sliding lifetime; the horizon is a fixed constant, not a configuration knob — changing it is a code change. Secure when the browser arrives over TLS — the built-in listener with --tls-cert/--tls-key, or a trusted proxy reporting HTTPS). Under that same TLS condition the name carries the __Host- prefix (__Host-candy_code_session_<port>), pinning it to this exact origin; a cleartext bind keeps the bare name, which is what plaintext can honestly carry. Adopting the prefix renames the cookie, so sessions opened before the upgrade sign out once on next visit — an accepted one-time cost, not a rolling behaviour. Posting {"token": "…"} works too.
  3. Before each WebSocket connect the page asks POST /api/ticket (cookie + X-Candy-Code-Auth secret) for a single-use ticket valid 30 s, bound to its cookie session and to that login secret, and opens /ws?ticket=….

Sessions persist across restarts as hash-only rows: CookieSessions::persisted() keeps expiry records keyed by a sha256 fingerprint of the owner token in sessions.json in the state dir (0600, mode-before-rename, pruned on boot), so restarting the server no longer signs every browser out — but rotating the token while the server was down does, because every row is bound to the old token's fingerprint. A signed-in browser session that goes unused for the cookie lifetime (7 d sliding, stamped on each authenticated request) has its open sockets swept shut with close code 4001 — "your sign-in expired"; logging out revokes instantly and closes every WebSocket bound to the session the same way.

Scripts and tools authenticate directly:

  • HTTP: Authorization: Bearer <token>;
  • WebSocket: the same header, or — for a client that cannot set headers — offer the subprotocol candy-code.auth.<token> beside candy-code.v1. The 101 echoes candy-code.v1 only, never the token entry.

Rate limiting. Ten wrong credentials from one address within a minute lock that address out for five minutes (429 with Retry-After). Behind a trusted proxy the address is the right-most untrusted X-Forwarded-For hop. The limiter authenticates before it consults strikes: a valid bearer token or candy-code.auth. subprotocol is admitted even while its address is locked out, so an attacker flooding the shared loopback bucket cannot lock out the owner. A non-upgrade GET /ws is answered 426 before auth and never counts. Failed ticket presentations count only on a real WebSocket upgrade with a matching Origin — cross-site probes (<img src=…/ws?ticket=bogus>) get their 401/426 for free; junk cookie attempts always count. The strike that trips a lockout is logged once.

Ingress hardening. ClientAddressGuard (--allowed-ips / server.allowedIps) and the Host check run immediately after header parsing, before any body is buffered. Every request gets a 10 s header/body read deadline — a stalled body is answered 408 with Connection: close and the socket is torn down (idle pre-first-byte connections are dropped too) — and a single address may hold at most 16 simultaneous connections; more are refused 429. These bound HTTP ingress only — never LLM turns.

HTTP endpoints

Endpoint Auth Answer
GET /api/health none {"ok": true, "protocol": 1, "web": <bool>} — the web flag says whether a browser bundle was found; the payload still names neither the version nor the root
POST /api/login none (rate limited) {"code"} or {"token"} → {"ok": true, "loginSecret": "<64-hex>"} + the session cookie; wrong → 401
POST /api/ticket session cookie + X-Candy-Code-Auth secret {"ticket", "expiresInSeconds": 30}; a bearer client gets 400 (it needs no ticket)
POST /api/logout any revokes the session, closes every WebSocket bound to it with close code 4001, and clears the cookie
POST /api/hooks/{name} the webhooks user-config secret in the x-candy-code-hook header (constant-time; wrong ones lock out per hook and address) — or, when the row names signature, an HMAC-SHA256 of the raw body, sha256=<hex> in x-hub-signature-256 (GitHub) or x-signature (generic), or the configured header; a failed signature feeds the same lockout the body (≤ 64 KiB) is fence-escaped as untrusted input and spliced into the hook's configured prompt at {{payload}} — or appended below a plain label — and admitted through the same background door bg.spawn uses; {"ok": true, "bgId": …} on admission, 413 when the body is declared past the 64 KiB cap or arrives as an empty buffer behind a non-empty declaration (an over-cap body is refused, never spliced as an empty run), 429 over the configured per-minute rate — counted per address, and per hook overall, 503 if the turn cannot start. A signed row dedupes redeliveries too: a X-GitHub-Delivery (or configured deliveryHeader) id already served answers 200 {"ok": true, "duplicate": true} without starting a second session (a per-hook LRU of the freshest 1024 ids; a delivery that failed with 503 keeps its id unrecorded, so the sender retry still runs), and an over-cap signed body is refused 413 before the compare, never as a struck signature. Mounted only when webhooks names the hook: unconfigured, the path 404s like any unknown endpoint. bypass-permissions is refused for hooks at launch — a webhook has no one to answer an ask, and bypass answers every ask yes; dont-ask is accepted because it never asks — it refuses. A mode-less hook inherits the stricter of the server's mode and default, so an accept-edits or auto server hands mode-less hooks default.
POST /api/canvas session cookie + X-Candy-Code-Auth secret mints a single-use link to one canvas artifact: body {"sessionId","artifactId"} → {"url": "/canvas/<64-hex>", "expiresInSeconds": 60}; the id must name a .html document in that session's media store — anything else, including an unknown id, answers the shared 404 not_found, and a malformed body answers 400
GET/HEAD /canvas/{token} the token itself — public, like a share page the stored document with Content-Type: text/html; charset=utf-8 under a sandbox CSP (sandbox allow-scripts, connect-src 'none', frame-ancestors 'self'; X-Frame-Options: SAMEORIGIN) and Cache-Control: no-store. The token is consumed on first sight: unknown, expired, spent, or an artifact retired in between all answer the same byte-identical 404; other methods get 405
GET /ws ticket, bearer or token subprotocol — never the cookie alone, which a browser attaches by itself the WebSocket upgrade; Origin is checked, and a ticket only opens the socket for the login secret that minted it
anything else none the web UI's files (GET/HEAD only)

Refusals are JSON: {"error": {"kind": "…", "message": "…"}}. Clients branch on kind (unauthorized, rate_limited, host_refused, origin_refused, subprotocol_required, not_found, hook_unavailable, …), never on the message.

Signed inbound deliveries: the GitHub recipe

GitHub's webhook settings cannot attach a custom header, so a hook fed by GitHub names a signature scheme instead of relying on the x-candy-code-hook compare:

  1. In the repository's Settings → Webhooks, add a webhook to https://<host>:<port>/api/hooks/<name>, choose application/json as the content type, and set the secret to the same value you will put in the row.

  2. In the server user config, name the scheme on the row:

    {"webhooks": {"deploy": {"secret": "<32+ characters>", "prompt": "Review the push: {{payload}}", "signature": {"scheme": "github-sha256"}}}}
  3. The scheme replaces the header-secret compare: the route recomputes hash_hmac('sha256', <raw body>, <row secret>) and hash_equals-checks it against the sha256=<hex> value in x-hub-signature-256. A wrong or missing signature strikes the same per-hook-and-address lockout as a wrong header secret.

  4. GitHub's X-GitHub-Delivery id dedupes redeliveries: a delivery already served answers 200 {"ok": true, "duplicate": true} without starting a second session, while one that failed with 503 stays replayable so GitHub's own retry still runs. The dedupe lives in the server process only; a restart re-admits an already-seen delivery (GitHub retries a timed-out delivery past one, so the ring bounds duplicates, not events).

  5. For senders that are not GitHub, scheme: "hmac-sha256" defaults the signature header to x-signature and carries no delivery header — dedupe for such a row is opt-in by naming deliveryHeader explicitly. Any header/deliveryHeader override must be a single HTTP header name.

A push payload past the 64 KiB body cap arrives loud: the signed route answers 413 before the signature compare, so a middleware-swapped empty body can never false-strike a legitimate large sender into the lockout (raising the per-route cap is a separate change).

Channel bundles mount their own inbound routes under /channels/<bundle>/ — the router forwards the whole request and never learns a platform's protocol; each bundle terminates its own trust door (see PLUGINS.md, whose sugarcraft/candy-msteams example also covers the developer tunnel — devtunnel, ngrok, or a Tailscale Funnel URL — because Teams cannot reach a laptop's localhost).

Outbound webhooks are wired: the webhooksOut user-tier map (see SETTINGS.md) posts signed event deliveries to endpoints the operator names. The setting is read once at launch — a malformed endpoint is an exit-2 startup refusal, never a silent no-webhooks — and a cloned project can never add an endpoint, because the key is deliberately outside the layered tiers. Both hosts emit: the TUI announces turn.completed when a turn really settles, permission.asked when a prompt reaches the human, and schedule.fired for fired/error rows its pump makes; serve mirrors turn.completed and permission.asked off each hosted session's event stream and announces schedule.fired from its own schedule pump (the row lock means exactly one host fires a row, so exactly one delivery follows). Each delivery is an HMAC-SHA256-signed POST (X-Candy-Code-Signature: sha256=<hex> over the exact body, paired X-Candy-Code-Timestamp) on the event loop — dispatch never blocks the turn that caused it, redirects are refused rather than followed, transport failures and 5xx answers climb a 2/8/30-second retry ladder, and the in-flight queue is capped so a dead endpoint sheds new events instead of growing memory. session.ended completes the event vocabulary of the dispatcher itself; no emitter posts it yet in either host.

WebSocket

GET /ws with subprotocol candy-code.v1 — required: an upgrade that does not offer it is refused 426 before upgrading. Text frames only, UTF-8 JSON.

Limit Value Past it
Client message (all fragments) 1 MiB close 1009
Binary message not accepted close 1003
Invalid UTF-8, bad masking, bad opcode — close 1002 / 1007
A handler error — close 1011
Server stopping — close 1001

Pings are answered with pongs; a client close is echoed. permessage-deflate is off: it costs latency and CPU, and compressing secrets beside attacker-influenced text is a known oracle.

Messages are JSON-RPC 2.0 — the candy-code.v1 protocol below.

The candy-code.v1 protocol

Every message is a JSON-RPC 2.0 object. A client sends requests (with an id, answered) and notifications (without one, never answered); the server answers and sends events — notifications whose method is event. The server never sends a request of its own: a permission question is an event, and the answer is a request any client may make.

{"jsonrpc":"2.0","id":"c1-42","method":"session.send","params":{"sessionId":"a1b2…","text":"run the tests"}}
{"jsonrpc":"2.0","id":"c1-42","result":{"admitted":"started","turnId":"t_9f…","messageId":"…"}}
{"jsonrpc":"2.0","method":"event","params":{"sessionId":"a1b2…","seq":812,"type":"tool.started","ts":1790000000123,"turnId":"t_9f…","durable":true,"data":{…}}}

Handshake

The first request on a socket must be server.hello:

{"jsonrpc":"2.0","id":"h","method":"server.hello","params":{
  "minProtocol":1,"maxProtocol":1,
  "client":{"name":"my-tool","version":"0.1.0"},
  "caps":[],
  "resume":{"<sessionId>":<lastSeq>}}}

Its answer names the protocol (1), the server (version, connectionId, root, pid), the features — every method and event type this server supports, generated from the code that serves them — the limits below, the principal and its scopes, the defaults (the permission mode new sessions start in, and the delivery a client's composer should pick for a prompt sent while a turn runs — the queueMode setting, steer unless set, which is what the TUI's Enter does mid-turn; a session.send that names no delivery still queues), and, for each session in resume, how that subscription was resumed. features.dirBrowse is {enabled, root}: whether fs.listDirs and a browse-rooted workspace.open answer, and the browse root (null when off) — what a client checks before it offers a directory picker. Anything other than server.hello before it is answered -32002 (not_initialized) and the socket is closed with 4002; a message over 64 KiB before it closes the socket with 1009. A client must ignore event types and fields it does not know: within protocol 1 changes are additive only.

Limit (limits key) Value
maxClientFrameBytes 16 MiB
maxServerFrameBytes 4 MiB — a larger answer is refused too_large; a tool output past 256 KiB arrives truncated, and tool.output reads the rest; session.export pages the same way (limit/offset, with revision guarding the walk)
maxInflight 64 — advisory: announced in server.hello for clients to pace by; the dispatcher enforces no in-flight ceiling of its own
tickIntervalMs 15000 — a server.tick event this often
softBufferedBytes / maxBufferedBytes 1 MiB / 16 MiB (see Backpressure)
maxSubscribersPerSession 50

A client may send 50 requests a second, with bursts of 200; past that it is answered -32011 (rate_limited, retryAfterMs).

Errors

An error's data.kind is the machine-readable reason; branch on it, never on the message. Nothing a client sent is echoed back except the request id, which is returned exactly as sent (string or integer).

Code Meaning
-32700 parse error
-32600 invalid request (also unsupported_protocol)
-32601 method not found
-32602 invalid params
-32001 unauthorized — reserved: a socket authenticates at the upgrade, so no request meets it today
-32002 not initialized — server.hello first
-32003 forbidden (scope, or a write the server does not allow remotely)
-32004 not found (session_not_found, ask_not_found, …)
-32009 conflict (already_resolved, session_locked, refused, command_refused, trust_write_failed, …)
-32010 busy, retryable (too_many_turns, turn_running, draining, …)
-32011 rate limited, retryable
-32020 permission mode refused
-32030 unsupported in server (ui_only, remember_user_unavailable, …)
-32099 internal — the cause is in the server's log, never in the answer

Every method that changes something takes an optional idempotencyKey (up to 64 characters): a retry with the same key gets the original answer instead of doing the thing twice — a prompt resent after a dropped connection is not a second turn. Answers are kept five minutes, at most 1,000.

Methods

Scope read is enough for everything that only looks; the owner holds all four scopes (read, write, approve, admin) — but the declared scopes are not enforced per connection today: the split that bites is owner vs non-owner on the principal, and per-connection scope narrowing is still an open product decision. "Idempotent" marks the methods that accept an idempotencyKey. Every request's params are checked against the method's schema before it runs — a field of the wrong type, or a missing required one, is -32602 naming the field. The full schema of every params, result and event data is protocol/candy-code.v1.schema.json; it and the two tables below are generated from the code (php scripts/gen-protocol-schema.php --write), never edited by hand.

Method Scope Idempotent Required params What it does
agents.control write yes sessionId, agentId, verb Cancel, pause, resume or background a delegated run.
agents.list read — The agents a turn can delegate to.
agents.message write yes sessionId, agentId, text Message a delegated run: into its mailbox while it runs, as a follow-up once it finished.
agents.subtree read sessionId The sub-agents a session's turns have delegated to, with their latest activity.
agents.transcript read sessionId, agentId A delegated run's own transcript, read from a byte offset.
audio.status read sessionId, jobId A transcription job's state and text, from its ledger.
audio.transcribe write yes sessionId, audioBase64, mime Transcribe a base64 audio take through the configured voice endpoint; answers with its job id.
bg.inject write yes bgId, sessionId Send a settled background session's result into a session as a prompt.
bg.list read — The background sessions this server supervises, running and settled.
bg.output read bgId A background session's output from an offset.
bg.spawn write yes task Start a background session on a task, as /bg does.
bg.stop write yes bgId Stop a background session.
client.viewing read — Say which sessions this client shows, and which is in front.
command.exec write yes sessionId, name Run a slash command in a session (command files, and the built-ins that run headless).
command.list read sessionId The slash commands a session knows, and where each runs.
context.instructionWrite write yes sessionId, path Write one instruction document the session already reads — replace it by spelling content, or append raw bytes by spelling append (exactly one). The jail is the listing itself: path must equal a context.sources instructionFiles row, or "personal" for your own ~/.candy-code/AGENTS.md. A replace whose expectBytes no longer matches the file on disk refuses instruction_changed; a document past the loader's size cap refuses instruction_too_large; a path that now resolves through a symlink outside its jail refuses instruction_symlink. A landed write announces context.changed (reason "instructions") so the panel re-measures.
context.sources read sessionId What the session's context is built from: instruction files, memory notes, skills, declared MCP servers, refused paths, the token breakdown, and this root's pending project-trust prompts.
context.trust approve sessionId, askId, decision Answer one project-trust prompt (permission.asked with kind "trust") by its askId: grant or reject; a user-tier remember writes the answering prompt's target list (trustedProjectMcp for an mcp or mcp-pin row, the matching trustedProject* key for the others) in your own config, a project-tier one is refused.
files.changed read — The workspace's changed and untracked files.
files.diff read — The workspace's uncommitted changes to tracked files, as a unified diff.
files.read read path A file under the project root, read-only and size-capped.
fs.listDirs read — The child directories (names only, never files) of a directory under the browse root; needs serve --allow-dir-browse.
fs.search read — Workspace file names ranked against a partial (the web composer @-mention popup); jailed to the project root.
generate.status read sessionId, jobId A generation job's state, progress and artifact refs, from its ledger.
generate.submit write yes sessionId, prompt Start an image or video generation; answers with its job id.
mcp.resources read sessionId The launch-frozen MCP resource rows of the session root, without starting any server.
media.fetch read sessionId A stored media artifact's bytes, in base64 slices.
memory.add write yes content Add a note, routed like /memory add: a project note goes to the repository store when the tree can host one.
memory.delete write yes id Delete a note from the store that owns the id.
memory.edit write yes id, content Replace a note's text in the store that owns the id.
memory.list read — The notes of one memory scope, from both stores, each badged with its source.
memory.log read — The home store's commit history, newest first — the revisions memory.undo names.
memory.search read query Notes matching a query, best first, across every scope and both stores.
memory.undo write yes — Restore the home store to an earlier revision (by default the state before its latest commit), recorded as a new commit.
permission.audit approve — Recent tool-call decisions from this user's redacted audit log tail; a bounded read, every session unless one is named.
permission.forget approve yes — Remove one saved permission rule from the user config, addressed by its pattern or by its 1-based saved index.
permission.pending read — The questions still open, for one session or all open sessions.
permission.respond approve yes sessionId, askId, reply Answer an open permission question; the first answer wins.
permission.rules read — The effective permission mode and rules, read-only; saved user-tier rows carry their tier and 1-based saved index.
push.subscribe write yes endpoint, keys Store this browser's push endpoint so the server can notify it when a question is waiting or a turn finished while no client follows the session. The endpoint must be an https URL at a known push service (FCM, Mozilla, Apple, Microsoft); anything else is refused and nothing is stored. Keys arrive as the browser reports them (p256dh: base64url P-256 point, auth: base64url 16 octets). name opts the row into carrying the session title in the payload — WITHOUT it every notification stays redacted generic text.
push.unsubscribe write yes endpoint Drop the stored row for this push endpoint, when this client's principal class owns it; an unknown or foreign-owned endpoint answers false.
push.vapidKey read — The VAPID public key (RFC 8292, base64url of the 65-octet P-256 point) this server signs push messages with — the value the browser passes to PushManager.subscribe(). The private half never leaves the server.
server.health read — Liveness and load.
server.hello read — The handshake: protocol version, features, limits; optionally resume subscriptions (snapshotLimit pages their reset snapshots).
server.info read — What this server offers: providers, agents, commands, tools, permission modes.
server.logs admin — The tail of the server log, flattened and capped; admin scope is the only door.
server.shutdown admin yes — Stop the server, draining running turns first.
server.strings read — The web UI chrome strings in one locale: only web.-prefixed keys; server, tool and model text stay untranslated.
session.archive write yes sessionId Move a session to the archive tray; it leaves the default listing.
session.cancel write yes sessionId Cancel the running turn (hard, or soft at the next step boundary).
session.close write yes sessionId Release a session (refused while a turn runs unless force).
session.create write yes — Create a session and open it.
session.delete write yes sessionId Delete a session and its history.
session.dequeue write yes sessionId, queueId Remove a queued prompt.
session.export read sessionId A session's transcript as markdown, json or text; limit/offset page it and revision guards the walk.
session.fork write yes sessionId Branch a session into a new one carrying its transcript.
session.get read sessionId A session's snapshot: rows, status, queue, open questions, usage; limit/beforeIndex page the rows.
session.import write yes content Import an external agent transcript carried in the request; byte-identical re-sends land in the same session.
session.list read — The workspace's sessions, newest activity first, paged.
session.queue read sessionId The prompts queued behind the running turn.
session.rename write yes sessionId, name Rename a session.
session.send write yes sessionId, text Send a prompt: start a turn, or queue / steer / interrupt the running one.
session.setMode write yes sessionId, permissionMode The permission mode the session's next turns run in.
session.share write yes sessionId Publish an HTML snapshot of a session as a self-hosted share page at /s/{token}.
session.shares read — The live share pages of one session, or of every session when sessionId is absent.
session.subscribe read sessionId Follow a session's events from a cursor (replay) or from a snapshot; snapshotLimit pages the reset snapshot.
session.unarchive write yes sessionId Restore an archived session to the live listing.
session.unshare write yes token Revoke a share page by token; it 404s from its next request.
session.unsubscribe read sessionId Stop following a session.
settings.get read — Effective values and where each came from, or one tier's file; secrets masked.
settings.preview admin — What a save would write — the target file's diff, when each change applies, and what blocks it — without writing.
settings.schema read — Every setting: type, default, help, apply mode, and whether a client may write it; and the tiers a save can target.
settings.set admin yes — Write allowlisted settings to the user tier or a trusted project's local or shared file, in one write.
shells.input write yes sessionId, shellId Type into a running interactive background shell: literal bytes plus at most one named key, composed in that order and delivered as one human-origin send; the answer carries the cursor a following shells.output read threads from. This is a line-oriented door for a polling client — not a PTY stream over the socket, and it does not make the browser a terminal emulator.
shells.list read sessionId The background shells this session may see — its own plus the untagged ones — without their output.
shells.output read sessionId, shellId One windowed read of a background shell's output from a cursor.
shells.stop write yes sessionId, shellId Stop a background shell through the launch's kill ladder; a settled or foreign id is a no-op answer.
todo.get read sessionId A session's todo list, as its Todo tool last wrote it.
token.grant admin yes label, scopes Mint one viewer-token grant; the answer carries the raw token exactly once.
token.list admin — List the viewer-token grants in force — never the hashes, never a token.
token.revoke admin yes id Revoke one viewer-token grant by id; unknown and already-revoked answer alike.
tool.output read sessionId, toolCallId A finished tool call's full output, from an offset.
tools.client.register write yes sessionId, tools Announce client-hosted tools for this connection; an empty list withdraws them.
tools.client.result write yes sessionId, callId, registrationId, content Answer one tool.client.call with the client's result.
usage.rollup read scope The durable usage ledger folded by day and model — one snapshot of the same read /usage prints, with derived totals, the unpriced lower-bound flag, and this launch's session-retention setting (read-only). scope "session" narrows to sessionId; scope "all" spans every session the ledger holds; days trims to the last 7 or 30 whole UTC days.
workflow.list read — The workflows /workflow run can start.
workflow.pause write yes workflowId Pause a workflow run before its next stage.
workflow.resume write yes sessionId, workflowId Resume a paused workflow run in a session.
workflow.run write yes sessionId, name Run a workflow in a session, as /workflow run does: it occupies the session's turn.
workflow.runs read sessionId The workflow runs a session's transcript holds: /workflow reports and Workflow tool calls.
workflow.status read workflowId A workflow run's status.
workspace.close write yes root Stop a workspace host; refused while one of its turns runs, unless force.
workspace.list read — The project roots this server serves: its own, and each running workspace host.
workspace.open write yes root Start the workspace host for another project root, or find it running.

A session is opened on first use and holds the same lock a terminal session takes, so a session open in a candy-code TUI is refused session_locked rather than written by two processes. server.maxOpenSessions (32) bounds the sessions open at once — the least recently used idle one is released past it, never one with a turn running.

A live share page (session.share with the live flag, served at /s/{token}) renders the session's newest rows up to a fixed window and byte budget, and a truncated page says so in its own body; snapshots published before the budget shipped keep their frozen bytes. Re-publish a live share after upgrading so its page reflects what the session holds today — the server never rewrites a published snapshot behind your back.

Events

Durable events of a session are written to its event log before they are sent, carry a seq that is gap-free and increasing per session, and are what a reconnecting client replays. Live events (deltas, ticks) carry no seq, and a client never advances its cursor on one: every live stream is bracketed by durable events, so a dropped delta is repaired by the durable assistant.completed. A delta's data.offset is its byte offset into the part (data.partId), so a gap is visible. Server-scope events carry sessionId: null and no seq: there is no server log, so a client that missed one re-reads what it describes (session.list, permission.pending).

Runtime notices — what a turn's forked child records about itself (a parser warning, the count-only 💭 Recalled line) — are transcript rows too. Each served session owns its own notice sink, and the host drains it as its turn settles, on its server tick, and on the sink's one-shot loop wake; every drained row is a durable message.created with kind notice, uiOnly so it never re-enters the model. A notice from one session cannot surface in another because the sinks are per-session; a row recorded before any host exists (the launch's own MCP startup) stays in the process inbox, which serve arms but the TUI alone drains.

Type Scope Kind What it says
assistant.completed session durable The reply, complete; repairs any delta a client dropped.
assistant.delta session live Streamed reply text.
assistant.narration session live The tail of the reply so far, at most every 2 s, for narration subscriptions.
bg.completed server live A background session settled; bg.output reads its answer, bg.inject sends it to a session.
bg.started server live A background session started, or one an earlier server or TUI left running was re-adopted.
bg.status server live A background session's status changed (running, stalled, …).
compaction.completed session durable The history was compacted before a turn.
context.changed session live What this session's context is built from has moved (a settle, a compaction, a rules/memory/init command); live-only, and the client re-reads context.sources.
message.created session durable A transcript row was added: the prompt, a notice, a summary.
permission.asked server live A question was put for a client to answer: permission.requested with its sessionId, for every client, following the session or not — and a background session's relayed question, named by its background id and answered the same way. A third shape joins the arm: a project-trust prompt (kind "trust") discovered by a context.sources measurement, answered by context.trust and not by permission.respond.
permission.requested session durable A tool call is waiting for an answer (permission.respond).
permission.resolved session durable A question was answered or cancelled.
permission.settled server live A question was answered or cancelled (permission.resolved for every client) — a background session's relayed question included, cancelled when its session settled unanswered.
prompt.suggested session live A one-line follow-up suggestion for the turn that just settled, proposed by the title model and billed on it; live-only, never a transcript row, and the next settle replaces it.
reasoning.delta session live Streamed reasoning text.
server.overflow server live This client fell behind; ephemeral events were dropped — resubscribe.
server.shutdown server live The server is stopping.
server.tick server live Liveness, every tickIntervalMs.
session.created server live A session was created.
session.deleted server live A session was deleted.
session.status session durable The session became idle, busy or waiting_permission.
session.updated server live A session was renamed, its mode changed, its model changed, or its status changed (idle, busy, waiting_permission). A served /model or /rename reaches every client through this arm, not only the status lane.
spend_cap.breached session durable The session spend cap stopped the turn.
subagent.finished session durable A delegated sub-agent finished.
subagent.progress session live A delegated sub-agent made progress.
subagent.started session durable A delegated sub-agent started.
todo.updated session durable A Todo call rewrote the session's todo list; carries the whole list.
tool.client.call session live A client-hosted tool call is being asked of the clients: run name and answer tools.client.result with callId/registrationId; ephemeral — the pending call lives on a deadline, not in the log.
tool.finished session durable A tool call finished (content capped; tool.output has the rest).
tool.progress session live Live tail of a running tool call, frame-rate capped; ephemeral — tool.finished is the contract, so a late joiner replays nothing and still sees the whole output.
tool.started session durable A tool call started.
turn.completed session durable A turn ended, with its stopReason.
turn.dequeued session durable A queued prompt left the queue (sent or removed).
turn.queued session durable A prompt was queued behind the running turn.
turn.started session durable A turn began.
turn.steered session durable A steering message was handed to the running turn.
turn.step session live The running turn reached a step boundary.
usage.updated session durable Token and cost usage changed.

Client-hosted tools. When server.clientTools is on, a Write-scope connection may announce tools that run inside the client itself: tools.client.register stores the set against the connection and answers its client__* names, the model is offered them from the next turn onward, and calling one announces the ephemeral tool.client.call event on the session's feed with callId, registrationId, name, arguments and deadlineAt. Any subscriber of that session whose registrationId still owns the name may run the tool and answer tools.client.result; the first accepted answer settles the call and the rest read accepted: false. Registrations die with the connection that made them, and an open call fails at once when its host connection drops. Off (the default), every tools.client.* call is refused with the client_tools_disabled kind.

Sending, queueing, steering, cancelling

session.send answers how the prompt was admitted; the prompt's own row arrives as the durable message.created. While a turn runs, delivery decides what a new prompt does:

  • queue (the default) waits behind the turn — admitted: "queued" with a queueId, and a turn.queued event; session.queue lists the queue and session.dequeue takes an entry out (turn.dequeued);
  • steer hands the text to the running turn at its next step — admitted: "steered" with a steerId, and a turn.steered event. It is also held in the queue, so it is never lost: if the turn ends before reading it, it goes out as the next turn; if the turn read it, it leaves the queue;
  • interrupt cancels the running turn and sends the prompt now.

Idle, a prompt starts a turn (admitted: "started", with its turnId), or is parked behind a hook or command file that runs in a child (admitted: "pending"). A prompt that resolves to a handled command — a slash command or a !bang run — answers admitted: "handled": the command never becomes a model turn, so the answer is an admission, not -32009; every row it saves arrives as message.created, and a !bang additionally brackets its run with session.status busy → idle. A prompt the session refuses — the spend cap, an empty command expansion — is -32009 refused with the reason. server.maxConcurrentTurns (4) caps the turns running at once across sessions: one more is refused busy (too_many_turns), which is retryable.

A send may additionally carry up to four pasted images (images) or two base64 PDFs (documents), each {name?, mime, data}. The declared mime is a claim — the handler re-sniffs the bytes and refuses a lie (image_mime_mismatch, document_mime_mismatch) rather than hand a provider a false media_type. An image is at most 5 MiB and the images together at most 10 MiB (image_budget_exceeded beyond that); images and documents then share one decoded budget of 11 MiB, and a larger sum is refused attachment_budget_exceeded. Attachments ride only a prompt that STARTS a turn: while one runs, the queue and steer lanes carry text, so attachments are refused by name (images_while_busy, documents_while_busy) — interrupt admits them into the turn it replaces — and a /command or !bang route, which would silently drop them, refuses instead (images_with_command, documents_with_command). Blast radius to know: an uploaded document re-enters the model context on EVERY later turn until the planned document-resend fix, so it stays billable for the session; a repository file is better mentioned as @path (page-capped), and documents larger than the wire budget keep that route.

session.cancel stops the running turn: mode: "hard" (the default) at once, the way Esc Esc does; mode: "soft" at the next step boundary, letting the tool in flight finish. clearQueue: true also drops the queue. session.status follows the session: idle, busy, waiting_permission.

A built-in slash command whose body lives on the host (Host\Commands — /clear, /rewind, /memory, /permissions, /workflow, …) runs on the server: command.list lists it with runsIn: "server", and command.exec answers the rows it appended to the transcript and the effects it applied. It is refused -32009 (command_refused, with the reason) while a turn holds the session, /workflow pause|status inside its own run and /btw excepted. The screen-only ones (/theme, /pane, the pickers) and those whose logic is still the TUI's are listed runsIn: "client" and refused -32030 (ui_only). A project's or your own command files (.candy-code/commands/) run on the server exactly as typing /name args would. A session's user-invocable skills are listed with source: "skill" and runsIn: "server": selecting one sends the typed /name args over session.send, and the host rewrites it into the $name mention the TUI's slash door would produce. A skill is never a command.exec target, and a row whose name admission would not dispatch — claimed by a built-in spelling or a command file, or holding characters the slash shape rejects — is not listed at all.

todo.get answers the session's todo list as its Todo tool last wrote it: {items: [{content, status}]}, empty when the agent has kept none.

Permissions over the wire

A question a turn's gate or hook asks is a durable permission.requested event: every client following the session sees it. Any client holding the approve scope may answer with permission.respond {sessionId, askId, reply: "once"|"always"|"reject", note?, cascade?, remember?}. The first valid answer wins; a later one is refused -32009 already_resolved, with the winning answer in data.resolved. The answer reaches exactly the call that was asked about — the askId is a hash of the call's id, tool and arguments.

  • always is remembered for the session, for every later turn, and also answers the session's other open questions that what it remembered covers (listed in the answer's cascaded) — the same scope as the TUI's a (PERMISSIONS.md): always on git status answers an open git status --short, never an open git push; a leading in-project cd <dir> && is a no-op there too, and a pipeline or chain is remembered one grant per part (Bash(npm test *), Bash(tail *)), so a later line made of the same commands — or of read-only ones — is covered whatever its shape. The event's alwaysScope carries what always would remember as pattern — one pattern, or a comma-separated list for a per-part grant — (absent when it is the exact call). A question that grant covers arriving later in the same turn is answered without being put. A question a hook asked, or a security finding under auto, is put every time and offers no always. Grants are saved with the session and come back when the session is opened again.
  • reject with cascade: true rejects every other open question of the session and stops the turn at its next step.
  • remember: "project" is refused — permission rules are user-tier only. remember: "user" (the card's Always (save)) answers always and additionally saves the question's patterns as allow-rules in your user config — the same set the TUI's p writes — reported back in the answer's saved notice; saved rules take effect at the next launch, and the gate permission.forget takes one back out. A relayed background question refuses it (remember_user_unavailable): its answer carries no grant to persist.
  • A question still open when its turn ends — cancelled, failed, or settled — is resolved cancelled.
  • server.askTimeoutSeconds refuses a question nobody answered in time. It is unset by default: a question waits for as long as the turn does.

A client that reconnects is handed every question still open (pendingAsks in its subscribe or resume answer), whatever its cursor, and permission.pending lists them for one session or all.

Every client also hears a question put in any open session, following it or not: the server-scope permission.asked carries the question and its sessionId, and permission.settled ({sessionId, askId, reply?, cancelled?}) its answer or cancellation — so a dashboard watching one session learns of a question in another the moment it is put. Each status change (idle, busy, waiting_permission) likewise reaches every client as a session.updated carrying the session's summary. See PERMISSIONS.md.

Sessions start in the server's permission mode (default unless the server was started with another); session.create and session.setMode may choose any mode except bypass-permissions and dont-ask, which are refused -32020 unless the server runs with --allow-bypass.

Following a session: subscribe, replay, resync

session.subscribe {sessionId, afterSeq?, mode?} follows a session:

  • with afterSeq the log can still serve, the answer is {fromSeq, throughSeq, pendingAsks}, then every durable event after afterSeq is sent in order (200 per loop turn), then the live stream;
  • with no afterSeq, or one the log can no longer serve (older than the oldest event kept — 20,000 per session — or ahead of the log), the answer is {reset: true, snapshot, throughSeq, pendingAsks}: the transcript rows, status, permission mode, queue, open questions and sub-agents, and the live stream follows from throughSeq.

The subscription is registered before the catch-up is read, so an event logged meanwhile is delivered once, after the catch-up, never twice and never missed. A client's cursor is the highest gap-free seq it holds; reconnecting, it passes resume: {sessionId: cursor} to server.hello (or subscribes again) and gets exactly what it missed. Across a server restart the seqs continue — the log is in the session database — and the new connectionId in hello tells the client to resubscribe. mode: "narration" sends no deltas, only an assistant.narration tail at most every 2 s plus every durable event — for tiles and background panes.

A client showing several sessions at once need not choose the mode per subscription: client.viewing {sessionIds, foreground, narrate: true} narrates every session it follows except the one in front (the answer lists them as narrated), and moving foreground switches them without resubscribing. A tail names the byte offset into the reply where it starts and holds only what streamed since the last tool call; a session brought to the front is handed its tail at once, and the deltas that follow continue at offset + the tail's length — no gap, no repeat.

Backpressure

Each connection has an outbox; a turn never waits on a client. The socket is handed only what it will take, and the rest waits in the outbox:

  • past 1 MiB waiting, queued deltas of one part are merged (lossless), and the client's subscriptions to every session but the one client.viewing names as in front drop to narration;
  • past 16 MiB, every waiting live event is dropped for one server.overflow event ({dropped, action: "resubscribe"}). Durable events are never dropped: if the outbox is still past 16 MiB ten seconds later, the socket is closed with 1013 and the client resubscribes from its cursor.

Settings over the wire

settings.schema describes every setting from the same schema the TUI editor and SETTINGS.md are built from — type, default, choices, help, when a change applies, the environment variable or flag that can lock it, sensitive, and writableRemotely with the reason when it is not — plus the tiers a save can target (your config, and a trusted project's settings.local.json and committed settings.json) and whether each can be written now. settings.get answers every key's effective value with its provenance — which layer won, from which file, which layers it shadows, and the environment or flag lock — and the files behind those layers (or one tier's file with scope: "user"|"project"|"project-shared"). A secret never travels: a secret-typed key, any key at any depth whose name says it is a credential (apiKey, token, Authorization…), and the userinfo of a URL read as "********".

settings.set (scope admin) writes only keys whose risk class is cosmetic, tuning or narrowing — never anything that runs a command, pulls files into prompts, spends money, grants trust, changes permissions or the server's own binding, holds a secret, or is owned by a live command (theme is /theme's, provider is /model's) — and only to your config (scope: "user") or a trusted project's local file ("project") or committed shared file ("project-shared", .candy-code/settings.json, whose preview notes that everyone who clones the repository and trusts it gets the values), through the same writer and refusals as the TUI editor. It takes one key (key + value, or key + reset) or a whole change set (set and unset), and writes all of it or none of it; a reset deletes the key rather than writing its default. settings.preview (also admin) answers what that save would do without writing: the target file, a unified diff of its JSON, when each change applies, what refuses it, and the precedence notes — that the value now overrides your settings.json, or that a higher layer still outranks the file. There is no "this session only" tier over the wire: in a server it would be state every hosted session shares.

The web UI's Settings page is generated from settings.schema: one form, grouped as the TUI editor groups it, each field badged with when it applies and showing where its value comes from. A field a client may not write, a field the environment or a flag locks, and — on either project tier — a key a project may not set are shown disabled with the reason. Changes are staged, previewed as a diff, and saved in one write; a reset is staged the same way.

Background sessions

The workspace's background (/bg) sessions are reachable over the wire too. bg.list lists them — running ones and the ones that have settled, so their answers stay reachable — and bg.output reads one's output from an offset. bg.spawn starts one on a task the way /bg does (scope write: it runs code, like session.send), as the agent you name or the one /bg would pick, in the served root; it answers once the daemon has authenticated its handshake. bg.stop stops one. bg.inject sends a settled session's report — its task, outcome, answer and stats, the same report the TUI hands its agent — into a session as a prompt, admitted like session.send (delivery included); the report's @path tokens stay text, because they are the background model's words, not a request to attach a file. A session that has not settled is refused bg_not_settled.

A spawned daemon runs in the server's mode. A bg.spawn — and the host-side /bg it mirrors — starts its daemon in this server's admitted permission mode rather than the background bypass-permissions default: the mode is named in the spawn config, and the daemon resolves its gate from it. Nobody sits at a daemon's keyboard, so what the mode would ask about is relayed to the server's clients (falling back to the no-terminal approver's refusal, recorded in the session's output, when no answer arrives in time), while what it allows — every read-only tool included — runs normally. A server admitted for bypass-permissions with --allow-bypass spawns bypass daemons; a bg.spawn request can name no mode of its own, so no call escalates past the launch. An ask inside a spawned daemon is relayed to the server's clients as a server-scope permission.asked named by the session's background id: answer it with permission.respond exactly as an open session's question. The answer travels on a minted channel: at spawn the server mints a nonce-named answer path (session.answer-<128-bit hex>), pre-creates it 0600, and carries its name into the daemon's config and the index record — the relay only ever opens that one path, and a record whose answer path was never minted is refused, so content forged at any other name is ignored. One compatibility path stays open by design: a spawn that predates the minted-answer protocol — an older daemon adopted across a server upgrade, whose index record carries no answerPath at all — falls back on both sides to the legacy fixed <session>.answer path (BackgroundSessionRunner::withPermissionRelay and BackgroundSupervisor::permissionAskChannel), whose name is derivable from the buffer path and so readable in same-uid process arguments; that is the exposure the minted nonce removes, and every spawn from a minting server carries the nonce. Every asking carries a per-ask token, and an answer row settles only the asking whose askId and token it echoes; a stale line from a respawned call cannot resolve a fresh question. The question waits for an answer as long as server.askTimeoutSeconds says (0, the default, forever); with no client to answer in time the daemon settles its own ask and falls back to the no-terminal refusal above, recorded in its output unchanged — the server turns those settle lines into cancelled permission.settled events, so a timed-out ask leaves permission.pending, and an answer arriving after it reports unknown. Relayed asks are offered once or reject only — always is coerced to once before anything is written, so the row, the settled event and the respond result all carry once (remember: "session" included) — and cascade on a reject is refused cascade_unavailable because a relayed session holds no siblings to stop. A restarted server reads the answer record back on first sight of an ask: a question answered under the earlier server is neither re-announced nor double-answered. A local /bg from a terminal has no server to relay through and keeps the plain refusal.

A starting server re-adopts what an earlier one left. A background daemon outlives whatever started it, so on start the server adopts the daemons an earlier server — or a TUI of the same project — left running for its root, exactly as a relaunched TUI does; one whose owner is still running stays that owner's. From then on it polls them every 2 s and broadcasts what moved, as server-scope events: bg.started when one starts or is re-adopted (adopted: true), bg.status when one's status changes, and bg.completed when one settles, after which bg.output reads its answer and bg.inject delivers it. A daemon that finished while no server was running is reported on the first poll. A client that connects later reads bg.list.

Sub-agents, workflows, memory and todos

Delegated runs. Every run a Task call starts announces itself on the session's subagent.* events — started and finished durable, progress live — each carrying the run's latest beat: its id, agent name, the parent Task call (parentCallId) and, when nested, the delegating run (parentAgentId), its step, tokens, cost, recent tool calls and, once finished, its outcome, error and resumeId. agents.subtree folds them into one row per run — from the session's event log as well as what the server heard live, so runs that finished before this server started are still there; the task and description only started names survive the later beats. agents.transcript reads a run's own transcript (the log the TUI's Agent View tails) a page at a time from a byte offset, whole lines only, every string scrubbed of terminal escapes and control bytes.

Talking to a run. agents.message puts a line from you into a running run's mailbox, signed with the server's launch key, which the run reads at its next step boundary — the TUI Agent View composer's route. agents.control asks it to cancel, pause or resume the same way, or — the Agent View's Ctrl+X b — to background itself: the run is promoted to a background session and keeps going there, off this turn. A run that has finished has nobody left to read a mailbox: a message (or resume) continues it instead, as a follow-up of the same conversation under the same preset (it needs the engine backend and a run that kept a resumeId), and its beats arrive as the session's subagent.* events. A run the session never delegated is agent_not_found; one finished run that cannot be continued is not_resumable; cancel/pause/background on a finished one is agent_finished, and background on a nested run (one another run delegated) is agent_nested.

Workflows. workflow.list names the workflows /workflow run can start (available: false when the workspace has no engine). workflow.run ({sessionId, name, vars}) and workflow.resume run exactly as typing the command does: the run occupies the session's turn, its sub-agents show live, and its report lands as the turn's reply; a turn already running refuses it (command_refused). Because /workflow run splits its arguments on whitespace, each vars value is a single word. workflow.pause and workflow.status answer at once, mid-run too. workflow.runs lists the runs the session's transcript holds — the /workflow reports and the model's own Workflow tool calls, the latter while they run.

Memory and todos. memory.list|search|add|edit|delete are /memory over the wire, per scope (user, project, agent). todo.get answers the session's todo list as its Todo tool last wrote it, and every Todo call that changes the list is broadcast as the durable todo.updated (the whole list), so a client follows it live and a reconnecting one replays it.

Settled-turn memory and commit work. When a served turn ends in a reply and nothing queued takes its place, the session runs the same settle work the TUI does): auto-memory consolidation, the turn-mode auto-commit and the dream pass, each under the session's own notice sink, each billed to the session's spend total and followed by its producer's display-only notice row in the session's transcript (Auto-memory saved …, Auto-committed …, Dream pass …); a run that changed nothing says nothing. The throttles are the same on-disk files the TUI claims, so a project pays at most one five-minute auto-memory budget and one two-hour dream budget across every process serving it. The next-prompt suggestion is deliberately not run on serve — a session over the wire has no input box to show a ghost prompt in.

Web Push (push.*)

A browser that closes its tab stops hearing about the session — unless it registers a push subscription first. Three methods cover the lifecycle (the transport behind them is the web-push core: RFC 8291 aes128gcm encryption, RFC 8292 VAPID, allowlisted dialing):

  • push.vapidKey (read) answers the server's VAPID public key — the value PushManager.subscribe() takes as applicationServerKey. The pair is minted once into the state dir at 0600 (vapid.key); the private half never leaves the process.
  • push.subscribe (write) stores {endpoint, keys} — and refuses, before storing, any endpoint outside the push-service allowlist (FCM, Mozilla, Apple, Microsoft hosts). The row lives in push.json in the same 0600 state dir, keyed by sha256(endpoint) and owned by the caller's principal class; name: true opts that row into carrying the session title.
  • push.unsubscribe (write) drops the row for an endpoint, and only when the caller's principal class owns it.
  • A token rotation (serve token --rotate) signs every credential class out and drops the push rows those classes owned, so rotations never accumulate rows for clients that can no longer sign in.
  • Revoking one viewer grant, a grant expiring, a browser signing out, or its sign-in expiring drops only the push rows that one credential subscribed (a row records a digest of the grant id or session id, never the credential); the owner's and every other viewer's rows stay.

Triggers: a question waiting for an answer and a finished turn each send one notification — and only while no client is following that session, the rule being that push answers absence, never redundancy. Payloads are redacted generic text by default: {"kind": "question"|"finished", "body": "A question is waiting", "sessionId": "…"}, encrypted end-to-end so the push service ferries opaque bytes. The session title rides only for opted-in rows. A push service that reports the subscription gone (404/410) drops the row server-side; the browser re-subscribes if it still cares. Sends never block the serve loop: the sender resolves on the loop, and a failed delivery costs only a log line.

More than one project root (workspace hosts)

A server serves the root it was started on; its sessions, settings, trust answers, hooks, skills and MCP servers are that root's. That is not a policy but a property of the process: Cli\Bootstrap keeps a launch's root in process statics (the project the settings layers read, the frozen trust lists, the MCP clients started once per launch). So a second root runs in a process of its own — a workspace host — and the gateway (Server\Workspace\Gateway) in front of the protocol routes to it:

  • Its own methods. workspace.list → {items: [{root, primary, running, pid}]}; workspace.open {root} starts that root's host (or finds it running); workspace.close {root, force?} stops it, refused (-32010, turn_running) while one of its turns runs unless force. The server's own root is primary and closes only with the server. A root that is not a directory is -32004 root_not_found; at most eight hosts run at once (too_many_workspaces).
  • Routing. A request whose params name another root goes to that root's host — session.create {root}, session.list {root} — and so does any request naming a sessionId a host answered for. Everything else is the server's own. The root param is the gateway's; the hosts never see it. Answers and events relayed from a host carry root.
  • Following a session works as on the server's own root: the gateway is the host's one client and fans its events out to the clients that subscribed through it, keeping a cursor per client, so a second subscriber's replay never reaches the first twice. The last one to leave unsubscribes upstream.
  • A host that dies (crash, kill, lost socket) is announced to every client following one of its sessions as server.overflow {sessionId, dropped: 0, action: "resubscribe"}; resubscribing starts a fresh host, which opens the session from its store. A host that nobody follows and that runs no turn is stopped after 15 minutes idle, which bounds a long-running PHP process's memory.
  • A host that wedges (alive, never answering) cannot park a call forever: every forwarded call has a 300-second deadline, after which the client gets the retryable busy error (kind: "host_timeout") and the call stops counting as in flight, so the idle recycle can reap the host.

The host is spawned the way /bg spawns a session daemon: an argv (php -r with the entry point, nothing secret on it), in its own process group, with the root, a per-spawn token and the server's session settings (permission mode, --allow-bypass, the session and turn caps, the question timeout) on its stdin. The gateway binds a UNIX listener in <state dir>/workspaces (0700) only after the spawn, so no child inherits it; the child connects back and must send the token first, and from then on the socket carries the same candy-code.v1 JSON-RPC, WebSocket-framed. The child stops when its stdin closes — the gateway let go, or died — and is otherwise reaped with the usual TERM-then-KILL ladder over its group, its turns with it. Its output goes to <state dir>/workspaces/workspace-<hash>.log.

Choosing a new session's directory (--allow-dir-browse)

Off by default. With --allow-dir-browse (or server.dirBrowse: true) a client can pick the project root a new session starts in, anywhere under the browse root (--browse-root, default your home directory):

candy-code serve --allow-dir-browse --browse-root ~/src
  • fs.listDirs {path?, showHidden?} (scope read) lists one directory: {root, path, parent, entries: [{name, path, project, readable}], truncated, readable, project}. path is absolute, ~-relative or relative to the browse root (omitted: the root itself); parent is null at the root. Entries are child directories only — never a file name, a size or a file's content — sorted, at most 1000 (truncated says when more were there); dot-directories only with showHidden: true; project marks one holding .git, composer.json, package.json or .candy-code. A directory this process cannot read is reported (readable: false), not an error.
  • Containment. Every path is resolved (.. collapsed, links followed) and must stay inside the browse root: anything else is -32003 outside_browse_root — the same answer whether or not the path exists — and a link inside the root that points out of it is simply not listed. A missing directory is -32004 dir_not_found.
  • Starting the session. The client opens the picked root with workspace.open {root, browse: true} — which re-checks that browsing is on and the root is inside the browse root, rather than trusting the client — then session.create {root}. Picking the server's own root is the primary workspace, so the session is the server's own; any other root runs in a workspace host like any other (the eight-host cap applies).
  • Off, both fs.listDirs and workspace.open {browse: true} answer -32003 dir_browse_disabled ("start serve with --allow-dir-browse"), features.dirBrowse.enabled is false, and the web UI's "New session" starts a session on the server's own root as before.

What it exposes: every signed-in client can see the names of the directories under the browse root (not files, not contents) and start an agent session — which can then read and run things — in any of them. That is why it is opt-in and rooted: set --browse-root to the directory that holds your projects rather than leaving it at your whole home directory. candy-code attach does not use it; the TUI has its own /new picker.

Attaching a terminal (candy-code attach)

candy-code attach                      # a new session on the running server
candy-code attach 3fa9                 # an existing one: id, name or unique id prefix
candy-code attach --url http://127.0.0.1:7420 my-session

attach runs the usual full-screen TUI as one more client of a running server, over the same candy-code.v1 WebSocket the web UI uses. It finds the server through the discovery record serve keeps in its state directory (the one serve status reads; --url names another), authenticates as a bearer client with the owner token (CANDY_CODE_SERVER_TOKEN, else the state directory's token file — read, never created), says server.hello, and follows one session: session.create without an argument, else the session whose id or name is the argument, or whose id starts with it (resolved with session.list on the server). It subscribes from a snapshot, so the transcript on screen is the server's.

What runs where:

  • Turns run on the server. Enter is session.send; the reply streams back from the session's events (assistant.delta, reasoning.delta), tool rows from tool.started / tool.finished, the status bar's step and bill from turn.step / usage.updated. Tools run in the server's root under the session's permission mode, not this terminal's.
  • Its questions come up here. A permission.requested for the turn opens the usual approval modal; the answer is permission.respond, and an answer given first by another client (a browser on the same session) takes the modal down as permission.resolved arrives.
  • Esc Esc is a hard session.cancel of that turn (or takes the prompt out of the queue while it still waits there); a soft cancel is a soft one. A steer typed mid-turn is sent as the next prompt.
  • Nothing is saved locally. The server holds the session's single-writer lock and writes its transcript; the attached window neither takes the lock nor writes the session store, and makes no local title call (the server titles its own sessions; a one-shot completion sent through the attachment is refused).
  • Quitting detaches. A turn still running goes on, its events in the session's log for whoever subscribes next.

A dropped socket is not the end of the attachment. The window redials with exponential backoff — first after 0.25 s, each wait doubling up to 4 s, twelve attempts in all — and re-says server.hello with resume: {sessionId: cursor}; the server re-subscribes it and replays whatever the dark missed, or resets it from a paged snapshot when the log can no longer serve the cursor. A turn running while nobody listens lands in the log and is replayed on resume, exactly as a live stream would have been. The verdict stays final only for a deliberate close, a resume the server outright refuses (the session deleted, or locked to another process), and an exhausted ladder — the session the socket died for is what the redial aims to return to.

The other way round: a plain candy-code --resume <id> (or -c) whose session the server holds opens it read-only, as for any other holder, and the notice names the server and the candy-code attach <id> that would drive it instead.

attach exits 1 when it ran and could not attach — no server running, no token, the upgrade refused, no such session — saying why on stderr, and 2 for a usage error (an extra operand, a flag other than --url, a --url that is not an http(s):// or ws(s):// address, --output-format json).

An attached window routes slash commands the server owns: a name whose command.list row says runsIn: "server" (/compact, /clear) executes on the server's own copy through command.exec, and its reply rows land in the window the way a locally-run host command's do. Screen-only commands (/theme, /keys, /help) still run here, on the window's copy. An effect replays on the window only where the wire carries it (clear-transcript, open-title-editor); payload-carrying effects applied to the server's copy arrive back with the next snapshot or resume. And a turn another client starts on the same session no longer waits for the window to re-attach: the window follows it live through the event feed, keyed by turnId, so a foreign turn's deltas fold into the window's history when it completes and never interleave with a turn this window itself queued.

A served session can also teleport work outward. /handoff --remote <url> exports its transcript over session.import to another serve and prints the candy-code attach <new-id> --url <url> line that drives it there, leaving the local session untouched; the token is the one attach reads (see docs/COMMANDS.md). The upgrade is refused before any socket opens unless the target is loopback ws:// or TLS wss://.

Editors (candy-code acp)

candy-code acp makes candy-code an Agent Client Protocol agent: an editor that hosts agents over stdio — Zed, JetBrains IDEs, Neovim through an ACP plugin — starts it as a child process and speaks newline-delimited JSON-RPC 2.0 on its stdin and stdout. It needs no server, port or token: the editor is the client. In Zed, for example:

{
  "agent_servers": {
    "CandyCode": { "command": "candy-code", "args": ["acp"] }
  }
}

Every session runs through the same Host\SessionHub and SessionHost as serve's, on the same ReactPHP loop, so a turn the editor starts is the turn the TUI would run: same provider, tools, hooks, permission gate, transcript and session store (an acp session shows up in session list and can be reopened in the TUI with --resume).

ACP candy-code
initialize protocol version 1; loadSession: true; promptCapabilities.embeddedContext: true; no auth methods
authenticate accepted, nothing to do — the editor started this process as its own user
session/new {cwd} a new session in cwd — the project root. The first session fixes the root for the process; a session naming another directory is refused (start another candy-code acp). mcpServers is not used: the project's own .mcp.json applies, under its trust gate
session/load {sessionId, cwd} the stored session is opened (taking its lock, as --resume would) and its transcript replayed as session/updates — what was typed, said and thought, and each tool call with its outcome — before the answer
session/prompt the prompt is submitted to the session; answered with stopReason once the session is idle again
session/cancel the turn is cancelled at once — its child stopped, its running tool rows marked interrupted, its open permission questions settled — and the prompt answered cancelled
session/set_mode {modeId} the session's permission mode for its next turns; session/new and session/load advertise the six modes (default, accept-edits, plan, auto, dont-ask, bypass-permissions) with the one in force
session/update (agent → editor) agent_message_chunk ← assistant.delta, agent_thought_chunk ← reasoning.delta, tool_call ← tool.started, tool_call_update ← tool.finished (an edit's change as {type: "diff", path, oldText, newText}, one per changed region), plan ← todo.updated
session/request_permission (agent → editor) every permission question a turn asks; see below

Prompts. Text blocks are sent as written. A linked file (resource_link) becomes an @path mention, resolved and attached as a typed one is; an embedded resource — an editor's unsaved buffer — is sent as a <file path> block carrying the editor's text. A built-in slash command runs as it does over serve, its output sent back as message chunks; one only a screen can run (/help, say) is answered with a refusal saying so.

Stop reasons. end_turn, max_tokens (the provider's length stop), max_turn_requests (the step budget, the spend cap, or the loop guard — the web projector still names that row loop_guard; the ACP wire has no own value for it), cancelled, and refusal for a prompt the session would not take (the spend cap reached, an empty prompt) — its reason is sent as a message chunk first. A turn that fails answers the prompt with a JSON-RPC error carrying the failure.

Permissions. A question becomes a session/request_permission request naming the tool call (its title, kind, file locations and arguments) with one option per answer the question offers: allow_once, allow_always (only when the permission gate alone asked — as in the TUI, an always is remembered for the rest of the session) and reject_once. A cancelled outcome, an error answer or an option the question did not offer all reject. Nothing blocks while a question is open: the turn's child waits on its own channel and every other message is still read. Sessions start in the permission mode the launch resolves (--permission-mode, CANDY_CODE_PERMISSION_MODE, the permissionMode key), else default, so writes and shell commands ask.

Ids are echoed exactly. ACP clients send integer ids and JSON-RPC requires a response to carry the id as sent, so every message is read with McpMessage::parsePreservingId() (decision D12; MCP's own traffic is unchanged).

Stdout is the protocol and nothing else. Anything PHP would print is redirected to stderr, which an editor shows as the agent's log; launch warnings go there too. Closing stdin — the editor quitting or dropping the agent — closes every session (a running turn is cancelled, its lock released) and exits 0; so do SIGINT and SIGTERM. acp exits 2 for an operand or --output-format json.

Diffs. An Edit or Write result carries a unified diff (ToolResult::$diff); ToolResult::diffTextsOf() turns each of its hunks into the before and after text of that region, which is what an ACP diff holds — so an editor shows the change in its own diff view. A region that created the file has a null oldText.

What acp does not use: the editor's fs/* and terminal/* methods (the agent's own tools read and write the project, behind its own permission gate and checkpoints), image and audio prompt blocks, and the unstable session/list, session/resume and config-option methods.

Web UI

Feature-level detail of the page is owned by the candy-code-web README; this chapter is the shape and the trust story.

The browser UI is the candy-code-web package: a pre-built Vue bundle that serve hands out on the same port as the API and the WebSocket, so there is nothing else to run. The server looks for it in this order and names what it found on the web UI: startup line:

  1. --web-root <dir> (or CANDY_CODE_SERVER_WEB_ROOT);
  2. the installed package (composer require sugarcraft/candy-code-web; it is a suggest, not a dependency, so headless installs stay lean) — a composer-channel leg only: a packaged phar freezes the archive's own vendor as its single autoload root, so on the phar channel the web UI arrives through --web-root or not at all;
  3. neither: API and WebSocket only (also what --no-web asks for).

Open the sign-in URL and the page signs in, connects and shows:

  • New session (sidebar, dashboard, grid, palette): on a server started with --allow-dir-browse it opens a folder picker first — the current path as a breadcrumb, Up to the parent (disabled at the browse root), the child directories with a project badge, a "show hidden" toggle, a path box to type or paste into, and Start session here; keyboard-driven (arrows, Enter to open, Backspace for up, Esc to cancel). Without it, New session starts one on the server's own root at once.
  • Sessions in a sidebar — newest activity first, a filter, a status dot, and a count of the questions each one is waiting on (also in the tab title, and as an opt-in desktop notification — for a question, or a turn that finished — when that session is not on screen).
  • The transcript of the open session, virtualised so a long session scrolls like a short one: your prompts, the replies as Markdown streaming in (sanitised — neither a reply nor a file a tool read can put markup or script on the page; fenced code is coloured by a small highlighter fetched the first time one appears), the model's reasoning in a fold, and a card per tool call — name, key argument, duration and outcome, collapsed once it succeeded; open, it shows the arguments, the output (in full on request when the event was capped) and an edit's diff with line numbers. A refused call is marked with its reason.
  • Permission questions as cards with Allow once, Always (this session), Always (save), Reject and Reject & stop — y / a / n on a focused card answer once, always-for-this-session and reject; Always (save), the one answer that writes a durable grant into your config, is deliberately two-step, and it earns no one-key shortcut: the first press arms an inline confirmation naming exactly what will be saved, the second answers. And a note field: its text goes with a rejection as feedback the agent reads, and — on a question the agent asked itself (AskUser, PlanExit) — with Allow once too, as your answer in your own words. Every tab and client following the session shows the same question; the first answer wins and closes it everywhere.
  • The composer: Enter sends, Shift+Enter is a new line. While a turn runs, the option offered first is the server's own queueMode — announced as server.hello's defaults.delivery, steer unless configured otherwise, exactly as the terminal UI's Enter behaves mid-turn; queuing the prompt or interrupting the turn stay one choice away. The queue is listed above the box, each entry removable. Stop (or Esc Esc) cancels the turn. / completes the slash commands that run here: a built-in the server runs goes through command.exec, a command file is sent as a prompt, and a screen-only built-in says it runs only in the terminal UI.
  • A status bar: what the session is doing (and the step), context used, spend, the model, and the permission mode — changeable from there.
  • Tabs and a grid for watching several sessions at once. Every session opened stays a tab — picked by the configurable tab chord on the physical digit key (Alt+1…9 by default; the tabs: Alt+1 button in the tab strip cycles the modifier to Alt+Shift or Ctrl+Alt, and because the match is on the digit key.code, macOS Option glyphs and AZERTY layouts no longer matter) — with its status and open questions; the grid tiles the open tabs, up to 3×3, each live with its status, step and spend, the last few events, its questions and a line to prompt or steer it. The focused tile streams; the others are narrated (client.viewing with narrate) and catch up at once when focused.
  • An approvals drawer with every question open in any session of the server, answerable in place. It hears a question the moment it is put (permission.asked), whether or not the page follows that session.
  • Panels beside the session (the panels button, or a panel's name in the palette): the PANELS registry holds twelve, and the candy-code-web README documents each one in full; five are worth naming here. Agents — the tree of the runs the session delegated, live, nested under the run or Task call that started them, each opening into an agent view with the run's own transcript, a box to message it and pause, resume and cancel; the same tree hangs under each Task card in the transcript. Todo — the session's todo list, as the agent keeps it. Background — the workspace's /bg sessions with their status and output, started, stopped or sent into the session from there. Workflows — the workflows to run (with key=value context) and the session's runs, /workflow and Workflow tool alike, pausable while they run. Memory — the notes of each scope, searchable, to add, edit or delete. The other seven are Rules (the policy: grants made this session, and saved rules), Catalog (the agents the session can delegate to), Changes (the working tree's diff), Files (a workspace file browser), Context (what fills the model's context), Generate (the session's images) and Usage (tokens and spend).
  • A command palette (Ctrl+K / ⌘K): jump to a session, run or start a slash command, open a panel, start a session, change the theme.

The page keeps one WebSocket. When it drops, the page retries — after 0.5 s, then doubling to at most 15 s, each wait jittered, six tries in all — with a fresh ticket, and resumes every session it follows from the last event it holds, so nothing that happened meanwhile is missed or shown twice; while the ladder holds, a reload is never needed. When it runs out, the tab says the server is gone and offers Try again, which spends a fresh ladder (the candy-code-web README has the banner's words). A restarted server keeps signed-in browsers signed in (sign-in rows persist, hash-only) and the page resumes where it left off; rotating the owner token is what sends it back to the login prompt. A server that comes back as a different version offers a reload.

Developing the UI (candy-code-web/, Node 24): npm run dev serves it from Vite with hot reload and proxies /ws and /api to 127.0.0.1:7420; start that server with --allowed-origin http://localhost:5173 so it accepts the dev page's origin. The end-to-end suite (npm run e2e) drives the built UI in Chromium against a real serve on the offline echo provider. With no model, a prompt whose lines read ::tool <Name> <json-object> makes the echo provider call that tool — through the permission gate like a model's call — and then report what it returned:

::tool Write {"file_path": "notes.txt", "content": "alpha\nbeta\n"}

Security model

  • Loopback by default. 127.0.0.1 only; any other bind needs --allow-remote and gets a warning box.
  • Client address allow-list (opt-in). With --allowed-ips / server.allowedIps set, a client whose address is not listed (loopback is always admitted) is refused 403 ip_refused first — before the Host and Origin checks, the sign-in code and any credential.
  • Host check (DNS rebinding). Only 127.0.0.1, localhost, [::1] (any port), the bind address itself when it is not loopback, and server.allowedHosts are answered; anything else is 421.
  • Origin check (cross-site WebSocket hijacking, CSRF). On every upgrade and every non-GET request a present Origin must be the server's own (http:// or https:// plus the validated Host) or in server.allowedOrigins; anything else — null included — is 403. A missing Origin is allowed only with the bearer token or the token subprotocol: the cookie and a ticket, the two credentials a browser carries by itself, are refused without one. A cookie is also refused on Sec-Fetch-Site: cross-site.
  • No CORS. The UI is same-origin; every response carries X-Content-Type-Options: nosniff, X-Frame-Options: DENY, Referrer-Policy: no-referrer and a default-src 'self' content security policy.
  • Directory browsing (opt-in). --allow-dir-browse shows signed-in clients directory names — never files — under --browse-root, and lets them start sessions there; off by default (Choosing a new session's directory).
  • Logs record the method, path and status of each request and WebSocket open/close — never a query string (a ticket rides there), a header, a body or a prompt.
  • Permission modes. Server sessions start in default (they ask), as the TUI does — not in the bypass-permissions that /bg daemons keep. A background (/bg) daemon a client or the host path spawns from this server inherits the server's admitted mode rather than the background-surface default: its asks reach no keyboard, so the no-terminal approver refuses them (read-only tools stay auto-allowed); a local TUI's /bg is not a server spawn and keeps the documented background (bypass-permissions) default. bypass-permissions and dont-ask are refused — at startup and over the wire (-32020) — unless --allow-bypass / server.allowBypass.
  • Process hardening. Refuses root without --allow-root; runs under umask 077; the request body is capped at 64 KiB and 32 requests may be in flight at once; JSON is decoded with a depth limit of 64.

Why pcntl, posix and FFI

Every turn runs in a pcntl_fork() child. Without pcntl the engine falls back to running the turn on the loop itself, which on a server would stall every session and every socket for the length of the turn — so serve refuses instead.

A forked child inherits every descriptor the server holds: the listening socket and every browser connection. Held there, the listener keeps the port bound after the server closes it (a restart fails with "Address already in use") and keeps accepting connections into a backlog nobody reads, so a client of a stopped server hangs instead of being refused. So the server registers its listener and each accepted socket, and the first thing a turn child does is close exactly those with libc close(2) through FFI — PHP has no close-by-number. It closes nothing else: the child legitimately uses inherited pipes (stdio MCP servers) and provider sockets. The listener and every accepted socket are also marked close-on-exec, so no tool process ever inherits them. Without FFI there is no way to do this, and the leak would be silent — hence the refusal.

Remote access

The server can speak TLS itself (--tls-cert + --tls-key); beside that there are three ways to reach it from another machine, safest first.

One invariant holds on every bind, loopback or not: credentials are always mandatory — the token store gates every request surface, and --allow-remote only widens who may knock, never opens an unauthenticated mode. A future loopback-implicit convenience must not break that; nothing today does.

An SSH tunnel — nothing new listens on the network. Keep the default loopback bind and forward the port from the machine with the browser:

ssh -N -L 7420:127.0.0.1:7420 me@server   # then open the sign-in URL as printed

The printed http://127.0.0.1:7420/#code=… works unchanged on the far end, because the tunnel delivers it to the server's loopback address.

A TLS reverse proxy — below. The server stays on loopback; the proxy's public name goes in server.allowedHosts (or --allowed-host).

A direct bind — --host 0.0.0.0 --allow-remote (or ::, or one interface address), plain or with the server's own TLS:

candy-code serve --host 0.0.0.0 --allow-remote \
    --tls-cert /etc/ssl/candy-code.pem --tls-key /etc/ssl/candy-code.key

Without --tls-cert/--tls-key everything — the token, the sign-in code and the session cookie included — then crosses the network in cleartext, and the startup lines say so; with the pair the listener wraps itself in TLS, the sign-in URLs read https://, and the warning branches to the over-TLS wording instead of retiring (reachability still invites the whole network to knock, and an empty --allowed-ips roster is said out loud). A plaintext http:// client against the TLS endpoint gets no answer at all.

candy-code serve --host 0.0.0.0 --allow-remote
candy-code serve: listening on http://0.0.0.0:7420 (pid 4242)
  …
  sign in:         http://192.0.2.10:7420/#code=3f9c…
                   (one-time code, valid 120 s; Ctrl+C stops the server)

  !! Plain HTTP on 0.0.0.0: the token, sign-in code and session cookie cross the network in cleartext — use an SSH tunnel or a TLS reverse proxy (docs/SERVER.md, "Remote access").
     No --allowed-ips set: any address that can route here may attempt sign-in.

On a wildcard bind the server reads this machine's interface addresses once at start (loopback and link-local left out; IPv4 only on 0.0.0.0) and answers to each of them, and the sign-in URL — at start and from serve url — names each one, one per line, all sharing one code. These are literal IPs of this host, so answering to them reopens nothing: a DNS-rebinding page reaches the port under its own host name, never under one of this machine's addresses. A bind to one interface address answers to that address. Any other name — a DNS name for this machine, an address added after start — is refused with 421 until it is allowed:

{"error":{"kind":"host_refused","message":"this server does not answer to host `dev.example.com`; start it with --allowed-host dev.example.com or add it to server.allowedHosts"}}

The server log names the refused host the same way. --allowed-host (or CANDY_CODE_SERVER_ALLOWED_HOSTS, or server.allowedHosts) takes a host name, which matches on any port, or a host:port, which pins the port.

Limiting who may connect (--allowed-ips)

A direct bind answers anyone who can reach the port — they still need the sign-in code or the token, but they can try. --allowed-ips narrows that to the addresses you name:

candy-code serve --host 0.0.0.0 --allow-remote --allowed-ips 203.0.113.7,10.0.0.0/8

It takes single IPv4 or IPv6 addresses and CIDR ranges, comma-separated; repeats accumulate, and CANDY_CODE_SERVER_ALLOWED_IPS or the user-config key server.allowedIps (a JSON list) say the same when the flag is absent (the highest source that is set wins outright). An entry that is neither an address nor a range is refused at startup, exit 2. An IPv4-mapped IPv6 address (::ffff:203.0.113.7, what a dual-stack :: bind reports for an IPv4 client) counts as the IPv4 address it carries, on either side.

  • Loopback is always allowed (127.0.0.0/8, ::1), so serve url, candy-code attach and a reverse proxy on this machine keep working.
  • The client is the TCP peer — unless that peer is one of server.trustedProxies, in which case it is the forwarded X-Forwarded-For client the server already believes for rate limiting. Behind a trusted proxy the list therefore filters the real clients, and a proxied request is not admitted merely because the proxy is on loopback.
  • A refusal comes first — before the Host check, the sign-in code and any credential — for HTTP requests and WebSocket upgrades alike:
HTTP/1.1 403 Forbidden
{"error":{"kind":"ip_refused","message":"this server does not accept connections from 198.51.100.4; start it with --allowed-ips 198.51.100.4 or add it to server.allowedIps"}}

The server log records refused client 198.51.100.4: not in --allowed-ips / server.allowedIps, and the startup lines list the admitted ranges. Unset (the default) there is no address filter at all. The list is a filter, not encryption: over plain HTTP the traffic of an admitted client is still cleartext.

Behind a reverse proxy (TLS)

To reach the server from another machine over TLS, keep it on loopback and put a TLS proxy in front of it — Caddy, nginx or tailscale serve. With nginx:

location / {
    proxy_pass http://127.0.0.1:7420;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    # A turn can legitimately run for many minutes: never cut a quiet socket.
    proxy_read_timeout 3600s;
}

Mount at the host's root, as sketched. The server has no base-path setting: it matches /ws exactly and /api/ by prefix, and the links it mints are root-absolute — a canvas view answers with a /canvas/<id> URL, and sign-in URLs ride the root too. The built page resolves its own API and WebSocket URLs against the document base, so a proxy that strips a prefix can carry the page's assets; but server-minted links land at the host root regardless. If a sub-path mount is unavoidable, the proxy must also pass /ws, /api/* and /canvas/* un-renamed at the root, or those links break. A true base-path install is not supported server-side.

/ws?ticket=… carries its ticket in the query string, so a proxy access log for that location records it — sign-in codes and share URLs ride query strings the same way. Tickets are single-use and expire in 30 s and the codes are single-use, but the log is still the loosest copy of them: prefer access_log off; for the /ws location, or account for the exposure when choosing where logs go.

and in ~/.candy-code/config.json:

{
    "server.allowedHosts": ["agent.example.com"],
    "server.trustedProxies": ["127.0.0.1"]
}

server.trustedProxies is what lets the server believe the proxy's X-Forwarded-Proto: https (so the cookie gets Secure) and its X-Forwarded-For (so the rate limiter keys on the real client). The browser's origin is then https://agent.example.com, which matches the server's own origin through the forwarded Host and needs no --allowed-origin.

Windows

serve needs pcntl and posix, which Windows PHP does not have; it refuses to start there. WSL works. A Windows-native candy-code is experimental in a narrow sense: the chat/TUI — including the interactive tools over a real ConPTY allocation — is exercised by a dedicated Windows smoke job in CI, while serve itself stays out of scope there because its fork machinery has no Windows PHP to run on. Run the server under WSL (or a container).

Container

A ready-made serve image is published from this repository (ghcr.io/detain/sugarcraft-candy-code:latest, built by .github/workflows/candy-code-image.yml from candy-code/Dockerfile as a workflow_run after the split sync completes a successful push to master; see the registry-status note in DOCKER.md — the image is live since the first green run (39525070215) after the unzip + ext-gd build fixes, and every build records the resolved package reference in /opt/candy-code/BUILD-REF so a lagging packagist feed is visible — the recorded ref is the sugarcraft/candy-code-web package's (a sibling of the same split-synced stream), so a package-side-only lag stays outside what the row proves). It runs unprivileged as candy with HOME=/data — the serve preflight's refusal to run as root is honoured, not bypassed (--allow-root is never passed) — so all server state (sessions, token, discovery record, control socket) lives on the /data volume under ~/.candy-code/server. The default command is serve --host 0.0.0.0 --allow-remote and a HEALTHCHECK probes GET /api/health on the default port 7420. The sign-in URL still prints to stderr at startup; read it with docker logs. Full runbook: DOCKER.md.

See also