MCPcopy
hub / github.com/codeaashu/claude-code / autoCompactIfNeeded

Function autoCompactIfNeeded

src/services/compact/autoCompact.ts:241–351  ·  view source on GitHub ↗
(
  messages: Message[],
  toolUseContext: ToolUseContext,
  cacheSafeParams: CacheSafeParams,
  querySource?: QuerySource,
  tracking?: AutoCompactTrackingState,
  snipTokensFreed?: number,
)

Source from the content-addressed store, hash-verified

239}
240
241export async function autoCompactIfNeeded(
242 messages: Message[],
243 toolUseContext: ToolUseContext,
244 cacheSafeParams: CacheSafeParams,
245 querySource?: QuerySource,
246 tracking?: AutoCompactTrackingState,
247 snipTokensFreed?: number,
248): Promise<{
249 wasCompacted: boolean
250 compactionResult?: CompactionResult
251 consecutiveFailures?: number
252}> {
253 if (isEnvTruthy(process.env.DISABLE_COMPACT)) {
254 return { wasCompacted: false }
255 }
256
257 // Circuit breaker: stop retrying after N consecutive failures.
258 // Without this, sessions where context is irrecoverably over the limit
259 // hammer the API with doomed compaction attempts on every turn.
260 if (
261 tracking?.consecutiveFailures !== undefined &&
262 tracking.consecutiveFailures >= MAX_CONSECUTIVE_AUTOCOMPACT_FAILURES
263 ) {
264 return { wasCompacted: false }
265 }
266
267 const model = toolUseContext.options.mainLoopModel
268 const shouldCompact = await shouldAutoCompact(
269 messages,
270 model,
271 querySource,
272 snipTokensFreed,
273 )
274
275 if (!shouldCompact) {
276 return { wasCompacted: false }
277 }
278
279 const recompactionInfo: RecompactionInfo = {
280 isRecompactionInChain: tracking?.compacted === true,
281 turnsSincePreviousCompact: tracking?.turnCounter ?? -1,
282 previousCompactTurnId: tracking?.turnId,
283 autoCompactThreshold: getAutoCompactThreshold(model),
284 querySource,
285 }
286
287 // EXPERIMENT: Try session memory compaction first
288 const sessionMemoryResult = await trySessionMemoryCompaction(
289 messages,
290 toolUseContext.agentId,
291 recompactionInfo.autoCompactThreshold,
292 )
293 if (sessionMemoryResult) {
294 // Reset lastSummarizedMessageId since session memory compaction prunes messages
295 // and the old message UUID will no longer exist after the REPL replaces messages
296 setLastSummarizedMessageId(undefined)
297 runPostCompactCleanup(querySource)
298 // Reset cache read baseline so the post-compact drop isn't flagged as a

Callers

nothing calls this directly

Calls 13

isEnvTruthyFunction · 0.85
shouldAutoCompactFunction · 0.85
getAutoCompactThresholdFunction · 0.85
runPostCompactCleanupFunction · 0.85
featureFunction · 0.85
notifyCompactionFunction · 0.85
markPostCompactionFunction · 0.85
compactConversationFunction · 0.85
hasExactErrorMessageFunction · 0.85
logForDebuggingFunction · 0.85

Tested by

no test coverage detected