| 514 | } |
| 515 | |
| 516 | function trimHistory() { |
| 517 | if (messages.length <= MAX_HISTORY_MESSAGES) return; |
| 518 | // Find a safe cut point — don't break mid-tool-call sequence. |
| 519 | // Walk forward from the trim target to find a user message boundary. |
| 520 | let cut = messages.length - MAX_HISTORY_MESSAGES; |
| 521 | while (cut < messages.length && messages[cut].role !== "user") { |
| 522 | cut++; |
| 523 | } |
| 524 | if (cut > 0 && cut < messages.length) { |
| 525 | messages.splice(0, cut); |
| 526 | } |
| 527 | } |
| 528 | |
| 529 | function getEstimatedTokenMinuteLog(firstIterationMinuteBucket) { |
| 530 | return Array.from(minuteTokenMap.entries()) |