data/services/compact_service library

Classes

AutoCompactTrackingState
Autocompact tracking state.
CompactionResult
Result of a compaction operation.
CompactMessage
A message in the conversation.
CompactProgressEvent
Compact progress event sent to UI.
ContentBlock
A content block inside a message.
MicrocompactResult
Result of a microcompact operation.
RecompactionInfo
Diagnosis context passed from autoCompactIfNeeded into compactConversation.
SessionMemoryCompactConfig
Configuration for session memory compaction thresholds.
TimeBasedMCConfig
Configuration for time-based microcompact trigger.
TokenWarningState
Token warning state result.

Enums

CompactHookType
Hook type for compact progress.
CompactProgressType
Compact progress event type.
CompactTrigger
Compact trigger origin.
ContentBlockType
Content block type within a message.
MessageRole
Lightweight message role (mirrors TS Message.type).
PartialCompactDirection
Direction for partial compact.

Constants

autocompactBufferTokens → const int
Buffer tokens for auto-compact threshold.
compactableTools → const Set<String>
Set of tool names that can be microcompacted.
defaultSmCompactConfig → const SessionMemoryCompactConfig
errorMessageIncompleteResponse → const String
errorMessageNotEnoughMessages → const String
errorMessagePromptTooLong → const String
errorMessageUserAbort → const String
errorThresholdBufferTokens → const int
Error threshold buffer tokens.
manualCompactBufferTokens → const int
Manual compact buffer tokens.
maxConsecutiveAutocompactFailures → const int
Max consecutive autocompact failures before circuit breaker trips.
maxOutputTokensForSummary → const int
Reserve this many tokens for output during compaction.
postCompactMaxFilesToRestore → const int
Post-compact constants.
postCompactMaxTokensPerFile → const int
postCompactMaxTokensPerSkill → const int
postCompactSkillsTokenBudget → const int
postCompactTokenBudget → const int
timeBasedMCClearedMessage → const String
Sentinel for cleared tool result content.
warningThresholdBufferTokens → const int
Warning threshold buffer tokens.

Properties

isCompactWarningSuppressed bool
Whether the compact warning is currently suppressed.
no setter

Functions

adjustIndexToPreserveAPIInvariants(List<CompactMessage> messages, int startIndex) int
Adjust the start index to ensure we don't split tool_use/tool_result pairs or thinking blocks that share the same message.id with kept assistant messages.
annotateBoundaryWithPreservedSegment(CompactMessage boundary, String anchorUuid, List<CompactMessage>? messagesToKeep) CompactMessage
Annotate a compact boundary with relink metadata for messagesToKeep.
buildPostCompactMessages(CompactionResult result) List<CompactMessage>
Build the base post-compact messages array from a CompactionResult. Ensures consistent ordering across all compaction paths.
calculateMessagesToKeepIndex(List<CompactMessage> messages, int lastSummarizedIndex) int
Calculate the starting index for messages to keep after compaction.
calculateTokenWarningState(int tokenUsage, String model, int contextWindow, {bool autoCompactEnabled = true}) TokenWarningState
Calculate the token warning state given current usage.
clearCompactWarningSuppression() → void
Clear the suppression flag at start of new microcompact attempt.
collectCompactableToolIds(List<CompactMessage> messages) List<String>
Collect tool_use IDs whose tool name is compactable.
estimateMessageTokens(List<CompactMessage> messages) int
Estimate token count for messages — pads by 4/3 to be conservative.
evaluateTimeBasedTrigger(List<CompactMessage> messages, String? querySource) → ({TimeBasedMCConfig config, double gapMinutes})?
Evaluate whether the time-based microcompact trigger should fire.
formatCompactSummary(String summary) String
Formats the compact summary by stripping the <analysis> drafting scratchpad.
getAutoCompactThreshold(String model, int contextWindow) int
Calculate the auto-compact threshold.
getCompactPrompt({String? customInstructions}) String
Get the full compact prompt.
getCompactUserSummaryMessage(String summary, {bool suppressFollowUpQuestions = false, String? transcriptPath, bool recentMessagesPreserved = false}) String
Get the compact user summary message content.
getEffectiveContextWindowSize(String model, int contextWindow) int
Returns the context window size minus the max output tokens for the model.
getPartialCompactPrompt({String? customInstructions, PartialCompactDirection direction = PartialCompactDirection.from}) String
Get the partial compact prompt.
getSessionMemoryCompactConfig() SessionMemoryCompactConfig
getTimeBasedMCConfig() TimeBasedMCConfig
groupMessagesByApiRound(List<CompactMessage> messages) List<List<CompactMessage>>
Group messages by API round. The preamble (all messages up to and including the first assistant message) forms group 0. Each subsequent assistant message starts a new group (the assistant + all following user/attachment messages until the next assistant).
hasTextBlocks(CompactMessage message) bool
Check if a message contains text blocks (text content for user/assistant).
maybeTimeBasedMicrocompact(List<CompactMessage> messages, String? querySource) MicrocompactResult?
Time-based microcompact: content-clear old tool results when the gap since the last assistant message exceeds the threshold.
mergeHookInstructions(String? userInstructions, String? hookInstructions) String?
Merges user-supplied custom instructions with hook-provided instructions.
microcompactMessages(List<CompactMessage> messages, {String? querySource}) MicrocompactResult
Run microcompact on messages. Returns original messages if no compaction needed.
registerPostCompactCleanup(PostCompactCleanupCallback callback) → void
Register a callback to run after compaction.
resetSessionMemoryCompactConfig() → void
roughTokenCountEstimation(String text) int
Rough token count estimation using ~4 chars per token.
roughTokenCountEstimationForMessages(List<CompactMessage> messages) int
Rough token count for a JSON-serializable object.
runPostCompactCleanup(String? querySource) → void
Run all registered post-compact cleanup callbacks.
setSessionMemoryCompactConfig(SessionMemoryCompactConfig config) → void
setTimeBasedMCConfig(TimeBasedMCConfig config) → void
shouldAutoCompact(List<CompactMessage> messages, String model, int contextWindow, int tokenCount, {String? querySource, bool autoCompactEnabled = true, int snipTokensFreed = 0}) bool
Determine whether auto-compact should run.
stripImagesFromMessages(List<CompactMessage> messages) List<CompactMessage>
Strip image blocks from user messages before sending for compaction. Images are not needed for generating a conversation summary.
suppressCompactWarning() → void
Suppress the compact warning (after successful microcompact).
truncateHeadForPTLRetry(List<CompactMessage> messages, int? tokenGap) List<CompactMessage>?
Drops the oldest API-round groups from messages until tokenGap is covered. Returns null when nothing can be dropped without leaving an empty summarize set.
truncateToTokens(String content, int maxTokens) String
Truncate content to roughly maxTokens, keeping the head.

Typedefs

PostCompactCleanupCallback = void Function(String? querySource)
Callbacks for post-compact cleanup.