Skip to content
Crystal CodeDocs
ENEnglish

Server protocol

crystal server is a second operator surface beside the terminal. An operator, or a wrapper program such as a desktop application, starts it in a workspace. Separate front ends, for example a web page or a desktop program, then connect to it over HTTP and drive the session. Those front ends are not part of this repository.

For the command line, startup, authentication, and shutdown, see Server. This page records the protocol a client speaks.

Routes in this reference are relative to the API base. crystal server defaults to / and can use --api-base or server.apiBase to add a prefix; crystal web fixes the API base at /api.

The server uses these engine pieces, which any other front end can use too:

  • CrystalCode.Engine.Launch (SessionLauncher, SessionLaunchOptions, SessionLaunchOverrides, SessionLaunchAccess): the launch path the terminal and crystal run also use.
  • SessionRunner: the serialized input loop. crystal run uses it too.
  • SessionState: the front-end-neutral reducer that produces SessionSnapshot. ChildSessionFold is shared with the terminal’s child projection.
  • CodingSession.BeginOrigin and SessionEvent.Origin: events a client’s request produced carry that client’s id. Draft images, pending /attach images, and recalled messages belong to the origin that made them.
  • Plain-data report events: ToolsListed carries a ToolCatalogReport and HelpRequested carries SlashCompletion values.
  • CodingSession.TryAttachImage, TryGetImage, TryExport, and the structured SessionClosure from CloseAsync.
  • One process hosts one active CodingSession. /clear, /resume, /fork, /cd, and /space replace or move that session inside the process, exactly as in the terminal. A front end that wants several sessions starts several processes.
  • The server is a front end that implements SessionFrontEnd. It holds no product logic. Approval, trust, the workspace fence, and ToolInvocationPolicy stay where they are. The server only carries their questions to a connected client.
  • Every engine capability is reachable: every slash command, every CodingSession operation a front end calls, every SessionFrontEnd contract, and every SessionEvent.
  • The protocol carries no version identifier in routes, headers, or fields. It is not a public web API. It follows the build: a wrapper knows which executable it started, and GET /info reports the build identity.
  • Front ends probe GET /info instead of a version. These fields keep their names: product, build, state, startedUtc, scope, authentication, operations, eventTypes, interactionKinds, and slashCommands. New fields and new list entries may appear; a name is not changed or removed.

The server owns the wire shape. Every field is written explicitly. Engine records, Crystal chat types, and plugin interfaces are never serialized by reflection, so settings, provider definitions, opaque reasoning state, and image bytes cannot reach a client by accident.

  • JSON with camelCase fields over UTF-8. Server-sent events for the stream.
  • Requests send Authorization: Bearer <token>. GET /health needs no token and returns only the state.
  • Every request carries X-Crystal-Client: <random id> chosen by the client for that page or window (letters, digits, -, _, ., at most 128). A browser stream that cannot set the header passes ?client=. It routes targeted events and records which client started a request.
  • A state-changing JSON request may carry clientRequestId; POST /images takes it as a query parameter. A repeat from the same client within ten minutes returns the first result without running again.
  • Requests that need the live session return 503 before it is ready.
  • Errors are application/problem+json with English text.
  • Clients ignore event types and fields they do not know.
  • JSON bodies are limited to 1 MiB; image uploads keep the 20 MiB host limit.
  • observe: snapshot, events, images, export, children, quick prompt list, the read-only queries (/sessions, /models, /options, /agents, /skills, /mcp, /plugins, /tasks, and task logs), and Pursue state and checks.
  • operate: input, interrupt, recall, queue retract, mode, options, verbose, draft, image upload, quick prompt send, side question control, interaction answers, and the slash commands that only report or act inside the session: /help, /status, /stats, /btw, /clear, /fork, /child, /sessions, /compact and /compact full, /todos, /attach, /export, /tools, /plugins, /notify, and /mcp without arguments, /mcp list|show, /cd without a path, /plan, /mode, /pursue (no argument, or status, start, pause, resume, or clear), /quick (alias /shortcuts, including list and send <name>), /skills, and plugin or MCP prompt commands.
  • admin: shutdown, token management, answering a trust interaction, and slash commands that change trust, directory access, approval, the model or its slots, prompt sets, rules, agents, the workspace, saved configuration, or quit the session (/approval, /thinking, /context, /tier, /speed, /tokens, /model, /promptset, /promptattach, /statusline, /cd <path>, /space, /trust, /rules, /access, /resume, /agents, /verbose, /quit, /title <text>, /pursue model|thinking|tier|speed|context|limit, and the argument forms of /compact, /todos, /tools, /skills, /plugins, /notify, and /mcp). /notify test runs the operator’s 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.

