Skip to content

The agent that grows with you

feat(telemetry): per-model tool-call quality, friction and context-peak counters

teknium12efa4f3caa1f
diff --git a/acp_adapter/server.py b/acp_adapter/server.py
index f66a0865c47..e9d1d902dc0 100644
--- a/acp_adapter/server.py
+++ b/acp_adapter/server.py
@@ -326,12 +326,12 @@ class HermesACPAgent(SlashCommandsMixin, acp.Agent):
from hermes_cli.model_switch import switch_model
from hermes_cli.models import parse_model_input
- current_provider = getattr(state.agent, "provider", None)
+ current_provider, current_model = getattr(state.agent, "provider", None), str(state.model or "")
explicit_provider, model_input = parse_model_input(raw_model, "")
cfg = load_config()
result = switch_model(
raw_input=model_input, explicit_provider=explicit_provider,
- current_provider=current_provider or "openrouter", current_model=str(state.model or ""),
+ current_provider=current_provider or "openrouter", current_model=current_model,
current_base_url=str(getattr(state.agent, "base_url", "") or ""),
current_api_key=str(getattr(state.agent, "api_key", "") or ""),
user_providers=cfg.get("providers") if isinstance(cfg.get("providers"), dict) else {},
@@ -358,7 +358,8 @@ class HermesACPAgent(SlashCommandsMixin, acp.Agent):
self.session_manager.save_session(state.session_id)
from hermes_cli.observability.shared_metrics_events import record_model_switch
- record_model_switch(from_provider=current_provider, to_provider=target_provider, surface="acp")
+ record_model_switch(
+ from_provider=current_provider, to_provider=target_provider, surface="acp", from_model=current_model)
return current_provider, target_provider, new_model
@staticmethod
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.py
index e30572fec47..5c114ec4be8 100644
--- a/agent/chat_completion_helpers.py
+++ b/agent/chat_completion_helpers.py
@@ -3378,7 +3378,8 @@ class _StreamingCall(StreamingWaitMonitor):
has_truncated_tool_args = True
mock_tool_calls.append(SimpleNamespace(
id=tc["id"], type=tc["type"], extra_content=tc.get("extra_content"),
- function=SimpleNamespace(name=tc["function"]["name"], arguments=arguments)))
+ function=SimpleNamespace(name=tc["function"]["name"], arguments=arguments,
+ args_repaired=arguments != tc["function"]["arguments"])))
return mock_tool_calls or None, has_truncated_tool_args
def _finish_chat_stream(self, stream, role, content_parts, reasoning_parts, tool_calls_acc, finish_reason,
diff --git a/agent/transports/chat_completions.py b/agent/transports/chat_completions.py
index 1122ba999b6..d2cab147770 100644
--- a/agent/transports/chat_completions.py
+++ b/agent/transports/chat_completions.py
@@ -656,10 +656,13 @@ class ChatCompletionsTransport(ProviderTransport):
name = alias_map.get(name, name)
arguments = getattr(tc_function, "arguments", None)
extra = _attr_or_model_extra(tc, "extra_content")
- return ToolCall(
+ call = ToolCall(
id=getattr(tc, "id", None), name=name, arguments="{}" if arguments is None else arguments,
provider_data=None if extra is None else {"extra_content": _dump_extra_content(extra)},
)
+ if getattr(tc_function, "args_repaired", False) is True:
+ call.args_repaired = True # stream assembly fixed the JSON; read by tool-call quality metrics
+ return call
def validate_response(self, response: Any) -> bool:
"""Check that response has valid choices and is not a router failure shim."""
diff --git a/agent/turn_response_intake.py b/agent/turn_response_intake.py
index 67374daa781..35f63802333 100644
--- a/agent/turn_response_intake.py
+++ b/agent/turn_response_intake.py
@@ -90,6 +90,7 @@ def _fire_post_api_request_hook(
response, assistant_message, finish_reason=finish_reason
),
usage=agent._usage_summary_for_api_request_hook(response),
+ context_length=getattr(getattr(agent, "context_compressor", None), "context_length", None),
assistant_message=assistant_message,
assistant_content_chars=len(assistant_message.content or ""),
assistant_tool_call_count=len(getattr(assistant_message, "tool_calls", None) or []),
diff --git a/agent/turn_tool_validation.py b/agent/turn_tool_validation.py
index 85caf66d643..27d10e5e52c 100644
--- a/agent/turn_tool_validation.py
+++ b/agent/turn_tool_validation.py
@@ -90,6 +90,7 @@ def validate_tool_calls(
agent._uniquify_tool_call_ids(tool_calls)
# Repair mismatched tool names before validating (model hallucinations).
+ repaired_ids = set()
for tc in tool_calls:
if tc.function.name not in valid_names:
repaired = agent._repair_tool_call(tc.function.name)
@@ -97,6 +98,10 @@ def validate_tool_calls(
agent._vprint(f"{agent.log_prefix}πŸ”§ Auto-repaired tool name: '{tc.function.name}' -> '{repaired}'",
force=True, diagnostic=True)
tc.function.name = repaired
+ repaired_ids.add(id(tc))
+ # Counted here, before any exit or normalization, so every emitted call is seen once as the model sent it.
+ from hermes_cli.observability.shared_metrics_model import record_tool_call_quality
+ record_tool_call_quality(agent, tool_calls, repaired_ids)
invalid_tool_calls = [tc.function.name for tc in tool_calls if tc.function.name not in valid_names]
# Mixed batch: error-result ONLY the invalid calls and run the valid
# ones; voiding the turn discards real work. Strikes advance only when a
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.ts
index 04c7bdec145..47d87b82b51 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -3185,7 +3185,9 @@ export interface SessionBranchWholeResult {
export interface SessionUndoParams {
session_id: string
profile?: string | null
+ intent?: UndoIntent | null
}
+export type UndoIntent = 'retry' | 'undo'
export interface SessionUndoResult {
removed: number
}
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index 716dacae7e8..cfc5d4c19c9 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -31232,6 +31232,17 @@
],
"default": null,
"title": "Profile"
+ },
+ "intent": {
+ "anyOf": [
+ {
+ "$ref": "#/components/schemas/UndoIntent"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null
}
},
"required": [
@@ -35785,6 +35796,14 @@
"title": "UiMetaConflict",
"type": "object"
},
+ "UndoIntent": {
+ "enum": [
+ "retry",
+ "undo"
+ ],
+ "title": "UndoIntent",
+ "type": "string"
+ },
"Usage": {
"additionalProperties": true,
"description": "``tui_gateway/server.py::_get_usage`` + ``agent/context_breakdown.py::context_usage_fields``.",
diff --git a/gateway/slash_commands_model.py b/gateway/slash_commands_model.py
index 10a7cbe8968..182ceb00beb 100644
--- a/gateway/slash_commands_model.py
+++ b/gateway/slash_commands_model.py
@@ -380,7 +380,9 @@ class GatewayModelCommandsMixin:
return error
from hermes_cli.observability.shared_metrics_events import record_model_switch
- record_model_switch(from_provider=ctx.current_provider, to_provider=result.target_provider, surface="gateway")
+ record_model_switch(
+ from_provider=ctx.current_provider, to_provider=result.target_provider, surface="gateway",
+ from_model=ctx.current_model)
global_error = await self._record_model_switch(result, ctx, source=source, one_turn=one_turn, picker=picker)
reply = await self._model_switch_confirmation(
result, ctx, one_turn=one_turn, picker=picker, global_error=global_error,
diff --git a/gateway/slash_commands_session.py b/gateway/slash_commands_session.py
index efa2d42f1f7..3e6bab37b60 100644
--- a/gateway/slash_commands_session.py
+++ b/gateway/slash_commands_session.py
@@ -424,10 +424,21 @@ class GatewaySessionCommandsMixin:
session_entry.session_id, truncated, active_only=True, reject_active_turn_lease=True):
return "Retry failed; transcript was not changed."
session_entry.last_prompt_tokens = 0 # transcript was truncated
+ self._record_model_friction("retry", source, session_entry.session_id)
return await self._handle_message(MessageEvent(
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:
+ """Slash dispatch does not install the routed profile's scope, so a multiplexed runner
+ names the owning home explicitly."""
+ from hermes_cli.observability.shared_metrics_model import record_model_friction
+ home = None
+ 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)
+
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
echoing the backed-up text; evicts the cached agent so the next turn rebuilds from the
@@ -445,6 +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)
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.py
index 9916b124ba9..e598a4cfce0 100644
--- a/hermes_cli/cli_loops_mixin.py
+++ b/hermes_cli/cli_loops_mixin.py
@@ -179,8 +179,18 @@ class CLILoopsMixin:
return True # confirmation cancelled β€” command handled, keep REPL alive
self.new_session(title=title)
+ def _record_model_friction(self, signal: str) -> 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_friction
+ record_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))
+
def _cmd_retry(self, cmd_original: str):
retry_msg = self.retry_last()
+ if retry_msg:
+ self._record_model_friction("retry")
if retry_msg and hasattr(self, '_pending_input'):
self._pending_input.put(retry_msg) # process_loop sends it to the agent
@@ -204,6 +214,7 @@ class CLILoopsMixin:
else f"This removes the last {_undo_n} user turns from history.")
if self._confirm_destructive_slash("undo", _undo_desc, cmd_original=cmd_original) is None:
return True # confirmation cancelled β€” command handled, keep REPL alive
+ self._record_model_friction("undo")
self.undo_last(_undo_n)
def _cmd_skills(self, cmd_original: str):
diff --git a/hermes_cli/cli_model_switch_mixin.py b/hermes_cli/cli_model_switch_mixin.py
index 4c7350b7e54..fdf370d1efe 100644
--- a/hermes_cli/cli_model_switch_mixin.py
+++ b/hermes_cli/cli_model_switch_mixin.py
@@ -246,7 +246,8 @@ def _commit_model_switch(
# A TUI slash worker replays /model on its shadow CLI; the tui_gateway mirror counts the real switch.
if not getattr(cli, "is_slash_worker", False):
from hermes_cli.observability.shared_metrics_events import record_model_switch
- record_model_switch(from_provider=old_provider, to_provider=result.target_provider, surface="cli")
+ record_model_switch(
+ from_provider=old_provider, to_provider=result.target_provider, surface="cli", from_model=old_model)
if not picker:
cli._pending_one_turn_model_restore = snapshot
_print_switch_summary(cli, result, old_model, one_turn=one_turn, strict_context=not picker)
diff --git a/hermes_cli/hooks.py b/hermes_cli/hooks.py
index baa5feea4da..0586aec24e2 100644
--- a/hermes_cli/hooks.py
+++ b/hermes_cli/hooks.py
@@ -145,7 +145,7 @@ _DEFAULT_PAYLOADS = {
"api_call_count": 1, "api_duration": 1.234,
"started_at": 1756000000.0, "ended_at": 1756000001.234, "first_chunk_at": 1756000000.512,
"finish_reason": "stop", "message_count": 4, "response_model": "claude-sonnet-4-6",
- "usage": {"input_tokens": 2048, "output_tokens": 512},
+ "usage": {"input_tokens": 2048, "output_tokens": 512}, "context_length": 200000,
"assistant_content_chars": 1200, "assistant_tool_call_count": 0,
# Per-advisor metrics on a MoA turn, None otherwise: MoA returns only the aggregator's
# response, so without this an observer cannot see or price the fan-out.
diff --git a/hermes_cli/observability/relay_shared_metrics.py b/hermes_cli/observability/relay_shared_metrics.py
index 4c31c0edfe5..c71c9f006c9 100644
--- a/hermes_cli/observability/relay_shared_metrics.py
+++ b/hermes_cli/observability/relay_shared_metrics.py
@@ -18,6 +18,7 @@ from hermes_cli.version_info import get_version_info
from .shared_metrics import SharedMetricsStore
from . import shared_metrics_contract as contract
from . 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
from .shared_metrics_subscriber import SharedMetricsSubscriber
@@ -133,6 +134,7 @@ class _TaskRun:
completed_tool_call_ids: set[tuple[str, str, str]] = field(default_factory=set)
unidentified_tool_calls: int = 0
retry_count: int = 0
+ model_route: dict[str, str] | None = None
@dataclass
@@ -152,6 +154,7 @@ class _MetricsSession:
last_outcome: str = "unknown"
first_turn_ns: int = 0
last_turn_ns: int = 0
+ model_state: model_.ModelSessionState = field(default_factory=model_.ModelSessionState)
class _Runtime:
@@ -321,6 +324,7 @@ class _Runtime:
task.retry_count += 1
return
if task is not None:
+ task.model_route = fields
task.model_call_ids.add(request_id)
if _retry_ordinal(event) > 0:
# A real Hermes retry can advance api_request_id while carrying the
@@ -351,6 +355,7 @@ class _Runtime:
return
model_call.fields = contract.model_call_fields(event)
if finish:
+ session.model_state.observe_call(model_call.fields, event.get("usage"), event.get("context_length"))
model_call.ttft_bucket = fields_.ttft_bucket(event)
self._finish_model_call(session, model_call_key, "success")
tokens = fields_.model_token_fields(
@@ -363,6 +368,7 @@ class _Runtime:
)
else:
model_call.error_class = contract.model_error_class(event)
+ session.model_state.observe_error(model_call.fields, model_call.error_class)
def start_tool_call(self, event: dict[str, Any]) -> None:
"""Open one privacy-safe Relay tool lifecycle under its task."""
@@ -790,6 +796,8 @@ class _Runtime:
retry_count=task.retry_count,
)
self._count_session_turn(session, task, fields["outcome"])
+ if not session.closing:
+ self._observe_model_turn(session, task, fields)
try:
popped = self._guarded(
"Hermes shared-metrics task close failed",
@@ -817,11 +825,43 @@ class _Runtime:
session.last_outcome = outcome
session.last_turn_ns = monotonic_ns()
+ def _observe_model_turn(self, session: _MetricsSession, task: _TaskRun, fields: dict[str, str]) -> None:
+ """A turn the user saw end (session-close aborts excluded): trailing-failure state and interrupts."""
+ route = task.model_route or session.model_state.last_route
+ session.model_state.observe_turn(fields["outcome"], route, session.last_turn_ns)
+ if fields["end_reason"] == "user_cancelled" and route is not None and model_.attended(task.start_fields):
+ self._guarded(
+ "Hermes shared-metrics friction mark failed", self._mark,
+ session, None, contract.MODEL_FRICTION_MARK, model_.friction_fields("interrupt", route),
+ )
+
+ def _emit_model_session_marks(self, session: _MetricsSession) -> None:
+ state = session.model_state
+ marks = [(contract.CONTEXT_PEAK_MARK, state.context_peak_fields())]
+ abandoned = state.quick_abandon_route(monotonic_ns())
+ if abandoned is not None and model_.attended(session.start_fields):
+ marks.append((contract.MODEL_FRICTION_MARK, model_.friction_fields("quick_abandon", abandoned)))
+ for mark, data in marks:
+ 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."""
+ session = self._session({"session_id": session_id}) if session_id else None
+ route = None
+ if session is not None:
+ with session.lock:
+ route = session.model_state.last_route
+ data = model_.friction_fields(signal, route or fallback_route)
+ if data is not None:
+ self.record_process_mark(contract.MODEL_FRICTION_MARK, data)
+
def _emit_session_summary(self, session: _MetricsSession) -> None:
"""One hermes.session.count row per closed top-level session (delegated children excluded)."""
start = session.start_fields
if not session.turns or start is None or start.get("entrypoint") == "delegated":
return
+ self._emit_model_session_marks(session)
summary = fields_.session_fields(
start, turns=session.turns, failed_turns=session.failed_turns,
last_outcome=session.last_outcome,
@@ -1094,6 +1134,15 @@ def record_process_mark(mark: str, data: dict[str, Any]) -> None:
runtime._safe(runtime.record_process_mark, mark, data)
+def record_session_friction(signal: str, session_id: str, fallback_route: dict[str, str]) -> None:
+ """Record one friction signal in the active profile's runtime (callers already 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_friction, signal, session_id, fallback_route)
+
+
def _run_task_hook(method: str, *, retry_failed: bool = False, **event: Any) -> None:
if not enabled():
return
diff --git a/hermes_cli/observability/schemas/hermes.shared_metrics.v3.schema.json b/hermes_cli/observability/schemas/hermes.shared_metrics.v3.schema.json
index 3e46c7e5498..05b782862e9 100644
--- a/hermes_cli/observability/schemas/hermes.shared_metrics.v3.schema.json
+++ b/hermes_cli/observability/schemas/hermes.shared_metrics.v3.schema.json
@@ -174,6 +174,15 @@
},
{
"$ref": "#/$defs/cron_run_counter"
+ },
+ {
+ "$ref": "#/$defs/model_tool_quality_counter"
+ },
+ {
+ "$ref": "#/$defs/model_friction_counter"
+ },
+ {
+ "$ref": "#/$defs/context_peak_counter"
}
]
}
@@ -1951,6 +1960,189 @@
"minimum": 1
}
}
+ },
+ "model_tool_quality_counter": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "name",
+ "type",
+ "dimensions",
+ "value"
+ ],
+ "properties": {
+ "name": {
+ "const": "hermes.model_tool_quality.count"
+ },
+ "type": {
+ "const": "counter"
+ },
+ "dimensions": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "call_role",
+ "issue",
+ "model",
+ "provider"
+ ],
+ "properties": {
+ "call_role": {
+ "enum": [
+ "auxiliary",
+ "primary"
+ ]
+ },
+ "issue": {
+ "enum": [
+ "empty_arguments",
+ "invalid_json",
+ "none",
+ "repaired",
+ "schema_mismatch",
+ "unknown_tool"
+ ]
+ },
+ "model": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 256,
+ "pattern": "^[a-z0-9][a-z0-9._:/@+\\-]*$"
+ },
+ "provider": {
+ "$ref": "#/$defs/provider_identifier"
+ }
+ },
+ "description": "One per tool call a model emitted; issue=none when clean, so issue rates have a denominator."
+ },
+ "value": {
+ "type": "integer",
+ "minimum": 1
+ }
+ }
+ },
+ "model_friction_counter": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "name",
+ "type",
+ "dimensions",
+ "value"
+ ],
+ "properties": {
+ "name": {
+ "const": "hermes.model_friction.count"
+ },
+ "type": {
+ "const": "counter"
+ },
+ "dimensions": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "model",
+ "provider",
+ "signal"
+ ],
+ "properties": {
+ "model": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 256,
+ "pattern": "^[a-z0-9][a-z0-9._:/@+\\-]*$"
+ },
+ "provider": {
+ "$ref": "#/$defs/provider_identifier"
+ },
+ "signal": {
+ "enum": [
+ "interrupt",
+ "quick_abandon",
+ "retry",
+ "switch_away",
+ "undo"
+ ]
+ }
+ },
+ "description": "A user friction action attributed to the model that produced the turn."
+ },
+ "value": {
+ "type": "integer",
+ "minimum": 1
+ }
+ }
+ },
+ "context_peak_counter": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "name",
+ "type",
+ "dimensions",
+ "value"
+ ],
+ "properties": {
+ "name": {
+ "const": "hermes.context_peak.count"
+ },
+ "type": {
+ "const": "counter"
+ },
+ "dimensions": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "limit_hit",
+ "model",
+ "peak_fill_bucket",
+ "provider",
+ "window_bucket"
+ ],
+ "properties": {
+ "limit_hit": {
+ "enum": [
+ "no",
+ "yes"
+ ]
+ },
+ "model": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 256,
+ "pattern": "^[a-z0-9][a-z0-9._:/@+\\-]*$"
+ },
+ "peak_fill_bucket": {
+ "enum": [
+ "50_to_75",
+ "75_to_90",
+ "90_to_100",
+ "gte_100",
+ "lt_50",
+ "unknown"
+ ]
+ },
+ "provider": {
+ "$ref": "#/$defs/provider_identifier"
+ },
+ "window_bucket": {
+ "enum": [
+ "lt_32k",
+ "32k_to_128k",
+ "128k_to_256k",
+ "256k_to_1m",
+ "gte_1m",
+ "unknown"
+ ]
+ }
+ },
+ "description": "One per closed session: the fullest primary-model context it reached."
+ },
+ "value": {
+ "type": "integer",
+ "minimum": 1
+ }
+ }
}
}
}
diff --git a/hermes_cli/observability/shared_metrics_contract.py b/hermes_cli/observability/shared_metrics_contract.py
index 9e8ee9cf9ee..67deb4a1936 100644
--- a/hermes_cli/observability/shared_metrics_contract.py
+++ b/hermes_cli/observability/shared_metrics_contract.py
@@ -65,6 +65,14 @@ CURATOR_RUN_METRIC = "hermes.curator.run.count"
DELEGATION_RUN_METRIC = "hermes.delegation.run.count"
EXECUTION_BACKEND_METRIC = "hermes.execution_backend.count"
# ---- end v4 loop ----
+# ---- v4 model ----
+MODEL_TOOL_QUALITY_MARK = "hermes.model_tool_quality"
+MODEL_FRICTION_MARK = "hermes.model_friction"
+CONTEXT_PEAK_MARK = "hermes.context_peak"
+MODEL_TOOL_QUALITY_METRIC = "hermes.model_tool_quality.count"
+MODEL_FRICTION_METRIC = "hermes.model_friction.count"
+CONTEXT_PEAK_METRIC = "hermes.context_peak.count"
+# ---- end v4 model ----
MODEL_IDENTIFIER_MAX_LENGTH = 256
PROVIDER_IDENTIFIER_MAX_LENGTH = 64
_METRIC_IDENTIFIER_CHARACTERS = frozenset("abcdefghijklmnopqrstuvwxyz0123456789._:/@+-")
@@ -192,6 +200,16 @@ EXTENSION_NAMES = _CatalogValues(
"bundled_skill_names", "mcp_catalog_names", "plugin_catalog_names", extra=frozenset({"custom"})
)
DISPLAY_LANGUAGES = _CatalogValues("display_languages", extra=frozenset({"other"}))
+# ---- v4 model ----
+TOOL_CALL_ISSUES = frozenset({
+ "empty_arguments", "invalid_json", "none", "repaired", "schema_mismatch", "unknown_tool",
+})
+FRICTION_SIGNALS = frozenset({"interrupt", "quick_abandon", "retry", "switch_away", "undo"})
+CONTEXT_WINDOW_BUCKETS = frozenset({
+ "lt_32k", "32k_to_128k", "128k_to_256k", "256k_to_1m", "gte_1m", "unknown",
+})
+LIMIT_HIT_VALUES = frozenset({"no", "yes"})
+# ---- end v4 model ----
# ---- v4 loop ----
MEMORY_OPS = frozenset({"add", "other", "read", "remove", "replace", "search"})
@@ -403,6 +421,14 @@ _COUNTER_DIMENSION_VALUES: dict[str, dict[str, frozenset[str]]] = {
CRON_RUN_METRIC: {
"delivery_kind": CRON_DELIVERY_KINDS, "duration_bucket": DURATION_BUCKETS, "outcome": CRON_RUN_OUTCOMES,
},
+ # ---- v4 model ----
+ MODEL_TOOL_QUALITY_METRIC: {"call_role": MODEL_CALL_ROLES, "issue": TOOL_CALL_ISSUES},
+ MODEL_FRICTION_METRIC: {"signal": FRICTION_SIGNALS},
+ CONTEXT_PEAK_METRIC: {
+ "limit_hit": LIMIT_HIT_VALUES, "peak_fill_bucket": CONTEXT_FILL_BUCKETS,
+ "window_bucket": CONTEXT_WINDOW_BUCKETS,
+ },
+ # ---- end v4 model ----
}
_MODEL_ROUTE_MAX_LENGTHS = {
"model": MODEL_IDENTIFIER_MAX_LENGTH, "provider": PROVIDER_IDENTIFIER_MAX_LENGTH,
@@ -415,6 +441,11 @@ _IDENTIFIER_FIELDS: dict[str, dict[str, int]] = {
MODEL_SWITCH_METRIC: dict.fromkeys(("from_provider", "to_provider"), PROVIDER_IDENTIFIER_MAX_LENGTH),
FALLBACK_METRIC: dict.fromkeys(("from_provider", "to_provider"), PROVIDER_IDENTIFIER_MAX_LENGTH),
INSTALL_SNAPSHOT_METRIC: {"main_provider": PROVIDER_IDENTIFIER_MAX_LENGTH},
+ # ---- v4 model ----
+ MODEL_TOOL_QUALITY_METRIC: _MODEL_ROUTE_MAX_LENGTHS,
+ MODEL_FRICTION_METRIC: _MODEL_ROUTE_MAX_LENGTHS,
+ CONTEXT_PEAK_METRIC: _MODEL_ROUTE_MAX_LENGTHS,
+ # ---- end v4 model ----
}
# metric -> closed dimension field set
_METRIC_FIELDS: dict[str, frozenset[str]] = {
@@ -453,6 +484,10 @@ _DECISION_MARK_METRICS = {
# ---- v4 gateway ----
PLATFORM_HEALTH_MARK: PLATFORM_HEALTH_METRIC, PLATFORM_DELIVERY_MARK: PLATFORM_DELIVERY_METRIC,
REPLY_LATENCY_MARK: REPLY_LATENCY_METRIC, CRON_RUN_MARK: CRON_RUN_METRIC,
+ # ---- v4 model ----
+ MODEL_TOOL_QUALITY_MARK: MODEL_TOOL_QUALITY_METRIC, MODEL_FRICTION_MARK: MODEL_FRICTION_METRIC,
+ CONTEXT_PEAK_MARK: CONTEXT_PEAK_METRIC,
+ # ---- end v4 model ----
}
diff --git a/hermes_cli/observability/shared_metrics_events.py b/hermes_cli/observability/shared_metrics_events.py
index 6ebb67acc21..2b1760a1bf7 100644
--- a/hermes_cli/observability/shared_metrics_events.py
+++ b/hermes_cli/observability/shared_metrics_events.py
@@ -77,11 +77,18 @@ def record_gateway_slash_command(event: Any) -> None:
record_slash_command(command=command, surface="gateway")
-def record_model_switch(*, from_provider: str | None, to_provider: str | None, surface: str) -> None:
+def record_model_switch(
+ *, from_provider: str | None, to_provider: str | None, surface: str, from_model: str | None = None,
+) -> None:
+ """``from_model`` also counts the switch as friction against the model the user left."""
_emit(
contract.MODEL_SWITCH_MARK, fields_.model_switch_fields,
from_provider=from_provider, to_provider=to_provider, surface=surface,
)
+ if from_model:
+ from .shared_metrics_model import record_model_friction
+
+ record_model_friction("switch_away", provider=from_provider, model=from_model)
def record_fallback(*, from_provider: str | None, to_provider: str | None, reason: Any) -> None:
diff --git a/hermes_cli/observability/shared_metrics_model.py b/hermes_cli/observability/shared_metrics_model.py
new file mode 100644
index 00000000000..bba5569f906
--- /dev/null
+++ b/hermes_cli/observability/shared_metrics_model.py
@@ -0,0 +1,214 @@
+"""Per-model quality, friction and context-pressure shared metrics.
+
+Tool-call quality is counted where the agent validates the calls a model emitted (every call,
+clean ones as ``issue=none``, so rates have a denominator). Friction and context peaks are
+attributed to the model that produced the turn, which the relay runtime tracks per metrics session
+in :class:`ModelSessionState`. Provider/model always go through ``model_call_fields`` (the catalog
+helpers), so custom endpoints and loopback servers read ``custom``.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+from dataclasses import dataclass
+from typing import Any, Iterable
+
+from . import shared_metrics_contract as contract
+from . import shared_metrics_fields as fields_
+
+logger = logging.getLogger(__name__)
+
+# A session that ends this soon after a failed turn reads as the user giving up on the model.
+QUICK_ABANDON_NS = 60 * 1_000_000_000
+# Lower bound inclusive, so 128k (128_000 and 131_072) and 1M windows land in one bucket each.
+_WINDOW_THRESHOLDS = (
+ (32_000, "lt_32k"), (128_000, "32k_to_128k"), (256_000, "128k_to_256k"), (1_000_000, "256k_to_1m"),
+)
+# The rejections Hermes answers with a forced (overflow-triggered) compression.
+_LIMIT_ERROR_CLASSES = frozenset({"context_overflow", "payload_too_large"})
+# Unattended runs have no user to interrupt or abandon them.
+_UNATTENDED_ENTRYPOINTS = frozenset({"background", "batch", "delegated", "scheduled_task"})
+
+
+def model_route(provider: Any, model: Any) -> dict[str, str]:
+ return contract.model_call_fields({"provider": provider, "model": model})
+
+
+def window_bucket(context_length: Any) -> str:
+ length = contract._non_negative_number(context_length)
+ return contract._bucket(length, _WINDOW_THRESHOLDS, "gte_1m") if length else "unknown"
+
+
+def friction_fields(signal: str, route: dict[str, str] | None) -> dict[str, str] | None:
+ if signal not in contract.FRICTION_SIGNALS:
+ return None
+ return {**(route or model_route(None, None)), "signal": signal}
+
+
+def _prompt_tokens(usage: Any) -> float | None:
+ if not isinstance(usage, dict):
+ return None
+ tokens = contract._non_negative_number(usage.get("prompt_tokens"))
+ return tokens if tokens is not None else contract._non_negative_number(usage.get("input_tokens"))
+
+
+@dataclass
+class ModelSessionState:
+ """Per-session model attribution the runtime keeps between hooks (caller holds session.lock)."""
+
+ last_route: dict[str, str] | None = None
+ peak_route: dict[str, str] | None = None
+ peak_tokens: float = -1.0
+ peak_window: float | None = None
+ limit_hit: bool = False
+ failed_turn_ns: int = 0
+ failed_route: dict[str, str] | None = None
+
+ def observe_call(self, route: dict[str, str], usage: Any, context_length: Any) -> None:
+ """One finished primary call: remember its model and the fullest context seen."""
+ self.last_route = route
+ tokens, window = _prompt_tokens(usage), contract._non_negative_number(context_length)
+ if self.peak_route is None:
+ self.peak_route = route
+ if tokens is None or not window:
+ return
+ if self.peak_window is None or tokens / window > self.peak_tokens / self.peak_window:
+ self.peak_route, self.peak_tokens, self.peak_window = route, tokens, window
+
+ def observe_error(self, route: dict[str, str], error_class: str) -> None:
+ """A failed primary call still names the model: a session whose every call overflowed
+ is exactly the one the context peak row must report."""
+ self.last_route = route
+ if self.peak_route is None:
+ self.peak_route = route
+ if error_class in _LIMIT_ERROR_CLASSES:
+ self.limit_hit = True
+
+ def observe_turn(self, outcome: str, route: dict[str, str] | None, now_ns: int) -> None:
+ """Only the trailing turn matters for abandonment: a later success clears it."""
+ failed = outcome == "failed"
+ self.failed_turn_ns = now_ns if failed else 0
+ self.failed_route = (route or self.last_route) if failed else None
+
+ def quick_abandon_route(self, now_ns: int) -> dict[str, str] | None:
+ if self.failed_turn_ns and now_ns - self.failed_turn_ns <= QUICK_ABANDON_NS:
+ return self.failed_route or self.last_route
+ return None
+
+ def context_peak_fields(self) -> dict[str, str] | None:
+ """One row per session that reached a primary model; None when no call was made."""
+ if self.peak_route is None:
+ return None
+ known = self.peak_window is not None
+ return {
+ **self.peak_route,
+ "limit_hit": "yes" if self.limit_hit else "no",
+ "peak_fill_bucket": (
+ fields_.context_fill_bucket(self.peak_tokens, self.peak_window) if known else "unknown"
+ ),
+ "window_bucket": window_bucket(self.peak_window) if known else "unknown",
+ }
+
+
+def attended(start_fields: dict[str, str] | None) -> bool:
+ return bool(start_fields) and start_fields.get("entrypoint") not in _UNATTENDED_ENTRYPOINTS
+
+
+# ---- tool-call quality -----------------------------------------------------------------------
+
+def _required_params(tools: Iterable[Any] | None) -> dict[str, tuple[str, ...]]:
+ required: dict[str, tuple[str, ...]] = {}
+ for tool in tools or ():
+ fn = tool.get("function") if isinstance(tool, dict) else None
+ if not isinstance(fn, dict) or not isinstance(fn.get("name"), str):
+ continue
+ params = fn.get("parameters")
+ names = params.get("required") if isinstance(params, dict) else None
+ required[fn["name"]] = tuple(n for n in names if isinstance(n, str)) if isinstance(names, list) else ()
+ return required
+
+
+def tool_call_issue(
+ name: Any, raw_args: Any, *, valid_names: Any, required: dict[str, tuple[str, ...]], repaired: bool,
+) -> str:
+ """The first problem with one emitted call, most severe first; ``none`` when clean.
+
+ Empty arguments are only an issue when the tool declares required parameters: for a
+ parameterless tool Hermes's normalization to ``{}`` is exactly what the model meant.
+ """
+ if name not in valid_names:
+ return "unknown_tool"
+ needed = required.get(name, ())
+ if isinstance(raw_args, (dict, list)):
+ parsed = raw_args
+ elif raw_args is None or not str(raw_args).strip():
+ return "empty_arguments" if needed else ("repaired" if repaired else "none")
+ else:
+ try:
+ parsed = json.loads(str(raw_args))
+ except (TypeError, ValueError):
+ return "invalid_json"
+ if not isinstance(parsed, dict) or any(key not in parsed for key in needed):
+ return "schema_mismatch"
+ return "repaired" if repaired else "none"
+
+
+def record_tool_call_quality(agent: Any, tool_calls: Iterable[Any], repaired_ids: frozenset[int] | set[int]) -> None:
+ """Count every tool call one primary response emitted, before Hermes normalizes it.
+
+ ``repaired_ids`` holds ``id(tc)`` of calls whose name Hermes auto-repaired; streamed calls
+ whose argument JSON was repaired carry ``function.args_repaired``. No-op unless enabled.
+ """
+ try:
+ from .relay_shared_metrics import enabled, record_process_mark
+
+ if not tool_calls or not enabled():
+ return
+ route = model_route(getattr(agent, "provider", None), getattr(agent, "model", None))
+ valid_names = getattr(agent, "valid_tool_names", None) or frozenset()
+ required = _required_params(getattr(agent, "tools", None))
+ for tc in tool_calls:
+ fn = tc.function
+ issue = tool_call_issue(
+ fn.name, fn.arguments, valid_names=valid_names, required=required,
+ repaired=id(tc) in repaired_ids or getattr(fn, "args_repaired", False) is True,
+ )
+ record_process_mark(contract.MODEL_TOOL_QUALITY_MARK, {**route, "call_role": "primary", "issue": issue})
+ except Exception:
+ logger.debug("Shared-metrics tool-call quality not recorded", exc_info=True)
+
+
+# ---- friction --------------------------------------------------------------------------------
+
+def record_model_friction(
+ signal: str, *, session_id: Any = None, agent: Any = None, provider: Any = None, model: Any = None,
+ hermes_home: Any = None,
+) -> None:
+ """Count one user friction action against the model that produced the session's last turn.
+
+ Falls back to ``agent`` (or ``provider``/``model``) when this process never saw the session's
+ turns (restart, remote compute host). ``hermes_home`` binds the owning profile for callers that
+ run outside it (multiplexed gateway, Desktop sessions of a secondary profile).
+ """
+ token = None
+ try:
+ if hermes_home:
+ from hermes_constants import set_hermes_home_override
+
+ token = set_hermes_home_override(str(hermes_home))
+ from .relay_shared_metrics import enabled, record_session_friction
+
+ if signal not in contract.FRICTION_SIGNALS or not enabled():
+ return
+ 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))
+ except Exception:
+ logger.debug("Shared-metrics %s friction not recorded", signal, exc_info=True)
+ finally:
+ if token is not None:
+ from hermes_constants import reset_hermes_home_override
+
+ reset_hermes_home_override(token)
diff --git a/tests/hermes_cli/test_shared_metrics_model.py b/tests/hermes_cli/test_shared_metrics_model.py
new file mode 100644
index 00000000000..92afc781274
--- /dev/null
+++ b/tests/hermes_cli/test_shared_metrics_model.py
@@ -0,0 +1,158 @@
+"""Per-model tool-call quality, friction and context-peak shared metrics."""
+
+from __future__ import annotations
+
+import json
+from types import SimpleNamespace
+
+from hermes_cli import lifecycle
+from hermes_cli.observability import relay_shared_metrics
+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 _tool_call(call_id, name, arguments, **function_extra):
+ return SimpleNamespace(
+ id=call_id, type="function",
+ function=SimpleNamespace(name=name, arguments=arguments, **function_extra),
+ )
+
+
+def _agent(provider, model):
+ tools = [
+ {"type": "function", "function": {"name": "read_file", "parameters": {
+ "type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}}},
+ {"type": "function", "function": {"name": "todo", "parameters": {"type": "object", "properties": {}}}},
+ ]
+ return SimpleNamespace(
+ provider=provider, model=model, session_id="s1", tools=tools,
+ valid_tool_names={"read_file", "todo"}, log_prefix="", _invalid_tool_retries=0, _invalid_json_retries=0,
+ _uniquify_tool_call_ids=lambda calls: None,
+ _repair_tool_call=lambda name: "read_file" if name == "Read_File" else None,
+ _vprint=lambda *a, **k: None, _buffer_vprint=lambda *a, **k: None, _flush_status_buffer=lambda: None,
+ _build_assistant_message=lambda message, finish_reason: {"role": "assistant", "content": ""},
+ _persist_session=lambda *a: None, _cleanup_task_resources=lambda *a: None,
+ )
+
+
+def _validate(agent, tool_calls) -> None:
+ from agent.turn_tool_validation import validate_tool_calls
+
+ validate_tool_calls(
+ agent, SimpleNamespace(content="", tool_calls=tool_calls), "tool_calls",
+ messages=[], conversation_history=[], api_call_count=1, effective_task_id="t1",
+ )
+
+
+def test_every_emitted_tool_call_counts_once_with_its_issue(direct_runtime, tmp_path):
+ """Clean calls count as ``none`` (the rate denominator); each defective call counts once with
+ the issue the model caused; a user-named provider never leaves the machine."""
+ _validate(_agent("openrouter", "anthropic/claude-sonnet"), [
+ _tool_call("c1", "read_file", '{"path": "a"}'),
+ _tool_call("c2", "todo", ""), # parameterless: "" means {}
+ _tool_call("c3", "read_file", '{"path": "a"'), # truncated JSON
+ _tool_call("c4", "acme_secret_tool", "{}"),
+ _tool_call("c5", "read_file", ""), # required param, no arguments
+ _tool_call("c6", "read_file", '{"file": "a"}'), # missing required key
+ _tool_call("c7", "Read_File", '{"path": "a"}'), # name auto-repaired
+ _tool_call("c8", "read_file", '{"path": "a"}', args_repaired=True),
+ ])
+ _validate(_agent("custom:acme-private", "acme-internal"), [_tool_call("c9", "todo", "{}")])
+ _flush()
+
+ rows = _stored_values(tmp_path, "hermes.model_tool_quality.count")
+ assert "acme" not in json.dumps(rows)
+ assert sorted((d["provider"], d["model"], d["call_role"], d["issue"], v) for d, v in rows) == sorted([
+ ("openrouter", "anthropic/claude-sonnet", "primary", "none", 2),
+ ("openrouter", "anthropic/claude-sonnet", "primary", "invalid_json", 1),
+ ("openrouter", "anthropic/claude-sonnet", "primary", "unknown_tool", 1),
+ ("openrouter", "anthropic/claude-sonnet", "primary", "empty_arguments", 1),
+ ("openrouter", "anthropic/claude-sonnet", "primary", "schema_mismatch", 1),
+ ("openrouter", "anthropic/claude-sonnet", "primary", "repaired", 2),
+ ("custom", "custom", "primary", "none", 1),
+ ])
+
+
+def test_tool_call_quality_records_nothing_while_disabled(direct_runtime, tmp_path, monkeypatch):
+ monkeypatch.setattr("hermes_cli.config.read_raw_config_readonly", lambda: {})
+ _validate(_agent("openrouter", "anthropic/claude-sonnet"), [_tool_call("c1", "nope", "{")])
+ assert not (tmp_path / "hermes-home" / "telemetry").exists() or not _stored_values(
+ tmp_path, "hermes.model_tool_quality.count")
+
+
+def _turn(session_id, task_id, model, result, *, usage=None, context_length=None, error=None, **start):
+ base = {"session_id": session_id, "task_id": task_id, "api_request_id": f"{task_id}-r",
+ "provider": "openrouter", "model": model}
+ lifecycle.invoke_hook("pre_llm_call", **base, platform="cli", **start)
+ lifecycle.invoke_hook("pre_api_request", **base)
+ if error:
+ lifecycle.invoke_hook("api_request_error", **base, retryable=True, reason=error)
+ if usage is not None or error is None: # an error with no usage never recovered
+ lifecycle.invoke_hook("post_api_request", **base, usage=usage, context_length=context_length)
+ if result is not None:
+ relay_shared_metrics.finish_task_run(session_id=session_id, task_id=task_id, platform="cli", result=result)
+
+
+def test_friction_is_attributed_to_the_model_that_produced_the_turn(direct_runtime, tmp_path):
+ """After a /model switch the retry still blames the model whose turn is retried; interrupts and
+ a quick exit after a failure count once; a session-close abort and delegated work never do."""
+ from hermes_cli.observability import shared_metrics_events as events
+ from hermes_cli.observability.shared_metrics_model import record_model_friction
+
+ _turn("s1", "t1", "model-a", {"completed": True})
+ events.record_model_switch(from_provider="openrouter", to_provider="anthropic", surface="cli", from_model="model-a")
+ record_model_friction("retry", session_id="s1", provider="anthropic", model="model-b")
+ record_model_friction("undo", session_id="gone", provider="anthropic", model="model-b")
+ _turn("s1", "t2", "model-a", {"interrupted": True, "turn_exit_reason": "interrupted_by_user"})
+ _turn("s1", "t3", "model-a", {"failed": True, "turn_exit_reason": "failed"})
+ lifecycle.finalize_session(session_id="s1")
+
+ _turn("s2", "t1", "model-c", {"completed": True})
+ _turn("s2", "t2", "model-c", None) # still running when the session closes
+ lifecycle.finalize_session(session_id="s2")
+ _turn("child", "t1", "model-d", {"interrupted": True}, parent_session_id="s1")
+ lifecycle.finalize_session(session_id="child")
+ _flush()
+
+ rows = _stored_values(tmp_path, "hermes.model_friction.count")
+ assert sorted((d["provider"], d["model"], d["signal"], v) for d, v in rows) == sorted([
+ ("openrouter", "model-a", "switch_away", 1),
+ ("openrouter", "model-a", "retry", 1),
+ ("anthropic", "model-b", "undo", 1),
+ ("openrouter", "model-a", "interrupt", 1),
+ ("openrouter", "model-a", "quick_abandon", 1),
+ ])
+
+
+def test_context_peak_is_one_bucketed_row_per_session(direct_runtime, tmp_path):
+ """The fullest primary context a session reached, its window bucket and whether it overflowed;
+ delegated children add no row."""
+ _turn("s1", "t1", "model-a", {"completed": True}, usage={"prompt_tokens": 50_000}, context_length=200_000)
+ _turn("s1", "t2", "model-a", {"completed": True}, usage={"prompt_tokens": 160_000}, context_length=200_000,
+ error="context_overflow")
+ _turn("s1", "t3", "model-a", {"completed": True}, usage={"prompt_tokens": 20_000}, context_length=200_000)
+ lifecycle.finalize_session(session_id="s1")
+ _turn("s2", "t1", "model-b", {"completed": True}, usage={"input_tokens": 10_000}, context_length=1_048_576)
+ lifecycle.finalize_session(session_id="s2")
+ _turn("s3", "t1", "model-c", None, error="context_overflow") # every call overflowed, none finished
+ relay_shared_metrics.finish_task_run(session_id="s3", task_id="t1", platform="cli", result={"failed": True})
+ lifecycle.finalize_session(session_id="s3")
+ _turn("child", "t1", "model-d", {"completed": True}, usage={"prompt_tokens": 1}, context_length=8_000,
+ parent_session_id="s1")
+ lifecycle.finalize_session(session_id="child")
+ _flush()
+
+ rows = _stored_values(tmp_path, "hermes.context_peak.count")
+ assert sorted(
+ (d["model"], d["peak_fill_bucket"], d["window_bucket"], d["limit_hit"], v) for d, v in rows
+ ) == [
+ ("model-a", "75_to_90", "128k_to_256k", "yes", 1),
+ ("model-b", "lt_50", "gte_1m", "no", 1),
+ ("model-c", "unknown", "unknown", "yes", 1),
+ ]
diff --git a/tui_gateway/contracts/sessions.py b/tui_gateway/contracts/sessions.py
index a5a90291a27..685161f1e74 100644
--- a/tui_gateway/contracts/sessions.py
+++ b/tui_gateway/contracts/sessions.py
@@ -422,8 +422,14 @@ method("session.branch_whole", params=SessionBranchWholeParams, result=SessionBr
doc="session.branch of the whole history without echoing the copied transcript back.")
+class UndoIntent(WireEnum):
+ RETRY = "retry"
+ UNDO = "undo"
+
+
class SessionUndoParams(SessionParams):
- pass
+ # ``retry``: the client resends the dropped turn (Ink /retry), so metrics count a retry, not an undo.
+ intent: UndoIntent | None = None
class SessionUndoResult(Result):
diff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.py
index 50b6e754a35..2e2db54971d 100644
--- a/tui_gateway/methods_session.py
+++ b/tui_gateway/methods_session.py
@@ -1939,6 +1939,8 @@ def _(rid, params: dict, session: dict) -> dict:
removed = _rewind_active_session_history(session, user_turns - 1)[2]
except Exception as exc:
return _err(rid, 5008, f"undo: {exc}")
+ if removed: # Ink /retry is undo + resend and says so via ``intent`` (helper: methods_tools).
+ _tui_model_friction("retry" if params.get("intent") == "retry" else "undo", session)
return _ok(rid, {"removed": removed})
diff --git a/tui_gateway/methods_tools.py b/tui_gateway/methods_tools.py
index db69b8631fb..ce9c379db28 100644
--- a/tui_gateway/methods_tools.py
+++ b/tui_gateway/methods_tools.py
@@ -829,9 +829,17 @@ def _cmd_retry(rid, params, session, name, arg):
if err:
return err
content = cc.retryable_user_text(rewound[1].get("content"))
+ _tui_model_friction("retry", session)
return _ok(rid, {"type": "send", "message": content})
+def _tui_model_friction(signal, session):
+ from hermes_cli.observability.shared_metrics_model import record_model_friction
+ record_model_friction(
+ signal, session_id=session.get("session_key"), agent=session.get("agent"),
+ hermes_home=session.get("profile_home"))
+
+
def _cmd_steer(rid, params, session, name, arg):
if not arg:
return _err(rid, 4004, "usage: /steer <prompt>")
@@ -927,6 +935,7 @@ def _cmd_undo(rid, params, session, name, arg):
):
with contextlib.suppress(Exception):
step()
+ _tui_model_friction("undo", session)
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/tui_gateway/model_switch.py b/tui_gateway/model_switch.py
index fc888ba9658..6f08a8d2c4c 100644
--- a/tui_gateway/model_switch.py
+++ b/tui_gateway/model_switch.py
@@ -350,7 +350,8 @@ def _apply_model_switch(
from hermes_cli.observability.shared_metrics_events import record_model_switch
record_model_switch(
- from_provider=current_provider, to_provider=result.target_provider, surface=_session_source(session))
+ from_provider=current_provider, to_provider=result.target_provider, surface=_session_source(session),
+ from_model=current_model)
return {
"value": result.new_model, "warning": result.warning_message or "",
"confirm_required": False,
diff --git a/ui-tui/src/app/slash/commands/core.ts b/ui-tui/src/app/slash/commands/core.ts
index 65b7f50bd2b..e7a44584ebb 100644
--- a/ui-tui/src/app/slash/commands/core.ts
+++ b/ui-tui/src/app/slash/commands/core.ts
@@ -758,7 +758,7 @@ export const coreCommands: SlashCommand[] = [
return ctx.transcript.send(last)
}
- ctx.gateway.rpc<SessionUndoResponse>('session.undo', { session_id: ctx.sid }).then(
+ ctx.gateway.rpc<SessionUndoResponse>('session.undo', { intent: 'retry', session_id: ctx.sid }).then(
ctx.guarded<SessionUndoResponse>(r => {
if ((r.removed ?? 0) <= 0) {
return ctx.transcript.sys('nothing to retry')
diff --git a/website/docs/developer-guide/relay-shared-metrics.md b/website/docs/developer-guide/relay-shared-metrics.md
index aeae5d8ee64..a2780037724 100644
--- a/website/docs/developer-guide/relay-shared-metrics.md
+++ b/website/docs/developer-guide/relay-shared-metrics.md
@@ -293,6 +293,17 @@ Sessions are summarized when they close (finalize, reset or process exit);
delegated child sessions are not counted separately. Milestones latch in the
local database, so each fires once per install however many processes reach it.
+#### Per-model quality, friction and context pressure
+
+Provider and model follow the model-route rules: a provider Hermes ships and its
+model id; custom endpoints and loopback servers read `custom`.
+
+| Metric | Dimensions | Question it answers |
+|---|---|---|
+| `hermes.model_tool_quality.count` | provider, model, call role, issue (`none`, `invalid_json`, `unknown_tool`, `schema_mismatch`, `empty_arguments`, `repaired`) | Which models emit broken tool calls, and how often Hermes had to repair them. Every emitted call counts once (clean ones as `none`), so the value is a rate denominator. `empty_arguments` only counts for tools with required parameters; `repaired` means Hermes fixed the tool name or the argument JSON and ran the call. |
+| `hermes.model_friction.count` | provider, model, signal (`retry`, `undo`, `interrupt`, `quick_abandon`, `switch_away`) | Which models users fight with. Attributed to the model that produced the turn: `/retry` and `/undo` where they execute, a user interrupt of an interactive turn, a session that ends within 60 seconds of a failed turn, and `/model` switching away from the model. |
+| `hermes.context_peak.count` | provider, model, peak fill bucket, window bucket (`lt_32k` … `gte_1m`), limit hit (`yes`/`no`) | How close sessions get to each model's context window, and how often they overflow it. One row per closed session; `limit_hit` means a primary call was rejected as too large (context overflow or HTTP 413), the rejections Hermes answers with a forced compression. |
+
Local state is written under:
```text