Compaction
Crystal does not reduce context. Before each model round, and again
before the post-turn compaction check, optional microcompaction may
replace old successful tool results with Tool result omitted after compaction. It does not call a model. The last protectTurns user
turns stay intact, then the newest protectTokens of older successful
results stay intact. Older successful results are replaced only when
the estimated size of the removed text is more than minimumTokens.
The placeholder that replaces them is not subtracted from that estimate.
User text, assistant text, and
failed results stay. The walk stops at the previous summary. The
archive, the screen, resume, fork, and export keep the original tool
text. A rewrite is saved on the model transcript. The following compact
decision then uses that transcript’s estimate, because the previous
provider usage still counts the removed text. Microcompaction is off
when microCompaction is omitted. /compact micro toggles it, and
on or off sets it, writes config.json, and does not summarize.
It is refused during a turn or compaction. /status adds a
Microcompaction row only while it is on. Defaults are 2 turns, 40000
protected tokens, and 20000 minimum tokens. protectTurns must be at
least 1. The token counts must be non-negative. Invalid values refuse
startup. Full compaction’s own prune does not follow this switch.
Resource trimming is a projection of the outbound request, not a change to the
transcript. ResourceTrimmer (one per session and one per image-capable child
run) chooses which held resources MultimodalTranscript.Convert expands into
bytes; MultimodalStreamingTurn asks it before each model call. A resource it
omits is converted to its marker text such as [Image #N], the existing
behavior for a marker with no held image. The transcript, _images, the saved session,
fork, and export are untouched. Omission is one-way for the life of the
trimmer, so a trimmed resource does not return when a newer one arrives and the
request prefix, which a provider may cache, changes only when a trim fires.
Automatic trimming fires when the trimmable resources in the transcript exceed
keepRecent + slack, and then keeps the newest keepRecent. A byte budget
(maxBytes, 0 for none) fires at once and drops the oldest trimmable resources
until the inline bytes fit, always keeping the newest. Trimmable means a
resource referenced by a tool result, plus operator-attached ones when
includeUserResources is set. resourceTrim in config.json holds enabled
(true), keepRecent (16, at least 1), slack (8), maxBytes (134217728), and
includeUserResources (false); the object is omitted when all are default and
invalid values refuse startup. A provider definition in providers.json may
carry a resourceTrim object with keepRecent, slack, maxBytes, and
includeUserResources. Each value it sets replaces the global one for that
provider’s models (HarnessSettings.EffectiveResourceTrim); enabled stays
global. When a later provider file overlays the same name and protocol, its
object replaces the earlier one. /trim with no argument or a count trims to
that many now, all keeps none, and on or off switches automatic
trimming and writes config.json. It is refused during a turn or
compaction. The omissions live in memory: /clear and resume reset them and
the limits apply again on the next request. A 413 is not handled separately.
Reserved output is reservedOutputTokens when set. Otherwise it is
the smallest of 20000, the model maxTokens, and a quarter of the
window, so a small window keeps most of itself for input. The
compaction ceiling is the lesser of the configured fraction of the
window and the window minus the reservation. Raising the reservation
lowers that ceiling, and lengthens the reply, only when the reservation
is already the tighter of the two. While the fraction leaves a larger
gap, a bigger reservation changes neither. A model request asks for
at most min(maxTokens, window - ceiling), so the prompt and the reply
fit the window together. A model without maxTokens sends no cap and
keeps the provider default. Switching the selected context budget
rebuilds the session client and drops the cached plugin session client,
plugin image client, and image-description client, because each output
cap is fixed when that client is opened. The review client is dropped
when its own budget or output cap changes, including when review uses
the session model.
The size that is compared with that limit is the last finished model round’s provider-reported input plus output, plus a local estimate of the items added after the final item of that round (normally tool results). The report is the anchor. It is matched by item identity, so a rewrite of the transcript, such as microcompaction or compaction, drops the anchor and the next check estimates the whole list until a round reports again. A round with no usage from the endpoint sets no anchor. Without an anchor, the whole list is estimated and the last reported usage is checked beside it. With one, the anchor already holds that report. A reasoning block counts once: the larger of its readable text and its provider state, because that state repeats the text.
When that size crosses the lesser of the configured fraction of the model context window and the usable window (context minus reserved output), the host:
- Clears old tool results outside a protected recent band of 2 user turns and 40000 tokens, when that frees more than 20000 tokens.
- Asks for one structured summary of older turns, folding any
previous summary, and keeps a recent tail verbatim. The tail is 25%
of the usable window, at least 2000 tokens and at most 32000. That
summary request follows the same
retrypolicy as a model round. The session model writes it unlesscompactionModelis enabled. The summary prompt caps its reply at one quarter of the compact ceiling, at mostmin(writer maxTokens, 16384), and never more than half the effective summary window, so the result lands below the ceiling that would trigger the next compaction. The writer is the session model, or the compaction model when that is on. A writer withoutmaxTokensstill sends that cap. The cap is fixed on the summary client. Crystal’sChatRequestcannot lower one call, and the session client keeps the turn cap. A summary whose finish reason islengthis not stored. - Stops if the summary request itself cannot fit or the summarizer returns nothing and prune did not help. The turn does not retry compaction in a loop.
CTX percent uses the last model round’s provider usage while a round is
streaming, then a separately marked ~ estimate after each tool batch until
the next round reports. That estimate is the anchored size above, so it adds
only the new tool results to the last report. Estimates never replace saved
provider usage and are not part of cumulative usage. CTX is not the sum of rounds in
the turn. The status bar can show 100% when usage meets or exceeds the
window. Compaction does not block the session loop: the progress row
stays on Compacting and the composer remains usable.
/compact (alias /summarize) runs immediately and does not wait for
the threshold. When the retained tail already holds every turn, it still
summarizes everything before the latest user turn. A session with nothing
before that turn prints Nothing earlier to compact. It is refused while
a turn is running. /compact full takes no argument. It folds the whole conversation, including
the latest user turn, into the summary and keeps no tail, so the model
context becomes the live system prompt and the summary. It follows the same
display rules as /compact and prints Nothing earlier to compact when the
session has no conversation. /compact model, /compact thinking,
/compact tier, /compact speed, and /compact context show or set the
optional summarizer, its gear, and its own service tier, speed, and context
budget. /compact summary toggles
showCompactionSummary, and /compact auto (alias automatic) toggles
showAutomaticCompactionSummary. /compact micro toggles microcompaction.
Any of those commands accepts on or off, writes config.json, and does
not summarize. Any other argument is rejected.
compactionModel in config.json is enabled, provider, model,
and optional thinkingEffort, serviceTier, speed, and contextWindow.
An omitted object means off, and enabled: false keeps a stored provider, model, gear,
and slots unused. A slot applies to the summarizer only, must be listed by
its model, and sends no tier or speed when unset; an unset context is the
model’s first declared budget. /tier, /speed, and /context change only
the session client, never an approval, extended approval, compaction, or
image client on the same model.
While off, the summary request uses the session model and omits
reasoning. It does not reuse the session client, because that client
keeps the turn output cap. The host opens a summary client with the
summary reply cap, and opens it again when the model, tier, speed, context
budget, or cap changes. While on, the host opens a separate client and maps that
model’s gear the same way as the approval model: no thinking omits
reasoning, off disables it when the model allows that, and default
or an unsupported gear uses the provider default without changing the
saved gear. Changing the session model does not replace that client.
A side question that must summarize first opens its own summary client
and releases it; the answer still uses the session model.
The trigger, retained tail, and CTX percent stay on the session
window. The summary prompt budget is the smaller of that window and
the compaction model’s own context budget. A summary that cannot fit
takes the existing path that does not write one. /status adds a
Compaction model row only while the switch is on.
crystal, crystal space, and crystal run accept
--compaction-model on|off, --compaction-provider,
--compaction-model-id, --compaction-thinking, --compaction-tier,
--compaction-speed, and --compaction-context for one process.
Those flags are not written to config.json. on needs a saved
selection or a provider and model id on the same command.
User and assistant text in the folded head are replaced
by the summary; they are not kept beside it. The screen keeps the earlier
lines. When showCompactionSummary is on (the default; omitted from
config.json when on, false when off), a manual /compact prints the
stored summary under those lines in a rounded panel titled Earlier context.
Automatic compaction prints Compacted context only, unless
showAutomaticCompactionSummary is on. That switch defaults off, is omitted
from config.json until enabled, and uses the same panel. It does not change
/compact itself. A compaction with no summary text does not print one. A side
question that summarizes a private copy does not print it.
A session holds an exclusive operating system lock on
~/.crystal/sessions/<id>.lock for the id it has open (SessionStore.TryLock).
The lock ends with the process, so a crash leaves nothing to release. The
empty lock file stays on disk after a clean exit, because deleting it would
let two holders lock different files. Resuming a session that is already open
fails with Session is already open <id>, at launch and in /resume. A
launch that loses the race fails when the session is created. /clear,
/fork, and --fork take a new id and are not affected. Listing and reading
stay unlocked.
Session data is saved to the selected backend after each
completed turn, after a child invocation settles, after a successful /compact,
and on an orderly exit
when the transcript has a user message or a compaction summary. A running
turn is also checkpointed: after its user message is added, after each model
round, and after each tool batch is committed to the archive. A checkpoint
uses the live model context, and a tool call without a result gets the
checkpoint-only result described for child checkpoints; the live turn is not
changed. A turn that ends without a result, including a recalled message, is
saved again with the state the next turn starts from. A checkpoint that cannot
be written prints one note and does not fail the turn. A process that is killed
or loses power therefore loses at most the model round or tool batch in flight.
Child invocations are not checkpointed while they run; the parent checkpoint
records them as unfinished. The session stores the compacted model transcript (live system prompt, one
summary, recent tail, and reasoning items with their readable text and
opaque provider state), the last usage snapshot, and cumulative provider usage.
Switchable thinking-chain compression is deferred product work. The host
does not, after a thinking pass, ask a model to compress and summarize
that thinking according to a requirement. Context compaction,
microcompaction, verboseThinking, and Anthropic thinkingDisplay
summarized are not that path. No prompt file, configuration field, or
command is reserved for it.
crystal --resume (-r) opens a terminal selector for this workspace.
crystal --resume <id> loads that file and stays in the process workspace.
crystal --resume <path> lists that directory, asks for trust before the
selector, and enters the directory after a session is chosen. Escape leaves
the process workspace unchanged. crystal --resume all lists every workspace,
shows each path, and enters the chosen session’s workspace after trust.
--workspace and --resume <path> must name the same directory when both
are set. A missing or empty session exits without entering the TTY.
/resume, /resume <path>, and /resume all use the same rules inside a
running session. /resume <id> restores that transcript and stays in the
current workspace. The word all is reserved. A value that is both an
existing directory and a session id is rejected. After a workspace change,
the live system prompt is refreshed from that directory’s Plan, Work, or custom-mode text;
the summary and tail are kept. The selector lists resumable sessions newest
first by update time, supports typing to filter by id, preview, or workspace
path, and leaves the current session untouched on Escape. Both terminal entry
points map session summaries to Display ResumeOption values through
SessionPicker. Display ResumePicker owns search, selection, and the
height-based list viewport and paints the scrollbar with
TranscriptScrollbar. SessionRenderer pauses the composer, routes decoded
input to the page, and restores the previous frame on exit. Wheel input
scrolls the list and moves the selection only when it would leave the
viewport. Usage is restored
so the status bar, /status, and the next compact decision
have a baseline. Sessions saved before cumulative usage was introduced retain
an unknown cumulative value rather than treating their last request as the
whole session. /clear starts a new id.
/sessions lists resumable sessions for the current workspace in descending
update order; /sessions all includes every workspace. The current id is
marked and every row keeps the complete id for use with /resume <id> or
/fork <id>. Empty and unreadable session files are omitted.
Session topics. TopicModelSettings (topicModel in config.json) holds
the switch, an optional own provider and model, the thinking gear, and own
tier, speed, and context. HarnessSettings.ForTopic returns the session
settings unchanged when there is no own model, so the session tier, speed,
and context apply; with an own model it uses the same ForModel path as the
side models. CodingSession keeps the topic and whether the operator set it
under _topicGate. After a completed turn, StartTopicIfNeeded runs one
background request (Task.Run, cancelled by /clear, resume, a manual
topic, and close) on a separate client that keeps the model’s own output
cap, because reasoning tokens count against it, the
topic.md system text, and CompactionText of the archive cut to 8000
characters. SessionActivity.NamingTopic (naming_topic on the wire,
Naming Topic in the progress row) is set while the request runs and only
when no turn or compaction owns the row. It starts after TurnFinished
is published, because the turn footer clears the progress row. A
New conversation answer clears the attempted flag so the next completed
turn asks again; a failed or cut reply does not. Only a cancellation of the
naming token itself is silent; a provider timeout, which also surfaces as a
cancellation, is a failure that says the request timed out and clears the
running request. The reply is read inside the request’s try and handled
outside it, so a session save that fails after naming keeps the topic in
memory and reports not saved once instead of a naming failure. The request
starts with no origin and no input capture, like a turn or a side question, so its notes,
ChromeChanged, and activity reach every Server client and every Bridge
session and never fail the request that asked for it. A turn may start while
naming runs: naming keeps its own client, and when it ends inside a turn it
does not clear the turn’s progress row. A generation counter drops a stale
reply. A reply with no text says why: cut at the output limit, a tool call,
or empty. The result is
normalized by SessionTopic (one line, no quotes or trailing period, at most
80 characters); New conversation is treated as no answer. The session is
saved and ChromeChanged carries SessionChrome.Topic. The session file
stores topic and topicSource (model or operator); SessionSummary
and SavedSessionInfo carry Topic, and SessionSummary.Title falls back
to the first user message. Bridge sends session_info_update with the new
title when ChromeChanged changes the engine session id or topic. It uses
the id and workspace from the same event. The title is the topic, or the first
user message when the topic is empty, or an empty string when the conversation
has neither. ConversationCleared carries that title with the new engine id.
/topic is SessionVerb.Topic; Server treats a bare /topic as operate and
every other form as admin. The option catalog offers topic, topic_model
(session plus catalog models), and topic_thinking, plus topic_tier,
topic_speed, and topic_context for an own model. /clear, /resume, and
/fork publish ChromeChanged before ConversationCleared or HistoryReplayed.
The snapshot chrome, including the session id and topic, updates only from
SessionStarted and ChromeChanged. /clear and a fork start without a
topic.
/fork first persists the current conversation, copies its transcript,
compaction summary, todos, mode, counters, and usage baseline to a new id, and
continues on that id. The source snapshot remains available under its original
id and is not overwritten by the branch. /fork <id> branches a saved session
instead. A branch uses the current workspace and a refreshed live system
prompt. Forking stops a running turn before taking the snapshot; listing
sessions does not.