Route Scope Purpose
GET /health none state and startedUtc (when this server process started, UTC)
GET /info observe Build identity, startedUtc, capability lists (event types, operations, slash commands, interaction kinds), session id, workspace
GET /snapshot observe Session state, lastSeq, pending interactions, server state
GET /events?after=<seq> observe Event stream; honors Last-Event-ID
POST /input operate {"text"}: a prompt, a slash command, a follow-up, or empty text that releases the queue. Returns accepted (false when the engine refused the input), pending (a setting was recorded for the next turn), error (the refusal text or null), turnActive, and quit
POST /interrupt operate TryInterrupt
POST /recall operate TryRecall; the client states that its composer can take the message back
POST /queue/retract operate TryRetractQueued. Accepts an optional clientRequestId. Returns retracted and text (the newest follow-up, or null when the queue is empty). The active turn continues
POST /mode operate cycle moves forward through Work, Plan, and enabled custom modes in name order. Also accepts toggle-plan or set with a name. Returns mode, planMode, and pending. During a turn the change applies on the next turn
POST /verbose operate {"target","enabled"}: SetVerbose (Ctrl+O and Ctrl+G)
PUT /draft operate {"text"}: NotifyDraftChanged for this client’s draft images
POST /images operate Raw image bytes: TryAttachImage; returns number, mimeType, marker, and trustedMarker to put in the submitted text
GET /images/{number} observe TryGetImage; bytes of a session or tool image
GET /quick-prompts observe The F6 catalog
POST /quick-prompts/{name}/send operate SubmitQuickPromptAsync; Fill stays in the client
POST /side/cancel, POST /side/clear operate Side question control; /btw itself goes through /input
GET /children, GET /children/{id} observe Child list, archive, events, usage, and todos (F7 and /child)
GET /pursue observe pursue: current objective state or null, including id, runId, checkCount, and latestCheck
GET /pursue/configuration observe configuration: checker model, compaction, and limits, available without an objective
PUT /pursue/limits/{name} admin {"value": integer or null}: edits one limit through /pursue limit; returns configuration. Names: continuations, stalls, model-calls, tool-calls, duration, wait. Invalid names, types, or ranges return 400; busy refusal returns 409
GET /pursue/checks?after=0&limit=50 observe Checks oldest first: objectiveId, checks, nextOffset, hasMore. limit is 1–100
GET /pursue/checks/{id} observe check: one retained checker attempt with evidence; 404 for an unknown id
GET /sessions?all=true|false observe ListSavedSessions: saved sessions, newest first, for this workspace or every workspace. Each has open (another process, or this one, holds it)
GET /models observe ListModels: every catalog model with credentialReady, contextWindows, thinking, imageInput, and maxTokens, plus pending. No base address, header, or key
GET /options observe ListOptions: the same option list as options.changed, plus pending
PUT /options/{id} operate, or the scope of the option’s command {"value"}: a listed value as a string, or true/false for a switch. Runs that value’s slash command. Returns pending, options, and pendingSettings. 404 for an unknown option, 400 for a value it does not offer, 403 when the command needs admin, 409 with the engine’s text when it refuses
GET /agents observe ListAgents: enabled, concurrency, limits, agents, and notes
GET /skills observe ListSkills: enabled and skills (name, description, source, location), without bodies
GET /mcp observe ListMcp: enabled, servers (source home, project, or session), and notes. No command, argument, environment, header, or URL
GET /plugins observe ListPlugins: enabled, plugins, and notes
GET /tasks observe ListBackgroundTasks: background Bash tasks, newest first
GET /tasks/{id}/logs?offset=&limit= observe TryReadBackgroundTaskLog: text, nextOffset, hasMore. 404 for an unknown task, 410 when the offset left the bounded log
GET /export?format=markdown|json&system=true|false observe TryExport as a download; /export still writes on the server
GET /interactions, POST /interactions/{id} operate Pending interactions and answers
POST /auth/ticket observe Event-stream ticket
GET /auth/tokens, POST /auth/tokens, DELETE /auth/tokens/{id} admin List, issue (scope, optional label), and revoke process-local tokens; the startup token cannot be revoked
POST /shutdown admin Same as /quit
Switch id Model picker id
approval_model_enabled approval_model
extended_approval extended_model
compaction_model_enabled compaction_model
image_model_enabled image_model
audio_model_enabled audio_model
video_model_enabled video_model
document_model_enabled document_model

