context_compressor_window.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. """Compaction window planning for ContextCompressor: the head/middle/tail boundaries that compress() and
  2. the opt-in prepared-compaction pass (agent/prepared_compaction.py) both plan, and the splice of a prepared
  3. summary into that window."""
  4. from __future__ import annotations
  5. from typing import Any, Optional
  6. from agent.context_compressor_tail import tail_cut_progress_floor
  7. from agent.prepared_compaction import PreparedCompaction, PreparedSummary
  8. class CompactionWindowMixin:
  9. """Window planning shared by compress() and the background pass."""
  10. # Set by agent_init when compression.prepare_ahead is on; None leaves compress() inline as before.
  11. prepared_compaction: Optional[PreparedCompaction] = None
  12. def _compress_window(self, messages: list[dict[str, Any]]) -> tuple[int, int]:
  13. """Return ``(compress_start, compress_end)`` for the summarizable middle."""
  14. compress_start = self._align_boundary_forward(messages, self._protect_head_size(messages))
  15. compress_end = self._find_tail_cut_by_tokens(messages, compress_start)
  16. # A role collision can merge the summary into the first tail row; keep an actionable user
  17. # event out of that slot by retaining an older assistant/tool bridge. The bridge never moves
  18. # the cut below the progress floor: a bridge that leaves only handoff rows in the window
  19. # would no-op with ``empty_post_handoff_window`` at every trigger.
  20. latest_actionable_idx = self._find_last_user_message_idx(messages, 0)
  21. if compress_end == latest_actionable_idx:
  22. bridge_idx = latest_actionable_idx - 1
  23. bridge_role = messages[bridge_idx].get("role") if bridge_idx >= 0 else None
  24. if bridge_role == "tool":
  25. bridge_idx = self._align_boundary_backward(messages, latest_actionable_idx)
  26. elif bridge_role != "assistant":
  27. bridge_idx = -1
  28. if bridge_idx >= tail_cut_progress_floor(self, messages, compress_start, bridge_idx):
  29. compress_end = bridge_idx
  30. return compress_start, compress_end
  31. def _plan_compaction_window(self, messages: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], int, int, int]:
  32. """Phases 1-2 of compress(): ``(working, pruned_count, compress_start, compress_end)``.
  33. ``working`` is a pruned copy without blank echoes; the boundaries index into it."""
  34. working, pruned_count = self._prune_old_tool_results(
  35. messages, protect_tail_count=self.protect_last_n, protect_tail_tokens=self.tail_token_budget,
  36. )
  37. working = self._drop_blank_echoes(working)
  38. compress_start, compress_end = self._compress_window(working)
  39. return working, pruned_count, compress_start, compress_end
  40. def _take_prepared_summary(
  41. self, messages: list[dict[str, Any]], compress_start: int, *, fresh: bool, provider_context: bool,
  42. ) -> Optional[PreparedSummary]:
  43. """The summary prepared in the background for this window, which an automatic compaction splices at
  44. ITS boundary; every newer message stays outside the summary, in the tail. ``fresh`` compactions
  45. (manual, focus, overflow recovery, memory-provider context) summarize anew, and once a memory
  46. provider supplies context no further summaries are prepared (each would be thrown away)."""
  47. if self.prepared_compaction is None:
  48. return None
  49. if provider_context:
  50. self.prepared_compaction.stop_for_provider_context()
  51. return self.prepared_compaction.take(
  52. messages, self._session_id, compress_start, eligible=not (fresh or provider_context),
  53. )
  54. def _adopt_prepared_summary(self, prepared: PreparedSummary) -> str:
  55. """Adopt a prepared summary as an inline summary call would have left it; returns the handoff text."""
  56. from agent.prepared_compaction import adopt
  57. adopt(self, prepared)
  58. return prepared.summary