Skip to content
Crystal CodeDocs
ENEnglish

Bridge protocol

crystal bridge speaks the Agent Client Protocol (ACP) version 1 on stdin and stdout. This page records what Bridge sends and accepts, and where it goes beyond the stable ACP schema. For the command line and operator-facing behavior, see Bridge.

Bridge is a front end on the engine contract. It references CrystalCode.Engine only, adds no package, holds no product logic, and writes every wire field explicitly with Utf8JsonWriter. No engine record is serialized by reflection. No third-party ACP SDK or JSON-RPC library is used. See Assemblies and namespaces.

  • One process hosts one active session. session/new, session/load, session/resume, and fork save the active session and replace it. A request that names another session id returns -32002.
  • additionalDirectories become session write rules and are process-only.
  • Bridge does not call the client’s fs/* or terminal/* methods. Editors follow the agent through tool call locations and diff content.
  • protocolVersion is always 1, whatever the client sent. v2 is a draft and is not implemented.

Bridge never adds a field at the root of a spec type. Its capabilities are advertised under agentCapabilities._meta.crystal, and the client capabilities it reads beyond the schema come only from clientCapabilities._meta.crystal. A non-schema update, method, or session id is sent only after the client opted in there. A client that never opts in sees plain ACP.

Deviation ACP Bridge Advertised as
session/load or session/resume with a cwd that differs from the saved workspace cwd is fixed after setup The session moves to the request cwd after trust, as /resume <path> does, the live system prompt is refreshed, and the request’s additionalDirectories apply crystal.loadAcrossCwd: true
/cd, /space, and /access inside a session cwd is immutable and additional roots have no mid-session change The commands work. The change is reported in session_info_update._meta.crystal (workspace, additionalDirectories) crystal.mutableWorkspace: true
Session fork Only the session fork RFD, not the stable schema _crystal/session/fork is the extension method. session/fork is also answered in the RFD’s shape. sessionCapabilities.fork is not sent crystal.fork: "rfd"
Subagent sessions Only the subagent sessions RFD Read from clientCapabilities._meta.crystal.subagents: {}. Only then does Bridge send subagent_update and child traffic under child session ids. A root clientCapabilities.subagents is not read crystal.subagents: "rfd"
_crystal/* notifications Extension notifications are allowed; a client may ignore them Sent only after clientCapabilities._meta.crystal.extensions: {}. _crystal/* requests are answered without it crystal.eventKinds
  • UTF-8 JSON-RPC 2.0 objects, one per line. A batch is rejected with -32600.
  • Stdout belongs to the protocol. Console output is pointed at stderr before anything else runs.
  • Requests are read in order by one reader. Long requests (session/prompt, session/load) run concurrently with later ones, so session/cancel, permission answers, and extension calls stay live.
  • $/cancel_request cancels a running request and answers it with -32800. For session/prompt it also interrupts the turn and answers once the turn has stopped. Bridge sends $/cancel_request for its own outstanding permission and elicitation requests when the turn that raised them ends.
Code ACP meaning Bridge use
-32700 Parse error Malformed JSON
-32600 Invalid request Not a JSON-RPC object, or a batch
-32601 Method not found Unknown method, including an unlisted _crystal/*
-32602 Invalid params Missing or mistyped fields, a relative path, an unsupported content block, a config value not offered
-32002 Resource not found An unknown or inactive session id, an unknown saved session, an unknown image number or child id
-32800 Request cancelled $/cancel_request and shutdown
-32603 Internal error Every engine refusal and failure: a refused launch, a command refused while busy, a failed turn, context overflow

-32000 (Authentication required) is never sent, and no other code in the -32000 to -32099 range is used. Bridge has no authMethods, and a missing provider credential is a launch refusal.

error.message is the engine’s English text. error.data.crystal carries kind (launch_refused, command_refused, turn_failed, context_overflow, trust_refused, internal), the engine stop reason when a turn ended, and the turn counts and usage. No error text or data contains a secret.

initialize returns:

{
"protocolVersion": 1,
"agentInfo": {"name": "crystal-code", "title": "Crystal Code", "version": "<build identity>"},
"authMethods": [],
"agentCapabilities": {
"loadSession": true,
"promptCapabilities": {"image": true, "audio": false, "embeddedContext": true},
"mcpCapabilities": {"http": true, "sse": true},
"sessionCapabilities": {
"list": {}, "resume": {}, "close": {}, "additionalDirectories": {}
},
"_meta": {"crystal": {
"extensions": ["_crystal/..."], "eventKinds": ["..."],
"loadAcrossCwd": true, "mutableWorkspace": true,
"fork": "rfd", "subagents": "rfd"
}}
}
}

agentInfo.version is the first 12 characters of the product commit, or dev for a build without one. _meta.crystal.extensions lists every _crystal/* method this build answers, and eventKinds every _crystal/* notification. Both follow the build and carry no version.

image and embeddedContext are always true. Bridge accepts every block it advertises and never fails a prompt because the current model cannot use one. audio is false because the engine has no audio input.

Client capability Effect
elicitation.form The question tool, MCP elicitation, trust, and session and child choices become forms. Without it they fall back as described under Forms
session.notices Notes, errors, and retries become notice. Without it only errors and turn-level failures become agent text
session.compaction Compaction becomes compaction_update and compaction_summary_chunk. Without it a displayed summary becomes agent text
session.configOptions.boolean Switches are boolean options. Without it they are two-value selects
_meta.crystal.subagents (not ACP) Child sessions are restricted sessions in the subagent RFD shapes
_meta.crystal.extensions (not ACP) _crystal/* notifications are sent
fs, terminal, auth.terminal Read and ignored
ACP Engine
session/new {cwd, mcpServers, additionalDirectories} Prepare the launch with Workspace = cwd, create the session, and start it. Returns sessionId, configOptions, and modes
session/load {sessionId, cwd, ...} Resume that saved session and replay the archive before responding. An unknown saved session is -32002
session/resume {sessionId, cwd, ...} The same restore without replay
_crystal/session/fork {sessionId, cwd, ...} and RFD session/fork /fork <id> semantics: a new id from that saved session, in cwd. The source file is not changed
session/list {cwd, cursor} Saved sessions newest first. title is the first user message preview, updatedAt the update time, additionalDirectories the saved outside roots, and _meta.crystal carries mode, planMode, userTurns, and createdAt. Pages of 50 with an opaque cursor. Omitting cwd lists every workspace
session/close {sessionId} Interrupt, collect, and close. The process stays up for another session/new
session/set_mode The mode option’s /mode <id> command. A mode not offered is -32602
session/set_config_option See Config options
session/cancel Interrupt the turn. Pending permission and elicitation requests for it are cancelled and treated as deny
  • sessionId is the engine session id. /clear makes a new engine id. Bridge keeps the ACP id stable for the connection and reports the new engine id in session_info_update._meta.crystal.engineSessionId. session/load accepts either id.
  • cwd must be absolute.
  • session_info_update is sent after the first user message and on each save, with title and updatedAt.
  • mcpServers become session-level MCP definitions. See MCP servers.

ACP’s root set is [cwd, ...additionalDirectories], and on load and resume the request carries the complete intended list. After session/new, load, resume, or fork, the session’s roots outside the workspace are exactly the request’s additionalDirectories, each as a write rule in request order. Saved outside rules and access.json defaults outside cwd are not applied.

Narrowing rules are read rules on cwd or a directory inside it. They only remove write access, so dropping them would widen access. session/new seeds them from access.json for that workspace; load and resume keep the saved ones. A request entry inside cwd is rejected with -32602. Each entry must be absolute and an existing directory, and a credential path is rejected with -32602. The next load or resume replaces the roots with the request list again.

Trust uses the workspaceTrust switch. The question goes to the client as a form. A client without forms gets -32603, kind trust_refused, naming the directory and saying to run crystal there once, or to turn the switch off.

session/load streams the archive in order before it responds:

  • user_message_chunk for user text and images;
  • agent_thought_chunk for readable reasoning;
  • agent_message_chunk for assistant text;
  • tool_call and tool_call_update (final status and content) for each call and result;
  • for each archived ## Earlier context block, a completed compaction_update with its summary when the client has session.compaction, and otherwise an agent_message_chunk with _meta.crystal.replay = "compaction";
  • a final plan, usage_update, available_commands_update, and config_option_update.

Opaque reasoning state is never sent. Notices are not replayed. A replayed image carries its bytes; an image the session no longer holds is replayed as its plain [Image #N] text. A /resume inside a session replays as load does.

Each block is given to the model in the richest form the engine supports for the current model. A block the engine cannot use becomes a one-line mention in the user message, never an error. Names, titles, and URIs inside mentions come from the client, so control characters and line breaks are removed and each value is bounded. Bridge removes U+2063 from client text and resources, so only an image it attached has a trusted marker.

Block Handling
text Joined in order. Text that starts with / is a slash command, exactly as typed in the terminal
image Attached with the signature check, 20 MiB limit, and media store of the terminal. When the model has no image input, or the bytes fail validation, the block becomes [Image not attached: <reason>] and a notice warning names the reason
resource (text) A fenced block headed by its URI (or absolute path for file://) and MIME type
resource (blob) An image MIME type is handled as image. A blob that decodes as UTF-8 text with a text-like MIME type is handled as a text resource. Any other blob becomes [Attached resource not shown: <uri> <mimeType>, <size> bytes, binary content is not passed to the model]
resource_link See below. Never refused
audio -32602

A resource_link is mapped by its URI:

URI Handling
file:// with a local absolute path to an image file, on a model with image input Attached through the same path resolution and checks as /attach. If that fails, it falls back to the next row
file:// with a local absolute path, any other file or a directory [Linked file: <name> at <absolute path>] or [Linked directory: ...], marked (not found) when missing. The model reads it with its own tools under normal approval
file:// with a remote host, or a path that is not a local absolute path The mention for other schemes
Any other scheme [Linked resource: <name> <uri> (<mimeType>) - Crystal Code did not open this link]. Bridge does not fetch it. The model can reach it only through a tool the session already has, such as read_mcp_resource. There is no built-in web fetch

title replaces name when present. size is added when known. description is not sent to the model. The archive stores the message as the model saw it, so session/load replays a link as its mention text or its image.

Engine stop reason stopReason
completed end_turn
output_truncated max_tokens
model_call_limit_reached, tool_call_limit_reached, duration_limit_reached max_turn_requests
content_filtered refusal
interrupted cancelled
failed, context_overflow error -32603, kind turn_failed or context_overflow, with the engine text

Every response carries _meta.crystal with the engine stop reason, modelCalls, toolCalls, usage, lastRequestUsage, cumulativeUsage, and contextWindow.

  • A slash command that does not start a turn returns end_turn once it finishes, after its output has arrived as updates. A command the engine refuses is -32603 with kind command_refused. A command sent while a turn runs returns end_turn at once and follows the engine’s busy rules. /quit closes the session; the next request for its id is -32002.
  • A prompt sent while a turn runs is a follow-up with the engine’s queue semantics. Its response resolves when the turn that consumed it ends. _crystal/queue/release is the empty-Enter release.
  • A cancelled turn always answers cancelled, never an error.

Every update carries _meta.crystal.event with the engine event name. Child events also carry _meta.crystal.child (childSessionId, invocationId).

Engine Update
UserMessageSent Not echoed during a live turn. Replay sends user_message_chunk
UserMessageRecalled _crystal/recalled with the draft
StreamReceived text agent_message_chunk, with a messageId per model round
StreamReceived reasoning agent_thought_chunk. Reasoning state is dropped; _meta on the next thought names the format only
StreamReceived tool call tool_call (pending) on first sight, tool_call_update with rawInput as arguments complete
StreamReceived usage, UsageChanged, ContextEstimated usage_update with used and size (the selected context budget). _meta.crystal holds cumulative input, output, reasoning, the ~ estimate flag, and interim
RetryScheduled notice warning with attempt and delay, plus _crystal/activity
ToolCallsIssued tool_call with title, kind, locations, and rawInput
ApprovalReviewing tool_call_update with _meta.crystal.approval = {stage: primary|extended, state: reviewing}
ApprovalPassed tool_call_update status in_progress, with _meta.crystal.approval (reason, risk, authority, summary, verdicts)
ToolResultsReceived tool_call_update completed or failed with content and rawOutput
TodosChanged plan
SlashCommandsChanged available_commands_update
SessionOptionsChanged config_option_update with the complete list, and current_mode_update when the mode changed
SessionStarted, ChromeChanged _crystal/chrome with the full plain chrome
PreferencesChanged _crystal/preferences
StatusFieldsChanged _crystal/statusFields
ActivityChanged _crystal/activity
QueueChanged _crystal/queue
LoadingProgressed _crystal/loading with kind (tool_set, plugin, or mcp_server) and name
PursueChanged, PursueChecked _crystal/pursue (pursue, same fields as crystal server) and _crystal/pursueChecked (index, verdict, reason, nextStep, evidence, usage), only for a client that opted in under clientCapabilities._meta.crystal. /pursue start and resume are one prompt turn: the prompt is answered once, when the whole run ends
NoteWritten, ErrorWritten notice info or error
HelpRequested, StatusReported, StatsReported, ToolsListed, TodosListed, DocumentWritten Agent message text from the engine’s plain-text report renderers, _meta.crystal.report with the kind (help, status, stats, tools, todos, document), and _crystal/report with the kind and structured values
SideQuestionSnapshot _crystal/side. Never conversation content
HistoryReplayed The replay sequence above
ConversationCleared session_info_update with the new _meta.crystal.engineSessionId
PromptHistoryLoaded, ImageHistoryInvalidated _crystal/promptHistory, _crystal/imagesInvalidated
ChildSessionChanged, ChildEventReceived See Child Agents
ChildViewRequested _crystal/childView
CompactionStarted, CompactionFinished With session.compaction: compaction_update in_progress, then compaction_summary_chunk when a summary is shown, then compaction_update completed, failed, or cancelled. unchanged is sent as completed with _meta.crystal.status. Without it, a shown summary is an agent_message_chunk whose messageId is the compaction id

_crystal/* notifications use the params.sessionId envelope of session/update and go only to a client with _meta.crystal.extensions. Every engine event is mapped to an update, mapped to a _crystal/* notification, or listed with a reason as deliberately unmapped (UserMessageSent, TurnStarted, and TurnFinished, whose content is the prompt and its response).

  • toolCallId is the model’s call id. Child calls appear only under their child session id.
  • title is the same one-line summary the terminal shows.
  • locations list the absolute paths a call reads or writes, with a line where the arguments name one, resolved by the resolver approval uses.
Tools Kind
read, list, tree, skill, view_image, describe_image, read_mcp_resource, list_mcp_resources read
glob, grep, search search
edit, write, apply_patch edit. A patch with only Delete File is delete, with only a move is move
bash, bash_start, bash_status, bash_logs, bash_stop execute
todowrite, todoread think
question other
task other, with _meta.crystal.child
MCP, plugin, and external tools other, with _meta.crystal.source

edit, write, and apply_patch send diff entries (path, oldText, newText) computed from disk before execution, one per file. A delete is a diff with empty newText and _meta.crystal.delete. Results send the tool text as content; tool images send image blocks. Long bash output is bounded by the tool output limit.

Status flow: pending when issued, in_progress after approval passes, then completed or failed from the result. A denied call is failed with the rejection text the model sees. A call screened out for an unknown tool or wrong input is failed with the screening text.

An approval prompt becomes session/request_permission with the tool call and these options:

optionId kind Engine
once allow_once Allow once
session allow_always Allow for this session
always allow_always Always allow
deny reject_once Deny

session and always are offered only when the call can reuse a grant, as on the server. _meta.crystal carries risk, authority, the host summary, requirePrompt, the primary and extended review verdicts, and, for a child call without subagent sessions, child. A cancelled request, an unknown option, or a closed connection is deny. Bridge never answers a permission itself.

With elicitation.form, these become elicitation/create with sessionId and, for a tool, toolCallId:

Engine Form Result
question tool One property per question, keyed q1..qN. Single select is a string enum of option labels; multiple is an array of that enum. Custom text allowed adds a qN_custom string accept maps to answers in question order; decline and cancel dismiss
MCP elicitation The engine’s question shape, not the server’s raw schema accept, decline, cancel as in MCP
Trust One boolean trust, with the directory in the message accept with true trusts and is remembered
/resume choice A string enum of session ids with previews in oneOf titles The id, or decline
/child choice A string enum of child ids The id, or decline

URL mode is never used. Without form support, questions are dismissed, MCP elicitation is cancelled, trust is refused with an error, and choices are declined.

configOptions come from the engine’s option catalog, in this order. Each value names the slash command that selects it. session/set_config_option and session/set_mode run that command, so validation, refusal while busy (-32603, command_refused), and config.json writes match the terminal. A value or option not offered is -32602. The response carries the complete list of options offered to this process.

id category Values Command
mode mode Plan, Work, enabled custom modes /mode
model model Grouped by provider; value provider/model /model <provider> <model>
thinking thought_level The model’s gears, plus default and off when allowed /thinking
context model_config Declared budgets /context
tier model_config Declared tiers plus unset /tier
speed model_config Declared speeds plus unset /speed
approval _crystal_approval default, edit, review, audit, full /approval
approval_model_enabled _crystal_approval switch /approval model on|off
approval_model _crystal_approval catalog /approval model --select <provider> <model>
approval_thinking, approval_tier, approval_speed, approval_context _crystal_approval the approval model’s gears, tiers, speeds, and budgets /approval thinking, tier, speed, context
extended_approval _crystal_approval switch /approval extended on|off
extended_model _crystal_approval catalog /approval extended --select <provider> <model>
extended_thinking, extended_tier, extended_speed, extended_context _crystal_approval the extended reviewer’s tuning /approval extended thinking, tier, speed, context
prompt_set _crystal_prompt default plus sets /promptset
agents _crystal_agents switch /agents on|off
compaction_model_enabled _crystal_compaction switch /compact model on|off
compaction_model _crystal_compaction catalog /compact model --select <provider> <model>
compaction_thinking, compaction_tier, compaction_speed, compaction_context _crystal_compaction the compaction model’s tuning /compact thinking, tier, speed, context
micro_compaction _crystal_compaction switch /compact micro on|off
topic _crystal_topic switch /topic on|off
topic_model _crystal_topic session plus catalog /topic model [provider model]
topic_thinking, topic_tier, topic_speed, topic_context _crystal_topic the topic model’s tuning /topic thinking, tier, speed, context
pursue_model _crystal_pursue session plus catalog /pursue model [provider model]
pursue_thinking, pursue_tier, pursue_speed, pursue_context _crystal_pursue checker tuning /pursue thinking, tier, speed, context
pursue_compaction_model _crystal_pursue session plus catalog /pursue compaction model [provider model]
pursue_compaction_thinking, pursue_compaction_tier, pursue_compaction_speed, pursue_compaction_context _crystal_pursue tuning for the pursue compaction model /pursue compaction thinking, tier, speed, context
image_model_enabled, audio_model_enabled, video_model_enabled, document_model_enabled _crystal_describe switch /describe <kind> on|off
image_model, audio_model, video_model, document_model _crystal_describe catalog models that declare that input /describe <kind> model --select <provider> <model>
image_thinking, image_tier, image_speed, image_context, and the same for audio, video, and document _crystal_describe that model’s tuning /describe <kind> thinking, tier, speed, context
estimated_tokens _crystal_display switch /tokens on|off

thinking, context, tier, and speed appear only when the model offers a choice. The tuning options of a dedicated model appear whenever its configured model offers the choice. A select lists only values with a command plus the current value. tier and speed name unset with unset, which clears the slot. Only a value with no command, such as a stored model that left the catalog, is shown while current and cannot be chosen.

The dedicated model pickers display unset before a selection. Choosing a model preserves the switch state. Turning a switch off keeps the model and its tuning. The legacy modes field mirrors mode. Options a process flag locks, such as --prompt-set, are still listed with their value, and setting them returns the engine refusal. Everything else (/rules, /access, /mcp, /tools, /plugins, /notify, /statusline, /verbose, /todos) stays a slash command.

available_commands_update lists every completable verb, including plugin and MCP prompt commands, with the engine help text. Verbs that take arguments get input.hint built from the first argument keys, and _meta.crystal.arguments carries the full completion tree. /quit closes the session as session/close does.

TodosChanged maps to plan: content, status (pending, in_progress, completed), and priority medium. A cancelled todo is sent as completed with _meta.crystal.status = cancelled. Child todos never replace the parent plan.

Without the subagents opt-in, which is plain ACP, no subagent_update and no child session id is ever sent. The parent task tool call carries the child’s status, model calls, tool calls, and latest text as tool_call_update content. Child approvals and forms use the parent session id and the parent task call’s toolCallId, with the child label in the title and _meta.crystal.child (childSessionId, agent, label, and the child’s own toolCallId and name).

With clientCapabilities._meta.crystal.subagents: {}, each child is announced by subagent_update on the parent (sessionId is the child id, title the label, description the Agent name) before any of its traffic. Child events, approvals, and forms are then sent under the child session id. No child capability is advertised: the engine does not accept input for a child, and cancelling the parent stops all children. Children cannot use the question tool, so child forms are only MCP elicitation. _crystal/children/* returns the full records either way.

All are requests on the active session unless noted. Results are explicit JSON. An unknown _crystal/* method is -32601; an engine refusal is -32603 with command_refused.

Method Purpose
_crystal/snapshot The session state, with the fields of GET /snapshot on the server, without pending interactions
_crystal/session/fork Fork a saved session
_crystal/recall Recall the last message; the draft follows as _crystal/recalled
_crystal/queue/release Release the queue, as empty input does
_crystal/queue/retract Take the newest queued follow-up back; returns retracted and text. The active turn continues
_crystal/mode/cycle, _crystal/mode/togglePlan Cycle the mode or toggle Plan; returns mode and planMode
_crystal/verbose {target, enabled} Turn verbose output on or off
_crystal/draft {text} Report the unsent draft, so draft images follow it
_crystal/image/attach {data}, _crystal/image/get {number} Attach image bytes to the draft; read a session or tool image
_crystal/quickPrompts/list, _crystal/quickPrompts/send {name} The F6 quick prompt catalog; send one
_crystal/side/ask {question}, _crystal/side/cancel, _crystal/side/clear /btw and side question control
_crystal/children/list, _crystal/children/get {childSessionId} Child summaries; one record with archive, usage, and todos
_crystal/export {format, system} Markdown or JSON export; returns fileName, mediaType, and text
_crystal/compact {full} /compact or /compact full
_crystal/status {full}, _crystal/stats {scope}, _crystal/tools The command, answered with the structured report values
_crystal/models Models in the catalog, with pending changes; no base address, header, or key
_crystal/agents, _crystal/skills, _crystal/mcp, _crystal/plugins The fields of the matching GET route
_crystal/tasks, _crystal/tasks/logs {taskId, offset, limit} Background tasks and bounded task logs. An unknown task is -32002; a bad offset or limit is -32602
_crystal/pursue/get Current objective state or null, with id, runId, checkCount, and latestCheck
_crystal/pursue/configuration Checker model, compaction, and limits, also without an objective
_crystal/pursue/limit {name, value} Edits one limit and returns configuration. Names: continuations, stalls, model-calls, tool-calls, duration, wait. Invalid input is -32602; busy refusal is -32603
_crystal/pursue/checks {after?, limit?}, _crystal/pursue/check {id} Paged checks, and one check with its evidence; the same fields as GET /pursue/checks and GET /pursue/checks/{id}. Unknown id is -32002

A client cannot type the invisible marker prefix, so a prompt names an image from _crystal/image/attach as its plain [Image #N]. Bridge turns that text into the trusted marker once, and only for a number attached that way and not yet used. Any other [Image #N] stays plain text. Reading the host clipboard is not exposed, because it reads the machine Bridge runs on.

  • fs/* and terminal/* client methods.
  • session/delete: the engine has no delete semantics for saved sessions.
  • The ACP authenticate and logout methods, and the configurable LLM provider RFD. Provider definitions and keys stay in Home, and keys never cross the protocol. /login and /logout work as slash commands through a form (see Bridge).
  • A client-provided system prompt.
  • Audio input, URL-mode elicitation, MCP over ACP, and several concurrent sessions in one process.
  • No secret is on the command line, in a wire field, in a notice, or in stderr. Editor MCP server values are treated like provider definitions: never in events, logs, or errors.
  • Trust, approval modes, grants, forced prompts, the credential-path ban, read-only directories, and Full are unchanged.
  • Prompt text, resources, tool output, and MCP content are untrusted data for the model, as everywhere else.
  • Bridge listens on nothing.