Set the model picker to a provider/model value and use the switch to enable it. Every tier and speed option lists unset first, and PUT with unset clears that slot. unset is not a catalog token, so it never names a model’s own value. A value with no command, such as a stored model that left the catalog, appears only while current and is rejected by PUT. A picker shows unset until a model has been configured. Turning the switch off keeps the model and its tuning. Changing the model preserves the switch state. Enabling requires a configured model. These writes require admin scope. Clients that previously sent off to a model picker now use its switch, and clients that picked a model through extended_approval now use extended_model.

Pursue model settings are offered by GET /options and set with PUT /options/{id}: pursue_model, pursue_thinking, pursue_tier, pursue_speed, pursue_context, and the same suffixes under pursue_compaction_. Both model pickers use session to restore inheritance. Tuning depends on the selected model’s capabilities; checker tier, speed, and context are omitted while it uses the session model. Changes publish options.changed. Writes need admin scope and are refused while busy.

configuration.model has usesSessionModel, nullable provider, model, tier, speed, context, and thinking. configuration.compaction uses the same fields with usesSessionSetting instead of usesSessionModel: inheritance falls back to session compaction, then the checker model. configuration.limits has continuations, stalls, modelCalls, toolCalls, durationSeconds, and waitSeconds. Null means unlimited. These are configured choices; inherited slots are resolved at runtime. Configuration edits also emit the formatted report.document acknowledgement to their originating client. Read configuration again to refresh limits; there is no dedicated configuration-change event.

Each event is one SSE message whose id is seq:

{"seq":1042,"type":"stream.text","time":"2026-10-26T02:36:20Z","sessionId":"…",
"origin":"client-7f3a","target":"client-7f3a",
"source":{"childSessionId":"…","invocationId":"…"},
"data":{"delta":"…"}}

sessionId is null before the session exists. origin names the client whose request produced the event. target appears only on events meant for one client. source appears only on child events: ChildEventReceived is unwrapped, so a child’s text arrives as stream.text with a source. Every SessionEvent and every Crystal ChatStreamEvent maps to one type:

Engine event Type
SessionStarted, ChromeChanged session.started, chrome.changed
PreferencesChanged, StatusFieldsChanged preferences.changed, status-fields.changed
SessionOptionsChanged options.changed: each option’s id, name, category, current, switch, and values (value, name, the slash command that selects it, optional description and group). An empty command cannot be chosen directly. Send the command through POST /input
SlashCommandsChanged, PromptHistoryLoaded commands.changed, prompt-history.loaded
ImageHistoryInvalidated, ActivityChanged images.invalidated, activity.changed
LoadingProgressed loading.progressed: kind (tool_set, plugin, or mcp_server) and name, sent while activity.changed reports a loading activity
UserMessageSent, UserMessageRecalled message.sent, message.recalled
TurnStarted, TurnFinished, ModelRoundClosed turn.started, turn.finished, round.closed
StreamReceived stream.text, stream.reasoning, stream.reasoning-state, stream.tool-call, stream.usage, stream.completed
ToolCallsIssued, ToolResultsReceived tools.called, tools.results
RetryScheduled, UsageChanged, ContextEstimated retry.scheduled, usage.changed, context.estimated
QueueChanged, TodosChanged queue.changed, todos.changed
PursueChanged, PursueChecked pursue.changed (pursue: null, or objective, status, phase, reasonCode, reason, checks, continuations, stalls, nextStep), pursue.checked (index, verdict, reason, nextStep, evidence, usage). /pursue start and resume run as one turn, with stop reasons pursue_blocked and pursue_limit_reached
HistoryReplayed, ConversationCleared conversation.replayed, conversation.cleared
CompactionStarted, CompactionFinished compaction.started (id, manual), compaction.finished (id, status: completed, unchanged, failed, or cancelled; summary, the stored summary of a completed compaction or null; shown, whether the operator’s summary display setting draws it)
NoteWritten, ErrorWritten note, error
HelpRequested, StatusReported, StatsReported, ToolsListed, TodosListed, DocumentWritten report.help, report.status, report.stats, report.tools, report.todos, report.document (document: title and blocks, each with type of paragraph, keyValues, table, or list)
SideQuestionSnapshot side.changed
ApprovalPassed, ApprovalReviewing approval.passed, approval.reviewing (with stage primary or extended)
ChildSessionChanged, ChildViewRequested child.changed, child.view

