Skip to content
Crystal CodeDocs
ENEnglish

Assemblies and namespaces

The terminal host and the only executable. Owns CLI commands, the terminal host loop (alternate screen, key loop, Ctrl+C, termination signals), the headless crystal run entry, and the projection of engine events onto CrystalCode.Display. It also owns the terminal surfaces for the engine’s prompts: approval cards and keys, the question overlay, and the saved-session picker. crystal run supplies its own observer, approval prompt, question prompt, and session chooser. It does not own session logic, approval policy, prompts, storage, or tools, and it does not own the frame painter, composer buffer, or transcript log. crystal version and crystal --version print the build identity as plain text and exit. The build section is Crystal Code (this repository’s commit), Crystal (the Crystal library repository’s commit), SDK (the .NET SDK that compiled the executable), and Configuration (the MSBuild configuration stamped on the executable). A blank line separates it from the host section: Runtime (the shared framework hosting the process) and OS (RuntimeInformation.OSDescription plus the operating-system architecture). A line is omitted when that value was not recorded. An empty section is omitted, including the blank line. Commits are the 40-character source revision the SDK appends to the assembly informational version. The assembly version placeholder is left unread. SDK is the NETCoreSdkVersion assembly metadata stamped by Directory.Build.targets for projects in this repository. Configuration is AssemblyConfigurationAttribute. The host passes RuntimeInformation.FrameworkDescription, OSDescription, and OSArchitecture. The description is kept whole and the architecture is appended in lower case. The report does not start a process. The outbound User-Agent stays Crystal Code.

The contract external dotnet tools may reference when a call needs host facts. It defines ToolHostContext, IHostTool, IHostMultimodalTool, and the optional IHostToolApprovalClassifier. ToolHostContext carries the workspace root, the session id, the approval mode, and the extension’s global and project runtime-data directories. An approval classifier receives the model call and a context carrying the workspace root, session id, and approval mode before invocation and returns the call’s risk and authority; the engine merges that proposal with its own classification and it can only raise risk or authority, never lower them. ClassifyApprovalAsync receives user/turn cancellation and an independent two-second timeout. Its entry is dispatched on a worker so blocking before returning a task does not block approval. After timeout or cancellation that classifier instance stays disabled until the external catalog reloads; late work is observed and its result is discarded. In-process code still cannot be forcibly terminated. Null results, exceptions, timeouts, disabled instances, and either invalid classification field fail closed to Privileged + PrivilegedEscalation, merged with the host floor. User/turn cancellation propagates without approval. Classification summaries are authored by the host; a tool’s Summary is not sent to the operator or the reviewer. The engine awaits IApprovalClassifier ClassifyAsync; its default implementation adapts existing synchronous plugin classifiers. Synchronous external classification fails closed when a tool has an asynchronous pre-classifier. It references only Crystal and Crystal.Tools. It does not reference the engine, the display, the executable, or a terminal library. Tools that implement only Crystal’s ITool or IMultimodalTool do not reference it. There is no paired test project; dispatch, approval classification, and load-context identity are tested in CrystalCode.Engine.Tests.

The contract a disk plugin references. It defines IPlugin, contribution lists, the hook and raw hook interfaces, the hook context types, syntax tokenizer contracts, the model and environment views, and IPluginDataDirectory for an extension’s runtime data directories. It references only Crystal and Crystal.Tools. It does not reference the engine, the display, the executable, or a terminal library. There is no paired test project; discovery, the load context, and hook order are tested in CrystalCode.Engine.Tests.

The front-end-neutral class library. Owns session and turn execution, Plan, Work, and custom-mode catalogs, approval policy, context compaction, ~/.crystal storage, built-in coding tools, operator tool sets, operator plugins, prompts, in-process plugin contracts, slash commands, and the event stream a front end observes. It never reads a key, writes to the console, or paints. See Engine contract.

Engine tests: workspace fencing, approval classification, compaction selection, session serialization, command behavior, external tool sets, launch overrides, trust and resume preparation, the session runner, event data guards, a headless session driven by a scripted model, and the dependency guard. Does not reference the host executable.

The HTTP front end behind crystal server: ASP.NET Core Minimal API endpoints and server-sent events on Kestrel, authentication and scopes, the explicit wire mapping, the interaction broker, the event log, and the host that wires SessionRunner to HTTP. One process hosts one active session. It holds no product logic. The executable’s Commands/ServerCommand parses the command line, resolves the token, and hands off to it. The protocol is in Server protocol.

