Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion hermes_cli/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -3005,6 +3005,17 @@ def _ensure_hermes_home_managed(home: Path):
},
},

# Generic trusted-edge observability correlation. The secret key remains in
# HERMES_OBSERVABILITY_CORRELATION_HMAC_K1; config.yaml only controls which
# consumers may emit or persist the derived identifier.
"observability": {
"correlation": {
"scheme": "hmac-sha256-v1:k1",
"emitter_metadata_enabled": False,
"history_execution_writer_enabled": False,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This flag has no consumer: _load_correlation_config() reads only scheme and emitter_metadata_enabled, and the new test asserts this field is absent from metadata. Please remove it until a concrete writer uses it, or implement that writer and its behavior in this change.

},
},

# Real-time token streaming to messaging platforms (Telegram, Discord,
# Slack, etc.). Read at the top level by the gateway; absent this block the
# gateway falls back to these same defaults, so adding it here only makes
Expand Down Expand Up @@ -4125,6 +4136,14 @@ def _ensure_hermes_home_managed(home: Path):
"category": "tool",
"advanced": True,
},
"HERMES_OBSERVABILITY_CORRELATION_HMAC_K1": {
"description": "K1 HMAC secret for trusted observability correlation (base64:<strict-unpadded-base64url>)",
"prompt": "Observability correlation K1 HMAC secret",
"url": None,
"password": True,
"category": "tool",
"advanced": True,
},

# ── Messaging platforms ──
"TELEGRAM_BOT_TOKEN": {
Expand Down Expand Up @@ -5272,7 +5291,7 @@ def check_config_version() -> Tuple[int, int]:
"fallback_providers", "credential_pool_strategies", "toolsets",
"agent", "terminal", "display", "compression", "delegation",
"auxiliary", "moa", "custom_providers", "context", "memory", "gateway",
"sessions", "streaming", "updates", "mcp_servers",
"observability", "sessions", "streaming", "updates", "mcp_servers",
}

