shared_metrics_snapshot.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. """Collect the once-a-day install configuration snapshot for shared metrics.
  2. Only counts, closed enums (terminal backend, bundled memory provider, shipped locale), the main
  3. provider id and the profile's age are read out; server names, plugin names, skill names, job
  4. prompts and profile names stay local (the contract buckets every count).
  5. """
  6. from __future__ import annotations
  7. import contextlib
  8. import json
  9. import sqlite3
  10. import time
  11. from itertools import islice
  12. from pathlib import Path
  13. from typing import Any
  14. from hermes_constants import get_hermes_home
  15. from . import shared_metrics_contract as contract
  16. # The largest bucket starts at 251: counting past it only costs I/O.
  17. _COUNT_CAP = 251
  18. def _sub(config: Any, key: str) -> Any:
  19. return config.get(key) if isinstance(config, dict) else None
  20. def _mcp_server_count(config: dict[str, Any]) -> int:
  21. servers = _sub(config, "mcp_servers")
  22. if not isinstance(servers, dict):
  23. return 0
  24. return sum(1 for spec in servers.values() if not (isinstance(spec, dict) and spec.get("enabled") is False))
  25. def _plugin_count(config: dict[str, Any]) -> int:
  26. enabled = _sub(_sub(config, "plugins"), "enabled")
  27. return len(enabled) if isinstance(enabled, list) else 0
  28. def _cron_job_count() -> int:
  29. try:
  30. # utf-8-sig: same dialect as cron/jobs.load_jobs (Windows editors may leave a BOM).
  31. with open(get_hermes_home() / "cron" / "jobs.json", encoding="utf-8-sig") as handle:
  32. jobs = json.load(handle).get("jobs", [])
  33. except (OSError, ValueError, AttributeError):
  34. return 0
  35. return sum(1 for job in jobs if isinstance(job, dict) and job.get("enabled", True))
  36. def _skill_count() -> int:
  37. from agent.skill_utils import iter_skill_index_files
  38. skills_dir = get_hermes_home() / "skills"
  39. if not skills_dir.is_dir():
  40. return 0
  41. return sum(1 for _ in islice(iter_skill_index_files(skills_dir, "SKILL.md"), _COUNT_CAP))
  42. def _profile_count() -> int:
  43. from hermes_cli.profiles import list_profile_names
  44. return len(list_profile_names())
  45. def _messaging_platform_count() -> int:
  46. from gateway.config import load_gateway_config
  47. return len(load_gateway_config().get_connected_platforms())
  48. def _display_language() -> str:
  49. from agent.i18n import get_language
  50. return get_language()
  51. def _safe_count(reader) -> int:
  52. try:
  53. return reader()
  54. except Exception:
  55. return 0
  56. # The profile's first session never moves once it exists, so it is read from state.db once.
  57. _first_session_at: dict[str, float] = {}
  58. def _first_session_started_at(home: Path | None = None) -> float | None:
  59. """Epoch of the profile's first session; ``now`` when it has none yet (a brand-new install).
  60. Raises ``sqlite3.Error`` when state.db exists but cannot be read.
  61. """
  62. home = home or get_hermes_home()
  63. if str(home) in _first_session_at:
  64. return _first_session_at[str(home)]
  65. database = home / "state.db"
  66. if not database.exists():
  67. return time.time()
  68. with contextlib.closing(
  69. sqlite3.connect(f"file:{database}?mode=ro", uri=True, timeout=1)
  70. ) as connection:
  71. row = connection.execute("SELECT MIN(started_at) FROM sessions").fetchone()
  72. if not row or row[0] is None:
  73. return time.time()
  74. _first_session_at[str(home)] = float(row[0])
  75. return _first_session_at[str(home)]
  76. def install_age_bucket(home: Path | None = None) -> str:
  77. """How long ago the profile's first-ever session started, bucketed; ``unknown`` if unreadable.
  78. ``home`` defaults to the bound profile; callers off the turn thread must pass theirs."""
  79. from .shared_metrics_fields import install_age_bucket as bucket
  80. try:
  81. first = _first_session_started_at(home)
  82. except sqlite3.Error:
  83. return "unknown"
  84. return bucket(time.time() - first)
  85. def collect_install_snapshot(config: dict[str, Any]) -> dict[str, str]:
  86. """Bounded snapshot fields for the active profile's ``config``."""
  87. model = _sub(config, "model")
  88. language = "other"
  89. with contextlib.suppress(Exception):
  90. language = _display_language()
  91. from .shared_metrics_install import install_v4_snapshot_fields
  92. from .shared_metrics_prepared_compaction import prepare_ahead_state
  93. return {**contract.install_snapshot_fields(
  94. memory_provider=_sub(_sub(config, "memory"), "provider"),
  95. mcp_servers=_mcp_server_count(config),
  96. plugins=_plugin_count(config),
  97. skills=_skill_count(),
  98. cron_jobs=_cron_job_count(),
  99. profiles=_profile_count(),
  100. messaging_platforms=_safe_count(_messaging_platform_count),
  101. install_age_bucket=install_age_bucket(),
  102. main_provider=_sub(model, "provider") if isinstance(model, dict) else None,
  103. terminal_backend=_sub(_sub(config, "terminal"), "backend"),
  104. display_language=language,
  105. ), **install_v4_snapshot_fields(config), "compression_prepare_ahead": prepare_ahead_state(config)}