agent_init_compression_notice.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. """Init-time compression banner and the once-per-profile Codex gpt-5.x autoraise notice."""
  2. from __future__ import annotations
  3. from contextlib import suppress
  4. from typing import Any, Optional
  5. from hermes_constants import get_hermes_home
  6. def _build_codex_gpt5_autoraise_notice(
  7. autoraise: dict[str, Any], context_length: Optional[int] = None
  8. ) -> str:
  9. """One-time notice when Codex gpt-5.x raises compaction (``autoraise``: model/from/to).
  10. ``context_length`` is the live-resolved window (Codex's catalog shifts server-side) so the
  11. banner reports what this session got. Printed for CLI and replayed via status_callback for
  12. gateway users, so it must be self-contained and include the exact opt-back-out command.
  13. """
  14. model = str(autoraise.get("model") or "gpt-5.4/5.5").strip().lower().rsplit("/", 1)[-1]
  15. if isinstance(context_length, int) and context_length > 0:
  16. cap = f"{round(context_length / 1000)}K"
  17. else:
  18. # Static fallback: codex-spark is natively 128K; gpt-5.4/5.5/5.6 are capped at 272K.
  19. cap = "128K" if model.startswith("gpt-5.3-codex-spark") else "272K"
  20. from_pct = round(autoraise["from"] * 100)
  21. to_pct = round(autoraise["to"] * 100)
  22. return (
  23. f"ℹ Codex {model} caps context at {cap}, so auto-compaction was raised "
  24. f"to {to_pct}% (from {from_pct}%) to use more of the window before "
  25. f"summarizing.\n"
  26. f" Opt back out: hermes config set compression.codex_gpt55_autoraise false"
  27. )
  28. def _codex_gpt55_autoraise_notice_marker():
  29. """Per-profile marker path (``$HERMES_HOME`` is profile-scoped; not a config key)."""
  30. return get_hermes_home() / ".codex_gpt55_autoraise_notice"
  31. def _codex_gpt55_autoraise_notice_state(autoraise: dict[str, Any]) -> str:
  32. """Notice identity keyed on what it displays (model + from→to percentages).
  33. An unchanged threshold stays silent across restarts; a changed global threshold or a
  34. different autoraised Codex model re-notifies once.
  35. """
  36. model = str(autoraise.get("model") or "").strip().lower().rsplit("/", 1)[-1]
  37. from_pct = round(float(autoraise["from"]) * 100)
  38. to_pct = round(float(autoraise["to"]) * 100)
  39. return f"{model}:{from_pct}:{to_pct}"
  40. def _codex_gpt55_autoraise_notice_seen(autoraise: dict[str, Any]) -> bool:
  41. """True if this exact notice was already shown for this profile (unreadable = unseen)."""
  42. try:
  43. current = _codex_gpt55_autoraise_notice_state(autoraise)
  44. return _codex_gpt55_autoraise_notice_marker().read_text(
  45. encoding="utf-8"
  46. ).strip() == current
  47. except (OSError, KeyError, TypeError, ValueError):
  48. return False
  49. def _record_codex_gpt55_autoraise_notice(autoraise: dict[str, Any]) -> None:
  50. """Persist that the notice was shown. Best-effort: a failure only re-shows it later."""
  51. with suppress(OSError, KeyError, TypeError, ValueError):
  52. marker = _codex_gpt55_autoraise_notice_marker()
  53. marker.parent.mkdir(parents=True, exist_ok=True)
  54. marker.write_text(_codex_gpt55_autoraise_notice_state(autoraise), encoding="utf-8")
  55. def _emit_compression_summary(agent, cs):
  56. # Codex autoraise notice: once per profile/config state (persisted marker; the gateway
  57. # rebuilds the agent per message). The display gate hides the banner, not the autoraise.
  58. _autoraise = agent._compression_threshold_autoraised or {}
  59. _autoraise_notice = None
  60. if (
  61. # A change in the raised threshold (or the autoraised model) updates the marker state and
  62. # re-notifies once. The config display gate (compression.codex_gpt55_autoraise_notice) still
  63. # suppresses the banner entirely without disabling the threshold autoraise. See #54432.
  64. bool(_autoraise)
  65. and cs.enabled
  66. and cs.autoraise_notice_enabled
  67. and not _codex_gpt55_autoraise_notice_seen(_autoraise)
  68. ):
  69. _autoraise_notice = _build_codex_gpt5_autoraise_notice(
  70. _autoraise, context_length=getattr(agent.context_compressor, "context_length", None)
  71. )
  72. if not agent.quiet_mode:
  73. _cc = agent.context_compressor
  74. if cs.enabled:
  75. # The active engine's own threshold — a plugin's differs from cs.threshold.
  76. _pct = getattr(_cc, "threshold_percent", cs.threshold)
  77. _cap = getattr(_cc, "threshold_tokens_cap", None)
  78. # Name the cap only when it is what set the trigger; on small windows the ratio already sits below it.
  79. _eff_cap = getattr(_cc, "_effective_threshold_cap", lambda _ctx: None)(_cc.context_length)
  80. _cap_binds = _eff_cap is not None and _cc.threshold_tokens == _eff_cap
  81. _cap_note = f" (capped at {_cap:,} tokens)" if _cap_binds else ""
  82. print(f"📊 Context limit: {_cc.context_length:,} tokens (compress at {int(_pct*100)}% = {_cc.threshold_tokens:,}{_cap_note})")
  83. else:
  84. print(f"📊 Context limit: {_cc.context_length:,} tokens (auto-compression disabled)")
  85. # Gateway users get the same text via _compression_warning on turn 1.
  86. if _autoraise_notice:
  87. agent._safe_print(_autoraise_notice, diagnostic=True)
  88. # status_callback isn't wired yet: stash for replay on the first turn; mark shown so
  89. # repeated inits stay silent.
  90. agent._compression_warning = _autoraise_notice
  91. if _autoraise_notice:
  92. _record_codex_gpt55_autoraise_notice(_autoraise)
  93. # Feasibility check deferred to the first turn near threshold (eager costs ~400ms cold).
  94. agent._compression_feasibility_checked = False