Skip to content
Crystal CodeDocs
ENEnglish

Session and turn

One user message is one turn:

  1. Snapshot the transcript and current tool definitions.
  2. Stream one chat request. Publish each delta as an event as it arrives. If that round fails with a retryable provider error (HTTP 429, 404, 408, 5xx, timeout, network, or an incomplete stream), wait with exponential backoff and repeat the same round. The retry policy in config.json sets the limit and timing (defaults: five retries, 2s base, factor 2, 25% jitter, 30s cap when Retry-After is absent); Retry-After or retry-after-ms is honored when present. The engine publishes RetryScheduled; the terminal progress row shows Retrying In Ns (Attempt K) and counts the remaining wait down, and the transcript prints retrying model request plus the operator message. Live stream text from the failed attempt is discarded. HTTP 401, 403, quota, invalid_prompt, and context overflow are not retried. A connection that closes while the request body is still being written is retried once, so a stale connection can be replaced, and then reported with the transport cause instead of using the rest of the budget. User cancel still interrupts immediately.
  3. Select candidate zero.
  4. Resume when the finish reason is ProviderFinishReason.PauseTurn: the provider paused a server-side tool loop. Append the candidate’s items without its tool calls, publish no stop, and start the next round, so the paused content is the last assistant turn the provider sees. Tools do not run on a paused round. Five pauses in a row without a different round in between fail the turn and publish Model paused the turn too many times in a row. Each pause counts as a model call against the turn limits. Stop before tools when the finish reason is not a normal stop or a tool request. length keeps the assistant text, drops tool calls, and stops as output_truncated. A content filter keeps the text and stops as content_filtered. Any other reason stops as failed and publishes Model stopped with finish reason '<value>'. These stops do not compact.
  5. If the candidate has tool calls, execute the full batch through ToolExecutor, or the multimodal bridge for an image-capable turn (approval runs first in either case). CallScreeningExecutor sits in front of ToolExecutor because Crystal rejects a whole batch when one call names an unregistered tool or has the wrong input kind. A bad call gets its own failed result, naming the available tools, and the other calls in the batch still run in order. A JSON call with no argument text is recorded with {}, since a model that calls a tool with no parameters often sends nothing and every provider codec that replays the call parses it as JSON. Sessions saved before this read an empty JSON argument as {}. Text-input arguments are never rewritten. A batch that does not fit the remaining tool-call budget stops as tool_call_limit_reached, keeps the assistant text and reasoning, and leaves those calls out of the transcript.
  6. Append exact ToolResult values.
  7. Repeat until the candidate has no tool calls, a configured limit stops the turn, or the user cancels. Before each model round, compact if the estimated transcript or the last model-round usage is over budget. One failed compact while still over budget stops the turn (context_overflow). A provider failure that survives retry stops the turn as failed: the error is published, the progress row clears, and the transcript, including that user message, is saved.

Text and image-capable turns share executionBudget from config.json. The default per-turn limits are 1024 model calls, 8192 tool calls, and 7 days. The setting may be "unlimited" for all three, or an object with optional maximumModelCalls, maximumToolCalls, and maximumDurationSeconds fields. Omitted fields keep their defaults; null removes that field’s limit. Model calls and duration must be positive when finite. Tool calls may be zero to prevent tool execution. Duration must fit the runtime timer. A turn with unlimited limits still ends on model completion, user cancellation, or context compaction exhaustion. This host owns the live turn budget; it follows the nullable-limit semantics of Crystal’s AgentRunLimits without using Agent for streaming UI turns.

Built-in bash has its own per-command timer, bashTimeoutSeconds in config.json. Omitting it keeps 600 seconds. null or "unlimited" disables that timer. A positive integer up to the runtime timer limit replaces it. User cancellation and the turn budget still stop the command. External tool sets keep their own timeoutSeconds, which defaults to 120 seconds and does not follow bashTimeoutSeconds. 8. After a completed turn, consider compaction from that last round’s reported usage plus an estimate of anything added after it. /compact (alias /summarize) summarizes earlier turns immediately, without waiting for that threshold. Compaction runs inside an engine call the front end awaits; the front end keeps its own surface live meanwhile (the terminal host pumps the frame so the spinner, resize, and composer stay live).

The session keeps two transcripts. The archive appends user text, assistant text, reasoning, tool calls, and tool results as they are committed, and compaction does not change it. The model context is the list sent to the model. Compaction replaces that list with the live system prompt, a summary, and a recent tail. Usage, approval review, and later model calls read the model context. Resume, fork replay, and export read the archive. /stats tool share reads the archive, and a session file with no archive counts tools from its saved items. A session file written before the archive existed loads its saved items as the archive. Every compaction summary, manual or automatic and whether or not it is shown, is also appended to the archive as an ## Earlier context system message, so fork replay, resume, and export show the same block again. A child’s summary goes into the child’s archive the same way. showCompactionSummary and showAutomaticCompactionSummary decide only whether a front end draws the summary when it is written: CompactionFinished carries the summary and a Shown flag. Side questions skip archived summaries that follow a turn. Images stay when either transcript still mentions them. /clear drops both.