Folder Owns
Hosting CrystalServer (Kestrel, startup, the listening line, warnings, shutdown), ServerSession (launch, the live CodingSession, SessionRunner, close), ServerOptions, ServerRuntime, ListenAddress, the discovery file, ClientRegistry, and the clientRequestId ledger
Security AccessGuard (Host and Origin checks, CORS and exposed headers for listed origins, bearer tokens, stream tickets, failure rate limit; the lists come from --allow-*/--expose-header and the server section of config.json), TokenStore (hashed process-local tokens), scopes and the scope of each SessionVerb, problem responses
Events EventHub: the session observer that numbers, serializes, buffers, and fans out events and owns the SessionState reducer
Interactions InteractionBroker: approval, question, trust, session, and child prompts as interactions with validated answers
Wire WireWriter, WireEvents, SnapshotWriter: every wire field written explicitly
Endpoints Route groups for input and modes, images, quick prompts, side questions, children, export, interactions, tokens, and the event stream

Server tests against a real Kestrel listener on a loopback port and a scripted model, the parity guards, the secret-leak test, and the dependency guard.

The ACP front end behind crystal bridge: newline-delimited JSON-RPC 2.0 on the raw stdin and stdout streams, the explicit ACP wire mapping, prompt content blocks, and the host that wires SessionLauncher and SessionRunner to one ACP session. One process hosts one active session. It references CrystalCode.Engine only and adds no package: JSON-RPC and the wire use System.Text.Json from the shared framework. It holds no product logic and never serializes an engine record by reflection. The executable’s Commands/BridgeCommand parses the command line, points Console.Out and the Spectre console at stderr, maps SIGINT, SIGTERM, and SIGHUP to shutdown, and hands off to CrystalBridge.RunAsync. The protocol and its phases are in docs/bridge.md.

Which session options a client sees as config options is operator configuration, not engine behavior. BridgeHostSettings (Engine Configuration, read and written by DiskSettingsStore as the bridge section of config.json) holds the customConfigOptions switch and the saved id list, and the engine’s option catalog is unchanged. BridgeCommand resolves a flag, then the saved list while the switch is on, then the built-in default, into the expanded id list on BridgeOptions. Bridge filters by id at the wire (SessionUpdates, BridgeAgent) and never edits the catalog. A hidden option is refused as -32602 over ACP and stays a slash command. The same section holds workspaceTrust (default off): whether Bridge asks before entering an untrusted directory. BridgeCommand resolves --workspace-trust, then that value, and hands the result to the launcher as SessionLaunchOptions.WorkspaceTrust, so the engine’s trust checks, also inside the session, follow it. The terminal’s top-level workspaceTrust is not read for Bridge. Like server, the section is never written by a command line.

