( messages: Message[], toolUseContext: ToolUseContext, cacheSafeParams: CacheSafeParams, querySource?: QuerySource, tracking?: AutoCompactTrackingState, snipTokensFreed?: number, )
| 268 | } |
| 269 | |
| 270 | export 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 |
nothing calls this directly
no test coverage detected