Crystal consumption
The interactive turn uses IStreamingChatClient and ToolExecutor. When the
selected model declares imageInput and its adapter supports it, the session
uses IStreamingMultimodalChatClient and a host executor that preserves the
same approval policy. The session owns those clients and may replace them on
/model. It does
not use Crystal.Agents.Agent for the live UI: that Agent completes model
turns without token streaming.
The live parent keeps its streaming loop. Child invocations consume
Crystal.Harness.AgentHarness or its multimodal counterpart through local
Agent adapters that reuse the host streaming turns. The host owns prompts,
tool catalogs, approval, compaction, persistence, and terminal projection.
Child invocation ownership
Section titled “Child invocation ownership”An Agent definition, a persisted child session, and a Harness invocation are
three identities. Every task without sessionId creates a child; continuation
uses that child id and a fresh invocation id. Concurrent continuation of the
same child is rejected. The parent is not an IAgent: direct child invocations
are depth zero inside Harness, whose MaximumDepth is zero. Child catalogs
also remove task, question, and background Bash tools.
CodingSession binds child execution, configuration, and commands through its
Sessions components. Improving that configuration is medium-priority product
work and is not in this build. Current manifests, /agents, and process
overrides stand. Which settings change is not defined, and no new
configuration field or command is reserved. AgentCatalog loads bounded
manifests and prompts from Home and workspace; an invalid or disabled
workspace directory shadows the Home definition. AgentToolsPlugin
contributes the session-bound task tool through the existing plugin
registry. Ordinary tool catalogs are built first;
child catalogs intersect their definition snapshot with the current parent
ceiling before constructing approved executors. A plugin hook cannot restore
a tool absent from that executor’s catalog. Child todos and transcripts are
independent. The filesystem remains shared.
The Engine holds one SharedTurnBudget per parent turn. Text and multimodal
turns atomically reserve logical model rounds and whole tool batches from it.
Retries stay inside a round reservation. Child compaction reserves a model
call only when its summary client is actually invoked. The parent’s turn timer
and cancellation token also cover child queue waits, approvals, and backoff.
Harness receives per-invocation limits and enforces invocation lifecycle and
depth. Its whole-run reservation model is not used as a second copy of the
parent’s remaining quota; otherwise the first parallel invocation could reserve
all capacity, and text and image Harness instances would spend separate pools.
TaskBatchExecutor runs only consecutive task calls in parallel, retaining
input result order. Every other tool is an execution barrier. The same grouping
is preserved by the multimodal bridge. A session semaphore counts active
children rather than Agent types; each child also has single-invocation
admission. The parent’s approval policy is shared, and a semaphore serializes
classification and review. A separate operator gate serializes the operator
approval card with the child picker, so a pending review never delays the
picker. A scoped child label reaches the approval card, and review sees the
child’s context. No state lock is held while waiting for approval or a
concurrency slot.
Child clients are cached independently of parent, review, and compaction
clients by resolved provider, model, service tier, speed, and fitted output cap.
Changing thinking does not create a client. Parent model changes leave child
clients alive. Child images require both model imageInput and adapter image
capabilities. The multimodal path reuses MultimodalStreamingTurn and the
approved bridge, allocates media numbers from the parent, and supplies only
that child’s image map to its model. Text children never expose native image
tools. A child summarizer uses its own context budget and the configured
compaction prompt overlays; a configured compaction model is honored.
Each completed invocation updates its child ledger and the parent ledger once.
During execution, each logical model reservation and accepted tool batch updates
the child’s cumulative call counts through ChildSessionChanged, including
compaction calls and excluding retries. Text and image turns report counts at
the same reservation points. Continuations add to the invocation’s saved baseline;
final settlement uses that baseline so live counts are not added twice. Server
events and reconnect snapshots expose these same cumulative child counts.
Parallel increments and saved snapshots are serialized. Live cumulative usage
uses per-child snapshots rather than adding every stream update. The parent’s
last-request usage stays its own; child usage never replaces it. Missing usage
retains the existing unknown-total behavior. Failed retry attempts contribute
only their last reported usage snapshot. ContextEstimated carries local
estimates independently of provider TokenUsage.
SessionDocument.Children embeds child archives, compacted items, model and
gear snapshots, todos, usage, notes, and media references. Checkpoints taken while a parent waits for
children use its live model context, not the pre-turn transcript. Pending tool
calls receive checkpoint-only results identifying completed children or warning
that an interrupted operation may already have effects. These results never
modify the live turn. Children do not create
session files or appear in saved-session lists. Fork deep-copies child state,
resume restores counters directly, and clear removes it. Saved running or
queued children become interrupted rather than restarting side effects.
Child media is persisted before the parent JSON reference. Export inlines
available child media using the existing store.
ChildSessionChanged, ChildEventReceived, and ChildViewRequested convey
immutable event records; the latter is an inspection request, not engine focus.
The terminal owns parent/child event projections, the F7 child picker, read-only
child input routing, composer visibility, and the focused model/usage chrome.
Inactive events remain available when switching views. ApprovalPassed and
ApprovalReviewing (which names the primary or extended stage) use the same source-scoped event path; terminal approval
callbacks own only the shared modal, never the focused transcript or progress.
Runtime approval cards survive child completion and view switches without
restarting completed progress. Child tool batches publish TodosChanged and
refresh their stored todo snapshot before the next model round. The input pump
awaits CodingSession.EnqueueAsync for child inspection instead of discarding
an asynchronous command through the synchronous queue path. Parent events are
cached without being projected into a focused child, and restoring the parent
replays them without replaying submissions into the composer. Shared preferences,
completions, prompt history, image invalidation, queue state, plugin status, and
stats/side-question panel requests are applied once outside conversation replay.
Switching views cannot re-seed old prompt history, invalidate new draft image
attachments, or reopen dismissed panels. Live child usage and todo events update
the terminal’s picker snapshots without rebuilding the focused transcript. The
pickers refresh through the existing input polling loop and retain selection by
child id across active-status sorting. The read-only composer region shows the
child identity and Esc/F7 hints; the model status field retains the model name.
A shared modal retains input ownership during shortcut returns. Disabling Agents clears
the terminal’s child projection and navigation affordance. The terminal never
submits text to a child. Headless JSON labels child events and media provenance;
text output keeps the returned summary with the task result and reports child
usage separately.
Built-in child prompts are agents/general, agents/work, and agents/plan.
They do not reuse the parent Work or Plan body or those attachments. general
uses agents/general, and agents/plan when the parent turn is Plan. work
uses agents/work and is not offered during a parent Plan turn. explore
always uses agents/plan. Resolution
follows the named-prompt order, then appends only that agent’s attachments,
then the built-in child safety and role lines. Custom Agent prompt.md files
are not replaced or extended by prompt overlays, prompt sets, or prompt
attachments. They still receive the child safety rules and bound placeholders.
Approval is a ToolInvocationPolicy supplied to ToolExecutor. Rejection
returns Harness-authored ToolOutput. Tool exceptions become model-visible
only through a Harness ToolExceptionMapper.
Ordinary tool-call batches run serially. Work and Plan construct ToolExecutor
with serial mode and concurrency one. A host wrapper permits only adjacent
task groups to overlap, in both text and multimodal paths. Configurable
concurrency for ordinary tools remains deferred; do not reserve a field for it.
Image input boundary
Section titled “Image input boundary”CrystalCode.Engine owns image attachment, MIME signature validation,
session persistence, transcript markers, and projection onto Crystal’s typed
multimodal contracts. A front end owns only how it presents and edits the
markers in its composer. [Image #N] is presentation and persistence metadata;
providers receive typed ImageContent, never a marker in place of its bytes.
Pasted markers are atomic composer spans with a distinct color: cursor movement
and deletion cannot leave a partial attached marker. User-entered text with the
same spelling remains plain text. On submission, only attached spans receive an
invisible provenance prefix; only prefixed markers in transcript items produce
model images. The prefix is removed for display and text-only model requests.
Session JSON records whether markers have this prefix. Older sessions without
that flag tag references to their saved images on load, preserving their prior
semantics. Deleted unsent images are discarded immediately while idle and at
submission during an active turn. Workspace and clipboard images
are checked against the 20 MiB limit and validated by MIME signature before
they enter the session; the media store validates again before writing. Saved
image bytes live in owner-only, content-addressed files under
~/.crystal/media/<sha256>. Session JSON stores the hash and MIME type, not
Base64 bytes. The media file is written before the session references it, and
both writes use a temporary file followed by an atomic replacement. Sessions
persist only images referenced by the archive or the model context. A missing, truncated, or
modified media file is skipped on resume while the text and other attachments
remain available; the operator receives a note, and its reference is retained
on later saves so restoring the file can repair the session. Inline data is
a supported session representation; local saves move its image bytes to the
media store.
JSON session export retains marker provenance and inlines available image bytes
in data so its contents do
not depend on Home media files. If a referenced media file is unavailable, its
metadata remains in the export but bytes cannot be included. The store does
not automatically delete unreferenced media files.
Inline image bytes and absolute image URIs are supported. Images returned by
an in-process plugin, a dotnet operator tool’s native IMultimodalTool path,
or an exec tool with "output": "content" are assigned the same markers and
become input on the following model round. A text-only turn rejects exec
image results instead of dropping them.
Clipboard paste reserves its image number before waiting for the OS reader.
Tool images reserve numbers through the same session lock, which also protects
image lookup and mutation. A failed paste leaves a gap rather than reusing its
number. Input batches dispatch keys in order, so Ctrl+V finishes attaching
before a following Enter submits the prompt.
Dotnet multimodal tools are omitted from active catalogs when the selected
model or provider does not support image input. Declared audioInput or
videoInput does not keep them.
Resource description models are imageModel, audioModel,
videoModel, and documentModel in config.json, held by ResourceModels (one
ResourceModelSettings each, keyed by ResourceKind). Each has the same
fields as approvalModel: enabled, provider, model, thinkingEffort,
serviceTier, speed, and contextWindow. A model is on only with
enabled: true; a stored entry without it is off and unchecked. An enabled
model must name a catalog model that declares the corresponding input flag: imageInput,
audioInput, videoInput, or fileInput. Its slots must also be declared
by that model. Slots apply to
that model’s client only: unset tier or speed is not sent, unset context is
the model’s first declared budget, and the session /tier, /speed, and
/context choice does not apply. /describe (SessionVerb.Describe) and the
--image-*, --audio-*, --video-*, and --document-* launch flags set them; the option
catalog offers image_*, audio_*, video_*, and document_* model, thinking, tier,
speed, and context options under _crystal_describe, and chrome carries
Image, Audio, Video, and Document (SideModelChrome, null while off). Server
classifies a bare /describe, a kind, or <kind> model as operate and every
other form as admin.
Each enabled resource description model exposes its matching tool in Plan and Work. The tool sends the resource to that model in a separate request and returns text. view_image passes an image to the active model and is available only on image-capable turns. See Built-in tools for the supported input formats.
The Responses, OpenAI-compatible Chat Completions, DeepSeek Chat Completions,
Anthropic Messages, Gemini GenerateContent, and Ollama Chat adapters accept
text and image input and emit only text, reasoning, and tool-call events.
The native Gemini adapter sends tool-result images as inlineData parts on
functionResponse. That is the Gemini 3 multimodal function-response field;
an older model may reject the request. The native Ollama adapter sends them
on the tool message images array. Transcripts keep markers either way.
Chat Completions and Anthropic images
are restricted to user and tool messages, matching their wire contracts. Clipboard
image input is read through Windows PowerShell on Windows, the macOS system
osascript command on macOS, and wl-paste or xclip on Linux; it does not
capture the screen. Windows reads clipboard PNG bytes before falling back to
bitmap conversion, and passes Base64 text from PowerShell to the host. macOS
tries PNG, JPEG, and GIF clipboard representations in that order. Linux checks
advertised clipboard types and tries PNG, JPEG, GIF, and WebP in that order.
Reader output and temporary files are bounded by the image size limit. A
missing reader, an empty image clipboard, unsupported image bytes, an oversized
image, and a reader failure have separate operator errors. Reader commands are
optional at runtime, and their absence
does not prevent the application from starting. A model must
opt in with imageInput: true; unsupported combinations are rejected before
sending a request. audioInput, videoInput, and fileInput are stored
declarations published on plugin model facts and on PluginClientRequest.
The engine uses imageInput and adapter support to enable native attachments
and multimodal tools. Selected service tiers and speeds are
also published on both contracts; a custom protocol factory must apply a
non-null slot or reject it when the client is created. Audio, video, and document description requires an adapter that accepts the corresponding input for the selected model.
CrystalCode does not capture screenshots, control browsers, phones, virtual machines, interpret coordinates, or define frame/device protocols. External plugins own those behaviors and may return ordinary typed images through the generic tool boundary.