Server
crystal server serves a Crystal Code session over HTTP. Start it in your workspace and connect from the recommended Crystal Code Web browser front end or a compatible client. To serve the page and session API from the same process, use Web mode.
One process hosts one session. /clear, /resume, /fork, /cd, and /space replace or move that session inside the process, as in the terminal. A front end that wants several sessions starts several processes.
The endpoints, events, snapshot, and interactions are in Server protocol. This page covers starting, securing, and stopping the process.
cd your-repocrystal serverTo connect the hosted front end, start the server with crystal server --allow-origin https://web.crystalcode.ink, then enter the printed address and token in the browser. See the browser walkthrough for connection and troubleshooting steps.
Command line
Section titled “Command line”crystal server [session launch options] [-w|--workspace <PATH>] [-r|--resume [TARGET]] [--listen <HOST:PORT>] [--socket <PATH>] [--api-base <PATH>] [--tls-cert <PATH> --tls-key <PATH>] [--auth token|none] [--token-file <PATH>] [--token-stdin] [--allow-host <HOST>]... [--allow-origin <ORIGIN>]... [--expose-header <NAME>]... [--allow-private-network] [--exit-on-stdin-close]| Option | Meaning |
|---|---|
| Session launch options | The set crystal accepts. They shape this process only and are not written to config.json or prompt.json |
--listen <host:port> |
Default 127.0.0.1:0; port 0 picks a free port. The host is an IP address or localhost. 0.0.0.0 and [::] listen on every interface |
--socket <path> |
Listen on a Unix domain socket with mode 0600 instead of TCP. Cannot be combined with TLS |
--api-base <path> |
Prefix every route (default /; for example /api). The value must be / or an absolute path; a trailing slash is removed. Query strings, fragments, empty segments, . or .. segments, braces, percent signs, asterisks, and backslashes are rejected. Replaces server.apiBase for this process. Paths outside the prefix return 404; the prefix is reported separately from the server URL |
--space |
Serve the operator space, as on crystal run. Cannot be combined with --workspace |
--exit-on-stdin-close |
End the server when the wrapper closes stdin. Ignored with --token-stdin, which reads the token from stdin |
--tls-cert, --tls-key |
Serve HTTPS |
--auth token|none |
Token authentication (default) or none |
--token-file, --token-stdin |
Token sources. See Authentication |
--allow-host, --allow-origin, --expose-header, --allow-private-network |
Host and CORS options. See Hosts and CORS |
No secret is a command flag. A TLS private key password comes from CRYSTAL_SERVER_TLS_PASSWORD.
Startup
Section titled “Startup”The server is in one of these states: starting, awaiting_operator, ready, closing, or failed. GET /health and GET /info report it, and so does the server.state event.
- The listener starts first, so clients can connect before the session exists. Requests that need the session return 503 until it is ready.
- When the workspace needs trust (the
workspaceTrustswitch applies) or--resumeneeds a choice, the state isawaiting_operatorand the question is sent to a connected client. A declined trust or session choice, or an invalid launch, setsfailed, prints the reason on stderr, and exits with code 1. - A saved session that another process has open cannot be resumed. The server enters
failedwithSession is already open <id>, and/resumeof such a session reports the same text and keeps the current one.
GET /health and GET /info also return startedUtc, when this server process started. It does not change across /clear and /resume. A client that sees a different value has reached a new process and should load GET /snapshot again instead of continuing from its last event sequence.
Listening line
Section titled “Listening line”Once listening, the server writes one JSON line to stdout for a wrapper:
{"event":"listening","url":"http://127.0.0.1:52144","pid":4242,"workspace":"/repo","discovery":"/home/me/.crystal/server/4242.json"}The line never carries a token.
Stderr summary
Section titled “Stderr summary”For the operator, stderr then gets a summary: URL, listen address, port, workspace, auth mode, the token (only a generated token, and only when stderr is a terminal; otherwise where to find it), the discovery file, the pid, and Ctrl+C stops the server. Progress lines follow as they happen: Waiting for a client to answer a startup question, Session ready, Stopping <reason>, Session saved <id>, and Server stopped.
Discovery file
Section titled “Discovery file”The server writes ~/.crystal/server/<pid>.json with owner-only permissions in an owner-only directory. It holds the URL, pid, workspace, build identity, and the token when the server generated it. The session id is not in the file, because /clear, /resume, and /fork change it; read GET /info. The file is deleted on exit. A file left by a crashed process names a dead pid.
Authentication
Section titled “Authentication”--auth token is the default on every crystal server listener, including loopback and a Unix socket, because other local processes and browser pages can reach loopback. server.auth in config.json can change it; a token source without --auth implies token.
Token sources, first match wins:
CRYSTAL_SERVER_TOKEN.--token-file, an owner-only file.--token-stdin, one line.- Otherwise a generated 256-bit random token, written to the discovery file and printed on stderr only when stderr is a terminal.
A supplied token has at least 16 characters. Tokens never appear in arguments, the listening line, or logs. Only the SHA-256 of each token is kept, and comparison is constant time.
Requests send Authorization: Bearer <token>. GET /health needs no token and returns only the state.
--auth none turns token checks off. Every request then has every scope, and the server prints a warning at start. Host and Origin checks still apply.
Twenty failed authentications from one address within a minute return 429 for the rest of that minute. JSON bodies are limited to 1 MiB; image uploads keep the 20 MiB host limit.
Network and TLS
Section titled “Network and TLS”To reach the server from another machine on the LAN, listen on 0.0.0.0:<port>. A client that uses a DNS name also needs that name in --allow-host; an IP address needs nothing. A non-loopback listener without --tls-cert and --tls-key is allowed, but the server warns that tokens and session content travel in clear text.
The Host header must name localhost, an IP address, or an --allow-host value, which blocks DNS rebinding. Otherwise the response is 421.
Scopes
Section titled “Scopes”| Scope | Allows |
|---|---|
observe |
Snapshot, events, images, export, children, the quick prompt list, the read-only queries (sessions, models, options, Agents, skills, MCP servers, plugins, background tasks and their logs), and Pursue state and checks |
operate |
Input, interrupt, recall, queue retract, mode, options (an option whose command needs admin still needs it), verbose, draft, image upload, quick prompt send, side question control, interaction answers, Pursue start, pause, resume, clear, and status, and slash commands that only report or act inside the session |
admin |
Shutdown, token management, answering trust or login interactions, and slash commands that change trust, directory access, approval, the model or its slots, prompt sets, rules, agents, skills, title, workspace, saved configuration, or quit the session; /login, /logout, and Pursue model, thinking, tier, speed, context, limit, and compaction settings |
/notify test runs your operatorNotify command on the server host, so it needs admin.
The startup token has every scope. POST /auth/tokens issues a narrower token, for example observe only, that lives for this process and can be revoked with DELETE /auth/tokens/{id}. Issued tokens are not persisted.
Browsers cannot set headers on EventSource. POST /auth/ticket returns a single-use ticket valid for 30 seconds. Only GET /events?ticket= accepts it, with the scope of the token that asked for it. A long-lived token never goes in a URL.
Hosts and CORS
Section titled “Hosts and CORS”CORS is off unless --allow-origin lists an origin. A request with an Origin header that is not listed is rejected with 403, even with --auth none. A rejected origin gets no CORS header, so its 403 is opaque to the page by design.
| Option | Effect |
|---|---|
--allow-origin <origin> |
Allow a browser page from that origin |
--allow-origin '*' |
Allow every origin. Each response echoes the request’s own Origin; the Host check and token authentication still apply. The server prints a warning. With --auth none nothing is left between a web page and the workspace, so keep the token on |
--allow-host <host> |
Add a Host value, such as a DNS name |
--expose-header <name> |
Add a name to Access-Control-Expose-Headers. Retry-After, Content-Disposition, and WWW-Authenticate are always exposed |
--allow-private-network |
Answer Access-Control-Allow-Private-Network: true to a preflight from a listed origin that sends Access-Control-Request-Private-Network. Off by default; current Chrome asks the user instead of sending this preflight |
CORS headers (Access-Control-Allow-Origin, Vary: Origin, and Access-Control-Expose-Headers) go on every response to a listed origin, including 401, 421, and 429, so a page can tell the cause apart. A listed origin that reaches a disallowed Host gets a readable 421. GET /health goes through the same Host and Origin checks as every other route.
config.json may hold the same lists under server: allowOrigins, allowHosts, exposeHeaders, and allowPrivateNetwork. It also accepts server.apiBase (default /) and server.auth (token or none). Command-line list values are added to config values; --api-base replaces the configured value. Invalid entries stop startup. See Configuration.
Web mode
Section titled “Web mode”crystal web serves the same session API and the browser front end found under Crystal Home. Both website installers put Crystal Code Web there by default. You can also supply your own front end.
crystal web [every crystal server option except --api-base] [--spa-fallback on|off]- Put the front end in
~/.crystal/web(moved by--homeorCRYSTAL_HOME) withindex.htmlas its entry page. Crystal does not create or modify this directory. - The API prefix is fixed at
/api;server.apiBaseand--api-basedo not apply.GET /configat the root needs no token and returns{"product":"crystal-code","apiBase":"/api","authentication":true}(the last value reflects whether API authentication is enabled). It contains no token or machine paths. - Files and
/configneed no token;/apiuses the server’s authentication, scopes, and ticket rules. The Host check covers every path. The page’s own origin is allowed; other origins need--allow-originorserver.allowOrigins. - Files cannot escape the
web/root. Dot-prefixed, hidden, and system files are not served./and directory paths serveindex.html. With SPA fallback enabled (default), a missing path without an extension also servesindex.html;--spa-fallback on|offorweb.spaFallbackcontrols this. crystal webauthentication defaults tononeand prints a warning. Setweb.author pass--auth tokento require a token. This default is independent of the listen address: an unauthenticated listener on0.0.0.0is exposed without a token. A token source without--authimpliestoken.- A missing
web/directory orindex.htmlproduces a warning; the API and/configremain available.
See Configuration for server and web settings.
Shutdown
Section titled “Shutdown”/quit, POST /shutdown, Ctrl+C (SIGINT), SIGTERM, SIGQUIT, or stdin closing with --exit-on-stdin-close start shutdown, also while the server waits on a startup question.
-
server.statewithstate: closingand areasongoes out at once, before a running turn has unwound. Reasons areinterrupt,terminate,quit_signal,request,quit,stdin_closed, andcancelled. The first reason wins. -
The turn is interrupted without starting queued work, and pending interactions are cancelled.
-
The session is saved, and
server.closingreports the session id, whether it was saved, and the samereason. Before the session existed there is noserver.closing. -
The last stdout line is written for a wrapper:
{"event":"stopped","pid":4242,"exitCode":0,"reason":"interrupt","sessionId":"…","saved":true}reasonis the stop reason, orfailedwith anerrorfield when the launch failed.sessionIdis null when no session was opened. -
Every stream ends, the listener stops, and the discovery file and socket are deleted. The exit code is 0; a failed launch exits with 1.
A second Ctrl+C while the server is stopping ends the process at once.
Output streams
Section titled “Output streams”- stdout carries only the
listeningline and thestoppedline, for a wrapper. - stderr carries the readable summary and progress lines for the operator.