( messages: Message[], querySource: QuerySource | undefined, )
| 454 | } |
| 455 | |
| 456 | function maybeTimeBasedMicrocompact( |
| 457 | messages: Message[], |
| 458 | querySource: QuerySource | undefined, |
| 459 | ): MicrocompactResult | null { |
| 460 | const trigger = evaluateTimeBasedTrigger(messages, querySource) |
| 461 | if (!trigger) { |
| 462 | return null |
| 463 | } |
| 464 | const { gapMinutes, config } = trigger |
| 465 | |
| 466 | const compactableIds = collectCompactableToolIds(messages) |
| 467 | |
| 468 | // Floor at 1: slice(-0) returns the full array (paradoxically keeps |
| 469 | // everything), and clearing ALL results leaves the model with zero working |
| 470 | // context. Neither degenerate is sensible — always keep at least the last. |
| 471 | const keepRecent = Math.max(1, config.keepRecent) |
| 472 | const keepSet = new Set(compactableIds.slice(-keepRecent)) |
| 473 | const clearSet = new Set(compactableIds.filter(id => !keepSet.has(id))) |
| 474 | |
| 475 | if (clearSet.size === 0) { |
| 476 | return null |
| 477 | } |
| 478 | |
| 479 | let tokensSaved = 0 |
| 480 | const result: Message[] = messages.map(message => { |
| 481 | if (message.type !== 'user' || !Array.isArray(message.message.content)) { |
| 482 | return message |
| 483 | } |
| 484 | let touched = false |
| 485 | const newContent = message.message.content.map(block => { |
| 486 | if ( |
| 487 | block.type === 'tool_result' && |
| 488 | clearSet.has(block.tool_use_id) && |
| 489 | block.content !== TIME_BASED_MC_CLEARED_MESSAGE |
| 490 | ) { |
| 491 | tokensSaved += calculateToolResultTokens(block) |
| 492 | touched = true |
| 493 | return { ...block, content: TIME_BASED_MC_CLEARED_MESSAGE } |
| 494 | } |
| 495 | return block |
| 496 | }) |
| 497 | if (!touched) return message |
| 498 | return { |
| 499 | ...message, |
| 500 | message: { ...message.message, content: newContent }, |
| 501 | } |
| 502 | }) |
| 503 | |
| 504 | if (tokensSaved === 0) { |
| 505 | return null |
| 506 | } |
| 507 | |
| 508 | logEvent('ncode_time_based_microcompact', { |
| 509 | gapMinutes: Math.round(gapMinutes), |
| 510 | gapThresholdMinutes: config.gapThresholdMinutes, |
| 511 | toolsCleared: clearSet.size, |
| 512 | toolsKept: keepSet.size, |
| 513 | keepRecent: config.keepRecent, |
no test coverage detected