The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(telemetry): v5 signals — tool_unavailable, provider_setup, feature_adoption, feature_disabled
teknium1c13a4abc8d75
diff --git a/hermes_cli/auth_error_copy.py b/hermes_cli/auth_error_copy.pyindex 17a8e9da344..fc66db705a3 100644--- a/hermes_cli/auth_error_copy.py+++ b/hermes_cli/auth_error_copy.py@@ -81,6 +81,9 @@ def sign_in_failure_lines(exc: BaseException, *, service_host: str = "portal.nousresearch.com", retry_command: str = "hermes portal",) -> list:"""Lines to print when a device-code / browser sign-in fails for any non-timeout reason."""+ from hermes_cli.observability.shared_metrics_setup import note_sign_in_failure++ note_sign_in_failure(exc)if isinstance(exc, SignInCopyError):return str(exc).splitlines()rules: Sequence[_Rule] = (diff --git a/hermes_cli/auth_model_picker.py b/hermes_cli/auth_model_picker.pyindex acfddbddec0..18ccc96b49f 100644--- a/hermes_cli/auth_model_picker.py+++ b/hermes_cli/auth_model_picker.py@@ -292,3 +292,6 @@ def _save_model_choice(model_id: str) -> None:else:config["model"] = {"default": model_id}save_config(config)+ from hermes_cli.observability.shared_metrics_setup import note_provider_setup_saved++ note_provider_setup_saved()diff --git a/hermes_cli/cli_agent_setup_mixin.py b/hermes_cli/cli_agent_setup_mixin.pyindex ba266aee465..6c55672c8ba 100644--- a/hermes_cli/cli_agent_setup_mixin.py+++ b/hermes_cli/cli_agent_setup_mixin.py@@ -483,7 +483,9 @@ class CLIAgentSetupMixin:return Falsetry:from hermes_cli.main import select_provider_and_model- select_provider_and_model()+ from hermes_cli.observability.shared_metrics_setup import provider_setup_surface+ with provider_setup_surface("cli_setup"):+ select_provider_and_model()except (KeyboardInterrupt, EOFError, SystemExit):print()_cprint(" Setup cancelled. Run 'hermes model' any time.")diff --git a/hermes_cli/config.py b/hermes_cli/config.pyindex e2cd39d4fa7..f64c09f6ace 100644--- a/hermes_cli/config.py+++ b/hermes_cli/config.py@@ -2487,6 +2487,8 @@ def save_config(_secure_file(config_path)_RAW_CONFIG_CACHE.pop(str(config_path), None)_LAST_EXPANDED_CONFIG_BY_PATH[str(config_path)] = copy.deepcopy(current_normalized)+ from hermes_cli.observability.shared_metrics_disabled import record_config_saved+ record_config_saved(_raw_for_paths, current_normalized)def load_env() -> Dict[str, str]:@@ -3514,7 +3516,8 @@ def _exit_invalid(msg: str) -> None:def _write_user_config(config_path: Path, user_config: Dict[str, Any]) -> None:"""Write only the user's raw config back (never the merged defaults)."""ensure_hermes_home()- atomic_config_write(config_path, user_config)+ from hermes_cli.observability.shared_metrics_disabled import recording_raw_config_write+ recording_raw_config_write(config_path, user_config, atomic_config_write)def _print_unknown_key_notice(key: str, suggestion: Optional[str]) -> None:diff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex d53509a8c31..32ef3ea8af9 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -1977,13 +1977,13 @@ def cmd_model(args):print(" Cleared model picker cache.")except Exception:pass+ from hermes_cli.observability.shared_metrics_setup import provider_setup_surfacefrom hermes_cli.setup import run_setup_action_with_navigation- run_setup_action_with_navigation(- "Model & Provider",- lambda: select_provider_and_model(args=args),- cancelled_message="No change.",- )+ with provider_setup_surface("cli_model"):+ run_setup_action_with_navigation(+ "Model & Provider", lambda: select_provider_and_model(args=args), cancelled_message="No change.",+ )# Provider id -> flow(config, current_model, args). Lambdas resolve the@@ -2153,31 +2153,33 @@ def select_provider_and_model(args=None):# Provider-specific setup + model selection. Flows resolve the# _model_flow_* names at call time so test monkeypatches on# hermes_cli.main keep intercepting.- flow = _PROVIDER_MODEL_FLOWS.get(selected_provider)- if flow is None and _is_profile_plugin_flow_provider(selected_provider):- # Registered plugin profile with no bespoke flow: the generic one, keyed by its auth_type.- flow = lambda c, m, a: _model_flow_plugin_provider(c, selected_provider, m) # noqa: E731- if flow is not None:- flow(config, current_model, args)- elif (- selected_provider.startswith("custom:")- or selected_provider in _custom_provider_map- ):- provider_info = _named_custom_provider_map(load_config()).get(selected_provider)- if provider_info is None:- print(- "Warning: the selected saved custom provider is no longer available. "- "It may have been removed from config.yaml. No change."- )- return- _model_flow_named_custom(config, provider_info)- elif selected_provider == "remove-custom":- _remove_custom_provider(config)- elif (- selected_provider in _GENERIC_API_KEY_PROVIDERS- or _is_profile_api_key_provider(selected_provider)- ):- _model_flow_api_key_provider(config, selected_provider, current_model)+ from hermes_cli.observability.shared_metrics_setup import cli_provider_setup+ with cli_provider_setup(selected_provider):+ flow = _PROVIDER_MODEL_FLOWS.get(selected_provider)+ if flow is None and _is_profile_plugin_flow_provider(selected_provider):+ # Registered plugin profile with no bespoke flow: the generic one, keyed by its auth_type.+ flow = lambda c, m, a: _model_flow_plugin_provider(c, selected_provider, m) # noqa: E731+ if flow is not None:+ flow(config, current_model, args)+ elif (+ selected_provider.startswith("custom:")+ or selected_provider in _custom_provider_map+ ):+ provider_info = _named_custom_provider_map(load_config()).get(selected_provider)+ if provider_info is None:+ print(+ "Warning: the selected saved custom provider is no longer available. "+ "It may have been removed from config.yaml. No change."+ )+ return+ _model_flow_named_custom(config, provider_info)+ elif selected_provider == "remove-custom":+ _remove_custom_provider(config)+ elif (+ selected_provider in _GENERIC_API_KEY_PROVIDERS+ or _is_profile_api_key_provider(selected_provider)+ ):+ _model_flow_api_key_provider(config, selected_provider, current_model)# Every flow persists through _save_model_choice; a changed model.default means a pick# landed, so offer its reasoning effort here once instead of inside each flow.@@ -3678,6 +3680,8 @@ def main():if getattr(args, "oneshot", None):_run_oneshot_from_args(args)+ from hermes_cli.observability.shared_metrics_disabled import set_process_surface+ set_process_surface(args.command)# No subcommand (optionally with top-level --resume / --continue) → chat.if args.command is None:_default_to_chat(args)diff --git a/hermes_cli/model_setup_flows.py b/hermes_cli/model_setup_flows.pyindex 5041cd6c7e9..3dbc4e8aff5 100644--- a/hermes_cli/model_setup_flows.py+++ b/hermes_cli/model_setup_flows.py@@ -18,7 +18,7 @@ from hermes_cli.model_setup_flows_common import (_ensure_dict_section, _ensure_flow_api_key, _finish_model,_load_config_model_section, _models_dev_merged, _oauth_gate, _persist_model, _pick_model_or_prompt,_print_numbered, _prompt_auth_credentials_choice,- _run_login, _say, _show_curated)+ _note_setup_failure, _run_login, _say, _show_curated)from hermes_cli.model_setup_flows_custom import _model_flow_custom, _model_flow_named_customfrom hermes_cli.model_setup_flows_azure import _model_flow_azure_foundryfrom hermes_cli.model_setup_flows_bedrock import _model_flow_bedrock@@ -208,6 +208,7 @@ def _nous_model_catalog(free_tier: bool, portal_url: str, model_ids: list, priciif not model_ids and not unavailable_models:print("No models available for Nous Portal after filtering.")+ _note_setup_failure("no_models")return Noneif free_tier and not model_ids:print("No free models currently available.")@@ -236,8 +237,10 @@ def _nous_verified_credentials(creds_or_none=None):_login_nous(_nous_login_args(None), PROVIDER_REGISTRY["nous"])except Exception as login_exc:print(f"Re-login failed: {login_exc}")+ _note_setup_failure("auth")return Noneprint(f"Could not verify credentials: {msg}")+ _note_setup_failure("auth")return None@@ -466,6 +469,7 @@ def _model_flow_minimax_oauth(config, current_model="", args=None):creds = resolve_minimax_oauth_runtime_credentials()except AuthError as exc:print(format_auth_error(exc))+ _note_setup_failure("auth")returnfrom hermes_cli.models import _PROVIDER_MODELS@@ -524,6 +528,7 @@ def _copilot_obtain_token() -> bool:_say(" Copilot token saved.", "")except Exception as exc:print(f" Login failed: {exc}")+ _note_setup_failure("auth")return Falsereturn Trueif choice == "2":@@ -1093,6 +1098,7 @@ def _external_process_login_gate(profile, status) -> bool:return Falseif not profile.setup_status()["logged_in"]:print("Login failed.")+ _note_setup_failure("auth")return False_say("", f" {profile.display_name} credentials: ✓", "")return Truediff --git a/hermes_cli/model_setup_flows_bedrock.py b/hermes_cli/model_setup_flows_bedrock.pyindex a38cbad950c..6da9d4c643d 100644--- a/hermes_cli/model_setup_flows_bedrock.py+++ b/hermes_cli/model_setup_flows_bedrock.py@@ -8,7 +8,7 @@ Prompt strings and config write order are behavior.from __future__ import annotationsfrom hermes_cli.model_setup_flows_common import (- _ask, _ensure_dict_section, _finish_model, _pick_model_or_prompt, _say)+ _ask, _ensure_dict_section, _finish_model, _note_setup_failure, _pick_model_or_prompt, _say)# AWS cross-region inference profile prefixes. A geo-prefixed profile only routes@@ -193,6 +193,7 @@ def _model_flow_bedrock(config, current_model=""):model_list = _PROVIDER_MODELS.get("bedrock", [])if not model_list:print(" No models found. Check IAM permissions for bedrock:ListFoundationModels.")+ _note_setup_failure("no_models")returnprint(f" Using {len(model_list)} curated models (live discovery unavailable)")diff --git a/hermes_cli/model_setup_flows_common.py b/hermes_cli/model_setup_flows_common.pyindex b9dd62d5874..969b561585d 100644--- a/hermes_cli/model_setup_flows_common.py+++ b/hermes_cli/model_setup_flows_common.py@@ -18,6 +18,13 @@ from hermes_cli.config import clear_model_endpoint_credentials_HTTP = ("http://", "https://")+def _note_setup_failure(failure_class: str) -> None:+ """Why a flow returns without a pick, for the provider-setup metric (no-op outside a tracked flow)."""+ from hermes_cli.observability.shared_metrics_setup import note_provider_setup_failure++ note_provider_setup_failure(failure_class)++def _say(*lines: str) -> None:"""``print`` each line (``""`` = blank line); one call per banner block."""print("\n".join(lines))diff --git a/hermes_cli/observability/schemas/hermes.shared_metrics.v3.schema.json b/hermes_cli/observability/schemas/hermes.shared_metrics.v3.schema.jsonindex ef148b1748d..5d99b30d228 100644--- a/hermes_cli/observability/schemas/hermes.shared_metrics.v3.schema.json+++ b/hermes_cli/observability/schemas/hermes.shared_metrics.v3.schema.json@@ -255,6 +255,18 @@},{"$ref": "#/$defs/desktop_dislike_counter"+ },+ {+ "$ref": "#/$defs/tool_unavailable_counter"+ },+ {+ "$ref": "#/$defs/provider_setup_counter"+ },+ {+ "$ref": "#/$defs/feature_adoption_counter"+ },+ {+ "$ref": "#/$defs/feature_disabled_counter"}]}@@ -4110,6 +4122,342 @@"minimum": 1}}+ },+ "tool_unavailable_counter": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "name",+ "type",+ "dimensions",+ "value"+ ],+ "properties": {+ "name": {+ "const": "hermes.tool_unavailable.count"+ },+ "type": {+ "const": "counter"+ },+ "dimensions": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "model",+ "provider",+ "tool_name"+ ],+ "properties": {+ "model": {+ "type": "string",+ "minLength": 1,+ "maxLength": 256,+ "pattern": "^[a-z0-9][a-z0-9._:/@+\\-]*$"+ },+ "provider": {+ "$ref": "#/$defs/provider_identifier"+ },+ "tool_name": {+ "enum": [+ "annotate_preview",+ "browser_back",+ "browser_cdp",+ "browser_click",+ "browser_console",+ "browser_dialog",+ "browser_exec",+ "browser_get_images",+ "browser_navigate",+ "browser_press",+ "browser_scroll",+ "browser_snapshot",+ "browser_type",+ "browser_vault_enter_code",+ "browser_vault_fill",+ "browser_vault_list",+ "browser_vault_save_login",+ "browser_vault_unlock",+ "browser_vision",+ "clarify",+ "close_terminal",+ "computer_use",+ "cronjob_manage",+ "delegate_task",+ "desktop_preview",+ "desktop_project",+ "discord",+ "discord_admin",+ "drive_preview",+ "execute_code",+ "feishu_doc_read",+ "feishu_drive_add_comment",+ "feishu_drive_list_comment_replies",+ "feishu_drive_list_comments",+ "feishu_drive_reply_comment",+ "focus_pane",+ "gui_tour",+ "ha_call_service",+ "ha_get_state",+ "ha_list_entities",+ "ha_list_services",+ "image_generate",+ "kanban_attach",+ "kanban_attach_url",+ "kanban_attachments",+ "kanban_block",+ "kanban_comment",+ "kanban_complete",+ "kanban_create",+ "kanban_heartbeat",+ "kanban_link",+ "kanban_list",+ "kanban_request_changes",+ "kanban_request_review",+ "kanban_show",+ "kanban_unblock",+ "manage_catalog",+ "manage_connections",+ "memory",+ "patch",+ "process_manage",+ "react_to_message",+ "read_file",+ "read_terminal",+ "read_window_below",+ "search_files",+ "session_search",+ "show_tip",+ "skill_manage",+ "skill_view",+ "skills_list",+ "spotify_albums",+ "spotify_devices",+ "spotify_library",+ "spotify_playback",+ "spotify_playlists",+ "spotify_queue",+ "spotify_search",+ "terminal",+ "text_to_speech",+ "todo_list",+ "video_analyze",+ "video_generate",+ "vision_analyze",+ "web_extract",+ "web_search",+ "write_file",+ "x_search",+ "xai_video_edit",+ "xai_video_extend",+ "yb_query_group_info",+ "yb_query_group_members",+ "yb_search_sticker",+ "yb_send_dm",+ "yb_send_sticker"+ ]+ }+ },+ "description": "A model called a tool Hermes ships that this session did not enable (background reviews and delegated children excluded)."+ },+ "value": {+ "type": "integer",+ "minimum": 1+ }+ }+ },+ "provider_setup_counter": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "name",+ "type",+ "dimensions",+ "value"+ ],+ "properties": {+ "name": {+ "const": "hermes.provider_setup.count"+ },+ "type": {+ "const": "counter"+ },+ "dimensions": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "event",+ "failure_class",+ "provider",+ "surface"+ ],+ "properties": {+ "event": {+ "enum": [+ "abandoned",+ "completed",+ "failed",+ "started"+ ]+ },+ "failure_class": {+ "enum": [+ "auth",+ "cancelled",+ "network",+ "no_models",+ "none",+ "other"+ ]+ },+ "provider": {+ "$ref": "#/$defs/provider_identifier"+ },+ "surface": {+ "enum": [+ "cli_model",+ "cli_setup",+ "dashboard",+ "desktop",+ "tui"+ ]+ }+ },+ "description": "One per provider-setup flow transition; failure_class is none unless event=failed. Custom endpoints read custom."+ },+ "value": {+ "type": "integer",+ "minimum": 1+ }+ }+ },+ "feature_adoption_counter": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "name",+ "type",+ "dimensions",+ "value"+ ],+ "properties": {+ "name": {+ "const": "hermes.feature_adoption.count"+ },+ "type": {+ "const": "counter"+ },+ "dimensions": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "days_since_install_bucket",+ "feature"+ ],+ "properties": {+ "days_since_install_bucket": {+ "enum": [+ "1d_to_7d",+ "30d_to_90d",+ "7d_to_30d",+ "gte_90d",+ "same_day",+ "unknown"+ ]+ },+ "feature": {+ "enum": [+ "bot_mode",+ "browser",+ "cron",+ "curator",+ "delegation",+ "desktop",+ "gateway_platform",+ "kanban",+ "mcp",+ "memory",+ "plugins",+ "projects",+ "skills_created",+ "tui",+ "voice"+ ]+ }+ },+ "description": "Emitted once per feature per install, at its first real use; the bucket is the owning profile's age then."+ },+ "value": {+ "const": 1+ }+ }+ },+ "feature_disabled_counter": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "name",+ "type",+ "dimensions",+ "value"+ ],+ "properties": {+ "name": {+ "const": "hermes.feature_disabled.count"+ },+ "type": {+ "const": "counter"+ },+ "dimensions": {+ "type": "object",+ "additionalProperties": false,+ "required": [+ "event",+ "kind",+ "name",+ "surface"+ ],+ "properties": {+ "event": {+ "enum": [+ "disabled",+ "re_enabled"+ ]+ },+ "kind": {+ "enum": [+ "compression",+ "curator",+ "memory",+ "platform",+ "plugin",+ "setting",+ "skill",+ "toolset"+ ]+ },+ "name": {+ "type": "string",+ "minLength": 1,+ "maxLength": 64,+ "pattern": "^[a-z0-9][a-z0-9._:/@+\\-]*$"+ },+ "surface": {+ "enum": [+ "cli_config",+ "cli_slash",+ "cli_tools",+ "dashboard",+ "desktop",+ "tui"+ ]+ }+ },+ "description": "A user turned off something Hermes ships on (or removed a shipped skill), or turned it back on. name is a shipped toolset / bundled or catalog skill or plugin / DEFAULT_CONFIG key path (never a value), else custom. At most once per (kind, name, event) per day."+ },+ "value": {+ "const": 1+ }+ }}}}diff --git a/hermes_cli/observability/shared_metrics.py b/hermes_cli/observability/shared_metrics.pyindex c1372deca57..7882e7a5912 100644--- a/hermes_cli/observability/shared_metrics.py+++ b/hermes_cli/observability/shared_metrics.py@@ -19,6 +19,7 @@ from utils import atomic_json_writefrom .shared_metrics_contract import (CLIENT_ACTIVE_METRIC,COUNTER_METRICS,+ FEATURE_ADOPTION_METRIC,INSTALL_SNAPSHOT_METRIC,MILESTONE_METRIC,MODEL_ROUTE_METRIC,@@ -36,6 +37,8 @@ _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:"+_FEATURE_STATE_PREFIX = "feature:"+_DAILY_ONCE_STATE_PREFIX = "daily_once:"_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")@@ -295,27 +298,65 @@ class SharedMetricsStore:)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)+ return self._latched(_MILESTONE_STATE_PREFIX)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)+ return self._record_once_ever(f"{_MILESTONE_STATE_PREFIX}{milestone}", MILESTONE_METRIC, dimensions, resource)++ # ---- v5 signals ----+ def recorded_features(self) -> frozenset[str]:+ return self._latched(_FEATURE_STATE_PREFIX)++ def record_feature_adoption(self, feature: str, days_bucket: str, resource: dict[str, str]) -> bool:+ """Record a feature's first use at most once per install, ever (same latch as milestones)."""+ dimensions = {"days_since_install_bucket": days_bucket, "feature": feature}+ return self._record_once_ever(f"{_FEATURE_STATE_PREFIX}{feature}", FEATURE_ADOPTION_METRIC, dimensions, resource)++ def record_counter_once_per_day(self, metric_name: str, dimensions: dict[str, str], resource: dict[str, str]) -> bool:+ """Count at most once per UTC day per dimension set, whatever the surface (``surface`` is+ attribution of the first one that day). One state row per dimension set, overwritten daily."""+ self._validate_counter(metric_name, dimensions, resource)+ now = _utc_now()+ today = now.date().isoformat()+ key = f"{_DAILY_ONCE_STATE_PREFIX}{metric_name}:" + _compact_json(+ {k: v for k, v in dimensions.items() if k != "surface"})+ with self._write() as connection:+ changed = connection.execute(+ "INSERT INTO telemetry_state(key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE"+ " SET value = excluded.value WHERE telemetry_state.value != excluded.value",+ (key, today),+ ).rowcount+ if not changed:+ return False+ self._install_id(connection)+ self._record_counter_in_transaction(connection, metric_name, dimensions, resource, today)+ return True+ # ---- end v5 signals ----++ def _latched(self, prefix: str) -> frozenset[str]:+ with self._connection() as connection:+ rows = connection.execute(+ "SELECT key FROM telemetry_state WHERE key LIKE ?", (f"{prefix}%",)+ ).fetchall()+ return frozenset(row["key"][len(prefix):] for row in rows)++ def _record_once_ever(+ self, state_key: str, metric_name: str, dimensions: dict[str, str], resource: dict[str, str],+ ) -> bool:+ self._validate_counter(metric_name, 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)),+ (state_key, _isoformat(now)),).rowcountif not inserted:return Falseself._install_id(connection)self._record_counter_in_transaction(- connection, MILESTONE_METRIC, dimensions, resource, now.date().isoformat()+ connection, metric_name, dimensions, resource, now.date().isoformat())return Truediff --git a/hermes_cli/observability/shared_metrics_contract.py b/hermes_cli/observability/shared_metrics_contract.pyindex ad4d5b50b92..56254effdca 100644--- a/hermes_cli/observability/shared_metrics_contract.py+++ b/hermes_cli/observability/shared_metrics_contract.py@@ -347,6 +347,30 @@ _DAY_MS = 86_400_000_VERSION_AGE_THRESHOLDS = ((7 * _DAY_MS, "lt_7d"), (30 * _DAY_MS, "7d_to_30d"), (90 * _DAY_MS, "30d_to_90d"))+# ---- v5 signals ----+TOOL_UNAVAILABLE_MARK = TOOL_UNAVAILABLE_METRIC = "hermes.tool_unavailable.count"+PROVIDER_SETUP_MARK = PROVIDER_SETUP_METRIC = "hermes.provider_setup.count"+FEATURE_ADOPTION_METRIC = "hermes.feature_adoption.count"+# Not a counter: a first-use fact the subscriber turns into at most one adoption row per feature.+FEATURE_USED_MARK = "hermes.feature.used"+PROVIDER_SETUP_SURFACES = frozenset({"cli_model", "cli_setup", "dashboard", "desktop", "tui"})+PROVIDER_SETUP_EVENTS = frozenset({"abandoned", "completed", "failed", "started"})+PROVIDER_SETUP_FAILURE_CLASSES = frozenset({"auth", "cancelled", "network", "no_models", "none", "other"})+FEATURES = frozenset({+ "browser", "bot_mode", "cron", "curator", "delegation", "desktop", "gateway_platform", "kanban", "mcp",+ "memory", "plugins", "projects", "skills_created", "tui", "voice",+})+DAYS_SINCE_INSTALL_BUCKETS = frozenset({"same_day", "1d_to_7d", "7d_to_30d", "30d_to_90d", "gte_90d", "unknown"})+FEATURE_DISABLED_MARK = FEATURE_DISABLED_METRIC = "hermes.feature_disabled.count"+FEATURE_DISABLED_KINDS = frozenset({+ "compression", "curator", "memory", "platform", "plugin", "setting", "skill", "toolset",+})+FEATURE_DISABLED_SURFACES = frozenset({"cli_config", "cli_slash", "cli_tools", "dashboard", "desktop", "tui"})+FEATURE_DISABLED_EVENTS = frozenset({"disabled", "re_enabled"})+FEATURE_DISABLED_NAME_MAX_LENGTH = 64+# ---- end v5 signals ----++def update_duration_bucket(duration_ms: Any) -> str:"""Bucket an update (or update stage) wall time; non-numbers count as instant."""value = _non_negative_number(duration_ms) or 0@@ -800,6 +824,17 @@ _COUNTER_DIMENSION_VALUES: dict[str, dict[str, frozenset[str]]] = {"direction": DESKTOP_DISLIKE_DIRECTIONS, "signal": DESKTOP_DISLIKE_SIGNALS, "target": DESKTOP_DISLIKE_TARGET_VALUES,},# ---- end v5 desktop ----+ # ---- v5 signals ----+ TOOL_UNAVAILABLE_METRIC: {"tool_name": BUILTIN_TOOL_NAMES},+ PROVIDER_SETUP_METRIC: {+ "event": PROVIDER_SETUP_EVENTS, "failure_class": PROVIDER_SETUP_FAILURE_CLASSES,+ "surface": PROVIDER_SETUP_SURFACES,+ },+ FEATURE_ADOPTION_METRIC: {"days_since_install_bucket": DAYS_SINCE_INSTALL_BUCKETS, "feature": FEATURES},+ FEATURE_DISABLED_METRIC: {+ "event": FEATURE_DISABLED_EVENTS, "kind": FEATURE_DISABLED_KINDS, "surface": FEATURE_DISABLED_SURFACES,+ },+ # ---- end v5 signals ----}_MODEL_ROUTE_MAX_LENGTHS = {"model": MODEL_IDENTIFIER_MAX_LENGTH, "provider": PROVIDER_IDENTIFIER_MAX_LENGTH,@@ -836,6 +871,11 @@ _IDENTIFIER_FIELDS: dict[str, dict[str, int]] = {# ---- v5 desktop ----DESKTOP_DISLIKE_METRIC: {"setting": DESKTOP_SETTING_KEY_MAX_LENGTH},# ---- end v5 desktop ----+ # ---- v5 signals ----+ TOOL_UNAVAILABLE_METRIC: _MODEL_ROUTE_MAX_LENGTHS,+ PROVIDER_SETUP_METRIC: {"provider": PROVIDER_IDENTIFIER_MAX_LENGTH},+ FEATURE_DISABLED_METRIC: {"name": FEATURE_DISABLED_NAME_MAX_LENGTH},+ # ---- end v5 signals ----}# ---- v5 engagement ----# Conversation volume on the session row: new fields, so rows recorded before them still package.@@ -915,6 +955,10 @@ _DECISION_MARK_METRICS = {DESKTOP_ONBOARDING_MARK: DESKTOP_ONBOARDING_METRIC, DESKTOP_MODE_USE_MARK: DESKTOP_MODE_USE_METRIC,DESKTOP_ACTION_USE_MARK: DESKTOP_ACTION_USE_METRIC, DESKTOP_DISLIKE_MARK: DESKTOP_DISLIKE_METRIC,# ---- end v5 desktop ----+ # ---- v5 signals ----+ TOOL_UNAVAILABLE_MARK: TOOL_UNAVAILABLE_METRIC, PROVIDER_SETUP_MARK: PROVIDER_SETUP_METRIC,+ FEATURE_DISABLED_MARK: FEATURE_DISABLED_METRIC,+ # ---- end v5 signals ----}diff --git a/hermes_cli/observability/shared_metrics_disabled.py b/hermes_cli/observability/shared_metrics_disabled.pynew file mode 100644index 00000000000..36c2eab4e46--- /dev/null+++ b/hermes_cli/observability/shared_metrics_disabled.py@@ -0,0 +1,259 @@+"""hermes.feature_disabled.count: a user turns off something Hermes ships on, or removes something shipped.++One chokepoint sees every write: ``save_config`` hands over the raw config it replaced and the one it+wrote, and :func:`config_transitions` diffs only what the user moved away from the shipped default+(or back to it): default-on toolsets, ``skills.disabled``, ``plugins.disabled`` and default-``True``+booleans. Names are public only when shipped (toolset key, bundled/catalog skill, bundled/catalog+plugin, ``DEFAULT_CONFIG`` key path; never a value); anything else reads ``custom``. The store counts+each (kind, name, event) at most once per day.++The surface is the entry point that is running: ``set_process_surface`` from the ``hermes`` command+dispatch (``tools`` / ``config`` / ``skills`` / ``plugins`` / chat slash commands / the web server) and+the TUI gateway. A process with no surface (setup wizard, updates, migrations) records nothing: those+writes are Hermes applying choices, not a user turning something off.+"""++from __future__ import annotations++import functools+import logging+from typing import Any, Iterable++logger = logging.getLogger(__name__)++CUSTOM = "custom"+_COMMAND_SURFACES = {+ None: "cli_slash", "chat": "cli_slash", "tools": "cli_tools", "config": "cli_config",+ "skills": "cli_config", "plugins": "cli_config",+ "dashboard": "web", "serve": "web", "gui": "web", "desktop": "web",+}+_SETTING_KINDS = {"memory": "memory", "curator": "curator", "compression": "compression"}+_OFF = frozenset({"false", "off", "no", "0", "none", ""})+_process_surface: str | None = None+++def set_process_surface(command: Any) -> None:+ """Called once by the ``hermes`` dispatch (``command`` is the subcommand, None for chat) or the+ TUI gateway (``"tui_gateway"``). Unknown commands clear it."""+ global _process_surface+ _process_surface = "tui_gateway" if command == "tui_gateway" else _COMMAND_SURFACES.get(command)+++def current_surface() -> str | None:+ surface = _process_surface+ if surface == "web":+ from .shared_metrics_setup import web_setup_surface++ return web_setup_surface()+ if surface == "tui_gateway":+ try:+ from tui_gateway.server import _resolve_session_platform++ return _resolve_session_platform()+ except Exception:+ return "tui"+ return surface+++# ---- names -----------------------------------------------------------------------------------++def _bundled_plugin_names() -> frozenset[str]:+ from .shared_metrics_catalog import _REPO_ROOT++ root = _REPO_ROOT / "plugins"+ try:+ return frozenset(+ p.parent.name.lower() for p in [*root.glob("*/plugin.yaml"), *root.glob("*/*/plugin.yaml")]+ )+ except OSError:+ return frozenset()+++def plugin_metric_name(raw: Any) -> str:+ from .shared_metrics_catalog import _norm, _safe, plugin_catalog_names++ name = _norm(raw).rsplit("/", 1)[-1]+ return name if name and (name in _safe(_bundled_plugin_names) or name in _safe(plugin_catalog_names)) else CUSTOM+++def skill_metric_name(raw: Any) -> str:+ from .shared_metrics_catalog import skill_metric_name as catalog_skill_name++ return catalog_skill_name(raw)+++def default_on_settings() -> frozenset[str]:+ """Dotted ``DEFAULT_CONFIG`` paths whose shipped value is ``True`` (the closed setting vocabulary)."""+ from hermes_cli.config import DEFAULT_CONFIG++ from .shared_metrics_contract import FEATURE_DISABLED_NAME_MAX_LENGTH, _metric_identifier++ paths: set[str] = set()++ def walk(node: Any, prefix: str) -> None:+ for key, value in node.items():+ if not isinstance(key, str) or key.startswith("_"):+ continue+ path = f"{prefix}{key}"+ if isinstance(value, dict):+ walk(value, f"{path}.")+ elif value is True and _metric_identifier(path, max_length=FEATURE_DISABLED_NAME_MAX_LENGTH) == path:+ paths.add(path)++ walk(DEFAULT_CONFIG, "")+ return frozenset(paths)+++# ---- transitions -----------------------------------------------------------------------------++def _get(config: Any, path: str) -> Any:+ node = config+ for part in path.split("."):+ if not isinstance(node, dict) or part not in node:+ return True # absent = the shipped default (True for every tracked path)+ node = node[part]+ return node+++def _on(value: Any) -> bool:+ if isinstance(value, str):+ return value.strip().lower() not in _OFF+ return bool(value)+++def _setting_transitions(old: dict, new: dict) -> Iterable[tuple[str, str, str]]:+ for path in sorted(default_on_settings()):+ before, after = _on(_get(old, path)), _on(_get(new, path))+ if before != after:+ yield _SETTING_KINDS.get(path.split(".", 1)[0], "setting"), path, "re_enabled" if after else "disabled"+++def _names(config: Any, section: str, key: str, *, per_platform: str | None = None) -> set[str]:+ from agent.skill_utils import parse_config_string_list++ block = config.get(section) if isinstance(config, dict) else None+ if not isinstance(block, dict):+ return set()+ names = set(parse_config_string_list(block.get(key)) or ())+ platforms = block.get(per_platform) if per_platform else None+ if isinstance(platforms, dict):+ for value in platforms.values():+ names |= set(parse_config_string_list(value) or ())+ return {str(n) for n in names}+++def _plugin_kind(name: str) -> str:+ """A messaging-platform plugin (bundled or catalog) reports as a platform, other plugins as plugins."""+ from .shared_metrics_catalog import _safe, bundled_platform_names, catalog_platform_names++ platforms = _safe(bundled_platform_names) | _safe(catalog_platform_names)+ return "platform" if name.strip().lower().rsplit("/", 1)[-1] in platforms else "plugin"+++def _list_transitions(old_names: set[str], new_names: set[str], kind: str, namer) -> Iterable[tuple[str, str, str]]:+ for names, event in ((new_names - old_names, "disabled"), (old_names - new_names, "re_enabled")):+ for name in sorted(names):+ yield (_plugin_kind(name) if kind == "plugin" else kind), namer(name), event+++def _toolset_transitions(old: dict, new: dict) -> Iterable[tuple[str, str, str]]:+ def scope(config: dict) -> tuple[Any, Any]:+ agent = config.get("agent") if isinstance(config.get("agent"), dict) else {}+ return config.get("platform_toolsets"), agent.get("disabled_toolsets")++ if scope(old) == scope(new):+ return+ from hermes_cli.tools_config import _configurable_keys, _get_platform_tools++ platforms = {"cli"}+ for config in (old, new):+ if isinstance(config.get("platform_toolsets"), dict):+ platforms |= {str(p) for p in config["platform_toolsets"]}+ shipped = _configurable_keys()+ for platform in sorted(platforms):+ default = _get_platform_tools({}, platform, include_default_mcp_servers=False) & shipped+ before = _get_platform_tools(old, platform, include_default_mcp_servers=False)+ after = _get_platform_tools(new, platform, include_default_mcp_servers=False)+ for toolset in sorted(default):+ if (toolset in before) != (toolset in after):+ yield "toolset", toolset, "re_enabled" if toolset in after else "disabled"+++def config_transitions(old: Any, new: Any) -> list[tuple[str, str, str]]:+ """(kind, name, event) for each shipped-on thing the write turned off or back on (deduped)."""+ old = old if isinstance(old, dict) else {}+ new = new if isinstance(new, dict) else {}+ found: list[tuple[str, str, str]] = []+ for batch in (+ _setting_transitions(old, new),+ _list_transitions(_names(old, "skills", "disabled", per_platform="platform_disabled"),+ _names(new, "skills", "disabled", per_platform="platform_disabled"), "skill", skill_metric_name),+ _list_transitions(_names(old, "plugins", "disabled"), _names(new, "plugins", "disabled"), "plugin",+ plugin_metric_name),+ _toolset_transitions(old, new),+ ):+ try:+ found.extend(t for t in batch if t not in found)+ except Exception:+ logger.debug("Feature-disabled transitions skipped", exc_info=True)+ return found+++# ---- recording -------------------------------------------------------------------------------++def _emit(transitions: Iterable[tuple[str, str, str]], surface: str) -> None:+ from .relay_shared_metrics import record_process_mark+ from .shared_metrics_contract import FEATURE_DISABLED_MARK++ for kind, name, event in transitions:+ record_process_mark(FEATURE_DISABLED_MARK, {"event": event, "kind": kind, "name": name, "surface": surface})+++def record_config_saved(old_raw: Any, new_config: Any) -> None:+ """``save_config``'s hook, after the write and outside its lock. Never raises."""+ if _process_surface is None:+ return+ try:+ from .relay_shared_metrics import enabled++ if not enabled() or (surface := current_surface()) is None:+ return+ _emit(config_transitions(old_raw, new_config), surface)+ except Exception:+ logger.debug("Feature-disabled not recorded", exc_info=True)+++def recording_raw_config_write(config_path: Any, user_config: Any, write) -> None:+ """``hermes config set/unset`` write the raw file directly (not via ``save_config``): diff the file+ they replace against what they write. The write itself runs unguarded, so its errors are the caller's."""+ before = None+ if _process_surface is not None:+ try:+ from .relay_shared_metrics import enabled++ if enabled():+ from hermes_cli.config import read_user_config_raw++ before = read_user_config_raw(config_path)+ except Exception:+ logger.debug("Config snapshot for feature-disabled skipped", exc_info=True)+ write(config_path, user_config)+ if before is not None:+ record_config_saved(before, user_config)+++def record_skill_removed(name: Any) -> None:+ """A catalog skill (bundled/optional) was uninstalled; third-party hub skills were never shipped."""+ if _process_surface is None:+ return+ try:+ from .relay_shared_metrics import enabled++ if not enabled() or (surface := current_surface()) is None:+ return+ if (metric_name := skill_metric_name(name)) != CUSTOM:+ _emit([("skill", metric_name, "disabled")], surface)+ except Exception:+ logger.debug("Skill removal not recorded", exc_info=True)diff --git a/hermes_cli/observability/shared_metrics_model.py b/hermes_cli/observability/shared_metrics_model.pyindex 62061ef9ad2..6fcbcc580a4 100644--- a/hermes_cli/observability/shared_metrics_model.py+++ b/hermes_cli/observability/shared_metrics_model.py@@ -165,6 +165,7 @@ def record_tool_call_quality(agent: Any, tool_calls: Iterable[Any], repaired_idsif not tool_calls or not enabled():return+ from .shared_metrics_signals import tool_unavailable_fieldsroute = model_route(getattr(agent, "provider", None), getattr(agent, "model", None))valid_names = getattr(agent, "valid_tool_names", None) or frozenset()required = _required_params(getattr(agent, "tools", None))@@ -175,6 +176,8 @@ def record_tool_call_quality(agent: Any, tool_calls: Iterable[Any], repaired_idsrepaired=id(tc) in repaired_ids or getattr(fn, "args_repaired", False) is True,)record_process_mark(contract.MODEL_TOOL_QUALITY_MARK, {**route, "call_role": "primary", "issue": issue})+ if (unavailable := tool_unavailable_fields(agent, fn.name, issue, route)) is not None:+ record_process_mark(contract.TOOL_UNAVAILABLE_MARK, unavailable)except Exception:logger.debug("Shared-metrics tool-call quality not recorded", exc_info=True)diff --git a/hermes_cli/observability/shared_metrics_process.py b/hermes_cli/observability/shared_metrics_process.pyindex 11ed6c566cf..38929d3afda 100644--- a/hermes_cli/observability/shared_metrics_process.py+++ b/hermes_cli/observability/shared_metrics_process.py@@ -188,9 +188,11 @@ def _report_dead_markers(home: Path, own: Path) -> None:record = Nonerows = [(contract.PROCESS_EXIT_MARK, process_exit_fields(record))] if isinstance(record, dict) else []settle_claim(claimed, path, emit_saved(rows) == len(rows))+ from .shared_metrics_setup import report_abandoned_setupsfrom .shared_metrics_update import report_pending_updatesreport_pending_updates()+ report_abandoned_setups(home)except Exception:logger.debug("Dead process markers not reported", exc_info=True)finally:diff --git a/hermes_cli/observability/shared_metrics_setup.py b/hermes_cli/observability/shared_metrics_setup.pynew file mode 100644index 00000000000..8ac46824366--- /dev/null+++ b/hermes_cli/observability/shared_metrics_setup.py@@ -0,0 +1,390 @@+"""hermes.provider_setup.count: where connecting a model provider starts, succeeds, fails or is walked away from.++A flow is ``started`` once the user has picked a provider. Its end is recorded by the surface that+ran it (``completed`` / ``failed`` + a closed failure class). A flow nobody finished cannot record+itself, so ``started`` also drops a small marker under the owning profile's store dir (the+process-exit pattern): the finisher claims it by rename, and a marker whose process is gone (or that+has been pending longer than any real flow takes) is reported ``abandoned`` by the next setup start+or Hermes start in that profile. Whoever claims the marker records, so each flow ends exactly once.++Only the catalog provider name leaves (custom endpoints read ``custom``); never a key, token, base+URL or error text. Rows are saved synchronously: a setup killed right after ``started`` must still+have left its row, and none of this runs on a hot path.+"""++from __future__ import annotations++import contextlib+import json+import logging+import os+import threading+import time+from dataclasses import dataclass+from pathlib import Path+from typing import Any, Iterator+++logger = logging.getLogger(__name__)++MARKER_DIRNAME = "provider_setup_markers"+# Device codes expire in ~15 minutes; a flow still pending an hour later was left open and forgotten.+STALE_AFTER_S = 3600+# Picker rows that are not a provider (menus, removal) never start a setup flow.+_NOT_A_PROVIDER = frozenset({"aux-config", "cancel", "reasoning", "remove-custom"})+_AUTH_ERROR_TYPES = frozenset({"AuthError", "SignInCopyError"})+_OAUTH_SESSION_KEY = "_metrics_setup_flow"+# OAuth session status (+ reason) at its end -> (event, failure_class).+_OAUTH_ENDINGS = {+ "approved": ("completed", "none"),+ "cancelled": ("failed", "cancelled"),+ "denied": ("failed", "auth"),+ "expired": ("abandoned", "none"),+ "error": ("failed", "other"),+}+_OAUTH_REASONS = {+ "user_declined": ("failed", "cancelled"),+ "superseded": ("failed", "cancelled"),+ "timeout": ("abandoned", "none"),+ "account_retired": ("failed", "auth"),+}+++@dataclass+class SetupFlow:+ home: str+ surface: str+ provider: str # already the catalog metric name+ marker: Path+++def markers_dir(home: Path) -> Path:+ return home / "telemetry" / "shared_metrics" / MARKER_DIRNAME+++def _bound(hermes_home: Any) -> Iterator[None]:+ token = None+ if hermes_home:+ from hermes_constants import set_hermes_home_override++ token = set_hermes_home_override(str(hermes_home))+ try:+ yield+ finally:+ if token is not None:+ from hermes_constants import reset_hermes_home_override++ reset_hermes_home_override(token)+++def collection_enabled(hermes_home: Any = None) -> bool:+ """The owning profile's shared-metrics gate (cheap; lets async callers skip the thread hop)."""+ try:+ with _bound(hermes_home):+ from .relay_shared_metrics import enabled++ return bool(enabled())+ except Exception:+ return False+++def provider_setup_fields(*, surface: Any, provider: Any, event: Any, failure_class: Any = "none") -> dict[str, str] | None:+ from . import shared_metrics_contract as contract+ from .shared_metrics_catalog import provider_metric_name++ if surface not in contract.PROVIDER_SETUP_SURFACES or event not in contract.PROVIDER_SETUP_EVENTS:+ return None+ failure = "none"+ if event == "failed":+ failure = failure_class if failure_class in contract.PROVIDER_SETUP_FAILURE_CLASSES - {"none"} else "other"+ return {"event": event, "failure_class": failure, "provider": provider_metric_name(provider), "surface": surface}+++def setup_failure_class(exc: BaseException) -> str:+ """Closed class for an exception that ended a setup flow; inert (type checks only)."""+ from hermes_cli.auth_error_copy import is_cancelled, is_network_error++ if is_cancelled(exc):+ return "cancelled"+ if is_network_error(exc):+ return "network"+ if {cls.__name__ for cls in type(exc).__mro__} & _AUTH_ERROR_TYPES:+ return "auth"+ return "other"+++def _save_row(fields: dict[str, str] | None) -> bool:+ """Save one row and wait for the store; a row the contract cannot build is settled as is."""+ if fields is None:+ return True+ from .shared_metrics_contract import PROVIDER_SETUP_MARK+ from .shared_metrics_events import emit_saved++ return emit_saved([(PROVIDER_SETUP_MARK, fields)]) == 1+++def begin_provider_setup(surface: str, provider: Any, *, hermes_home: Any = None) -> SetupFlow | None:+ """Record ``started`` and drop the pending marker; None (no files, no rows) when collection is off."""+ try:+ with _bound(hermes_home):+ from .relay_shared_metrics import enabled++ if not provider or provider in _NOT_A_PROVIDER or not enabled():+ return None+ fields = provider_setup_fields(surface=surface, provider=provider, event="started")+ if fields is None:+ return None+ from gateway.status import get_process_start_time+ from hermes_constants import get_hermes_home++ home = get_hermes_home()+ report_abandoned_setups(home)+ directory = markers_dir(home)+ directory.mkdir(parents=True, exist_ok=True)+ pid = os.getpid()+ marker = directory / f"{surface}-{pid}-{time.time_ns()}.json"+ record = {+ "pid": pid, "start_time": get_process_start_time(pid), "started_at": time.time(),+ "surface": surface, "provider": fields["provider"],+ }+ tmp = marker.with_name(f".{marker.name}.tmp")+ tmp.write_text(json.dumps(record), encoding="utf-8")+ os.replace(tmp, marker)+ _save_row(fields)+ return SetupFlow(home=str(home), surface=surface, provider=fields["provider"], marker=marker)+ except Exception:+ logger.debug("Provider setup start not recorded", exc_info=True)+ return None+++def finish_provider_setup(flow: SetupFlow | None, event: str, failure_class: str = "none") -> None:+ """Record the flow's end once: only if its marker is still unclaimed (never raises)."""+ if flow is None:+ return+ try:+ from .shared_metrics_process import settle_claim++ claimed = flow.marker.with_name(f"{flow.marker.name}.{os.getpid()}.reporting")+ try:+ os.replace(flow.marker, claimed)+ except OSError: # already reported (abandoned) by another start+ return+ with _bound(flow.home):+ fields = provider_setup_fields(+ surface=flow.surface, provider=flow.provider, event=event, failure_class=failure_class,+ )+ settle_claim(claimed, flow.marker, _save_row(fields))+ except Exception:+ logger.debug("Provider setup end not recorded", exc_info=True)+++def _reportable(record: Any) -> bool:+ from gateway.status import runtime_status_pid_is_live++ from .shared_metrics_contract import _non_negative_number++ if not isinstance(record, dict):+ return True+ started = _non_negative_number(record.get("started_at"))+ if started is None or time.time() - started > STALE_AFTER_S:+ return True+ return not runtime_status_pid_is_live(record)+++def report_abandoned_setups(home: Path) -> None:+ """Report every pending marker whose flow can no longer finish as ``abandoned``.++ Callers bind ``home`` (the scan runs at a setup start or on the process-exit reporter thread).+ """+ from .shared_metrics_process import _claimer_alive, settle_claim++ directory = markers_dir(home)+ if not directory.is_dir():+ return+ for path in sorted(directory.iterdir()):+ if path.name.startswith(".") or ".json" not in path.name:+ continue+ if path.name.endswith(".reporting") and _claimer_alive(path):+ continue+ try:+ record = json.loads(path.read_text(encoding="utf-8-sig"))+ except (OSError, ValueError):+ record = None+ if not path.name.endswith(".reporting") and not _reportable(record):+ continue+ original = path.with_name(path.name.split(".json")[0] + ".json")+ claimed = original.with_name(f"{original.name}.{os.getpid()}.reporting")+ try:+ os.replace(path, claimed)+ except OSError: # a concurrent reporter or the finisher won+ continue+ fields = provider_setup_fields(+ surface=record.get("surface"), provider=record.get("provider"), event="abandoned",+ ) if isinstance(record, dict) else None+ settle_claim(claimed, original, _save_row(fields))+++def record_provider_setup_done(surface: str, provider: Any, *, hermes_home: Any = None, background: bool = False) -> None:+ """A setup that starts and lands in one action (an API key saved from a form): both rows at once.+ ``background`` keeps a request handler from waiting on a cold metrics runtime; the owning home is+ captured here, since a thread does not inherit the profile binding."""+ try:+ with _bound(hermes_home):+ from .relay_shared_metrics import enabled++ if not provider or not enabled():+ return+ from hermes_constants import get_hermes_home++ home = str(get_hermes_home())++ def run() -> None:+ finish_provider_setup(begin_provider_setup(surface, provider, hermes_home=home), "completed")++ if background:+ threading.Thread(target=run, name="hermes-setup-metrics", daemon=True).start()+ else:+ run()+ except Exception:+ logger.debug("Provider setup not recorded", exc_info=True)+++def provider_for_api_key_env(env_var: Any) -> str | None:+ """The shipped provider whose API key lives in ``env_var``; None for any other variable."""+ from hermes_cli.auth import PROVIDER_REGISTRY++ if env_var == "OPENROUTER_API_KEY": # the aggregator is not a registry entry+ return "openrouter"+ return next((slug for slug, pconfig in PROVIDER_REGISTRY.items()+ if env_var in (getattr(pconfig, "api_key_env_vars", None) or ())), None)+++def record_api_key_saved(env_var: Any, surface: str) -> None:+ """Count a provider API key saved from a settings form (other variables are not setups)."""+ try:+ from .relay_shared_metrics import enabled++ if enabled() and (provider := provider_for_api_key_env(env_var)):+ record_provider_setup_done(surface, provider, background=True)+ except Exception:+ logger.debug("API key setup not recorded", exc_info=True)+++# ---- CLI flows (`hermes setup`, `hermes model`, first-run chat) ------------------------------++_cli = threading.local()+++def note_provider_setup_saved() -> None:+ """A CLI flow persisted the provider/model choice (called by the shared save helpers)."""+ hints = getattr(_cli, "hints", None)+ if hints is not None:+ hints["saved"] = True+++def note_provider_setup_failure(failure_class: str) -> None:+ """A CLI flow reported a failure it then returned from instead of raising (first one wins)."""+ hints = getattr(_cli, "hints", None)+ if hints is not None and hints.get("failure") is None:+ hints["failure"] = failure_class+++def note_sign_in_failure(exc: BaseException) -> None:+ with contextlib.suppress(Exception):+ note_provider_setup_failure(setup_failure_class(exc))+++def _model_route() -> tuple[Any, ...]:+ from hermes_cli.config import load_config++ model = load_config().get("model")+ if not isinstance(model, dict):+ return (model,)+ return tuple(model.get(key) for key in ("provider", "default", "base_url"))+++def provider_setup_surface(surface: str) -> Iterator[None]:+ """Name the surface whose provider picker runs inside (``hermes model``, the setup wizard, the+ first-run chat prompt). The picker is shared, so only these entry points know which one it is."""+ previous = getattr(_cli, "surface", None)+ _cli.surface = surface+ try:+ yield+ finally:+ _cli.surface = previous+++def cli_provider_setup(provider: Any) -> Iterator[None]:+ """Track one CLI provider flow under the entry point's surface. Without one (fallback picking,+ tests driving the picker directly) nothing is tracked.++ Completed when the flow saved a choice or changed the model route; a flow that returns without+ either failed with the class it reported, else the user backed out (``cancelled``).+ """+ surface = getattr(_cli, "surface", None)+ flow = begin_provider_setup(surface, provider) if surface else None+ if flow is None:+ yield+ return+ before = None+ with contextlib.suppress(Exception):+ before = _model_route()+ hints: dict[str, Any] = {"saved": False, "failure": None}+ _cli.hints = hints+ try:+ yield+ except BaseException as exc:+ _cli.hints = None+ finish_provider_setup(flow, "failed", setup_failure_class(exc))+ raise+ _cli.hints = None+ landed = hints["saved"]+ if not landed:+ with contextlib.suppress(Exception):+ landed = before is not None and _model_route() != before+ if landed:+ finish_provider_setup(flow, "completed")+ else:+ finish_provider_setup(flow, "failed", hints["failure"] or "cancelled")+++# ---- dashboard / Desktop OAuth sessions ------------------------------------------------------++def web_setup_surface() -> str:+ from hermes_cli.process_identity import is_desktop_owned_backend++ return "desktop" if is_desktop_owned_backend() else "dashboard"+++def begin_oauth_setup(provider: str, hermes_home: Any) -> SetupFlow | None:+ try:+ return begin_provider_setup(web_setup_surface(), provider, hermes_home=hermes_home)+ except Exception:+ logger.debug("OAuth setup start not recorded", exc_info=True)+ return None+++def attach_oauth_setup(sess: dict[str, Any] | None, flow: SetupFlow | None) -> None:+ if flow is not None and isinstance(sess, dict):+ sess[_OAUTH_SESSION_KEY] = flow+++def settle_oauth_setup(sess: dict[str, Any] | None, *, abandoned: bool = False) -> None:+ """End an OAuth session's flow from its status (no-op while pending, or when already ended)."""+ try:+ if not isinstance(sess, dict) or sess.get(_OAUTH_SESSION_KEY) is None:+ return+ status = "cancelled" if sess.get("cancelled") else str(sess.get("status") or "")+ ending = _OAUTH_REASONS.get(str(sess.get("reason") or "")) if status in {"denied", "error"} else None+ ending = ending or _OAUTH_ENDINGS.get(status)+ if ending is None:+ if not abandoned:+ return+ ending = ("abandoned", "none")+ flow = sess.pop(_OAUTH_SESSION_KEY, None)+ finish_provider_setup(flow, *ending)+ except Exception:+ logger.debug("OAuth setup end not recorded", exc_info=True)diff --git a/hermes_cli/observability/shared_metrics_signals.py b/hermes_cli/observability/shared_metrics_signals.pynew file mode 100644index 00000000000..bc95582b7b1--- /dev/null+++ b/hermes_cli/observability/shared_metrics_signals.py@@ -0,0 +1,141 @@+"""v5 signals: which disabled built-in tools models reach for, and when an install first adopts a feature.++``hermes.tool_unavailable.count`` is counted where the agent validates the calls a model emitted: a+name Hermes ships (``toolsets.BUILTIN_TOOL_NAMES``) that this session did not enable. Any other name+stays the v4 ``unknown_tool`` quality issue only, so a plugin, MCP or hallucinated name never leaves.++``hermes.feature_adoption.count`` rides on counters the subscriber already records: the first counter+row that proves a feature was really used latches it once per install, with the owning profile's age.+Features no counter can see report through :func:`record_feature_used`.+"""++from __future__ import annotations++import logging+import sqlite3+import time+from pathlib import Path+from typing import Any, Callable++from . import shared_metrics_contract as contract++logger = logging.getLogger(__name__)++_DAY_S = 86_400+_DAYS_SINCE_INSTALL_THRESHOLDS = (+ (_DAY_S, "same_day"), (7 * _DAY_S, "1d_to_7d"), (30 * _DAY_S, "7d_to_30d"), (90 * _DAY_S, "30d_to_90d"),+)+++# ---- tool unavailable ------------------------------------------------------------------------++def tool_unavailable_fields(agent: Any, name: Any, issue: str, route: dict[str, str]) -> dict[str, str] | None:+ """Fields for a call to a shipped built-in the session has disabled; None for anything else.++ Background reviews and delegated children run with toolsets Hermes (or the parent model)+ narrowed on purpose, so their misses say nothing about what users should get by default.+ """+ if issue != "unknown_tool" or not isinstance(name, str) or name not in contract.BUILTIN_TOOL_NAMES:+ return None+ if getattr(agent, "_delegate_depth", 0):+ return None+ from tools.skill_provenance import is_background_review++ if is_background_review():+ return None+ return {**route, "tool_name": name}+++# ---- feature adoption ------------------------------------------------------------------------++def _success(d: dict[str, str]) -> bool:+ return d.get("outcome") == "success"+++def _tool(*names: str, prefix: str = "") -> Callable[[dict[str, str]], bool]:+ def used(d: dict[str, str]) -> bool:+ tool = d.get("tool_name") or ""+ return _success(d) and (tool in names or bool(prefix) and tool.startswith(prefix))++ return used+++_TASK_SURFACE = {"desktop": "desktop", "tui": "tui"}+# metric -> [(feature, predicate over the recorded dimensions)]. Unattended Hermes-owned work only+# counts where the user set it up (a cron job, a curator run doing real work).+_FEATURE_RULES: dict[str, tuple[tuple[str, Callable[[dict[str, str]], bool]], ...]] = {+ contract.MEMORY_OP_METRIC: (("memory", lambda d: _success(d) and d.get("origin") == "foreground"),),+ contract.SKILL_LIFECYCLE_METRIC: (("skills_created", lambda d: d.get("action") == "created"),),+ contract.DELEGATION_RUN_METRIC: (("delegation", lambda d: True),),+ contract.CRON_RUN_METRIC: (("cron", lambda d: d.get("outcome") in {"success", "failed"}),),+ contract.CURATOR_RUN_METRIC: (("curator", _success),),+ contract.TASK_STARTED_METRIC: (+ ("gateway_platform", lambda d: d.get("platform") not in {None, "none"}),+ ("desktop", lambda d: d.get("execution_surface") == "desktop"),+ ("tui", lambda d: d.get("execution_surface") == "tui"),+ ),+ contract.TOOL_USAGE_METRIC: (+ ("mcp", _tool("mcp")),+ ("plugins", _tool("plugin")),+ ("browser", _tool(prefix="browser_")),+ ("voice", _tool("text_to_speech")),+ ("kanban", _tool(prefix="kanban_")),+ ("projects", _tool("desktop_project")),+ ),+ contract.SLASH_COMMAND_METRIC: (+ ("voice", lambda d: d.get("command") == "voice"),+ ("kanban", lambda d: d.get("command") == "kanban"),+ ),+ contract.FEATURE_USED_MARK: tuple((feature, lambda d, f=feature: d.get("feature") == f) for feature in sorted(contract.FEATURES)),+}+++def features_for(metric_name: str, dimensions: dict[str, str]) -> tuple[str, ...]:+ """Features a recorded counter proves were used (each is latched once per install by the store)."""+ return tuple(name for name, used in _FEATURE_RULES.get(metric_name, ()) if used(dimensions))+++def days_since_install_bucket(home: Path) -> str:+ """The owning profile's age (its first session), bucketed; ``unknown`` when state.db is unreadable."""+ from .shared_metrics_snapshot import _first_session_started_at++ try:+ first = _first_session_started_at(home)+ except sqlite3.Error:+ return "unknown"+ age = contract._non_negative_number(time.time() - first) if first is not None else None+ return "unknown" if age is None else contract._bucket(age, _DAYS_SINCE_INSTALL_THRESHOLDS, "gte_90d")+++def feature_used_counter(event: Any) -> tuple[str, dict[str, str]] | None:+ """A first-use fact for a feature no counter sees (never stored as a counter row itself)."""+ if not contract._valid_shape(event, **contract._MARK_SHAPE):+ return None+ if contract._event_text(event, "name") != contract.FEATURE_USED_MARK:+ return None+ data = getattr(event, "data", None)+ if not isinstance(data, dict) or set(data) != {"feature"} or data["feature"] not in contract.FEATURES:+ return None+ return contract.FEATURE_USED_MARK, {"feature": data["feature"]}+++def record_feature_used(feature: str, *, hermes_home: Any = None) -> None:+ """Report one real use of ``feature`` (only the first per install becomes a row). Never raises.+ ``hermes_home`` binds the owning profile for callers outside it."""+ token = None+ try:+ if hermes_home:+ from hermes_constants import set_hermes_home_override++ token = set_hermes_home_override(str(hermes_home))+ from .relay_shared_metrics import enabled, record_process_mark++ if feature in contract.FEATURES and enabled():+ record_process_mark(contract.FEATURE_USED_MARK, {"feature": feature})+ except Exception:+ logger.debug("Shared-metrics feature use not recorded", exc_info=True)+ finally:+ if token is not None:+ from hermes_constants import reset_hermes_home_override++ reset_hermes_home_override(token)diff --git a/hermes_cli/observability/shared_metrics_subscriber.py b/hermes_cli/observability/shared_metrics_subscriber.pyindex d7f702e93d8..24bdbacc7bf 100644--- a/hermes_cli/observability/shared_metrics_subscriber.py+++ b/hermes_cli/observability/shared_metrics_subscriber.py@@ -12,11 +12,14 @@ from hermes_cli.config import detect_install_methodfrom hermes_constants import get_hermes_homefrom . import shared_metrics_engagement as engagement+from . import shared_metrics_signals as signalsfrom .shared_metrics import SharedMetricsStorefrom .shared_metrics_fields import milestones_forfrom .shared_metrics_contract import (CLIENT_ACTIVE_METRIC,COMMIT_TICKET_KEY,+ FEATURE_DISABLED_METRIC,+ FEATURE_USED_MARK,INSTALL_SNAPSHOT_METRIC,MODEL_ROUTE_METRIC,TOOL_CALL_METRIC,@@ -48,6 +51,7 @@ _COUNTERS = (tool_approval_counter,skill_counter,decision_counter,+ signals.feature_used_counter,)@@ -76,6 +80,7 @@ class SharedMetricsSubscriber:self._active = Trueself._lock = threading.RLock()self._milestones_done: set[str] = set(store.recorded_milestones())+ self._features_done: set[str] = set(store.recorded_features())self._saved_tickets: dict[str, int] = {}# Events arrive on the Relay thread, which carries no profile binding.self._hermes_home = get_hermes_home()@@ -116,6 +121,33 @@ class SharedMetricsSubscriber:except Exception:logger.warning("Unable to update the Hermes engagement rollup", exc_info=True)+ def _persist(self, metric_name: str, dimensions: dict, amount: int) -> None:+ store, resource = self.store, self._client_resource+ special = {+ FEATURE_USED_MARK: lambda: None, # a first-use fact, not a counter row+ FEATURE_DISABLED_METRIC: lambda: store.record_counter_once_per_day(metric_name, dimensions, resource),+ CLIENT_ACTIVE_METRIC: lambda: store.record_client_active(resource),+ INSTALL_SNAPSHOT_METRIC: lambda: store.record_install_snapshot(dimensions, resource),+ }.get(metric_name)+ if special is not None:+ special()+ else:+ store.record_counter(metric_name, dimensions, resource, amount)++ def _record_features(self, metric_name: str, dimensions: dict) -> None:+ """Latch each feature's first real use (once per install, with the owning profile's age)."""+ reached = [f for f in signals.features_for(metric_name, dimensions) if f not in self._features_done]+ if not reached:+ return+ age = signals.days_since_install_bucket(self._hermes_home)+ for feature in reached:+ try:+ self.store.record_feature_adoption(feature, age, self._client_resource)+ except Exception: # the counter row is saved; a later use retries the latch+ logger.debug("Feature adoption not latched: %s", feature, exc_info=True)+ continue+ self._features_done.add(feature)+def take_saved(self, ticket: str) -> int:"""How many events carrying ``ticket`` settled without a store error (and forget the ticket)."""with self._lock:@@ -138,13 +170,9 @@ class SharedMetricsSubscriber:if not self._active:returntry:- if metric_name == CLIENT_ACTIVE_METRIC:- self.store.record_client_active(self._client_resource)- 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, amount)+ self._persist(metric_name, dimensions, amount)self._record_milestones(metric_name, dimensions)+ self._record_features(metric_name, dimensions)except Exception:saved = Falselogger.warning(diff --git a/hermes_cli/setup.py b/hermes_cli/setup.pyindex 6d0e8fdb4d9..7d64dd53115 100644--- a/hermes_cli/setup.py+++ b/hermes_cli/setup.py@@ -381,8 +381,10 @@ def setup_model_provider(config: dict, *, quick: bool = False):_info("Choose how to connect to your main chat model.",f" Guide: {_DOCS_BASE}/integrations/providers", None)from hermes_cli.main import select_provider_and_model+ from hermes_cli.observability.shared_metrics_setup import provider_setup_surfacetry:- select_provider_and_model()+ with provider_setup_surface("cli_setup"):+ select_provider_and_model()except (SystemExit, KeyboardInterrupt):_info(None, "Provider setup skipped.")except Exception as exc:diff --git a/hermes_cli/web_routers/config_env.py b/hermes_cli/web_routers/config_env.pyindex d7a36b28e5d..f945a4f94f6 100644--- a/hermes_cli/web_routers/config_env.py+++ b/hermes_cli/web_routers/config_env.py@@ -335,11 +335,17 @@ async def set_env_var(body: EnvVarUpdate, profile: Optional[str] = None):if is_redacted_credential_preview(body.value):raise HTTPException(status_code=400, detail=REDACTED_CREDENTIAL_WRITE_DETAIL)with _env_write_errors("PUT /api/env failed"):- from hermes_cli.credential_lifecycle import save_provider_env_credential+ return await scoped_to_thread(body.profile or profile, lambda: _save_env_credential(body.key, body.value))- return await scoped_to_thread(- body.profile or profile, lambda: save_provider_env_credential(body.key, body.value)- )++def _save_env_credential(key: str, value: str) -> Any:+ """Save under the request's profile scope; a provider API key also counts as a provider setup."""+ from hermes_cli.credential_lifecycle import save_provider_env_credential+ from hermes_cli.observability.shared_metrics_setup import record_api_key_saved, web_setup_surface++ result = save_provider_env_credential(key, value)+ record_api_key_saved(key, web_setup_surface())+ return result# Live credential probes keyed by env var: (url, auth) where auth is "bearer"@@ -721,11 +727,21 @@ def upsert_custom_endpoint(body: CustomEndpointUpdate, profile: Optional[str] =endpoint_id, _entry = _write_custom_endpoint(cfg, body)save_config(cfg)response = _custom_endpoint_response(cfg)+ from hermes_constants import get_hermes_home+ home = get_hermes_home()+ _record_custom_endpoint_setup(home)response["ok"] = Trueresponse["id"] = endpoint_idreturn response+def _record_custom_endpoint_setup(home: Any) -> None:+ """Counted after the config lock is released (a cold metrics runtime must not stall writers)."""+ from hermes_cli.observability.shared_metrics_setup import record_provider_setup_done, web_setup_surface++ record_provider_setup_done(web_setup_surface(), "custom", hermes_home=home, background=True)++@router.post("/api/providers/custom-endpoints/{endpoint_id}/activate")def activate_custom_endpoint(endpoint_id: str, profile: Optional[str] = None):"""Set a configured custom endpoint as the default model provider."""diff --git a/hermes_cli/web_routers/oauth.py b/hermes_cli/web_routers/oauth.pyindex 027f42c2f64..a7caf6b4012 100644--- a/hermes_cli/web_routers/oauth.py+++ b/hermes_cli/web_routers/oauth.py@@ -107,7 +107,31 @@ def _drop_oauth_session(sid: str) -> None:def _start_poller(target, sid: str, prefix: str = "oauth-poll") -> None:- threading.Thread(target=target, args=(sid,), daemon=True, name=f"{prefix}-{sid[:6]}").start()+ with _oauth_sessions_lock:+ sess = _oauth_sessions.get(sid)++ def run() -> None:+ try:+ target(sid)+ finally: # the session's status is final once its poller returns+ from hermes_cli.observability.shared_metrics_setup import settle_oauth_setup+ settle_oauth_setup(sess)++ threading.Thread(target=run, daemon=True, name=f"{prefix}-{sid[:6]}").start()+++def _track_oauth_setup(flow, session_id: str) -> None:+ """Hand the setup flow to its session; settle it now if the poller already ended."""+ from hermes_cli.observability.shared_metrics_setup import (+ attach_oauth_setup, finish_provider_setup, settle_oauth_setup,+ )+ with _oauth_sessions_lock:+ sess = _oauth_sessions.get(session_id)+ if sess is None: # cancelled before the start response even returned+ finish_provider_setup(flow, "failed", "cancelled")+ return+ attach_oauth_setup(sess, flow)+ settle_oauth_setup(sess)def _device_session_started(@@ -776,15 +800,45 @@ async def start_oauth_login(provider_id: str, request: Request, profile: Optionaraise HTTPException(status_code=400, detail=f"Unknown provider {provider_id}")if catalog_entry["flow"] == "external":raise HTTPException(400, f"{provider_id} uses an external CLI; run `{catalog_entry['cli_command']}` manually")+ if catalog_entry["flow"] != "device_code":+ raise HTTPException(status_code=400, detail="Unsupported flow")+ flow = await _begin_oauth_setup_metric(provider_id, profile)try:- if catalog_entry["flow"] == "device_code":- return await _start_device_code_flow(provider_id, profile=profile)- except HTTPException:- raise+ body = await _start_device_code_flow(provider_id, profile=profile)except Exception as e:+ await _end_oauth_setup_metric(flow, e)+ if isinstance(e, HTTPException):+ raise_log.exception("oauth/start %s failed", provider_id)raise HTTPException(status_code=500, detail=str(e))- raise HTTPException(status_code=400, detail="Unsupported flow")+ if flow is not None:+ await asyncio.get_running_loop().run_in_executor(None, _track_oauth_setup, flow, body["session_id"])+ return body+++async def _begin_oauth_setup_metric(provider_id: str, profile: Optional[str]):+ """Start the provider-setup metric off the event loop (a cold metrics runtime blocks); None when the+ owning profile does not collect. Never raises: the start route's own validation owns errors."""+ from hermes_cli.observability.shared_metrics_setup import begin_oauth_setup, collection_enabled+ try:+ profile_name = _oauth_profile_name(profile)+ home = _resolve_profile_dir(profile_name) if profile_name else None+ if not collection_enabled(home):+ return None+ return await asyncio.get_running_loop().run_in_executor(None, begin_oauth_setup, provider_id, home)+ except Exception:+ return None+++async def _end_oauth_setup_metric(flow, exc: Exception) -> None:+ if flow is None:+ return+ from hermes_cli.observability.shared_metrics_setup import finish_provider_setup, setup_failure_class+ with contextlib.suppress(Exception):+ # A 401/403 from the start route is the provider refusing this account/client.+ refused = isinstance(exc, HTTPException) and exc.status_code in {401, 403}+ failure = "auth" if refused else setup_failure_class(exc)+ await asyncio.get_running_loop().run_in_executor(None, finish_provider_setup, flow, "failed", failure)@router.post("/api/providers/oauth/{provider_id}/submit")diff --git a/tests/hermes_cli/test_shared_metrics_signals.py b/tests/hermes_cli/test_shared_metrics_signals.pynew file mode 100644index 00000000000..cf65adcf01c--- /dev/null+++ b/tests/hermes_cli/test_shared_metrics_signals.py@@ -0,0 +1,324 @@+"""v5 signals: hermes.tool_unavailable.count, hermes.provider_setup.count, hermes.feature_adoption.count."""++from __future__ import annotations++import json+import os+import subprocess+import sys+import time+from types import SimpleNamespace++import pytest++from hermes_cli.observability import relay_shared_metrics+from hermes_cli.observability import shared_metrics_contract as contract+from hermes_cli.observability import shared_metrics_setup as setup_metrics+from hermes_cli.observability import shared_metrics_signals as signals+from hermes_cli.observability.shared_metrics import SharedMetricsStore+++def marks(tmp_path, monkeypatch):+ captured: list[tuple[str, dict]] = []+ policy = {"on": True}+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))+ monkeypatch.setattr(relay_shared_metrics, "enabled", lambda: policy["on"])+ monkeypatch.setattr(relay_shared_metrics, "record_process_mark", lambda mark, data: captured.append((mark, data)))++ def saved(rows):+ captured.extend(rows)+ return len(rows)++ monkeypatch.setattr(relay_shared_metrics, "record_process_marks_saved", saved, raising=False)+ yield SimpleNamespace(rows=captured, policy=policy, home=tmp_path / "home")+++def _setup_rows(rows):+ assert all(contract.counter_dimensions_are_valid(contract.PROVIDER_SETUP_METRIC, d) for _, d in rows), rows+ return [(d["surface"], d["provider"], d["event"], d["failure_class"]) for m, d in rows+ if m == contract.PROVIDER_SETUP_MARK]+++def _dead_pid() -> int:+ child = subprocess.Popen([sys.executable, "-c", "pass"])+ child.wait()+ return child.pid+++# ---- tool unavailable ----++def test_only_a_disabled_shipped_builtin_is_reported(monkeypatch):+ monkeypatch.setattr("tools.skill_provenance.is_background_review", lambda: False)+ route = {"model": "m", "provider": "openrouter"}+ agent = SimpleNamespace(_delegate_depth=0)+ fields = signals.tool_unavailable_fields(agent, "browser_navigate", "unknown_tool", route)+ assert fields == {"model": "m", "provider": "openrouter", "tool_name": "browser_navigate"}+ assert contract.counter_dimensions_are_valid(contract.TOOL_UNAVAILABLE_METRIC, fields)+ # Not shipped (plugin/MCP/hallucinated): stays v4 unknown_tool only.+ assert signals.tool_unavailable_fields(agent, "mcp_github_search", "unknown_tool", route) is None+ assert signals.tool_unavailable_fields(agent, "browser_navigate", "invalid_json", route) is None+ assert signals.tool_unavailable_fields(SimpleNamespace(_delegate_depth=1), "memory", "unknown_tool", route) is None+ monkeypatch.setattr("tools.skill_provenance.is_background_review", lambda: True)+ assert signals.tool_unavailable_fields(agent, "memory", "unknown_tool", route) is None+++def test_turn_validation_reports_disabled_builtin_once_and_unknown_names_never(marks, monkeypatch):+ from hermes_cli.observability.shared_metrics_model import record_tool_call_quality++ monkeypatch.setattr("tools.skill_provenance.is_background_review", lambda: False)+ agent = SimpleNamespace(provider="openrouter", model="anthropic/claude-sonnet-4", valid_tool_names={"memory"},+ tools=[], _delegate_depth=0)+ calls = [SimpleNamespace(function=SimpleNamespace(name=n, arguments="{}"))+ for n in ("browser_navigate", "memory", "my_plugin_tool")]+ record_tool_call_quality(agent, calls, set())+ unavailable = [d for m, d in marks.rows if m == contract.TOOL_UNAVAILABLE_MARK]+ assert unavailable == [{"model": unavailable[0]["model"], "provider": "openrouter", "tool_name": "browser_navigate"}]+ assert contract.counter_dimensions_are_valid(contract.TOOL_UNAVAILABLE_METRIC, unavailable[0])+++# ---- feature adoption ----++def test_counter_rows_map_to_features():+ assert signals.features_for(contract.MEMORY_OP_METRIC, {"origin": "foreground", "outcome": "success"}) == ("memory",)+ assert signals.features_for(contract.MEMORY_OP_METRIC, {"origin": "background_review", "outcome": "success"}) == ()+ assert signals.features_for(contract.TOOL_USAGE_METRIC, {"tool_name": "mcp", "outcome": "success"}) == ("mcp",)+ assert signals.features_for(contract.TOOL_USAGE_METRIC, {"tool_name": "browser_click", "outcome": "failed"}) == ()+ assert signals.features_for(contract.TOOL_USAGE_METRIC, {"tool_name": "kanban_create", "outcome": "success"}) == ("kanban",)+ assert set(signals.features_for(contract.TASK_STARTED_METRIC, {"platform": "telegram", "execution_surface": "desktop"})) \+ == {"gateway_platform", "desktop"}+ assert signals.features_for(contract.FEATURE_USED_MARK, {"feature": "bot_mode"}) == ("bot_mode",)++[email protected](("age_s", "bucket"), [+ (60, "same_day"), (2 * 86_400, "1d_to_7d"), (10 * 86_400, "7d_to_30d"), (40 * 86_400, "30d_to_90d"),+ (200 * 86_400, "gte_90d"),+])+def test_days_since_install_bucket(monkeypatch, tmp_path, age_s, bucket):+ monkeypatch.setattr("hermes_cli.observability.shared_metrics_snapshot._first_session_started_at",+ lambda home: time.time() - age_s)+ assert signals.days_since_install_bucket(tmp_path) == bucket+++def test_feature_adoption_latches_once_per_install(tmp_path):+ resource = {"hermes_version": "1.0.0", "os_family": "linux", "architecture": "x86_64", "install_method": "git"}+ store = SharedMetricsStore(tmp_path / "m.sqlite3", tmp_path / "outbox")+ assert store.record_feature_adoption("memory", "same_day", resource) is True+ again = SharedMetricsStore(tmp_path / "m.sqlite3", tmp_path / "outbox")+ assert again.record_feature_adoption("memory", "1d_to_7d", resource) is False+ assert again.recorded_features() == frozenset({"memory"})+ with pytest.raises(ValueError):+ store.record_feature_adoption("not_a_feature", "same_day", resource)+++def test_feature_used_mark_projection_and_disabled_gate(marks):+ event = SimpleNamespace(kind="mark", name=contract.FEATURE_USED_MARK, data={"feature": "projects"})+ signals.record_feature_used("projects")+ signals.record_feature_used("nope")+ assert marks.rows == [(contract.FEATURE_USED_MARK, {"feature": "projects"})]+ marks.policy["on"] = False+ signals.record_feature_used("projects")+ assert len(marks.rows) == 1+ projected = signals.feature_used_counter(event)+ assert projected in (None, (contract.FEATURE_USED_MARK, {"feature": "projects"}))+++# ---- provider setup ----++def test_started_then_completed_once_and_marker_cleared(marks):+ flow = setup_metrics.begin_provider_setup("cli_model", "openrouter")+ assert flow is not None and flow.marker.exists()+ setup_metrics.finish_provider_setup(flow, "completed")+ setup_metrics.finish_provider_setup(flow, "failed", "auth") # already ended+ assert _setup_rows(marks.rows) == [+ ("cli_model", "openrouter", "started", "none"), ("cli_model", "openrouter", "completed", "none")]+ assert not list(setup_metrics.markers_dir(marks.home).iterdir())+++def test_custom_endpoint_reads_custom_and_no_raw_values(marks):+ setup_metrics.finish_provider_setup(setup_metrics.begin_provider_setup("desktop", "custom:my-box"), "completed")+ assert {row[1] for row in _setup_rows(marks.rows)} == {"custom"}+++def test_disabled_collection_writes_nothing(marks):+ marks.policy["on"] = False+ assert setup_metrics.begin_provider_setup("cli_setup", "openrouter") is None+ assert marks.rows == [] and not setup_metrics.markers_dir(marks.home).exists()+++def test_dead_or_stale_marker_is_abandoned_at_the_next_start_and_live_waits(marks):+ from gateway.status import get_process_start_time++ directory = setup_metrics.markers_dir(marks.home)+ directory.mkdir(parents=True)+ now = time.time()+ (directory / "cli_setup-1-1.json").write_text(json.dumps(+ {"pid": _dead_pid(), "start_time": None, "started_at": now, "surface": "cli_setup", "provider": "anthropic"}))+ parent = os.getppid()+ live = directory / f"tui-{parent}-2.json"+ live.write_text(json.dumps({"pid": parent, "start_time": get_process_start_time(parent), "started_at": now,+ "surface": "tui", "provider": "nous"}))+ (directory / f"dashboard-{parent}-3.json").write_text(json.dumps(+ {"pid": parent, "start_time": get_process_start_time(parent), "started_at": now - 2 * setup_metrics.STALE_AFTER_S,+ "surface": "dashboard", "provider": "xai"}))++ flow = setup_metrics.begin_provider_setup("cli_setup", "openrouter")+ setup_metrics.report_abandoned_setups(marks.home)+ rows = _setup_rows(marks.rows)+ assert sorted(r for r in rows if r[2] == "abandoned") == [+ ("cli_setup", "anthropic", "abandoned", "none"), ("dashboard", "xai", "abandoned", "none")]+ assert live.exists() and flow.marker.exists()+++def test_cli_flow_classifies_landed_backed_out_failed_and_raised(marks, monkeypatch):+ route = {"v": ("openrouter", "a", None)}+ monkeypatch.setattr(setup_metrics, "_model_route", lambda: route["v"])++ with setup_metrics.cli_provider_setup("openrouter"): # no entry-point surface: untracked+ pass+ assert marks.rows == []++ with setup_metrics.provider_setup_surface("cli_setup"):+ with setup_metrics.cli_provider_setup("anthropic"):+ setup_metrics.note_provider_setup_saved()+ with setup_metrics.cli_provider_setup("anthropic"):+ pass # returned without saving: backed out+ with setup_metrics.cli_provider_setup("nous"):+ setup_metrics.note_provider_setup_failure("no_models")+ with setup_metrics.cli_provider_setup("gemini"):+ route["v"] = ("gemini", "g", None) # route changed without the save helper+ with pytest.raises(KeyboardInterrupt):+ with setup_metrics.cli_provider_setup("xai"):+ raise KeyboardInterrupt+ with pytest.raises(ConnectionError):+ with setup_metrics.cli_provider_setup("xai"):+ raise ConnectionError("down")+ with setup_metrics.cli_provider_setup("remove-custom"):+ pass+ ends = [r for r in _setup_rows(marks.rows) if r[2] != "started"]+ assert ends == [+ ("cli_setup", "anthropic", "completed", "none"), ("cli_setup", "anthropic", "failed", "cancelled"),+ ("cli_setup", "nous", "failed", "no_models"), ("cli_setup", "gemini", "completed", "none"),+ ("cli_setup", "xai", "failed", "cancelled"), ("cli_setup", "xai", "failed", "network"),+ ]+ setup_metrics.note_provider_setup_saved() # outside a flow: inert++[email protected](("sess", "ending"), [+ ({"status": "approved"}, ("completed", "none")),+ ({"status": "expired"}, ("abandoned", "none")),+ ({"status": "error", "reason": "timeout"}, ("abandoned", "none")),+ ({"status": "denied"}, ("failed", "auth")),+ ({"status": "denied", "reason": "user_declined"}, ("failed", "cancelled")),+ ({"status": "pending", "cancelled": True}, ("failed", "cancelled")),+])+def test_oauth_session_endings(marks, monkeypatch, sess, ending):+ monkeypatch.setattr(setup_metrics, "web_setup_surface", lambda: "desktop")+ flow = setup_metrics.begin_oauth_setup("nous", None)+ setup_metrics.attach_oauth_setup(sess, flow)+ setup_metrics.settle_oauth_setup(sess)+ setup_metrics.settle_oauth_setup(sess)+ assert [r[2:] for r in _setup_rows(marks.rows)] == [("started", "none"), ending]+++def test_pending_oauth_session_does_not_settle(marks, monkeypatch):+ monkeypatch.setattr(setup_metrics, "web_setup_surface", lambda: "dashboard")+ sess = {"status": "pending"}+ setup_metrics.attach_oauth_setup(sess, setup_metrics.begin_oauth_setup("xai", None))+ setup_metrics.settle_oauth_setup(sess)+ assert [r[2] for r in _setup_rows(marks.rows)] == ["started"]+++def test_api_key_env_maps_to_provider_only():+ assert setup_metrics.provider_for_api_key_env("OPENROUTER_API_KEY") == "openrouter"+ assert setup_metrics.provider_for_api_key_env("GITHUB_TOKEN_FOR_TOOLS_XYZ") is None+++# ---- feature disabled ----++from hermes_cli.observability import shared_metrics_disabled as disabled_metrics # noqa: E402+++def test_settings_skills_plugins_transitions_only_count_moves_from_and_back_to_default():+ old = {"skills": {"disabled": ["my-private-skill"]}, "plugins": {"disabled": []}}+ new = {+ "memory": {"memory_enabled": False}, "compression": {"enabled": "false"}, "curator": {"enabled": True},+ "display": {"show_reasoning": False, "skin": "mono"}, # a value change on a non-bool: never a row+ "skills": {"disabled": ["my-private-skill", "arxiv"], "platform_disabled": {"telegram": ["totally-custom"]}},+ "plugins": {"disabled": ["disk-cleanup", "telegram", "some-private-plugin"]},+ }+ got = set(disabled_metrics.config_transitions(old, new))+ assert got == {+ ("memory", "memory.memory_enabled", "disabled"), ("compression", "compression.enabled", "disabled"),+ ("setting", "display.show_reasoning", "disabled"),+ ("skill", "arxiv", "disabled"), ("skill", "custom", "disabled"),+ ("plugin", "disk-cleanup", "disabled"), ("platform", "telegram", "disabled"),+ ("plugin", "custom", "disabled"),+ }+ back = set(disabled_metrics.config_transitions(new, old))+ assert ("memory", "memory.memory_enabled", "re_enabled") in back and ("skill", "arxiv", "re_enabled") in back+ assert all(contract.counter_dimensions_are_valid(contract.FEATURE_DISABLED_METRIC, {+ "event": e, "kind": k, "name": n, "surface": "cli_config"}) for k, n, e in got | back)+++def test_toolset_transitions_use_the_real_resolver():+ from hermes_cli.tools_config import _get_platform_tools++ default = sorted(_get_platform_tools({}, "cli", include_default_mcp_servers=False))+ assert "memory" in default+ new = {"platform_toolsets": {"cli": [t for t in default if t != "memory"]}}+ assert ("toolset", "memory", "disabled") in disabled_metrics.config_transitions({}, new)+ assert ("toolset", "memory", "re_enabled") in disabled_metrics.config_transitions(new, {})+ assert disabled_metrics.config_transitions({}, {"platform_toolsets": {"cli": default}}) == []+++def test_record_config_saved_needs_a_surface_and_collection(marks, monkeypatch):+ monkeypatch.setattr(disabled_metrics, "_process_surface", None)+ disabled_metrics.record_config_saved({}, {"memory": {"memory_enabled": False}})+ assert marks.rows == [] # setup/migration writes: no entry-point surface+ disabled_metrics.set_process_surface("config")+ marks.policy["on"] = False+ disabled_metrics.record_config_saved({}, {"memory": {"memory_enabled": False}})+ assert marks.rows == []+ marks.policy["on"] = True+ disabled_metrics.record_config_saved({}, {"memory": {"memory_enabled": False}})+ assert marks.rows == [(contract.FEATURE_DISABLED_MARK, {+ "event": "disabled", "kind": "memory", "name": "memory.memory_enabled", "surface": "cli_config"})]+ disabled_metrics.set_process_surface(None)+ assert disabled_metrics.current_surface() == "cli_slash"+++def test_store_counts_feature_disabled_once_per_day(tmp_path):+ resource = {"hermes_version": "1.0.0", "os_family": "linux", "architecture": "x86_64", "install_method": "git"}+ store = SharedMetricsStore(tmp_path / "m.sqlite3", tmp_path / "outbox")+ dims = {"event": "disabled", "kind": "toolset", "name": "memory", "surface": "cli_tools"}+ assert store.record_counter_once_per_day(contract.FEATURE_DISABLED_METRIC, dims, resource) is True+ assert store.record_counter_once_per_day(+ contract.FEATURE_DISABLED_METRIC, {**dims, "surface": "desktop"}, resource) is False+ assert store.record_counter_once_per_day(+ contract.FEATURE_DISABLED_METRIC, {**dims, "event": "re_enabled"}, resource) is True+++def test_real_config_writes_report_the_move_away_from_default(marks, monkeypatch):+ from hermes_cli.config import load_config, save_config, set_config_value++ marks.home.mkdir(parents=True, exist_ok=True)+ monkeypatch.setattr(disabled_metrics, "_process_surface", "cli_config")+ config = load_config()+ config.setdefault("memory", {})["memory_enabled"] = False+ save_config(config)+ set_config_value("curator.enabled", "false")+ rows = [(d["kind"], d["name"], d["event"]) for m, d in marks.rows if m == contract.FEATURE_DISABLED_MARK]+ assert rows == [("memory", "memory.memory_enabled", "disabled"), ("curator", "curator.enabled", "disabled")]+++def test_off_thread_setup_records_in_the_owning_profile(marks, tmp_path, monkeypatch):+ seen: list[str] = []+ monkeypatch.setattr(relay_shared_metrics, "record_process_marks_saved", lambda rows: (+ seen.append(str(__import__("hermes_constants").get_hermes_home())), len(rows))[1])+ home_a, home_b = tmp_path / "a", tmp_path / "b"+ for home in (home_a, home_b, home_a):+ flow = setup_metrics.begin_provider_setup("dashboard", "xai", hermes_home=home)+ assert flow.marker.parent == setup_metrics.markers_dir(home)+ setup_metrics.finish_provider_setup(flow, "completed")+ assert seen == [str(h) for h in (home_a, home_a, home_b, home_b, home_a, home_a)]diff --git a/tools/bot_mode_dm.py b/tools/bot_mode_dm.pyindex 2b595ac5269..8e69f24867b 100644--- a/tools/bot_mode_dm.py+++ b/tools/bot_mode_dm.py@@ -214,6 +214,8 @@ def message_agent_tool(target: str = "", message: str = "", task_id: Optional[st"message_agent is unavailable. Do not retry.")except Exception as exc: # pragma: no cover — defensivereturn _err(f"Bot Mode gate check failed: {exc}")+ from hermes_cli.observability.shared_metrics_signals import record_feature_used+ record_feature_used("bot_mode", hermes_home=home)root, me = _hermes_root(Path(home)), _self_profile_name(Path(home))roster_homes = dict(_roster(root))diff --git a/tools/skills_hub_install.py b/tools/skills_hub_install.pyindex 04d82a3426d..e82b0f056fe 100644--- a/tools/skills_hub_install.py+++ b/tools/skills_hub_install.py@@ -219,6 +219,8 @@ def uninstall_skill(skill_name: str) -> Tuple[bool, str]:shutil.rmtree(install_path)lock.record_uninstall(skill_name)append_audit_log("UNINSTALL", skill_name, entry["source"], entry["trust_level"], "n/a", "user_request")+ from hermes_cli.observability.shared_metrics_disabled import record_skill_removed+ record_skill_removed(skill_name)return True, f"Uninstalled '{skill_name}' from {entry['install_path']}"diff --git a/tui_gateway/entry.py b/tui_gateway/entry.pyindex 196db5f9c0e..b09f0acb3e0 100644--- a/tui_gateway/entry.py+++ b/tui_gateway/entry.py@@ -282,6 +282,8 @@ def main():from hermes_cli.observability.shared_metrics_process import begin_processbegin_process("tui")+ from hermes_cli.observability.shared_metrics_disabled import set_process_surface+ set_process_surface("tui_gateway")# One TLS authority: trust the OS store process-wide before any# outbound call resolves a CA bundle (see agent/ssl_verify.py).diff --git a/tui_gateway/methods_complete.py b/tui_gateway/methods_complete.pyindex 5058cc6ff88..b3b767d7964 100644--- a/tui_gateway/methods_complete.py+++ b/tui_gateway/methods_complete.py@@ -373,6 +373,8 @@ def _(rid, params: dict) -> dict:# Under the profile scope the save publishes into the addressed profile's secret scope (and the# shared os.environ only for the launch profile), so the refreshed inventory below sees it.save_provider_env_credential(env_var, api_key)+ from hermes_cli.observability.shared_metrics_setup import record_provider_setup_done+ record_provider_setup_done(_resolve_session_platform(), slug, background=True)# The launch profile's boot record may still say "nothing configured"; the gated picker's own chat# waits on setup.status, so the fresh key must move the record (+ setup.ready). reconcile_record# leaves it alone when the bound home is another profile's.diff --git a/tui_gateway/methods_projects.py b/tui_gateway/methods_projects.pyindex 3b41d21d4d3..7f8ea13bc08 100644--- a/tui_gateway/methods_projects.py+++ b/tui_gateway/methods_projects.py@@ -95,6 +95,8 @@ def _(rid, params, pdb, conn) -> dict:**_pick(params, "slug", "primary_path", "description", "icon", "color", "board_slug"))if params.get("use"):pdb.set_active(conn, pid)+ from hermes_cli.observability.shared_metrics_signals import record_feature_used+ record_feature_used("projects")proj = pdb.get_project(conn, pid)return _ok(rid, {"project": proj.to_dict() if proj else None})diff --git a/website/docs/developer-guide/relay-shared-metrics.md b/website/docs/developer-guide/relay-shared-metrics.mdindex 8e890e7c6f0..0732d89ffb3 100644--- a/website/docs/developer-guide/relay-shared-metrics.md+++ b/website/docs/developer-guide/relay-shared-metrics.md@@ -425,6 +425,17 @@ idle, with `0` active minutes and surfaces); every other profile's row readsdatabase and the count is not reported.<!-- ---- end v5 engagement ---- -->+<!-- ---- v5 signals ---- -->+#### Onboarding and feature signals++| Metric | Dimensions | Question it answers |+|---|---|---|+| `hermes.tool_unavailable.count` | provider, model, tool name (shipped built-ins only) | Which toolsets should be on by default: the model called a tool Hermes ships that this session did not enable. Any other unknown name (plugin, MCP, hallucinated) stays a `model_tool_quality` `unknown_tool` issue only. Background reviews and delegated children, whose toolsets are narrowed on purpose, are excluded. |+| `hermes.provider_setup.count` | provider (catalog name; custom endpoints read `custom`), surface (`cli_setup`, `cli_model`, `tui`, `desktop`, `dashboard`), event (`started`, `completed`, `failed`, `abandoned`), failure class (`auth`, `network`, `no_models`, `cancelled`, `other`; `none` unless failed) | Where connecting a provider breaks down. `started` counts once a provider is picked; the flow's end is recorded by the surface that ran it. A flow nobody finished leaves a local marker that the next setup start or Hermes start in the profile reports as `abandoned` (its process is gone, or it has been pending over an hour); an OAuth device code left to expire is also `abandoned`. API keys saved from a form (TUI/Desktop/dashboard) and custom endpoints start and complete in one action. Never a key, token, base URL or error text. Leaving the provider picker before choosing one is not counted. |+| `hermes.feature_adoption.count` | feature (`memory`, `skills_created`, `delegation`, `cron`, `gateway_platform`, `desktop`, `tui`, `mcp`, `plugins`, `browser`, `voice`, `kanban`, `projects`, `bot_mode`, `curator`), days since install (`same_day`, `1d_to_7d`, `7d_to_30d`, `30d_to_90d`, `gte_90d`, `unknown`) | How long after install each major feature is first really used. Once per feature per install, latched in the local database, derived from the counters above (a foreground memory write, a created skill, a successful MCP/plugin/browser/TTS/kanban tool call, a Desktop/TUI/gateway task, a cron run, a curator run) plus direct first-use reports for Bot Mode messages and project creation. The age is the owning profile's (its first session). |+| `hermes.feature_disabled.count` | kind (`toolset`, `skill`, `plugin`, `platform`, `setting`, `memory`, `curator`, `compression`), name, surface (`cli_tools`, `cli_config`, `cli_slash`, `tui`, `desktop`, `dashboard`), event (`disabled`, `re_enabled`) | What users turn off. Diffed at the config write itself: a default-on toolset removed, a skill or plugin added to its disabled list, a default-`true` setting set false (and each moved back). Names are public only when shipped — toolset key, bundled/catalog skill, bundled/catalog plugin (messaging-platform plugins report as `platform`), `DEFAULT_CONFIG` key path (never a value) — else `custom`. Uninstalling a catalog skill counts as `disabled`. Only user entry points record (`hermes tools` / `config` / `skills` / `plugins`, chat slash commands, TUI/Desktop, dashboard); setup and migrations do not. At most once per (kind, name, event) per day. |+<!-- ---- end v5 signals ---- -->+Local state is written under:```text