The composer stays open while a turn runs. Enter with text enqueues a follow-up (FIFO). Queued items stay in a panel above the composer until they are sent. The queue is sent when the current tool batch finishes or when the turn (thinking or conversation) ends. Empty Enter while a follow-up is queued interrupts the turn, or compaction if that is still running, so the queue is sent now. Empty Enter with nothing queued does not stop the turn. /quit, /clear, /resume, and /fork stop a busy turn and then run, including a command submitted while other session work is still on the stack. /clear, /resume, and /fork stay in the queue and run in the order typed. /clear, /resume, and /fork drop queued follow-up text; the panel updates and does not keep it. During compaction those three except /quit are refused, as are other commands that change the session, workspace, or model, except the next-turn settings below. /status, /help, /todos, and other commands that only report state or adjust the display run immediately. /quit cancels compaction and exits. With an empty composer and a queued follow-up, Ctrl+C takes the newest queued message out of the queue and puts it in the composer (TryRetractQueued); it does not interrupt. Server POST /queue/retract and Bridge _crystal/queue/retract make that same call through SessionRunner and return the text to the caller. Server deduplicates retries by clientRequestId. The engine retains the origin of each queued item so Bridge can finish the matching ACP request with cancelled. Bridge restores one-time attachment authorization for the image markers in the returned draft. A deferred /clear, /resume, or /fork stays in the queue. With nothing queued, Ctrl+C interrupts. At an idle prompt, Ctrl+C clears the composer. Two Ctrl+C presses on an empty composer exit.

Mode (/plan, /mode <name>, Tab, Shift+Tab, CycleMode, TogglePlan, and TrySetMode), the approval level (/approval with no argument or a level), /thinking, /tier, /speed, /context, and /model <selection> are accepted while a turn or compaction runs and apply on the next turn. Every other command that changes the session stays refused with Finish the current turn before ..., including the approval-model, extended-approval, and compaction-model forms.

  • While busy, a covered command is validated and recorded as pending. It changes nothing live: no executor rebuild, no system message replacement, no client, and no config.json write. The running turn keeps the tools, approval policy, child Plan ceiling, and model it started with. The note is the usual one followed by Applies next turn, for example Mode Plan Applies next turn.
  • One pending value per setting, and the last command wins. A command that names the active value drops that setting’s pending value. A cycle (Tab, Shift+Tab, /plan, /approval, /thinking, /tier, /speed, /context without an argument) steps from the pending value when there is one.
  • Validation uses the settings the next turn will start with: /thinking, /tier, /speed, and /context check the pending model. /model checks the credential and the image capability when typed, so a refusal reaches the operator then. A new pending model drops the pending context, tier, and speed, and a pending thinking gear it does not offer.
  • FinishTurnAsync applies the pending values after the turn is collected, and the manual /compact path applies them after compaction. That is before CompleteTurnAsync starts a queued follow-up, and also for an interrupted turn and for /clear, /resume, and /fork, which stop the turn first. The order is model, context, tier, speed, thinking, mode, approval. Each goes through the same path as an idle command and saves to config.json then. A value that fails (for example, a credential removed in the meantime) writes an error and the others still apply. These notes and errors carry no origin. Pending values live in memory only; a crash loses them.
  • SessionChrome keeps the active values. SessionChrome.Pending (SessionPendingSettings) lists the waiting ones, and CodingSession.PendingSettings returns the same value. A tier or speed pending as unset clears that slot. /status adds a Next turn section. The terminal status bar shows Next: ... after the other items on both the default and the custom line and never drops it.
  • SessionRunner reports each input’s result in SessionInputResult: Error is the first error the engine wrote for that input (not errors from a turn or side question it started), Accepted is true without one, Pending is true when it recorded a next-turn setting, and Queued is true when it added a follow-up, even if the item has since been removed.
  • A stricter approval level does not restrict the running turn either. The operator interrupts to get that effect at once.

The terminal registers SIGTERM and SIGHUP through PosixSignalRegistration (on Windows these are the console shutdown and close events). SIGINT stays with the Ctrl+C rules above. The first signal cancels the default termination, interrupts the running turn or compaction, and stops the key loop. The loop collects an interrupted turn with no cancellation token, so the plugin turn-end hook and the transcript update are not skipped, and then the session closes and saves as on /quit. The handler holds the process open for up to four seconds while that runs, because Windows ends the process when a close or shutdown handler returns. A second signal uses the default termination. SIGKILL and power loss cannot be handled; the turn checkpoints cover them. This handling lives in the executable. The engine has no signal code.

/btw (alias /side) asks one side question from the archive and the newest 20 side exchanges in this process. The request uses the work model, the current system message, an empty tool list, and its own cancellation. When that request does not fit the window, the host compacts a copy and does not write the summary back. If the copy still does not fit, the side question fails. Text still streaming in the current round is not included. A tool call is not executed. Text that arrived with it is kept; a tool call with no text fails, and the question stays in the panel so it can be asked again. The question, the answer, and the token usage stay out of the queue, the transcript, the usage ledger, compaction, and the saved session. The terminal draws the answer in a panel above the composer and leaves the status bar, transcript, and progress row in place. Until reasoning starts, that panel shows Waiting for the model with the same one-cell spinner as the progress row. Once reasoning starts and before answer text, it shows Thinking with that spinner, and the frame keeps advancing while the panel is open. Esc, Enter, or Space closes the panel. Left and Right step through earlier answers. x clears the in-memory thread. While that panel is open, Ctrl+C cancels an in-flight side question, closes the panel, and leaves the main turn running. /clear, /resume, and /fork drop the thread. crystal run rejects the command with every other slash command.