The chrome object in session.started, chrome.changed, and the snapshot names the active provider and model along with the session id, workspace, mode, approval, thinking, prompt set, context window, service tier, and speed. Its pending object lists settings chosen during a turn that apply on the next turn, and a key appears only while that setting waits.

Server events: server.state, server.closing (with the session id and whether it was saved), interaction.opened, interaction.resolved, interaction.cancelled, and resync.

stream.reasoning-state reports that opaque provider state arrived, with its format name only. Image bytes never appear in events: trusted markers are written as plain [Image #N] and an images array lists the numbers to fetch from GET /images/{number}. message.recalled also carries the raw draft with trusted markers, so the sending client can put it back in its composer.

Delivery: state events go to every client. Reports, child.view, and the notes and errors a request produced go only to the client that sent that request. A running turn, a child, and a queued follow-up have no origin, so everything they produce goes to every client.

GET /snapshot returns the state a client needs to draw the session without replaying history: state, sessionId, chrome, preferences, slash commands, prompt history, conversation (messages, readable reasoning, tool calls, and tool results), live (the in-progress model round: text, reasoning, tool-call arguments so far, retries), turnActive, activity, queue, todos, status fields, usage, context window and estimate, the side-question thread, child summaries, the last turn’s stop reason and counts, the pending interactions this client may answer, and lastSeq. The snapshot and lastSeq are taken under one lock, so a client that follows with GET /events?after=lastSeq misses nothing and sees nothing twice. The snapshot is built by the engine’s front-end-neutral session state, not by server code.

The snapshot also carries pursue (the same shape as pursue.changed, or null) and approvals, each call that passed approval in this conversation.

Anything that asks the operator becomes an interaction with an id, a kind, and a payload.

Kind Engine contract Answer
approval IApprovalPrompt.AskAsync once, session, always, or deny; calls that cannot reuse a grant offer only once and deny
question IUserPrompt.AskAsync {"answers":[["label"],…]} in question order, custom text where a question allows it, or {"dismissed":true}
trust IWorkspaceTrustPrompt.ConfirmAsync {"trust":true|false}; needs admin
choose_session ISessionChooser.ChooseAsync {"sessionId":"…"} or {"sessionId":null} to decline
choose_child SessionFrontEnd.ChooseChildAsync {"childId":"…"} or {"childId":null} to decline
login SessionFrontEnd.CreateLoginInteraction {"address":"…"}, the HTTP or HTTPS address the browser ended on, or {"cancelled":true}; needs admin
  • An approval payload carries the call, the classification (a child’s call has a summary prefixed with the child), the primary review verdict and the extended review verdict when they ran, and the allowed choices. The answer is {"choice":"once|session|always|deny"}.
  • A login payload carries provider, steps, linkLabel, link (when the flow provides a sign-in address), and prompt. /login <provider> opens it and requires admin scope. The server never opens a browser; the client opens the link on the operator’s machine. If the browser callback cannot reach the server host, the client answers with the address where the browser ended. That address contains a one-time authorization code, so it is never written to events, snapshots, logs, or diagnostics. interaction.resolved carries only the id, kind, and client. POST /interrupt or a cancelled answer cancels sign-in. Account providers appear in GET /models as type: authentication, with credentialReady true only while signed in.
  • An answer the engine did not offer is rejected with 400 and the interaction stays open. An answer to an interaction that is gone or belongs to another client returns 409.
  • Interactions raised by the model (approval, question) go to every client with operate. The first valid answer wins and the rest receive interaction.resolved.
  • Interactions raised by a client command (choose_session from /resume, choose_child from /child, trust from /cd) go to that client. If it disconnects, they go to every client with operate.
  • A cancelled turn cancels its interactions with interaction.cancelled. Otherwise an interaction waits, as the terminal card does. Shutdown cancels every interaction; the engine treats that as declined.
  • Events also go into a ring buffer bounded by count and bytes.
  • Refresh: GET /snapshot, then GET /events?after=lastSeq.
  • Reconnect: the browser sends Last-Event-ID. When that cursor has left the buffer the server sends resync and closes the stream; the client fetches a new snapshot.
  • The stream sends a comment heartbeat every 15 seconds and retry: 2000. A slow client falls behind on its own cursor and never blocks the engine.
  • /clear, /resume, and /fork change the session id. Each publishes chrome.changed before conversation.cleared or conversation.replayed, so the snapshot chrome carries the new session id and topic. Every later envelope carries the new id, and the cleared or replayed event tells the client to redraw.