The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(compression): derive native threshold from local trigger
Marco Fernstaedta2af8405d1d5
diff --git a/agent/agent_init.py b/agent/agent_init.pyindex 63e8f4c4362..5b78192587f 100644--- a/agent/agent_init.py+++ b/agent/agent_init.py@@ -2337,21 +2337,22 @@ def init_agent(codex_responses_native_compaction = _is_truthy(_compression_cfg.get("codex_responses_native", False))- _native_threshold_raw = _compression_cfg.get(- "codex_responses_compact_threshold", 200_000- )- try:- if isinstance(_native_threshold_raw, bool):- raise ValueError- codex_responses_compact_threshold = int(_native_threshold_raw)- if codex_responses_compact_threshold <= 0:- raise ValueError- except (TypeError, ValueError):- _ra().logger.warning(- "Invalid compression.codex_responses_compact_threshold=%r; using 200000.",- _native_threshold_raw,- )- codex_responses_compact_threshold = 200_000+ _native_threshold_raw = _compression_cfg.get("codex_responses_compact_threshold")+ codex_responses_compact_threshold = None+ if _native_threshold_raw is not None:+ try:+ if isinstance(_native_threshold_raw, (bool, float)):+ raise ValueError+ codex_responses_compact_threshold = int(_native_threshold_raw)+ if codex_responses_compact_threshold <= 0:+ raise ValueError+ except (TypeError, ValueError):+ _ra().logger.warning(+ "Invalid compression.codex_responses_compact_threshold=%r; "+ "using the automatic threshold derived from local compression.",+ _native_threshold_raw,+ )+ codex_responses_compact_threshold = None# Opt-in idle compaction: compact a session up front when it resumes after# this many seconds of inactivity (0 = disabled). Time-based, so it# complements the size-based threshold above. Consumed by build_turn_context().diff --git a/agent/native_compaction.py b/agent/native_compaction.pyindex 5dbd374825e..b1e4d2b3355 100644--- a/agent/native_compaction.py+++ b/agent/native_compaction.py@@ -55,6 +55,7 @@ logger = logging.getLogger(__name__)# trigger so the server always gets the first shot at compaction.LOCAL_TRIGGER_SAFETY_MARGIN = 8_192+# Deterministic fallback when automatic mode cannot inspect a local trigger.DEFAULT_COMPACT_THRESHOLD = 200_000# Model-family gate. Substring match on the lowercased model id so dated@@ -86,33 +87,41 @@ def resolve_compact_threshold(configured_threshold: Any,local_trigger_tokens: Any = None,) -> int:- """Clamp the configured native threshold below the local compressor trigger.+ """Resolve automatic mode or clamp an explicit native threshold.- Without the clamp a native threshold above the local trigger would let the- local summarizer fire first every time, making native compaction dead- config. ``local_trigger_tokens`` is ``ContextCompressor.threshold_tokens``- when a compressor is attached, else None.+ An omitted or invalid setting follows the resolved local compressor trigger.+ An explicit positive integer remains absolute unless it must be clamped so+ native compaction fires first. ``local_trigger_tokens`` is+ ``ContextCompressor.threshold_tokens`` when a compressor is attached."""- try:- configured = int(configured_threshold)- except (TypeError, ValueError):- configured = DEFAULT_COMPACT_THRESHOLD- if isinstance(configured_threshold, bool) or configured <= 0:- configured = DEFAULT_COMPACT_THRESHOLD-local = Nonetry:if local_trigger_tokens is not None and not isinstance(local_trigger_tokens, bool):local = int(local_trigger_tokens)except (TypeError, ValueError):local = None- if local is None or local <= 0:- return configured+ if local is not None and local <= 0:+ local = None- if local > LOCAL_TRIGGER_SAFETY_MARGIN:- upper = local - LOCAL_TRIGGER_SAFETY_MARGIN- else:- upper = max(1_024, int(local * 0.8))+ upper = None+ if local is not None:+ if local > LOCAL_TRIGGER_SAFETY_MARGIN:+ upper = max(1_024, local - LOCAL_TRIGGER_SAFETY_MARGIN)+ else:+ upper = max(1_024, int(local * 0.8))++ try:+ configured = (+ None+ if isinstance(configured_threshold, (bool, float))+ else int(configured_threshold)+ )+ except (TypeError, ValueError):+ configured = None+ if isinstance(configured_threshold, bool) or configured is None or configured <= 0:+ return upper if upper is not None else DEFAULT_COMPACT_THRESHOLD+ if upper is None:+ return configuredreturn max(1_024, min(configured, upper))@@ -176,7 +185,7 @@ def native_compaction_context_management(compressor = getattr(agent, "context_compressor", None)threshold = resolve_compact_threshold(- getattr(agent, "codex_responses_compact_threshold", DEFAULT_COMPACT_THRESHOLD),+ getattr(agent, "codex_responses_compact_threshold", None),getattr(compressor, "threshold_tokens", None) if compressor is not None else None,)return [{"type": "compaction", "compact_threshold": threshold}]diff --git a/cli-config.yaml.example b/cli-config.yaml.exampleindex 622f4fa7669..da6d4e8e64d 100644--- a/cli-config.yaml.example+++ b/cli-config.yaml.example@@ -658,9 +658,13 @@ compression:# fallback and still handles every non-eligible session.codex_responses_native: false- # Server-side compaction trigger in input tokens. Clamped below the local- # compression threshold at request time so the server compacts first.- codex_responses_compact_threshold: 200000+ # Optional absolute server compaction trigger in input tokens. The default+ # null value follows the resolved local compression trigger with an 8192 token+ # safety margin. For example, a local trigger of 765000 selects 756808.+ # A positive integer stays absolute and only clamps downward when needed so+ # the server compacts first. Invalid values use this automatic behavior. If+ # the local trigger is unavailable, automatic mode uses 200000.+ codex_responses_compact_threshold: null# Number of non-system messages to protect at the head of the transcript, in# ADDITION to the system prompt (which is always implicitly protected).diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex b5ecdbfa2ea..aeb98a8375f 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -984,10 +984,11 @@ DEFAULT_CONFIG = {# the ChatGPT Codex backend; every other# route/model is unaffected. Hermes' local# compression stays armed as the fallback.- "codex_responses_compact_threshold": 200000, # Server-side compaction trigger- # (input tokens). Clamped below the local- # compression threshold at request time so- # the server compacts before Hermes does.+ "codex_responses_compact_threshold": None, # Optional absolute server compaction+ # trigger in input tokens. None follows the+ # resolved local compression trigger with a+ # safety margin. Explicit values only clamp+ # downward so the server compacts first."in_place": True, # When True, compaction rewrites the message# list and rebuilds the system prompt WITHOUT# rotating the session id — the conversationdiff --git a/tests/run_agent/test_native_compaction.py b/tests/run_agent/test_native_compaction.pyindex bf7150c32ee..31fca0f82c9 100644--- a/tests/run_agent/test_native_compaction.py+++ b/tests/run_agent/test_native_compaction.py@@ -25,7 +25,7 @@ def _agent(base_url="https://api.openai.com/v1",enabled=True,compression_enabled=True,- threshold=DEFAULT_COMPACT_THRESHOLD,+ threshold: object = DEFAULT_COMPACT_THRESHOLD,compressor=None,):return SimpleNamespace(@@ -145,20 +145,51 @@ class TestRequestGate:)assert payload[0]["compact_threshold"] < 100_000+ def test_omitted_threshold_tracks_resolved_local_trigger(self):+ compressor = SimpleNamespace(threshold_tokens=765_000)+ payload = native_compaction_context_management(+ _agent(threshold=None, compressor=compressor), is_codex_backend=False+ )+ assert payload == [{"type": "compaction", "compact_threshold": 756_808}]+class TestThresholdClamp:+ def test_omitted_threshold_derives_from_local_trigger(self):+ assert resolve_compact_threshold(None, 765_000) == 756_808+def test_clamps_below_local_trigger(self):assert resolve_compact_threshold(200_000, 100_000) == 100_000 - 8_192+ def test_explicit_threshold_remains_absolute_for_larger_window(self):+ assert resolve_compact_threshold(200_000, 765_000) == 200_000+def test_no_local_trigger_uses_configured(self):assert resolve_compact_threshold(200_000, None) == 200_000- def test_garbage_configured_falls_back_to_default(self):- assert resolve_compact_threshold("garbage", None) == DEFAULT_COMPACT_THRESHOLD- assert resolve_compact_threshold(True, None) == DEFAULT_COMPACT_THRESHOLD- assert resolve_compact_threshold(-5, None) == DEFAULT_COMPACT_THRESHOLD+ @pytest.mark.parametrize("configured", ["garbage", True, -5, 1.5])+ def test_invalid_configured_uses_automatic_local_threshold(self, configured):+ assert resolve_compact_threshold(configured, 765_000) == 756_808++ def test_automatic_without_local_trigger_uses_documented_fallback(self):+ assert resolve_compact_threshold(None, None) == DEFAULT_COMPACT_THRESHOLD++ @pytest.mark.parametrize(+ ("local_trigger", "expected"),+ [+ (8_193, 1_024),+ (8_192, 6_553),+ (4_000, 3_200),+ (1_024, 1_024),+ (1_000, 1_024),+ (1, 1_024),+ ],+ )+ def test_automatic_tiny_local_trigger_respects_provider_floor(+ self, local_trigger, expected+ ):+ assert resolve_compact_threshold(None, local_trigger) == expected- def test_tiny_local_trigger_stays_positive(self):+ def test_explicit_tiny_local_trigger_stays_positive(self):assert resolve_compact_threshold(200_000, 4_000) >= 1_024@@ -382,7 +413,7 @@ class TestResponseCapture:class TestAgentInitConfig:- def test_defaults_off_and_threshold(self, monkeypatch):+ def test_defaults_off_and_automatic_threshold(self, monkeypatch):from run_agent import AIAgentagent = AIAgent(@@ -397,7 +428,59 @@ class TestAgentInitConfig:enabled_toolsets=[],)assert agent.codex_responses_native_compaction is False- assert agent.codex_responses_compact_threshold == 200_000+ assert agent.codex_responses_compact_threshold is None++ def test_public_config_default_selects_automatic_threshold(self):+ from hermes_cli.config import DEFAULT_CONFIG++ assert (+ DEFAULT_CONFIG["compression"]["codex_responses_compact_threshold"] is None+ )++ @pytest.mark.parametrize(+ ("threshold_yaml", "configured", "resolved"),+ [+ (None, None, 756_808),+ ("null", None, 756_808),+ ("200000", 200_000, 200_000),+ ("true", None, 756_808),+ ("-5", None, 756_808),+ ("1.5", None, 756_808),+ ('"bad"', None, 756_808),+ ],+ )+ def test_loaded_config_reaches_request_threshold(+ self, tmp_path, monkeypatch, threshold_yaml, configured, resolved+ ):+ from run_agent import AIAgent++ home = tmp_path / ".hermes"+ home.mkdir()+ lines = ["compression:", " codex_responses_native: true"]+ if threshold_yaml is not None:+ lines.append(f" codex_responses_compact_threshold: {threshold_yaml}")+ (home / "config.yaml").write_text("\n".join(lines) + "\n", encoding="utf-8")+ monkeypatch.setenv("HERMES_HOME", str(home))++ agent = AIAgent(+ api_key="test-key",+ base_url="https://api.openai.com/v1",+ api_mode="codex_responses",+ model="gpt-5.6",+ provider="openai-api",+ quiet_mode=True,+ skip_context_files=True,+ skip_memory=True,+ enabled_toolsets=[],+ )+ compressor = getattr(agent, "context_compressor")+ compressor.threshold_tokens = 765_000+ kwargs = agent._build_api_kwargs([{"role": "user", "content": "hi"}])++ assert getattr(agent, "codex_responses_compact_threshold") == configured+ assert kwargs["context_management"] == [+ {"type": "compaction", "compact_threshold": resolved}+ ]def test_kwargs_have_no_context_management_by_default(self):from run_agent import AIAgentdiff --git a/website/docs/developer-guide/context-compression-and-caching.md b/website/docs/developer-guide/context-compression-and-caching.mdindex 146b53b58a5..b32bda51961 100644--- a/website/docs/developer-guide/context-compression-and-caching.md+++ b/website/docs/developer-guide/context-compression-and-caching.md@@ -93,7 +93,7 @@ compression:codex_gpt55_autoraise_notice: true # Show the one-time autoraise notice (default: true)codex_app_server_auto: native # native|hermes|off for Codex app-server thread compactioncodex_responses_native: false # gpt-5.6 on direct OpenAI/Codex: server-side compaction (opt-in)- codex_responses_compact_threshold: 200000 # Server-side compaction trigger (input tokens)+ codex_responses_compact_threshold: null # Automatic server compaction triggerin_place: true # Compact on the same session id, no rotation (default: true)# Summarization model/provider configured under auxiliary:@@ -120,7 +120,7 @@ auxiliary:| `codex_gpt55_autoraise_notice` | `true` | bool | Show the one-time Codex gpt-5.5 autoraise notice. Set `false` to keep the 85% autoraise but suppress the banner || `codex_app_server_auto` | `native` | `native`, `hermes`, `off` | Thread-compaction mode for Codex app-server sessions (see below) || `codex_responses_native` | `false` | bool | Opt in to OpenAI's server-side compaction on the Responses API. Engages only for gpt-5.6-family models on the direct OpenAI API or a ChatGPT Codex subscription (see below) |-| `codex_responses_compact_threshold` | `200000` | ≥1 tokens | Server-side compaction trigger in input tokens. Clamped below the local compression threshold at request time so the server compacts first |+| `codex_responses_compact_threshold` | `null` | `null` or positive integer | `null` follows the resolved local compression trigger with an 8,192 token safety margin. A positive integer remains absolute and only clamps downward when required. Invalid values use automatic behavior. Automatic mode falls back to `200000` when no usable local trigger exists || `in_place` | `true` | bool | Compact on the same session id instead of rotating to a new one (see below) |### In-place compaction (single stable session id)@@ -264,6 +264,14 @@ the request without it. Switching the session to a non-eligible model or routesimply stops the field from being sent — captured checkpoints are dropped fromreplay by the existing cross-issuer guard when the endpoint changes.+By default, `compression.codex_responses_compact_threshold: null` derives the+native threshold from the resolved local trigger. For example, a local trigger+of 765,000 selects 756,808. Set a positive integer to preserve an absolute+threshold such as 200,000. Invalid values select automatic behavior. If no+usable local trigger exists, automatic mode uses 200,000. The provider minimum+is 1,024 tokens, so an unusually small local trigger at or below that floor+cannot preserve strict native first ordering.+### Computed Values (for a 200K context model at defaults)```