Folder Owns
Transport JsonRpcConnection (one reader, one ordered writer, concurrent requests, $/cancel_request both ways, parse and batch errors), the error codes, JsonRpcException, and request field readers
Hosting CrystalBridge (the public entry), BridgeOptions (with the offered option ids), BridgeAgent (initialize, session/new, load, resume, fork, list, prompt, cancel, set_mode, set_config_option, close), BridgeSession (the live CodingSession, SessionRunner, the front-end contracts as forms, held updates, the ACP id that survives /clear, the SessionState behind _crystal/snapshot, child approval routing), Extensions (every _crystal/* method), ReportCapture (structured values for report requests), ClientFeatures, LaunchTrustPrompt (trust before a session exists), SessionSetup, and TurnTracker (which engine turn a prompt waits for, faults, clears)
Prompts PromptContent: content blocks to submitted text, image attachment through the engine, file image links through TryAttachImageFile, and mention lines
Wire SessionUpdates (events to session/update and _crystal/* notifications, compaction updates, archive replay, with the mapped, notified, and deliberately unmapped lists), ChildUpdates (subagent sessions for a client that opts in, the parent task call otherwise), CrystalWire (extension values with the server’s field names), CatalogWire (the model, Agent, skill, MCP, plugin, and background task results), ToolCallWire, PermissionWire, TurnWire, ConfigWire (config options and legacy modes from SessionOptionsChanged), FormWire (elicitation forms and answers), McpServerWire (client MCP servers as session definitions), SessionList

Bridge tests over in-process pipes with a scripted model, the parity guards, the secret-leak test, and the dependency guard.

The terminal UI library. Owns the alternate-screen frame, input routing, composer, transcript viewport, markdown paint, and queue card. Spectre widgets are rasterized into frame rows. AnsiConsole.Live is not the session shell. Terminal.Gui is a parked package reference for supply-chain review and is not called. The host loop stays in this assembly’s shell types; a later migration to Terminal.Gui would replace that loop inside this project only.

Committed transcript entries may carry a Spectre IRenderable alongside a plain-text fallback. The display engine measures the widget at the current terminal width when its cache is rebuilt, so tables, grids, panels, and other high-level components participate in resize, scrollback, and repaint like text. Non-interactive output renders the same widget directly. The shell progress region owns transient indeterminate progress and elapsed time; static command reports remain committed transcript widgets.

Terminal PursuePage owns the live inspector’s stable check-id selection, follow-latest state, cached unstyled detail rows, and independent detail scroll. It draws PaintLine frames using existing theme tokens and TranscriptScrollbar, side by side from 100 columns and stacked below. SessionProjection forwards parent PursueChanged even when a child has focus. SessionRenderer paints the page in its existing polling loop, reserves footer rows for progress and navigation, and keeps the parent composer, transcript, and stream in place. Parent activity uses a separate progress chrome while a child has focus, preventing child progress from being shown as pursue activity. Modals suspend the page without discarding its selection or scroll. F9 and terminal-only /pursue view are intercepted in the renderer; SlashOptionMap adds that completion only for the terminal. Pause/resume keys return ordinary slash input to the host, never invoke execution directly. No engine command, event, or protocol is added.

Plugin syntax paint uses Display-owned SyntaxSpan values and a cache lookup callback on MarkdownRenderer and TranscriptLog. Display never references plugin or engine contracts. The terminal host adapts validated engine tokens and owns asynchronous scheduling, cache lifetime, and repaint requests.

Display tests: layout, chrome, input decoder, scroll policy, composer, paint, transcript log, queue card, and the dependency guard. Does not reference the host executable.

Model adapters. Each adapter implements IChatClient and, when the provider can stream, IStreamingChatClient. Image-capable adapters additionally implement IStreamingMultimodalChatClient. Provider options, wire DTOs, and transport exceptions stay in this assembly. No tools, no UI, no home-directory layout.

Terminal host tests: session renderer, event-to-slash-option mapping, status and tool-list widgets, tool-call and progress text, transcript replay, the session picker, approval cards and keys, the image-marker contract with Display, and crystal run against a scripted model.

Provider adapter tests. One folder per vendor, mirroring CrystalCode.Providers. Does not reference the host executable.

Root identifier is CrystalCode, matching the existing solution. Folder path under a project root equals the namespace after the project name, so engine namespaces read CrystalCode.Engine.Sessions and so on.

CrystalCode (executable):

Folder Owns
Commands Spectre.Console.Cli commands. Bare crystal stays the terminal. space opens the operator space under the data directory. run is the headless task command. server resolves the server token (ServerTokenSource) and signals (ShutdownSignals) and starts CrystalCode.Server. bridge captures the raw stdio streams, rebinds console output to stderr, registers signals, and starts CrystalCode.Bridge. version prints the build identity
Run Unattended front end for crystal run: plain-text or JSON-lines log, denied operator prompts, dismissed questions, and exit codes. Overrides and launch preparation come from CrystalCode.Engine.Launch
Terminal Host loop, event projection, session renderer, status and tool-list widgets, progress and tool-call text (ToolCallText reveals hidden characters in the engine’s ToolCallSummary), transcript replay, session picker, question overlay, startup trust and resume prompts (StartupPrompt), slash-option mapping
Terminal/Approvals Approval prompt, card, diff preview, and keys

CrystalCode.Engine (namespaces below are relative to CrystalCode.Engine):

Folder Owns
Configuration Loaded options, defaults, thinking and mode labels, display-case helpers
Events Immutable session events, observer interface, chrome and preference snapshots
Home ~/.crystal paths and file I/O; DiskSettingsStore is the default config.json implementation and reads provider files through ProviderFiles
Home/Interfaces Configuration persistence contracts such as ISettingsStore
Launch Launch options a front end received (SessionLaunchOptions), in-memory overrides (SessionLaunchOverrides), --allow-read / --allow-write rules (SessionLaunchAccess), and SessionLauncher, which resolves the workspace, resume target, trust, prompt attachments, and mode before a session exists
Sessions Session (CodingSession), transcript, ledger, streaming turn, slash commands and completions, chat client lifetime, status, usage, and tool-list text, the input loop for front ends without a frame loop (SessionRunner), the front-end-neutral reducer (SessionState, SessionSnapshot, LiveRound, ChildSessionFold), front-end contract (SessionFrontEnd, ISessionChooser)
Approvals Risk, authority, grants, policy, review transcript
Approvals/Interfaces Prompt and reviewer contracts
Compaction Window accounting and summary substitution
Tools Workspace fence and built-in ITool types
Tools/External Operator tool sets (tools.json), exec and isolated ITool / IMultimodalTool loaders, and host-context dispatch
Prompts Caller-owned system text. Built-in Work and Plan identify the assistant as Crystal Code
Modes Operator-defined custom modes: modes/<name> discovery, tool selection, prompt composition, and launch-name validation
Notifications Operator notification: OperatorNotifier runs the operatorNotify command, and NotifyingApprovalPrompt and NotifyingUserPrompt wrap the front-end prompts so every operator wait reaches it
Skills OpenCode-compatible SKILL.md discovery and catalog
Plugins In-process registry and built-in contributions
Plugins/Interfaces Contribution contracts
Plugins/Providers Built-in DeepSeek, OpenAI-compatible, Responses, Anthropic, Gemini, and Ollama client factories
Version Build identity for crystal version: product commit, Crystal commit, compiling SDK, compile configuration, host runtime, and host operating system. Two plain-text sections

CrystalCode.Display:

Folder Owns
Input Decode ReadKey bursts into keys, paste, and wheel events
Shell Alternate screen, painter, layout, key burst, scroll policy, status and progress chrome
Composer Prompt buffer, keys, slash picker
Cards Queue overlay
Transcript Viewport log, role cards, sequential fallback
Paint Markup, markdown, theme, wrapping

Quick prompts keep the same dependency direction: Engine Home owns QuickPromptStore, bounded UTF-8 file reads, validation, and immutable catalog values; Display Composer owns the isolated quick-prompt picker and preview. The terminal maps catalog values, routes F6 only outside modal prompts, and inserts Fill at the current composer cursor. Send uses CodingSession.SubmitQuickPromptAsync, bypasses slash parsing, and never consumes pending or composer draft images. Ordinary queued submissions bind pending images at enqueue time so later quick sends cannot steal them. Quick queue entries do not request cancellation after tools; explicit queue release and ordinary follow-ups retain their existing interrupt behavior.

Provider types live under CrystalCode.Providers plus one folder per wire family (DeepSeek, OpenAI, Responses, Anthropic, Gemini, and Ollama). Shared OpenAI-compatible Chat Completions request and stream parsing lives in Compatible. Shared direct-HTTP lifecycle and SSE framing for Responses and Messages, Gemini GenerateContent, and Ollama Chat lives in Protocol; each wire codec still owns its request and event semantics. Gemini uses SSE and replays signed response parts so function calls retain thought signatures. Opaque reasoning state is provider-owned: an adapter replays state only in its own format. A block it cannot replay keeps its readable text instead of failing (assistant text, or the protocol’s readable reasoning field where it has one). Ollama uses JSON lines and native tool_name results. Anthropic Messages marks prompt-cache breakpoints (cache_control: ephemeral) on the last system block and the last message content block of every request, so the tool definitions, the system prompt, and the conversation prefix written by the previous round are read from the provider’s prompt cache; the multimodal codec keeps the message breakpoint when image expansion splits a marked text block. Other adapters rely on their providers’ automatic prefix caching and send no cache directives. Chat Completions, Responses, Anthropic Messages, Gemini, and Ollama map an error payload, an event whose type is error, and a JSON body returned where an event stream or JSON lines were expected to provider faults carrying the provider code and message. Gemini uses error.status when error.code is a number. A non-streaming JSON response with an error payload maps the same way even when the HTTP status is 200. Anthropic Messages reports uncached input, cache writes, and cache reads as separate counts. The adapter sums them into the one input count Crystal exposes, because the session reads that count as the prompt size. A usage figure the endpoint did not report is absent, never zero, and an event stream without any usage emits no usage event. A stream may report usage more than once; each report is a cumulative snapshot of the attempt and the latest one wins. The Messages adapter reports as soon as message_start carries the input side, so a request that breaks mid-stream still charges its input. A Messages stream that reaches message_stop without a stop_reason in a message_delta fails as a truncated stream rather than completing as a normal stop. An event or response whose fields are missing or mistyped fails as an Anthropic fault instead of leaking a JSON reader exception. The Messages adapter maps max_tokens and model_context_window_exceeded to length, and refusal to a content filter, and pause_turn to the provider finish reason ProviderFinishReason.PauseTurn. The adapter declares no server tools, but a gateway or later request may run them. Blocks the provider ran itself (server_tool_use, mcp_tool_use, container_upload, and every *_tool_result, including web search results with their encrypted content) are never surfaced as tool calls. They are kept as opaque reasoning state under the anthropic.messages.server_block format, in stream order and with streamed input assembled, and written back verbatim on the next request. Other providers drop them as non-replayable state without readable text. A replayed block carries no cache marker, so the moving breakpoint sits on the last block that can hold one. Framed Responses and Anthropic error events keep the provider message as the fault text. Session retry then reports the cause instead of treating the truncated stream as retryable. Outbound chat requests send a constant User-Agent of Crystal Code with no version. Provider SDKs are not used.