Skip to content
Crystal CodeDocs
ENEnglish

Engine contract

CrystalCode.Engine runs the conversation and reports what happens. A front end hands it a SessionFrontEnd, calls it, and observes events. It never reads engine state directly and the engine never draws, reads keys, or writes to the console.

A front end supplies (SessionFrontEnd):

  • Observer (ISessionObserver) receives every SessionEvent.
  • Approvals (IApprovalPrompt) asks the operator to approve a tool call and is told when a call auto-passes or is under review.
  • Questions (IUserPrompt) answers the built-in question tool.
  • Sessions (ISessionChooser) picks a saved session for /resume, including one workspace or every workspace.
  • Trust (IWorkspaceTrustPrompt) asks whether to trust a directory. A front end that cannot ask returns false.
  • Optionally ChooseChildAsync for /child, McpServers for session-only editor servers, CreateLoginInteraction for account sign-in, and SyntaxReady to receive the controlled syntax service after plugins attach. Server and Bridge supply form-backed login interactions but no browser opener; the terminal supplies its login popup and syntax callback.

CodingSession wraps Approvals and Questions once, at construction, in NotifyingApprovalPrompt and NotifyingUserPrompt. Every engine path that asks the operator, including child approvals behind the operator gate and MCP elicitation, uses the wrapped prompts, so the operatorNotify command runs for the terminal, crystal server, and children alike without front-end code. The notifier starts the command on the thread pool after delaySeconds, and the wrapper cancels the pending start when the prompt returns. A started command runs to exit or timeoutSeconds, with no shell, the workspace as working directory, and CRYSTAL_NOTIFY_* variables plus the same values as JSON on stdin. Output is drained and discarded. The first failure in a session is one English note. CloseAsync stops pending and running commands. The turn event is raised from CompleteTurnAsync when no follow-up started and the turn was not interrupted, and the next submission cancels it. Trust, /resume, and child choices are operator-initiated and do not notify. crystal run replaces the setting with off in memory.

A front end prepares a session with SessionLauncher.PrepareAsync. It maps its own command line onto SessionLaunchOptions and passes a SessionLaunchRequest (working directory, workspace, operator space, resume target, trust check, whether the launch provider and model may be saved by a later preference command, and optional additional roots). The launcher applies overrides in memory, checks credentials, resolves the resume target, checks trust, and validates prompt attachments, directory rules, and the mode. It asks the operator only through the IWorkspaceTrustPrompt and ISessionChooser it receives; a null prompt returns TrustNeedsOperator or ResumeNeedsOperator so the front end chooses its wording. SessionTrustCheck.Prompt follows workspaceTrust and remembers a yes, Require refuses an untrusted directory without asking (crystal run), and Skip neither checks nor records. The result’s SessionLaunch.CreateSession builds the CodingSession. The terminal opens its trust and resume prompts on their own alternate screen (StartupPrompt) before the session frame exists.

A front end calls CodingSession: Create, StartAsync, SubmitAsync (slash commands, follow-ups while a turn runs, interrupts, and turn starts; returns true when the operator asked to quit), CompleteTurnAsync once TurnTask finishes, FinishTurnAsync to collect a turn before exit, TryInterrupt, TryRecall, TogglePlan, CycleMode, TrySetMode, SetVerbose, NotifyDraftChanged, Enqueue, EnqueueAsync, SubmitQuickPromptAsync, PasteClipboardImageAsync, TryAttachImage, TryAttachImageFile, TryGetImage, TryExport, TryCancelSideQuestion, ClearSideQuestions, TrySetDirectoryAccess, and CloseAsync. TurnActive, TurnTask, RecallPending, AgentsEnabled, PlanMode, CustomMode, and SessionId report state. The usual turn is: SubmitAsync, await TurnTask, then CompleteTurnAsync.

SessionRunner is that loop for a front end without a frame loop of its own. It is the only caller of the session’s input methods while it runs. Inputs (SubmitAsync, SubmitQuickPromptAsync) go through one channel in order. Input that arrives while a session call is running goes to EnqueueAsync, or to a queued quick prompt, as the terminal pump forwards keys. A finished turn is collected with CompleteTurnAsync, which starts a queued follow-up. InvokeAsync runs a synchronous operation (a mode change, a draft update, an image attach, an export) in order with the inputs, also while a call is running. Text that was queued while a command ran, with no turn to collect, is started once that command returns. Cancellation interrupts and collects the turn without starting queued work. crystal run and crystal server use it; the terminal keeps its own pump. TryInterrupt, TryRecall, and TryCancelSideQuestion stay direct calls because Ctrl+C makes them from any thread.

