Skip to content

The agent that grows with you

feat(telemetry): wire memory, curator, delegation and backend call sites

teknium125c1b008c82a
diff --git a/agent/curator.py b/agent/curator.py
index 28f2616ba7e..4bce58a5555 100644
--- a/agent/curator.py
+++ b/agent/curator.py
@@ -914,7 +914,7 @@ def _consolidation_pass(prefix: str, auto_summary: str, dry_run: bool, before_na
def run_curator_review(
on_summary: Optional[Callable[[str], None]] = None, synchronous: bool = False,
- dry_run: bool = False, consolidate: Optional[bool] = None,
+ dry_run: bool = False, consolidate: Optional[bool] = None, trigger: str = "manual",
) -> Dict[str, Any]:
"""Execute a single curator review pass: (1) automatic state transitions (no LLM); (2) if *consolidate* and there are
candidates, fork an AIAgent on the review prompt; (3) update .curator_state; (4) call *on_summary*.
@@ -924,6 +924,7 @@ def run_curator_review(
recorded in ``state.last_report_path`` so users can read what WOULD have happened."""
consolidate = get_consolidate() if consolidate is None else consolidate
start = datetime.now(timezone.utc)
+ hermes_home = get_hermes_home() # the LLM pass may run on a thread with no profile binding
if dry_run: # count candidates without mutating state
counts = {"checked": len(_safe_curated_report()), "marked_stale": 0, "archived": 0, "reactivated": 0}
else:
@@ -969,16 +970,18 @@ def run_curator_review(
elapsed = (datetime.now(timezone.utc) - start).total_seconds()
state2 = {**load_state(), "last_run_duration_seconds": elapsed, "last_run_summary": final_summary}
# Per-run report, best-effort; path recorded for `hermes curator status`.
+ after_report = _safe_curated_report()
try:
report_path = _write_run_report(
started_at=start, elapsed_seconds=elapsed, auto_counts=counts, auto_summary=auto_summary,
- before_report=before_report, before_names=before_names, after_report=_safe_curated_report(), llm_meta=llm_meta,
+ before_report=before_report, before_names=before_names, after_report=after_report, llm_meta=llm_meta,
)
if report_path is not None:
state2["last_report_path"] = str(report_path)
except Exception as e:
logger.debug("Curator report write failed: %s", e, exc_info=True)
save_state(state2)
+ _record_run_metric(trigger, dry_run, counts, before_report, after_report, llm_meta, hermes_home)
_notify(on_summary, f"curator: {final_summary}")
if synchronous:
@@ -999,6 +1002,21 @@ def run_curator_review(
# --- Provider/model resolution for the review fork ---
+def _record_run_metric(trigger, dry_run, counts, before_report, after_report, llm_meta, hermes_home) -> None:
+ from hermes_cli.observability.shared_metrics_loop import record_curator_run
+
+ def what_changed() -> Dict[str, int]:
+ before, after = _by_name(before_report), _by_name(after_report)
+ diff = _diff_and_classify(set(before), set(after), llm_meta.get("tool_calls") or [], llm_meta.get("final") or "")
+ patched = sum(int(after[n].get("patch_count") or 0) > int(before[n].get("patch_count") or 0)
+ for n in diff.after_names & set(before))
+ return {"archived": int(counts.get("archived", 0)) + len(diff.removed), "created": len(diff.added),
+ "merged": len(diff.consolidated), "patched": patched}
+
+ outcome = "skipped" if dry_run else "failed" if llm_meta.get("error") else "success"
+ record_curator_run(trigger=trigger, outcome=outcome, counts=what_changed, hermes_home=hermes_home)
+
+
class _ReviewRuntimeBinding(NamedTuple):
"""Provider/model for the curator review fork plus per-slot overrides."""
provider: str
@@ -1184,9 +1202,11 @@ def maybe_run_curator(*, idle_for_seconds: Optional[float] = None, on_summary: O
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
return None
try:
- return run_curator_review(on_summary=on_summary)
+ return run_curator_review(on_summary=on_summary, trigger="scheduled")
finally:
_release_run_claim()
except Exception as e:
diff --git a/agent/memory_manager.py b/agent/memory_manager.py
index 3381e86d3ab..d023a57f8bc 100644
--- a/agent/memory_manager.py
+++ b/agent/memory_manager.py
@@ -645,11 +645,15 @@ class MemoryManager:
provider = self._tool_to_provider.get(tool_name)
if provider is None:
return tool_error(f"No memory provider handles tool '{tool_name}'")
+ from hermes_cli.observability.shared_metrics_loop import record_provider_memory_call
try:
- return provider.handle_tool_call(tool_name, args, **kwargs)
+ result = provider.handle_tool_call(tool_name, args, **kwargs)
except Exception as e:
logger.error("Memory provider '%s' handle_tool_call(%s) failed: %s", provider.name, tool_name, e)
+ record_provider_memory_call(provider.name, tool_name, args, raised=True)
return tool_error(f"Memory tool '{tool_name}' failed: {e}")
+ record_provider_memory_call(provider.name, tool_name, args, result)
+ return result
def on_turn_start(self, turn_number: int, message: str, **kwargs) -> None:
def _tick(p: MemoryProvider) -> None:
diff --git a/tests/hermes_cli/test_shared_metrics_loop.py b/tests/hermes_cli/test_shared_metrics_loop.py
new file mode 100644
index 00000000000..c63154fa73a
--- /dev/null
+++ b/tests/hermes_cli/test_shared_metrics_loop.py
@@ -0,0 +1,227 @@
+"""Learning-loop, delegation and execution-backend shared metrics, read back from the real store."""
+
+from __future__ import annotations
+
+import json
+import threading
+from pathlib import Path
+
+import pytest
+
+from hermes_cli.observability import relay_shared_metrics
+from hermes_cli.observability import shared_metrics_loop as loop
+from hermes_cli.observability.shared_metrics import SharedMetricsStore
+from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+from tests.hermes_cli.test_relay_shared_metrics_runtime import direct_runtime # noqa: F401
+
+_LOOP_METRICS = {
+ "hermes.memory.op.count", "hermes.curator.run.count", "hermes.delegation.run.count",
+ "hermes.execution_backend.count",
+}
+
+
+def _rows(home: Path, metric: str) -> list[tuple[dict, int]]:
+ relay_shared_metrics._reset_for_tests() # drain the subscriber into the store
+ root = home / "telemetry" / "shared_metrics"
+ if not (root / "metrics.sqlite3").exists():
+ return []
+ store = SharedMetricsStore(root / "metrics.sqlite3", root / "outbox")
+ return [(row["dimensions"], row["value"]) for row in store.counter_snapshot() if row["metric_name"] == metric]
+
+
+def home(direct_runtime, tmp_path): # noqa: F811
+ path = tmp_path / "hermes-home"
+ path.mkdir(parents=True, exist_ok=True)
+ return path
+
+
+def _memory_store():
+ from tools.memory_tool import load_on_disk_store
+
+ return load_on_disk_store()
+
+
+def test_memory_tool_counts_each_operation_with_its_outcome_and_origin(home):
+ from tools.memory_tool import memory_tool
+ from tools.skill_provenance import BACKGROUND_REVIEW, reset_current_write_origin, set_current_write_origin
+
+ store = _memory_store()
+ assert json.loads(memory_tool("add", content="prefers tabs", store=store))["success"]
+ memory_tool("replace", content="x", store=store) # refused before the store: no old_text
+ memory_tool("replace", content="x", old_text="no such entry", store=store) # the store could not apply it
+ memory_tool("explode", store=store) # unknown action
+ token = set_current_write_origin(BACKGROUND_REVIEW)
+ try:
+ memory_tool(operations=[{"action": "add", "content": "a"}, {"action": "add", "content": "b"}], store=store)
+ finally:
+ reset_current_write_origin(token)
+
+ rows = {tuple(sorted(d.items())): v for d, v in _rows(home, "hermes.memory.op.count")}
+ base = {"provider": "builtin", "origin": "foreground"}
+ assert rows == {
+ tuple(sorted({**base, "op": "add", "outcome": "success"}.items())): 1,
+ tuple(sorted({**base, "op": "replace", "outcome": "rejected"}.items())): 1,
+ tuple(sorted({**base, "op": "replace", "outcome": "failed"}.items())): 1,
+ tuple(sorted({**base, "op": "other", "outcome": "rejected"}.items())): 1,
+ tuple(sorted({**base, "origin": "background_review", "op": "add", "outcome": "success"}.items())): 2,
+ }
+
+
+def test_memory_provider_tools_report_bounded_provider_and_op(home):
+ from agent.memory_manager import MemoryManager
+
+ class _Provider:
+ def __init__(self, name, tool, result=None, boom=False):
+ self.name, self._tool, self._result, self._boom = name, tool, result, boom
+
+ def get_tool_schemas(self):
+ return [{"name": self._tool, "description": "", "parameters": {"type": "object", "properties": {}}}]
+
+ def handle_tool_call(self, tool_name, args, **kw):
+ if self._boom:
+ raise RuntimeError("secret backend detail")
+ return self._result
+
+ manager = MemoryManager()
+ manager._tool_to_provider = {
+ "honcho_search": _Provider("honcho", "honcho_search", '{"results": []}'),
+ "acme_private_remember": _Provider("acme-private-memory", "acme_private_remember", boom=True),
+ }
+ manager.handle_tool_call("honcho_search", {"query": "q"})
+ manager.handle_tool_call("acme_private_remember", {"content": "c"})
+
+ rows = sorted((d["provider"], d["op"], d["outcome"]) for d, _ in _rows(home, "hermes.memory.op.count"))
+ assert rows == [("honcho", "search", "success"), ("plugin", "add", "failed")]
+
+
+def test_disabled_shared_metrics_record_no_loop_rows(home, monkeypatch):
+ monkeypatch.setattr(
+ "hermes_cli.config.read_raw_config_readonly", lambda: {"telemetry": {"shared_metrics": {"enabled": False}}},
+ )
+ from tools.memory_tool import memory_tool
+
+ memory_tool("add", content="x", store=_memory_store())
+ loop.record_execution_backend("terminal", "local", '{"exit_code": 0, "error": null}')
+ loop.record_curator_run(trigger="manual", outcome="success")
+ relay_shared_metrics._reset_for_tests()
+ assert all(not _rows(home, metric) for metric in _LOOP_METRICS)
+
+
+def test_async_curator_pass_records_in_the_profile_that_started_it(home, tmp_path):
+ from agent import curator
+
+ owner = tmp_path / "owner-profile"
+ owner.mkdir()
+ done = threading.Event()
+ token = set_hermes_home_override(owner) # the review thread does not inherit this binding
+ try:
+ curator.run_curator_review(consolidate=False, on_summary=lambda _msg: done.set())
+ finally:
+ reset_hermes_home_override(token)
+ assert done.wait(30)
+
+ assert _rows(home, "hermes.curator.run.count") == []
+ zero = {f"{k}_bucket": "0" for k in ("archived", "created", "merged", "patched")}
+ assert _rows(owner, "hermes.curator.run.count") == [({**zero, "outcome": "success", "trigger": "manual"}, 1)]
+
+
+def test_scheduled_curator_pass_held_elsewhere_counts_as_skipped(home, monkeypatch):
+ from agent import curator
+
+ monkeypatch.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)
+
+
+def test_delegation_fanout_split_into_units_is_one_row_in_the_parent_profile(home, tmp_path):
+ call = ["task-a", "task-b", "task-c"]
+ loop.begin_delegation_run(call, subagents=3, depth=2)
+
+ other = tmp_path / "unit-thread-profile"
+ other.mkdir()
+
+ def unit(results):
+ token = set_hermes_home_override(other) # async units finish on runner threads
+ try:
+ loop.finish_delegation_unit(call, results, background=True)
+ finally:
+ reset_hermes_home_override(token)
+
+ for results in ([{"status": "completed"}], [{"status": "completed"}, {"status": "failed"}]):
+ worker = threading.Thread(target=unit, args=(results,))
+ worker.start()
+ worker.join()
+
+ assert _rows(other, "hermes.delegation.run.count") == []
+ assert _rows(home, "hermes.delegation.run.count") == [(
+ {"depth": "2", "mode": "background", "outcome": "partial", "subagent_count_bucket": "3_to_5"}, 1,
+ )]
+
+
+def test_delegate_task_call_is_one_row_however_many_children(home, monkeypatch):
+ import types
+
+ import tools.delegate_tool as dt
+
+ statuses = iter(["completed", "failed", "completed"])
+ monkeypatch.setattr(dt, "_run_single_child", lambda task_index, goal, child=None, parent_agent=None, **kw: {
+ "task_index": task_index, "status": next(statuses), "summary": "ok", "error": None, "api_calls": 1,
+ "duration_seconds": 1,
+ })
+ monkeypatch.setattr(dt, "_build_child_preserving_parent_tools", lambda **kw: types.SimpleNamespace(tool_progress_callback=None))
+ monkeypatch.setattr(dt, "_resolve_delegation_credentials", lambda *a, **k: {
+ "model": "m", "provider": "openrouter", "base_url": "https://x/v1", "api_key": "k", "api_mode": "chat_completions",
+ })
+ parent = types.SimpleNamespace(
+ session_id="root", model="m", tool_progress_callback=None, _delegate_spinner=None, _safe_print=lambda _l: None,
+ )
+
+ dt.delegate_task(tasks=[{"goal": f"worker task number {i}"} for i in range(3)], parent_agent=parent)
+
+ assert _rows(home, "hermes.delegation.run.count") == [(
+ {"depth": "1", "mode": "foreground", "outcome": "partial", "subagent_count_bucket": "3_to_5"}, 1,
+ )]
+
+
+def test_terminal_calls_count_against_the_configured_backend(home):
+ from tools.terminal_tool import terminal_tool
+
+ assert json.loads(terminal_tool("echo hi"))["exit_code"] == 0
+ assert json.loads(terminal_tool("exit 3"))["exit_code"] == 3 # the command failed, the backend did not
+ terminal_tool("echo control-plane", _host_local=True) # Hermes' own children are not user work
+
+ assert _rows(home, "hermes.execution_backend.count") == [
+ ({"backend": "local", "error_class": "none", "kind": "terminal", "outcome": "success"}, 2),
+ ]
+
+
+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}'
+ loop.record_browser_call(lambda legacy: '{"success": false, "error": "x"}', lambda: "browserbase")
+ with pytest.raises(RuntimeError):
+ loop.record_browser_call(lambda legacy: legacy(_raise), lambda: "some-private-provider")
+
+ rows = sorted((d["backend"], d["outcome"], d["error_class"]) for d, _ in _rows(home, "hermes.execution_backend.count"))
+ assert rows == [
+ ("browserbase", "success", "none"), ("extension", "failed", "tool_error"), ("other", "failed", "exception"),
+ ]
+
+
+def test_browser_tool_backend_is_resolved_from_the_profile_at_call_time(home, monkeypatch):
+ import tools.browser_tool as bt
+
+ handler = bt._routed_handler("browser_back", lambda args, kw: '{"success": true}')
+ handler({}, task_id="t")
+ monkeypatch.setenv("BROWSER_CDP_URL", "ws://127.0.0.1:9/devtools/browser/x") # `/browser connect` mid-session
+ handler({}, task_id="t")
+
+ rows = sorted((d["backend"], d["outcome"]) for d, _ in _rows(home, "hermes.execution_backend.count"))
+ assert rows == [("cdp", "success"), ("local", "success")]
+
+
+def _raise():
+ raise RuntimeError("boom")
diff --git a/tools/browser_tool.py b/tools/browser_tool.py
index f2d99ba953e..f68a62d5c0f 100644
--- a/tools/browser_tool.py
+++ b/tools/browser_tool.py
@@ -23,6 +23,7 @@ from agent.redact import redact_cdp_url
from hermes_constants import get_hermes_home, hermes_home_key
from utils import env_int
from hermes_cli.config import DEFAULT_CONFIG, cfg_get
+from hermes_cli.observability.shared_metrics_loop import record_browser_call
# Env keys re-added to the agent-browser subprocess AFTER credential stripping.
@@ -1348,8 +1349,10 @@ def _routed_check_fn(name: str):
def _routed_handler(name: str, fallback):
def handler(args, **kw):
- return routed_browser_handler(name, args, fallback=lambda: fallback(args, kw),
- task_id=kw.get("task_id"), session_id=kw.get("session_id"))
+ return record_browser_call(lambda legacy: routed_browser_handler(
+ name, args, fallback=lambda: legacy(lambda: fallback(args, kw)),
+ task_id=kw.get("task_id"), session_id=kw.get("session_id"),
+ ), _cloud.browser_backend_name)
return handler
diff --git a/tools/browser_tool_cloud.py b/tools/browser_tool_cloud.py
index d2ca2e46c59..b18d327e7fc 100644
--- a/tools/browser_tool_cloud.py
+++ b/tools/browser_tool_cloud.py
@@ -183,6 +183,20 @@ def _is_local_backend() -> bool:
return terminal_env("TERMINAL_ENV", "local").strip().lower() in ("local", "")
+def browser_backend_name() -> str:
+ """Shared-metrics label for the backend legacy browser calls use in the active profile, in session-creation
+ precedence (CDP override > Camofox > cloud provider > local engine). Config reads only, no network I/O."""
+ _bt = _origin()
+ if _cdp._get_cdp_override_raw():
+ return "cdp"
+ if _bt._is_camofox_mode():
+ return "camofox"
+ provider = _get_cloud_provider()
+ if provider is not None:
+ return str(getattr(provider, "name", "") or "other")
+ return "lightpanda" if _get_browser_engine() == "lightpanda" else "local"
+
+
def _get_browser_engine() -> str:
"""Return the browser engine: ``auto`` (no ``--engine`` flag), ``lightpanda`` or ``chrome``.
diff --git a/tools/code_execution_tool.py b/tools/code_execution_tool.py
index 94195404ab6..45b9d658e46 100644
--- a/tools/code_execution_tool.py
+++ b/tools/code_execution_tool.py
@@ -779,22 +779,23 @@ def execute_code(
if _guard.get("user_approved"):
from tools.interrupt import clear_current_thread_interrupt
clear_current_thread_interrupt()
+ from hermes_cli.observability.shared_metrics_loop import record_execution_backend
if env_type != "local":
- return _execute_remote(code, task_id, enabled_tools, reset=bool(reset))
+ return record_execution_backend("code", "remote", _execute_remote(code, task_id, enabled_tools, reset=bool(reset)))
from tools.interrupt import is_interrupted as _is_interrupted
# Session kernels are always on locally (one interpreter per conversation); the guards above
# already ran for this cell, and the kernel path shares env builder, RPC server and redaction.
from tools.code_kernel import execute_in_session_kernel
_cfg = _load_config()
_mode = _get_execution_mode()
- return execute_in_session_kernel(
+ return record_execution_backend("code", "local", execute_in_session_kernel(
code, task_id=task_id or "", mode=_mode, child_python=_resolve_child_python(_mode),
child_cwd=_resolve_child_cwd(_mode, "", task_id=task_id or ""),
sandbox_tools=frozenset(_sandbox_tools_for(enabled_tools)),
timeout=_cfg.get("timeout", DEFAULT_TIMEOUT),
max_tool_calls=_cfg.get("max_tool_calls", DEFAULT_MAX_TOOL_CALLS),
reset=bool(reset), is_interrupted=_is_interrupted,
- )
+ ))
def _kill_process_group(proc, escalate: bool = False):
diff --git a/tools/delegate_tool_dispatch.py b/tools/delegate_tool_dispatch.py
index f836cfd6b03..2d23e039199 100644
--- a/tools/delegate_tool_dispatch.py
+++ b/tools/delegate_tool_dispatch.py
@@ -13,6 +13,7 @@ from concurrent.futures import FIRST_COMPLETED, wait as _cf_wait
from dataclasses import dataclass, replace
from typing import Any, Dict, List, Optional
+from hermes_cli.observability.shared_metrics_loop import begin_delegation_run, finish_delegation_unit
from tools.async_delegation import _new_delegation_id, record_unit_child
from tools.delegate_tool_child_run import _attach_child, _detach_child, _fabricated_entry, _signal_child_stop
from tools.delegate_tool_progress import (
@@ -202,6 +203,7 @@ def _execute_and_aggregate(batch: _Batch, *, honor_parent_interrupt: bool = True
if _idx < len(batch.live_paths):
entry["live_transcript"] = batch.live_paths[_idx]
update_manifest_statuses(batch.live_deleg_id, results)
+ finish_delegation_unit(batch.task_list, results, background=not honor_parent_interrupt)
combined: Dict[str, Any] = {"results": results, "total_duration_seconds": total_duration}
# Runtime truth about children's background processes, as prose the parent can't miss inside the JSON.
@@ -465,6 +467,10 @@ def _dispatch_background(batch: _Batch) -> str:
def _run_batch(batch: _Batch, background: bool) -> str:
"""Tool result JSON: a dispatch handle (background) or the joined combined results."""
+ # Every unit of this call shares task_list, so its last joined unit emits the call's one row.
+ begin_delegation_run(
+ batch.task_list, subagents=len(batch.children), depth=getattr(batch.parent_agent, "_delegate_depth", 0) + 1,
+ )
if background:
return _dispatch_background(batch)
return json.dumps(_execute_and_aggregate(batch), ensure_ascii=False)
diff --git a/tools/memory_tool.py b/tools/memory_tool.py
index 2047560f4e6..a27d8cfc457 100644
--- a/tools/memory_tool.py
+++ b/tools/memory_tool.py
@@ -213,32 +213,44 @@ def memory_tool(action: str = None, target: str = "memory", content: str = None,
whole matched entry is overwritten; old_text only locates it)."""
if store is None:
return tool_error("Memory is not available. It may be disabled in config or this environment.", success=False)
+ outcome, result = _memory_tool(action, target, content, old_text, new_text, operations, store)
+ from hermes_cli.observability.shared_metrics_loop import record_builtin_memory_call
+ record_builtin_memory_call(action, operations, outcome=outcome)
+ return result
+
+
+def _applied(result: Dict[str, Any]) -> Tuple[str, str]:
+ return ("success" if result.get("success") else "failed"), json.dumps(result, ensure_ascii=False)
+
+
+def _memory_tool(action, target, content, old_text, new_text, operations, store) -> Tuple[str, str]:
+ """``(outcome, result_json)``: ``rejected`` when refused or held before touching the store."""
if content is None and new_text is not None:
content = new_text
# Strict providers send JSON null for optional fields; treat as omitted.
target = "memory" if target is None else target
target_error = _memory_target_error(store, target)
if target_error is not None:
- return json.dumps(target_error)
+ return "rejected", json.dumps(target_error)
if operations:
if not isinstance(operations, list):
- return tool_error("operations must be a list of {action, content?, old_text?} objects.", success=False)
+ return "rejected", tool_error("operations must be a list of {action, content?, old_text?} objects.", success=False)
denied = _background_delete_gate(store, action, operations, target)
if denied is not None:
- return denied
+ return "rejected", denied
# Approval gate: stages (background/gateway) or prompts inline (CLI); off by default.
gate_result = _apply_write_gate(store, "batch", target, None, None, operations)
if gate_result is not None:
- return gate_result
- return json.dumps(store.apply_batch(target, operations), ensure_ascii=False)
+ return "rejected", gate_result
+ return _applied(store.apply_batch(target, operations))
if action not in _STORE_ACTIONS:
- return tool_error(f"Unknown action '{action}'. Use: add, replace, remove", success=False)
+ return "rejected", tool_error(f"Unknown action '{action}'. Use: add, replace, remove", success=False)
invalid = (_validate_single_op(store, action, target, content, old_text)
or _background_delete_gate(store, action, None, target, content, old_text)
or _apply_write_gate(store, action, target, content, old_text))
if invalid is not None:
- return invalid
- return json.dumps(_STORE_ACTIONS[action][0](store, target, content, old_text), ensure_ascii=False)
+ return "rejected", invalid
+ return _applied(_STORE_ACTIONS[action][0](store, target, content, old_text))
def get_builtin_memory_config(config: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
diff --git a/tools/terminal_tool.py b/tools/terminal_tool.py
index 0ba5010ea60..6e195ab5eda 100644
--- a/tools/terminal_tool.py
+++ b/tools/terminal_tool.py
@@ -1394,6 +1394,8 @@ def terminal_tool(
``_host_local`` forces the local backend for Hermes-owned control-plane
children (kept in a separate env cache from the configured backend).
"""
+ from hermes_cli.observability.shared_metrics_loop import record_terminal_backend as _metered
+ plan = None
try:
plan = _plan_execution(
command, task_id=task_id, timeout=timeout, background=background, _host_local=_host_local,
@@ -1462,18 +1464,18 @@ def terminal_tool(
)
if plan.promoted_from_foreground_timeout is not None:
result = _with_promoted_note(result, plan.promoted_from_foreground_timeout)
- return result
- return _run_foreground(
+ return _metered(None if _host_local else plan, result)
+ return _metered(None if _host_local else plan, _run_foreground(
command, env, plan,
task_id=task_id, session_id=session_id, session_key=session_key,
workdir=workdir, approval_note=verdict.note, clear_interrupt=verdict.approved_run,
- )
+ ))
except _Rejected as r:
return r.result_json
except EnvironmentConnectionError as e:
- return _degraded_result(e, task_id)
+ return _metered(None if _host_local else plan, _degraded_result(e, task_id), error_class="tool_error")
except Exception as e:
- return _fatal_error_json(e)
+ return _metered(None if _host_local else plan, _fatal_error_json(e), error_class="exception")
def check_terminal_requirements() -> bool: