The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(telemetry): loop metrics count only the user's real backend work and curator passes
teknium1f7b5ea6f7a07
diff --git a/agent/curator.py b/agent/curator.pyindex 4bce58a5555..5a8a69c94c9 100644--- a/agent/curator.py+++ b/agent/curator.py@@ -1201,9 +1201,7 @@ def maybe_run_curator(*, idle_for_seconds: Optional[float] = None, on_summary: O# Idle gating: only enforce when the caller provided a measurement.if not should_run_now() or (idle_for_seconds is not None and idle_for_seconds < get_min_idle_hours() * 3600.0):return None- if not _claim_run():- from hermes_cli.observability.shared_metrics_loop import record_curator_run- record_curator_run(trigger="scheduled", outcome="skipped") # another process holds this home's pass+ if not _claim_run(): # the holder's own pass is the one counted; every tick would re-count itreturn Nonetry:return run_curator_review(on_summary=on_summary, trigger="scheduled")diff --git a/hermes_cli/observability/schemas/hermes.shared_metrics.v3.schema.json b/hermes_cli/observability/schemas/hermes.shared_metrics.v3.schema.jsonindex c5d06292030..ebe32e7fd00 100644--- a/hermes_cli/observability/schemas/hermes.shared_metrics.v3.schema.json+++ b/hermes_cli/observability/schemas/hermes.shared_metrics.v3.schema.json@@ -1006,10 +1006,12 @@"daytona","docker","local",+ "managed_modal","modal","other","singularity",- "ssh"+ "ssh",+ "vercel_sandbox"]},"behind_bucket": {@@ -1778,11 +1780,13 @@"firecrawl","lightpanda","local",+ "managed_modal","modal","other","remote","singularity",- "ssh"+ "ssh",+ "vercel_sandbox"]},"error_class": {diff --git a/hermes_cli/observability/shared_metrics_contract.py b/hermes_cli/observability/shared_metrics_contract.pyindex 0c6603a026c..37f296ace60 100644--- a/hermes_cli/observability/shared_metrics_contract.py+++ b/hermes_cli/observability/shared_metrics_contract.py@@ -199,7 +199,10 @@ CONTEXT_FILL_BUCKETS = frozenset({"lt_50", "50_to_75", "75_to_90", "90_to_100",EXTENSION_KINDS = frozenset({"mcp_server", "plugin", "skill"})EXTENSION_SOURCES = frozenset({"bundled", "catalog", "hub", "local", "other", "url"})EXTENSION_OUTCOMES = frozenset({"failed", "success"})-TERMINAL_BACKENDS = frozenset({"daytona", "docker", "local", "modal", "other", "singularity", "ssh"})+# Every built-in backend in tools/terminal_tool_config.py::_BUILTIN_BACKENDS.+TERMINAL_BACKENDS = frozenset({+ "daytona", "docker", "local", "managed_modal", "modal", "other", "singularity", "ssh", "vercel_sandbox",+})AUX_TASKS = _CatalogValues("aux_task_names", extra=frozenset({"none", "other"}))SLASH_COMMANDS = _CatalogValues("slash_command_names", extra=frozenset({"plugin", "skill", "unknown"}))SKILL_NAMES = _CatalogValues("bundled_skill_names", extra=frozenset({"custom"}))diff --git a/hermes_cli/observability/shared_metrics_loop.py b/hermes_cli/observability/shared_metrics_loop.pyindex a7f14d4e470..48042734230 100644--- a/hermes_cli/observability/shared_metrics_loop.py+++ b/hermes_cli/observability/shared_metrics_loop.py@@ -11,6 +11,7 @@ This module imports only the stdlib at load time so tool modules can import it ofrom __future__ import annotationsimport contextlib+import contextvarsimport jsonimport loggingimport threading@@ -275,9 +276,10 @@ _STATUS_ERROR_CLASSES = {def _terminal_failure(data: dict[str, Any]) -> str | None:- if not data.get("error"):- return None- return "timeout" if data.get("exit_code") == 124 else "tool_error"+ # 124 is the tool's own foreground-deadline code; it carries partial output and no ``error``.+ if data.get("exit_code") == 124:+ return "timeout"+ return "tool_error" if data.get("error") else Nonedef _code_failure(data: dict[str, Any]) -> str | None:@@ -304,7 +306,7 @@ def execution_backend_fields(*, kind: Any, backend: Any, result: Any, error_claskind_value = _norm(kind)if kind_value not in EXECUTION_BACKENDS_BY_KIND:return None- backend_value = _norm(backend)+ backend_value = _norm(backend() if callable(backend) else backend)failure = error_class if error_class is not None else _FAILURE_CLASSIFIERS[kind_value](_parsed(result))return {"backend": backend_value if backend_value in EXECUTION_BACKENDS_BY_KIND[kind_value] else "other",@@ -314,8 +316,26 @@ def execution_backend_fields(*, kind: Any, backend: Any, result: Any, error_clas}+# Set while Hermes itself drives a backend (TUI/Desktop path completion listings): that is not the+# user's workload, so it must not show up as backend usage.+_UNMETERED = contextvars.ContextVar("shared_metrics_unmetered_backend", default=False)+++def unmetered_backend_calls() -> Iterator[None]:+ """Run Hermes-owned terminal/browser/code calls without counting them as execution-backend use."""+ token = _UNMETERED.set(True)+ try:+ yield+ finally:+ _UNMETERED.reset(token)++def record_execution_backend(kind: str, backend: Any, result: Any = None, *, error_class: str | None = None) -> Any:- """Count one tool call that reached its backend; returns ``result`` unchanged."""+ """Count one tool call that reached its backend; returns ``result`` unchanged. ``backend`` may be a+ callable so resolving it costs nothing while collection is off."""+ if _UNMETERED.get():+ return result_emit("EXECUTION_BACKEND_MARK", execution_backend_fields, kind=kind, backend=backend, result=result,error_class=error_class,@@ -353,8 +373,10 @@ def record_browser_call(call: Callable[[Callable[[Callable[[], Any]], Any]], Anydef _safe_record_browser(backend: Callable[[], str], result: Any, error_class: str | None) -> None:- try:- name = backend()- except Exception:- name = "other"+ def name() -> str:+ try:+ return backend()+ except Exception:+ return "other"+record_execution_backend("browser", name, result, error_class=error_class)diff --git a/tests/hermes_cli/test_shared_metrics_loop.py b/tests/hermes_cli/test_shared_metrics_loop.pyindex c63154fa73a..f0952760461 100644--- a/tests/hermes_cli/test_shared_metrics_loop.py+++ b/tests/hermes_cli/test_shared_metrics_loop.py@@ -126,14 +126,14 @@ def test_async_curator_pass_records_in_the_profile_that_started_it(home, tmp_patassert _rows(owner, "hermes.curator.run.count") == [({**zero, "outcome": "success", "trigger": "manual"}, 1)]-def test_scheduled_curator_pass_held_elsewhere_counts_as_skipped(home, monkeypatch):+def test_scheduled_ticks_that_find_the_pass_held_elsewhere_record_nothing(home, monkeypatch):from agent import curatormonkeypatch.setattr(curator, "should_run_now", lambda: True)monkeypatch.setattr(curator, "_claim_run", lambda: False)- assert curator.maybe_run_curator() is None- [(dims, value)] = _rows(home, "hermes.curator.run.count")- assert (dims["trigger"], dims["outcome"], value) == ("scheduled", "skipped", 1)+ for _ in range(3): # gateway housekeeping ticks while another process holds the claim+ assert curator.maybe_run_curator() is None+ assert _rows(home, "hermes.curator.run.count") == []def test_delegation_fanout_split_into_units_is_one_row_in_the_parent_profile(home, tmp_path):@@ -198,6 +198,52 @@ def test_terminal_calls_count_against_the_configured_backend(home):]+def test_foreground_terminal_timeout_is_a_failed_timeout(home):+ from tools.terminal_tool import terminal_tool++ assert json.loads(terminal_tool("sleep 5", timeout=1))["exit_code"] == 124++ assert _rows(home, "hermes.execution_backend.count") == [+ ({"backend": "local", "error_class": "timeout", "kind": "terminal", "outcome": "failed"}, 1),+ ]+++def test_path_completion_listing_is_not_user_backend_work(home):+ import tui_gateway.methods_complete as mc+ from tools.terminal_tool import terminal_tool++ for _ in range(3): # three keystrokes of `@file:` on a non-local backend each list the directory+ assert mc._backend_dir_entries(str(home), "sess-1") is not None+ terminal_tool("echo user-work")++ assert _rows(home, "hermes.execution_backend.count") == [+ ({"backend": "local", "error_class": "none", "kind": "terminal", "outcome": "success"}, 1),+ ]+++def test_every_shipped_terminal_backend_has_its_own_bucket():+ from hermes_cli.observability import shared_metrics_contract as contract+ from tools.terminal_tool_config import _BUILTIN_BACKENDS++ schema = json.loads(+ (Path(contract.__file__).parent / "schemas" / "hermes.shared_metrics.v3.schema.json").read_text()+ )+ execution = schema["$defs"]["execution_backend_counter"]["properties"]["dimensions"]+ for backend in _BUILTIN_BACKENDS:+ fields = loop.execution_backend_fields(kind="terminal", backend=backend, result="{}", error_class=None)+ assert fields["backend"] == backend+ assert backend in execution["properties"]["backend"]["enum"]+++def test_browser_backend_is_not_resolved_while_collection_is_off(home, monkeypatch):+ monkeypatch.setattr(+ "hermes_cli.config.read_raw_config_readonly", lambda: {"telemetry": {"shared_metrics": {"enabled": False}}},+ )+ resolved = []+ loop.record_browser_call(lambda legacy: legacy(lambda: '{"success": true}'), lambda: resolved.append(1) or "local")+ assert resolved == []++def test_browser_calls_name_the_backend_that_served_them(home):served = loop.record_browser_call(lambda legacy: legacy(lambda: '{"success": true}'), lambda: "browserbase")assert served == '{"success": true}'diff --git a/tui_gateway/methods_complete.py b/tui_gateway/methods_complete.pyindex 3585d7d4cda..5058cc6ff88 100644--- a/tui_gateway/methods_complete.py+++ b/tui_gateway/methods_complete.py@@ -165,6 +165,7 @@ def _backend_dir_entries(search_dir: str, session_key: str | None) -> list[tuple'if [ -d "$p" ]; then printf "%s/\\n" "${p##*/}"; else printf "%s\\n" "${p##*/}"; fi; done')try:+ from hermes_cli.observability.shared_metrics_loop import unmetered_backend_callsfrom tools.terminal_tool import terminal_tool# Pre-confirm this internal read-only listing: its fixed `sh -c` script shape is# guard-flagged as "shell command via -c/-lc flag", so under smart approvals every@@ -172,9 +173,10 @@ def _backend_dir_entries(search_dir: str, session_key: str | None) -> list[tuple# configured), and Desktop's ws reconnect loop turns that into model traffic from an# idle machine (#115478). The script is a constant and the search dir is quoted, so# nothing here needs an approval verdict.- result = json.loads(terminal_tool(- f"sh -c {shlex.quote(script)} sh {shlex.quote(search_dir)}", task_id=session_key, timeout=3,- force=True))+ with unmetered_backend_calls(): # Hermes' own listing, not the user's backend work+ result = json.loads(terminal_tool(+ f"sh -c {shlex.quote(script)} sh {shlex.quote(search_dir)}", task_id=session_key, timeout=3,+ force=True))except Exception:return []if result.get("error") or result.get("exit_code") not in (0, None):diff --git a/website/docs/developer-guide/relay-shared-metrics.md b/website/docs/developer-guide/relay-shared-metrics.mdindex b9332394387..7ddf58f2275 100644--- a/website/docs/developer-guide/relay-shared-metrics.md+++ b/website/docs/developer-guide/relay-shared-metrics.md@@ -305,9 +305,9 @@ itself ships.| `hermes.slash_command.count` | command, surface | Which built-in commands are used (`/retry`, `/undo`, `/new` are friction signals). Skill and plugin commands report `skill`/`plugin`. || `hermes.extension.install.count` | kind, source, name, outcome | Which catalog skills, MCP servers and plugins get installed. `name` is a bundled/optional skill, `optional-mcps/` or `plugin-catalog/` entry, otherwise `custom`. || `hermes.memory.op.count` | op (`add`/`replace`/`remove`/`read`/`search`/`other`), provider (`builtin`, a bundled memory plugin, else `plugin`), origin (`foreground`/`background_review`), outcome (`success`/`failed`/`rejected`) | Is the learning loop writing memory, who asks for it (the user's turn or the background review), and how often writes are refused or fail. Never the memory text. |-| `hermes.curator.run.count` | trigger (`scheduled`/`manual`), outcome (`success`/`failed`/`skipped`), archived/merged/patched/created buckets | Does the skill curator run, and does it actually consolidate anything. Dry runs and passes another process already holds report `skipped`. Never skill names. |+| `hermes.curator.run.count` | trigger (`scheduled`/`manual`), outcome (`success`/`failed`/`skipped`), archived/merged/patched/created buckets | Does the skill curator run, and does it actually consolidate anything. Dry runs report `skipped`; a scheduled check that finds another process already running the pass records nothing. Never skill names. || `hermes.delegation.run.count` | subagent-count bucket, depth (`1`–`3`, `gte_4`), mode (`foreground`/`background`), outcome (`success`/`partial`/`failed`/`cancelled`) | How wide and deep delegate_task fan-outs go and how often every child finishes. One row per call, however many completion units it splits into. |-| `hermes.execution_backend.count` | kind (`terminal`/`browser`/`code`), backend, outcome, error class | Which sandboxes carry real work and how reliable each is. Terminal backends are the `terminal.backend` values (else `other`); browser backends are `local`, `lightpanda`, `cdp`, `camofox`, `extension` or a bundled cloud provider (else `other`); execute_code is `local` or `remote`. A command's own nonzero exit is still a backend success; terminal and execute_code calls a guard refuses before they reach the backend are not counted. |+| `hermes.execution_backend.count` | kind (`terminal`/`browser`/`code`), backend, outcome, error class | Which sandboxes carry real work and how reliable each is. Terminal backends are the `terminal.backend` values (else `other`); browser backends are `local`, `lightpanda`, `cdp`, `camofox`, `extension` or a bundled cloud provider (else `other`); execute_code is `local` or `remote`. A command's own nonzero exit is still a backend success, but a foreground command that hits its timeout is `failed`/`timeout`; terminal and execute_code calls a guard refuses before they reach the backend, and Hermes' own listings for TUI/Desktop path completion, are not counted. || `hermes.platform.health` | platform, event (`connect_ok`/`connect_failed`/`reconnect`/`disconnect`), error class (`auth`/`network`/`rate_limited`/`config`/`other`) | Which messaging platforms fail to connect or drop, and why. Classified from exception types, HTTP statuses and Hermes's own fatal codes, never error text. || `hermes.platform.delivery` | platform, outcome (`sent`/`failed`), failure class (`rate_limited`/`too_long`/`auth`/`network`/`forbidden`/`other`) | How often replies fail to reach the user per platform (one count per logical reply, retries included). || `hermes.gateway.reply_latency` | platform, first-response bucket (`lt_2s` … `gte_60s`) | Time from an accepted inbound message to the first visible reply text (stream first chunk or final message). |