# Valid fields inside a custom_providers list entry
Expand Down
37 changes: 37 additions & 0 deletions plugins/observability/langfuse/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,43 @@ HERMES_LANGFUSE_MAX_CHARS=12000 # max chars per field (default: 12000)
HERMES_LANGFUSE_DEBUG=true # verbose plugin logging
```

## Trusted-edge correlation

Correlation metadata is disabled by default. To emit a pseudonymous identifier
on Langfuse root traces, enable the generic observability gate in
`~/.hermes/config.yaml`:

```yaml
observability:
correlation:
scheme: hmac-sha256-v1:k1
emitter_metadata_enabled: true
```

Store the secret only in `~/.hermes/.env`:

```bash
HERMES_OBSERVABILITY_CORRELATION_HMAC_K1=base64:<strict-unpadded-base64url>
```

The decoded key must be 32–64 bytes. The payload accepts only `A-Z`, `a-z`,
`0-9`, `_`, and `-`; padding, whitespace, `+`, and `/` are rejected. Restart
Hermes after changing the gate or secret because the plugin loads this
configuration once when it registers.

When enabled with a valid key, root metadata gains
`correlation_scheme: hmac-sha256-v1:k1` and a lowercase 64-hex
`correlation_id`. Missing or invalid configuration emits neither field and
leaves all existing Langfuse tracing behavior unchanged.

### Privacy

The HMAC key is never sent to Langfuse or written to `config.yaml`, and the
plugin does not log the key, task identifier, or derived digest. The digest is
a pseudonymous join key, not encryption; access to it should be limited to the
trusted observability systems that need correlation. Existing `task_id`
metadata remains in Langfuse for dashboard compatibility.

## Disable

```bash
Expand Down
117 changes: 116 additions & 1 deletion plugins/observability/langfuse/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,15 @@
HERMES_LANGFUSE_SAMPLE_RATE - sampling rate 0.0–1.0 (default: 1.0)
HERMES_LANGFUSE_MAX_CHARS - max chars per field (default: 12000)
HERMES_LANGFUSE_DEBUG - set to "true" for verbose logging
HERMES_OBSERVABILITY_CORRELATION_HMAC_K1
- K1 HMAC key as base64:<strict-unpadded-base64url>
"""
from __future__ import annotations

import base64
import binascii
import hashlib
import hmac
import json
import logging
import os
Expand Down Expand Up @@ -52,6 +58,22 @@ class TraceState:
last_updated_at: float = field(default_factory=time.time)


_CORRELATION_SCHEME = "hmac-sha256-v1:k1"
_CORRELATION_SECRET_ENV = "HERMES_OBSERVABILITY_CORRELATION_HMAC_K1"
_CORRELATION_MESSAGE_PREFIX = b"hermes-observability-correlation-hmac-v1\x00"
_CORRELATION_KEY_PAYLOAD_RE = re.compile(r"^[A-Za-z0-9_-]+$")


@dataclass(frozen=True)
class CorrelationConfig:
scheme: str = _CORRELATION_SCHEME
emitter_metadata_enabled: bool = False
hmac_key: Optional[bytes] = field(default=None, repr=False)


_CORRELATION_CONFIG = CorrelationConfig()


_STATE_LOCK = threading.Lock()
_TRACE_STATE: Dict[str, TraceState] = {}
# Hard cap on live trace state. Each turn keys _TRACE_STATE by a unique
Expand Down Expand Up @@ -92,6 +114,93 @@ def _env_bool(*names: str) -> bool:
return False


def _parse_correlation_hmac_k1(value: Any) -> Optional[bytes]:
"""Parse the strict, unpadded base64url K1 secret format."""
if not isinstance(value, str) or not value.startswith("base64:"):
return None

payload = value[len("base64:"):]
if not _CORRELATION_KEY_PAYLOAD_RE.fullmatch(payload):
return None
if len(payload) % 4 == 1:
return None

try:
decoded = base64.b64decode(
payload + ("=" * (-len(payload) % 4)),
altchars=b"-_",
validate=True,
)
except (binascii.Error, ValueError):
return None

canonical = base64.urlsafe_b64encode(decoded).decode("ascii").rstrip("=")
if canonical != payload or not 32 <= len(decoded) <= 64:
return None
return decoded


def _load_correlation_config() -> CorrelationConfig:
"""Load the immutable trusted-edge config once during plugin registration."""
try:
from hermes_cli.config import load_config_readonly

config = load_config_readonly()
except Exception:
return CorrelationConfig()
if not isinstance(config, dict):
return CorrelationConfig()

observability = config.get("observability")
if not isinstance(observability, dict):
return CorrelationConfig()

correlation = observability.get("correlation")
if not isinstance(correlation, dict):
return CorrelationConfig()

scheme = correlation.get("scheme")
if not isinstance(scheme, str):
scheme = ""
enabled = correlation.get("emitter_metadata_enabled") is True
key = None
if enabled and scheme == _CORRELATION_SCHEME:
key = _parse_correlation_hmac_k1(os.environ.get(_CORRELATION_SECRET_ENV))
return CorrelationConfig(
scheme=scheme,
emitter_metadata_enabled=enabled,
hmac_key=key,
)


def _derive_correlation_id(
task_id: Any,
config: Optional[CorrelationConfig] = None,
) -> Optional[str]:
"""Derive the K1 correlation digest without coercing or normalizing task IDs."""
correlation = config if config is not None else _CORRELATION_CONFIG
key = correlation.hmac_key
if (
correlation.emitter_metadata_enabled is not True
or correlation.scheme != _CORRELATION_SCHEME
or not isinstance(key, bytes)
or not 32 <= len(key) <= 64
or not isinstance(task_id, str)
or not task_id
or task_id != task_id.strip()
or "\x00" in task_id
):
return None

try:
task_bytes = task_id.encode("utf-8", errors="strict")
except UnicodeEncodeError:
return None

message = _CORRELATION_MESSAGE_PREFIX + task_bytes
return hmac.new(key, message, hashlib.sha256).hexdigest()


def _debug_enabled() -> bool:
return _env_bool("HERMES_LANGFUSE_DEBUG")

Expand Down Expand Up @@ -615,6 +724,10 @@ def _start_root_trace(task_key: str, *, task_id: str, session_id: str, platform:
"model": model,
"api_mode": api_mode,
}
correlation_id = _derive_correlation_id(task_id)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is where the new identifier becomes outbound Langfuse metadata. Current policy requires a generic consent flow with config gate, setup prompt, and hermes tools toggle (AGENTS.md:118-121); this PR adds the gate but does not update the Langfuse setup surface. Please add the required explicit opt-in flow before emitting it.

if correlation_id is not None:
metadata["correlation_scheme"] = _CORRELATION_SCHEME
metadata["correlation_id"] = correlation_id

# session_id must be passed in trace_context for Langfuse session grouping.
trace_ctx: Dict[str, Any] = {"trace_id": trace_id}
Expand Down Expand Up @@ -663,7 +776,7 @@ def _start_root_trace(task_key: str, *, task_id: str, session_id: str, platform:
except Exception:
pass

_debug(f"started trace {trace_id} for {task_key}")
_debug(f"started trace {trace_id}")
return TraceState(trace_id=trace_id, root_ctx=root_ctx, root_span=root_span)


Expand Down Expand Up @@ -1126,6 +1239,8 @@ def on_post_tool_call(*, tool_name: str = "", args: Any = None, result: Any = No


def register(ctx) -> None:
global _CORRELATION_CONFIG
_CORRELATION_CONFIG = _load_correlation_config()
# Register for both hook name variants so the plugin works across
# Hermes versions. pre_api_request / post_api_request fire per API
# call (preferred); pre_llm_call / post_llm_call fire once per turn.
Expand Down
Loading