The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(telemetry): v5 efficiency metrics — turn cost, wasted tokens, tool output truncation, tool overhead, prompt-cache breaks
teknium1607dff390a32
diff --git a/agent/conversation_compression.py b/agent/conversation_compression.pyindex e0fa61a97ac..f3b61a3e954 100644--- a/agent/conversation_compression.py+++ b/agent/conversation_compression.py@@ -1499,7 +1499,7 @@ def _emit_compression_attempt_telemetry()from hermes_cli.observability.shared_metrics_events import finish_compression_attempt- finish_compression_attempt(commit_status, failure_class, getattr(agent.context_compressor, "context_length", None))+ finish_compression_attempt(commit_status, failure_class, getattr(agent.context_compressor, "context_length", None), agent=agent)def _existing_system_prompt(agent: Any, system_message: str) -> str:diff --git a/agent/conversation_loop.py b/agent/conversation_loop.pyindex c64b3125abd..379adf45e26 100644--- a/agent/conversation_loop.py+++ b/agent/conversation_loop.py@@ -34,6 +34,7 @@ from agent.surface_switch import (identity_line_value, note_inert_pinned_tools, runtime_host_value, stage_surface_switch_note,)from agent.turn_context import PreflightCompressionTimedOut, build_turn_context+from hermes_cli.observability.shared_metrics_efficiency import record_cache_break, record_prompt_rebuildfrom agent.turn_retry_state import TurnRetryState# Phase helpers of the turn loop, bound at import so a source-tree swap cannot load a# skewed phase mid-turn.@@ -782,6 +783,7 @@ def _restore_or_build_system_prompt(agent, system_message, conversation_history)pass_refresh_bot_chat_tools(agent)agent._cached_system_prompt = agent._build_system_prompt(system_message)+ record_cache_break(agent, "toolset_change")stage_surface_switch_note(agent, agent._cached_system_prompt, conversation_history)# Persist so the NEXT turn restores the new bytes verbatim (cache break is# once per capability change). Tools re-pin too: without it the next@@ -845,6 +847,8 @@ def _restore_or_build_system_prompt(agent, system_message, conversation_history)# persisted over the pin below. Pinned first, so the prompt describes the tools sent.built_for_this_surface = _restore_pinned_tools(agent, session_row)agent._cached_system_prompt = agent._build_system_prompt(system_message)+ if conversation_history:+ record_prompt_rebuild(agent, stored_prompt, stored_state, agent._cached_system_prompt)# The rebuilt prompt describes the CURRENT surface, but a surface note left in the# transcript by an earlier switch does not — retire it here too, or a rebuild for andiff --git a/agent/tool_executor.py b/agent/tool_executor.pyindex b89a9bda395..40905959b78 100644--- a/agent/tool_executor.py+++ b/agent/tool_executor.py@@ -57,6 +57,7 @@ from tools.tool_result_storage import (extract_persisted_path,)from tools.budget_config import BudgetConfig, DEFAULT_BUDGET, budget_for_context_window+from hermes_cli.observability.shared_metrics_efficiency import note_tool_result, record_tool_batch# A tool result this large (raw stdout, file dumps) is the biggest allocation a turn ever drops.# The commit only flags it: the string is still referenced by the publish frames here, so the@@ -1114,6 +1115,7 @@ def _commit_tool_result(config=budget,)_record_persisted_path_for_stub(agent, tool_call_id, persisted_result)+ note_tool_result(agent, function_name, tool_call_id, function_result, persisted_result)subdir_hints = agent._subdirectory_hints.check_tool_call(function_name, function_args)if subdir_hints:@@ -1187,7 +1189,10 @@ def _finalize_tool_batch(agent, messages: list, effective_task_id: str, num_toolsteer marker is never truncated/discarded when enforcement replaces a result."""if num_tools <= 0:return- enforce_turn_budget(messages[-num_tools:], env=get_active_env(effective_task_id), config=budget)+ batch = messages[-num_tools:]+ contents_before = [message.get("content") for message in batch]+ enforce_turn_budget(batch, env=get_active_env(effective_task_id), config=budget)+ record_tool_batch(agent, batch, contents_before)agent._apply_pending_steer_to_tool_results(messages, num_tools)diff --git a/agent/turn_api_request.py b/agent/turn_api_request.pyindex b00934cc722..1be4db0a628 100644--- a/agent/turn_api_request.py+++ b/agent/turn_api_request.py@@ -13,6 +13,7 @@ import loggingfrom typing import Anyfrom agent.message_sanitization import sanitize_outbound_kwargs, strip_images_for_rejecting_model+from hermes_cli.observability.shared_metrics_efficiency import observe_request_toolsfrom utils import env_var_enabledlogger = logging.getLogger("agent.conversation_loop")@@ -116,6 +117,7 @@ def build_api_request()# A model that rejected image content gets text only; history keeps the images.strip_images_for_rejecting_model(agent, api_messages)+ observe_request_tools(agent, tools_for_api)if tools_for_api == agent.tools:api_kwargs = agent._build_api_kwargs(api_messages)else:diff --git a/gateway/slash_commands_session.py b/gateway/slash_commands_session.pyindex 3e6bab37b60..48d1e77fb33 100644--- a/gateway/slash_commands_session.py+++ b/gateway/slash_commands_session.py@@ -429,7 +429,7 @@ class GatewaySessionCommandsMixin:text=last_user_msg, message_type=MessageType.TEXT, source=source,raw_message=event.raw_message, channel_prompt=event.channel_prompt))- def _record_model_friction(self, signal: str, source, session_id: str) -> None:+ def _record_model_friction(self, signal: str, source, session_id: str, turns: int = 1) -> None:"""Slash dispatch does not install the routed profile's scope, so a multiplexed runnernames the owning home explicitly."""from hermes_cli.observability.shared_metrics_model import record_model_friction@@ -437,7 +437,7 @@ class GatewaySessionCommandsMixin:if getattr(getattr(self, "config", None), "multiplex_profiles", False):with contextlib.suppress(Exception):home = self._resolve_profile_home_for_source(source)- record_model_friction(signal, session_id=session_id, hermes_home=home)+ record_model_friction(signal, session_id=session_id, hermes_home=home, turns=turns)async def _handle_undo_command(self, event: MessageEvent) -> str:"""Handle /undo [N] — back up N user turns (default 1), soft-deleting the truncated rows and@@ -456,7 +456,7 @@ class GatewaySessionCommandsMixin:if result is None:return t("gateway.undo.nothing")session_entry.last_prompt_tokens = 0 # transcript was truncated- self._record_model_friction("undo", source, session_entry.session_id)+ self._record_model_friction("undo", source, session_entry.session_id, result.get("turns_undone") or 1)try:# The cache is keyed by the profile-namespaced key; a bare build_session_key(source)# yields ``agent:main:…`` and misses for every secondary profile.diff --git a/hermes_cli/cli_loops_mixin.py b/hermes_cli/cli_loops_mixin.pyindex d3844204fbf..92f6858c3c4 100644--- a/hermes_cli/cli_loops_mixin.py+++ b/hermes_cli/cli_loops_mixin.py@@ -179,13 +179,13 @@ class CLILoopsMixin:return True # confirmation cancelled — command handled, keep REPL aliveself.new_session(title=title)- def _record_model_friction(self, signal: str) -> None:+ def _record_model_friction(self, signal: str, turns: int = 1) -> None:# The TUI slash worker's shadow CLI has no metrics surface: tui_gateway counts what it executes.if self._slash_metrics_surface:from hermes_cli.observability.shared_metrics_model import record_model_frictionrecord_model_friction(signal, session_id=getattr(self, "session_id", None), agent=getattr(self, "agent", None),- provider=getattr(self, "provider", None), model=getattr(self, "model", None))+ provider=getattr(self, "provider", None), model=getattr(self, "model", None), turns=turns)def _cmd_retry(self, cmd_original: str):retry_msg = self.retry_last()@@ -217,7 +217,7 @@ class CLILoopsMixin:_history = self.conversation_historyself.undo_last(_undo_n)if self.conversation_history is not _history: # only a successful rewind installs a new history- self._record_model_friction("undo")+ self._record_model_friction("undo", min(_undo_n, sum(isinstance(m, dict) and m.get("role") == "user" for m in _history)))def _cmd_skills(self, cmd_original: str):with self._busy_command(self._slow_command_status(cmd_original)):diff --git a/hermes_cli/observability/relay_shared_metrics.py b/hermes_cli/observability/relay_shared_metrics.pyindex 3880eef80fd..f9aacbcadc1 100644--- a/hermes_cli/observability/relay_shared_metrics.py+++ b/hermes_cli/observability/relay_shared_metrics.py@@ -8,7 +8,7 @@ import contextvarsimport loggingimport threadingimport uuid-from collections import deque+from collections import OrderedDict, dequefrom dataclasses import dataclass, fieldfrom time import monotonic_nsfrom typing import Any, Callable@@ -19,6 +19,7 @@ from hermes_cli.version_info import get_version_infofrom .shared_metrics import SharedMetricsStorefrom . import shared_metrics_contract as contract+from . import shared_metrics_efficiency as efffrom . import shared_metrics_fields as fields_from . import shared_metrics_model as model_from .shared_metrics_contract import MODEL_CALL_SCOPE, SUBSCRIBER_NAME, TASK_SCOPE@@ -111,6 +112,7 @@ class _ModelCall:fields: dict[str, str]error_class: str = "none"ttft_bucket: str = "unknown"+ started_ns: int = field(default_factory=monotonic_ns)@dataclass@@ -137,6 +139,7 @@ class _TaskRun:unidentified_tool_calls: int = 0retry_count: int = 0model_route: dict[str, str] | None = None+ cost: eff.TurnCost = field(default_factory=eff.TurnCost)@dataclass@@ -158,6 +161,7 @@ class _MetricsSession:last_turn_ns: int = 0model_state: model_.ModelSessionState = field(default_factory=model_.ModelSessionState)lineage_root: str = ""+ efficiency: eff.SessionEfficiency = field(default_factory=eff.SessionEfficiency)@dataclass@@ -166,6 +170,7 @@ class _PeakLineage:open: set[str] = field(default_factory=set)peak: model_.ModelSessionState = field(default_factory=model_.ModelSessionState)+ tools: eff.ToolUsage = field(default_factory=eff.ToolUsage)def _absorb_peak(into: model_.ModelSessionState, segment: model_.ModelSessionState) -> None:@@ -197,6 +202,9 @@ class _Runtime:# Leaf lock (nothing is acquired under it): taken while a session.lock is held.self._lineages: dict[str, _PeakLineage] = {}self._lineage_lock = threading.Lock()+ # Leaf lock: conversations whose next cold cache read Hermes already announced.+ self._cold_expected: OrderedDict[str, None] = OrderedDict()+ self._cold_lock = threading.Lock()self._task_creation_lock = threading.RLock()self._task_sessions_lock = threading.RLock()# Guards the opt-in send pass: at most one in flight per process.@@ -313,6 +321,12 @@ class _Runtime:self._remember_turn(session, task, event)return task+ def start_user_turn(self, event: dict[str, Any]) -> None:+ """pre_llm_call: a user message started this task (Hermes-owned forks never fire it)."""+ task = self.start_task(event)+ if task is not None:+ task.cost.user_turn = True+def _run_in_task(self, task: _TaskRun, callback: Callable[..., Any], *args: Any, **kwargs: Any) -> Any:@@ -383,6 +397,7 @@ class _Runtime:self._join_lineage(session, session.tasks.get(model_call.task_id))if finish:session.model_state.observe_call(model_call.fields, event.get("usage"), event.get("context_length"))+ self._observe_turn_call(session, session.tasks.get(model_call.task_id), model_call, event)model_call.ttft_bucket = fields_.ttft_bucket(event)self._finish_model_call(session, model_call_key, "success")tokens = fields_.model_token_fields(@@ -473,6 +488,8 @@ class _Runtime:task.unidentified_tool_calls += 1if tool_call is None:tool_call = self._open_tool_call(task, event)+ if task.cost.user_turn:+ session.efficiency.tools.used.add(eff.toolset_metric_name(event.get("toolset")))self._finish_tool_call(task, tool_call, event)def record_skill_lifecycle(self, event: dict[str, Any]) -> None:@@ -863,6 +880,74 @@ class _Runtime:"Hermes shared-metrics friction mark failed", self._mark,session, None, contract.MODEL_FRICTION_MARK, model_.friction_fields("interrupt", route),)+ if task.cost.user_turn and model_.attended(task.start_fields):+ rows = session.efficiency.finish_turn(+ task.cost, fields, route=route, model_calls=len(task.model_call_ids),+ tool_calls=len(task.tool_call_ids) + task.unidentified_tool_calls,+ )+ self._emit_rows(session, rows)++ def _emit_rows(self, session: _MetricsSession | None, rows: list[tuple[str, dict[str, str]]]) -> None:+ for mark, data in rows:+ if session is None:+ self._guarded("Hermes shared-metrics efficiency mark failed", self.record_process_mark, mark, data)+ else:+ self._guarded("Hermes shared-metrics efficiency mark failed", self._mark, session, None, mark, data)++ def _observe_turn_call(+ self, session: _MetricsSession, task: _TaskRun | None, model_call: _ModelCall, event: dict[str, Any]+ ) -> None:+ """One finished primary call of a user turn: its tokens, and a cold cache read nobody announced."""+ if task is None or not task.cost.user_turn:+ return+ route, usage = model_call.fields, event.get("usage")+ task.cost.add_call(route, usage)+ expected = self._consume_cold(self._cold_key(session.session_id))+ cause = session.efficiency.observe_cache(route, usage, model_call.started_ns, monotonic_ns(), expected=expected)+ if cause is not None:+ self._emit_rows(session, [eff.cache_break_row(cause, route)])++ @staticmethod+ def _cold_key(session_id: str) -> str:+ """The conversation (lineage root survives compression rotation), else the session."""+ return get_conversation_context() or session_id++ def _announce_cold(self, key: str) -> bool:+ """Expect the next read of ``key`` to be cold; False when a break was already announced."""+ with self._cold_lock:+ if key in self._cold_expected:+ return False+ self._cold_expected[key] = None+ while len(self._cold_expected) > 256:+ self._cold_expected.popitem(last=False)+ return True++ def _consume_cold(self, key: str) -> bool:+ with self._cold_lock:+ return self._cold_expected.pop(key, False) is None++ def record_known_cache_break(self, cause: str, route: dict[str, str], session_id: str) -> None:+ """Hermes invalidated the prefix itself: count it, and don't recount the cold read it causes."""+ self._announce_cold(self._cold_key(session_id))+ self._emit_rows(None, [eff.cache_break_row(cause, route)])++ def record_session_tools(self, session_id: str, agent: Any, tools_for_api: list) -> None:+ session = self._session({"session_id": session_id}) if session_id else None+ if session is None:+ return+ key = (id(getattr(agent, "tools", None)), id(tools_for_api), len(tools_for_api))+ with session.lock:+ if session.closing or session.efficiency.tools_key == key:+ return+ snapshot = eff.tool_snapshot(agent, tools_for_api) # registry + estimator: outside the lock+ with session.lock:+ if session.closing:+ return+ session.efficiency.tools_key = key+ changed = session.efficiency.tools.observe(*snapshot)+ route = model_.model_route(getattr(agent, "provider", None), getattr(agent, "model", None))+ if changed and self._announce_cold(self._cold_key(session_id)):+ self._emit_rows(session, [eff.cache_break_row("toolset_change", route)])def _join_lineage(self, session: _MetricsSession, task: _TaskRun | None) -> None:"""Compression rotates the session id mid-conversation. The turn publishes the lineage root@@ -877,24 +962,30 @@ class _Runtime:with self._lineage_lock:self._lineages.setdefault(root, _PeakLineage()).open.add(session.session_id)- def _context_peak_fields(self, session: _MetricsSession, counted: bool) -> dict[str, str] | None:- """This session's peak, or, for a lineage segment, the conversation's merged peak once its- last open segment closes (None before that)."""+ def _close_lineage_segment(+ self, session: _MetricsSession, counted: bool+ ) -> tuple[dict[str, str] | None, eff.ToolUsage | None]:+ """This session's context peak and tool usage, or, for a lineage segment, the conversation's+ merged ones once its last open segment closes (None before that)."""state = session.model_state if counted else None+ tools = session.efficiency.tools if counted and model_.attended(session.start_fields) else eff.ToolUsage()+ tools.surface = (session.start_fields or {}).get("execution_surface", "unknown")with self._lineage_lock:lineage = self._lineages.get(session.lineage_root) if session.lineage_root else Noneif lineage is None:- return state.context_peak_fields() if state is not None else None+ return (state.context_peak_fields() if state is not None else None), toolslineage.open.discard(session.session_id)if state is not None:_absorb_peak(lineage.peak, state)+ lineage.tools.absorb(tools)if lineage.open:- return None+ return None, Nonedel self._lineages[session.lineage_root]- return lineage.peak.context_peak_fields()+ return lineage.peak.context_peak_fields(), lineage.toolsdef _emit_model_session_marks(self, session: _MetricsSession, counted: bool) -> None:- marks = [(contract.CONTEXT_PEAK_MARK, self._context_peak_fields(session, counted))]+ peak, tools = self._close_lineage_segment(session, counted)+ marks = [(contract.CONTEXT_PEAK_MARK, peak), *(tools.rows() if tools is not None else ())]abandoned = session.model_state.quick_abandon_route(monotonic_ns()) if counted else Noneif abandoned is not None and model_.attended(session.start_fields):marks.append((contract.MODEL_FRICTION_MARK, model_.friction_fields("quick_abandon", abandoned)))@@ -902,16 +993,22 @@ class _Runtime:if data is not None:self._guarded("Hermes shared-metrics model session mark failed", self._mark, session, None, mark, data)- def record_friction(self, signal: str, session_id: str, fallback_route: dict[str, str]) -> None:- """A user friction action, attributed to the session's last primary model when known."""+ def record_friction(self, signal: str, session_id: str, fallback_route: dict[str, str], turns: int = 1) -> None:+ """A user friction action, attributed to the session's last primary model when known; an+ /undo or /retry also counts the tokens of the turns it threw away."""session = self._session({"session_id": session_id}) if session_id else None- route = None- if session is not None:- with session.lock:+ route, wasted = None, []+ # A session this process never saw (restart, remote host) still counts, with tokens unknown.+ with session.lock if session is not None else contextlib.nullcontext():+ if session is not None:route = session.model_state.last_route+ if signal in contract.WASTE_REASONS:+ efficiency = session.efficiency if session is not None else eff.SessionEfficiency()+ wasted = efficiency.discard_turns(signal, turns, route or fallback_route)data = model_.friction_fields(signal, route or fallback_route)if data is not None:self.record_process_mark(contract.MODEL_FRICTION_MARK, data)+ self._emit_rows(None, wasted)def _emit_session_summary(self, session: _MetricsSession) -> None:"""One hermes.session.count row per closed top-level session (delegated children excluded)."""@@ -1137,7 +1234,7 @@ def _close_child_session(runtime: _Runtime, kwargs: dict[str, Any]) -> None:_HOOK_HANDLERS: dict[str, Callable[[_Runtime, dict[str, Any]], Any]] = {"on_session_start": lambda rt, kw: rt.record_client_active(kw),- "pre_llm_call": lambda rt, kw: rt.start_task(kw),+ "pre_llm_call": lambda rt, kw: rt.start_user_turn(kw),"pre_api_request": lambda rt, kw: rt.start_model_call(kw),"pre_tool_call": lambda rt, kw: rt.start_tool_call(_with_runtime_toolset(kw)),"post_tool_call": lambda rt, kw: rt.record_tool_call(_with_runtime_toolset(kw)),@@ -1211,13 +1308,29 @@ def record_process_marks_saved(marks: list[tuple[str, dict[str, Any]]]) -> int:return (runtime._safe(runtime.record_process_marks_saved, marks) or 0) if runtime is not None else 0-def record_session_friction(signal: str, session_id: str, fallback_route: dict[str, str]) -> None:+def record_session_friction(signal: str, session_id: str, fallback_route: dict[str, str], turns: int = 1) -> None:"""Record one friction signal in the active profile's runtime (callers already checked enabled())."""if not relay_runtime.relay_instrumentation_enabled():returnruntime = _get_runtime(retry_failed=True)if runtime is not None:- runtime._safe(runtime.record_friction, signal, session_id, fallback_route)+ runtime._safe(runtime.record_friction, signal, session_id, fallback_route, turns)+++def record_session_tools(session_id: str, agent: Any, tools_for_api: list) -> None:+ """The tools one primary request sent (caller checked enabled()); never creates a runtime."""+ runtime = _RUNTIMES.get(relay_runtime.current_profile_key())+ if isinstance(runtime, _Runtime):+ runtime._safe(runtime.record_session_tools, session_id, agent, tools_for_api)+++def record_known_cache_break(cause: str, route: dict[str, str], session_id: str) -> None:+ """A prompt-cache break Hermes caused (caller checked enabled())."""+ if not relay_runtime.relay_instrumentation_enabled():+ return+ runtime = _get_runtime(retry_failed=True)+ if runtime is not None:+ runtime._safe(runtime.record_known_cache_break, cause, route, session_id)def _run_task_hook(method: str, *, retry_failed: bool = False, **event: Any) -> None:diff --git a/hermes_cli/observability/schemas/hermes.shared_metrics.v3.schema.json b/hermes_cli/observability/schemas/hermes.shared_metrics.v3.schema.jsonindex f9f9195c19c..2911dd478cf 100644--- a/hermes_cli/observability/schemas/hermes.shared_metrics.v3.schema.json+++ b/hermes_cli/observability/schemas/hermes.shared_metrics.v3.schema.json@@ -210,6 +210,24 @@},{"$ref": "#/$defs/model_reply_issue_counter"+ },+ {+ "$ref": "#/$defs/task_cost_counter"+ },+ {+ "$ref": "#/$defs/wasted_tokens_counter"+ },+ {+ "$ref": "#/$defs/tool_output_truncation_counter"+ },+ {+ "$ref": "#/$defs/tool_overhead_counter"+ },+ {+ "$ref": "#/$defs/tool_enabled_unused_counter"+ },+ {+ "$ref": "#/$defs/cache_break_counter"}]}@@ -2812,6 +2830,421 @@"minimum": 1}}+ },+ "task_cost_counter": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "name",+ "type",+ "dimensions",+ "value"+ ],+ "properties": {+ "name": {+ "const": "hermes.task_cost.count"+ },+ "type": {+ "const": "counter"+ },+ "dimensions": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "api_calls_bucket",+ "model",+ "outcome",+ "provider",+ "tokens_bucket",+ "tool_calls_bucket"+ ],+ "properties": {+ "api_calls_bucket": {+ "enum": [+ "0",+ "1",+ "2",+ "3_to_5",+ "6_to_10",+ "11_to_25",+ "26_to_50",+ "51_to_100",+ "gte_101"+ ]+ },+ "model": {+ "type": "string",+ "minLength": 1,+ "maxLength": 256,+ "pattern": "^[a-z0-9][a-z0-9._:/@+\\-]*$"+ },+ "outcome": {+ "enum": [+ "completed",+ "failed",+ "interrupted"+ ]+ },+ "provider": {+ "$ref": "#/$defs/provider_identifier"+ },+ "tokens_bucket": {+ "enum": [+ "lt_2k",+ "2k_to_10k",+ "10k_to_50k",+ "50k_to_200k",+ "200k_to_1m",+ "gte_1m",+ "unknown"+ ]+ },+ "tool_calls_bucket": {+ "enum": [+ "0",+ "1",+ "2",+ "3_to_5",+ "6_to_10",+ "11_to_25",+ "26_to_50",+ "51_to_100",+ "gte_101"+ ]+ }+ },+ "description": "One per user turn the user saw end: what it cost (prompt + completion tokens over its primary calls) and how much work it took."+ },+ "value": {+ "type": "integer",+ "minimum": 1+ }+ }+ },+ "wasted_tokens_counter": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "name",+ "type",+ "dimensions",+ "value"+ ],+ "properties": {+ "name": {+ "const": "hermes.wasted_tokens.count"+ },+ "type": {+ "const": "counter"+ },+ "dimensions": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "model",+ "provider",+ "reason",+ "tokens_bucket"+ ],+ "properties": {+ "model": {+ "type": "string",+ "minLength": 1,+ "maxLength": 256,+ "pattern": "^[a-z0-9][a-z0-9._:/@+\\-]*$"+ },+ "provider": {+ "$ref": "#/$defs/provider_identifier"+ },+ "reason": {+ "enum": [+ "interrupt",+ "retry",+ "undo"+ ]+ },+ "tokens_bucket": {+ "enum": [+ "lt_2k",+ "2k_to_10k",+ "10k_to_50k",+ "50k_to_200k",+ "200k_to_1m",+ "gte_1m",+ "unknown"+ ]+ }+ },+ "description": "One per user turn thrown away by an interrupt, /retry or /undo, with the tokens it had spent."+ },+ "value": {+ "type": "integer",+ "minimum": 1+ }+ }+ },+ "tool_output_truncation_counter": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "name",+ "type",+ "dimensions",+ "value"+ ],+ "properties": {+ "name": {+ "const": "hermes.tool_output_truncation.count"+ },+ "type": {+ "const": "counter"+ },+ "dimensions": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "original_size_bucket",+ "tool",+ "truncated"+ ],+ "properties": {+ "original_size_bucket": {+ "enum": [+ "lt_1k",+ "1k_to_10k",+ "10k_to_50k",+ "50k_to_100k",+ "100k_to_500k",+ "gte_500k",+ "unknown"+ ]+ },+ "tool": {+ "$ref": "#/$defs/vocabulary_identifier"+ },+ "truncated": {+ "enum": [+ "no",+ "yes"+ ]+ }+ },+ "description": "One per tool result: whether Hermes spilled or truncated it (per-result cap or per-turn budget), by raw size."+ },+ "value": {+ "type": "integer",+ "minimum": 1+ }+ }+ },+ "tool_overhead_counter": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "name",+ "type",+ "dimensions",+ "value"+ ],+ "properties": {+ "name": {+ "const": "hermes.tool_overhead.count"+ },+ "type": {+ "const": "counter"+ },+ "dimensions": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "enabled_tool_count_bucket",+ "execution_surface",+ "tool_schema_tokens_bucket"+ ],+ "properties": {+ "enabled_tool_count_bucket": {+ "$ref": "#/$defs/size_bucket"+ },+ "execution_surface": {+ "$ref": "#/$defs/execution_surface"+ },+ "tool_schema_tokens_bucket": {+ "enum": [+ "0",+ "lt_2k",+ "2k_to_5k",+ "5k_to_10k",+ "10k_to_20k",+ "20k_to_40k",+ "gte_40k"+ ]+ }+ },+ "description": "One per closed interactive conversation: how many tools it had enabled and the estimated tokens their definitions cost per request."+ },+ "value": {+ "type": "integer",+ "minimum": 1+ }+ }+ },+ "tool_enabled_unused_counter": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "name",+ "type",+ "dimensions",+ "value"+ ],+ "properties": {+ "name": {+ "const": "hermes.tool_enabled_unused.count"+ },+ "type": {+ "const": "counter"+ },+ "dimensions": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "toolset",+ "used"+ ],+ "properties": {+ "toolset": {+ "enum": [+ "bot_room",+ "browser",+ "clarify",+ "code_execution",+ "coding",+ "computer_use",+ "connections",+ "context_engine",+ "cronjob",+ "custom",+ "debugging",+ "delegation",+ "desktop_ui",+ "discord",+ "discord_admin",+ "feishu_doc",+ "feishu_drive",+ "file",+ "hermes-acp",+ "hermes-api-server",+ "hermes-bluebubbles",+ "hermes-cli",+ "hermes-cron",+ "hermes-dingtalk",+ "hermes-discord",+ "hermes-email",+ "hermes-feishu",+ "hermes-gateway",+ "hermes-homeassistant",+ "hermes-matrix",+ "hermes-mattermost",+ "hermes-qqbot",+ "hermes-signal",+ "hermes-slack",+ "hermes-sms",+ "hermes-telegram",+ "hermes-webhook",+ "hermes-wecom",+ "hermes-wecom-callback",+ "hermes-weixin",+ "hermes-whatsapp",+ "hermes-yuanbao",+ "homeassistant",+ "image_gen",+ "kanban",+ "memory",+ "project",+ "safe",+ "search",+ "session_search",+ "setup",+ "skills",+ "spotify",+ "terminal",+ "todo",+ "tts",+ "video",+ "video_gen",+ "vision",+ "web",+ "x_search",+ "yuanbao"+ ]+ },+ "used": {+ "enum": [+ "no",+ "yes"+ ]+ }+ },+ "description": "One per enabled shipped toolset per closed interactive conversation (MCP/plugin/user toolsets read custom): whether any of its tools ran."+ },+ "value": {+ "type": "integer",+ "minimum": 1+ }+ }+ },+ "cache_break_counter": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "name",+ "type",+ "dimensions",+ "value"+ ],+ "properties": {+ "name": {+ "const": "hermes.cache_break.count"+ },+ "type": {+ "const": "counter"+ },+ "dimensions": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "cause",+ "model",+ "provider"+ ],+ "properties": {+ "cause": {+ "enum": [+ "cache_expired",+ "compression",+ "model_switch",+ "provider_reported_miss",+ "system_prompt_rebuild",+ "toolset_change"+ ]+ },+ "model": {+ "type": "string",+ "minLength": 1,+ "maxLength": 256,+ "pattern": "^[a-z0-9][a-z0-9._:/@+\\-]*$"+ },+ "provider": {+ "$ref": "#/$defs/provider_identifier"+ }+ },+ "description": "A prompt-cache break mid-conversation: a cause Hermes knows (compression is expected), or a cold provider read after a warm one on the same route."+ },+ "value": {+ "type": "integer",+ "minimum": 1+ }+ }}}}diff --git a/hermes_cli/observability/shared_metrics_contract.py b/hermes_cli/observability/shared_metrics_contract.pyindex 6c87cb8b90b..101a1cfb812 100644--- a/hermes_cli/observability/shared_metrics_contract.py+++ b/hermes_cli/observability/shared_metrics_contract.py@@ -13,7 +13,7 @@ from agent.relay_runtime import (RUNTIME_SCHEMA_VERSION,)from hermes_cli.platforms import PLATFORMS-from toolsets import BUILTIN_TOOL_NAMES+from toolsets import BUILTIN_TOOL_NAMES, BUILTIN_TOOLSET_NAMESSCHEMA_KEY = "hermes.metrics.schema_version"# A random per-emit token (no payload) on rows whose producer waits to learn they were SAVED: facts@@ -372,6 +372,39 @@ TERMINAL_COMMAND_KINDS = frozenset({TERMINAL_OUTCOMES = frozenset({"killed", "nonzero", "ok", "timeout"})MODEL_REPLY_ISSUES = frozenset({"empty", "none", "reasoning_only", "refusal", "truncated_length"})# ---- end v5 harness ----+# ---- v5 efficiency ----+TASK_COST_MARK = TASK_COST_METRIC = "hermes.task_cost.count"+WASTED_TOKENS_MARK = WASTED_TOKENS_METRIC = "hermes.wasted_tokens.count"+TOOL_OUTPUT_TRUNCATION_MARK = TOOL_OUTPUT_TRUNCATION_METRIC = "hermes.tool_output_truncation.count"+TOOL_OVERHEAD_MARK = TOOL_OVERHEAD_METRIC = "hermes.tool_overhead.count"+TOOL_ENABLED_UNUSED_MARK = TOOL_ENABLED_UNUSED_METRIC = "hermes.tool_enabled_unused.count"+CACHE_BREAK_MARK = CACHE_BREAK_METRIC = "hermes.cache_break.count"+# Prompt + completion tokens of one user turn, summed over its primary calls.+TURN_TOKEN_BUCKETS = frozenset({+ "lt_2k", "2k_to_10k", "10k_to_50k", "50k_to_200k", "200k_to_1m", "gte_1m", "unknown",+})+TASK_COST_OUTCOMES = frozenset({"completed", "failed", "interrupted"})+# Tool and API calls of one agentic turn: COUNT_BUCKETS stops at gte_11, far below real loops.+TURN_ACTIVITY_BUCKETS = frozenset({+ "0", "1", "2", "3_to_5", "6_to_10", "11_to_25", "26_to_50", "51_to_100", "gte_101",+})+WASTE_REASONS = frozenset({"interrupt", "retry", "undo"})+# Characters of one raw tool result, before Hermes spills or truncates it.+TOOL_OUTPUT_SIZE_BUCKETS = frozenset({+ "lt_1k", "1k_to_10k", "10k_to_50k", "50k_to_100k", "100k_to_500k", "gte_500k", "unknown",+})+TOOL_SCHEMA_TOKEN_BUCKETS = frozenset({+ "0", "lt_2k", "2k_to_5k", "5k_to_10k", "10k_to_20k", "20k_to_40k", "gte_40k",+})+# Toolsets Hermes ships; MCP servers and plugin toolsets collapse to custom.+TOOLSET_NAMES = BUILTIN_TOOLSET_NAMES | {"custom"}+# compression is the expected cause; the rest are Hermes invalidating a warm prefix (bugs or+# user-driven), or the provider reporting a cold read Hermes did not cause.+CACHE_BREAK_CAUSES = frozenset({+ "cache_expired", "compression", "model_switch", "provider_reported_miss", "system_prompt_rebuild",+ "toolset_change",+})+# ---- end v5 efficiency ----_ARCHITECTURE_ALIASES = {"amd64": "x86_64", "x64": "x86_64", "x86_64": "x86_64",@@ -579,6 +612,22 @@ _COUNTER_DIMENSION_VALUES: dict[str, dict[str, frozenset[str]]] = {},MODEL_REPLY_ISSUE_METRIC: {"issue": MODEL_REPLY_ISSUES},# ---- end v5 harness ----+ # ---- v5 efficiency ----+ TASK_COST_METRIC: {+ "api_calls_bucket": TURN_ACTIVITY_BUCKETS, "outcome": TASK_COST_OUTCOMES,+ "tokens_bucket": TURN_TOKEN_BUCKETS, "tool_calls_bucket": TURN_ACTIVITY_BUCKETS,+ },+ WASTED_TOKENS_METRIC: {"reason": WASTE_REASONS, "tokens_bucket": TURN_TOKEN_BUCKETS},+ TOOL_OUTPUT_TRUNCATION_METRIC: {+ "original_size_bucket": TOOL_OUTPUT_SIZE_BUCKETS, "tool": TOOL_NAMES, "truncated": YES_NO,+ },+ TOOL_OVERHEAD_METRIC: {+ "enabled_tool_count_bucket": SIZE_BUCKETS, "execution_surface": EXECUTION_SURFACES,+ "tool_schema_tokens_bucket": TOOL_SCHEMA_TOKEN_BUCKETS,+ },+ TOOL_ENABLED_UNUSED_METRIC: {"toolset": TOOLSET_NAMES, "used": YES_NO},+ CACHE_BREAK_METRIC: {"cause": CACHE_BREAK_CAUSES},+ # ---- end v5 efficiency ----}_MODEL_ROUTE_MAX_LENGTHS = {"model": MODEL_IDENTIFIER_MAX_LENGTH, "provider": PROVIDER_IDENTIFIER_MAX_LENGTH,@@ -601,6 +650,11 @@ _IDENTIFIER_FIELDS: dict[str, dict[str, int]] = {TOOL_RECOVERY_METRIC: _MODEL_ROUTE_MAX_LENGTHS,MODEL_REPLY_ISSUE_METRIC: _MODEL_ROUTE_MAX_LENGTHS,# ---- end v5 harness ----+ # ---- v5 efficiency ----+ TASK_COST_METRIC: _MODEL_ROUTE_MAX_LENGTHS,+ WASTED_TOKENS_METRIC: _MODEL_ROUTE_MAX_LENGTHS,+ CACHE_BREAK_METRIC: _MODEL_ROUTE_MAX_LENGTHS,+ # ---- end v5 efficiency ----}# metric -> closed dimension field set_METRIC_FIELDS: dict[str, frozenset[str]] = {@@ -657,6 +711,11 @@ _DECISION_MARK_METRICS = {TOOL_RECOVERY_MARK: TOOL_RECOVERY_METRIC, TERMINAL_OUTCOME_MARK: TERMINAL_OUTCOME_METRIC,MODEL_REPLY_ISSUE_MARK: MODEL_REPLY_ISSUE_METRIC,# ---- end v5 harness ----+ # ---- v5 efficiency ----+ TASK_COST_MARK: TASK_COST_METRIC, WASTED_TOKENS_MARK: WASTED_TOKENS_METRIC,+ TOOL_OUTPUT_TRUNCATION_MARK: TOOL_OUTPUT_TRUNCATION_METRIC, TOOL_OVERHEAD_MARK: TOOL_OVERHEAD_METRIC,+ TOOL_ENABLED_UNUSED_MARK: TOOL_ENABLED_UNUSED_METRIC, CACHE_BREAK_MARK: CACHE_BREAK_METRIC,+ # ---- end v5 efficiency ----}diff --git a/hermes_cli/observability/shared_metrics_efficiency.py b/hermes_cli/observability/shared_metrics_efficiency.pynew file mode 100644index 00000000000..5426a665312--- /dev/null+++ b/hermes_cli/observability/shared_metrics_efficiency.py@@ -0,0 +1,363 @@+"""Efficiency shared metrics: what one user turn costs, what users throw away, and where Hermes+spends tokens it did not have to (spilled tool output, idle tool schemas, prompt-cache breaks).++Per-turn state lives on the relay runtime's task/session objects (see ``TurnCost`` and+``SessionEfficiency``); the agent-side entry points below run on the agent thread and are no-ops+unless shared metrics are enabled. Provider/model always go through the catalog helpers.+"""++from __future__ import annotations++import logging+import re+from collections import deque+from dataclasses import dataclass, field+from typing import Any, Iterable++from . import shared_metrics_contract as contract+from .shared_metrics_contract import _bucket, _non_negative_number++logger = logging.getLogger(__name__)++_TOKEN_THRESHOLDS = (+ (2_000, "lt_2k"), (10_000, "2k_to_10k"), (50_000, "10k_to_50k"), (200_000, "50k_to_200k"),+ (1_000_000, "200k_to_1m"),+)+_ACTIVITY_THRESHOLDS = (+ (1, "0"), (2, "1"), (3, "2"), (6, "3_to_5"), (11, "6_to_10"), (26, "11_to_25"), (51, "26_to_50"),+ (101, "51_to_100"),+)+_OUTPUT_SIZE_THRESHOLDS = (+ (1_000, "lt_1k"), (10_000, "1k_to_10k"), (50_000, "10k_to_50k"), (100_000, "50k_to_100k"),+ (500_000, "100k_to_500k"),+)+_SCHEMA_TOKEN_THRESHOLDS = (+ (1, "0"), (2_000, "lt_2k"), (5_000, "2k_to_5k"), (10_000, "5k_to_10k"), (20_000, "10k_to_20k"),+ (40_000, "20k_to_40k"),+)+_TASK_COST_OUTCOMES = {"success": "completed", "cancelled": "interrupted"}+# Anthropic's default prompt-cache TTL: a cold read after this idle gap is expiry, not a bug.+CACHE_TTL_S = 300.0+# Per-session memory of spent turns an /undo or /retry can still reach.+_SPENT_TURNS_KEPT = 64+_PENDING_OUTPUTS_ATTR = "_shared_metrics_tool_outputs"+_PENDING_OUTPUTS_MAX = 256+# The one notice tools/tool_output_truncate.py writes when terminal, execute_code or MCP output was+# cut down inside the tool, before Hermes ever saw the full text.+_TOOL_TRUNCATION_NOTICE = re.compile(r"\[[A-Z_ ]{1,32} TRUNCATED - [\d,]{1,20} chars omitted out of ([\d,]{1,20}) total\]")+_NOTICE_MIN_CHARS = 1_000+++def tokens_bucket(tokens: int | None) -> str:+ return "unknown" if tokens is None else _bucket(max(0, tokens), _TOKEN_THRESHOLDS, "gte_1m")+++def activity_bucket(count: int) -> str:+ return _bucket(max(0, int(count)), _ACTIVITY_THRESHOLDS, "gte_101")+++def output_size_bucket(size: int | None) -> str:+ return "unknown" if size is None else _bucket(max(0, size), _OUTPUT_SIZE_THRESHOLDS, "gte_500k")+++def schema_tokens_bucket(tokens: int) -> str:+ return _bucket(max(0, int(tokens)), _SCHEMA_TOKEN_THRESHOLDS, "gte_40k")+++def _int(value: Any) -> int | None:+ number = _non_negative_number(value)+ return None if number is None else int(number)+++def call_tokens(usage: Any) -> int | None:+ """Prompt (cache reads/writes included) plus completion tokens of one call; None without usage."""+ if not isinstance(usage, dict):+ return None+ total = _int(usage.get("total_tokens"))+ if total is not None:+ return total+ parts = [_int(usage.get(key)) for key in (+ "input_tokens", "output_tokens", "cache_read_tokens", "cache_write_tokens")]+ return sum(p for p in parts if p is not None) if any(p is not None for p in parts) else None+++def toolset_metric_name(toolset: Any) -> str:+ """A shipped toolset's own name; MCP servers, plugins and user toolsets read ``custom``."""+ return toolset if isinstance(toolset, str) and toolset in contract.BUILTIN_TOOLSET_NAMES else "custom"+++def _route(route: dict[str, str] | None) -> dict[str, str]:+ from .shared_metrics_model import model_route++ return dict(route) if route else model_route(None, None)+++# ---- per-turn cost and waste (runtime state; caller holds session.lock) ------------------------++@dataclass+class TurnCost:+ """Token spend of one task; ``user_turn`` marks a turn a user message started (pre_llm_call),+ which Hermes-owned forks sharing the session id never fire."""++ user_turn: bool = False+ tokens: int = 0+ known: bool = False+ route: dict[str, str] | None = None++ def add_call(self, route: dict[str, str], usage: Any) -> None:+ self.route = route+ tokens = call_tokens(usage)+ if tokens is not None:+ self.tokens += tokens+ self.known = True++ def bucket(self) -> str:+ return tokens_bucket(self.tokens if self.known else None)+++@dataclass+class _SpentTurn:+ route: dict[str, str]+ tokens_bucket: str+ wasted: bool = False+++def _wasted_row(reason: str, turn: _SpentTurn) -> tuple[str, dict[str, str]]:+ return contract.WASTED_TOKENS_MARK, {**turn.route, "reason": reason, "tokens_bucket": turn.tokens_bucket}+++@dataclass+class ToolUsage:+ """What the session paid to carry tool definitions, and which shipped toolsets it touched."""++ observed: bool = False+ surface: str = "unknown"+ enabled_toolsets: frozenset[str] = frozenset()+ enabled_count: int = 0+ schema_tokens: int = 0+ names: tuple[str, ...] | None = None+ used: set[str] = field(default_factory=set)++ def observe(self, names: tuple[str, ...], toolsets: frozenset[str], enabled_count: int, schema_tokens: int) -> bool:+ """Record the tools one request sent; True when a later request changed the array."""+ changed = self.names is not None and names != self.names+ self.observed, self.names = True, names+ self.enabled_toolsets = self.enabled_toolsets | toolsets+ self.enabled_count, self.schema_tokens = max(self.enabled_count, enabled_count), schema_tokens+ return changed++ def absorb(self, other: ToolUsage) -> None:+ if not other.observed:+ return+ self.observed, self.surface = True, other.surface+ self.enabled_toolsets = self.enabled_toolsets | other.enabled_toolsets+ self.enabled_count = max(self.enabled_count, other.enabled_count)+ self.schema_tokens = max(self.schema_tokens, other.schema_tokens)+ self.used |= other.used++ def rows(self) -> list[tuple[str, dict[str, str]]]:+ if not self.observed:+ return []+ rows = [(contract.TOOL_OVERHEAD_MARK, {+ "enabled_tool_count_bucket": contract.size_bucket(self.enabled_count),+ "execution_surface": self.surface,+ "tool_schema_tokens_bucket": schema_tokens_bucket(self.schema_tokens),+ })]+ rows.extend(+ (contract.TOOL_ENABLED_UNUSED_MARK, {"toolset": name, "used": "yes" if name in self.used else "no"})+ for name in sorted(self.enabled_toolsets)+ )+ return rows+++@dataclass+class SessionEfficiency:+ spent: deque[_SpentTurn] = field(default_factory=lambda: deque(maxlen=_SPENT_TURNS_KEPT))+ tools: ToolUsage = field(default_factory=ToolUsage)+ tools_key: tuple[int, int, int] | None = None+ cache_read: int = 0+ cache_route: dict[str, str] | None = None+ cache_ended_ns: int = 0++ def finish_turn(+ self, cost: TurnCost, terminal: dict[str, str], *, route: dict[str, str] | None,+ model_calls: int, tool_calls: int,+ ) -> list[tuple[str, dict[str, str]]]:+ """task_cost for one user turn the user saw end; an interrupt also counts its tokens wasted."""+ turn = _SpentTurn(_route(cost.route or route), cost.bucket())+ rows = [(contract.TASK_COST_MARK, {+ **turn.route,+ "api_calls_bucket": activity_bucket(model_calls),+ "outcome": _TASK_COST_OUTCOMES.get(terminal.get("outcome", ""), "failed"),+ "tokens_bucket": turn.tokens_bucket,+ "tool_calls_bucket": activity_bucket(tool_calls),+ })]+ if terminal.get("end_reason") == "user_cancelled":+ turn.wasted = True+ rows.append(_wasted_row("interrupt", turn))+ self.spent.append(turn)+ return rows++ def discard_turns(self, reason: str, turns: int, fallback_route: dict[str, str]) -> list[tuple[str, dict[str, str]]]:+ """An /undo or /retry threw away the newest ``turns`` turns: one row per turn not already+ counted (an interrupted turn the user then undoes was wasted once, at the interrupt)."""+ rows = []+ for _ in range(max(1, min(int(turns), _SPENT_TURNS_KEPT))):+ turn = self.spent.pop() if self.spent else _SpentTurn(_route(fallback_route), "unknown")+ if not turn.wasted:+ rows.append(_wasted_row(reason, turn))+ return rows++ def observe_cache(+ self, route: dict[str, str], usage: Any, started_ns: int, ended_ns: int, *, expected: bool,+ ) -> str | None:+ """A cold primary read after a warm one on the same route is a break Hermes did not announce+ (``expected``: Hermes already counted the cause); a gap past the cache TTL is plain expiry."""+ read = _int(usage.get("cache_read_tokens")) if isinstance(usage, dict) else None+ if read is None:+ return None+ prev_read, prev_route, prev_ended = self.cache_read, self.cache_route, self.cache_ended_ns+ self.cache_read, self.cache_route, self.cache_ended_ns = read, route, ended_ns+ if expected or read or not prev_read or prev_route != route:+ return None+ idle_s = (started_ns - prev_ended) / 1e9+ return "cache_expired" if idle_s >= CACHE_TTL_S else "provider_reported_miss"+++def cache_break_row(cause: str, route: dict[str, str] | None) -> tuple[str, dict[str, str]]:+ return contract.CACHE_BREAK_MARK, {**_route(route), "cause": cause}+++# ---- agent-side entry points (agent thread; never raise) ---------------------------------------++def _internal_agent(agent: Any) -> bool:+ """Hermes-owned forks (background review, curator) share the user's session id."""+ return getattr(agent, "_memory_write_origin", None) == "background_review"+++def _agent_route(agent: Any) -> dict[str, str]:+ from .shared_metrics_model import model_route++ return model_route(getattr(agent, "provider", None), getattr(agent, "model", None))+++def _enabled() -> bool:+ from .relay_shared_metrics import enabled++ return enabled()+++def note_tool_result(agent: Any, tool_name: Any, tool_call_id: Any, raw: Any, persisted: Any) -> None:+ """Remember one committed tool result until its batch's turn budget has run."""+ try:+ if _internal_agent(agent) or not _enabled():+ return+ pending = agent.__dict__.setdefault(_PENDING_OUTPUTS_ATTR, {})+ if len(pending) >= _PENDING_OUTPUTS_MAX:+ return+ size, cut_in_tool = _result_size(raw)+ pending[str(tool_call_id or id(persisted))] = [+ contract.tool_metric_name({"tool_name": tool_name}), size, cut_in_tool or persisted is not raw,+ ]+ except Exception:+ logger.debug("Shared-metrics tool output not noted", exc_info=True)+++def _result_size(result: Any) -> tuple[int | None, bool]:+ """(characters the tool produced, whether the tool itself already truncated them)."""+ if isinstance(result, dict): # multimodal envelope: its text parts are what can spill+ parts = result.get("content") or []+ return sum(len(p.get("text") or "") for p in parts if isinstance(p, dict) and p.get("type") == "text"), False+ if not isinstance(result, str):+ return None, False+ notice = _TOOL_TRUNCATION_NOTICE.search(result) if len(result) >= _NOTICE_MIN_CHARS else None+ if notice is None:+ return len(result), False+ return max(len(result), int(notice.group(1).replace(",", ""))), True+++def record_tool_batch(agent: Any, batch: list[dict], contents_before: list[Any]) -> None:+ """One row per tool result of the batch: truncated when the per-result cap or the per-turn+ budget replaced it (the budget runs after the cap, so a result is judged once, here)."""+ try:+ pending = agent.__dict__.pop(_PENDING_OUTPUTS_ATTR, None)+ if not pending or not _enabled():+ return+ for message, before in zip(batch, contents_before):+ entry = pending.get(str(message.get("tool_call_id") or ""))+ if entry is not None and message.get("content") is not before:+ entry[2] = True+ from .relay_shared_metrics import record_process_mark++ for tool, size, truncated in pending.values():+ record_process_mark(contract.TOOL_OUTPUT_TRUNCATION_MARK, {+ "original_size_bucket": output_size_bucket(size), "tool": tool, "truncated": "yes" if truncated else "no",+ })+ except Exception:+ logger.debug("Shared-metrics tool output truncation not recorded", exc_info=True)+++def observe_request_tools(agent: Any, tools_for_api: Any) -> None:+ """The tool definitions one primary request carries (evidence for trimming default toolsets)."""+ try:+ if getattr(agent, "_persist_disabled", False) or _internal_agent(agent) or not _enabled():+ return+ from .relay_shared_metrics import record_session_tools++ record_session_tools(str(getattr(agent, "session_id", "") or ""), agent, tools_for_api or [])+ except Exception:+ logger.debug("Shared-metrics tool overhead not observed", exc_info=True)+++def tool_snapshot(agent: Any, tools_for_api: list) -> tuple[tuple[str, ...], frozenset[str], int, int]:+ """(sent tool names, enabled shipped toolsets, enabled tool count, estimated schema tokens)."""+ from agent.model_metadata import _estimate_tools_tokens_rough+ from model_tools import get_toolset_for_tool++ names = tuple(_tool_names(tools_for_api))+ enabled = list(_tool_names(getattr(agent, "tools", None) or tools_for_api))+ extra = getattr(agent, "valid_tool_names", None) or ()+ enabled_names = set(enabled) | {n for n in extra if isinstance(n, str)}+ toolsets = frozenset(toolset_metric_name(get_toolset_for_tool(n)) for n in enabled_names)+ return names, toolsets, len(enabled_names), _estimate_tools_tokens_rough(tools_for_api) if tools_for_api else 0+++def _tool_names(tools: Iterable[Any]) -> Iterable[str]:+ for tool in tools or ():+ fn = tool.get("function") if isinstance(tool, dict) else None+ name = fn.get("name") if isinstance(fn, dict) else (tool.get("name") if isinstance(tool, dict) else None)+ if isinstance(name, str):+ yield name+++def record_cache_break(agent: Any, cause: str) -> None:+ """Hermes itself invalidated the conversation's cached prefix (compression, a rebuilt prompt)."""+ try:+ if cause not in contract.CACHE_BREAK_CAUSES or getattr(agent, "_persist_disabled", False):+ return+ if _internal_agent(agent) or not _enabled():+ return+ from .relay_shared_metrics import record_known_cache_break++ record_known_cache_break(cause, _agent_route(agent), str(getattr(agent, "session_id", "") or ""))+ except Exception:+ logger.debug("Shared-metrics cache break not recorded", exc_info=True)+++def record_prompt_rebuild(agent: Any, stored_prompt: Any, stored_state: str, rebuilt: Any) -> None:+ """A continuing conversation rebuilt its system prompt instead of replaying the stored bytes."""+ if stored_state in ("null", "empty"):+ record_cache_break(agent, "system_prompt_rebuild")+ return+ if stored_state != "stale_runtime" or not stored_prompt or rebuilt == stored_prompt:+ return+ try:+ from agent.surface_switch import identity_line_value++ switched = any(+ (stored := identity_line_value(stored_prompt, label)) and stored != str(getattr(agent, attr, "") or "").strip()+ for label, attr in (("Model", "model"), ("Provider", "provider"))+ )+ except Exception:+ switched = False+ record_cache_break(agent, "model_switch" if switched else "system_prompt_rebuild")diff --git a/hermes_cli/observability/shared_metrics_events.py b/hermes_cli/observability/shared_metrics_events.pyindex 672eed613cc..0fceee2b772 100644--- a/hermes_cli/observability/shared_metrics_events.py+++ b/hermes_cli/observability/shared_metrics_events.py@@ -70,13 +70,19 @@ def begin_compression_attempt(trigger: str, tokens_before: Any) -> None:_compression_attempt.pending = (trigger, tokens_before)-def finish_compression_attempt(commit_status: str, failure_class: str | None, context_length: Any) -> None:- """Count this thread's pending compression attempt once."""+def finish_compression_attempt(+ commit_status: str, failure_class: str | None, context_length: Any, agent: Any = None,+) -> None:+ """Count this thread's pending compression attempt once; a committed one broke the prompt cache."""pending, _compression_attempt.pending = getattr(_compression_attempt, "pending", None), Noneif not pending:returnoutcome = "success" if commit_status == "committed" else "skipped" if failure_class == "lock_contended" else "failed"record_compression(trigger=pending[0], outcome=outcome, tokens_before=pending[1], context_length=context_length)+ if outcome == "success" and agent is not None:+ from .shared_metrics_efficiency import record_cache_break++ record_cache_break(agent, "compression")def record_gateway_slash_command(event: Any) -> None:diff --git a/hermes_cli/observability/shared_metrics_model.py b/hermes_cli/observability/shared_metrics_model.pyindex bba5569f906..62061ef9ad2 100644--- a/hermes_cli/observability/shared_metrics_model.py+++ b/hermes_cli/observability/shared_metrics_model.py@@ -183,9 +183,10 @@ def record_tool_call_quality(agent: Any, tool_calls: Iterable[Any], repaired_idsdef record_model_friction(signal: str, *, session_id: Any = None, agent: Any = None, provider: Any = None, model: Any = None,- hermes_home: Any = None,+ hermes_home: Any = None, turns: int = 1,) -> None:"""Count one user friction action against the model that produced the session's last turn.+ ``turns``: how many turns an /undo removed (their tokens count as wasted).Falls back to ``agent`` (or ``provider``/``model``) when this process never saw the session'sturns (restart, remote compute host). ``hermes_home`` binds the owning profile for callers that@@ -204,7 +205,7 @@ def record_model_friction(if agent is not None:provider, model = getattr(agent, "provider", provider), getattr(agent, "model", model)session_id = getattr(agent, "session_id", None) or session_id- record_session_friction(signal, str(session_id or ""), model_route(provider, model))+ record_session_friction(signal, str(session_id or ""), model_route(provider, model), turns)except Exception:logger.debug("Shared-metrics %s friction not recorded", signal, exc_info=True)finally:diff --git a/tests/hermes_cli/test_relay_shared_metrics_runtime.py b/tests/hermes_cli/test_relay_shared_metrics_runtime.pyindex f2bd7d94597..6e53e8d143d 100644--- a/tests/hermes_cli/test_relay_shared_metrics_runtime.py+++ b/tests/hermes_cli/test_relay_shared_metrics_runtime.py@@ -413,6 +413,7 @@ def test_direct_runtime_records_without_enabling_a_plugin(direct_runtime, tmp_pa"hermes.install.milestone","hermes.install.snapshot","hermes.model_route.count",+ "hermes.task_cost.count","hermes.task_run.finished","hermes.task_run.started","hermes.tool.usage.count",diff --git a/tests/hermes_cli/test_shared_metrics_efficiency.py b/tests/hermes_cli/test_shared_metrics_efficiency.pynew file mode 100644index 00000000000..e4cd5844955--- /dev/null+++ b/tests/hermes_cli/test_shared_metrics_efficiency.py@@ -0,0 +1,237 @@+"""v5 efficiency metrics: per-turn cost, wasted tokens, tool output truncation, tool overhead and+prompt-cache breaks."""++from __future__ import annotations++import json+from pathlib import Path+from types import SimpleNamespace++import pytest++from hermes_cli import lifecycle+from hermes_cli.observability import relay_shared_metrics+from hermes_cli.observability import shared_metrics_contract as contract+from hermes_cli.observability import shared_metrics_efficiency as eff+from hermes_cli.observability.shared_metrics_model import record_model_friction+from tests.hermes_cli.test_relay_shared_metrics_runtime import ( # noqa: F401 - fixture+ _stored_values,+ direct_runtime,+)+++def _flush() -> None:+ relay_shared_metrics._get_runtime(retry_failed=True).relay.subscribers.flush()+++def _rows(tmp_path, metric):+ _flush()+ return sorted((tuple(sorted(d.items())), v) for d, v in _stored_values(tmp_path, metric))+++def _usage(total, cache_read=0):+ return {"input_tokens": total // 2, "output_tokens": total - total // 2, "cache_read_tokens": cache_read,+ "total_tokens": total}+++def _turn(session_id, task_id, result, *, calls=(), tools=(), model="model-a", **start):+ """One user turn: ``calls`` are the usages of its primary calls, ``tools`` the tools it ran."""+ base = {"session_id": session_id, "task_id": task_id, "provider": "openrouter", "model": model}+ lifecycle.invoke_hook("pre_llm_call", **base, platform="cli", **start)+ for i, usage in enumerate(calls or [None]):+ request = {**base, "api_request_id": f"{task_id}-r{i}"}+ lifecycle.invoke_hook("pre_api_request", **request)+ lifecycle.invoke_hook("post_api_request", **request, usage=usage)+ for i, (tool, toolset) in enumerate(tools):+ call = {**base, "tool_call_id": f"{task_id}-c{i}", "tool_name": tool, "toolset": toolset}+ lifecycle.invoke_hook("pre_tool_call", **call, args={})+ lifecycle.invoke_hook("post_tool_call", **call, args={}, result="ok", status="ok")+ if result is not None:+ relay_shared_metrics.finish_task_run(session_id=session_id, task_id=task_id, platform="cli", result=result)+++def _agent(session_id="s1", model="model-a", tools=None):+ tools = tools if tools is not None else [+ {"type": "function", "function": {"name": name, "description": "d" * 400, "parameters": {"type": "object"}}}+ for name in ("read_file", "terminal", "acme_private_tool")+ ]+ return SimpleNamespace(provider="openrouter", model=model, session_id=session_id, tools=tools,+ valid_tool_names={t["function"]["name"] for t in tools})+++def _dims(**kw):+ return tuple(sorted(kw.items()))+++ROUTE = {"model": "model-a", "provider": "openrouter"}+++def test_task_cost_is_one_row_per_user_turn_with_its_tokens_and_work(direct_runtime, tmp_path):+ """Tokens sum over the turn's primary calls; a session-close abort, a delegated child and an+ internal fork sharing the session id are not user turns."""+ _turn("s1", "t1", {"completed": True}, calls=[_usage(1500), _usage(900)],+ tools=[("terminal", "terminal")] * 3)+ _turn("s1", "t2", {"interrupted": True, "turn_exit_reason": "interrupted_by_user"}, calls=[_usage(60_000)])+ _turn("s1", "t3", {"failed": True, "turn_exit_reason": "failed"}, calls=[None])+ _turn("s1", "t4", None, calls=[_usage(10)]) # still running at close+ lifecycle.finalize_session(session_id="s1")+ _turn("child", "t1", {"completed": True}, calls=[_usage(10)], parent_session_id="s1")+ lifecycle.finalize_session(session_id="child")++ common = dict(ROUTE)+ assert _rows(tmp_path, "hermes.task_cost.count") == sorted([+ (_dims(**common, api_calls_bucket="2", outcome="completed", tokens_bucket="2k_to_10k",+ tool_calls_bucket="3_to_5"), 1),+ (_dims(**common, api_calls_bucket="1", outcome="interrupted", tokens_bucket="50k_to_200k",+ tool_calls_bucket="0"), 1),+ (_dims(**common, api_calls_bucket="1", outcome="failed", tokens_bucket="unknown",+ tool_calls_bucket="0"), 1),+ ])+ # The interrupt threw its tokens away.+ assert _rows(tmp_path, "hermes.wasted_tokens.count") == [+ (_dims(**common, reason="interrupt", tokens_bucket="50k_to_200k"), 1)]+++def test_undo_and_retry_count_the_tokens_of_the_turns_they_discard(direct_runtime, tmp_path):+ """/undo 2 discards two turns; an interrupted turn then undone was wasted once; a session this+ process never saw still counts, tokens unknown."""+ _turn("s1", "t1", {"completed": True}, calls=[_usage(1_000)])+ _turn("s1", "t2", {"completed": True}, calls=[_usage(20_000)])+ _turn("s1", "t3", {"completed": True}, calls=[_usage(300_000)])+ record_model_friction("undo", session_id="s1", provider="openrouter", model="model-a", turns=2)+ _turn("s1", "t4", {"interrupted": True, "turn_exit_reason": "interrupted_by_user"}, calls=[_usage(5_000)])+ record_model_friction("undo", session_id="s1", provider="openrouter", model="model-a")+ record_model_friction("retry", session_id="s1", provider="openrouter", model="model-a")+ record_model_friction("retry", session_id="gone", provider="openrouter", model="model-a")++ assert _rows(tmp_path, "hermes.wasted_tokens.count") == sorted([+ (_dims(**ROUTE, reason="undo", tokens_bucket="200k_to_1m"), 1),+ (_dims(**ROUTE, reason="undo", tokens_bucket="10k_to_50k"), 1),+ (_dims(**ROUTE, reason="interrupt", tokens_bucket="2k_to_10k"), 1),+ (_dims(**ROUTE, reason="retry", tokens_bucket="lt_2k"), 1),+ (_dims(**ROUTE, reason="retry", tokens_bucket="unknown"), 1),+ ])+++def test_tool_output_truncation_is_judged_after_the_turn_budget(direct_runtime, tmp_path):+ from tools.tool_result_storage import enforce_turn_budget, maybe_persist_tool_result+ from tools.budget_config import BudgetConfig++ agent = _agent()+ budget = BudgetConfig(default_result_size=5_000, turn_budget=12_000, preview_size=100)+ from tools.tool_output_truncate import truncate_head_tail++ cut = json.dumps({"output": truncate_head_tail("e" * 300_000, 3_000), "exit_code": 0})+ results = [("read_file", "a" * 200), ("terminal", "b" * 80_000), ("mcp_acme_query", "c" * 9_000),+ ("read_file", "d" * 4_900), ("execute_code", cut)]+ batch = []+ for i, (name, raw) in enumerate(results):+ kept = maybe_persist_tool_result(raw, name, f"c{i}", env=None, config=budget)+ eff.note_tool_result(agent, name, f"c{i}", raw, kept)+ batch.append({"role": "tool", "tool_call_id": f"c{i}", "content": kept})+ before = [m["content"] for m in batch]+ enforce_turn_budget(batch, env=None, config=budget)+ eff.record_tool_batch(agent, batch, before)+ assert not getattr(agent, "_shared_metrics_tool_outputs", None)++ rows = _rows(tmp_path, "hermes.tool_output_truncation.count")+ assert "acme" not in json.dumps(rows)+ got = {(dict(d)["tool"], dict(d)["original_size_bucket"], dict(d)["truncated"]) for d, _ in rows}+ assert ("read_file", "lt_1k", "no") in got+ assert ("terminal", "50k_to_100k", "yes") in got+ assert ("mcp", "1k_to_10k", "yes") in got+ assert ("execute_code", "100k_to_500k", "yes") in got # cut inside the tool: its original size+ assert sum(v for _, v in rows) == 5+++def test_tool_overhead_and_unused_toolsets_report_once_per_conversation(direct_runtime, tmp_path, monkeypatch):+ toolsets = {"read_file": "file", "terminal": "terminal", "acme_private_tool": "acme-private"}+ monkeypatch.setattr("model_tools.get_toolset_for_tool", toolsets.get)+ agent = _agent()+ _turn("s1", "t1", None, calls=[_usage(100)])+ eff.observe_request_tools(agent, agent.tools)+ eff.observe_request_tools(agent, agent.tools) # same array: latched, no recount+ _turn("s1", "t1", {"completed": True}, tools=[("terminal", "terminal")])+ lifecycle.finalize_session(session_id="s1")++ overhead = _rows(tmp_path, "hermes.tool_overhead.count")+ assert [dict(d) for d, _ in overhead] == [{+ "enabled_tool_count_bucket": "3_to_5", "execution_surface": "cli", "tool_schema_tokens_bucket": "lt_2k"}]+ assert _rows(tmp_path, "hermes.tool_enabled_unused.count") == sorted([+ (_dims(toolset="custom", used="no"), 1), (_dims(toolset="file", used="no"), 1),+ (_dims(toolset="terminal", used="yes"), 1)])+ assert "acme" not in json.dumps(_stored_values(tmp_path, "hermes.tool_enabled_unused.count"))+++def test_cache_breaks_count_known_causes_once_and_unannounced_cold_reads_as_misses(direct_runtime, tmp_path,+ monkeypatch):+ agent = _agent()+ _turn("s1", "t1", {"completed": True}, calls=[_usage(9_000, cache_read=0), _usage(9_000, cache_read=8_000)])+ eff.record_cache_break(agent, "compression")+ _turn("s1", "t2", {"completed": True}, calls=[_usage(9_000, cache_read=0)]) # expected cold read+ _turn("s1", "t3", {"completed": True}, calls=[_usage(9_000, cache_read=8_000), _usage(9_000, cache_read=0)])+ # A different route's first read is cold by nature, not a break.+ _turn("s1", "t4", {"completed": True}, calls=[_usage(9_000, cache_read=0)], model="model-b")+ # Idle past the TTL: expiry.+ _turn("s1", "t5", {"completed": True}, calls=[_usage(9_000, cache_read=8_000)])+ rt = relay_shared_metrics._get_runtime(retry_failed=True)+ rt._sessions["s1"].efficiency.cache_ended_ns -= int(eff.CACHE_TTL_S * 1e9) + 1+ _turn("s1", "t6", {"completed": True}, calls=[_usage(9_000, cache_read=0)])+ # The tool array changing mid-conversation.+ monkeypatch.setattr("model_tools.get_toolset_for_tool", lambda name: None)+ eff.observe_request_tools(agent, agent.tools)+ eff.observe_request_tools(agent, agent.tools[:1])+ # Internal forks and persistence-disabled side agents never count.+ eff.record_cache_break(SimpleNamespace(**vars(_agent()), _memory_write_origin="background_review"), "compression")+ eff.record_cache_break(SimpleNamespace(**vars(_agent()), _persist_disabled=True), "compression")++ assert _rows(tmp_path, "hermes.cache_break.count") == sorted([+ (_dims(**ROUTE, cause="compression"), 1), (_dims(**ROUTE, cause="provider_reported_miss"), 1),+ (_dims(**ROUTE, cause="cache_expired"), 1), (_dims(**ROUTE, cause="toolset_change"), 1)])+++def test_prompt_rebuild_names_a_model_switch_apart_from_other_rebuilds(monkeypatch):+ causes = []+ monkeypatch.setattr(eff, "record_cache_break", lambda agent, cause: causes.append(cause))+ agent = _agent(model="model-b")+ stored = "You are Hermes.\nModel: model-a\nProvider: openrouter\n"+ eff.record_prompt_rebuild(agent, stored, "stale_runtime", stored.replace("model-a", "model-b"))+ eff.record_prompt_rebuild(_agent(model="model-a"), stored, "stale_runtime", stored + "Host: x\n")+ eff.record_prompt_rebuild(agent, None, "null", "rebuilt")+ eff.record_prompt_rebuild(agent, stored, "stale_runtime", stored) # replayed bytes: no break+ eff.record_prompt_rebuild(agent, None, "missing", "fresh") # a brand-new conversation+ assert causes == ["model_switch", "system_prompt_rebuild", "system_prompt_rebuild"]+++def test_nothing_is_recorded_while_disabled(direct_runtime, tmp_path, monkeypatch):+ monkeypatch.setattr("hermes_cli.config.read_raw_config_readonly", lambda: {})+ agent = _agent()+ eff.note_tool_result(agent, "terminal", "c1", "x" * 10, "x" * 10)+ assert not getattr(agent, "_shared_metrics_tool_outputs", None)+ eff.record_cache_break(agent, "compression")+ eff.observe_request_tools(agent, agent.tools)+ assert not (tmp_path / "hermes-home" / "telemetry").exists()++[email protected]("count,bucket", [(0, "0"), (2, "2"), (5, "3_to_5"), (25, "11_to_25"), (50, "26_to_50"),+ (100, "51_to_100"), (101, "gte_101")])+def test_turn_activity_buckets_reach_long_agentic_loops(count, bucket):+ assert eff.activity_bucket(count) == bucket+ assert bucket in contract.TURN_ACTIVITY_BUCKETS+++def test_v3_schema_accepts_exactly_the_contract_values():+ import hermes_cli.observability as observability++ schema = json.loads((Path(observability.__file__).parent / "schemas/hermes.shared_metrics.v3.schema.json").read_text())+ by_name = {d["properties"]["name"]["const"]: d for d in schema["$defs"].values() if "properties" in d}+ refs = {item["$ref"].rsplit("/", 1)[1] for item in schema["properties"]["metrics"]["items"]["oneOf"]}+ for metric in (contract.TASK_COST_METRIC, contract.WASTED_TOKENS_METRIC, contract.TOOL_OUTPUT_TRUNCATION_METRIC,+ contract.TOOL_OVERHEAD_METRIC, contract.TOOL_ENABLED_UNUSED_METRIC, contract.CACHE_BREAK_METRIC):+ assert any(schema["$defs"][r]["properties"]["name"]["const"] == metric for r in refs if r.endswith("_counter"))+ dims = by_name[metric]["properties"]["dimensions"]["properties"]+ expected = contract._COUNTER_DIMENSION_VALUES[metric]+ for field_name, spec in dims.items():+ if "enum" in spec:+ assert set(spec["enum"]) == set(expected[field_name]), (metric, field_name)+ assert set(dims) == set(expected) | ({"model", "provider"} & set(dims)), metricdiff --git a/toolsets.py b/toolsets.pyindex a1cf5d52a37..0918c4696b1 100644--- a/toolsets.py+++ b/toolsets.py@@ -258,6 +258,7 @@ TOOLSETS = {# Captured before create_custom_toolset() can add user-named tools: shared metrics may export only# these names, so a plugin, MCP server or custom toolset name never leaves the machine.BUILTIN_TOOL_NAMES = frozenset(tool for spec in TOOLSETS.values() for tool in spec["tools"])+BUILTIN_TOOLSET_NAMES = frozenset(TOOLSETS)def _registry():diff --git a/tui_gateway/methods_tools.py b/tui_gateway/methods_tools.pyindex ce9c379db28..6c72e02547f 100644--- a/tui_gateway/methods_tools.py+++ b/tui_gateway/methods_tools.py@@ -833,11 +833,11 @@ def _cmd_retry(rid, params, session, name, arg):return _ok(rid, {"type": "send", "message": content})-def _tui_model_friction(signal, session):+def _tui_model_friction(signal, session, turns=1):from hermes_cli.observability.shared_metrics_model import record_model_frictionrecord_model_friction(signal, session_id=session.get("session_key"), agent=session.get("agent"),- hermes_home=session.get("profile_home"))+ hermes_home=session.get("profile_home"), turns=turns)def _cmd_steer(rid, params, session, name, arg):@@ -935,7 +935,7 @@ def _cmd_undo(rid, params, session, name, arg):):with contextlib.suppress(Exception):step()- _tui_model_friction("undo", session)+ _tui_model_friction("undo", session, turns_undone)turn_word = "turn" if turns_undone == 1 else "turns"notice = f"↶ Undid {turns_undone} {turn_word} ({rewound_count} message(s)). Edit and resubmit, or send a new message."return _ok(rid, {"type": "prefill", "message": target_text, "notice": notice})diff --git a/website/docs/developer-guide/relay-shared-metrics.md b/website/docs/developer-guide/relay-shared-metrics.mdindex de11386d02c..6229188ccab 100644--- a/website/docs/developer-guide/relay-shared-metrics.md+++ b/website/docs/developer-guide/relay-shared-metrics.md@@ -350,6 +350,23 @@ leave — only the closed values below.| `hermes.model_reply_issue.count` | provider, model, issue (`none`, `empty`, `reasoning_only`, `refusal`, `truncated_length`) | Which models return unusable replies. One row per primary model response (usable ones as `none`, the rate denominator). `refusal` and `truncated_length` come only from the structured finish reason (`content_filter`, `length`); `empty` is a valid response with no visible text, tool call or reasoning. |<!-- ---- end v5 harness ---- -->+<!-- ---- v5 efficiency ---- -->+#### Efficiency: turn cost, waste, tool overhead and prompt-cache breaks++Provider and model follow the model-route rules above. A "user turn" is one user+message through its final reply; Hermes-owned work (background memory/skill review,+the curator, delegated subagents' own turns) is not a user turn.++| Metric | Dimensions | Question it answers |+|---|---|---|+| `hermes.task_cost.count` | provider, model, tokens bucket (`lt_2k` … `gte_1m`, `unknown`), tool calls bucket, API calls bucket (`0` … `51_to_100`, `gte_101`), outcome (`completed`, `interrupted`, `failed`) | What a user turn costs per model. Tokens are prompt (cache reads/writes included) plus completion over the turn's primary calls; `unknown` when the provider reported no usage. One row per interactive turn the user saw end (a session-close abort is not a turn). |+| `hermes.wasted_tokens.count` | provider, model, reason (`interrupt`, `retry`, `undo`), tokens bucket | How many tokens users throw away. One row per turn an interrupt, `/retry` or `/undo` discarded (`/undo N` counts N turns), attributed to the model that produced that turn; a turn interrupted and then undone counts once. `unknown` when this process never saw the turn (restart, remote host). |+| `hermes.tool_output_truncation.count` | tool (shipped tool name, else `mcp` / `plugin`), truncated (`yes`/`no`), original size bucket (characters: `lt_1k` … `gte_500k`) | Which tools produce output too large to keep inline. One row per tool result; `yes` when the tool cut its own output (terminal, `execute_code` and MCP head/tail truncation; the size is then the original) or the per-result cap or per-turn budget spilled it to disk. |+| `hermes.tool_overhead.count` | enabled tool count bucket, tool schema tokens bucket (`0`, `lt_2k` … `gte_40k`), execution surface | What carrying tool definitions costs. One row per closed interactive conversation: the tools it had enabled and Hermes's own estimate of the tokens their definitions add to each request. |+| `hermes.tool_enabled_unused.count` | toolset (a toolset Hermes ships; MCP servers, plugins and user toolsets read `custom`), used (`yes`/`no`) | Which default toolsets are paid for but never used. One row per enabled toolset per closed interactive conversation (bounded by the shipped toolsets). |+| `hermes.cache_break.count` | provider, model, cause (`compression`, `model_switch`, `toolset_change`, `system_prompt_rebuild`, `provider_reported_miss`, `cache_expired`) | How often Hermes throws away a warm prompt cache, and why. `compression` is expected; `model_switch`, `toolset_change` (the tool array changed mid-conversation) and `system_prompt_rebuild` (a continuing conversation rebuilt its system prompt instead of replaying the stored bytes) are Hermes-known causes; `provider_reported_miss` is a primary call reading zero cached tokens right after a warm read on the same model with no Hermes-known cause, `cache_expired` the same after at least five idle minutes. A known cause is not counted again as a miss. |+<!-- ---- end v5 efficiency ---- -->+Local state is written under:```text