MCPcopy Index your code
hub / github.com/claude-code-best/claude-code / autoCompactIfNeeded

Function autoCompactIfNeeded

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

Source from the content-addressed store, hash-verified

268}
269
270export async function autoCompactIfNeeded(
271 messages: Message[],
272 toolUseContext: ToolUseContext,
273 cacheSafeParams: CacheSafeParams,
274 querySource?: QuerySource,
275 tracking?: AutoCompactTrackingState,
276 snipTokensFreed?: number,
277): Promise<{
278 wasCompacted: boolean
279 compactionResult?: CompactionResult
280 consecutiveFailures?: number
281}> {
282 if (isEnvTruthy(process.env.DISABLE_COMPACT)) {
283 return { wasCompacted: false }
284 }
285
286 // Circuit breaker: stop retrying after N consecutive failures.
287 // Without this, sessions where context is irrecoverably over the limit
288 // hammer the API with doomed compaction attempts on every turn.
289 if (
290 tracking?.consecutiveFailures !== undefined &&
291 tracking.consecutiveFailures >= MAX_CONSECUTIVE_AUTOCOMPACT_FAILURES
292 ) {
293 return { wasCompacted: false }
294 }
295
296 const model = toolUseContext.options.mainLoopModel
297 const shouldCompact = await shouldAutoCompact(
298 messages,
299 model,
300 querySource,
301 snipTokensFreed,
302 )
303
304 if (!shouldCompact) {
305 return { wasCompacted: false }
306 }
307
308 const recompactionInfo: RecompactionInfo = {
309 isRecompactionInChain: tracking?.compacted === true,
310 turnsSincePreviousCompact: tracking?.turnCounter ?? -1,
311 previousCompactTurnId: tracking?.turnId,
312 autoCompactThreshold: getAutoCompactThreshold(model),
313 querySource,
314 }
315
316 // EXPERIMENT: Try session memory compaction first
317 const sessionMemoryResult = await trySessionMemoryCompaction(
318 messages,
319 toolUseContext.agentId,
320 recompactionInfo.autoCompactThreshold,
321 )
322 if (sessionMemoryResult) {
323 // Reset lastSummarizedMessageId since session memory compaction prunes messages
324 // and the old message UUID will no longer exist after the REPL replaces messages
325 setLastSummarizedMessageId(undefined)
326 runPostCompactCleanup(querySource)
327 // Reset cache read baseline so the post-compact drop isn't flagged as a

Callers

nothing calls this directly

Calls 12

shouldAutoCompactFunction · 0.85
getAutoCompactThresholdFunction · 0.85
runPostCompactCleanupFunction · 0.85
notifyCompactionFunction · 0.85
markPostCompactionFunction · 0.85
compactConversationFunction · 0.85
hasExactErrorMessageFunction · 0.85
isEnvTruthyFunction · 0.50
logErrorFunction · 0.50
logForDebuggingFunction · 0.50

Tested by

no test coverage detected