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