SessionEvent.Origin names the client whose request produced an event. A front end serving several clients wraps each request in CodingSession.BeginOrigin; SessionRunner does this per input. The turn task and child invocations start under no origin, so their events have none, and the engine never sets an origin for a single-operator front end. Draft images from a paste or TryAttachImage, pending /attach images, and the recall window belong to the origin that made them: NotifyDraftChanged discards only that origin’s draft images, a submission takes only that origin’s pending images, and UserMessageRecalled carries the sending origin. Closing the session discards every origin’s drafts.

SessionState is the front-end-neutral reducer. A front end that must redraw at any time applies every event and reads SessionSnapshot: chrome, preferences, slash commands, prompt history, the committed conversation, the round still streaming (LiveRound, without opaque reasoning state), queue, todos, status fields, activity, usage, the side-question thread, children with live usage and todos folded in, and the last turn. Reports addressed to one client are not session state. ChildSessionFold holds the child folding the terminal’s child projection also uses.

TryAttachImage attaches bytes a front end received (an upload, or a paste on another machine) to the draft with the same signature and size checks as a clipboard paste, and returns the image with its trusted marker. TryGetImage returns a held session image by number. TryExport renders the Markdown or JSON export in memory as SessionExportContent; /export still writes a file. CloseAsync returns a SessionClosure with the session id, whether it was saved, and the plain-text resume hint the terminal prints. Without a ChooseChildAsync, /child reports that child inspection is not available in this front end.

Events are immutable sealed records, one type per file under Events:

  • Lifecycle and chrome: SessionStarted, ChromeChanged, PreferencesChanged, SessionOptionsChanged, SlashCommandsChanged, PromptHistoryLoaded, ImageHistoryInvalidated, ActivityChanged.
  • Turn: UserMessageSent, TurnStarted, StreamReceived (carries Crystal’s ChatStreamEvent), ToolCallsIssued, ToolResultsReceived, ModelRoundClosed, RetryScheduled, UsageChanged, TurnFinished, QueueChanged.
  • Conversation: HistoryReplayed, ConversationCleared, TodosChanged.
  • Text and reports: NoteWritten, ErrorWritten, HelpRequested, StatusReported, ToolsListed, TodosListed.

Events carry plain data. ToolsListed carries a ToolCatalogReport (Plan and Work definitions, external tool metadata and notes, the external-tools switch, and the external approval policy), not the settings object or the live catalog. HelpRequested carries plugin verbs as SlashCompletion values, not plugin objects. No event can reach HarnessSettings, a provider definition (which may hold a literal API key), ExternalCatalog, or a plugin type.

The engine publishes from whichever thread produced the change, including the turn thread while a model round streams. Observers must be thread-safe and return quickly; a front end with a UI thread marshals to it. Events carry engine values, not captions: the engine reports SessionActivity and the front end chooses the wording and layout.

The engine owns the usage numbers. It keeps the context usage and the session cumulative totals, including the baseline that in-turn cumulative counts are added to, and reports them through UsageChanged and TurnFinished. A front end renders them and does not compute totals.

Some engine calls take time (a turn collecting, /compact, a model switch). The front end awaits them without freezing its surface. The terminal host does this by pumping the frame while the call runs.

