compaction_display.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. """Client-facing projection helpers for model-only compaction carriers."""
  2. from __future__ import annotations
  3. from typing import Any, Dict, Optional
  4. from agent.context_compressor import ContextCompressor, is_compaction_summary_message
  5. _COMPACTION_INTERNAL_FIELDS = (
  6. "tool_calls",
  7. "finish_reason",
  8. "reasoning",
  9. # Provider replay/metadata fields that ride the wire on every request but are invisible to
  10. # ``msg["content"]``/``msg["tool_calls"]`` accounting. Codex Responses sessions in particular carry
  11. # ``codex_reasoning_items`` blobs of ``encrypted_content`` that can dominate the serialized session (a
  12. # measured 214-turn session held ~115K tokens / 27% of its payload there — #55572).
  13. # ``reasoning_details`` is handled separately (see ``_reasoning_details_text_chars``): its signed/base64
  14. # envelope is excluded from the budget, mirroring the preflight estimator's exclusion in
  15. # ``model_metadata._estimate_message_tokens_without_images`` (#73298).
  16. # An assistant turn may carry only reasoning/thinking content with no visible text (extended-thinking
  17. # turns, thinking-only recovery responses). Such a turn is persisted with its reasoning fields and is
  18. # recallable from the transcript, but dropping it here as "empty" makes it vanish from the
  19. # resumed/reloaded session view while the desktop's reasoning disclosure has nothing to render. Keep it
  20. # when it carries reasoning so the "Thinking…" block still shows. (#44022)
  21. "reasoning_content",
  22. "reasoning_details",
  23. "codex_reasoning_items",
  24. "codex_message_items",
  25. )
  26. def project_compaction_message_for_display(message: dict[str, Any]) -> Optional[dict[str, Any]]:
  27. """Return authentic transcript content, or ``None`` for a pure handoff.
  28. Model-facing recovery history retains the complete carrier. Display
  29. projections instead remove the handoff, inherited tool state, and internal
  30. reasoning while preserving any real prior-tail content or live user ask
  31. embedded in the carrier.
  32. """
  33. if not isinstance(message, dict):
  34. return None
  35. if not is_compaction_summary_message(message):
  36. return message.copy()
  37. projected = ContextCompressor._strip_context_summary_handoff_message(message)
  38. if projected is None:
  39. return None
  40. projected = projected.copy()
  41. for key in _COMPACTION_INTERNAL_FIELDS:
  42. projected.pop(key, None)
  43. projected.pop("display_kind", None)
  44. return projected