hermes-agent/agent/telemetry/policy.py
emozilla ccfa079252 feat(telemetry): local-first telemetry & observability
Add a built-in telemetry system that records what the agent does — workflows,
model calls, tool calls, errors — to the local machine, powers `/insights`, and
can export to an operator-chosen destination. Default-on locally; nothing leaves
the machine unless the user exports it or opts into the aggregate plane.

Three planes with a hard wall between them:
  - local: full-fidelity observability (real model/provider/tool names), on by
    default, never leaves the machine.
  - aggregate: opt-in metadata, default off. No uploader ships — consent is
    recorded via telemetry.consent_state, and `preview` shows what would be
    produced, computed locally.
  - trajectories: full message content, opt-in, exported only to the operator's
    own destination.

Mechanism:
  - Bundled `telemetry` plugin registers observational lifecycle hooks
    (on_session_start / post_api_request / post_tool_call / on_session_finalize).
    No core call sites are edited; hooks already carry the data.
  - Fire-and-forget emitter: emit() returns in microseconds, never blocks or
    raises into a model/tool call. A daemon thread writes events to an
    append-only JSONL log and the tel_* tables in state.db (its own sqlite
    connection, separate from SessionDB).
  - tel_runs / tel_model_calls / tel_tool_calls live in the declarative
    SCHEMA_SQL and are reconciled automatically; SCHEMA_VERSION 16 -> 17.
  - metrics derives rollups for /usage and /insights; rollup builds per-run
    summaries for `hermes telemetry preview`.

Consent is config, not a parallel command surface. The config file is the root
of trust: set telemetry.consent_state with `hermes config set`, or pin any
telemetry.* key (including allow_aggregate) via managed scope, which overrides
the user's value per key. `hermes telemetry` exposes only what config cannot:
status (report), preview (query), and export.

Export:
  - exporter_bulk writes telemetry (and, when the trajectories plane is enabled,
    session content) to ndjson/json.
  - otlp_exporter streams spans to a configured OpenTelemetry Collector over
    OTLP/HTTP. The SDK is an optional extra (hermes-agent[otlp]), lazily
    installed via tools.lazy_deps on first use.
  - Secrets are always redacted on every export path
    (redact_sensitive_text(force=True)); content export is gated by the
    trajectories plane, and PII scrubbing follows telemetry.content_redaction.
    OTLP auth headers reference environment variable names, never inline values.

No outbound emission to Nous. The aggregate uploader is intentionally not built.
2026-06-24 02:14:02 -04:00

107 lines
3.6 KiB
Python

"""Telemetry consent posture and the aggregate-plane gate.
Consent is a single field, ``telemetry.consent_state``:
* "unknown" — no choice recorded; never uploads (the default).
* "local" — declined the aggregate plane; local plane only.
* "aggregate" — opted in to the aggregate plane.
The config file is the source of truth: set ``telemetry.consent_state`` with
``hermes config set`` (or a managed-scope pin). There is no separate boolean mirror —
a single field cannot drift out of sync with itself, so a stray value can't
accidentally imply consent.
``allow_aggregate`` is the hard gate. An administrator pins
``telemetry.allow_aggregate: false`` through the managed-scope layer
(``/etc/hermes/config.yaml``), which takes precedence over the user's config; when it
is false, the aggregate plane is off regardless of ``consent_state``.
This module makes the decisions; it performs no I/O and contains no uploader. A future
uploader must call :func:`may_upload_aggregate` at its boundary.
"""
from __future__ import annotations
import uuid
from dataclasses import dataclass
from typing import Any, Dict
CONSENT_UNKNOWN = "unknown"
CONSENT_LOCAL = "local"
CONSENT_AGGREGATE = "aggregate"
_VALID_STATES = {CONSENT_UNKNOWN, CONSENT_LOCAL, CONSENT_AGGREGATE}
@dataclass(slots=True)
class TelemetryDecision:
"""The resolved telemetry posture for the current process."""
local_enabled: bool
aggregate_enabled: bool
consent_state: str
install_id: str
allow_aggregate: bool
def may_upload_aggregate(self) -> bool:
"""The single gate the uploader must consult before any network send."""
return self.allow_aggregate and self.consent_state == CONSENT_AGGREGATE
def _telemetry_cfg(config: Dict[str, Any]) -> Dict[str, Any]:
cfg = config.get("telemetry") if isinstance(config, dict) else None
return cfg if isinstance(cfg, dict) else {}
def ensure_install_id(config: Dict[str, Any]) -> str:
"""Return a stable install id, minting one if the config slot is empty.
Does not persist — the caller writes the returned value back to config.yaml. A
fresh uuid4 is used; clearing ``telemetry.install_id`` (e.g. with
``hermes config set telemetry.install_id ""``) causes the next call to mint anew.
"""
tel = _telemetry_cfg(config)
existing = tel.get("install_id")
if isinstance(existing, str) and existing.strip():
return existing
return str(uuid.uuid4())
def resolve(config: Dict[str, Any]) -> TelemetryDecision:
"""Resolve the effective telemetry posture from config.
``consent_state`` is the single source of truth for the aggregate opt-in.
``allow_aggregate`` (admin-pinnable via managed scope) hard-disables the aggregate
plane regardless of consent.
"""
tel = _telemetry_cfg(config)
local_enabled = bool(tel.get("local", True))
allow_aggregate = bool(tel.get("allow_aggregate", True))
state = tel.get("consent_state", CONSENT_UNKNOWN)
if state not in _VALID_STATES:
state = CONSENT_UNKNOWN
aggregate_enabled = allow_aggregate and state == CONSENT_AGGREGATE
return TelemetryDecision(
local_enabled=local_enabled,
aggregate_enabled=aggregate_enabled,
consent_state=state,
install_id=ensure_install_id(config),
allow_aggregate=allow_aggregate,
)
def may_upload_aggregate(config: Dict[str, Any]) -> bool:
"""Convenience gate for the uploader boundary."""
return resolve(config).may_upload_aggregate()
__all__ = [
"CONSENT_UNKNOWN",
"CONSENT_LOCAL",
"CONSENT_AGGREGATE",
"TelemetryDecision",
"resolve",
"may_upload_aggregate",
"ensure_install_id",
]