Image markers cross the boundary as text. UserMessageSent and replayed transcripts carry [Image #N] markers, and a marker is trusted only when it starts with ImageMarkerText.Prefix (U+2063). A composer that attaches images prefixes exactly the attached spans. Display cannot reference the engine, so it holds its own copy of the prefix; ImageMarkerContractTests keeps the two equal.

Adding a front end means referencing CrystalCode.Engine, implementing the five contracts above, and projecting events onto its own surface. The terminal host in CrystalCode is the reference implementation. The headless test in CrystalCode.Engine.Tests is the smallest correct driver. A later Avalonia desktop front end uses C# markup and does not add XAML or AXAML files. crystal bridge is the Agent Client Protocol (ACP) front end on this contract (Bridge protocol), not an engine protocol. It uses SessionLauncher with SessionTrustCheck.Prompt and a form-backed trust prompt only for a client with forms, SessionLaunchRequest.AdditionalRoots, SessionFrontEnd.McpServers, SessionRunner, event origins, ToolCallSummary and ToolFileChanges for tool titles and diffs, the SessionOptionsChanged catalog for config options, the engine’s plain-text report renderers, CompactionStarted and CompactionFinished, SessionLaunchRequest.Fork, and its own SessionState, and maps every event to ACP or a _crystal/* notification itself.

A front end may pass MCP servers for one session through SessionFrontEnd.McpServers. They use McpServerSource.Session, are merged after Home and Project by name, follow the Project approval choice, are not saved in the session file, and their values appear in no event or text. SessionLaunchRequest.AdditionalRoots, when not null, is the complete set of write roots outside the workspace: the new session drops saved and default outside rules and keeps read rules on or inside the workspace (a new session seeds those from access.json). Neither is written to access.json. SessionLaunchRequest.Fork with a resume target opens a copy of a saved session under a new id, as /fork <id> does, and saves it at once. SessionOptionsChanged carries the selectable session settings, each value naming the slash command that selects it; the session publishes it at start and whenever a value or its choices change, and not when nothing changed. CompactionStarted and CompactionFinished report each compaction with an id, a status (completed, unchanged, failed, or cancelled), and the summary only when the summary display setting shows it. CodingSession.TryAttachImageFile attaches an image file with /attach’s checks and returns the marker instead of writing a note. HelpText and StatsText render /help and /stats as plain text beside StatusText and ToolListText. SessionChrome names the active provider as well as the model.

crystal server is the HTTP front end on this contract (Server protocol). It uses SessionLauncher, SessionRunner, SessionState, and event origins, and maps every event to wire JSON itself.

crystal run is the headless front end in this executable, not a second assembly. It reads one task from an argument or from stdin, applies process-only overrides, starts one user turn, and exits. The interactive crystal and crystal space commands apply the same session overrides: approval, the approval model and its thinking gear, service tier, and speed, extended approval and its model, gear, tier, speed, trigger, and primary-review switch, Plan, Work, or a custom mode (--mode), thinking, the selected model’s context budget, service tier, speed, prompt set, prompt attachments, skills, external tools, plugins, and turn quotas. Overrides are not written to config.json. That includes the approval-model switch (--approval-model, --approval-provider, --approval-model-id), gear (--approval-thinking), and slots (--approval-tier, --approval-speed), and every --extended-approval flag. A later interactive preference command writes the field the operator changed, and can also write a --provider or --model passed at launch. It does not write the other launch overrides. The task text, --format, --show-thinking, --space, and --workspace-trust stay on crystal run. Slash commands are rejected on crystal run so they cannot change saved settings. Secrets are not command flags.

The run supplies RunLog or RunJsonLog, UnattendedApprovalPrompt, UnattendedUserPrompt, UnattendedSessionChooser, and UnattendedTrustPrompt. The trust prompt is a fail-closed fallback. The directory check itself runs before the session is created and follows --workspace-trust, not workspaceTrust. The approval prompt denies every call that would have asked the operator. The question prompt dismisses. Session choice is declined. Review and Audit still call the reviewing model: allow executes the tool, and deny returns the reviewer’s reason. An enabled extended approval model runs the same way after a primary allow. Plan does not offer write, edit, multi_edit, apply_patch, or bash. The approval policy also rejects those side effects when a catalog still contains them.

--format default writes a readable trace. Each model round prints thinking text only when --show-thinking is set, then the assistant reply, then each tool beside its own result. With --show-thinking, the reply is labeled [Assistant]. read, list, glob, grep, and other successful tools keep a short head excerpt and an omitted-line count. edit, multi_edit, write, and apply_patch keep their result. bash keeps the command, the exit status, and a short tail, with a longer tail when the command fails. Other failures keep the result text. Labels use square brackets, exit status uses parentheses, and omitted-line markers use angle brackets. --format json writes one JSON object per line, with type, a UTC timestamp, and sessionID, and keeps the full tool output. Event types are step_start, text, reasoning, tool_use, error, note, retry, step_finish, stopped, and session. text and reasoning carry one segment each, not stream deltas. A retry discards the failed attempt’s unsent segment. tool_use carries callId, status, and output, and name and arguments only when a call with the same id was issued; a result is never paired with another call. output shows trusted image markers as plain [Image #N], and images lists those numbers. step_finish carries reason, modelCalls, toolCalls, contextWindow, and three usage objects with inputTokens, outputTokens, and optional reasoningTokens: usage for the turn total, including children, lastRequestUsage for the final request, and cumulativeUsage for the session. An object is omitted when a provider did not report it. A turn that faults before it reports a result still gets a step_finish with reason failed and no counts. Child events reuse the parent shapes with a child_ prefix (child_text, child_reasoning, child_tool_use, child_error, child_note, child_retry) and add childSessionID and invocationID. child_status reports agent, label, status, modelCalls, toolCalls, images, and, once known, usage. Thinking text is omitted unless --show-thinking is set. The process then prints the saved session id. Exit 0 means the turn completed and no operator prompt was denied or dismissed. Exit 1 is an invalid command, configuration, credential, workspace, or prompt set. Exit 2 is a failed model request, including a turn that faults before it reports a result. A cancellation the turn did not request, such as a request timeout, is a failed request, not an interrupt. Exit 3 is a model-call, tool-call, or duration budget, or context overflow. Exit 4 is a finish that was not a failure, budget stop, or interrupt, after an operator denial or a dismissed question. Exit 5 is an interrupt. A failure, budget stop, or interrupt outranks a denial.