Skip to content

The agent that grows with you

feat(telemetry): decision-data metrics core: sessions, milestones, tokens, TTFT, snapshot fields, event API

teknium126e7a9ac35a3
diff --git a/hermes_cli/observability/relay_shared_metrics.py b/hermes_cli/observability/relay_shared_metrics.py
index 257462cfc2e..9a75251e230 100644
--- a/hermes_cli/observability/relay_shared_metrics.py
+++ b/hermes_cli/observability/relay_shared_metrics.py
@@ -17,6 +17,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 .shared_metrics_contract import MODEL_CALL_SCOPE, SUBSCRIBER_NAME, TASK_SCOPE
from .shared_metrics_subscriber import SharedMetricsSubscriber
@@ -106,6 +107,7 @@ class _ModelCall:
task_id: str
fields: dict[str, str]
error_class: str = "none"
+ ttft_bucket: str = "unknown"
@dataclass
@@ -143,6 +145,13 @@ class _MetricsSession:
tasks: dict[str, _TaskRun] = field(default_factory=dict)
tool_calls: dict[tuple[str, str, str, str], _ToolCall] = field(default_factory=dict)
retired_turn_ids: deque[str] = field(default_factory=lambda: deque(maxlen=256))
+ # Session-level aggregation, emitted once as hermes.session.count when the session closes.
+ start_fields: dict[str, str] | None = None
+ turns: int = 0
+ failed_turns: int = 0
+ last_outcome: str = "unknown"
+ first_turn_ns: int = 0
+ last_turn_ns: int = 0
class _Runtime:
@@ -342,7 +351,16 @@ class _Runtime:
return
model_call.fields = contract.model_call_fields(event)
if finish:
+ model_call.ttft_bucket = fields_.ttft_bucket(event)
self._finish_model_call(session, model_call_key, "success")
+ tokens = fields_.model_token_fields(
+ event.get("usage"), call_role="primary", **model_call.fields
+ )
+ if tokens is not None:
+ self._guarded(
+ "Hermes shared-metrics token mark failed", self._mark,
+ session, session.tasks.get(model_call.task_id), contract.MODEL_TOKENS_MARK, tokens,
+ )
else:
model_call.error_class = contract.model_error_class(event)
@@ -472,6 +490,7 @@ class _Runtime:
session, {**event, **_ABORTED, "completed": False, "interrupted": False}
):
return
+ self._emit_session_summary(session)
try:
self.relay.subscribers.flush()
except Exception as exc:
@@ -725,7 +744,8 @@ class _Runtime:
if outcome == "failed" and error_class == "none":
error_class = "unknown"
fields = contract.model_route_fields(
- model_call.fields, call_role="primary", outcome=outcome, error_class=error_class
+ model_call.fields, call_role="primary", outcome=outcome, error_class=error_class,
+ ttft_bucket=model_call.ttft_bucket,
)
self._guarded(
"Hermes shared-metrics model call close failed",
@@ -769,6 +789,7 @@ class _Runtime:
tool_call_count=len(task.tool_call_ids) + task.unidentified_tool_calls,
retry_count=task.retry_count,
)
+ self._count_session_turn(session, task, fields["outcome"])
try:
popped = self._guarded(
"Hermes shared-metrics task close failed",
@@ -786,6 +807,47 @@ class _Runtime:
_forget(self._turn_sessions, (session.session_id, turn_id), session)
return True
+ @staticmethod
+ def _count_session_turn(session: _MetricsSession, task: _TaskRun, outcome: str) -> None:
+ if session.start_fields is None:
+ session.start_fields = dict(task.start_fields)
+ session.first_turn_ns = task.started_ns
+ session.turns += 1
+ session.failed_turns += outcome == "failed"
+ session.last_outcome = outcome
+ session.last_turn_ns = monotonic_ns()
+
+ 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
+ summary = fields_.session_fields(
+ start, turns=session.turns, failed_turns=session.failed_turns,
+ last_outcome=session.last_outcome,
+ active_ms=max(0, session.last_turn_ns - session.first_turn_ns) // 1_000_000,
+ )
+ self._guarded(
+ "Hermes shared-metrics session summary failed", self._mark,
+ session, None, contract.SESSION_MARK, summary,
+ )
+
+ def record_process_mark(self, mark: str, data: dict[str, Any]) -> None:
+ """A process-level fact with no owning task (setup, installs, commands, switches)."""
+ # No flush here: the next task close or the atexit shutdown drains the subscriber.
+ self._with_scope_stack(self.relay.scope.event, mark, data=data, metadata=self._event_metadata())
+
+ def record_auxiliary_tokens(self, event: dict[str, Any]) -> None:
+ tokens = fields_.model_token_fields(
+ event.get("usage"), call_role="auxiliary", aux_task=event.get("aux_task"),
+ model=event.get("response_model") or event.get("model"), provider=event.get("provider"),
+ )
+ if tokens is not None:
+ self._with_scope_stack(
+ self.relay.scope.event, contract.MODEL_TOKENS_MARK, data=tokens,
+ metadata=self._event_metadata(),
+ )
+
def _export(self) -> None:
exported = self._safe(self.subscriber.store.create_and_export_package_if_due)
# Sending must never delay the caller: _export runs on finish_task, the user's
@@ -975,6 +1037,7 @@ _HOOK_HANDLERS: dict[str, Callable[[_Runtime, dict[str, Any]], Any]] = {
"post_approval_response": lambda rt, kw: rt.record_approval(kw),
"on_skill_lifecycle": lambda rt, kw: rt.record_skill_lifecycle(kw),
"post_api_request": lambda rt, kw: rt.update_model_call(kw, finish=True),
+ "post_auxiliary_call": lambda rt, kw: rt.record_auxiliary_tokens(kw),
"api_request_error": lambda rt, kw: rt.update_model_call(kw, finish=False),
"on_session_end": lambda rt, kw: rt.finish_task(kw),
"subagent_stop": _close_child_session,
@@ -1012,6 +1075,15 @@ def finish_task_run(
)
+def record_process_mark(mark: str, data: dict[str, Any]) -> None:
+ """Emit one process-level decision mark when shared metrics are on (never raises)."""
+ if not enabled() or not relay_runtime.relay_instrumentation_enabled():
+ return
+ runtime = _get_runtime(retry_failed=True)
+ if runtime is not None:
+ runtime._safe(runtime.record_process_mark, mark, data)
+
+
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 bf88950d0e6..f2e8ded8734 100644
--- a/hermes_cli/observability/schemas/hermes.shared_metrics.v3.schema.json
+++ b/hermes_cli/observability/schemas/hermes.shared_metrics.v3.schema.json
@@ -123,6 +123,33 @@
},
{
"$ref": "#/$defs/install_snapshot_counter"
+ },
+ {
+ "$ref": "#/$defs/session_counter"
+ },
+ {
+ "$ref": "#/$defs/install_milestone_counter"
+ },
+ {
+ "$ref": "#/$defs/setup_completed_counter"
+ },
+ {
+ "$ref": "#/$defs/model_tokens_sum"
+ },
+ {
+ "$ref": "#/$defs/compression_counter"
+ },
+ {
+ "$ref": "#/$defs/model_switch_counter"
+ },
+ {
+ "$ref": "#/$defs/fallback_counter"
+ },
+ {
+ "$ref": "#/$defs/slash_command_counter"
+ },
+ {
+ "$ref": "#/$defs/extension_install_counter"
}
]
}
@@ -296,6 +323,18 @@
"failed",
"success"
]
+ },
+ "ttft_bucket": {
+ "enum": [
+ "1s_to_2s",
+ "2s_to_5s",
+ "500ms_to_1s",
+ "5s_to_15s",
+ "gte_15s",
+ "lt_500ms",
+ "not_streamed",
+ "unknown"
+ ]
}
},
"dependentRequired": {
@@ -315,7 +354,7 @@
"outcome"
]
},
- "description": "v3 rows carry call_role/error_class/outcome; rows counted by an older build carry only model/provider."
+ "description": "v3 rows carry call_role/error_class/outcome (and ttft_bucket from the decision-data build); rows counted by an older build carry only model/provider."
},
"value": {
"type": "integer",
@@ -760,8 +799,12 @@
},
"use_count_bucket": {
"$ref": "#/$defs/count_bucket"
+ },
+ "skill_name": {
+ "$ref": "#/$defs/catalog_identifier"
}
- }
+ },
+ "description": "skill_name is a bundled/optional skill name or 'custom'; absent on rows counted before it existed."
},
"value": {
"type": "integer",
@@ -900,6 +943,170 @@
},
"skill_count_bucket": {
"$ref": "#/$defs/size_bucket"
+ },
+ "display_language": {
+ "$ref": "#/$defs/catalog_identifier"
+ },
+ "install_age_bucket": {
+ "$ref": "#/$defs/install_age_bucket"
+ },
+ "main_provider": {
+ "$ref": "#/$defs/provider_identifier"
+ },
+ "messaging_platform_count_bucket": {
+ "$ref": "#/$defs/size_bucket"
+ },
+ "terminal_backend": {
+ "enum": [
+ "daytona",
+ "docker",
+ "local",
+ "modal",
+ "other",
+ "singularity",
+ "ssh"
+ ]
+ }
+ },
+ "description": "The five decision-data fields are absent on snapshots counted before they existed."
+ },
+ "value": {
+ "const": 1
+ }
+ }
+ },
+ "session_duration_bucket": {
+ "enum": [
+ "1m_to_5m",
+ "2h_to_8h",
+ "30m_to_2h",
+ "5m_to_30m",
+ "gte_8h",
+ "lt_1m"
+ ]
+ },
+ "install_age_bucket": {
+ "enum": [
+ "1d_to_7d",
+ "1h_to_1d",
+ "30d_to_90d",
+ "7d_to_30d",
+ "gte_90d",
+ "lt_1h",
+ "unknown"
+ ]
+ },
+ "provider_identifier": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 64,
+ "pattern": "^[a-z0-9][a-z0-9._:/@+\\-]*$"
+ },
+ "session_counter": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "name",
+ "type",
+ "dimensions",
+ "value"
+ ],
+ "properties": {
+ "name": {
+ "const": "hermes.session.count"
+ },
+ "type": {
+ "const": "counter"
+ },
+ "dimensions": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "active_duration_bucket",
+ "entrypoint",
+ "execution_surface",
+ "failed_turn_count_bucket",
+ "last_outcome",
+ "platform",
+ "turn_count_bucket"
+ ],
+ "properties": {
+ "active_duration_bucket": {
+ "$ref": "#/$defs/session_duration_bucket"
+ },
+ "entrypoint": {
+ "$ref": "#/$defs/task_entrypoint"
+ },
+ "execution_surface": {
+ "$ref": "#/$defs/execution_surface"
+ },
+ "failed_turn_count_bucket": {
+ "$ref": "#/$defs/count_bucket"
+ },
+ "last_outcome": {
+ "enum": [
+ "cancelled",
+ "failed",
+ "success",
+ "timed_out",
+ "unknown"
+ ]
+ },
+ "platform": {
+ "$ref": "#/$defs/vocabulary_identifier"
+ },
+ "turn_count_bucket": {
+ "$ref": "#/$defs/size_bucket"
+ }
+ }
+ },
+ "value": {
+ "type": "integer",
+ "minimum": 1
+ }
+ }
+ },
+ "install_milestone_counter": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "name",
+ "type",
+ "dimensions",
+ "value"
+ ],
+ "properties": {
+ "name": {
+ "const": "hermes.install.milestone"
+ },
+ "type": {
+ "const": "counter"
+ },
+ "dimensions": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "install_age_bucket",
+ "milestone"
+ ],
+ "properties": {
+ "install_age_bucket": {
+ "$ref": "#/$defs/install_age_bucket"
+ },
+ "milestone": {
+ "enum": [
+ "first_delegation",
+ "first_gateway_message",
+ "first_long_session",
+ "first_mcp_tool_success",
+ "first_scheduled_task",
+ "first_skill_created",
+ "first_skill_reused",
+ "first_task_started",
+ "first_task_success",
+ "first_tool_success",
+ "setup_completed"
+ ]
}
}
},
@@ -907,6 +1114,356 @@
"const": 1
}
}
+ },
+ "setup_completed_counter": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "name",
+ "type",
+ "dimensions",
+ "value"
+ ],
+ "properties": {
+ "name": {
+ "const": "hermes.setup.completed"
+ },
+ "type": {
+ "const": "counter"
+ },
+ "dimensions": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "provider",
+ "surface"
+ ],
+ "properties": {
+ "provider": {
+ "$ref": "#/$defs/provider_identifier"
+ },
+ "surface": {
+ "enum": [
+ "cli",
+ "desktop",
+ "other"
+ ]
+ }
+ }
+ },
+ "value": {
+ "type": "integer",
+ "minimum": 1
+ }
+ }
+ },
+ "model_tokens_sum": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "name",
+ "type",
+ "dimensions",
+ "value"
+ ],
+ "properties": {
+ "name": {
+ "const": "hermes.model_tokens.sum"
+ },
+ "type": {
+ "const": "counter"
+ },
+ "dimensions": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "aux_task",
+ "call_role",
+ "model",
+ "provider",
+ "token_type"
+ ],
+ "properties": {
+ "aux_task": {
+ "$ref": "#/$defs/vocabulary_identifier"
+ },
+ "call_role": {
+ "enum": [
+ "auxiliary",
+ "primary"
+ ]
+ },
+ "model": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 256,
+ "pattern": "^[a-z0-9][a-z0-9._:/@+\\-]*$"
+ },
+ "provider": {
+ "$ref": "#/$defs/provider_identifier"
+ },
+ "token_type": {
+ "enum": [
+ "cache_read",
+ "cache_write",
+ "input",
+ "output",
+ "reasoning"
+ ]
+ }
+ },
+ "description": "value is the summed token count for the day, not an event count."
+ },
+ "value": {
+ "type": "integer",
+ "minimum": 1
+ }
+ }
+ },
+ "compression_counter": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "name",
+ "type",
+ "dimensions",
+ "value"
+ ],
+ "properties": {
+ "name": {
+ "const": "hermes.compression.count"
+ },
+ "type": {
+ "const": "counter"
+ },
+ "dimensions": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "context_fill_bucket",
+ "outcome",
+ "trigger"
+ ],
+ "properties": {
+ "context_fill_bucket": {
+ "enum": [
+ "50_to_75",
+ "75_to_90",
+ "90_to_100",
+ "gte_100",
+ "lt_50",
+ "unknown"
+ ]
+ },
+ "outcome": {
+ "enum": [
+ "failed",
+ "skipped",
+ "success"
+ ]
+ },
+ "trigger": {
+ "enum": [
+ "auto",
+ "manual",
+ "other",
+ "overflow"
+ ]
+ }
+ }
+ },
+ "value": {
+ "type": "integer",
+ "minimum": 1
+ }
+ }
+ },
+ "model_switch_counter": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "name",
+ "type",
+ "dimensions",
+ "value"
+ ],
+ "properties": {
+ "name": {
+ "const": "hermes.model_switch.count"
+ },
+ "type": {
+ "const": "counter"
+ },
+ "dimensions": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "execution_surface",
+ "from_provider",
+ "to_provider"
+ ],
+ "properties": {
+ "execution_surface": {
+ "$ref": "#/$defs/execution_surface"
+ },
+ "from_provider": {
+ "$ref": "#/$defs/provider_identifier"
+ },
+ "to_provider": {
+ "$ref": "#/$defs/provider_identifier"
+ }
+ }
+ },
+ "value": {
+ "type": "integer",
+ "minimum": 1
+ }
+ }
+ },
+ "fallback_counter": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "name",
+ "type",
+ "dimensions",
+ "value"
+ ],
+ "properties": {
+ "name": {
+ "const": "hermes.fallback.count"
+ },
+ "type": {
+ "const": "counter"
+ },
+ "dimensions": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "error_class",
+ "from_provider",
+ "to_provider"
+ ],
+ "properties": {
+ "error_class": {
+ "$ref": "#/$defs/vocabulary_identifier"
+ },
+ "from_provider": {
+ "$ref": "#/$defs/provider_identifier"
+ },
+ "to_provider": {
+ "$ref": "#/$defs/provider_identifier"
+ }
+ }
+ },
+ "value": {
+ "type": "integer",
+ "minimum": 1
+ }
+ }
+ },
+ "slash_command_counter": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "name",
+ "type",
+ "dimensions",
+ "value"
+ ],
+ "properties": {
+ "name": {
+ "const": "hermes.slash_command.count"
+ },
+ "type": {
+ "const": "counter"
+ },
+ "dimensions": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "command",
+ "execution_surface"
+ ],
+ "properties": {
+ "command": {
+ "$ref": "#/$defs/catalog_identifier"
+ },
+ "execution_surface": {
+ "$ref": "#/$defs/execution_surface"
+ }
+ }
+ },
+ "value": {
+ "type": "integer",
+ "minimum": 1
+ }
+ }
+ },
+ "extension_install_counter": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "name",
+ "type",
+ "dimensions",
+ "value"
+ ],
+ "properties": {
+ "name": {
+ "const": "hermes.extension.install.count"
+ },
+ "type": {
+ "const": "counter"
+ },
+ "dimensions": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": [
+ "kind",
+ "name",
+ "outcome",
+ "source"
+ ],
+ "properties": {
+ "kind": {
+ "enum": [
+ "mcp_server",
+ "plugin",
+ "skill"
+ ]
+ },
+ "name": {
+ "$ref": "#/$defs/catalog_identifier"
+ },
+ "outcome": {
+ "enum": [
+ "failed",
+ "success"
+ ]
+ },
+ "source": {
+ "enum": [
+ "bundled",
+ "catalog",
+ "hub",
+ "local",
+ "other",
+ "url"
+ ]
+ }
+ }
+ },
+ "value": {
+ "type": "integer",
+ "minimum": 1
+ }
+ }
+ },
+ "catalog_identifier": {
+ "type": "string",
+ "pattern": "^[a-z0-9][a-z0-9_.-]{0,63}$",
+ "description": "A public name Nous publishes (slash-command registry, bundled/optional skills, optional-mcps/ and plugin-catalog/ entries, shipped locales), or the placeholder custom/plugin/skill/unknown/other."
}
}
}
diff --git a/hermes_cli/observability/shared_metrics.py b/hermes_cli/observability/shared_metrics.py
index cce1c5c8b20..58bb807a921 100644
--- a/hermes_cli/observability/shared_metrics.py
+++ b/hermes_cli/observability/shared_metrics.py
@@ -20,7 +20,9 @@ from .shared_metrics_contract import (
CLIENT_ACTIVE_METRIC,
COUNTER_METRICS,
INSTALL_SNAPSHOT_METRIC,
+ MILESTONE_METRIC,
MODEL_ROUTE_METRIC,
+ SUM_METRICS,
client_resource_is_valid,
counter_dimensions_are_valid,
)
@@ -33,6 +35,7 @@ _SCHEMA_BUSY_TIMEOUT_MS = 5_000
_LOCAL_HISTORY_RETENTION_DAYS = 30
_ACTIVE_INSTALL_STATE_KEY = "client_active_recorded_at"
_INSTALL_SNAPSHOT_STATE_KEY = "install_snapshot_recorded_at"
+_MILESTONE_STATE_PREFIX = "milestone:"
_ACTIVE_INSTALL_INTERVAL = timedelta(hours=24)
# Column order of the client resource in every counter_aggregates statement.
_RESOURCE_COLUMNS = ("hermes_version", "os_family", "architecture", "install_method")
@@ -116,12 +119,12 @@ _INCREMENT_COUNTER_SQL = """
INSERT INTO counter_aggregates(
period_start, metric_name, hermes_version, os_family, architecture,
install_method, dimensions_json, value, packaged_value
- ) VALUES (?, ?, ?, ?, ?, ?, ?, 1, 0)
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0)
ON CONFLICT(
period_start, metric_name, hermes_version, os_family, architecture,
install_method, dimensions_json
)
- DO UPDATE SET value = value + 1
+ DO UPDATE SET value = value + excluded.value
"""
# (column, declaration) added to package_outbox for transmission bookkeeping.
_SEND_COLUMNS = (
@@ -246,15 +249,45 @@ class SharedMetricsStore:
return True
def record_counter(
- self, metric_name: str, dimensions: dict[str, str], resource: dict[str, str]
+ self, metric_name: str, dimensions: dict[str, str], resource: dict[str, str],
+ amount: int = 1,
) -> None:
- """Increment one allowlisted counter for the current UTC day."""
+ """Add ``amount`` (1 for event counters, a token count for sums) for the current UTC day."""
self._validate_counter(metric_name, dimensions, resource)
+ if isinstance(amount, bool) or not isinstance(amount, int) or amount < 1 or (
+ amount != 1 and metric_name not in SUM_METRICS
+ ):
+ raise ValueError(f"Unsupported amount for shared metric: {metric_name}")
with self._connection() as connection:
self._record_counter_in_transaction(
- connection, metric_name, dimensions, resource, _utc_now().date().isoformat()
+ connection, metric_name, dimensions, resource, _utc_now().date().isoformat(), amount
)
+ def recorded_milestones(self) -> frozenset[str]:
+ with self._connection() as connection:
+ rows = connection.execute(
+ "SELECT key FROM telemetry_state WHERE key LIKE ?", (f"{_MILESTONE_STATE_PREFIX}%",)
+ ).fetchall()
+ return frozenset(row["key"][len(_MILESTONE_STATE_PREFIX):] for row in rows)
+
+ def record_milestone(self, milestone: str, install_age_bucket: str, resource: dict[str, str]) -> bool:
+ """Record an install milestone at most once, ever (compare-and-set across processes)."""
+ dimensions = {"install_age_bucket": install_age_bucket, "milestone": milestone}
+ self._validate_counter(MILESTONE_METRIC, dimensions, resource)
+ now = _utc_now()
+ with self._write() as connection:
+ inserted = connection.execute(
+ "INSERT INTO telemetry_state(key, value) VALUES (?, ?) ON CONFLICT(key) DO NOTHING",
+ (f"{_MILESTONE_STATE_PREFIX}{milestone}", _isoformat(now)),
+ ).rowcount
+ if not inserted:
+ return False
+ self._install_id(connection)
+ self._record_counter_in_transaction(
+ connection, MILESTONE_METRIC, dimensions, resource, now.date().isoformat()
+ )
+ return True
+
@staticmethod
def _validate_counter(
metric_name: str, dimensions: dict[str, str], resource: dict[str, str]
@@ -273,12 +306,13 @@ class SharedMetricsStore:
dimensions: dict[str, str],
resource: dict[str, str],
period_start: str,
+ amount: int = 1,
) -> None:
connection.execute(
_INCREMENT_COUNTER_SQL,
(
period_start, metric_name, *(resource[column] for column in _RESOURCE_COLUMNS),
- _compact_json(dimensions),
+ _compact_json(dimensions), amount,
),
)
diff --git a/hermes_cli/observability/shared_metrics_catalog.py b/hermes_cli/observability/shared_metrics_catalog.py
new file mode 100644
index 00000000000..a8228355c2a
--- /dev/null
+++ b/hermes_cli/observability/shared_metrics_catalog.py
@@ -0,0 +1,147 @@
+"""Public-name catalogs for shared metrics: the only non-enum names a package may carry.
+
+Every set here is something Nous itself publishes (slash-command registry, bundled and optional
+skills, optional-mcps/ and plugin-catalog/ entries, built-in auxiliary tasks, shipped locales).
+A name outside its set is reported as ``custom`` so user-defined identities never leave the machine.
+Loaders are cached: the catalogs only change with the installed Hermes version.
+"""
+
+from __future__ import annotations
+
+import functools
+import logging
+from pathlib import Path
+
+logger = logging.getLogger(__name__)
+
+_REPO_ROOT = Path(__file__).resolve().parents[2]
+
+CUSTOM = "custom"
+
+
+def _skill_dir_names(root: Path) -> frozenset[str]:
+ try:
+ return frozenset(p.parent.name.lower() for p in root.rglob("SKILL.md"))
+ except OSError:
+ return frozenset()
+
+
+def _yaml_stems(root: Path) -> frozenset[str]:
+ try:
+ return frozenset(p.stem.lower() for p in root.glob("*.yaml"))
+ except OSError:
+ return frozenset()
+
+
+def slash_command_names() -> frozenset[str]:
+ from hermes_cli.commands import COMMAND_REGISTRY
+
+ return frozenset(command.name for command in COMMAND_REGISTRY)
+
+
+def bundled_skill_names() -> frozenset[str]:
+ from hermes_constants import get_bundled_skills_dir, get_optional_skills_dir
+
+ return _skill_dir_names(get_bundled_skills_dir(_REPO_ROOT / "skills")) | _skill_dir_names(
+ get_optional_skills_dir(_REPO_ROOT / "optional-skills")
+ )
+
+
+def mcp_catalog_names() -> frozenset[str]:
+ from hermes_constants import get_optional_mcps_dir
+
+ root = get_optional_mcps_dir(_REPO_ROOT / "optional-mcps")
+ try:
+ return frozenset(p.name.lower() for p in root.iterdir() if p.is_dir())
+ except OSError:
+ return frozenset()
+
+
+def plugin_catalog_names() -> frozenset[str]:
+ return _yaml_stems(_REPO_ROOT / "plugin-catalog")
+
+
+def aux_task_names() -> frozenset[str]:
+ from hermes_cli.main_provider_setup import _AUX_TASKS
+
+ return frozenset(key for key, _name, _desc in _AUX_TASKS)
+
+
+def display_languages() -> frozenset[str]:
+ return _yaml_stems(_REPO_ROOT / "locales")
+
+
+def _norm(value: object) -> str:
+ return value.strip().lower() if isinstance(value, str) else ""
+
+
+def _safe(loader) -> frozenset[str]:
+ try:
+ return loader()
+ except Exception:
+ logger.debug("Shared-metrics catalog %s unavailable", loader.__name__, exc_info=True)
+ return frozenset()
+
+
+def slash_command_metric_name(raw: object) -> str:
+ """Canonical registry name for a command or alias; skill and plugin commands stay anonymous."""
+ name = _norm(raw).lstrip("/").split(" ", 1)[0]
+ if not name:
+ return "unknown"
+ try:
+ from hermes_cli.commands import resolve_command
+
+ command = resolve_command(name)
+ except Exception:
+ command = None
+ if command is not None and command.name in _safe(slash_command_names):
+ return command.name
+ try:
+ from agent.skill_commands import resolve_skill_command_key
+
+ if resolve_skill_command_key(name):
+ return "skill"
+ from hermes_cli.plugins import get_plugin_command_handler
+
+ if get_plugin_command_handler(name) is not None:
+ return "plugin"
+ except Exception:
+ pass
+ return "unknown"
+
+
+def skill_metric_name(raw: object) -> str:
+ name = _norm(raw)
+ return name if name in _safe(bundled_skill_names) else CUSTOM
+
+
+_EXTENSION_CATALOGS = {
+ "skill": bundled_skill_names,
+ "mcp_server": mcp_catalog_names,
+ "plugin": plugin_catalog_names,
+}
+
+
+def extension_metric_name(kind: str, raw: object) -> str:
+ """A catalog entry's public name, else ``custom`` (URL/local installs of anything)."""
+ loader = _EXTENSION_CATALOGS.get(kind)
+ name = _norm(raw).rsplit("/", 1)[-1]
+ return name if loader is not None and name in _safe(loader) else CUSTOM
+
+
+def aux_task_metric_name(raw: object) -> str:
+ name = _norm(raw)
+ if not name:
+ return "none"
+ return name if name in _safe(aux_task_names) else "other"
+
+
+def display_language_metric_name(raw: object) -> str:
+ name = _norm(raw) or "en"
+ return name if name in _safe(display_languages) else "other"
diff --git a/hermes_cli/observability/shared_metrics_contract.py b/hermes_cli/observability/shared_metrics_contract.py
index 3e700f39c20..5c334267cd0 100644
--- a/hermes_cli/observability/shared_metrics_contract.py
+++ b/hermes_cli/observability/shared_metrics_contract.py
@@ -26,6 +26,14 @@ TOOL_APPROVAL_MARK = "hermes.tool_approval"
SKILL_LIFECYCLE_MARK = "hermes.skill.lifecycle"
SKILL_LOAD_MARK = "hermes.skill.load"
INSTALL_SNAPSHOT_MARK = "hermes.install.snapshot"
+SESSION_MARK = "hermes.session"
+SETUP_COMPLETED_MARK = "hermes.setup.completed"
+MODEL_TOKENS_MARK = "hermes.model_tokens"
+COMPRESSION_MARK = "hermes.compression"
+MODEL_SWITCH_MARK = "hermes.model_switch"
+FALLBACK_MARK = "hermes.fallback"
+SLASH_COMMAND_MARK = "hermes.slash_command"
+EXTENSION_INSTALL_MARK = "hermes.extension.install"
SUBSCRIBER_NAME = "hermes.nemo_relay.shared_metrics"
CLIENT_ACTIVE_METRIC = "hermes.client.active"
LEGACY_MODEL_CALL_METRIC = "hermes.model_call.count"
@@ -38,6 +46,15 @@ SKILL_LIFECYCLE_METRIC = "hermes.skill.lifecycle.count"
SKILL_LOAD_METRIC = "hermes.skill.load.count"
TOOL_USAGE_METRIC = "hermes.tool.usage.count"
INSTALL_SNAPSHOT_METRIC = "hermes.install.snapshot"
+SESSION_METRIC = "hermes.session.count"
+MILESTONE_METRIC = "hermes.install.milestone"
+SETUP_COMPLETED_METRIC = "hermes.setup.completed"
+MODEL_TOKENS_METRIC = "hermes.model_tokens.sum"
+COMPRESSION_METRIC = "hermes.compression.count"
+MODEL_SWITCH_METRIC = "hermes.model_switch.count"
+FALLBACK_METRIC = "hermes.fallback.count"
+SLASH_COMMAND_METRIC = "hermes.slash_command.count"
+EXTENSION_INSTALL_METRIC = "hermes.extension.install.count"
MODEL_IDENTIFIER_MAX_LENGTH = 256
PROVIDER_IDENTIFIER_MAX_LENGTH = 64
_METRIC_IDENTIFIER_CHARACTERS = frozenset("abcdefghijklmnopqrstuvwxyz0123456789._:/@+-")
@@ -120,6 +137,52 @@ def _bundled_memory_providers() -> frozenset[str]:
MEMORY_PROVIDERS = _bundled_memory_providers() | {"builtin", "plugin"}
+
+class _CatalogValues:
+ """A closed enum backed by a public catalog (see shared_metrics_catalog), loaded on first use."""
+
+ def __init__(self, *loaders: str, extra: frozenset[str]) -> None:
+ self.loaders, self.extra = loaders, extra
+
+ def values(self) -> frozenset[str]:
+ from . import shared_metrics_catalog as catalog
+
+ return self.extra.union(*(catalog._safe(getattr(catalog, name)) for name in self.loaders))
+
+ def __contains__(self, value: object) -> bool:
+ return value in self.extra or value in self.values()
+
+
+# ---- decision-data taxonomies ----------------------------------------------------------------
+SESSION_DURATION_BUCKETS = frozenset({"lt_1m", "1m_to_5m", "5m_to_30m", "30m_to_2h", "2h_to_8h", "gte_8h"})
+INSTALL_AGE_BUCKETS = frozenset({
+ "lt_1h", "1h_to_1d", "1d_to_7d", "7d_to_30d", "30d_to_90d", "gte_90d", "unknown",
+})
+MILESTONES = frozenset({
+ "setup_completed", "first_task_started", "first_task_success", "first_tool_success",
+ "first_gateway_message", "first_scheduled_task", "first_delegation", "first_skill_created",
+ "first_skill_reused", "first_mcp_tool_success", "first_long_session",
+})
+SETUP_SURFACES = frozenset({"cli", "desktop", "other"})
+TOKEN_TYPES = frozenset({"input", "output", "cache_read", "cache_write", "reasoning"})
+TTFT_BUCKETS = frozenset({
+ "lt_500ms", "500ms_to_1s", "1s_to_2s", "2s_to_5s", "5s_to_15s", "gte_15s", "not_streamed", "unknown",
+})
+COMPRESSION_TRIGGERS = frozenset({"auto", "manual", "other", "overflow"})
+COMPRESSION_OUTCOMES = frozenset({"failed", "skipped", "success"})
+CONTEXT_FILL_BUCKETS = frozenset({"lt_50", "50_to_75", "75_to_90", "90_to_100", "gte_100", "unknown"})
+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"})
+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"}))
+EXTENSION_NAMES = _CatalogValues(
+ "bundled_skill_names", "mcp_catalog_names", "plugin_catalog_names", extra=frozenset({"custom"})
+)
+DISPLAY_LANGUAGES = _CatalogValues("display_languages", extra=frozenset({"other"}))
+
_ARCHITECTURE_ALIASES = {
"amd64": "x86_64", "x64": "x86_64", "x86_64": "x86_64",
"aarch64": "arm64", "arm64": "arm64",
@@ -212,6 +275,10 @@ _COUNTER_DIMENSION_VALUES: dict[str, dict[str, frozenset[str]]] = {
"retry_count_bucket": COUNT_BUCKETS, "termination": TASK_TERMINATIONS,
"tool_call_count_bucket": COUNT_BUCKETS,
},
+ MODEL_ROUTE_METRIC: {
+ "call_role": MODEL_CALL_ROLES, "error_class": MODEL_ERROR_CLASSES, "outcome": MODEL_OUTCOMES,
+ "ttft_bucket": TTFT_BUCKETS,
+ },
TOOL_CALL_METRIC: {
"approval_outcome": TOOL_APPROVAL_OUTCOMES, "latency_bucket": TOOL_LATENCY_BUCKETS,
"outcome": TOOL_OUTCOMES, "retry_count_bucket": TOOL_RETRY_BUCKETS,
@@ -227,53 +294,92 @@ _COUNTER_DIMENSION_VALUES: dict[str, dict[str, frozenset[str]]] = {
SKILL_LIFECYCLE_METRIC: {"action": SKILL_LIFECYCLE_ACTIONS, "provenance": SKILL_PROVENANCES},
SKILL_LOAD_METRIC: {
"post_patch_state": SKILL_POST_PATCH_STATES, "provenance": SKILL_PROVENANCES,
- "reuse_state": SKILL_REUSE_STATES, "use_count_bucket": COUNT_BUCKETS,
+ "reuse_state": SKILL_REUSE_STATES, "skill_name": SKILL_NAMES, "use_count_bucket": COUNT_BUCKETS,
},
INSTALL_SNAPSHOT_METRIC: {
- "cron_job_count_bucket": SIZE_BUCKETS, "mcp_server_count_bucket": SIZE_BUCKETS,
- "memory_provider": MEMORY_PROVIDERS, "plugin_count_bucket": SIZE_BUCKETS,
- "profile_count_bucket": SIZE_BUCKETS, "skill_count_bucket": SIZE_BUCKETS,
+ "cron_job_count_bucket": SIZE_BUCKETS, "display_language": DISPLAY_LANGUAGES,
+ "install_age_bucket": INSTALL_AGE_BUCKETS, "mcp_server_count_bucket": SIZE_BUCKETS,
+ "memory_provider": MEMORY_PROVIDERS, "messaging_platform_count_bucket": SIZE_BUCKETS,
+ "plugin_count_bucket": SIZE_BUCKETS, "profile_count_bucket": SIZE_BUCKETS,
+ "skill_count_bucket": SIZE_BUCKETS, "terminal_backend": TERMINAL_BACKENDS,
+ },
+ SESSION_METRIC: {
+ "active_duration_bucket": SESSION_DURATION_BUCKETS, "entrypoint": TASK_ENTRYPOINTS,
+ "execution_surface": EXECUTION_SURFACES, "failed_turn_count_bucket": COUNT_BUCKETS,
+ "last_outcome": TASK_OUTCOMES, "platform": GATEWAY_PLATFORMS, "turn_count_bucket": SIZE_BUCKETS,
+ },
+ MILESTONE_METRIC: {"install_age_bucket": INSTALL_AGE_BUCKETS, "milestone": MILESTONES},
+ SETUP_COMPLETED_METRIC: {"surface": SETUP_SURFACES},
+ MODEL_TOKENS_METRIC: {"aux_task": AUX_TASKS, "call_role": MODEL_CALL_ROLES, "token_type": TOKEN_TYPES},
+ COMPRESSION_METRIC: {
+ "context_fill_bucket": CONTEXT_FILL_BUCKETS, "outcome": COMPRESSION_OUTCOMES,
+ "trigger": COMPRESSION_TRIGGERS,
+ },
+ MODEL_SWITCH_METRIC: {"execution_surface": EXECUTION_SURFACES},
+ FALLBACK_METRIC: {"error_class": MODEL_ERROR_CLASSES},
+ SLASH_COMMAND_METRIC: {"command": SLASH_COMMANDS, "execution_surface": EXECUTION_SURFACES},
+ EXTENSION_INSTALL_METRIC: {
+ "kind": EXTENSION_KINDS, "name": EXTENSION_NAMES, "outcome": EXTENSION_OUTCOMES,
+ "source": EXTENSION_SOURCES,
},
}
_MODEL_ROUTE_MAX_LENGTHS = {
"model": MODEL_IDENTIFIER_MAX_LENGTH, "provider": PROVIDER_IDENTIFIER_MAX_LENGTH,
}
-_MODEL_ROUTE_OUTCOME_VALUES = {
- "call_role": MODEL_CALL_ROLES, "error_class": MODEL_ERROR_CLASSES, "outcome": MODEL_OUTCOMES,
+# metric -> {field: max length} for provider/model identifiers, validated by shape (no catalog).
+_IDENTIFIER_FIELDS: dict[str, dict[str, int]] = {
+ MODEL_ROUTE_METRIC: _MODEL_ROUTE_MAX_LENGTHS,
+ MODEL_TOKENS_METRIC: _MODEL_ROUTE_MAX_LENGTHS,
+ SETUP_COMPLETED_METRIC: {"provider": PROVIDER_IDENTIFIER_MAX_LENGTH},
+ 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},
}
-# metric -> closed dimension field set (model-route identifiers are validated by shape)
+# metric -> closed dimension field set
_METRIC_FIELDS: dict[str, frozenset[str]] = {
- **{name: frozenset(contract) for name, contract in _COUNTER_DIMENSION_VALUES.items()},
- MODEL_ROUTE_METRIC: frozenset(_MODEL_ROUTE_MAX_LENGTHS) | frozenset(_MODEL_ROUTE_OUTCOME_VALUES),
+ name: frozenset(contract) | frozenset(_IDENTIFIER_FIELDS.get(name, ()))
+ for name, contract in _COUNTER_DIMENSION_VALUES.items()
}
# Older field sets still accepted at packaging so counters recorded before an upgrade drain.
-_LEGACY_METRIC_FIELDS: dict[str, frozenset[str]] = {
- MODEL_ROUTE_METRIC: frozenset(_MODEL_ROUTE_MAX_LENGTHS),
- TASK_STARTED_METRIC: _METRIC_FIELDS[TASK_STARTED_METRIC] - {"platform"},
- TASK_FINISHED_METRIC: _METRIC_FIELDS[TASK_FINISHED_METRIC] - {"failure_class", "platform"},
+_LEGACY_METRIC_FIELDS: dict[str, tuple[frozenset[str], ...]] = {
+ MODEL_ROUTE_METRIC: (
+ frozenset(_MODEL_ROUTE_MAX_LENGTHS), _METRIC_FIELDS[MODEL_ROUTE_METRIC] - {"ttft_bucket"},
+ ),
+ TASK_STARTED_METRIC: (_METRIC_FIELDS[TASK_STARTED_METRIC] - {"platform"},),
+ TASK_FINISHED_METRIC: (_METRIC_FIELDS[TASK_FINISHED_METRIC] - {"failure_class", "platform"},),
+ SKILL_LOAD_METRIC: (_METRIC_FIELDS[SKILL_LOAD_METRIC] - {"skill_name"},),
+ INSTALL_SNAPSHOT_METRIC: (_METRIC_FIELDS[INSTALL_SNAPSHOT_METRIC] - {
+ "display_language", "install_age_bucket", "main_provider", "messaging_platform_count_bucket",
+ "terminal_backend",
+ },),
}
COUNTER_METRICS = frozenset(_METRIC_FIELDS) - {LEGACY_MODEL_CALL_METRIC}
+# Counters whose value is a summed quantity rather than an event count.
+SUM_METRICS = frozenset({MODEL_TOKENS_METRIC})
_SKILL_MARK_METRICS = {
SKILL_LIFECYCLE_MARK: SKILL_LIFECYCLE_METRIC, SKILL_LOAD_MARK: SKILL_LOAD_METRIC,
}
+# Marks projected one-to-one onto a counter of the same contract.
+_DECISION_MARK_METRICS = {
+ SESSION_MARK: SESSION_METRIC, SETUP_COMPLETED_MARK: SETUP_COMPLETED_METRIC,
+ COMPRESSION_MARK: COMPRESSION_METRIC, MODEL_SWITCH_MARK: MODEL_SWITCH_METRIC,
+ FALLBACK_MARK: FALLBACK_METRIC, SLASH_COMMAND_MARK: SLASH_COMMAND_METRIC,
+ EXTENSION_INSTALL_MARK: EXTENSION_INSTALL_METRIC,
+}
def counter_dimensions_are_valid(metric_name: str, dimensions: dict[str, Any]) -> bool:
"""Return whether dimensions match one closed shared-metric contract (current or legacy)."""
- fields = set(dimensions)
- if fields != _METRIC_FIELDS.get(metric_name) and fields != _LEGACY_METRIC_FIELDS.get(metric_name):
+ fields = frozenset(dimensions)
+ if fields != _METRIC_FIELDS.get(metric_name) and fields not in _LEGACY_METRIC_FIELDS.get(metric_name, ()):
return False
- if metric_name == MODEL_ROUTE_METRIC:
- return all(
- dimensions[field] == _metric_identifier(dimensions[field], max_length=max_length)
- for field, max_length in _MODEL_ROUTE_MAX_LENGTHS.items()
- ) and all(
- isinstance(dimensions[field], str) and dimensions[field] in _MODEL_ROUTE_OUTCOME_VALUES[field]
- for field in fields & set(_MODEL_ROUTE_OUTCOME_VALUES)
- )
+ identifiers = _IDENTIFIER_FIELDS.get(metric_name, {})
contract = _COUNTER_DIMENSION_VALUES[metric_name]
return all(
- isinstance(dimensions[field], str) and dimensions[field] in contract[field]
+ isinstance(value := dimensions[field], str) and (
+ value == _metric_identifier(value, max_length=identifiers[field]) if field in identifiers
+ else value in contract[field]
+ )
for field in fields
)
@@ -451,6 +557,35 @@ def skill_counter(event: Any) -> tuple[str, dict[str, str]] | None:
return _mark_counter(event, _SKILL_MARK_METRICS)
+def decision_counter(event: Any) -> tuple[str, dict[str, str]] | None:
+ """Return the counter for one session/setup/compression/switch/fallback/command/install mark."""
+ return _mark_counter(event, _DECISION_MARK_METRICS)
+
+
+_TOKEN_MARK_DIMENSIONS = frozenset({"aux_task", "call_role", "model", "provider"})
+
+
+def model_token_counters(event: Any) -> list[tuple[str, dict[str, str], int]]:
+ """Expand one token-usage mark into ``(metric, dimensions, amount)`` sums, one per token type."""
+ if not _valid_shape(event, **_MARK_SHAPE) or _event_text(event, "name") != MODEL_TOKENS_MARK:
+ return []
+ data = getattr(event, "data", None)
+ if not isinstance(data, dict) or set(data) != _TOKEN_MARK_DIMENSIONS | TOKEN_TYPES:
+ return []
+ base = {field: data[field] for field in _TOKEN_MARK_DIMENSIONS}
+ counters = []
+ for token_type in sorted(TOKEN_TYPES):
+ amount = data[token_type]
+ if isinstance(amount, bool) or not isinstance(amount, int) or amount < 0:
+ return []
+ dimensions = {**base, "token_type": token_type}
+ if not counter_dimensions_are_valid(MODEL_TOKENS_METRIC, dimensions):
+ return []
+ if amount:
+ counters.append((MODEL_TOKENS_METRIC, dimensions, amount))
+ return counters
+
+
def skill_lifecycle_fields(kwargs: dict[str, Any]) -> dict[str, str] | None:
"""Build bounded fields for one successful non-load skill transition."""
action = _norm(kwargs.get("action"))
@@ -477,10 +612,17 @@ def skill_load_fields(kwargs: dict[str, Any]) -> dict[str, str] | None:
),
"provenance": skill_provenance(kwargs.get("provenance")),
"reuse_state": "reused" if reused else "first_use",
+ "skill_name": _skill_metric_name(kwargs.get("skill_name")),
"use_count_bucket": count_bucket(use_count),
}
+def _skill_metric_name(value: Any) -> str:
+ from .shared_metrics_catalog import skill_metric_name
+
+ return skill_metric_name(value)
+
+
def skill_provenance(value: Any) -> str:
"""Normalize producer provenance to the closed shared-metrics taxonomy."""
return _allowlisted(_norm(value), SKILL_PROVENANCES)
@@ -787,7 +929,8 @@ def model_call_fields(kwargs: dict[str, Any]) -> dict[str, str]:
def model_route_fields(
- kwargs: dict[str, Any], *, call_role: str, outcome: str, error_class: str
+ kwargs: dict[str, Any], *, call_role: str, outcome: str, error_class: str,
+ ttft_bucket: str = "unknown",
) -> dict[str, str]:
"""The terminal route plus how the logical call ended. ``error_class`` is the last
classified attempt error, so ``success`` + ``rate_limit`` reads as "recovered from a 429"."""
@@ -796,6 +939,7 @@ def model_route_fields(
"call_role": _allowlisted(call_role, MODEL_CALL_ROLES),
"error_class": error_class if error_class in MODEL_ERROR_CLASSES else "unknown",
"outcome": outcome if outcome in MODEL_OUTCOMES else "failed",
+ "ttft_bucket": ttft_bucket if ttft_bucket in TTFT_BUCKETS else "unknown",
}
@@ -819,18 +963,28 @@ def size_bucket(count: int) -> str:
def install_snapshot_fields(
*, memory_provider: Any, mcp_servers: int, plugins: int, skills: int, cron_jobs: int,
- profiles: int,
+ profiles: int, messaging_platforms: int, install_age_bucket: str, main_provider: Any,
+ terminal_backend: Any, display_language: Any,
) -> dict[str, str]:
- """Bounded daily configuration snapshot: counts only, plus a bundled memory provider name."""
+ """Bounded daily configuration snapshot: counts, closed enums and public names only."""
+ from .shared_metrics_catalog import display_language_metric_name
+
provider = _norm(memory_provider)
+ backend = _norm(terminal_backend) or "local"
return {
"cron_job_count_bucket": size_bucket(cron_jobs),
+ "display_language": display_language_metric_name(display_language),
+ "install_age_bucket": install_age_bucket if install_age_bucket in INSTALL_AGE_BUCKETS else "unknown",
+ "main_provider": _metric_identifier(main_provider, max_length=PROVIDER_IDENTIFIER_MAX_LENGTH)
+ if main_provider else "none",
"mcp_server_count_bucket": size_bucket(mcp_servers),
"memory_provider": "builtin" if not provider
else provider if provider in MEMORY_PROVIDERS else "plugin",
+ "messaging_platform_count_bucket": size_bucket(messaging_platforms),
"plugin_count_bucket": size_bucket(plugins),
"profile_count_bucket": size_bucket(profiles),
"skill_count_bucket": size_bucket(skills),
+ "terminal_backend": backend if backend in TERMINAL_BACKENDS else "other",
}
diff --git a/hermes_cli/observability/shared_metrics_events.py b/hermes_cli/observability/shared_metrics_events.py
new file mode 100644
index 00000000000..0220d46d0a1
--- /dev/null
+++ b/hermes_cli/observability/shared_metrics_events.py
@@ -0,0 +1,68 @@
+"""Call-site API for process-level shared-metrics facts.
+
+Setup completion, slash commands, compression, model switches, fallbacks and extension installs
+happen outside any single tool or model call, so their producers call these functions directly.
+Every function takes RAW values (normalization lives in shared_metrics_fields), is a no-op unless
+shared metrics are enabled, and never raises into the caller.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any, Callable
+
+from . import shared_metrics_contract as contract
+from . import shared_metrics_fields as fields_
+
+logger = logging.getLogger(__name__)
+
+
+def _emit(mark: str, build: Callable[..., dict[str, str] | None], **raw: Any) -> None:
+ try:
+ from .relay_shared_metrics import enabled, record_process_mark
+
+ if not enabled():
+ return
+ data = build(**raw)
+ if data is not None:
+ record_process_mark(mark, data)
+ except Exception:
+ logger.debug("Shared-metrics %s not recorded", mark, exc_info=True)
+
+
+def record_setup_completed(*, surface: str, provider: str | None) -> None:
+ _emit(contract.SETUP_COMPLETED_MARK, fields_.setup_completed_fields, surface=surface, provider=provider)
+
+
+def record_slash_command(*, command: str, surface: str) -> None:
+ _emit(contract.SLASH_COMMAND_MARK, fields_.slash_command_fields, command=command, surface=surface)
+
+
+def record_compression(
+ *, trigger: str, outcome: str, tokens_before: int | None, context_length: int | None
+) -> None:
+ _emit(
+ contract.COMPRESSION_MARK, fields_.compression_fields, trigger=trigger, outcome=outcome,
+ tokens_before=tokens_before, context_length=context_length,
+ )
+
+
+def record_model_switch(*, from_provider: str | None, to_provider: str | None, surface: str) -> None:
+ _emit(
+ contract.MODEL_SWITCH_MARK, fields_.model_switch_fields,
+ from_provider=from_provider, to_provider=to_provider, surface=surface,
+ )
+
+
+def record_fallback(*, from_provider: str | None, to_provider: str | None, reason: Any) -> None:
+ _emit(
+ contract.FALLBACK_MARK, fields_.fallback_fields,
+ from_provider=from_provider, to_provider=to_provider, reason=reason,
+ )
+
+
+def record_extension_install(*, kind: str, source: str, name: str | None, outcome: str) -> None:
+ _emit(
+ contract.EXTENSION_INSTALL_MARK, fields_.extension_install_fields,
+ kind=kind, source=source, name=name, outcome=outcome,
+ )
diff --git a/hermes_cli/observability/shared_metrics_fields.py b/hermes_cli/observability/shared_metrics_fields.py
new file mode 100644
index 00000000000..0035c16db14
--- /dev/null
+++ b/hermes_cli/observability/shared_metrics_fields.py
@@ -0,0 +1,198 @@
+"""Bounded field builders for the decision-data shared metrics.
+
+Sessions, install milestones, setup completion, token volumes, compression, model switches,
+fallbacks, slash commands and extension installs. Every builder takes RAW runtime values and
+returns only closed-enum, bucketed or public-catalog dimensions (see shared_metrics_contract).
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from . import shared_metrics_catalog as catalog
+from . import shared_metrics_contract as contract
+from .shared_metrics_contract import (
+ MODEL_IDENTIFIER_MAX_LENGTH, PROVIDER_IDENTIFIER_MAX_LENGTH, _bucket, _metric_identifier, _norm,
+)
+
+_MINUTE_MS = 60_000
+_SESSION_DURATION_THRESHOLDS = (
+ (_MINUTE_MS, "lt_1m"), (5 * _MINUTE_MS, "1m_to_5m"), (30 * _MINUTE_MS, "5m_to_30m"),
+ (120 * _MINUTE_MS, "30m_to_2h"), (480 * _MINUTE_MS, "2h_to_8h"),
+)
+_HOUR_S = 3_600
+_INSTALL_AGE_THRESHOLDS = (
+ (_HOUR_S, "lt_1h"), (24 * _HOUR_S, "1h_to_1d"), (7 * 24 * _HOUR_S, "1d_to_7d"),
+ (30 * 24 * _HOUR_S, "7d_to_30d"), (90 * 24 * _HOUR_S, "30d_to_90d"),
+)
+_TTFT_THRESHOLDS = (
+ (0.5, "lt_500ms"), (1.0, "500ms_to_1s"), (2.0, "1s_to_2s"), (5.0, "2s_to_5s"), (15.0, "5s_to_15s"),
+)
+_CONTEXT_FILL_THRESHOLDS = ((50, "lt_50"), (75, "50_to_75"), (90, "75_to_90"), (100, "90_to_100"))
+# A session this long is the "real use" signal (vs a one-shot try-out).
+LONG_SESSION_TURNS = 6
+
+
+def _number(value: Any) -> float | None:
+ return contract._non_negative_number(value)
+
+
+def provider_identifier(value: Any) -> str:
+ return _metric_identifier(value, max_length=PROVIDER_IDENTIFIER_MAX_LENGTH)
+
+
+def session_fields(
+ start_fields: dict[str, str], *, turns: int, failed_turns: int, last_outcome: str, active_ms: int,
+) -> dict[str, str]:
+ """One closed session: where it ran, how many turns, how long it was active, how it ended."""
+ return {
+ "active_duration_bucket": _bucket(max(0, active_ms), _SESSION_DURATION_THRESHOLDS, "gte_8h"),
+ "entrypoint": start_fields.get("entrypoint", "unknown"),
+ "execution_surface": start_fields.get("execution_surface", "unknown"),
+ "failed_turn_count_bucket": contract.count_bucket(failed_turns),
+ "last_outcome": last_outcome if last_outcome in contract.TASK_OUTCOMES else "unknown",
+ "platform": start_fields.get("platform", "none"),
+ "turn_count_bucket": contract.size_bucket(turns),
+ }
+
+
+def install_age_bucket(age_seconds: Any) -> str:
+ age = _number(age_seconds)
+ return "unknown" if age is None else _bucket(age, _INSTALL_AGE_THRESHOLDS, "gte_90d")
+
+
+def ttft_bucket(event: dict[str, Any]) -> str:
+ """Time to first streamed chunk for one primary call; ``not_streamed`` when nothing streamed."""
+ started, first = _number(event.get("started_at")), _number(event.get("first_chunk_at"))
+ if started is None:
+ return "unknown"
+ if first is None:
+ return "not_streamed"
+ return _bucket(max(0.0, first - started), _TTFT_THRESHOLDS, "gte_15s")
+
+
+def context_fill_bucket(tokens_before: Any, context_length: Any) -> str:
+ tokens, length = _number(tokens_before), _number(context_length)
+ if tokens is None or not length:
+ return "unknown"
+ return _bucket(100 * tokens / length, _CONTEXT_FILL_THRESHOLDS, "gte_100")
+
+
+_USAGE_KEYS = {
+ "input": "input_tokens", "output": "output_tokens", "cache_read": "cache_read_tokens",
+ "cache_write": "cache_write_tokens", "reasoning": "reasoning_tokens",
+}
+
+
+def model_token_fields(
+ usage: Any, *, model: Any, provider: Any, call_role: str, aux_task: Any = None,
+) -> dict[str, Any] | None:
+ """Token-usage mark data (dimensions + integer amounts); None when there is no usage."""
+ if not isinstance(usage, dict):
+ return None
+ amounts = {}
+ for token_type, key in _USAGE_KEYS.items():
+ value = usage.get(key)
+ amounts[token_type] = value if isinstance(value, int) and not isinstance(value, bool) and value > 0 else 0
+ if not any(amounts.values()):
+ return None
+ return {
+ "aux_task": catalog.aux_task_metric_name(aux_task) if call_role == "auxiliary" else "none",
+ "call_role": call_role,
+ "model": _metric_identifier(model, max_length=MODEL_IDENTIFIER_MAX_LENGTH),
+ "provider": provider_identifier(provider),
+ **amounts,
+ }
+
+
+def setup_completed_fields(*, surface: Any, provider: Any) -> dict[str, str]:
+ value = _norm(surface)
+ return {
+ "provider": provider_identifier(provider) if provider else "none",
+ "surface": value if value in contract.SETUP_SURFACES else "other",
+ }
+
+
+_COMPRESSION_TRIGGERS = {
+ **dict.fromkeys(("auto", "threshold", "preflight", "auto_threshold"), "auto"),
+ **dict.fromkeys(("overflow", "context_overflow", "overflow_error", "error"), "overflow"),
+ **dict.fromkeys(("manual", "user", "command", "slash"), "manual"),
+}
+_COMPRESSION_OUTCOMES = {
+ **dict.fromkeys(("success", "ok", "compressed", "completed"), "success"),
+ **dict.fromkeys(("skipped", "noop", "not_needed"), "skipped"),
+}
+
+
+def compression_fields(*, trigger: Any, outcome: Any, tokens_before: Any, context_length: Any) -> dict[str, str]:
+ return {
+ "context_fill_bucket": context_fill_bucket(tokens_before, context_length),
+ "outcome": _COMPRESSION_OUTCOMES.get(_norm(outcome), "failed"),
+ "trigger": _COMPRESSION_TRIGGERS.get(_norm(trigger), "other"),
+ }
+
+
+def model_switch_fields(*, from_provider: Any, to_provider: Any, surface: Any) -> dict[str, str]:
+ return {
+ "execution_surface": contract.execution_surface({"execution_surface": surface}),
+ "from_provider": provider_identifier(from_provider),
+ "to_provider": provider_identifier(to_provider),
+ }
+
+
+def fallback_fields(*, from_provider: Any, to_provider: Any, reason: Any) -> dict[str, str]:
+ value = getattr(reason, "value", reason)
+ return {
+ "error_class": contract.model_error_class({"reason": value}),
+ "from_provider": provider_identifier(from_provider),
+ "to_provider": provider_identifier(to_provider),
+ }
+
+
+def slash_command_fields(*, command: Any, surface: Any) -> dict[str, str]:
+ return {
+ "command": catalog.slash_command_metric_name(command),
+ "execution_surface": contract.execution_surface({"execution_surface": surface}),
+ }
+
+
+def extension_install_fields(*, kind: Any, source: Any, name: Any, outcome: Any) -> dict[str, str] | None:
+ kind_value = _norm(kind)
+ if kind_value not in contract.EXTENSION_KINDS:
+ return None
+ source_value = _norm(source)
+ return {
+ "kind": kind_value,
+ "name": catalog.extension_metric_name(kind_value, name),
+ "outcome": "success" if _norm(outcome) in {"success", "ok", "installed"} else "failed",
+ "source": source_value if source_value in contract.EXTENSION_SOURCES else "other",
+ }
+
+
+def _long_session(d: dict[str, str]) -> bool:
+ return d.get("turn_count_bucket") not in {"0", "1", "2", "3_to_5"}
+
+
+# metric -> [(milestone, predicate over its dimensions)]
+_MILESTONE_RULES = {
+ contract.TASK_STARTED_METRIC: (
+ ("first_task_started", lambda d: True),
+ ("first_gateway_message", lambda d: d.get("platform") not in {None, "none"}),
+ ("first_scheduled_task", lambda d: d.get("entrypoint") == "scheduled_task"),
+ ),
+ contract.TASK_FINISHED_METRIC: (("first_task_success", lambda d: d.get("outcome") == "success"),),
+ contract.TOOL_USAGE_METRIC: (
+ ("first_tool_success", lambda d: d.get("outcome") == "success"),
+ ("first_mcp_tool_success", lambda d: d.get("outcome") == "success" and d.get("tool_name") == "mcp"),
+ ("first_delegation", lambda d: d.get("outcome") == "success" and d.get("tool_name") == "delegate_task"),
+ ),
+ contract.SKILL_LIFECYCLE_METRIC: (("first_skill_created", lambda d: d.get("action") == "created"),),
+ contract.SKILL_LOAD_METRIC: (("first_skill_reused", lambda d: d.get("reuse_state") == "reused"),),
+ contract.SESSION_METRIC: (("first_long_session", _long_session),),
+ contract.SETUP_COMPLETED_METRIC: (("setup_completed", lambda d: True),),
+}
+
+
+def milestones_for(metric_name: str, dimensions: dict[str, str]) -> tuple[str, ...]:
+ """Install milestones a recorded counter reaches (each is latched once per install by the store)."""
+ return tuple(name for name, reached in _MILESTONE_RULES.get(metric_name, ()) if reached(dimensions))
diff --git a/hermes_cli/observability/shared_metrics_snapshot.py b/hermes_cli/observability/shared_metrics_snapshot.py
index 758c9a1645d..95aa2147079 100644
--- a/hermes_cli/observability/shared_metrics_snapshot.py
+++ b/hermes_cli/observability/shared_metrics_snapshot.py
@@ -1,12 +1,16 @@
"""Collect the once-a-day install configuration snapshot for shared metrics.
-Only counts and a bundled memory-provider name are read out; server names, plugin names, skill
-names, job prompts and profile names stay local (the contract buckets every count).
+Only counts, closed enums (terminal backend, bundled memory provider, shipped locale), the main
+provider id and the profile's age are read out; server names, plugin names, skill names, job
+prompts and profile names stay local (the contract buckets every count).
"""
from __future__ import annotations
+import contextlib
import json
+import sqlite3
+import time
from itertools import islice
from typing import Any
@@ -59,8 +63,59 @@ def _profile_count() -> int:
return len(list_profile_names())
+def _messaging_platform_count() -> int:
+ from gateway.config import load_gateway_config
+
+ return len(load_gateway_config().get_connected_platforms())
+
+
+def _display_language() -> str:
+ from agent.i18n import get_language
+
+ return get_language()
+
+
+def _safe_count(reader) -> int:
+ try:
+ return reader()
+ except Exception:
+ return 0
+
+
+# The profile's first session never moves once it exists, so it is read from state.db once.
+_first_session_at: dict[str, float] = {}
+
+
+def _first_session_started_at() -> float | None:
+ home = str(get_hermes_home())
+ if home not in _first_session_at:
+ try:
+ with contextlib.closing(
+ sqlite3.connect(f"file:{get_hermes_home() / 'state.db'}?mode=ro", uri=True, timeout=1)
+ ) as connection:
+ row = connection.execute("SELECT MIN(started_at) FROM sessions").fetchone()
+ except sqlite3.Error:
+ return None
+ if not row or row[0] is None:
+ return None
+ _first_session_at[home] = float(row[0])
+ return _first_session_at[home]
+
+
+def install_age_bucket() -> str:
+ """How long ago this profile's first-ever session started, bucketed; ``unknown`` if none yet."""
+ from .shared_metrics_fields import install_age_bucket as bucket
+
+ first = _first_session_started_at()
+ return "unknown" if first is None else bucket(time.time() - first)
+
+
def collect_install_snapshot(config: dict[str, Any]) -> dict[str, str]:
"""Bounded snapshot fields for the active profile's ``config``."""
+ model = _sub(config, "model")
+ language = "other"
+ with contextlib.suppress(Exception):
+ language = _display_language()
return contract.install_snapshot_fields(
memory_provider=_sub(_sub(config, "memory"), "provider"),
mcp_servers=_mcp_server_count(config),
@@ -68,4 +123,9 @@ def collect_install_snapshot(config: dict[str, Any]) -> dict[str, str]:
skills=_skill_count(),
cron_jobs=_cron_job_count(),
profiles=_profile_count(),
+ messaging_platforms=_safe_count(_messaging_platform_count),
+ install_age_bucket=install_age_bucket(),
+ main_provider=_sub(model, "provider") if isinstance(model, dict) else None,
+ terminal_backend=_sub(_sub(config, "terminal"), "backend"),
+ display_language=language,
)
diff --git a/hermes_cli/observability/shared_metrics_subscriber.py b/hermes_cli/observability/shared_metrics_subscriber.py
index 626027bfdd1..f401c977119 100644
--- a/hermes_cli/observability/shared_metrics_subscriber.py
+++ b/hermes_cli/observability/shared_metrics_subscriber.py
@@ -11,6 +11,7 @@ from agent.relay_runtime import RUNTIME_INSTANCE_KEY
from hermes_cli.config import detect_install_method
from .shared_metrics import SharedMetricsStore
+from .shared_metrics_fields import milestones_for
from .shared_metrics_contract import (
CLIENT_ACTIVE_METRIC,
INSTALL_SNAPSHOT_METRIC,
@@ -19,8 +20,10 @@ from .shared_metrics_contract import (
TOOL_USAGE_METRIC,
client_active_counter,
client_resource,
+ decision_counter,
install_snapshot_counter,
model_call_dimensions,
+ model_token_counters,
skill_counter,
task_counter,
tool_approval_counter,
@@ -41,6 +44,7 @@ _COUNTERS = (
task_counter,
tool_approval_counter,
skill_counter,
+ decision_counter,
)
@@ -68,6 +72,7 @@ class SharedMetricsSubscriber:
self._runtime_id = runtime_id
self._active = True
self._lock = threading.RLock()
+ self._milestones_done: set[str] = set(store.recorded_milestones())
def deactivate(self) -> None:
"""Stop accepting events before telemetry is disabled or torn down."""
@@ -75,9 +80,22 @@ class SharedMetricsSubscriber:
self._active = False
@staticmethod
- def _classify(event: Any) -> list[tuple[str, dict]]:
- """Return every ``(metric_name, dimensions)`` the event satisfies."""
- return [m for m in (project(event) for project in _COUNTERS) if m is not None]
+ def _classify(event: Any) -> list[tuple[str, dict, int]]:
+ """Return every ``(metric_name, dimensions, amount)`` the event satisfies."""
+ counted = [(*m, 1) for m in (project(event) for project in _COUNTERS) if m is not None]
+ return counted + model_token_counters(event)
+
+ def _record_milestones(self, metric_name: str, dimensions: dict) -> None:
+ """Latch every install milestone this counter reaches (each once per install, ever)."""
+ reached = [m for m in milestones_for(metric_name, dimensions) if m not in self._milestones_done]
+ if not reached:
+ return
+ from .shared_metrics_snapshot import install_age_bucket
+
+ age = install_age_bucket()
+ for milestone in reached:
+ self.store.record_milestone(milestone, age, self._client_resource)
+ self._milestones_done.add(milestone)
def __call__(self, event: Any) -> None:
if self._runtime_id is not None:
@@ -87,7 +105,7 @@ class SharedMetricsSubscriber:
or metadata.get(RUNTIME_INSTANCE_KEY) != self._runtime_id
):
return
- for metric_name, dimensions in self._classify(event):
+ for metric_name, dimensions, amount in self._classify(event):
with self._lock:
if not self._active:
return
@@ -97,7 +115,8 @@ class SharedMetricsSubscriber:
elif metric_name == INSTALL_SNAPSHOT_METRIC:
self.store.record_install_snapshot(dimensions, self._client_resource)
else:
- self.store.record_counter(metric_name, dimensions, self._client_resource)
+ self.store.record_counter(metric_name, dimensions, self._client_resource, amount)
+ self._record_milestones(metric_name, dimensions)
except Exception:
logger.warning(
"Unable to persist the Hermes shared metric: %s", metric_name, exc_info=True
diff --git a/tests/agent/test_auxiliary_relay.py b/tests/agent/test_auxiliary_relay.py
index 707c9263f98..65b5b68c5ed 100644
--- a/tests/agent/test_auxiliary_relay.py
+++ b/tests/agent/test_auxiliary_relay.py
@@ -258,6 +258,7 @@ def test_auxiliary_provider_fallback_records_one_terminal_model_route(
"model": "accepted/model",
"outcome": "success",
"provider": "openrouter",
+ "ttft_bucket": "unknown",
}
assert snapshot[0]["value"] == 1
assert snapshot[0]["packaged_value"] == 0
diff --git a/tests/hermes_cli/test_relay_shared_metrics.py b/tests/hermes_cli/test_relay_shared_metrics.py
index a87a721b8be..e0064fd671c 100644
--- a/tests/hermes_cli/test_relay_shared_metrics.py
+++ b/tests/hermes_cli/test_relay_shared_metrics.py
@@ -498,7 +498,7 @@ def test_package_schema_matches_the_model_call_contract():
properties = _package_dimension_schema()["properties"]
assert schema["properties"]["schema_version"]["const"] == "hermes.shared_metrics.v3"
- assert set(properties) == {"call_role", "error_class", "model", "outcome", "provider"}
+ assert set(properties) == {"call_role", "error_class", "model", "outcome", "provider", "ttft_bucket"}
# Rows counted before the v3 upgrade carry only model/provider and must still drain.
assert set(_package_dimension_schema()["required"]) == {"model", "provider"}
assert properties["model"]["maxLength"] == MODEL_IDENTIFIER_MAX_LENGTH
@@ -767,6 +767,7 @@ def test_auxiliary_logical_scope_projects_one_normalized_terminal_route():
"model": "accepted/model",
"outcome": "success",
"provider": "openrouter",
+ "ttft_bucket": "unknown",
}
event.data.update({
@@ -779,6 +780,7 @@ def test_auxiliary_logical_scope_projects_one_normalized_terminal_route():
"model": "configured/model",
"outcome": "success",
"provider": "openrouter",
+ "ttft_bucket": "unknown",
}
event.metadata["hermes.call_role"] = "primary"
@@ -907,14 +909,16 @@ def test_skill_subscriber_contract_accepts_only_bounded_marks():
"post_patch_state": "reused_after_patch",
"provenance": "agent_created",
"reuse_state": "reused",
+ "skill_name": "custom",
"use_count_bucket": "3_to_5",
},
})
assert skill_counter(load) == ("hermes.skill.load.count", load.data)
+ # Only bundled/optional skill names (public) may appear; a local name is refused.
load.data["skill_name"] = "privacy-canary"
assert skill_counter(load) is None
- load.data.pop("skill_name")
+ load.data["skill_name"] = "custom"
load.data["provenance"] = "private-repository"
assert skill_counter(load) is None
lifecycle.metadata["skill_name"] = "privacy-canary"
@@ -937,16 +941,19 @@ def test_skill_event_fields_are_bounded_and_reject_malformed_usage():
"post_patch_state": "no_new_patch",
"provenance": "unknown",
"reuse_state": "reused",
+ "skill_name": "custom",
"use_count_bucket": "2",
}
assert skill_load_fields({
"use_count": 1,
"reused": False,
"reuse_after_patch": False,
+ "skill_name": "codex",
}) == {
"post_patch_state": "not_applicable",
"provenance": "unknown",
"reuse_state": "first_use",
+ "skill_name": "codex",
"use_count_bucket": "1",
}
assert (
diff --git a/tests/hermes_cli/test_relay_shared_metrics_runtime.py b/tests/hermes_cli/test_relay_shared_metrics_runtime.py
index bf1e550acf0..51f36ecc34f 100644
--- a/tests/hermes_cli/test_relay_shared_metrics_runtime.py
+++ b/tests/hermes_cli/test_relay_shared_metrics_runtime.py
@@ -390,6 +390,7 @@ def test_direct_runtime_records_without_enabling_a_plugin(direct_runtime, tmp_pa
"model": "claude-sonnet",
"outcome": "success",
"provider": "anthropic",
+ "ttft_bucket": "unknown",
}
serialized_events = json.dumps(direct_runtime.events)
assert "sensitive-prompt" not in serialized_events
@@ -409,6 +410,7 @@ def test_direct_runtime_records_without_enabling_a_plugin(direct_runtime, tmp_pa
metrics = {metric["name"]: metric for metric in package["metrics"]}
assert set(metrics) == {
"hermes.client.active",
+ "hermes.install.milestone",
"hermes.install.snapshot",
"hermes.model_route.count",
"hermes.task_run.finished",
@@ -434,6 +436,7 @@ def test_direct_runtime_records_without_enabling_a_plugin(direct_runtime, tmp_pa
"model": "claude-sonnet",
"outcome": "success",
"provider": "anthropic",
+ "ttft_bucket": "unknown",
}
assert metrics["hermes.model_route.count"]["value"] == 1
assert metrics["hermes.tool_call.count"] == {
@@ -673,6 +676,7 @@ def test_real_binding_drives_lifecycle_aggregation_export_and_snapshot(
"model": model_canary,
"outcome": outcome,
"provider": "custom",
+ "ttft_bucket": route_by_outcome[outcome]["dimensions"]["ttft_bucket"],
}
assert route_by_outcome[outcome]["value"] == 1
assert {
@@ -1290,6 +1294,7 @@ def test_disabling_shared_metrics_stops_collection_and_shutdown_export(
store = SharedMetricsStore(root / "metrics.sqlite3", root / "outbox")
assert [row["metric_name"] for row in store.counter_snapshot()] == [
"hermes.client.active",
+ "hermes.install.milestone",
"hermes.install.snapshot",
"hermes.task_run.started"
]
@@ -1710,6 +1715,7 @@ def test_terminal_model_error_retains_the_failed_route(direct_runtime):
"model": "claude-sonnet",
"outcome": "failed",
"provider": "anthropic",
+ "ttft_bucket": "unknown",
}
@@ -1755,6 +1761,7 @@ def test_nonretryable_provider_error_can_recover_within_one_logical_call(
"model": "gpt-5",
"outcome": "success",
"provider": "openai-api",
+ "ttft_bucket": "unknown",
}
@@ -2748,7 +2755,9 @@ def test_install_snapshot_is_daily_and_carries_only_bucketed_counts(
[snapshot] = _stored_counters(tmp_path)["hermes.install.snapshot"]
assert snapshot == {
- "cron_job_count_bucket": "0", "mcp_server_count_bucket": "1",
- "memory_provider": "plugin", "plugin_count_bucket": "3_to_5",
+ "cron_job_count_bucket": "0", "display_language": "en", "install_age_bucket": snapshot["install_age_bucket"],
+ "main_provider": "none", "mcp_server_count_bucket": "1", "memory_provider": "plugin",
+ "messaging_platform_count_bucket": "0", "plugin_count_bucket": "3_to_5",
"profile_count_bucket": snapshot["profile_count_bucket"], "skill_count_bucket": "0",
+ "terminal_backend": "local",
}