The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(caching): prompt_caching.cache_ttl: auto picks the 1h tier for human-paced sessions, 5m for machine-paced ones
teknium123301d705c08
diff --git a/agent/agent_init.py b/agent/agent_init.pyindex 732ff39a472..902a6a6f00d 100644--- a/agent/agent_init.py+++ b/agent/agent_init.py@@ -656,8 +656,8 @@ def _init_prompt_cache_config(agent):agent._anthropic_prompt_cache_policy())agent._cache_disabled = False- # cache_ttl: "5m" (default) or "1h" (2x write cost; pays off with >5-minute pauses);- # unknown values keep "5m". A falsy/off value disables caching entirely (OAuth plans+ # cache_ttl: "5m" (default), "1h" (2x write cost; pays off with >5-minute pauses) or "auto"+ # (1h when a person paces the session, 5m when a machine does); unknown values keep "5m". A falsy/off value disables caching entirely (OAuth plans# billing cache writes, proxies adding their own cache_control); the disable survives# /model switches and fallback re-derivation.# Anthropic supports "5m" (default) and "1h" cache TTL tiers. Read from config.yaml under@@ -669,10 +669,16 @@ def _init_prompt_cache_config(agent):with suppress(Exception):from hermes_cli.config import load_config_readonly as _load_pc_cfgfrom agent.agent_runtime_helpers import cache_ttl_means_disabled+ from agent.prompt_caching import AUTO_CACHE_TTL, auto_cache_ttl_for_source_pc_cfg = _load_pc_cfg().get("prompt_caching", {}) or {}_ttl = _pc_cfg.get("cache_ttl", "5m")if _ttl in {"5m", "1h"}:agent._cache_ttl = _ttl+ elif _ttl == AUTO_CACHE_TTL:+ # Decided once per session from its source (a delegated child is clamped to 5m again+ # in delegate_tool regardless).+ from run_agent import _session_source_for_agent # late: run_agent imports this module+ agent._cache_ttl = auto_cache_ttl_for_source(_session_source_for_agent(getattr(agent, "platform", None)))elif cache_ttl_means_disabled(_ttl):agent._use_prompt_caching = Falseagent._use_native_cache_layout = Falsediff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.pyindex d780c4c19dd..74986d6a9d2 100644--- a/agent/agent_runtime_helpers.py+++ b/agent/agent_runtime_helpers.py@@ -1474,7 +1474,8 @@ def prompt_caching_disabled_from_config() -> bool:def configured_cache_ttl() -> Optional[str]:"""Configured ``prompt_caching.cache_ttl`` tier (``5m``/``1h``), else None; mirrors- ``agent_init`` so stub paths don't regress a configured ``1h`` to 5m."""+ ``agent_init`` so stub paths don't regress a configured ``1h`` to 5m. ``auto`` is None here+ on purpose: stub/auxiliary calls are machine-paced, so they take the 5m tier ``None`` resolves to."""ttl = _raw_cache_ttl_from_config(None)return ttl if ttl in VALID_CACHE_TTLS else Nonediff --git a/agent/prompt_caching.py b/agent/prompt_caching.pyindex 6e511b1b3d1..eeab76297bd 100644--- a/agent/prompt_caching.py+++ b/agent/prompt_caching.py@@ -111,6 +111,23 @@ def is_qwen_model(model: str) -> bool:return "qwen" in (model or "").lower()+# ``prompt_caching.cache_ttl: auto`` picks the tier by who paces the session. The 1h tier+# writes at 2x base vs 1.25x for 5m and only pays off when turns are more than five minutes+# apart — a person stepping away and coming back. Machine-paced sessions call every few+# seconds until they finish and never collect the retention, so they stay on 5m.+# Measured on one install (2 days of per-call logs): 63% of interactive cache-write tokens+# were cold re-writes after a 5–60 min idle gap (1h saves ~42% of write cost there), while+# 1h on subagents/cron would have cost ~49% more.+AUTO_CACHE_TTL = "auto"+MACHINE_PACED_SOURCES = frozenset({"subagent", "cron", "oneshot", "webhook", "kanban", "api", "tool", "batch"})+++def auto_cache_ttl_for_source(source: str | None) -> str:+ """The tier ``auto`` resolves to for a session source: ``5m`` for machine-paced sources,+ ``1h`` for everything a human types into (cli, tui, desktop, messaging platforms)."""+ return "5m" if (source or "").strip().lower() in MACHINE_PACED_SOURCES else "1h"++def effective_cache_ttl(ttl: str | None, *, model: str = "", provider: str = "") -> str:"""Clamp a requested cache TTL to what the destination route supports (``None`` → ``5m``).diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex 7c916e57ac6..be90b8f7049 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -672,9 +672,10 @@ DEFAULT_CONFIG = {# guards. Example: 1800 = 30 min."idle_compact_after_seconds": 0,},- # Anthropic prompt caching (Claude via OpenRouter or native API). cache_ttl: "5m" | "1h"; other- # non-falsy values are ignored; falsy (false, null, "off", "disabled", "no", "none") disables- # caching.+ # Anthropic prompt caching (Claude via OpenRouter or native API). cache_ttl: "5m" | "1h" | "auto"+ # (auto = 1h for human-paced sessions — cli/tui/desktop/messaging — and 5m for subagent, cron,+ # oneshot, webhook, kanban, api); other non-falsy values are ignored; falsy (false, null, "off",+ # "disabled", "no", "none") disables caching."prompt_caching": {"cache_ttl": "5m"},# OpenRouter settings. response_cache: X-OpenRouter-Cache header — identical requests return# cached responses at zero billing; independent of Anthropic prompt caching. response_cache_ttl:diff --git a/tests/agent/test_prompt_cache_ttl_auto.py b/tests/agent/test_prompt_cache_ttl_auto.pynew file mode 100644index 00000000000..88ad160fc08--- /dev/null+++ b/tests/agent/test_prompt_cache_ttl_auto.py@@ -0,0 +1,41 @@+"""``prompt_caching.cache_ttl: auto`` picks the Anthropic cache tier by who paces the session.++The 1h tier writes at 2x base (5m: 1.25x) and only pays off across >5-minute pauses, i.e.+for a person; machine-paced sessions (subagent, cron, oneshot, webhook, ...) never collect the+retention. ``auto`` resolves once per session in ``_init_prompt_cache_config``.+"""++from agent.prompt_caching import MACHINE_PACED_SOURCES, auto_cache_ttl_for_source+++def test_auto_tier_follows_session_pace():+ assert auto_cache_ttl_for_source("cli") == "1h"+ assert auto_cache_ttl_for_source("telegram") == "1h"+ assert auto_cache_ttl_for_source(None) == "1h", "an unknown/blank source is a person until proven otherwise"+ for source in MACHINE_PACED_SOURCES:+ assert auto_cache_ttl_for_source(source) == "5m", source+++def test_real_agent_resolves_auto_from_its_platform(tmp_path, monkeypatch):+ """A real AIAgent under ``cache_ttl: auto``: a CLI session lands on 1h, a cron session on 5m, and+ caching itself stays enabled on both (auto is a tier choice, never a disable)."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ monkeypatch.delenv("HERMES_SESSION_SOURCE", raising=False)+ (tmp_path / "config.yaml").write_text(+ "prompt_caching:\n cache_ttl: auto\nmodel:\n default: anthropic/claude-sonnet-4.6\n", encoding="utf-8")+ from run_agent import AIAgent+ kw = dict(api_key="k", base_url="https://openrouter.ai/api/v1", provider="openrouter",+ api_mode="chat_completions", model="anthropic/claude-sonnet-4.6", quiet_mode=True,+ skip_context_files=True, skip_memory=True, save_trajectories=False, enabled_toolsets=["file"])+ interactive = AIAgent(session_id="p-cli", platform="cli", **kw)+ scheduled = AIAgent(session_id="p-cron", platform="cron", **kw)+ try:+ assert interactive._cache_ttl == "1h"+ assert scheduled._cache_ttl == "5m"+ assert interactive._use_prompt_caching and scheduled._use_prompt_caching+ assert not interactive._cache_disabled and not scheduled._cache_disabled+ finally:+ for a in (interactive, scheduled):+ close = getattr(a, "close", None)+ if callable(close):+ close()diff --git a/website/docs/developer-guide/context-compression-and-caching.md b/website/docs/developer-guide/context-compression-and-caching.mdindex f083ee20be1..2de2c0d23a4 100644--- a/website/docs/developer-guide/context-compression-and-caching.md+++ b/website/docs/developer-guide/context-compression-and-caching.md@@ -715,11 +715,13 @@ Prompt caching is automatically enabled when:- The provider supports `cache_control` (native Anthropic API or OpenRouter)```yaml-# config.yaml — TTL is configurable (must be "5m" or "1h")+# config.yaml — TTL is configurable: "5m", "1h", or "auto"prompt_caching:cache_ttl: "5m"```+`"auto"` resolves once per session in `agent/agent_init.py::_init_prompt_cache_config` via `agent/prompt_caching.py::auto_cache_ttl_for_source`: `1h` for human-paced sources, `5m` for `MACHINE_PACED_SOURCES` (subagent, cron, oneshot, webhook, kanban, api). Auxiliary/stub calls (`configured_cache_ttl()`) treat `auto` as `5m`.+The CLI shows caching status at startup:```💾 Prompt caching: ENABLED (Claude via OpenRouter, 5m TTL)diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.mdindex 932334fa30d..d4064115862 100644--- a/website/docs/user-guide/configuration.md+++ b/website/docs/user-guide/configuration.md@@ -1362,10 +1362,12 @@ The one explicit knob is the cache TTL tier Hermes requests on Anthropic-style b```yamlprompt_caching:- cache_ttl: "5m" # "5m" or "1h" (Anthropic-supported tiers); other values are ignored+ cache_ttl: "5m" # "5m", "1h" (Anthropic-supported tiers) or "auto"; other values are ignored```-`cache_ttl` selects the breakpoint TTL Hermes attaches for Claude via the native Anthropic API, OpenRouter, and Nous Portal. Only the two Anthropic-supported tiers (`"5m"`, `"1h"`) are honored — any other value is ignored. Providers with their own caps (e.g. Qwen Cloud, which maxes at 5 minutes) still clamp to what the upstream allows.+`cache_ttl` selects the breakpoint TTL Hermes attaches for Claude via the native Anthropic API, OpenRouter, and Nous Portal. The two Anthropic tiers (`"5m"`, `"1h"`) are sent as-is; any other value is ignored. Providers with their own caps (e.g. Qwen Cloud, which maxes at 5 minutes) still clamp to what the upstream allows.++The 1h tier writes at 2x the base input price (5m writes at 1.25x) and only pays off when your turns are more than five minutes apart — otherwise every tool result is written at the dearer rate for retention nobody uses. `"auto"` picks the tier per session from who paces it: `1h` for sessions a person types into (CLI, TUI, Desktop, Telegram/Discord/Slack and the other messaging platforms), `5m` for machine-paced ones (subagents, cron, `hermes -q` one-shots, webhooks, Kanban workers, the API server). On an install where interactive sessions are parked and resumed through the day, `auto` cut the interactive cache-write bill by roughly 40% while leaving fan-out subagent spend untouched. Delegated subagents are always clamped to `5m`, whatever the setting.## Auxiliary Models