Skip to content

The agent that grows with you

fix(telemetry): one-shot CLI runs report entrypoint one_shot, not interactive

teknium14b2c2ae999b8
diff --git a/hermes_cli/main.py b/hermes_cli/main.py
index 6e2d6269307..b8e132e7d59 100644
--- a/hermes_cli/main.py
+++ b/hermes_cli/main.py
@@ -105,6 +105,8 @@ _ONESHOT_CLEANUPS = (
("tools.browser_tool_lifecycle", "_emergency_cleanup_all_sessions", {}, Exception),
("tools.mcp_tool_lifecycle", "shutdown_mcp_servers", {}, BaseException),
("agent.auxiliary_client", "shutdown_cached_clients", {}, Exception),
+ # The atexit hook that closes the metrics session never runs past os._exit.
+ ("hermes_cli.observability.relay_shared_metrics", "shutdown_runtimes", {}, Exception),
)
diff --git a/hermes_cli/observability/relay_shared_metrics.py b/hermes_cli/observability/relay_shared_metrics.py
index aabfc670ef8..ab802a0c5bd 100644
--- a/hermes_cli/observability/relay_shared_metrics.py
+++ b/hermes_cli/observability/relay_shared_metrics.py
@@ -72,6 +72,29 @@ def _task_parent_handle(session: _MetricsSession, task_id: str) -> Any:
return session.relay_session.handle
+# Session sources a Hermes dispatcher stamps on the finite CLI child it spawns: a kanban worker
+# (``kanban_db_dispatch``) and an A2A forward (``--source a2a``). Nobody is at either keyboard.
+_DISPATCHED_SOURCES = frozenset({"a2a", "kanban"})
+
+
+def _with_launch_entrypoint(event: dict[str, Any]) -> dict[str, Any]:
+ """Declare the entrypoint of a finite CLI run (``hermes -z``, ``chat -q`` off a TTY, ``-Q``): the
+ ``HERMES_SINGLE_QUERY_SESSION`` marker those paths set (the same one ``cache_ttl: auto`` and the session
+ source read). ``background`` for a dispatcher-spawned child, else ``one_shot``; the REPL, other surfaces,
+ delegated children and an already-declared entrypoint are untouched."""
+ if (event.get("entrypoint") or event.get("parent_task_id") or event.get("parent_session_id")
+ or contract.execution_surface(event) != "cli"):
+ return event
+ from agent.oneshot_footprint import is_single_query_session
+
+ if not is_single_query_session():
+ return event
+ from gateway.session_context import get_session_env
+
+ source = str(get_session_env("HERMES_SESSION_SOURCE", "") or "").strip().lower()
+ return {**event, "entrypoint": "background" if source in _DISPATCHED_SOURCES else "one_shot"}
+
+
def _elapsed_ms(started_ns: int) -> int:
return max(0, (monotonic_ns() - started_ns) // 1_000_000)
@@ -324,7 +347,7 @@ class _Runtime:
return None
self._emit_client_active(session)
task_context = session.relay_session.context.copy()
- start_fields = contract.task_start_fields(event)
+ start_fields = contract.task_start_fields(_with_launch_entrypoint(event))
handle = task_context.run(
self._with_scope_stack, self.relay.scope.push,
TASK_SCOPE, self.relay.ScopeType.Function,
@@ -1407,6 +1430,16 @@ def start_task_run(
)
+def shutdown_runtimes() -> None:
+ """Run each live runtime's exit flush now, for a process that leaves through ``os._exit`` (the
+ ``hermes -z`` exit) and so never reaches the atexit hook that closes sessions and writes
+ ``task_run.finished`` / ``session.count``."""
+ with _RUNTIME_LOCK:
+ runtimes = [runtime for runtime in _RUNTIMES.values() if isinstance(runtime, _Runtime)]
+ for runtime in runtimes:
+ runtime._safe(runtime.shutdown)
+
+
def close_session_run(session_id: str) -> None:
"""Emit the summary of a session a surface retired without a finalize hook (gateway
auto-reset, idle expiry). Never creates a runtime; unknown ids are a no-op."""
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 ab1d04383eb..4a20a2567f0 100644
--- a/hermes_cli/observability/schemas/hermes.shared_metrics.v3.schema.json
+++ b/hermes_cli/observability/schemas/hermes.shared_metrics.v3.schema.json
@@ -699,6 +699,7 @@
"delegated",
"gateway_message",
"interactive",
+ "one_shot",
"other",
"python",
"scheduled_task",
diff --git a/hermes_cli/observability/shared_metrics_contract.py b/hermes_cli/observability/shared_metrics_contract.py
index 59324f57f4a..08d739e4a07 100644
--- a/hermes_cli/observability/shared_metrics_contract.py
+++ b/hermes_cli/observability/shared_metrics_contract.py
@@ -105,9 +105,11 @@ TASK_END_REASONS = frozenset({
"system_aborted", "timed_out", "unknown", "user_cancelled",
})
TASK_TERMINATIONS = frozenset({"none", "system_aborted", "timed_out", "unknown", "user_cancelled"})
+# ``one_shot``: a finite CLI run (``hermes -z``, ``hermes chat -q`` off a TTY, ``-Q``, ``--oneshot``) that
+# answers one prompt and exits — a person's shell line or their script, never the REPL.
TASK_ENTRYPOINTS = frozenset({
- "api", "background", "batch", "delegated", "gateway_message", "interactive", "other", "python",
- "scheduled_task", "unknown",
+ "api", "background", "batch", "delegated", "gateway_message", "interactive", "one_shot", "other",
+ "python", "scheduled_task", "unknown",
})
DURATION_BUCKETS = frozenset({
"1s_to_5s", "2m_to_10m", "30s_to_2m", "5s_to_30s", "gte_10m", "lt_1s",
diff --git a/hermes_cli/observability/shared_metrics_engagement.py b/hermes_cli/observability/shared_metrics_engagement.py
index 50765effbad..25671fa2b29 100644
--- a/hermes_cli/observability/shared_metrics_engagement.py
+++ b/hermes_cli/observability/shared_metrics_engagement.py
@@ -44,7 +44,9 @@ _ACTIVE_THRESHOLDS = (
_SWITCH_THRESHOLDS = ((2, "1"), (4, "2_to_3"), (11, "4_to_10"), (31, "11_to_30"))
# Task entrypoints that are a person using Hermes. Unattended cron runs (counted by hermes.cron.run),
# delegated children, background review forks, batch and API/python embedding are not engagement.
-_ENGAGED_ENTRYPOINTS = frozenset({"gateway_message", "interactive"})
+# ``one_shot`` keeps the treatment it had while it read ``interactive``: a person typing ``hermes -z`` and a
+# script looping it look the same from inside the process; the label lets the rollup split them instead.
+_ENGAGED_ENTRYPOINTS = frozenset({"gateway_message", "interactive", "one_shot"})
_INTERACTION_METRICS = frozenset({contract.TASK_STARTED_METRIC, contract.TASK_FINISHED_METRIC})
_ALL = "*"
diff --git a/scripts/smoke_nemo_relay_shared_metrics.py b/scripts/smoke_nemo_relay_shared_metrics.py
index 80ee2f2ae8d..5891f3545c8 100644
--- a/scripts/smoke_nemo_relay_shared_metrics.py
+++ b/scripts/smoke_nemo_relay_shared_metrics.py
@@ -382,7 +382,7 @@ def _validate_store(database_path: Path) -> list[dict[str, Any]]:
expected_start = {
"name": "hermes.task_run.started",
"dimensions": {
- "entrypoint": "interactive",
+ "entrypoint": "one_shot",
"execution_surface": "cli",
"platform": "none",
},
@@ -396,7 +396,7 @@ def _validate_store(database_path: Path) -> list[dict[str, Any]]:
[terminal] = by_name["hermes.task_run.finished"]
expected_terminal_dimensions = {
"end_reason": "completed",
- "entrypoint": "interactive",
+ "entrypoint": "one_shot",
"execution_surface": "cli",
"failure_class": "none",
"outcome": "success",
@@ -603,7 +603,7 @@ def _validate_packages(
[terminal] = metrics["hermes.task_run.finished"]
if terminal["dimensions"] != {
"end_reason": "completed",
- "entrypoint": "interactive",
+ "entrypoint": "one_shot",
"execution_surface": "cli",
"failure_class": "none",
"outcome": "success",
diff --git a/tests/hermes_cli/test_relay_shared_metrics_runtime.py b/tests/hermes_cli/test_relay_shared_metrics_runtime.py
index d458f9293f0..46001567511 100644
--- a/tests/hermes_cli/test_relay_shared_metrics_runtime.py
+++ b/tests/hermes_cli/test_relay_shared_metrics_runtime.py
@@ -2998,3 +2998,58 @@ def test_recovered_rows_report_saved_only_once_the_store_holds_them(real_binding
assert relay_shared_metrics.record_process_marks_saved([row]) == 1
saved = [(r["metric_name"], r["dimensions"], r["value"]) for r in SharedMetricsStore().counter_snapshot()]
assert saved == [("hermes.process.exit", row[1], 1)]
+
+
+def _cli_turn(session_id: str, parent_session_id: str = "") -> None:
+ hook = dict(session_id=session_id, task_id=f"{session_id}-t", platform="cli")
+ lifecycle.invoke_hook("pre_llm_call", **hook, parent_session_id=parent_session_id)
+ relay_shared_metrics.finish_task_run(**hook, result={"completed": True})
+
+
+def test_finite_cli_runs_report_their_own_entrypoint(direct_runtime, tmp_path, monkeypatch):
+ """`hermes -z` / `chat -q` / `-Q` runs (HERMES_SINGLE_QUERY_SESSION) report `one_shot`, a
+ dispatcher-spawned one (kanban worker, A2A forward) `background`; the REPL stays `interactive`,
+ and a delegated child or a non-CLI surface keeps its own entrypoint inside a finite run."""
+ monkeypatch.delenv("HERMES_SINGLE_QUERY_SESSION", raising=False)
+ monkeypatch.delenv("HERMES_SESSION_SOURCE", raising=False)
+ _cli_turn("repl")
+ monkeypatch.setenv("HERMES_SINGLE_QUERY_SESSION", "1")
+ _cli_turn("oneshot")
+ _cli_turn("child", parent_session_id="oneshot")
+ _finish_desktop_task("desktop", "desktop-t")
+ monkeypatch.setenv("HERMES_SESSION_SOURCE", "kanban")
+ _cli_turn("kanban")
+ for session_id in ("repl", "oneshot", "child", "desktop", "kanban"):
+ lifecycle.finalize_session(session_id=session_id)
+ _join_export_workers()
+
+ started = sorted((d["entrypoint"], d["execution_surface"], v)
+ for d, v in _stored_values(tmp_path, "hermes.task_run.started"))
+ assert started == [
+ ("background", "cli", 1), ("delegated", "cli", 1), ("interactive", "cli", 1),
+ ("interactive", "desktop", 1), ("one_shot", "cli", 1),
+ ]
+ finished = {d["entrypoint"] for d, _ in _stored_values(tmp_path, "hermes.task_run.finished")}
+ assert finished == {"background", "delegated", "interactive", "one_shot"}
+ # Delegated children are not sessions of their own.
+ sessions = sorted((d["entrypoint"], d["execution_surface"], d["turn_count_bucket"])
+ for d, _ in _stored_values(tmp_path, "hermes.session.count"))
+ assert sessions == [
+ ("background", "cli", "1"), ("interactive", "cli", "1"), ("interactive", "desktop", "1"),
+ ("one_shot", "cli", "1"),
+ ]
+
+
+def test_oneshot_hard_exit_cleanup_records_the_session_summary(direct_runtime, tmp_path, monkeypatch):
+ """`hermes -z` leaves through os._exit, past the atexit hook that closes the metrics session; its
+ pre-exit cleanup must write the run's session.count itself."""
+ from hermes_cli import main as hermes_main
+
+ monkeypatch.setenv("HERMES_SINGLE_QUERY_SESSION", "1")
+ monkeypatch.setattr(hermes_main, "_oneshot_cleanup_done", False)
+ _cli_turn("z-run")
+ hermes_main._cleanup_oneshot_runtime()
+ _join_export_workers()
+
+ sessions = _stored_values(tmp_path, "hermes.session.count")
+ assert [(d["entrypoint"], d["turn_count_bucket"], v) for d, v in sessions] == [("one_shot", "1", 1)]
diff --git a/website/docs/developer-guide/relay-shared-metrics.md b/website/docs/developer-guide/relay-shared-metrics.md
index 2ae7663db81..5a711ef8205 100644
--- a/website/docs/developer-guide/relay-shared-metrics.md
+++ b/website/docs/developer-guide/relay-shared-metrics.md
@@ -218,6 +218,29 @@ boundary closes the task for normal returns, early returns, exceptions, and
cancellations. Active task ownership follows the task ID if Hermes rotates its
conversation session during context compression.
+The `entrypoint` dimension (on `hermes.task_run.started`, `hermes.task_run.finished`
+and `hermes.session.count`) says who dispatched the run, from a closed set:
+
+| Value | Meaning |
+|---|---|
+| `interactive` | A person in a chat UI: the `hermes` REPL, a `hermes chat -q` that seeds the REPL on a TTY, `--tui`, Desktop, ACP editors. |
+| `one_shot` | A finite CLI run that answers one prompt and exits: `hermes -z` / `--oneshot`, `hermes chat -q` off a TTY or with `--oneshot`, `-Q` / `--quiet`. A person's shell line and a script looping it look the same, so both read `one_shot`. Bot Chat delivery turns (`hermes -p <profile> chat -c "Bot Chat" -Q`) are one-shot runs too: their author may be a person on another connection. Surface stays `cli`. |
+| `background` | An unattended run a Hermes dispatcher spawned: a kanban worker (`HERMES_SESSION_SOURCE=kanban`) or an A2A forward (`--source a2a`). |
+| `delegated` | A subagent run under a parent task or session (wins over the values above). |
+| `gateway_message` | A messaging-platform message. |
+| `scheduled_task`, `batch`, `api`, `python` | Cron, batch runner, API server, Python embedding. |
+| `other`, `unknown` | Unattributable. |
+
+A run is `one_shot` or `background` when its process carries the
+`HERMES_SINGLE_QUERY_SESSION` marker that the one-shot paths set (the same marker the
+session source and `cache_ttl: auto` read). Engagement (`hermes.engagement.*`) and the
+attended-only rows (task cost, tool usage per session, model friction) treat `one_shot`
+like `interactive`, as they did before the value existed; `background` and `delegated`
+runs are unattended and excluded there. Packages written before `one_shot` existed
+carry these runs as `interactive` and still validate. `hermes -z` leaves through
+`os._exit`, so it closes its metrics session before exiting rather than relying on the
+atexit hook.
+
Each tool invocation is represented by a Relay tool lifecycle named
`hermes.tool_call`. The terminal counter contains only bounded tool category,
outcome and approval outcome; the same event feeds `hermes.tool_call.latency`