Skip to content

The agent that grows with you

feat: label a model.context_length pin and warn once when it disagrees with the provider

teknium18e180c69f6c7
diff --git a/agent/agent_init.py b/agent/agent_init.py
index 43c0440b7bb..f182dc01222 100644
--- a/agent/agent_init.py
+++ b/agent/agent_init.py
@@ -1750,6 +1750,9 @@ def _resolve_context_length(agent, _agent_cfg, base_url):
# Persisted for switch_model / fallback AFTER the custom_providers branch (per-model overrides).
agent._config_context_length = _config_context_length
+ if _config_context_length is not None:
+ from agent.context_pin import warn_once_on_pin_disagreement
+ warn_once_on_pin_disagreement(agent.model, agent.base_url or "", _config_context_length)
_lmstudio_runtime_context_length = agent._ensure_lmstudio_runtime_loaded(_config_context_length)
if agent._lmstudio_load_was_unverified(_lmstudio_runtime_context_length):
diff --git a/agent/context_pin.py b/agent/context_pin.py
new file mode 100644
index 00000000000..f402dcd752a
--- /dev/null
+++ b/agent/context_pin.py
@@ -0,0 +1,73 @@
+"""``model.context_length`` is an explicit pin: it wins over provider metadata (#66168).
+
+Two helpers make that visible without changing the numeric value used: a label for every
+surface that renders the context window, and a one-time startup warning when the pin
+disagrees with what the provider is known to advertise for the model.
+"""
+from __future__ import annotations
+
+import logging
+from typing import Optional
+
+logger = logging.getLogger(__name__)
+
+_warned_pins: set = set()
+
+
+def is_context_pinned(context_length, config_context_length) -> bool:
+ """True when the displayed ``context_length`` is the ``model.context_length`` pin."""
+ return (
+ isinstance(config_context_length, int)
+ and not isinstance(config_context_length, bool)
+ and config_context_length > 0
+ and context_length == config_context_length
+ )
+
+
+def context_pin_suffix(context_length, config_context_length) -> str:
+ """`` (pinned)`` when the shown value comes from ``model.context_length``, else ``""``."""
+ return " (pinned)" if is_context_pinned(context_length, config_context_length) else ""
+
+
+def advertised_context_length(model: str, base_url: str = "") -> Optional[int]:
+ """Provider-advertised window from LOCAL sources only (persistent cache learned on this
+ endpoint, models.dev disk cache, hardcoded catalog). Never a network probe: users pin
+ precisely when the endpoint cannot report its window, so the check must not add startup
+ latency or a failing request."""
+ from agent.model_metadata import (
+ DEFAULT_CONTEXT_LENGTHS, _load_model_metadata_disk_cache, _longest_key_match,
+ _strip_provider_prefix, get_cached_context_length,
+ )
+ model = _strip_provider_prefix(str(model or ""))
+ if not model:
+ return None
+ if base_url:
+ cached = get_cached_context_length(model, base_url)
+ if cached:
+ return int(cached)
+ entry = _load_model_metadata_disk_cache().get(model) or {}
+ ctx = entry.get("context_length") if isinstance(entry, dict) else None
+ if isinstance(ctx, int) and ctx > 0:
+ return ctx
+ hit = _longest_key_match(DEFAULT_CONTEXT_LENGTHS, model.lower())
+ return hit[1] if hit else None
+
+
+def warn_once_on_pin_disagreement(model: str, base_url: str, config_context_length) -> bool:
+ """Log ONE warning per (model, pin) when ``model.context_length`` disagrees with the
+ advertised window. Returns True when the warning fired (the pin still wins)."""
+ if not is_context_pinned(config_context_length, config_context_length):
+ return False
+ advertised = advertised_context_length(model, base_url)
+ if not advertised or advertised == config_context_length:
+ return False
+ key = (str(model), int(config_context_length))
+ if key in _warned_pins:
+ return False
+ _warned_pins.add(key)
+ logger.warning(
+ "model.context_length pins %s at %s tokens but the provider advertises %s; the pin wins. "
+ "Remove model.context_length from config.yaml to use the advertised window.",
+ model, f"{config_context_length:,}", f"{advertised:,}",
+ )
+ return True
diff --git a/hermes_cli/banner.py b/hermes_cli/banner.py
index 730e834cc84..39358fb0e0a 100644
--- a/hermes_cli/banner.py
+++ b/hermes_cli/banner.py
@@ -860,12 +860,15 @@ def _route_model_for_banner(provider: Any) -> str:
return GUEST_MODEL if guest_carries_inference() else ""
-def _banner_left_lines(model: str, cwd: str, session_id, context_length, provider, *, accent: str, dim: str) -> list:
- """Model / cwd / session lines under the hero art."""
+def _banner_left_lines(model: str, cwd: str, session_id, context_length, provider, *, accent: str, dim: str,
+ context_pinned: bool = False) -> list:
+ """Model / cwd / session lines under the hero art. ``context_pinned`` marks a
+ ``model.context_length`` pin so the user can tell it apart from provider metadata (#66168)."""
def _dim_sep(label: str) -> str:
return f" [dim {dim}]·[/] [dim {dim}]{label}[/]"
lines = []
- ctx_str = _dim_sep(f"{_format_context_length(context_length)} context") if context_length else ""
+ pin = " (pinned)" if context_pinned else ""
+ ctx_str = _dim_sep(f"{_format_context_length(context_length)} context{pin}") if context_length else ""
nous_str = _dim_sep("Nous Research")
if not (model or "").strip():
# Credentials resolve lazily on the first message; the banner prints first. Ask the route
@@ -939,6 +942,7 @@ def build_welcome_banner(
console: "Console", model: str, cwd: str, tools: List[dict] = None, enabled_toolsets: List[str] = None,
session_id: str = None, get_toolset_for_tool=None, context_length: int = None, provider: str = None,
availability: Dict[str, Any] = None, skills_by_category: Dict[str, List[str]] = None,
+ context_pinned: bool = False,
):
"""Build and print a welcome banner with caduceus on left and info on right.
@@ -962,7 +966,8 @@ def build_welcome_banner(
# Use skin's custom caduceus art if provided
_bskin = _quiet(_active_skin)
left_lines = ["", getattr(_bskin, "banner_hero", None) or HERMES_CADUCEUS, ""]
- left_lines += _banner_left_lines(model, cwd, session_id, context_length, provider, accent=accent, dim=dim)
+ left_lines += _banner_left_lines(model, cwd, session_id, context_length, provider, accent=accent, dim=dim,
+ context_pinned=context_pinned)
right_lines = _banner_tool_lines(
tools, availability.get("unavailable_toolsets", []), get_toolset_for_tool,
lazy_tools=set(availability.get("lazy_tools", [])), disabled_tools=set(availability.get("disabled_tools", [])),
diff --git a/hermes_cli/cli_info_mixin.py b/hermes_cli/cli_info_mixin.py
index f47eea07016..37d313669b2 100644
--- a/hermes_cli/cli_info_mixin.py
+++ b/hermes_cli/cli_info_mixin.py
@@ -97,6 +97,8 @@ class CLIInfoMixin:
ctx_len = None
if hasattr(self, 'agent') and self.agent and hasattr(self.agent, 'context_compressor'):
ctx_len = self.agent.context_compressor.context_length
+ from agent.context_pin import is_context_pinned
+ ctx_pinned = is_context_pinned(ctx_len, getattr(getattr(self, "agent", None), "_config_context_length", None))
# Auto-compact for narrow terminals — the full banner needs ~80 columns to avoid wrapping.
if self.compact or shutil.get_terminal_size().columns < 80:
@@ -117,7 +119,7 @@ class CLIInfoMixin:
banner_kw = dict(
console=self.console, model=self.model, cwd=cwd,
enabled_toolsets=self.enabled_toolsets, session_id=self.session_id,
- context_length=ctx_len, provider=self.provider)
+ context_length=ctx_len, provider=self.provider, context_pinned=ctx_pinned)
if snapshot is not None:
self._defer_tool_warnings = True
@@ -733,7 +735,9 @@ class CLIInfoMixin:
print(f" {'─' * 40}")
from agent.context_breakdown import context_display_source
mark = "~" if context_display_source(compressor) != "provider_usage" else ""
- print(f" Current context: {mark}{last_prompt:,} / {ctx_len:,} ({mark}{pct:.0f}%)")
+ from agent.context_pin import context_pin_suffix
+ print(f" Current context: {mark}{last_prompt:,} / {ctx_len:,} ({mark}{pct:.0f}%)"
+ f"{context_pin_suffix(ctx_len, getattr(agent, '_config_context_length', None))}")
print(f" Messages: {len(self.conversation_history)}")
print(f" Compressions: {compressor.compression_count}")
diff --git a/hermes_cli/cli_loops_mixin.py b/hermes_cli/cli_loops_mixin.py
index 29f3ba824fb..9916b124ba9 100644
--- a/hermes_cli/cli_loops_mixin.py
+++ b/hermes_cli/cli_loops_mixin.py
@@ -102,10 +102,12 @@ class CLILoopsMixin:
ctx_len = None
if agent and hasattr(agent, "context_compressor"):
ctx_len = agent.context_compressor.context_length
+ from agent.context_pin import is_context_pinned
build_welcome_banner(
console=cc, model=self.model, cwd=os.getenv("TERMINAL_CWD", os.getcwd()),
tools=tools, enabled_toolsets=self.enabled_toolsets, session_id=self.session_id,
- context_length=ctx_len, provider=self.provider)
+ context_length=ctx_len, provider=self.provider,
+ context_pinned=is_context_pinned(ctx_len, getattr(agent, "_config_context_length", None)))
_cprint(_FRESH_START)
self._print_random_tip()
diff --git a/hermes_cli/cli_model_switch_mixin.py b/hermes_cli/cli_model_switch_mixin.py
index 6eb134bd6f8..7d408989d14 100644
--- a/hermes_cli/cli_model_switch_mixin.py
+++ b/hermes_cli/cli_model_switch_mixin.py
@@ -141,7 +141,9 @@ def _print_switch_summary(cli, result, old_model, *, one_turn: bool, strict_cont
raise
ctx = None
if ctx:
- _cprint(f" Context: {ctx:,} tokens")
+ from agent.context_pin import context_pin_suffix
+ _cprint(f" Context: {ctx:,} tokens"
+ f"{context_pin_suffix(ctx, getattr(agent, '_config_context_length', None) if agent else None)}")
if mi:
if mi.max_output:
_cprint(f" Max output: {mi.max_output:,} tokens")
diff --git a/hermes_cli/cli_status_bar_mixin.py b/hermes_cli/cli_status_bar_mixin.py
index 3e532d3ca47..2acfafc11b0 100644
--- a/hermes_cli/cli_status_bar_mixin.py
+++ b/hermes_cli/cli_status_bar_mixin.py
@@ -331,6 +331,9 @@ class CLIStatusBarMixin:
context_length = max(0, getattr(compressor, "context_length", 0) or 0)
snapshot["context_tokens"] = context_tokens
snapshot["context_length"] = context_length or None
+ from agent.context_pin import is_context_pinned
+ snapshot["context_pinned"] = is_context_pinned(
+ context_length, getattr(compressor, "_config_context_length", None))
snapshot["compressions"] = getattr(compressor, "compression_count", 0) or 0
if context_length:
pct = round((context_tokens / context_length) * 100)
@@ -1047,7 +1050,8 @@ class CLIStatusBarMixin:
if snapshot["context_length"]:
ctx_total = _format_context_length(snapshot["context_length"])
ctx_used = format_token_count_compact(snapshot["context_tokens"])
- context_label = f"{mark}{ctx_used}/{ctx_total}"
+ pin = " pinned" if snapshot.get("context_pinned") else ""
+ context_label = f"{mark}{ctx_used}/{ctx_total}{pin}"
else:
context_label = "ctx --"
segs.append([(_DIM, context_label)])
diff --git a/tests/agent/test_context_pin.py b/tests/agent/test_context_pin.py
new file mode 100644
index 00000000000..d840fa01740
--- /dev/null
+++ b/tests/agent/test_context_pin.py
@@ -0,0 +1,29 @@
+"""``model.context_length`` is a visible pin: one warning when it disagrees with the advertised
+window, and a ``(pinned)`` label wherever the window is rendered (#66168)."""
+import logging
+
+from agent import context_pin
+from agent.context_pin import context_pin_suffix, is_context_pinned, warn_once_on_pin_disagreement
+
+
+def test_pin_disagreement_warns_once_and_keeps_pin(monkeypatch, caplog):
+ monkeypatch.setattr(context_pin, "_warned_pins", set())
+ monkeypatch.setattr(context_pin, "advertised_context_length", lambda model, base_url="": 200_000)
+ with caplog.at_level(logging.WARNING, logger="agent.context_pin"):
+ assert warn_once_on_pin_disagreement("claude-sonnet-4", "", 999_000) is True
+ # Second session start in the same process: silent.
+ assert warn_once_on_pin_disagreement("claude-sonnet-4", "", 999_000) is False
+ # Control: a pin that matches the advertised window is not a disagreement.
+ assert warn_once_on_pin_disagreement("claude-sonnet-4", "", 200_000) is False
+ warnings = [r for r in caplog.records if "model.context_length pins" in r.getMessage()]
+ assert len(warnings) == 1
+ assert "999,000" in warnings[0].getMessage() and "200,000" in warnings[0].getMessage()
+
+
+def test_pinned_label_only_when_shown_value_is_the_pin():
+ assert is_context_pinned(999_000, 999_000) is True
+ assert context_pin_suffix(999_000, 999_000) == " (pinned)"
+ # Route changed / pin dropped, unpinned, or non-int pins never label.
+ assert context_pin_suffix(200_000, 999_000) == ""
+ assert context_pin_suffix(200_000, None) == ""
+ assert context_pin_suffix(1, True) == ""
diff --git a/website/docs/integrations/providers.md b/website/docs/integrations/providers.md
index dde0a0422c3..96cf30a934a 100644
--- a/website/docs/integrations/providers.md
+++ b/website/docs/integrations/providers.md
@@ -1283,7 +1283,7 @@ Set `context_length` when auto-detection gets the window size wrong.
Hermes uses a multi-source resolution chain to detect the correct context window for your model and provider:
-1. **Config override** — `model.context_length` in config.yaml (highest priority)
+1. **Config override** — `model.context_length` in config.yaml (highest priority). This is an explicit **pin**: it always wins over provider metadata, so Hermes labels it `(pinned)` wherever the window is shown (welcome banner, `/model`, `/usage`, the status bar) and logs one warning at startup when the pin disagrees with the window the provider is known to advertise. The pin is dropped automatically when you switch model, provider or base URL.
2. **Custom provider per-model** — `providers.<name>.models.<id>.context_length`
3. **Persistent cache** — previously discovered values (survives restarts)
4. **Endpoint `/models`** — queries your server's API (local/custom endpoints)