The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor: move Langfuse out of core into the langfuse catalog plugin
Tekniumcdf5732af67c
diff --git a/hermes_cli/config.py b/hermes_cli/config.pyindex 320011a689e..ca35d36c026 100644--- a/hermes_cli/config.py+++ b/hermes_cli/config.py@@ -214,11 +214,6 @@ _EXTRA_ENV_KEYS = frozenset({"MATRIX_PASSWORD", "MATRIX_ENCRYPTION", "MATRIX_DEVICE_ID", "MATRIX_HOME_ROOM","MATRIX_REQUIRE_MENTION", "MATRIX_FREE_RESPONSE_ROOMS", "MATRIX_AUTO_THREAD", "MATRIX_DM_AUTO_THREAD","MATRIX_RECOVERY_KEY",- # Langfuse observability plugin tuning keys + standard SDK vars (activation is via- # plugins.enabled; credentials gate the plugin at runtime).- "HERMES_LANGFUSE_ENV", "HERMES_LANGFUSE_RELEASE", "HERMES_LANGFUSE_SAMPLE_RATE",- "HERMES_LANGFUSE_MAX_CHARS", "HERMES_LANGFUSE_CAPTURE", "HERMES_LANGFUSE_DEBUG",- "LANGFUSE_PUBLIC_KEY", "LANGFUSE_SECRET_KEY", "LANGFUSE_BASE_URL",# ACP (Agent Client Protocol) keys — profile-isolable so profiles can use different backends."HERMES_ACP_AUTH_METHOD", "HERMES_ACP_AUTO_APPROVE", "HERMES_COPILOT_ACP_COMMAND","HERMES_COPILOT_ACP_ARGS", "COPILOT_CLI_PATH", "COPILOT_ACP_BASE_URL"})diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex d568f2ad7ef..a1fd8a0eee0 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -3018,14 +3018,6 @@ OPTIONAL_ENV_VARS = {"OpenViking API key", tools=["viking_search"]),"OPENVIKING_ENDPOINT": _tool("OpenViking server URL (default: http://127.0.0.1:1933)","OpenViking endpoint", password=None, advanced=True),- # ── Langfuse observability ──- "HERMES_LANGFUSE_PUBLIC_KEY": _tool("Langfuse project public key (pk-lf-...)",- "Langfuse public key", "https://cloud.langfuse.com", password=False),- "HERMES_LANGFUSE_SECRET_KEY": _tool("Langfuse project secret key (sk-lf-...)",- "Langfuse secret key", "https://cloud.langfuse.com"),- "HERMES_LANGFUSE_BASE_URL": _tool("Langfuse server URL (default: https://cloud.langfuse.com)",- "Langfuse server URL (leave empty for cloud.langfuse.com)", None, password=False,- advanced=True),# ── Messaging platforms ──"TELEGRAM_BOT_TOKEN": _msg("Complete Telegram bot token created by @BotFather (numeric bot ID followed by a colon "diff --git a/hermes_cli/left_core_migration.py b/hermes_cli/left_core_migration.pyindex 69b96faebdd..aea4b0a99d5 100644--- a/hermes_cli/left_core_migration.py+++ b/hermes_cli/left_core_migration.py@@ -1,7 +1,7 @@"""Move a home onto the catalog plugin of a feature that left core.-A feature (gateway platform, toolset) that moves from core into a standalone catalog plugin keeps its-names, config keys and env vars, so migrating is only "install the plugin". Each row of+A feature (gateway platform, toolset, bundled plugin) that moves from core into a standalone catalog+plugin keeps its names, config keys and env vars, so migrating is only "install the plugin". Each row of:data:`LEFT_CORE` names the catalog plugin and a read-only predicate "does this home use it". Thecontract is the one memory providers established (``memory_provider_migration``, whose helpers thisreuses; memory is not a row because its plugin name comes from ``memory.provider``, not a table):@@ -120,6 +120,19 @@ def spotify_in_use(home: Path, *, process_env: bool = False) -> bool:return _toolset_listed(_read_config(home), frozenset({"spotify"}))+def langfuse_in_use(home: Path, *, process_env: bool = False) -> bool:+ """What made core trace to Langfuse for *home*: its bundled plugin selected in ``plugins.enabled``+ under its key (``observability/langfuse``) or bare name (``langfuse``), and not vetoed by+ ``plugins.disabled`` (which wins, as in the loader). The plugin was opt-in, so keys alone are not use."""+ plugins = _read_config(home).get("plugins")+ plugins = plugins if isinstance(plugins, dict) else {}++ def listed(key: str) -> bool:+ names = plugins.get(key)+ return isinstance(names, list) and any(str(n) in {"observability/langfuse", "langfuse"} for n in names)+ return listed("enabled") and not listed("disabled")++@dataclass(frozen=True)class LeftCoreFeature:plugin: str # catalog entry name == installed plugin name@@ -150,6 +163,9 @@ class LeftCoreFeature:# Top-level command the plugin registers in place of core's ``hermes auth <cli>`` login# (``hermes <cli> login|status|logout``); :func:`moved_command_hint` points the old spelling at it.cli: str = ""+ # Key of the bundled plugin core shipped (``observability/langfuse``): `hermes plugins <verb>` on it+ # names the catalog plugin instead (:func:`moved_plugin_hint`).+ plugin_key: str = ""LEFT_CORE: tuple[LeftCoreFeature, ...] = (@@ -166,6 +182,14 @@ LEFT_CORE: tuple[LeftCoreFeature, ...] = ("`hermes auth spotify` is now `hermes spotify login`",cli="spotify",),+ LeftCoreFeature(+ plugin="langfuse", label="Langfuse", in_use=langfuse_in_use,+ unchanged="your Langfuse keys and HERMES_LANGFUSE_* settings are unchanged; the plugin is now "+ "`langfuse` (was observability/langfuse)",+ secret_env=("HERMES_LANGFUSE_SECRET_KEY",),+ private_env=("HERMES_LANGFUSE_PUBLIC_KEY", "HERMES_LANGFUSE_BASE_URL"),+ plugin_key="observability/langfuse",+ ),)def platform_install_hint(platform: str) -> str:@@ -200,6 +224,18 @@ def moved_command_hint(prog: str, value: str, action: str = "") -> str:return f"{feature.label} moved out of core into the '{feature.plugin}' plugin, which is not loaded.{get}"+def moved_plugin_hint(name: str) -> str:+ """For a plugin name nothing resolves to: the bundled key of a plugin that left core+ (``observability/langfuse``) or its catalog name, the line naming the install command for the+ active home, else ``""``. Appended to "No plugin named ..." errors."""+ from hermes_constants import get_hermes_home+ feature = next((f for f in LEFT_CORE if f.plugin_key and name in (f.plugin_key, f.plugin)), None)+ if feature is None:+ return ""+ return (f"{feature.label} moved out of core into the '{feature.plugin}' plugin: install it with "+ f"`{_install_command(feature.plugin, Path(get_hermes_home()))}`.")++_attempted: set[str] = set()_undelivered: dict[str, list[str]] = {}diff --git a/hermes_cli/plugins_cmd.py b/hermes_cli/plugins_cmd.pyindex 517521e1c64..5bc6b43545f 100644--- a/hermes_cli/plugins_cmd.py+++ b/hermes_cli/plugins_cmd.py@@ -263,7 +263,7 @@ def _sanitize_plugin_name(name: str, plugins_dir: Path, *, allow_subdir: bool ="""Validate a plugin name and return the safe target path inside *plugins_dir*.Raises ``ValueError`` on traversal or a target outside the plugins directory. ``allow_subdir``- permits forward slashes so category keys like ``observability/langfuse`` can be looked up+ permits forward slashes so category keys like ``web/firecrawl`` can be looked up(``..`` and backslashes stay rejected); install paths keep ``False`` — a clone lands top-level."""if allow_subdir and name:@@ -463,6 +463,9 @@ def _unknown_plugin_message(name: str, *, downloaded_only: bool = False) -> str:"""``No plugin named ...`` with the exact-name rule and the two commands that resolve it."""scope = (" This command only works on downloaded plugins; bundled ones can only be enabled or disabled."if downloaded_only else " Bundled plugins can only be enabled or disabled.")+ from hermes_cli.left_core_migration import moved_plugin_hint+ if moved := moved_plugin_hint(name):+ return f"[red]No plugin named '{name}'.[/red] {moved}"return (f"[red]No plugin named '{name}'.[/red] Run `hermes plugins list` to see the exact names "f"(nested plugins use their full key, e.g. web/firecrawl).{scope} ""To add one: `hermes plugins install <owner/repo>`.")@@ -541,7 +544,7 @@ def ensure_basic_auth_plugin_enabled_in_config(cfg: dict) -> bool:def _discard_key_and_leaf(names: set, key: str) -> None:- """Drop *key* and its bare leaf (``observability/langfuse`` -> ``langfuse``) from *names*, so a+ """Drop *key* and its bare leaf (``web/exa`` -> ``exa``) from *names*, so astale legacy bare-name entry can't keep vetoing the canonical key."""names.discard(key)names.discard(key.split("/")[-1])@@ -665,8 +668,8 @@ def _catalog_installed_dir(name: str) -> Optional[Path]:def _find_plugin_entry(name: str) -> Optional[tuple]:"""THE plugin name resolver for every verb (enable/disable/show/capabilities/remove/update, thedashboard and the Desktop hub): the discovered ``(name, version, description, source, dir_path, key)``- entry for a canonical key or manifest name; else a bare leaf (``langfuse`` ->- ``observability/langfuse``) only when unique; else the catalog name the plugin was installed under.+ entry for a canonical key or manifest name; else a bare leaf (``exa`` ->+ ``web/exa``) only when unique; else the catalog name the plugin was installed under.Never guesses between two candidates."""entries = _discover_all_plugins()exact = next((entry for entry in entries if name in (entry[0], entry[5])), None)diff --git a/hermes_cli/subcommands/tools.py b/hermes_cli/subcommands/tools.pyindex 467148c4f6a..4419d13207a 100644--- a/hermes_cli/subcommands/tools.py+++ b/hermes_cli/subcommands/tools.py@@ -40,10 +40,10 @@ def build_tools_parser(subparsers, *, cmd_tools: Callable) -> None:description="Run the install/bootstrap hook a tool backend declares — the\n""same step `hermes tools` runs after you pick a provider that\n""needs extra dependencies (browser Chromium, Camofox, cua-driver,\n"- "KittenTTS/Piper, ddgs, Langfuse, xAI, Codex). Stable,\n"+ "KittenTTS/Piper, ddgs, xAI, Codex). Stable,\n""non-interactive target the dashboard spawns to drive backend\n""setup. Keys: agent_browser, camofox, cua_driver, kittentts,\n"- "piper, ddgs, langfuse, xai_grok, openai_codex.")+ "piper, ddgs, xai_grok, openai_codex.")tools_postsetup_p.add_argument("post_setup_key", metavar="KEY",help="Post-setup hook key (e.g. agent_browser, camofox, kittentts)")diff --git a/hermes_cli/tools_config.py b/hermes_cli/tools_config.pyindex b1dc75dfa9b..50f4a25543d 100644--- a/hermes_cli/tools_config.py+++ b/hermes_cli/tools_config.py@@ -221,8 +221,6 @@ _NOUS = {"requires_nous_auth": True}_OPENAI_VOICE_KEY = _key("VOICE_TOOLS_OPENAI_KEY", "OpenAI API key", "https://platform.openai.com/api-keys")_ELEVENLABS_KEY = _key("ELEVENLABS_API_KEY", "ElevenLabs API key", "https://elevenlabs.io/app/settings/api-keys")_DEEPINFRA_KEY = _key("DEEPINFRA_API_KEY", "DeepInfra API key", "https://deepinfra.com/dash/api_keys")-_LANGFUSE_PUBLIC = ("HERMES_LANGFUSE_PUBLIC_KEY", "Langfuse public key (pk-lf-...)")-_LANGFUSE_SECRET = ("HERMES_LANGFUSE_SECRET_KEY", "Langfuse secret key (sk-lf-...)")TOOL_CATEGORIES = {"tts": {@@ -357,16 +355,6 @@ TOOL_CATEGORIES = {computer_use_backend="cua", post_setup="cua_driver"),],},- "langfuse": {- "name": "Langfuse Observability", "icon": "📊",- "providers": [- _row("Langfuse Cloud", tag="Hosted Langfuse (cloud.langfuse.com)", post_setup="langfuse",- env_vars=[_key(*_LANGFUSE_PUBLIC, "https://cloud.langfuse.com"), _key(*_LANGFUSE_SECRET, "https://cloud.langfuse.com")]),- _row("Langfuse Self-Hosted", tag="Self-hosted Langfuse instance", post_setup="langfuse",- env_vars=[_key(*_LANGFUSE_PUBLIC), _key(*_LANGFUSE_SECRET),- _key("HERMES_LANGFUSE_BASE_URL", "Langfuse server URL (e.g. http://localhost:3000)", default="http://localhost:3000")]),- ],- },}# Env-var fallback for toolsets NOT in TOOL_CATEGORIES. `vision` is only a presence marker (reconfigure menu +diff --git a/hermes_cli/tools_config_post_setup.py b/hermes_cli/tools_config_post_setup.pyindex 4a0eda77a67..d71154e6e3e 100644--- a/hermes_cli/tools_config_post_setup.py+++ b/hermes_cli/tools_config_post_setup.py@@ -158,26 +158,6 @@ def _post_setup_python(spec: dict) -> None:_info_lines(*spec["on_install"], *spec["always"])-def _post_setup_langfuse() -> None:- import pm-- # The bundled plugin has no dependency member; its SDK is an application extra.- _print_info(" Preparing langfuse SDK...")- try:- pm.sync_venv(["langfuse"], explicit=True)- except (pm.InstallError, OSError, ValueError) as exc:- _print_warning(f" langfuse SDK install failed: {exc}")- _info_lines("Retry with: hermes tools")- return- try:- from hermes_cli.plugins_cmd import cmd_enable- cmd_enable("observability/langfuse")- except (Exception, SystemExit) as exc:- _print_warning(f" Could not enable plugin automatically: {exc}")- _info_lines("Run manually: hermes plugins enable observability/langfuse")- return- _info_lines("Restart Hermes for tracing to take effect.", "Verify: hermes plugins list")-def _post_setup_xai_grok() -> None:"""Shared xAI credential bootstrap for any picker row that talks to xAI (TTS, STT, Video Gen, x_search@@ -295,7 +275,6 @@ _POST_SETUP_HOOKS: dict = {"browser_use_cli": lambda: _ensure_browser_use_cli(verbose_hints=True),"camofox": _post_setup_camofox,"cua_driver": lambda: install_cua_driver(upgrade=False),- "langfuse": _post_setup_langfuse,"xai_grok": _post_setup_xai_grok,"openai_codex": _post_setup_openai_codex,**{key: (lambda spec=spec: _post_setup_python(spec)) for key, spec in _PYTHON_POST_SETUP_HOOKS.items()},@@ -411,7 +390,6 @@ def _cloud_agent_browser_installed() -> bool:# they live in ``_POST_SETUP_AUTH_READY`` as auth checks. Late-bound lambdas so tests can monkeypatch the underlying predicates._POST_SETUP_READY: dict = {**{key: (lambda m=spec["module"]: _module_installed(m)) for key, spec in _PYTHON_POST_SETUP_HOOKS.items()},- "langfuse": lambda: _module_installed("langfuse"),"agent_browser": lambda: _agent_browser_installed(),"browserbase": lambda: _cloud_agent_browser_installed(),"camofox": lambda: _camofox_installed(),diff --git a/plugins/AGENTS.md b/plugins/AGENTS.mdindex 6139d41ff1f..a9fc087d5f1 100644--- a/plugins/AGENTS.md+++ b/plugins/AGENTS.md@@ -41,7 +41,8 @@ command. A hook with no concrete consumer is speculative infrastructure and is rconnectors, analytics dashboards, paid-service tie-ins ship as standalone plugin repos(`~/.hermes/plugins/` or pip entry point) promoted in Discord `#plugins-skills-and-skins`. Reason:every absorbed product is our maintenance burden against a fast-moving core for a backend we don't- own. `observability/`, `kanban/`, `disk-cleanup/` are precedent, not an invitation. Closing such a+ own. `kanban/`, `disk-cleanup/` are precedent, not an invitation (Langfuse already moved out to the+ official catalog plugin). Closing such aPR is a coupling decision, not a quality judgment.- Reference/docs-companion plugins (`example-dashboard`, `strike-freedom-cockpit`,`plugin-llm-example`, `plugin-llm-async-example`) live indiff --git a/plugins/observability/langfuse/README.md b/plugins/observability/langfuse/README.mddeleted file mode 100644index d574b6649f6..00000000000--- a/plugins/observability/langfuse/README.md+++ /dev/null@@ -1,94 +0,0 @@-# Langfuse Observability Plugin--This plugin ships bundled with Hermes but is **opt-in** — it only loads when-you explicitly enable it.--## Enable--```bash-# Interactive: credentials + PM preparation of the langfuse extra + enable-hermes tools # → Langfuse Observability-```--Restart Hermes after setup. If dependency preparation fails, retry through-`hermes tools`; do not inject the SDK into the selected environment with pip.-For manual source-checkout setup, see the-[plugin guide](../../../website/docs/user-guide/features/built-in-plugins.md#observabilitylangfuse).--## Required credentials--Set these in `~/.hermes/.env` (or via `hermes tools`):--```bash-HERMES_LANGFUSE_PUBLIC_KEY=pk-lf-...-HERMES_LANGFUSE_SECRET_KEY=sk-lf-...-HERMES_LANGFUSE_BASE_URL=https://cloud.langfuse.com # or your self-hosted URL-```--Without the SDK or credentials the hooks no-op silently — the plugin fails-open.--## Verify--```bash-hermes plugins list # observability/langfuse should show "enabled"-hermes chat -q "hello" # then check Langfuse for a "Hermes turn" trace-```--Generation observations include the Hermes system prompt when the provider-uses a separate `system` param (Anthropic Messages API). Open an **LLM call**-child span to inspect `role: system` (truncated via `HERMES_LANGFUSE_MAX_CHARS`).--## Optional tuning--```bash-HERMES_LANGFUSE_ENV=production # environment tag-HERMES_LANGFUSE_RELEASE=v1.0.0 # release tag-HERMES_LANGFUSE_SAMPLE_RATE=0.5 # sample 50% of traces-HERMES_LANGFUSE_MAX_CHARS=12000 # max chars per field (default: 12000)-HERMES_LANGFUSE_MAX_DEPTH=4 # max payload depth (default: 4)-HERMES_LANGFUSE_CAPTURE=sanitized # content capture mode (see below)-HERMES_LANGFUSE_DEBUG=true # verbose plugin logging-```--`HERMES_LANGFUSE_MAX_DEPTH` controls nested payload capture in both `sanitized`-and `full` modes, including tool arguments and JSON tool results. The root is-depth 0; each dictionary value or array element adds one level. Values beyond-the limit become `<max-depth>`, including scalars. For deeper MCP responses,-set it to a higher non-negative integer (for example, `10`) in the Hermes-process environment. Unset or blank values default to `4`; invalid or negative-values log a warning and fall back to `4`. `0` keeps only the root level.-Increasing the depth exports more content and may produce larger traces;-secret redaction, string-length limits, and the 50-item collection limit remain-unchanged. `metadata` mode still omits content.--## Capture modes--`HERMES_LANGFUSE_CAPTURE` controls how much *content* (prompts, responses,-tool arguments/results) is exported. Structural metadata — IDs, roles, tool-names, token usage, cost, timing — is always captured in every mode.--| mode | behavior |-|------|----------|-| `metadata` | No content. Each content field is replaced by a shape/size stub (`{"omitted": true, "type": "text", "chars": N}`). |-| `sanitized` | **(default)** Content is exported after secret-pattern redaction (API keys, tokens, JWTs, private keys, `password=`-style assignments) and truncation. Redaction runs *before* truncation. |-| `full` | Raw content, truncated only. Explicit opt-in — traces will contain whatever passed through the conversation, including injected memory and file contents. |--The active mode is recorded on every trace as `metadata.capture_mode`.--Note: `sanitized` is pattern-based defense in depth, not a DLP guarantee.-For personal sessions or shared Langfuse projects, prefer `metadata`.--## Error + shutdown coverage--- Failed model requests (`api_request_error` hook) close their generation- with `level=ERROR`, status code, retry counters, and a capture-mode-scrubbed- error message. Non-retryable failures also finish the turn trace.-- Session end/finalize closes any still-open traces for that session and- flushes queued events, so interrupted or tool-only turns don't dangle.--## Disable--```bash-hermes plugins disable observability/langfuse-```diff --git a/plugins/observability/langfuse/__init__.py b/plugins/observability/langfuse/__init__.pydeleted file mode 100644index 0e002e4b801..00000000000--- a/plugins/observability/langfuse/__init__.py+++ /dev/null@@ -1,1044 +0,0 @@-"""langfuse — Hermes plugin tracing conversations, LLM calls and tool usage to Langfuse.--Activated via ``plugins.enabled``; hooks are inert without the ``langfuse`` SDK-and credentials. Env: HERMES_LANGFUSE_PUBLIC_KEY / SECRET_KEY (required),-BASE_URL, ENV, RELEASE, SAMPLE_RATE, MAX_CHARS (12000), MAX_DEPTH (4), DEBUG, and CAPTURE =-metadata (sizes/ids/usage only) | sanitized (default: secret redaction +-truncation) | full (truncated raw content). See README.md.-"""-from __future__ import annotations--import atexit-import contextlib-import functools-import json-import logging-import os-import re-import threading-import time-from dataclasses import dataclass, field-from typing import Any, Dict, Optional--logger = logging.getLogger(__name__)--try:- from langfuse import Langfuse, propagate_attributes-except Exception: # pragma: no cover - fail-open when optional dep is missing- Langfuse = None- propagate_attributes = None---@dataclass-class TraceState:- trace_id: str- root_ctx: Any- root_span: Any- generations: dict[str, Any] = field(default_factory=dict)- tools: dict[str, Any] = field(default_factory=dict)- pending_tools_by_name: dict[str, list] = field(default_factory=dict)- turn_tool_calls: list[dict[str, Any]] = field(default_factory=list)- # Keyed by child_session_id: subagent_stop carries no child_subagent_id.- subagents: dict[str, Any] = field(default_factory=dict)- # Fingerprints of MoA fan-outs already recorded: the client holds its last- # fan-out until the next one, so tool-loop turns would re-emit advisors.- moa_emitted: set = field(default_factory=set)- last_updated_at: float = field(default_factory=time.time)---_STATE_LOCK = threading.Lock()-_TRACE_STATE: dict[str, TraceState] = {}-# Ceiling on live trace state (per turn_id): turns that never reach _finish_trace-# would leak forever, so over the cap the least-recently-updated are evicted.-# Bounds the leak, not concurrency.-_MAX_TRACE_STATE = 256-_LANGFUSE_CLIENT = None-# Under a multiplexed profile override, one settled client (or _INIT_FAILED) per Hermes home: the-# keys live in each profile's .env, so a single slot would trace profile B into profile A's project-# (or pin B to A's failed init). The slot above stays for the unscoped single-profile path.-_LANGFUSE_CLIENT_BY_HOME: dict[str, Any] = {}-# Separate from _STATE_LOCK (hot path) so the two never nest; serializes the-# first client build so racing callers can't each construct a client.-_LANGFUSE_CLIENT_LOCK = threading.Lock()-_READ_FILE_LINE_RE = re.compile(r"^\s*(\d+)\|(.*)$")-_READ_FILE_HEAD_LINES = 25-_READ_FILE_TAIL_LINES = 15-_READ_FILE_META_KEYS = ("total_lines", "file_size", "truncated", "is_binary", "is_image", "hint",- "_warning", "mime_type", "dimensions", "similar_files", "error")--# Langfuse-issued keys always carry these prefixes. Anything else is a leftover-# template value: the SDK accepts it at construction time but silently drops-# every trace at flush time (#23823).-_LANGFUSE_KEY_PREFIXES: dict[str, str] = {- "HERMES_LANGFUSE_PUBLIC_KEY": "pk-lf-",- "HERMES_LANGFUSE_SECRET_KEY": "sk-lf-",-}--# (langfuse usage key, CanonicalUsage attribute / summary-dict key, PricingEntry attribute)-_USAGE_FIELDS = (- ("input", "input_tokens", "input_cost_per_million"),- ("output", "output_tokens", "output_cost_per_million"),- ("cache_read_input_tokens", "cache_read_tokens", "cache_read_cost_per_million"),- ("cache_creation_input_tokens", "cache_write_tokens", "cache_write_cost_per_million"),- ("reasoning_tokens", "reasoning_tokens", None),-)---def _env(name: str, default: str = "") -> str:- return os.environ.get(name, default).strip()---def _secret(name: str) -> str:- """Credential read through the profile secret scope. A scope-less multiplex caller raises- (``UnscopedSecretError``): that is a spawn-site bug, and reading ``os.environ`` instead would- ship this profile's traces with the DEFAULT profile's keys."""- from agent.secret_scope import get_secret-- return (get_secret(name) or "").strip()---def _debug(message: str) -> None:- if _env("HERMES_LANGFUSE_DEBUG").lower() in {"1", "true", "yes", "on"}:- logger.info("Langfuse tracing: %s", message)---def _failsafe(label: str):- """Swallow + debug-log any exception: telemetry must never block the agent turn."""- try:- yield- except Exception as exc: # pragma: no cover - fail-open- _debug(f"{label} failed: {exc}")---_CAPTURE_MODES = ("metadata", "sanitized", "full")-_DEFAULT_CAPTURE_MODE = "sanitized"-_warned_invalid_capture = False---def _capture_mode() -> str:- """Resolve ``metadata | sanitized | full``; read per call so long-lived processes- can flip modes. Invalid values warn once and fall back to the default (never- capture more than the operator intended)."""- global _warned_invalid_capture- value = _env("HERMES_LANGFUSE_CAPTURE").lower()- if not value or value in _CAPTURE_MODES:- return value or _DEFAULT_CAPTURE_MODE- if not _warned_invalid_capture:- _warned_invalid_capture = True- logger.warning(- "Langfuse plugin: invalid HERMES_LANGFUSE_CAPTURE=%r, falling back "- "to %r (valid: %s)",- value, _DEFAULT_CAPTURE_MODE, ", ".join(_CAPTURE_MODES),- )- return _DEFAULT_CAPTURE_MODE---def _redact_secrets(value: str) -> str:- # force=True: redact even if the user disabled security.redact_secrets —- # this content is exported to an external service.- try:- from agent.redact import redact_sensitive_text- return redact_sensitive_text(value, force=True)- except Exception:- return value---# (types, shape builder) for _describe_content; first match wins (bool handled before).-_CONTENT_SHAPES = (- ((int, float), lambda v: {"type": "number"}),- (bytes, lambda v: {"type": "bytes", "length": len(v)}),- (str, lambda v: {"type": "text", "chars": len(v)}),- (dict, lambda v: {"type": "object", "keys": [str(k) for k in list(v.keys())[:20]]}),- ((list, tuple, set), lambda v: {"type": "array", "items": len(v)}),-)---def _describe_content(value: Any) -> Any:- """Metadata-mode stand-in for content: shape and size, never payload."""- if value is None or isinstance(value, bool):- return value- shape = next((build(value) for types, build in _CONTENT_SHAPES if isinstance(value, types)), None)- return {"omitted": True, **(shape or {"type": type(value).__name__})}---def _capture_content(value: Any, *, parse_json_strings: bool = False, tool_result_of: Optional[tuple] = None) -> Any:- """Apply the active capture mode to a CONTENT value.-- Only prompt/response text, tool arguments and tool results are content;- metadata fields (provider, model, IDs, counts) stay as-is in every mode.- ``tool_result_of=(tool_name, args)`` marks a tool result: JSON strings are- parsed first so a read_file payload can be collapsed to a preview keyed by- the call's ``args``.- """- if _capture_mode() == "metadata":- return _describe_content(value)- if tool_result_of is not None:- tool_name, args = tool_result_of- value = _maybe_parse_json_string(value) if isinstance(value, str) else value- value, parse_json_strings = _normalize_payload(value, tool_name=tool_name, args=args), True- return _safe_value(value, parse_json_strings=parse_json_strings)---# Sentinel: "_get_langfuse() has tried and failed". Tests reset by reloading-# the module; runtime callers must restart the process after fixing credentials.-_INIT_FAILED = object()---def _validate_langfuse_key(env_name: str, value: str) -> Optional[str]:- """Log-ready error if ``value`` lacks the prefix for ``env_name``; the preview- exposes placeholders without echoing a real secret pasted into the wrong var."""- expected = _LANGFUSE_KEY_PREFIXES.get(env_name, "")- if not expected or value.startswith(expected):- return None- preview = "<empty>" if not value else repr(value) if len(value) <= 12 else repr(value[:6] + "...")- return f"{env_name}={preview} (expected {expected!r} prefix)"---def _settled_client() -> Any:- """The active profile's settled client slot value (client, ``_INIT_FAILED`` or ``None`` = never- built). Never initializes."""- from hermes_constants import get_hermes_home_override, hermes_home_key-- if get_hermes_home_override() is None:- return _LANGFUSE_CLIENT- return _LANGFUSE_CLIENT_BY_HOME.get(hermes_home_key())---def _settle_client() -> Any:- """Build once and store for the active profile. Caller holds ``_LANGFUSE_CLIENT_LOCK``."""- global _LANGFUSE_CLIENT- from hermes_constants import get_hermes_home_override, hermes_home_key-- client = _build_client()- settled = _INIT_FAILED if client is None else client- if get_hermes_home_override() is None:- _LANGFUSE_CLIENT = settled- else:- _LANGFUSE_CLIENT_BY_HOME[hermes_home_key()] = settled- if client is not None:- # atexit is LIFO: registering AFTER the SDK's constructor means our- # finalizer runs first, so root spans ended there still get flushed- # by the SDK (short-lived processes: kanban workers, chat -q, cron).- atexit.register(_finalize_all_traces)- return settled---def _get_langfuse() -> Optional[Langfuse]:- """Cached Langfuse client, or ``None`` if the SDK/credentials are unavailable.- The first build is serialized so racing callers can't each construct a client- and leak the loser's HTTP connection + flush thread."""- # Fast path — already settled (success or _INIT_FAILED) needs no lock;- # re-check under it since a racing thread may have finished init.- settled = _settled_client()- if settled is None:- with _LANGFUSE_CLIENT_LOCK:- settled = _settled_client()- if settled is None:- settled = _settle_client()- return None if settled is _INIT_FAILED else settled---def _build_client() -> Optional[Langfuse]:- """Construct the SDK client from env, or None (with one warning) when it can't be."""- if Langfuse is None:- logger.warning(- "Langfuse plugin is enabled but the langfuse SDK is unavailable; "- "tracing is disabled. Run `hermes tools` and configure Langfuse "- "Observability to reinstall it."- )- return None-- public_key, secret_key = (_secret(f"HERMES_LANGFUSE_{n}") or _secret(f"LANGFUSE_{n}") for n in ("PUBLIC_KEY", "SECRET_KEY"))- if not (public_key and secret_key):- return None-- # The SDK does not validate keys at construction; placeholder keys- # would fail silently at flush time (#23823). Warn once here instead.- placeholder_issues = [issue for issue in (- _validate_langfuse_key("HERMES_LANGFUSE_PUBLIC_KEY", public_key),- _validate_langfuse_key("HERMES_LANGFUSE_SECRET_KEY", secret_key),- ) if issue]- if placeholder_issues:- logger.warning(- "Langfuse plugin: credentials look like placeholders, traces will "- "NOT be emitted (%s). Set real Langfuse keys (pk-lf-... / sk-lf-...) "- "or unset HERMES_LANGFUSE_PUBLIC_KEY / HERMES_LANGFUSE_SECRET_KEY to "- "silence this warning.",- "; ".join(placeholder_issues),- )- return None-- kwargs: dict[str, Any] = {"public_key": public_key, "secret_key": secret_key}- for key, name, default in (("base_url", "BASE_URL", "https://cloud.langfuse.com"), ("environment", "ENV", ""),- ("release", "RELEASE", "")):- value = _secret(f"HERMES_LANGFUSE_{name}") or _secret(f"LANGFUSE_{name}") or default- if value:- kwargs[key] = value- sample_rate = _secret("HERMES_LANGFUSE_SAMPLE_RATE")- if sample_rate:- try:- kwargs["sample_rate"] = float(sample_rate)- except ValueError:- logger.warning("Invalid HERMES_LANGFUSE_SAMPLE_RATE=%r", sample_rate)-- try:- return Langfuse(**kwargs)- except Exception as exc: # pragma: no cover - fail-open- logger.warning("Could not initialize Langfuse client: %s", exc)- return None---def _trace_key(task_id: str, session_id: str, *, turn_id: str = "", api_request_id: str = "") -> str:- """In-process trace scope key for one agent turn. ``turn_id`` wins over- ``api_request_id`` so the turn-level post_llm_call hook (no api_request_id)- resolves to the same key as request-level hooks; a bare ``task_id`` is the- legacy shape from before turn/request scoping."""- scope = f"task:{task_id}" if task_id else f"session:{session_id}" if session_id else f"thread:{threading.get_ident()}"- if turn_id:- return f"{scope}:turn:{turn_id}"- if api_request_id:- return f"{scope}:api:{api_request_id}"- return task_id or scope---def _state_for_turn(turn_id: str) -> Optional[TraceState]:- """Live trace state for a turn id alone (caller holds ``_STATE_LOCK``). Subagent- hooks carry ``parent_turn_id`` but no ``task_id``, so rebuilding the key would- miss; match on the unique ``:turn:<id>`` suffix instead."""- if not turn_id:- return None- suffix = f":turn:{turn_id}"- return next((state for key, state in _TRACE_STATE.items() if key.endswith(suffix)), None)---def _truncate_text(value: str, max_chars: int) -> Any:- # The SDK decodes data:*;base64 strings as media; a truncated one is- # invalid base64 and logs noisily, so redact the whole URI instead.- prefix = value[:200].lower()- if prefix.startswith("data:") and ";base64," in prefix:- header = value.split(",", 1)[0] if "," in value else "data:"- media_type = header[5:].split(";", 1)[0] if header.startswith("data:") else ""- return {"type": "data_uri", "media_type": media_type or None, "omitted": True, "length": len(value)}- # Redact BEFORE truncating so a secret straddling the cut cannot leak.- if _capture_mode() == "sanitized":- value = _redact_secrets(value)- over = len(value) - max_chars- return value if over <= 0 else value[:max_chars] + f"... [truncated {over} chars]"---def _maybe_parse_json_string(value: str) -> Any:- stripped = value.strip()- if len(stripped) < 2 or stripped[0] not in "{[":- return value- try:- parsed, idx = json.JSONDecoder().raw_decode(stripped)- except Exception:- return value- if not isinstance(parsed, (dict, list)):- return value-- trailing = stripped[idx:].strip()- if not trailing:- return parsed-- hint_key = "_hint" if trailing.startswith("[Hint:") else "_trailing_text"- if isinstance(parsed, dict):- return {**parsed, (hint_key if hint_key not in parsed else "_trailing_text"): trailing}- return {"data": parsed, hint_key: trailing}---def _normalize_payload(value: Any, *, tool_name: str = "", args: Any = None) -> Any:- """Collapse a read_file result (line-numbered content + file metadata) into a compact preview."""- is_read_file = (- isinstance(value, dict)- and isinstance(value.get("content"), str)- and all(k in value for k in ("total_lines", "file_size", "is_binary", "is_image"))- and not value.get("error")- )- if not is_read_file:- return value- normalized: dict[str, Any] = {}- if tool_name == "read_file" and isinstance(args, dict):- if isinstance(args.get("path"), str) and args["path"]:- normalized["path"] = args["path"]- normalized.update({key: args[key] for key in ("offset", "limit") if isinstance(args.get(key), int)})-- content = value.get("content", "")- matches = [_READ_FILE_LINE_RE.match(raw) for raw in content.splitlines()] if isinstance(content, str) and content else []- lines = [{"line": int(m.group(1)), "text": m.group(2)} for m in matches] if matches and all(matches) else []- if lines:- normalized["returned_lines"] = {"start": lines[0]["line"], "end": lines[-1]["line"], "count": len(lines)}- head, tail = _READ_FILE_HEAD_LINES, _READ_FILE_TAIL_LINES- normalized["content_preview"] = {"lines": lines} if len(lines) <= head + tail else {- "head": lines[:head], "tail": lines[-tail:], "omitted_line_count": len(lines) - head - tail,- }- elif value.get("content"):- normalized["content_preview"] = {"text": value.get("content", "")}-- normalized.update({key: value[key] for key in _READ_FILE_META_KEYS if key in value})-- b64 = value.get("base64_content")- if isinstance(b64, str) and b64:- normalized["base64_content"] = {"omitted": True, "length": len(b64)}- return normalized--[email protected]_cache(maxsize=8)-def _resolve_max_depth(configured_depth: str) -> int:- """Parse ``HERMES_LANGFUSE_MAX_DEPTH``; an invalid value warns ONCE per distinct value.- Cached on the raw string (not at import) so a long-lived process still picks up a changed- env var, while a bad value no longer logs one warning per captured prompt/tool payload."""- try:- max_depth = int(configured_depth)- if max_depth < 0:- raise ValueError- return max_depth- except ValueError:- logger.warning("Invalid HERMES_LANGFUSE_MAX_DEPTH=%r; use a non-negative integer. Falling back to 4.", configured_depth)- return 4---def _safe_value(value: Any, *, max_chars: Optional[int] = None, depth: int = 0,- parse_json_strings: bool = False, max_depth: Optional[int] = None) -> Any:- max_chars = max_chars if max_chars is not None else int(_env("HERMES_LANGFUSE_MAX_CHARS", "12000") or "12000")- if max_depth is None:- max_depth = _resolve_max_depth(_env("HERMES_LANGFUSE_MAX_DEPTH", "4") or "4")- if depth > max_depth:- return "<max-depth>"- if value is None or isinstance(value, (int, float, bool)):- return value- if isinstance(value, bytes):- return {"type": "bytes", "len": len(value)}- recurse = lambda v, d: _safe_value(v, max_chars=max_chars, depth=d, parse_json_strings=parse_json_strings, max_depth=max_depth)- if isinstance(value, str):- parsed = _maybe_parse_json_string(value) if parse_json_strings else value- return recurse(parsed, depth) if parsed is not value else _truncate_text(value, max_chars)- if isinstance(value, dict):- normalized = _normalize_payload(value)- if normalized is not value:- return recurse(normalized, depth)- return {str(k): recurse(v, depth + 1) for k, v in list(value.items())[:50]}- if isinstance(value, (list, tuple, set)):- return [recurse(v, depth + 1) for v in list(value)[:50]]- if hasattr(value, "__dict__"):- return recurse(vars(value), depth + 1)- return _truncate_text(repr(value), max_chars)---def _coerce_request_messages(*, request_messages: Any = None, messages: Any = None,- conversation_history: Any = None, user_message: Any = None) -> list[dict[str, Any]]:- for candidate in (request_messages, messages, conversation_history):- if isinstance(candidate, list):- return candidate- return [] if user_message is None else [{"role": "user", "content": user_message}]---def _serialize_system_prompt(system_prompt: Any) -> Optional[dict[str, Any]]:- """Normalize Anthropic/Bedrock ``system`` param or OpenAI-style system content."""- if isinstance(system_prompt, str):- text = system_prompt.strip()- elif isinstance(system_prompt, list):- # Anthropic: {"type": "text", "text": ...}; Bedrock Converse: {"text": ...}; or bare strings.- blocks = ((b.get("text", "") if b.get("type") in ("text", None) and "text" in b else None)- if isinstance(b, dict) else b for b in system_prompt)- text = "\n\n".join(b for b in blocks if isinstance(b, str) and b)- else:- return None- return {"role": "system", "content": _capture_content(text)} if text else None---def _messages_for_langfuse_input(*, request_messages: Any = None, messages: Any = None,- conversation_history: Any = None, user_message: Any = None,- system_prompt: Any = None) -> list[dict[str, Any]]:- """Generation input, prepending ``system_prompt`` when the provider split it out of messages."""- raw = _coerce_request_messages(request_messages=request_messages, messages=messages,- conversation_history=conversation_history, user_message=user_message)- system_msg = None if raw and raw[0].get("role") == "system" else _serialize_system_prompt(system_prompt)- serialized = _serialize_messages(raw)- return serialized if system_msg is None else [system_msg, *serialized]---def _serialize_message(message: dict[str, Any]) -> dict[str, Any]:- role, is_tool = message.get("role"), message.get("role") == "tool"- return {- "role": role, "content": _capture_content(message.get("content"), parse_json_strings=is_tool),- **({"tool_call_id": message["tool_call_id"]} if is_tool and message.get("tool_call_id") else {}),- **({"name": _safe_value(message["name"])} if is_tool and message.get("name") else {}),- **({"tool_calls": _capture_content(message["tool_calls"], parse_json_strings=True)} if message.get("tool_calls") else {}),- }---def _serialize_messages(messages: Any) -> list[dict[str, Any]]:- return [_serialize_message(m) for m in messages[-12:] if isinstance(m, dict)] if isinstance(messages, list) else []---def _serialize_tool_call(tool_call: Any) -> dict[str, Any]:- fn = getattr(tool_call, "function", None)- name, safe_arguments = getattr(fn, "name", None), _capture_content(getattr(fn, "arguments", None))- return {"id": getattr(tool_call, "id", None), "type": getattr(tool_call, "type", None) or "function",- "name": name, "arguments": safe_arguments, "function": {"name": name, "arguments": safe_arguments}}---def _serialize_assistant_message(message: Any) -> dict[str, Any]:- reasoning = next((getattr(message, attr, None) for attr in ("reasoning", "reasoning_content", "reasoning_details")- if getattr(message, attr, None) is not None), None)- return {- "content": _capture_content(getattr(message, "content", None)),- "reasoning": None if reasoning is None else _capture_content(reasoning),- "tool_calls": [_serialize_tool_call(tc) for tc in getattr(message, "tool_calls", None) or ()],- }---def _canonical_usage_and_cost(canonical: Any, *, provider: str, model: str,- base_url: str) -> tuple[dict[str, int], dict[str, float]]:- """Translate canonical Hermes usage into Langfuse usage and cost maps."""- usage_details: dict[str, int] = {- key: tokens for key, attr, _ in _USAGE_FIELDS- if (tokens := getattr(canonical, attr)) or key in ("input", "output")- }- cost_details: dict[str, float] = {}- try:- from agent.usage_pricing import estimate_usage_cost, resolve_billing_route-- # Subscription-included routes: Langfuse treats explicit cost_details- # (even zeros) as authoritative, so omit them and let it estimate.- route = resolve_billing_route(model, provider=provider, base_url=base_url)- if getattr(route, "billing_mode", "") == "subscription_included":- return usage_details, cost_details- cost = estimate_usage_cost(model, canonical, provider=provider, base_url=base_url, api_key="")- except Exception as exc: # pragma: no cover - fail-open- _debug(f"usage pricing failed: {exc}")- return usage_details, cost_details-- # No total (e.g. cache pricing unknown) => export no costs at all, so a- # partial component subtotal is never mistaken for the request total.- if cost.amount_usd is None:- return usage_details, cost_details-- # Langfuse only derives totals from input/output keys, so cache/custom keys- # need an explicit total (Hermes estimate also includes request pricing).- # A zero total is not exported: Langfuse would treat it as authoritative.- if cost.status != "included" and float(cost.amount_usd) > 0:- cost_details["total"] = float(cost.amount_usd)-- # Per-type breakdown for dashboards; keys mirror usage_details.- try:- from decimal import Decimal-- from agent.usage_pricing import get_pricing_entry-- entry = get_pricing_entry(model, provider=provider, base_url=base_url)- for key, attr, rate_attr in _USAGE_FIELDS if entry else ():- rate = getattr(entry, rate_attr, None) if rate_attr else None- tokens = getattr(canonical, attr)- if rate is not None and tokens:- cost_details[key] = float(Decimal(tokens) * rate / Decimal(1000000))- except Exception: # pragma: no cover - canonical total remains usable- pass-- return usage_details, cost_details---def _usage_and_cost(response: Any, *, provider: str, model: str, base_url: str, api_mode: str = "",- usage: Optional[dict] = None) -> tuple[dict[str, int], dict[str, float]]:- """Langfuse usage/cost maps from ``response.usage`` (post_llm_call) or, when ``usage``- is given (post_api_request), from that pre-built CanonicalUsage summary dict."""- raw_usage = getattr(response, "usage", None)- if usage is None and not raw_usage:- return {}, {}- try:- from agent.usage_pricing import CanonicalUsage, normalize_usage-- canonical = normalize_usage(raw_usage, provider=provider, api_mode=api_mode) if usage is None else CanonicalUsage(- output_tokens=usage.get("output_tokens", 0) or usage.get("completion_tokens", 0),- request_count=usage.get("request_count", 1),- **{attr: usage.get(attr, 0) for attr in ("input_tokens", "cache_read_tokens", "cache_write_tokens", "reasoning_tokens")},- )- return _canonical_usage_and_cost(canonical, provider=provider, model=model, base_url=base_url)- except Exception as exc: # pragma: no cover - fail-open- if usage is None:- _debug(f"usage normalization failed: {exc}")- return {}, {}---def _start_root_trace(task_key: str, *, task_id: str, session_id: str, platform: str, provider: str, model: str,- api_mode: str, messages: Any, client: Langfuse,- turn_id: str = "", api_request_id: str = "") -> TraceState:- trace_id = client.create_trace_id(seed=f"{session_id or 'sessionless'}::{task_id or task_key}")- last_user = next((m for m in reversed(messages) if isinstance(m, dict) and m.get("role") == "user"), None) \- if isinstance(messages, list) else None- trace_input = None if last_user is None else {"role": "user", "content": _capture_content(last_user.get("content"))}- metadata = {- "source": "hermes", "task_id": task_id, "turn_id": turn_id, "api_request_id": api_request_id,- "platform": platform, "provider": provider, "model": model, "api_mode": api_mode,- "capture_mode": _capture_mode(),- }- # session_id must be in trace_context for Langfuse session grouping.- trace_ctx: dict[str, Any] = {"trace_id": trace_id, **({"session_id": session_id} if session_id else {})}-- def open_root():- ctx = client.start_as_current_observation(trace_context=trace_ctx, name="Hermes turn", as_type="chain",- input=trace_input, metadata=metadata, end_on_exit=False)- return ctx, ctx.__enter__()-- root_ctx = root_span = None- if propagate_attributes is not None:- try:- with propagate_attributes(session_id=session_id or task_key, trace_name="Hermes turn",- tags=["hermes", "langfuse"]):- root_ctx, root_span = open_root()- except Exception:- root_ctx = None- if root_ctx is None:- root_ctx, root_span = open_root()-- with _failsafe("update_trace(input)"): # SDK v3 uses update_trace()- root_span.update_trace(input=trace_input)-- _debug(f"started trace {trace_id} for {task_key}")- return TraceState(trace_id=trace_id, root_ctx=root_ctx, root_span=root_span)---def _start_child_observation(state: TraceState, *, name: str, as_type: str, input_value: Any,- metadata: Optional[dict] = None, model: Optional[str] = None,- model_parameters: Optional[dict] = None) -> Any:- return state.root_span.start_observation(name=name, as_type=as_type, input=input_value, metadata=metadata or {},- model=model, model_parameters=model_parameters)---def _end_observation(observation: Any, *, output: Any = None, metadata: Optional[dict] = None,- usage_details: Optional[dict] = None, cost_details: Optional[dict] = None) -> None:- if observation is None:- return- with _failsafe("end observation"):- update_kwargs = {**({} if output is None else {"output": output}),- **{k: v for k, v in (("metadata", metadata), ("usage_details", usage_details),- ("cost_details", cost_details)) if v}}- if update_kwargs:- observation.update(**update_kwargs)- observation.end()---def _end_children(state: TraceState, *, include_subagents: bool = False) -> None:- pending = [obs for queue in state.pending_tools_by_name.values() for obs in queue]- subagents = state.subagents.values() if include_subagents else ()- for observation in (*state.generations.values(), *state.tools.values(), *pending, *subagents):- _end_observation(observation)---def _end_root(state: TraceState, label: str) -> None:- """End the root span then unwind its context; never raises."""- with _failsafe(label):- state.root_span.end()- # Unwind the root context manager now, while opentelemetry.trace.Span is- # still a real type; GC-driven close at interpreter teardown raises- # TypeError inside use_span's isinstance check.- if state.root_ctx is not None:- state.root_ctx.__exit__(None, None, None)---def _finalize_all_traces() -> None:- """atexit: end every open root span. Short-lived processes (kanban workers,- ``chat -q``, cron) exit with tool calls queued; children export via the SDK- flush but an un-ended root leaves an anonymous trace. Registered after the- client is built so (LIFO) it runs before the SDK's shutdown hook."""- with _STATE_LOCK:- states = list(_TRACE_STATE.items())- _TRACE_STATE.clear()- for key, state in states:- with _failsafe(f"atexit finalize for {key}"): # _end_root never raises- _end_children(state, include_subagents=True)- _end_root(state, f"atexit finalize for {key}")- if states:- # atexit runs with NO profile scope, so it must never build a client (a credential read- # here raises UnscopedSecretError under multiplex and would skip every flush). Flush only- # the clients that settled during the run — the launch profile's slot plus one per home.- for client in (_LANGFUSE_CLIENT, *_LANGFUSE_CLIENT_BY_HOME.values()):- if client is not None and client is not _INIT_FAILED:- _flush(client)---def _flush(client: Any) -> None:- if client is not None:- with contextlib.suppress(Exception):- client.flush()---def _finish_trace(task_key: str, *, output: Any = None) -> None:- client = _get_langfuse()- with _STATE_LOCK:- state = _TRACE_STATE.pop(task_key, None) if client is not None else None- if state is None:- return-- try:- _end_children(state)- final_output = output- if state.turn_tool_calls:- final_output = dict(output) if isinstance(output, dict) else {"content": output}- final_output["tool_calls"] = list(state.turn_tool_calls)- if final_output is not None:- # update_trace sets TRACE-level I/O (SDK v3); root I/O via update().- # Neither may prevent end(), else children export without a root.- for method, label in (("update_trace", "update_trace(output)"), ("update", "root update(output)")):- with _failsafe(label):- getattr(state.root_span, method)(output=final_output)- _end_root(state, "root end()")- except Exception as exc: # pragma: no cover - fail-open- _debug(f"finish trace failed: {exc}")- with contextlib.suppress(Exception): # last-chance end so the root still exports- state.root_span.end()- finally:- _flush(client)---def _request_key(api_call_count: Any) -> str:- return str(api_call_count or 0)---def _client_and_key(task_id: str, session_id: str, turn_id: str, api_request_id: str) -> tuple[Any, str]:- """(client, trace key) for a hook; client is None when tracing is unavailable."""- client = _get_langfuse()- if client is None:- return None, ""- return client, _trace_key(task_id, session_id, turn_id=turn_id, api_request_id=api_request_id)---def _duration_meta(api_duration: Any) -> dict[str, Any]:- return {"api_duration_s": round(api_duration, 3)} if api_duration and api_duration > 0 else {}---def _pop_generation(task_key: str, api_call_count: Any) -> tuple[Optional[TraceState], Any]:- """Detach the open generation for one API call. Returns (state, generation); either may be None."""- with _STATE_LOCK:- state = _TRACE_STATE.get(task_key)- return state, state.generations.pop(_request_key(api_call_count), None) if state else None---def _get_or_start_state_locked(task_key: str, **root_kwargs: Any) -> TraceState:- """Caller must hold ``_STATE_LOCK``. Starts a root trace if the key is new, first- evicting least-recently-updated state down to ``_MAX_TRACE_STATE - 1`` (evicted- roots are ended so they don't dangle on the Langfuse side)."""- state = _TRACE_STATE.get(task_key)- if state is None:- state = _start_root_trace(task_key, **root_kwargs)- over = len(_TRACE_STATE) - (_MAX_TRACE_STATE - 1)- for key, stale in sorted(_TRACE_STATE.items(), key=lambda kv: kv[1].last_updated_at)[:max(over, 0)]:- _TRACE_STATE.pop(key, None)- _end_root(stale, "evict stale trace")- _TRACE_STATE[task_key] = state- state.last_updated_at = time.time()- return state---def on_pre_llm_call(*, task_id: str = "", session_id: str = "", platform: str = "", model: str = "",- provider: str = "", api_mode: str = "", messages: Any = None,- turn_id: str = "", api_request_id: str = "", **_: Any) -> None:- # Only legacy request-shaped calls carry an API ``messages`` list; the- # turn-scoped pre_llm_call would otherwise open an orphan root trace.- if not isinstance(messages, list):- return- client, task_key = _client_and_key(task_id, session_id, turn_id, api_request_id)- if client is None:- return- with _STATE_LOCK:- _get_or_start_state_locked(task_key, task_id=task_id, session_id=session_id, platform=platform, provider=provider, model=model,- api_mode=api_mode, messages=messages, client=client, turn_id=turn_id, api_request_id=api_request_id)---def _emit_moa_reference_generations(state: TraceState, *, client: Langfuse, references: Any) -> None:- """Record each MoA advisor as its own generation: advisors routinely run on a- different provider/model, so otherwise the fan-out would collapse into one- generation priced at the aggregator's rate."""- if not isinstance(references, list) or not references:- return- fingerprint = json.dumps(- [[r.get("label"), r.get("model"), (r.get("usage") or {}).get("output_tokens")]- for r in references if isinstance(r, dict)],- sort_keys=True, default=str,- )- with _STATE_LOCK:- if fingerprint in state.moa_emitted:- return- state.moa_emitted.add(fingerprint)-- for ref in references:- if not isinstance(ref, dict):- continue- usage = ref.get("usage") or {}- usage_details = {key: usage[attr] for key, attr, _ in _USAGE_FIELDS if usage.get(attr)} if isinstance(usage, dict) else {}- cost_usd = ref.get("cost_usd")- cost_details = {"total": float(cost_usd)} if isinstance(cost_usd, (int, float)) else {}-- label = ref.get("label") or "advisor"- metadata = {"moa_role": "reference", "label": label,- **{k: ref[k] for k in ("provider", "cost_status", "cost_source", "temperature") if ref.get(k) is not None}}-- observation = _start_child_observation(state, name=f"MoA advisor: {label}", as_type="generation", input_value=None,- metadata=metadata, model=ref.get("model"))- _end_observation(observation, output=_capture_content(ref.get("output")), usage_details=usage_details,- cost_details=cost_details, metadata=metadata)---def on_pre_llm_request(*, task_id: str = "", session_id: str = "", platform: str = "", model: str = "",- provider: str = "", base_url: str = "", api_mode: str = "", api_call_count: int = 0,- request_messages: Any = None, messages: Any = None, message_count: int = 0,- approx_input_tokens: int = 0, conversation_history: Any = None,- user_message: Any = None, turn_id: str = "", api_request_id: str = "",- request: Any = None, system_prompt: Any = None, **_: Any) -> None:- client, task_key = _client_and_key(task_id, session_id, turn_id, api_request_id)- if client is None:- return-- # The request body carries the model actually dispatched (mid-session- # switch, fallback, middleware rewrite) — prefer it over the agent attribute.- body_model = request["body"].get("model") if isinstance(request, dict) and isinstance(request.get("body"), dict) else None- if isinstance(body_model, str) and body_model:- model = body_model-- input_messages = _coerce_request_messages(request_messages=request_messages, messages=messages,- conversation_history=conversation_history, user_message=user_message)- langfuse_input = _messages_for_langfuse_input(request_messages=input_messages, system_prompt=system_prompt)- has_system = bool(langfuse_input) and langfuse_input[0].get("role") == "system"- system_chars = len(str(langfuse_input[0].get("content") or "")) if has_system else 0- req_key = _request_key(api_call_count)-- with _STATE_LOCK:- state = _get_or_start_state_locked(- task_key, task_id=task_id, session_id=session_id, platform=platform, provider=provider, model=model,- api_mode=api_mode, messages=input_messages, client=client, turn_id=turn_id, api_request_id=api_request_id)- previous = state.generations.pop(req_key, None)- if previous is not None:- _end_observation(previous)- gen_metadata = {- "provider": provider, "platform": platform, "api_mode": api_mode, "base_url": base_url,- "message_count": message_count, "approx_input_tokens": approx_input_tokens,- **({"system_prompt_chars": system_chars} if system_chars else {}),- }- state.generations[req_key] = _start_child_observation(- state, name=f"LLM call {api_call_count}", as_type="generation",- input_value=langfuse_input, metadata=gen_metadata, model=model,- model_parameters={"api_mode": api_mode, "provider": provider},- )---def on_post_llm_call(*, task_id: str = "", session_id: str = "", provider: str = "", base_url: str = "",- api_mode: str = "", model: str = "", api_call_count: int = 0, assistant_message: Any = None,- response: Any = None, api_duration: float = 0.0, finish_reason: str = "", usage: Any = None,- assistant_content_chars: int = 0, assistant_tool_call_count: int = 0,- assistant_response: Any = None, turn_id: str = "", api_request_id: str = "",- response_model: Any = None, moa_references: Any = None, **_: Any) -> None:- client, task_key = _client_and_key(task_id, session_id, turn_id, api_request_id)- if client is None:- return-- # The response echoes the model that actually served the request.- if isinstance(response_model, str) and response_model:- model = response_model-- state, generation = _pop_generation(task_key, api_call_count)- if state is None or generation is None:- return-- if moa_references:- _emit_moa_reference_generations(state, client=client, references=moa_references)-- # Two call shapes: post_llm_call passes assistant_message / assistant_response- # objects; post_api_request passes summary counts + a usage dict.- if assistant_message is not None:- output = _serialize_assistant_message(assistant_message)- elif assistant_response is not None:- output = {"content": _capture_content(assistant_response), "reasoning": None, "tool_calls": []}- else:- output = {"content": f"[{assistant_content_chars} chars]" if assistant_content_chars else None, "reasoning": None,- "tool_calls": [{"id": f"tc_{i}"} for i in range(assistant_tool_call_count or 0)]}-- if output.get("tool_calls"):- state.turn_tool_calls.extend(output["tool_calls"])-- # post_api_request's ``response`` is a sanitized dict with no ``.usage``;- # gate on the attribute so the usage-dict fallback is actually reached.- if getattr(response, "usage", None) is not None:- usage_details, cost_details = _usage_and_cost(response, provider=provider, api_mode=api_mode, model=model, base_url=base_url)- elif isinstance(usage, dict) and usage:- usage_details, cost_details = _usage_and_cost(None, provider=provider, model=model, base_url=base_url, usage=usage)- else:- usage_details, cost_details = {}, {}-- gen_metadata = {"tool_call_count": len(output.get("tool_calls", [])) or assistant_tool_call_count,- **_duration_meta(api_duration), **({"finish_reason": finish_reason} if finish_reason else {})}- _end_observation(generation, output=output, usage_details=usage_details, cost_details=cost_details, metadata=gen_metadata)-- has_tools = bool(getattr(assistant_message, "tool_calls", None)) if assistant_message else assistant_tool_call_count > 0- if not has_tools and output.get("content"):- _finish_trace(task_key, output=output)---def on_pre_tool_call(*, tool_name: str = "", args: Any = None, task_id: str = "",- session_id: str = "", tool_call_id: str = "",- turn_id: str = "", api_request_id: str = "", **_: Any) -> None:- client, task_key = _client_and_key(task_id, session_id, turn_id, api_request_id)- if client is None:- return- with _STATE_LOCK:- state = _TRACE_STATE.get(task_key)- if state is None:- return- observation = _start_child_observation(state, name=f"Tool: {tool_name}", as_type="tool", input_value=_capture_content(args),- metadata={"tool_name": tool_name, "tool_call_id": tool_call_id})- if tool_call_id:- state.tools[tool_call_id] = observation- else:- state.pending_tools_by_name.setdefault(tool_name, []).append(observation)---def on_post_tool_call(*, tool_name: str = "", args: Any = None, result: Any = None,- task_id: str = "", session_id: str = "", tool_call_id: str = "",- turn_id: str = "", api_request_id: str = "", **_: Any) -> None:- task_key = _trace_key(task_id, session_id, turn_id=turn_id, api_request_id=api_request_id)- with _STATE_LOCK:- state = _TRACE_STATE.get(task_key)- if state is None:- return- observation = state.tools.pop(tool_call_id, None) if tool_call_id else None- queue = state.pending_tools_by_name.get(tool_name) if observation is None else None- if queue:- observation = queue.pop(0)- if not queue:- state.pending_tools_by_name.pop(tool_name, None)- if observation is None:- return-- safe_result_value = _capture_content(result, tool_result_of=(tool_name, args))-- # Backfill so the generation's tool_call record carries the result alongside arguments.- if tool_call_id:- with _STATE_LOCK:- state = _TRACE_STATE.get(task_key)- calls = state.turn_tool_calls if state is not None else []- tool_call = next((tc for tc in reversed(calls) if tc.get("id") == tool_call_id), None)- for target in (tool_call, tool_call.get("function")) if tool_call is not None else ():- if isinstance(target, dict):- target["output"] = safe_result_value-- _end_observation(observation, output=safe_result_value,- metadata={"tool_name": tool_name, "args": _capture_content(args, parse_json_strings=True)})---def on_api_request_error(*, task_id: str = "", session_id: str = "", api_call_count: int = 0,- api_duration: float = 0.0, status_code: Any = None, retry_count: Any = None,- max_retries: Any = None, retryable: Any = None, reason: Any = None, error: Any = None,- turn_id: str = "", api_request_id: str = "", **_: Any) -> None:- """Close (as ERROR) the open generation for a failed API request so the turn- doesn't look hung until eviction; a non-retryable failure also finishes the- turn, since the agent loop is about to unwind."""- client, task_key = _client_and_key(task_id, session_id, turn_id, api_request_id)- if client is None:- return- state, generation = _pop_generation(task_key, api_call_count)- if state is None:- return-- error = error if isinstance(error, dict) else {}- error_type, error_message = str(error.get("type") or ""), str(error.get("message") or "")-- # Error messages can embed request fragments (URLs w/ keys, prompt echoes) — capture-pipeline them.- error_metadata: dict[str, Any] = {- "error": True, "error_type": error_type, "error_message": _capture_content(error_message),- **{k: v for k, v in (("status_code", status_code), ("retry_count", retry_count), ("max_retries", max_retries),- ("retryable", retryable), ("reason", str(reason) if reason else None)) if v is not None},- **_duration_meta(api_duration),- }-- if generation is not None:- with _failsafe("error-level update"):- generation.update(level="ERROR", status_message=(error_type or "api_request_error")[:200])- _end_observation(generation, metadata=error_metadata)-- # A retryable failure is followed by another pre_api_request on the same- # trace; keep the turn open. A terminal failure ends the turn.- if retryable is False:- _finish_trace(task_key, output={"error": error_metadata})- else:- state.last_updated_at = time.time()---def on_session_finalize(*, session_id: str = "", reason: str = "", **_: Any) -> None:- """Session-end boundary: close still-open traces and flush. A turn ending on a- tool-only or empty final response never reaches ``_finish_trace``; its root- would dangle until eviction and queued events could be lost on exit."""- # Never lazily initialize a client here — if init never happened there are no traces.- client = _settled_client()- if client is None or client is _INIT_FAILED or not hasattr(client, "flush"):- return-- # This session's traces (all, when no session_id). Keys carry the session as- # "session:<id>" or "task:<id>" (gateway: task_id == session_id) or bare legacy id.- fragments = (f"session:{session_id}", f"task:{session_id}")- with _STATE_LOCK:- keys = [k for k in _TRACE_STATE if not session_id or k == session_id or any(f in k for f in fragments)]- for key in keys:- _finish_trace(key)- with _failsafe("finalize flush"):- client.flush()-- # Shut down only at true process exit (not /new, /reset, session expiry: the- # cached client must keep exporting). Doing it while modules are intact keeps- # the SDK's atexit handler off torn-down opentelemetry globals (TypeError on quit).- if reason == "shutdown" and callable(getattr(client, "shutdown", None)):- with _failsafe("langfuse shutdown"):- client.shutdown()---def on_subagent_start(*, parent_turn_id: str = "", parent_subagent_id: Any = None,- child_session_id: Any = None, child_subagent_id: Any = None,- child_role: str = "", child_goal: Any = None, **_: Any) -> None:- client = _get_langfuse()- if client is None or not child_session_id:- return-- with _STATE_LOCK:- state = _state_for_turn(parent_turn_id)- if state is None:- return- metadata = {"child_session_id": child_session_id, "child_subagent_id": child_subagent_id, "child_role": child_role,- **({"parent_subagent_id": parent_subagent_id} if parent_subagent_id else {})}- state.subagents[str(child_session_id)] = _start_child_observation(- state, name=f"Subagent: {child_role or 'delegate'}", as_type="span",- input_value=_capture_content(child_goal), metadata=metadata)---def on_subagent_stop(*, parent_turn_id: str = "", child_session_id: Any = None, child_role: str = "",- child_summary: Any = None, child_status: Any = None,- tool_call_history: Any = None, duration_ms: Any = None, **_: Any) -> None:- if not child_session_id:- return-- with _STATE_LOCK:- state = _state_for_turn(parent_turn_id)- if state is None:- return- observation = state.subagents.pop(str(child_session_id), None)- if observation is None:- return-- metadata = {"child_role": child_role, **{k: v for k, v in (("status", child_status), ("duration_ms", duration_ms)) if v},- **({"tool_call_count": len(tool_call_history), "tool_calls": _capture_content(tool_call_history)}- if isinstance(tool_call_history, list) else {})}- _end_observation(observation, output=_capture_content(child_summary), metadata=metadata)---def register(ctx) -> None:- # Both hook-name variants so the plugin works across Hermes versions:- # *_api_request fire per API call (preferred); *_llm_call once per turn.- hooks = (- ("pre_api_request", on_pre_llm_request), ("post_api_request", on_post_llm_call),- ("api_request_error", on_api_request_error), ("pre_llm_call", on_pre_llm_call),- ("post_llm_call", on_post_llm_call), ("pre_tool_call", on_pre_tool_call),- ("post_tool_call", on_post_tool_call), ("on_session_finalize", on_session_finalize),- ("on_session_end", on_session_finalize), ("subagent_start", on_subagent_start),- ("subagent_stop", on_subagent_stop),- )- for name, fn in hooks:- ctx.register_hook(name, fn)diff --git a/plugins/observability/langfuse/plugin.yaml b/plugins/observability/langfuse/plugin.yamldeleted file mode 100644index 9627e16e361..00000000000--- a/plugins/observability/langfuse/plugin.yaml+++ /dev/null@@ -1,19 +0,0 @@-name: langfuse-version: "1.0.0"-description: "Optional Langfuse observability for Hermes — traces conversations, LLM calls, and tool usage. Opt-in via `hermes plugins enable observability/langfuse` or `hermes tools → Langfuse Observability`."-author: NousResearch-requires_env:- - HERMES_LANGFUSE_PUBLIC_KEY- - HERMES_LANGFUSE_SECRET_KEY-provides_hooks:- - pre_api_request- - post_api_request- - api_request_error- - pre_llm_call- - post_llm_call- - pre_tool_call- - post_tool_call- - on_session_finalize- - on_session_end- - subagent_start- - subagent_stopdiff --git a/pm/extras.py b/pm/extras.pyindex 1e0a87acb33..fe72c69164e 100644--- a/pm/extras.py+++ b/pm/extras.py@@ -24,7 +24,6 @@ ANCHORS: dict[str, str | tuple[str, ...]] = {"parallel-web": "parallel","ddgs": "ddgs","otlp": "opentelemetry.sdk",- "langfuse": "langfuse","mistral": "mistralai","edge-tts": "edge_tts","neutts": "neutts",diff --git a/pyproject.toml b/pyproject.tomlindex a79d7ddfc47..3499250b184 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -430,7 +430,6 @@ otlp = ["opentelemetry-sdk==1.39.1","opentelemetry-exporter-otlp-proto-http==1.39.1",]-langfuse = ["langfuse==4.15.2"]bedrock = ["boto3==1.42.89"]vertex = ["google-auth==2.55.1"]azure-identity = ["azure-identity==1.25.3"]diff --git a/tests/hermes_cli/test_left_core_migration.py b/tests/hermes_cli/test_left_core_migration.pyindex 63baebac701..c0593caf88f 100644--- a/tests/hermes_cli/test_left_core_migration.py+++ b/tests/hermes_cli/test_left_core_migration.py@@ -371,3 +371,29 @@ def test_old_spotify_commands_point_at_the_plugin(tmp_path, monkeypatch):(home / "plugins" / "spotify").mkdir(parents=True) # installed but disabledassert "plugins enable spotify" in lcm.moved_command_hint("hermes", "spotify")assert lcm.moved_command_hint("hermes", "honcho") == ""+++_LANGFUSE_KEYS_ENV = "HERMES_LANGFUSE_PUBLIC_KEY=pk-lf-x\nHERMES_LANGFUSE_SECRET_KEY=sk-lf-x\n"++[email protected](("config", "in_use"), [+ ("plugins:\n enabled: [observability/langfuse]\n", True),+ ("plugins:\n enabled: [langfuse]\n", True), # legacy bare name the loader accepted+ ("plugins:\n enabled: [observability/langfuse]\n disabled: [langfuse]\n", False), # disabled wins+ ("plugins:\n enabled: [other]\n", False),+ ("", False), # keys alone: it was opt-in+])+def test_langfuse_in_use_is_the_bundled_plugin_enabled(tmp_path, config, in_use):+ home = _home(tmp_path, env=_LANGFUSE_KEYS_ENV, config=config)+ assert lcm.langfuse_in_use(home) is in_use+++def test_old_langfuse_plugin_key_points_at_the_catalog_plugin(tmp_path, monkeypatch):+ """`hermes plugins enable observability/langfuse` (every pre-move doc said so) names the install."""+ from hermes_cli.plugins_cmd import _unknown_plugin_message+ monkeypatch.setenv("HERMES_HOME", str(_home(tmp_path)))+ for name in ("observability/langfuse", "langfuse"):+ message = _unknown_plugin_message(name)+ assert "moved out of core into the 'langfuse' plugin" in message+ assert "hermes plugins install langfuse" in message+ assert "moved out of core" not in _unknown_plugin_message("nonexistent")diff --git a/tests/hermes_cli/test_tools_config_post_setup.py b/tests/hermes_cli/test_tools_config_post_setup.pyindex 1e4108ddc32..fb1fb3599be 100644--- a/tests/hermes_cli/test_tools_config_post_setup.py+++ b/tests/hermes_cli/test_tools_config_post_setup.py@@ -114,54 +114,3 @@ def test_importable_sdk_does_not_bypass_pm_constraints(monkeypatch, capsys, key,assert "Restart Hermes" not in outputelse:assert "Restart Hermes" in output--[email protected]("failure", [None, "sdk", "admission"])-def test_langfuse_setup_uses_plugin_admission_and_preserves_config_on_refusal(- monkeypatch, tmp_path, capsys, failure,-):- from hermes_cli.config import get_hermes_home, read_raw_config-- monkeypatch.setenv("HERMES_RUNTIME_DIR", str(tmp_path / "runtime"))- monkeypatch.setitem(sys.modules, "langfuse", ModuleType("langfuse"))- config_path = get_hermes_home() / "config.yaml"- config_path.write_text(- "plugins:\n enabled: [other]\n disabled: [langfuse, observability/langfuse]\n",- encoding="utf-8",- )- before = config_path.read_bytes()-- def resolve_candidate(**kwargs):- assert kwargs["explicit"] is True- assert kwargs["plugins"].data["enabled"]- if failure == "admission":- raise pm.InstallError("venv", "candidate refused")- # The real admission publisher must commit both lists, not a second UI writer.- from pm.publication import PluginSelection- from pm.paths import repo_root- from hermes_cli.runtime_state import runtime_lock, finish_publication- with runtime_lock(repo_root()):- PluginSelection(dict(kwargs["plugins"].data)).publish(repo_root())- finish_publication(repo_root())-- with (- patch("pm.sync_venv", side_effect=pm.InstallError("venv", "SDK refused") if failure == "sdk" else None) as sdk,- patch("pm.client.sync_venv", side_effect=resolve_candidate) as admission,- ):- _run_post_setup("langfuse")-- sdk.assert_called_once_with(["langfuse"], explicit=True)- if failure == "sdk":- admission.assert_not_called()- else:- admission.assert_called_once()- if failure:- assert config_path.read_bytes() == before- output = capsys.readouterr().out- assert "refused" in output- if failure == "sdk":- assert "Retry with: hermes tools" in output- else:- plugin_config = read_raw_config()["plugins"]- assert set(plugin_config["enabled"]) == {"other", "observability/langfuse"}- assert plugin_config["disabled"] == []diff --git a/tests/plugins/test_langfuse_max_depth.py b/tests/plugins/test_langfuse_max_depth.pydeleted file mode 100644index 102740a9f21..00000000000--- a/tests/plugins/test_langfuse_max_depth.py+++ /dev/null@@ -1,82 +0,0 @@-"""Configurable Langfuse payload depth regression for #116609."""--import importlib-import json--import pytest--[email protected](autouse=True)-def _fresh_max_depth_cache():- """``_resolve_max_depth`` is an ``lru_cache`` keyed on the raw env string, so its- once-per-value warning persists for the whole process. Clear it around every test- or an earlier resolution of the same invalid value (another test, a repeat run)- silently turns the "exactly one warning" assertions into 0 warnings."""- plugin = importlib.import_module("plugins.observability.langfuse")- plugin._resolve_max_depth.cache_clear()- yield- plugin._resolve_max_depth.cache_clear()--[email protected]("mode", ["sanitized", "full"])[email protected]("configured_depth", [None, "", "0", "4", "5", " 10 "])-def test_capture_respects_configured_depth_for_tool_inputs_and_outputs(- monkeypatch, mode, configured_depth,-):- plugin = importlib.import_module("plugins.observability.langfuse")- monkeypatch.setenv("HERMES_LANGFUSE_CAPTURE", mode)- if configured_depth is None:- monkeypatch.delenv("HERMES_LANGFUSE_MAX_DEPTH", raising=False)- else:- monkeypatch.setenv("HERMES_LANGFUSE_MAX_DEPTH", configured_depth)- max_depth = int(configured_depth) if configured_depth else 4-- # Each dict value/list element adds one level; scalars at the limit survive.- for leaf_depth in range(7):- payload = 7- expected = 7 if leaf_depth <= max_depth else "<max-depth>"- for level in reversed(range(leaf_depth)):- payload = {"data": payload} if level % 2 == 0 else [payload]- if level <= max_depth:- expected = {"data": expected} if level % 2 == 0 else [expected]- assert plugin._capture_content(payload) == expected- assert plugin._capture_content(- payload, tool_result_of=("example", {}),- ) == expected- assert plugin._capture_content(- json.dumps(payload), tool_result_of=("example", {}),- ) == (str(expected) if leaf_depth == 0 else expected)--[email protected]("invalid_depth", ["nope", "1.5", "-1"])-def test_invalid_max_depth_warns_and_preserves_default_capture(monkeypatch, caplog, invalid_depth):- plugin = importlib.import_module("plugins.observability.langfuse")- monkeypatch.setenv("HERMES_LANGFUSE_CAPTURE", "full")- monkeypatch.delenv("HERMES_LANGFUSE_MAX_DEPTH", raising=False)- payload = {"result": {"data": {"results": [{"index": 0}]}}}- default_capture = plugin._capture_content(payload)- monkeypatch.setenv("HERMES_LANGFUSE_MAX_DEPTH", invalid_depth)-- assert plugin._capture_content(payload) == default_capture- assert len(caplog.records) == 1- assert "HERMES_LANGFUSE_MAX_DEPTH" in caplog.text- assert "non-negative integer" in caplog.text---def test_invalid_max_depth_warns_once_per_value_not_per_payload(monkeypatch, caplog):- """A bad ``HERMES_LANGFUSE_MAX_DEPTH`` must not log one warning per captured prompt/tool payload- for the life of the process; a changed (still bad) value gets its own single warning."""- plugin = importlib.import_module("plugins.observability.langfuse")- monkeypatch.setenv("HERMES_LANGFUSE_CAPTURE", "full")- monkeypatch.setenv("HERMES_LANGFUSE_MAX_DEPTH", "abc")- payload = {"result": {"data": [{"index": 0}]}}-- for _ in range(5):- plugin._capture_content(payload)- plugin._capture_content(payload, tool_result_of=("example", {}))- assert sum("HERMES_LANGFUSE_MAX_DEPTH" in r.getMessage() for r in caplog.records) == 1-- monkeypatch.setenv("HERMES_LANGFUSE_MAX_DEPTH", "-7")- for _ in range(3):- plugin._capture_content(payload)- assert sum("HERMES_LANGFUSE_MAX_DEPTH" in r.getMessage() for r in caplog.records) == 2diff --git a/tests/plugins/test_langfuse_plugin.py b/tests/plugins/test_langfuse_plugin.pydeleted file mode 100644index 178464f1a49..00000000000--- a/tests/plugins/test_langfuse_plugin.py+++ /dev/null@@ -1,2261 +0,0 @@-"""Tests for the bundled observability/langfuse plugin."""-from __future__ import annotations--import importlib-import logging-import sys-from decimal import Decimal-from pathlib import Path-from types import SimpleNamespace--import pytest---# ----------------------------------------------------------------------------# Plugin discovery: langfuse is opt-in (not loaded unless explicitly enabled).-# This guards against someone accidentally re-introducing a per-hook-# load_config() gate or making the plugin auto-load.-# -----------------------------------------------------------------------------class TestDiscovery:- def test_plugin_is_discovered_as_standalone_opt_in(self, tmp_path, monkeypatch):- """Scanner should find the plugin but NOT load it by default."""- from hermes_cli import plugins as plugins_mod-- # Isolated HERMES_HOME so we don't read the developer's config.yaml.- home = tmp_path / ".hermes"- home.mkdir()- monkeypatch.setenv("HERMES_HOME", str(home))- monkeypatch.setattr(Path, "home", lambda: tmp_path)-- manager = plugins_mod.PluginManager()- manager.discover_and_load()-- # observability/langfuse appears in the plugin registry …- loaded = manager._plugins.get("observability/langfuse")- assert loaded is not None, "plugin not discovered"- # … but is not loaded (opt-in default → no config.yaml means nothing enabled)- assert loaded.enabled is False- assert "not enabled" in (loaded.error or "").lower()---# ----------------------------------------------------------------------------# Runtime gate: _get_langfuse() returns None and caches _INIT_FAILED when-# credentials are missing. Guards against regressing toward the rejected-# per-hook load_config() design.-# -----------------------------------------------------------------------------class TestRuntimeGate:- def _fresh_plugin(self):- """Import the plugin module fresh (clears any cached client)."""- mod_name = "plugins.observability.langfuse"- sys.modules.pop(mod_name, None)- return importlib.import_module(mod_name)-- def test_get_langfuse_returns_none_without_credentials(self, monkeypatch):- for k in (- "HERMES_LANGFUSE_PUBLIC_KEY", "HERMES_LANGFUSE_SECRET_KEY",- "LANGFUSE_PUBLIC_KEY", "LANGFUSE_SECRET_KEY",- ):- monkeypatch.delenv(k, raising=False)-- langfuse_plugin = self._fresh_plugin()- assert langfuse_plugin._get_langfuse() is None-- def test_missing_sdk_logs_one_warning(self, monkeypatch, caplog):- langfuse_plugin = self._fresh_plugin()- monkeypatch.setattr(langfuse_plugin, "Langfuse", None)- langfuse_plugin._LANGFUSE_CLIENT = None-- with caplog.at_level(logging.WARNING, logger=langfuse_plugin.__name__):- assert langfuse_plugin._get_langfuse() is None- assert langfuse_plugin._get_langfuse() is None-- messages = [record.getMessage() for record in caplog.records]- assert len(messages) == 1---# ----------------------------------------------------------------------------# Hooks are inert when the client is unavailable.-# -----------------------------------------------------------------------------class TestHooksInert:- def test_hooks_noop_without_client(self, monkeypatch):- """All 6 hooks must return without raising when _get_langfuse() is None."""- for k in (- "HERMES_LANGFUSE_PUBLIC_KEY", "HERMES_LANGFUSE_SECRET_KEY",- "LANGFUSE_PUBLIC_KEY", "LANGFUSE_SECRET_KEY",- ):- monkeypatch.delenv(k, raising=False)-- sys.modules.pop("plugins.observability.langfuse", None)- import importlib- mod = importlib.import_module("plugins.observability.langfuse")-- # Each hook should just return; no exceptions.- mod.on_pre_llm_call(task_id="t", session_id="s", messages=[{"role": "user", "content": "hi"}])- mod.on_pre_llm_request(task_id="t", session_id="s", api_call_count=1, request_messages=[])- mod.on_post_llm_call(task_id="t", session_id="s", api_call_count=1)- mod.on_pre_tool_call(tool_name="read_file", args={}, task_id="t", session_id="s")- mod.on_post_tool_call(tool_name="read_file", args={}, result="ok", task_id="t", session_id="s")---class TestPayloadSanitization:- def test_safe_value_redacts_base64_data_uri_instead_of_truncating(self):- sys.modules.pop("plugins.observability.langfuse", None)- import importlib- mod = importlib.import_module("plugins.observability.langfuse")-- payload = "data:image/png;base64," + ("a" * 20000)- result = mod._safe_value(payload)-- assert result == {- "type": "data_uri",- "media_type": "image/png",- "omitted": True,- "length": len(payload),- }-- def test_serialize_messages_redacts_data_uri_parts(self):- sys.modules.pop("plugins.observability.langfuse", None)- import importlib- mod = importlib.import_module("plugins.observability.langfuse")-- payload = "data:image/jpeg;base64," + ("b" * 20000)- serialized = mod._serialize_messages([- {"role": "user", "content": [{"type": "image_url", "image_url": {"url": payload}}]}- ])-- assert serialized[0]["content"][0]["image_url"]["url"] == {- "type": "data_uri",- "media_type": "image/jpeg",- "omitted": True,- "length": len(payload),- }---# ----------------------------------------------------------------------------# End-to-end collision regression: two turns of ONE gateway session must not-# share trace state. The helper-level tests above prove _trace_key returns-# distinct keys; this drives the real pre/post hooks to prove the keys are-# actually threaded through so the second turn gets its own root trace.-#-# Gateway reality this reproduces:-# * task_id == session_id for every turn (gateway/run.py)-# * turn_id is unique per turn (turn_context.py)-# * api_call_count resets to 1 each turn (conversation_loop.py)-#-# Before the turn/request scoping, _trace_key collapsed to the constant-# session_id. That worked only because _finish_trace pops the key on a clean-# turn end. When turn 1 does NOT finalize (interrupted, tool-only final step,-# or empty final content), its state lingered under session_id and turn 2-# silently merged into turn 1's trace instead of opening its own.-# ------------------------------------------------------------------------------class TestTurnTraceIsolation:- def _fresh_plugin(self):- sys.modules.pop("plugins.observability.langfuse", None)- return importlib.import_module("plugins.observability.langfuse")-- @staticmethod- def _fake_client(started):- """A minimal Langfuse stand-in that records each root trace opened.-- ``_start_root_trace`` calls ``create_trace_id`` then opens a root via- ``start_as_current_observation(...)`` (a context manager whose- ``__enter__`` returns the root span). We record one entry per root- actually opened so the test can count distinct traces.- """-- class _Span:- def update(self, **kw):- pass-- def end(self, **kw):- pass-- def set_trace_io(self, **kw):- pass-- def start_observation(self, **kw):- return _Span()-- class _RootCM:- def __enter__(self):- return _Span()-- def __exit__(self, *exc):- return False-- class _Client:- def create_trace_id(self, seed=None):- return f"trace::{seed}"-- def start_as_current_observation(self, **kw):- started.append(kw.get("trace_context", {}).get("trace_id"))- return _RootCM()-- def flush(self):- pass-- return _Client()-- def _run_turn(self, mod, *, session, turn_n, finalize):- """Drive one turn through the request-scoped hooks the gateway fires."""- task_id = session # gateway sets task_id == session_id- turn_id = f"{session}:{task_id}:turn{turn_n}"- api_call_count = 1 # resets every turn- api_request_id = f"{turn_id}:api:{api_call_count}"-- mod.on_pre_llm_request(- task_id=task_id,- session_id=session,- model="m",- provider="p",- api_mode="chat",- api_call_count=api_call_count,- request_messages=[{"role": "user", "content": "hi"}],- turn_id=turn_id,- api_request_id=api_request_id,- )- # finalize=False => leave a tool call on the final response so- # _finish_trace is skipped and the turn's state lingers.- mod.on_post_llm_call(- task_id=task_id,- session_id=session,- model="m",- provider="p",- api_mode="chat",- api_call_count=api_call_count,- assistant_content_chars=5 if finalize else 0,- assistant_tool_call_count=0 if finalize else 1,- usage={"input_tokens": 10, "output_tokens": 5},- turn_id=turn_id,- api_request_id=api_request_id,- )-- def test_unfinalized_turn_does_not_capture_next_turn(self, monkeypatch):- """A turn that never finalizes must not absorb the following turn."""- mod = self._fresh_plugin()- started: list = []- monkeypatch.setattr(mod, "_get_langfuse", lambda: self._fake_client(started))- monkeypatch.setattr(mod, "_end_observation", lambda *a, **k: None)- mod._TRACE_STATE.clear()-- # Turn 1 ends without finalizing (its final step still has a tool call).- self._run_turn(mod, session="sess-iso", turn_n=1, finalize=False)- # Turn 2 is a normal, fully finalizing turn in the SAME session.- self._run_turn(mod, session="sess-iso", turn_n=2, finalize=True)-- # Each turn opened its OWN root trace. On the pre-fix code the second- # turn reused turn 1's lingering state and only one trace was opened.- assert len(started) == 2-- # Turn 2 finalized and was popped by _finish_trace; only turn 1's- # (non-finalizing) state lingers. Assert the surviving key is turn 1's- # and that turn 2 never merged into it — `all(...)` over an empty set- # would pass vacuously, so pin the exact surviving key instead.- keys = list(mod._TRACE_STATE.keys())- assert len(keys) == 1- assert "turn1" in keys[0]- assert "turn2" not in keys[0]-- def test_pre_and_post_hooks_share_one_key_within_a_turn(self, monkeypatch):- """turn_id is preferred over api_request_id so the turn-scoped- post_llm_call (which carries no api_request_id) still resolves to the- same key as the request-scoped pre/post_api_request hooks. If the- ordering were reversed, finalization would silently break."""- mod = self._fresh_plugin()- turn_id = "S:T:turnX"- api_request_id = f"{turn_id}:api:1"-- k_pre_api = mod._trace_key("T", "S", turn_id=turn_id, api_request_id=api_request_id)- k_post_api = mod._trace_key("T", "S", turn_id=turn_id, api_request_id=api_request_id)- k_post_turn = mod._trace_key("T", "S", turn_id=turn_id, api_request_id="")-- assert k_pre_api == k_post_api == k_post_turn-- def test_non_finalizing_turns_do_not_grow_state_unboundedly(self, monkeypatch):- """Per-turn keys mean a turn that never finalizes leaves a lingering- entry. Without a cap that grows once per non-finalizing turn forever;- the LRU eviction must bound _TRACE_STATE at _MAX_TRACE_STATE.- """- mod = self._fresh_plugin()- started: list = []- monkeypatch.setattr(mod, "_get_langfuse", lambda: self._fake_client(started))- monkeypatch.setattr(mod, "_end_observation", lambda *a, **k: None)- monkeypatch.setattr(mod, "_MAX_TRACE_STATE", 8)- mod._TRACE_STATE.clear()-- # Far more non-finalizing turns than the cap.- for n in range(50):- self._run_turn(mod, session="sess-leak", turn_n=n, finalize=False)-- assert len(mod._TRACE_STATE) <= 8- # The survivors are the most-recently-updated turns (LRU eviction).- surviving = sorted(int(k.rsplit("turn", 1)[1]) for k in mod._TRACE_STATE)- assert surviving == list(range(42, 50))-- def test_finish_trace_exits_root_context_manager(self, monkeypatch):- """_finish_trace must call root_ctx.__exit__(), not just root_span.end().-- Regression for the "Exception ignored in: <generator>" traceback- on CLI exit. The plugin enters the root observation's context- manager (start_as_current_observation(...).__enter__()) but must- also exit it; otherwise the generator is left suspended and is- only unwound when the GC collects it during interpreter teardown.- By then opentelemetry.trace.Span has been set to None, and the- generator's close() -> use_span.__exit__ -> isinstance(span, Span)- raises TypeError: isinstance() arg 2 must be a type. Exiting the- context manager here unwinds the generator while modules are intact.- """- mod = self._fresh_plugin()- started: list = []- monkeypatch.setattr(mod, "_end_observation", lambda *a, **k: None)- mod._TRACE_STATE.clear()-- exited: list = []-- class _S:- def update(self, **kw): pass- def end(self, **kw): pass- def set_trace_io(self, **kw): pass- def start_observation(self, **kw): return _S()-- class _TrackingRootCM:- def __enter__(self):- return _S()- def __exit__(self, *exc):- exited.append(exc)- return False-- class _TrackingClient:- def create_trace_id(self, seed=None):- return f"trace::{seed}"- def start_as_current_observation(self, **kw):- started.append(kw.get("trace_context", {}).get("trace_id"))- return _TrackingRootCM()- def flush(self):- pass-- monkeypatch.setattr(mod, "_get_langfuse", lambda: _TrackingClient())-- self._run_turn(mod, session="sess-exit", turn_n=1, finalize=True)-- assert exited, (- "_finish_trace did not call root_ctx.__exit__; the generator is "- "left suspended and will raise TypeError on GC at interpreter "- "teardown when opentelemetry.trace.Span is None"- )- assert len(exited) == 1- assert exited[0] == (None, None, None)---# ----------------------------------------------------------------------------# Placeholder-credential guard (#23823).-#-# Regression coverage for the silent-failure bug: when an operator leaves-# HERMES_LANGFUSE_PUBLIC_KEY / SECRET_KEY at a template value like-# "placeholder", "test-key", or "your-langfuse-key", the SDK accepts the-# credentials at construction time (it does no server-side validation-# eagerly) but drops every trace at flush time, with no signal in the-# Hermes logs. The fix in `_get_langfuse()` validates the documented-# `pk-lf-` / `sk-lf-` prefix Langfuse always issues, surfaces a one-shot-# warning naming the offending env var(s), and short-circuits via the-# same `_INIT_FAILED` path used for missing credentials so subsequent-# hook invocations don't re-log.-# ------------------------------------------------------------------------------class _FakeLangfuse:- """Stand-in for the real :class:`langfuse.Langfuse` so tests don't- need the optional ``langfuse`` SDK installed. The plugin's runtime- gate refuses to proceed past ``if Langfuse is None`` when the SDK- is missing, which would short-circuit before the placeholder check- can fire. Patching ``plugin.Langfuse`` with this class lets the- placeholder validator exercise its full code path."""-- instances: list[_FakeLangfuse] = []-- def __init__(self, **kwargs):- self.kwargs = kwargs- _FakeLangfuse.instances.append(self)---class TestPlaceholderKeyDetection:- LOGGER_NAME = "plugins.observability.langfuse"-- def _fresh_plugin(self, monkeypatch=None):- mod_name = "plugins.observability.langfuse"- sys.modules.pop(mod_name, None)- mod = importlib.import_module(mod_name)- if monkeypatch is not None:- # Pretend the SDK is installed so `_get_langfuse()` actually- # reaches the placeholder check. Real SDK calls are never- # made because the placeholder/missing-credentials paths- # return before constructing a client.- _FakeLangfuse.instances.clear()- monkeypatch.setattr(mod, "Langfuse", _FakeLangfuse, raising=False)- return mod-- @staticmethod- def _clear_env(monkeypatch):- for k in (- "HERMES_LANGFUSE_PUBLIC_KEY", "HERMES_LANGFUSE_SECRET_KEY",- "LANGFUSE_PUBLIC_KEY", "LANGFUSE_SECRET_KEY",- ):- monkeypatch.delenv(k, raising=False)-- # -- helper unit tests (no SDK stub needed: these don't go through- # _get_langfuse, they exercise the pure-Python helpers directly) --------- def test_validate_langfuse_key_accepts_documented_prefix(self, monkeypatch):- self._clear_env(monkeypatch)- plugin = self._fresh_plugin()- assert plugin._validate_langfuse_key(- "HERMES_LANGFUSE_PUBLIC_KEY", "pk-lf-real-public-xyz"- ) is None- assert plugin._validate_langfuse_key(- "HERMES_LANGFUSE_SECRET_KEY", "sk-lf-real-secret-xyz"- ) is None--- # -- end-to-end _get_langfuse() behaviour --------------------------------- # These tests pass `monkeypatch` to _fresh_plugin() so the helper can- # stub out `Langfuse` (the optional SDK). Without that, every call- # short-circuits at `if Langfuse is None` before reaching the- # placeholder validator — masking the very behaviour we're testing.-- def test_placeholder_public_key_warns_and_skips(self, monkeypatch, caplog):- self._clear_env(monkeypatch)- monkeypatch.setenv("HERMES_LANGFUSE_PUBLIC_KEY", "placeholder")- monkeypatch.setenv("HERMES_LANGFUSE_SECRET_KEY", "sk-lf-real-secret-xyz")- plugin = self._fresh_plugin(monkeypatch)- with caplog.at_level(logging.WARNING, logger=self.LOGGER_NAME):- assert plugin._get_langfuse() is None- text = caplog.text- assert "HERMES_LANGFUSE_PUBLIC_KEY" in text- assert "'placeholder'" in text- assert "pk-lf-" in text- # The valid secret value must NOT appear (the var NAME does, in- # the "or unset ..." hint, but the value preview shouldn't).- assert "'sk-lf-" not in text- # Never constructed the SDK client — short-circuited before that.- assert _FakeLangfuse.instances == []-- def test_placeholder_secret_key_warns_and_skips(self, monkeypatch, caplog):- self._clear_env(monkeypatch)- monkeypatch.setenv("HERMES_LANGFUSE_PUBLIC_KEY", "pk-lf-real-public-xyz")- monkeypatch.setenv("HERMES_LANGFUSE_SECRET_KEY", "test-key")- plugin = self._fresh_plugin(monkeypatch)- with caplog.at_level(logging.WARNING, logger=self.LOGGER_NAME):- assert plugin._get_langfuse() is None- text = caplog.text- assert "HERMES_LANGFUSE_SECRET_KEY" in text- assert "'test-key'" in text- assert "sk-lf-" in text- # The valid public value must NOT appear.- assert "'pk-lf-" not in text- assert _FakeLangfuse.instances == []-- def test_both_placeholders_one_warning_with_both_keys(self, monkeypatch, caplog):- self._clear_env(monkeypatch)- monkeypatch.setenv("HERMES_LANGFUSE_PUBLIC_KEY", "placeholder")- monkeypatch.setenv("HERMES_LANGFUSE_SECRET_KEY", "placeholder")- plugin = self._fresh_plugin(monkeypatch)- with caplog.at_level(logging.WARNING, logger=self.LOGGER_NAME):- assert plugin._get_langfuse() is None- warnings = [r for r in caplog.records if r.levelname == "WARNING"- and r.name == self.LOGGER_NAME]- assert len(warnings) == 1, (- f"Expected a single combined warning; got {len(warnings)}:\n"- + "\n".join(r.getMessage() for r in warnings)- )- text = warnings[0].getMessage()- assert "HERMES_LANGFUSE_PUBLIC_KEY" in text- assert "HERMES_LANGFUSE_SECRET_KEY" in text-- def test_repeated_calls_do_not_re_warn(self, monkeypatch, caplog):- """The cached ``_INIT_FAILED`` sentinel must short-circuit- subsequent calls so each hook invocation isn't a fresh log- line — otherwise a busy gateway will spam the operator's- terminal."""- self._clear_env(monkeypatch)- monkeypatch.setenv("HERMES_LANGFUSE_PUBLIC_KEY", "placeholder")- monkeypatch.setenv("HERMES_LANGFUSE_SECRET_KEY", "placeholder")- plugin = self._fresh_plugin(monkeypatch)- with caplog.at_level(logging.WARNING, logger=self.LOGGER_NAME):- for _ in range(15):- assert plugin._get_langfuse() is None- warnings = [r for r in caplog.records if r.levelname == "WARNING"- and r.name == self.LOGGER_NAME]- assert len(warnings) == 1, (- f"Warning fired {len(warnings)} times across 15 calls; "- "expected 1 (cached via _INIT_FAILED)"- )---class TestRequestMessageCoercion:- def test_prefers_request_messages_then_messages_then_history_then_user_message(self):- sys.modules.pop("plugins.observability.langfuse", None)- mod = importlib.import_module("plugins.observability.langfuse")-- assert mod._coerce_request_messages(- request_messages=[{"role": "system", "content": "s"}],- messages=[{"role": "user", "content": "m"}],- conversation_history=[{"role": "user", "content": "h"}],- user_message="u",- ) == [{"role": "system", "content": "s"}]- assert mod._coerce_request_messages(- messages=[{"role": "user", "content": "m"}],- conversation_history=[{"role": "user", "content": "h"}],- user_message="u",- ) == [{"role": "user", "content": "m"}]- assert mod._coerce_request_messages(- conversation_history=[{"role": "user", "content": "h"}],- user_message="u",- ) == [{"role": "user", "content": "h"}]- assert mod._coerce_request_messages(user_message="u") == [{"role": "user", "content": "u"}]---class TestAssistantMessageSerialization:- def test_serialize_assistant_message_prefers_reasoning(self):- sys.modules.pop("plugins.observability.langfuse", None)- mod = importlib.import_module("plugins.observability.langfuse")-- message = SimpleNamespace(- content="answer",- reasoning="primary reasoning",- reasoning_content="fallback reasoning",- reasoning_details=[{"type": "summary", "text": "structured reasoning"}],- )-- assert mod._serialize_assistant_message(message)["reasoning"] == "primary reasoning"-- def test_serialize_assistant_message_uses_reasoning_content_when_reasoning_absent(self):- sys.modules.pop("plugins.observability.langfuse", None)- mod = importlib.import_module("plugins.observability.langfuse")-- message = SimpleNamespace(- content="answer",- reasoning=None,- reasoning_content="provider scratchpad",- reasoning_details=[{"type": "summary", "text": "structured reasoning"}],- )-- assert mod._serialize_assistant_message(message)["reasoning"] == "provider scratchpad"-- def test_serialize_assistant_message_uses_structured_reasoning_details(self):- sys.modules.pop("plugins.observability.langfuse", None)- mod = importlib.import_module("plugins.observability.langfuse")-- reasoning_details = [- {"type": "summary", "text": "checked tools"},- {"type": "encrypted_content", "encrypted_content": b"opaque"},- ]- message = SimpleNamespace(- content="answer",- reasoning=None,- reasoning_content=None,- reasoning_details=reasoning_details,- )-- assert mod._serialize_assistant_message(message)["reasoning"] == [- {"type": "summary", "text": "checked tools"},- {"type": "encrypted_content", "encrypted_content": {"type": "bytes", "len": 6}},- ]-- def test_serialize_assistant_message_without_reasoning_fields_sets_none(self):- sys.modules.pop("plugins.observability.langfuse", None)- mod = importlib.import_module("plugins.observability.langfuse")-- message = SimpleNamespace(content="answer")-- assert mod._serialize_assistant_message(message)["reasoning"] is None---class TestToolCallOutputBackfill:- def test_post_tool_call_backfills_matching_turn_tool_call_output(self, monkeypatch):- sys.modules.pop("plugins.observability.langfuse", None)- mod = importlib.import_module("plugins.observability.langfuse")-- observation = object()- state = mod.TraceState(trace_id="trace-1", root_ctx=None, root_span=None)- state.tools["call-1"] = observation- state.turn_tool_calls.append({- "id": "call-1",- "type": "function",- "name": "web_extract",- "arguments": '{"urls": ["https://example.com"]}',- "function": {- "name": "web_extract",- "arguments": '{"urls": ["https://example.com"]}',- },- })-- task_key = mod._trace_key("task-1", "session-1")- monkeypatch.setitem(mod._TRACE_STATE, task_key, state)-- ended = {}-- def fake_end_observation(obs, *, output=None, metadata=None, usage_details=None, cost_details=None):- ended["observation"] = obs- ended["output"] = output- ended["metadata"] = metadata-- monkeypatch.setattr(mod, "_end_observation", fake_end_observation)-- mod.on_post_tool_call(- tool_name="web_extract",- args={"urls": ["https://example.com"]},- result='{"results": [{"url": "https://example.com", "content": "Example Domain"}]}',- task_id="task-1",- session_id="session-1",- tool_call_id="call-1",- )-- assert ended["observation"] is observation- assert state.turn_tool_calls[0]["output"] == ended["output"]- assert state.turn_tool_calls[0]["function"]["output"] == ended["output"]- assert state.turn_tool_calls[0]["output"] == {- "results": [{"url": "https://example.com", "content": "Example Domain"}]- }-- def test_serialize_messages_keeps_tool_name_and_call_id(self):- sys.modules.pop("plugins.observability.langfuse", None)- mod = importlib.import_module("plugins.observability.langfuse")-- messages = [{- "role": "tool",- "name": "web_extract",- "tool_call_id": "call-1",- "content": '{"ok": true}',- }]-- assert mod._serialize_messages(messages) == [{- "role": "tool",- "name": "web_extract",- "tool_call_id": "call-1",- "content": {"ok": True},- }]---class TestToolObservationKeying:- """Tests for pre/post tool_call observation matching when tool_call_id is absent."""-- def _make_mod(self):- sys.modules.pop("plugins.observability.langfuse", None)- return importlib.import_module("plugins.observability.langfuse")-- def test_empty_tool_call_id_single_tool_sets_output(self, monkeypatch):- mod = self._make_mod()- obs = object()- state = mod.TraceState(trace_id="t", root_ctx=None, root_span=None)- state.pending_tools_by_name.setdefault("my_tool", []).append(obs)-- task_key = mod._trace_key("task-1", "sess-1")- monkeypatch.setitem(mod._TRACE_STATE, task_key, state)-- ended = {}-- def fake_end(o, *, output=None, metadata=None, **kw):- ended["obs"] = o- ended["output"] = output-- monkeypatch.setattr(mod, "_end_observation", fake_end)-- mod.on_post_tool_call(- tool_name="my_tool",- args={},- result='{"ok": true}',- task_id="task-1",- session_id="sess-1",- tool_call_id="",- )-- assert ended["obs"] is obs- assert ended["output"] == {"ok": True}- assert state.pending_tools_by_name.get("my_tool") is None--- def test_threaded_post_calls_preserve_fifo_under_lock(self, monkeypatch):- """The actual concurrency contract: when 8 threads race to drain- the pending queue, no observation is consumed twice and none is- lost. Validates ``_STATE_LOCK`` discipline, not Python list- semantics."""- import threading-- mod = self._make_mod()- n = 8- observations = [object() for _ in range(n)]- state = mod.TraceState(trace_id="t", root_ctx=None, root_span=None)- state.pending_tools_by_name["web_extract"] = list(observations)-- task_key = mod._trace_key("task-thr", "sess-thr")- monkeypatch.setitem(mod._TRACE_STATE, task_key, state)-- recorded: list = []- lock = threading.Lock()-- def fake_end(o, *, output=None, metadata=None, **kw):- with lock:- recorded.append(o)-- monkeypatch.setattr(mod, "_end_observation", fake_end)-- barrier = threading.Barrier(n)-- def worker():- barrier.wait()- mod.on_post_tool_call(- tool_name="web_extract", args={}, result='{"ok": true}',- task_id="task-thr", session_id="sess-thr", tool_call_id="",- )-- threads = [threading.Thread(target=worker) for _ in range(n)]- for t in threads:- t.start()- for t in threads:- t.join()-- # Every observation was consumed exactly once; queue is empty.- assert len(recorded) == n- assert set(map(id, recorded)) == set(map(id, observations))- assert state.pending_tools_by_name.get("web_extract") is None-- def test_explicit_tool_call_id_uses_tools_dict(self, monkeypatch):- """When tool_call_id is present, pending_tools_by_name is not touched."""- mod = self._make_mod()- obs = object()- state = mod.TraceState(trace_id="t", root_ctx=None, root_span=None)- state.tools["call-99"] = obs-- task_key = mod._trace_key("task-1", "sess-1")- monkeypatch.setitem(mod._TRACE_STATE, task_key, state)-- ended = {}-- def fake_end(o, *, output=None, metadata=None, **kw):- ended["obs"] = o- ended["output"] = output-- monkeypatch.setattr(mod, "_end_observation", fake_end)-- mod.on_post_tool_call(- tool_name="my_tool", args={}, result='{"status": "done"}',- task_id="task-1", session_id="sess-1", tool_call_id="call-99",- )-- assert ended["obs"] is obs- assert ended["output"] == {"status": "done"}- assert not state.tools---class TestUsageFromSanitizedResponse:- """Regression: ``post_api_request`` delivers ``response`` as a sanitized- dict (no ``.usage`` attribute) plus a separate ``usage`` summary dict. The- post-call handler must read the ``usage`` dict instead of treating the dict- response as a usage-bearing object and dropping all token/cost data."""-- def _setup(self, mod, monkeypatch):- # Active client so on_post_llm_call does not early-return.- monkeypatch.setattr(mod, "_get_langfuse", lambda: object())- observation = object()- state = mod.TraceState(trace_id="trace-1", root_ctx=None, root_span=None)- state.generations[mod._request_key(1)] = observation- monkeypatch.setitem(mod._TRACE_STATE, mod._trace_key("task-1", "session-1"), state)- captured = {}-- def fake_end_observation(obs, *, output=None, metadata=None, usage_details=None, cost_details=None):- captured["usage_details"] = usage_details-- monkeypatch.setattr(mod, "_end_observation", fake_end_observation)- return captured-- def test_sanitized_dict_response_uses_usage_dict(self, monkeypatch):- sys.modules.pop("plugins.observability.langfuse", None)- mod = importlib.import_module("plugins.observability.langfuse")- captured = self._setup(mod, monkeypatch)-- # A plain dict has no ``.usage`` attribute — mirrors post_api_request.- mod.on_post_llm_call(- task_id="task-1",- session_id="session-1",- api_call_count=1,- model="gemini-3-flash-preview",- response={"model": "gemini-3-flash-preview", "usage": {"input_tokens": 100, "output_tokens": 20}},- usage={"input_tokens": 100, "output_tokens": 20},- assistant_content_chars=42,- )-- # Before the fix the dict response shadowed the usage dict and tokens- # were lost (usage_details == {}).- assert captured["usage_details"] == {"input": 100, "output": 20}-- def test_real_response_object_with_usage_still_used(self, monkeypatch):- sys.modules.pop("plugins.observability.langfuse", None)- mod = importlib.import_module("plugins.observability.langfuse")- captured = self._setup(mod, monkeypatch)-- # A response object that genuinely carries usage must still take the- # response-object path (post_llm_call / legacy behavior).- seen = {}-- def fake_usage_and_cost(resp, **_):- seen["resp"] = resp- return {"input": 7, "output": 3}, {}-- monkeypatch.setattr(mod, "_usage_and_cost", fake_usage_and_cost)-- class _Resp:- usage = {"prompt_tokens": 7, "completion_tokens": 3}-- resp = _Resp()- mod.on_post_llm_call(- task_id="task-1",- session_id="session-1",- api_call_count=1,- model="gemini-3-flash-preview",- response=resp,- usage={"input_tokens": 999, "output_tokens": 999},- assistant_content_chars=42,- )-- assert seen["resp"] is resp- assert captured["usage_details"] == {"input": 7, "output": 3}---# ----------------------------------------------------------------------------# Model attribution: wire truth over stale agent attribute-# -----------------------------------------------------------------------------class TestModelAttribution:- def _fresh_plugin(self):- sys.modules.pop("plugins.observability.langfuse", None)- return importlib.import_module("plugins.observability.langfuse")-- def _client_capturing_generations(self, gens):- class _Gen:- def update(self, **kw): pass- def end(self, **kw): pass-- class _Span:- def update(self, **kw): pass- def end(self, **kw): pass- def set_trace_io(self, **kw): pass- def start_observation(self, **kw):- gens.append(kw)- return _Gen()-- class _RootCM:- def __enter__(self): return _Span()- def __exit__(self, *exc): return False-- class _Client:- def create_trace_id(self, seed=None): return "t"- def start_as_current_observation(self, **kw): return _RootCM()- def flush(self): pass-- return _Client()-- def test_pre_api_request_prefers_request_body_model(self, monkeypatch):- """Agent attribute says old model; request body says the switched one."""- mod = self._fresh_plugin()- gens: list = []- monkeypatch.setattr(mod, "_get_langfuse", lambda: self._client_capturing_generations(gens))- mod._TRACE_STATE.clear()-- mod.on_pre_llm_request(- task_id="t", session_id="s", turn_id="s:t:turn1",- api_call_count=1,- model="old-model-attr",- provider="openrouter",- request_messages=[{"role": "user", "content": "hi"}],- request={"body": {"model": "switched/new-model"}},- )- assert gens, "no generation started"- assert gens[0]["model"] == "switched/new-model"-- def test_pre_api_request_falls_back_to_attr_without_body_model(self, monkeypatch):- mod = self._fresh_plugin()- gens: list = []- monkeypatch.setattr(mod, "_get_langfuse", lambda: self._client_capturing_generations(gens))- mod._TRACE_STATE.clear()-- mod.on_pre_llm_request(- task_id="t", session_id="s", turn_id="s:t:turn2",- api_call_count=1,- model="attr-model",- request_messages=[{"role": "user", "content": "hi"}],- request={"body": {}},- )- assert gens[0]["model"] == "attr-model"-- def test_post_api_request_uses_response_model_for_cost(self, monkeypatch):- """Cost estimation must key off the model that actually served."""- mod = self._fresh_plugin()- monkeypatch.setattr(mod, "_get_langfuse", lambda: object())- mod._TRACE_STATE.clear()-- seen = {}- def fake_usage_and_cost(response, *, provider, api_mode, model, base_url):- seen["model"] = model- return {"input": 1, "output": 1}, {}- monkeypatch.setattr(mod, "_usage_and_cost", fake_usage_and_cost)-- class _Gen:- def update(self, **kw): pass- def end(self, **kw): pass-- class _Root:- def update(self, **kw): pass- def end(self, **kw): pass- def set_trace_io(self, **kw): pass-- turn_id = "s:t:turn3"- key = mod._trace_key("t", "s", turn_id=turn_id)- state = mod.TraceState(trace_id="x", root_ctx=None, root_span=_Root())- state.generations["1"] = _Gen()- mod._TRACE_STATE[key] = state-- class _Resp:- usage = {"prompt_tokens": 1, "completion_tokens": 1}-- mod.on_post_llm_call(- task_id="t", session_id="s", turn_id=turn_id, api_call_count=1,- model="stale-attr-model",- response_model="actual/served-model",- response=_Resp(),- assistant_content_chars=2,- )- assert seen["model"] == "actual/served-model"---# ----------------------------------------------------------------------------# Cost total: explicit "total" alongside the per-type breakdown-# -----------------------------------------------------------------------------class TestCostTotal:- """Langfuse ingests per-type ``cost_details`` keys but does not derive- ``calculatedTotalCost`` from them. Without an explicit ``total`` the- dashboard reads 0 for every priced generation."""-- def _fresh_plugin(self):- sys.modules.pop("plugins.observability.langfuse", None)- return importlib.import_module("plugins.observability.langfuse")-- def test_response_path_totals_the_breakdown(self):- mod = self._fresh_plugin()-- class _Usage:- input_tokens = 1000- output_tokens = 500- cache_read_input_tokens = 2000- cache_creation_input_tokens = 0-- class _Resp:- usage = _Usage()-- _, cost_details = mod._usage_and_cost(- _Resp(),- provider="anthropic",- api_mode="anthropic_messages",- model="claude-sonnet-4-6",- base_url="",- )-- components = {k: v for k, v in cost_details.items() if k != "total"}- assert components- assert cost_details["total"] == pytest.approx(sum(components.values()))-- def test_usage_summary_path_totals_the_breakdown(self, monkeypatch):- mod = self._fresh_plugin()- monkeypatch.setattr(mod, "_get_langfuse", lambda: object())- state = mod.TraceState(trace_id="trace-1", root_ctx=None, root_span=None)- state.generations[mod._request_key(1)] = object()- monkeypatch.setitem(mod._TRACE_STATE, mod._trace_key("task-1", "session-1"), state)- captured = {}-- def fake_end_observation(obs, *, output=None, metadata=None, usage_details=None, cost_details=None):- captured["cost_details"] = cost_details-- monkeypatch.setattr(mod, "_end_observation", fake_end_observation)-- # A dict response has no ``.usage``, so the handler takes the- # usage-summary path rather than the response-object path.- mod.on_post_llm_call(- task_id="task-1",- session_id="session-1",- api_call_count=1,- model="claude-sonnet-4-6",- provider="anthropic",- response={"model": "claude-sonnet-4-6"},- usage={"input_tokens": 1000, "output_tokens": 500},- assistant_content_chars=42,- )-- cost_details = captured["cost_details"]- components = {k: v for k, v in cost_details.items() if k != "total"}- assert components- assert cost_details["total"] == pytest.approx(sum(components.values()))-- def test_priced_model_with_no_tokens_reports_no_total(self):- mod = self._fresh_plugin()-- class _Usage:- input_tokens = 0- output_tokens = 0-- class _Resp:- usage = _Usage()-- _, cost_details = mod._usage_and_cost(- _Resp(),- provider="anthropic",- api_mode="anthropic_messages",- model="claude-sonnet-4-6",- base_url="",- )-- # A priced model that billed nothing writes no per-type keys, so- # summing them must not invent a 0.0 total on an empty breakdown.- assert cost_details == {}---# ----------------------------------------------------------------------------# Capture modes: metadata | sanitized | full (HERMES_LANGFUSE_CAPTURE)-# -----------------------------------------------------------------------------class TestCaptureModes:- def _fresh_plugin(self):- sys.modules.pop("plugins.observability.langfuse", None)- return importlib.import_module("plugins.observability.langfuse")-- def test_default_mode_is_sanitized(self, monkeypatch):- mod = self._fresh_plugin()- monkeypatch.delenv("HERMES_LANGFUSE_CAPTURE", raising=False)- assert mod._capture_mode() == "sanitized"-- def test_invalid_mode_falls_back_and_warns_once(self, monkeypatch, caplog):- mod = self._fresh_plugin()- monkeypatch.setenv("HERMES_LANGFUSE_CAPTURE", "everything")- with caplog.at_level(logging.WARNING):- assert mod._capture_mode() == "sanitized"- assert mod._capture_mode() == "sanitized"- warnings = [r for r in caplog.records if "HERMES_LANGFUSE_CAPTURE" in r.getMessage()]- assert len(warnings) == 1-- def test_metadata_mode_omits_content(self, monkeypatch):- mod = self._fresh_plugin()- monkeypatch.setenv("HERMES_LANGFUSE_CAPTURE", "metadata")- out = mod._capture_content("top secret prompt text")- assert out == {"omitted": True, "type": "text", "chars": 22}- obj = mod._capture_content({"password": "hunter22", "path": "/x"})- assert obj["omitted"] is True- assert set(obj["keys"]) == {"password", "path"}- assert "hunter22" not in str(obj)-- def test_metadata_mode_message_serialization_keeps_roles(self, monkeypatch):- mod = self._fresh_plugin()- monkeypatch.setenv("HERMES_LANGFUSE_CAPTURE", "metadata")- msgs = mod._serialize_messages([- {"role": "user", "content": "my ssn is 123-45-6789"},- {"role": "assistant", "content": "noted"},- ])- assert [m["role"] for m in msgs] == ["user", "assistant"]- assert all(isinstance(m["content"], dict) and m["content"]["omitted"] for m in msgs)- assert "6789" not in str(msgs)-- def test_sanitized_mode_redacts_secrets(self, monkeypatch):- mod = self._fresh_plugin()- monkeypatch.setenv("HERMES_LANGFUSE_CAPTURE", "sanitized")- samples = {- "openai": "here sk-" + "a" * 20 + " done",- "anthropic": "key sk-ant-" + "a" * 20 + " x",- "github": "tok ghp_" + "a" * 36,- "aws": "AKIA" + "A" * 16,- "langfuse": "pk-lf-" + "a" * 20,- "bearer": "Authorization: Bearer " + "a" * 20,- "assignment": 'api_key="supersecretvalue"',- }- for name, text in samples.items():- out = mod._capture_content(text)- # redact_sensitive_text masks secrets (e.g. "sk-aaa...aaaa") or- # replaces them with "«redacted:...»" sentinels — check that the- # original secret substring is gone, not for a specific marker.- assert text != out, f"{name} not redacted: {out!r}"-- def test_sanitized_mode_redacts_before_truncation(self, monkeypatch):- mod = self._fresh_plugin()- monkeypatch.setenv("HERMES_LANGFUSE_CAPTURE", "sanitized")- secret = "sk-" + "z" * 40- text = "x" * 100 + " " + secret + " " + "y" * 100- out = mod._truncate_text(text, 120)- assert "z" * 10 not in out- assert text != out, "secret was not redacted before truncation"-- def test_sanitized_mode_keeps_ordinary_text(self, monkeypatch):- mod = self._fresh_plugin()- monkeypatch.setenv("HERMES_LANGFUSE_CAPTURE", "sanitized")- text = "refactor the memory manager to emit spans"- assert mod._capture_content(text) == text-- def test_full_mode_keeps_secret_shaped_text(self, monkeypatch):- mod = self._fresh_plugin()- monkeypatch.setenv("HERMES_LANGFUSE_CAPTURE", "full")- text = "here sk-abcdefghijklmnop1234 done"- assert mod._capture_content(text) == text---# ----------------------------------------------------------------------------# api_request_error hook-# -----------------------------------------------------------------------------class TestApiRequestErrorHook:- def _fresh_plugin(self):- sys.modules.pop("plugins.observability.langfuse", None)- return importlib.import_module("plugins.observability.langfuse")-- def _seed_state(self, mod, task_key, gen_key="1"):- class _Gen:- def __init__(self):- self.updates = []- self.ended = False- def update(self, **kw):- self.updates.append(kw)- def end(self, **kw):- self.ended = True-- class _Root:- def __init__(self):- self.ended = False- def update(self, **kw): pass- def end(self, **kw): self.ended = True- def set_trace_io(self, **kw): pass-- gen = _Gen()- root = _Root()- state = mod.TraceState(trace_id="t", root_ctx=None, root_span=root)- state.generations[gen_key] = gen- mod._TRACE_STATE[task_key] = state- return gen, root-- def test_retryable_error_closes_generation_keeps_turn(self, monkeypatch):- mod = self._fresh_plugin()- monkeypatch.setattr(mod, "_get_langfuse", lambda: object())- mod._TRACE_STATE.clear()- turn_id = "s:t:turn1"- task_key = mod._trace_key("t", "s", turn_id=turn_id)- gen, root = self._seed_state(mod, task_key)-- mod.on_api_request_error(- task_id="t", session_id="s", api_call_count=1,- turn_id=turn_id,- status_code=429, retryable=True, retry_count=1, max_retries=3,- error={"type": "RateLimitError", "message": "slow down"},- )-- assert gen.ended is True- assert any(u.get("level") == "ERROR" for u in gen.updates)- # error metadata landed- meta = [u["metadata"] for u in gen.updates if "metadata" in u]- assert meta and meta[0]["status_code"] == 429- # turn stays open for the retry- assert task_key in mod._TRACE_STATE- assert root.ended is False-- def test_terminal_error_finishes_turn(self, monkeypatch):- mod = self._fresh_plugin()- monkeypatch.setattr(mod, "_get_langfuse", lambda: type("C", (), {"flush": lambda self: None})())- mod._TRACE_STATE.clear()- turn_id = "s:t:turn2"- task_key = mod._trace_key("t", "s", turn_id=turn_id)- gen, root = self._seed_state(mod, task_key)-- mod.on_api_request_error(- task_id="t", session_id="s", api_call_count=1,- turn_id=turn_id,- status_code=401, retryable=False,- error={"type": "AuthenticationError", "message": "bad key"},- )-- assert gen.ended is True- assert task_key not in mod._TRACE_STATE- assert root.ended is True-- def test_error_hook_noops_without_state(self, monkeypatch):- mod = self._fresh_plugin()- monkeypatch.setattr(mod, "_get_langfuse", lambda: object())- mod._TRACE_STATE.clear()- # Must not raise- mod.on_api_request_error(- task_id="t", session_id="s", api_call_count=1,- error={"type": "X", "message": "y"}, retryable=False,- )-- def test_error_message_respects_capture_mode(self, monkeypatch):- mod = self._fresh_plugin()- monkeypatch.setenv("HERMES_LANGFUSE_CAPTURE", "metadata")- monkeypatch.setattr(mod, "_get_langfuse", lambda: object())- mod._TRACE_STATE.clear()- turn_id = "s:t:turn3"- task_key = mod._trace_key("t", "s", turn_id=turn_id)- gen, _root = self._seed_state(mod, task_key)-- mod.on_api_request_error(- task_id="t", session_id="s", api_call_count=1, turn_id=turn_id,- retryable=True,- error={"type": "APIError", "message": "secret prompt echo sk-abc"},- )- meta = next(u["metadata"] for u in gen.updates if "metadata" in u)- assert isinstance(meta["error_message"], dict)- assert meta["error_message"]["omitted"] is True---# ----------------------------------------------------------------------------# on_session_finalize hook-# -----------------------------------------------------------------------------class TestSessionFinalizeHook:- def _fresh_plugin(self):- sys.modules.pop("plugins.observability.langfuse", None)- return importlib.import_module("plugins.observability.langfuse")-- def _client(self, flushes):- class _Client:- def flush(self):- flushes.append(1)- return _Client()-- def _state(self, mod):- class _Root:- def __init__(self):- self.ended = False- def update(self, **kw): pass- def end(self, **kw): self.ended = True- def set_trace_io(self, **kw): pass- root = _Root()- return mod.TraceState(trace_id="t", root_ctx=None, root_span=root), root-- def test_finalize_closes_matching_session_traces(self, monkeypatch):- mod = self._fresh_plugin()- flushes = []- client = self._client(flushes)- monkeypatch.setattr(mod, "_LANGFUSE_CLIENT", client)- monkeypatch.setattr(mod, "_get_langfuse", lambda: client)- mod._TRACE_STATE.clear()-- s1, r1 = self._state(mod)- s2, r2 = self._state(mod)- mod._TRACE_STATE["session:sess-a:turn:1"] = s1- mod._TRACE_STATE["session:sess-b:turn:1"] = s2-- mod.on_session_finalize(session_id="sess-a")-- assert "session:sess-a:turn:1" not in mod._TRACE_STATE- assert "session:sess-b:turn:1" in mod._TRACE_STATE- assert r1.ended is True- assert r2.ended is False- assert flushes # flushed at least once-- def test_finalize_without_session_closes_all(self, monkeypatch):- mod = self._fresh_plugin()- flushes = []- client = self._client(flushes)- monkeypatch.setattr(mod, "_LANGFUSE_CLIENT", client)- monkeypatch.setattr(mod, "_get_langfuse", lambda: client)- mod._TRACE_STATE.clear()-- s1, r1 = self._state(mod)- mod._TRACE_STATE["session:sess-x:turn:1"] = s1- mod.on_session_finalize()- assert not mod._TRACE_STATE- assert r1.ended is True-- def test_finalize_noop_when_client_never_initialized(self):- mod = self._fresh_plugin()- mod._TRACE_STATE.clear()- # _LANGFUSE_CLIENT is None on a fresh module; must not raise or init.- mod.on_session_finalize(session_id="whatever")-- def test_finalize_shuts_down_client_on_process_exit(self, monkeypatch):- """reason="shutdown" must call client.shutdown() while the interpreter- is alive, so the SDK's own atexit handler (which runs during- interpreter finalization, after opentelemetry.trace.Span is torn- down) becomes a no-op instead of raising the "isinstance() arg 2- must be a type" TypeError on quit."""- mod = self._fresh_plugin()- events = []-- class _Client:- def flush(self):- events.append("flush")-- def shutdown(self):- events.append("shutdown")-- client = _Client()- monkeypatch.setattr(mod, "_LANGFUSE_CLIENT", client)- monkeypatch.setattr(mod, "_get_langfuse", lambda: client)- mod._TRACE_STATE.clear()-- mod.on_session_finalize(session_id="sess-a", reason="shutdown")- assert "shutdown" in events- assert events.index("flush") < events.index("shutdown")-- def test_finalize_keeps_client_alive_on_session_rotation(self, monkeypatch):- """/new, /reset, and gateway session expiry finalize the session but- the process lives on — the cached client must NOT be shut down or- later sessions silently stop exporting."""- mod = self._fresh_plugin()- events = []-- class _Client:- def flush(self):- events.append("flush")-- def shutdown(self):- events.append("shutdown")-- client = _Client()- monkeypatch.setattr(mod, "_LANGFUSE_CLIENT", client)- monkeypatch.setattr(mod, "_get_langfuse", lambda: client)- mod._TRACE_STATE.clear()-- for reason in ("session_boundary", "new_session", "session_expired", ""):- mod.on_session_finalize(session_id="sess-a", reason=reason)- assert "shutdown" not in events- assert "flush" in events---# ----------------------------------------------------------------------------# Subagent tracing: delegated children as spans under the parent turn-# -----------------------------------------------------------------------------class TestSubagentTracing:- """``tools/delegate_tool.py`` emits subagent_start/subagent_stop. The- payloads carry ``parent_turn_id`` but no ``task_id``, so the parent trace- must be resolved by turn id rather than by rebuilding the scope key."""-- def _fresh_plugin(self):- sys.modules.pop("plugins.observability.langfuse", None)- return importlib.import_module("plugins.observability.langfuse")-- def _state(self, mod, monkeypatch, key, spans):- class _Obs:- def __init__(self, kw):- self.kw = kw- self.ended = False- self.updates = {}-- def update(self, **kw):- self.updates.update(kw)-- def end(self, **kw):- self.ended = True-- class _Root:- def start_observation(self, **kw):- obs = _Obs(kw)- spans.append(obs)- return obs-- monkeypatch.setattr(mod, "_get_langfuse", lambda: object())- state = mod.TraceState(trace_id="trace-1", root_ctx=None, root_span=_Root())- monkeypatch.setitem(mod._TRACE_STATE, key, state)- return state-- def test_start_attaches_span_despite_task_scoped_key(self, monkeypatch):- mod = self._fresh_plugin()- spans = []- # Key minted by the LLM hooks with a task id — a naive rebuild from- # session_id alone would not match this.- state = self._state(mod, monkeypatch, "task:task-9:turn:turn-7", spans)-- mod.on_subagent_start(- parent_session_id="sess-1",- parent_turn_id="turn-7",- child_session_id="child-sess-1",- child_subagent_id="sub-1",- child_role="researcher",- child_goal="find the thing",- )-- assert len(spans) == 1- assert spans[0].kw["name"] == "Subagent: researcher"- assert spans[0].kw["metadata"]["child_subagent_id"] == "sub-1"- assert "child-sess-1" in state.subagents-- def test_stop_ends_span_and_records_outcome(self, monkeypatch):- mod = self._fresh_plugin()- spans = []- state = self._state(mod, monkeypatch, "task:task-9:turn:turn-7", spans)-- mod.on_subagent_start(- parent_session_id="sess-1", parent_turn_id="turn-7",- child_session_id="child-sess-1", child_role="researcher",- child_goal="find the thing",- )- mod.on_subagent_stop(- parent_session_id="sess-1", parent_turn_id="turn-7",- child_session_id="child-sess-1", child_role="researcher",- child_summary="found it", child_status="ok",- tool_call_history=[{"name": "read_file"}, {"name": "grep"}],- duration_ms=1234,- )-- assert spans[0].ended is True- assert spans[0].updates["metadata"]["status"] == "ok"- assert spans[0].updates["metadata"]["tool_call_count"] == 2- assert spans[0].updates["metadata"]["duration_ms"] == 1234- # Popped so a repeated stop cannot double-end the span.- assert not state.subagents-- def test_unknown_turn_is_a_noop(self, monkeypatch):- mod = self._fresh_plugin()- spans = []- self._state(mod, monkeypatch, "task:task-9:turn:turn-7", spans)-- mod.on_subagent_start(- parent_turn_id="turn-does-not-exist",- child_session_id="child-sess-1", child_role="researcher",- )- mod.on_subagent_stop(- parent_turn_id="turn-does-not-exist",- child_session_id="child-sess-1",- )-- assert spans == []-- def test_start_without_child_session_is_a_noop(self, monkeypatch):- mod = self._fresh_plugin()- spans = []- self._state(mod, monkeypatch, "task:task-9:turn:turn-7", spans)-- # subagent_stop keys on child_session_id, so a start without one could- # never be matched and must not open an unclosable span.- mod.on_subagent_start(- parent_turn_id="turn-7", child_session_id=None, child_role="researcher",- )-- assert spans == []---# ----------------------------------------------------------------------------# MoA fan-out: one generation per advisor, priced at the advisor's own model-# -----------------------------------------------------------------------------class TestMoAReferenceGenerations:- """MoA returns only the aggregator's response, so without per-advisor- generations the whole fan-out collapses into one line priced at the- aggregator's model. Advisors routinely run on a different provider."""-- def _fresh_plugin(self):- sys.modules.pop("plugins.observability.langfuse", None)- return importlib.import_module("plugins.observability.langfuse")-- def _state(self, mod, monkeypatch, gens):- class _Obs:- def __init__(self, kw):- self.kw = kw- self.updates = {}- self.ended = False-- def update(self, **kw):- self.updates.update(kw)-- def end(self, **kw):- self.ended = True-- class _Root:- def start_observation(self, **kw):- obs = _Obs(kw)- gens.append(obs)- return obs-- monkeypatch.setattr(mod, "_get_langfuse", lambda: object())- return mod.TraceState(trace_id="t", root_ctx=None, root_span=_Root())-- def _refs(self):- return [- {- "label": "anthropic:claude-sonnet-4-6",- "model": "claude-sonnet-4-6",- "provider": "anthropic",- "usage": {"input_tokens": 100, "output_tokens": 50},- "cost_usd": 0.001,- "cost_status": "ok",- "cost_source": "pricing_table",- },- {- "label": "openai:gpt-5",- "model": "gpt-5",- "provider": "openai",- "usage": {"input_tokens": 80, "output_tokens": 40, "reasoning_tokens": 10},- "cost_usd": 0.002,- },- ]-- def test_one_generation_per_advisor_with_own_model_and_cost(self, monkeypatch):- mod = self._fresh_plugin()- gens = []- state = self._state(mod, monkeypatch, gens)-- mod._emit_moa_reference_generations(state, client=object(), references=self._refs())-- assert len(gens) == 2- assert gens[0].kw["model"] == "claude-sonnet-4-6"- assert gens[1].kw["model"] == "gpt-5"- # Each advisor's dollars, not the aggregator's rate applied to all.- assert gens[0].updates["cost_details"]["total"] == pytest.approx(0.001)- assert gens[1].updates["cost_details"]["total"] == pytest.approx(0.002)- assert gens[0].updates["usage_details"] == {"input": 100, "output": 50}- assert gens[1].updates["usage_details"]["reasoning_tokens"] == 10- assert all(g.ended for g in gens)-- def test_repeat_emit_is_deduped_within_a_turn(self, monkeypatch):- mod = self._fresh_plugin()- gens = []- state = self._state(mod, monkeypatch, gens)-- # The MoA client holds its last fan-out until the next one, so a- # tool-loop turn delivers the same references on every API call.- refs = self._refs()- mod._emit_moa_reference_generations(state, client=object(), references=refs)- mod._emit_moa_reference_generations(state, client=object(), references=refs)- mod._emit_moa_reference_generations(state, client=object(), references=list(refs))-- assert len(gens) == 2-- def test_a_new_fanout_emits_again(self, monkeypatch):- mod = self._fresh_plugin()- gens = []- state = self._state(mod, monkeypatch, gens)-- mod._emit_moa_reference_generations(state, client=object(), references=self._refs())- second = self._refs()- second[0]["usage"]["output_tokens"] = 999- mod._emit_moa_reference_generations(state, client=object(), references=second)-- assert len(gens) == 4-- def test_non_moa_turn_emits_nothing(self, monkeypatch):- mod = self._fresh_plugin()- gens = []- state = self._state(mod, monkeypatch, gens)-- for value in (None, [], "not-a-list", [None, "junk"]):- mod._emit_moa_reference_generations(state, client=object(), references=value)-- assert gens == []--class TestAtexitFinalization(TestTurnTraceIsolation):- """Short-lived processes (kanban workers, `hermes chat -q`, cron) can exit- with tool calls still queued — the root span never ends and the backend- shows an anonymous trace (no name/session/metadata). _finalize_all_traces- (registered atexit after client construction) must end every open root."""-- def test_finalize_all_ends_open_roots_and_clears_state(self, monkeypatch):- mod = self._fresh_plugin()- started: list = []- ended: list = []- client = self._fake_client(started)- monkeypatch.setattr(mod, "_get_langfuse", lambda: client)- monkeypatch.setattr(- mod, "_end_observation", lambda obs, **k: ended.append(obs)- )- mod._TRACE_STATE.clear()-- # Three worker-style turns that never finalize (tool calls pending).- for n in range(3):- self._run_turn(mod, session=f"worker-{n}", turn_n=0, finalize=False)- assert len(mod._TRACE_STATE) == 3-- root_ends: list = []- for state in mod._TRACE_STATE.values():- real_end = state.root_span.end- state.root_span.end = lambda *a, _r=real_end, **k: root_ends.append(1)-- mod._finalize_all_traces()-- assert len(root_ends) == 3, "every open root span must be ended"- assert mod._TRACE_STATE == {}, "state must be drained"- # Idempotent: a second call (SDK/atexit re-entry) is a no-op.- mod._finalize_all_traces()- assert len(root_ends) == 3-- def test_atexit_hook_is_registered_on_client_init(self, monkeypatch):- mod = self._fresh_plugin()- registered: list = []- import atexit as _atexit-- monkeypatch.setattr(mod, "Langfuse", lambda **kw: object())- monkeypatch.setattr(- _atexit, "register", lambda fn, *a, **k: registered.append(fn)- )- monkeypatch.setenv("HERMES_LANGFUSE_PUBLIC_KEY", "pk-lf-0123456789abcdef")- monkeypatch.setenv("HERMES_LANGFUSE_SECRET_KEY", "sk-lf-0123456789abcdef")- mod._LANGFUSE_CLIENT = None-- assert mod._get_langfuse() is not None- assert mod._finalize_all_traces in registered-- def test_finalize_flushes_every_profile_without_an_ambient_scope(self, monkeypatch, tmp_path):- """Multiplex gateway: every turn ran inside a profile scope (home override + secret scope),- so only the per-home slots hold clients and the launch slot stays empty. atexit has no- scope, and a credential read there raises UnscopedSecretError. The finalizer must not read- credentials at all — it ends the open roots and flushes each settled client, so neither- profile loses its pending traces."""- from agent import secret_scope- from hermes_constants import reset_hermes_home_override, set_hermes_home_override-- mod = self._fresh_plugin()- monkeypatch.setattr(secret_scope, "_MULTIPLEX_ACTIVE", True)- monkeypatch.setattr(mod, "_end_observation", lambda obs, **k: None)- mod._LANGFUSE_CLIENT = None- mod._TRACE_STATE.clear()- mod._LANGFUSE_CLIENT_BY_HOME.clear()-- flushed: list = []- fake_client = self._fake_client-- def _sdk(**kw):- client = fake_client([])- client.flush = lambda pk=kw["public_key"]: flushed.append(pk)- return client-- monkeypatch.setattr(mod, "Langfuse", _sdk)-- for profile in ("alpha", "beta"):- home = tmp_path / profile- home.mkdir()- home_token = set_hermes_home_override(home)- scope_token = secret_scope.set_secret_scope({- "HERMES_LANGFUSE_PUBLIC_KEY": f"pk-lf-{profile}-0123456789",- "HERMES_LANGFUSE_SECRET_KEY": f"sk-lf-{profile}-0123456789",- })- try:- self._run_turn(mod, session=f"{profile}-turn", turn_n=0, finalize=False)- finally:- secret_scope.reset_secret_scope(scope_token)- reset_hermes_home_override(home_token)-- assert len(mod._TRACE_STATE) == 2 and len(mod._LANGFUSE_CLIENT_BY_HOME) == 2- assert mod._LANGFUSE_CLIENT is None and secret_scope.current_secret_scope() is None-- mod._finalize_all_traces() # no scope: must not raise, must not build a client-- assert sorted(flushed) == ["pk-lf-alpha-0123456789", "pk-lf-beta-0123456789"]- assert mod._TRACE_STATE == {} and mod._LANGFUSE_CLIENT is None---class TestSystemPromptInGenerationInput:- """The generation input must carry the system prompt even for providers- that move it out of ``messages``: Anthropic Messages (``system`` kwarg)- and the Responses/Codex API (``instructions``). Hermes forwards it to- hooks as ``system_prompt``; the plugin prepends a ``role: system`` entry.-- Regression for the trace gap discussed in PR #32175 (Anthropic) and its- Codex sibling: without this, hosted traces show conversations without the- agent's instructions, skills, and memory."""-- def _make_mod(self):- sys.modules.pop("plugins.observability.langfuse", None)- return importlib.import_module("plugins.observability.langfuse")-- def _capture_generation(self, mod, monkeypatch):- """Route on_pre_llm_request into a seeded TraceState and record the- generation observation kwargs."""- captured = {}- monkeypatch.setattr(mod, "_get_langfuse", lambda: object())- state = mod.TraceState(trace_id="t", root_ctx=None, root_span=None)- task_key = mod._trace_key("task-1", "sess-1")- monkeypatch.setitem(mod._TRACE_STATE, task_key, state)-- def fake_child(state_, **kw):- captured["input"] = kw.get("input_value")- captured["metadata"] = kw.get("metadata")- return object()-- monkeypatch.setattr(mod, "_start_child_observation", fake_child)- return captured-- def _fire(self, mod, *, request_messages, system_prompt=None):- kwargs = dict(- task_id="task-1",- session_id="sess-1",- model="m",- provider="p",- api_mode="codex_responses",- api_call_count=1,- request_messages=request_messages,- )- if system_prompt is not None:- kwargs["system_prompt"] = system_prompt- mod.on_pre_llm_request(**kwargs)--- def test_anthropic_block_list_flattened(self, monkeypatch):- """Anthropic OAuth mode sends ``system`` as content blocks (with- cache_control); the trace should carry the readable text."""- mod = self._make_mod()- captured = self._capture_generation(mod, monkeypatch)- blocks = [- {"type": "text", "text": "part one", "cache_control": {"type": "ephemeral"}},- {"type": "text", "text": "part two"},- ]- self._fire(- mod,- request_messages=[{"role": "user", "content": "hi"}],- system_prompt=blocks,- )- first = captured["input"][0]- assert first["role"] == "system"- assert "part one" in first["content"]- assert "part two" in first["content"]--- def test_absent_system_prompt_keeps_previous_shape(self, monkeypatch):- mod = self._make_mod()- captured = self._capture_generation(mod, monkeypatch)- self._fire(mod, request_messages=[{"role": "user", "content": "hi"}])- assert captured["input"][0]["role"] == "user"- assert "system_prompt_chars" not in (captured["metadata"] or {})-- def test_system_survives_serialization_window(self, monkeypatch):- """_serialize_messages keeps only the last 12 messages; the system- prompt must be prepended after windowing so long conversations- never drop it."""- mod = self._make_mod()- captured = self._capture_generation(mod, monkeypatch)- many = [- {"role": "user" if i % 2 == 0 else "assistant", "content": f"m{i}"}- for i in range(30)- ]- self._fire(mod, request_messages=many, system_prompt="SYS")- assert captured["input"][0]["role"] == "system"- assert captured["input"][0]["content"] == "SYS"---class TestSystemPromptCrossesHookBoundary:- """End-to-end across the hook seam with real transport-built kwargs —- the regression coverage PR #32175's review asked for: verify the- provider-specific request shape (Anthropic ``system`` kwarg, Codex- ``instructions``) actually reaches the Langfuse generation input, with- no Hermes internals mocked (only the Langfuse client is faked)."""-- def _make_mod(self):- sys.modules.pop("plugins.observability.langfuse", None)- return importlib.import_module("plugins.observability.langfuse")-- def _capture_generation(self, mod, monkeypatch):- captured = {}- monkeypatch.setattr(mod, "_get_langfuse", lambda: object())- state = mod.TraceState(trace_id="t", root_ctx=None, root_span=None)- task_key = mod._trace_key("task-1", "sess-1")- monkeypatch.setitem(mod._TRACE_STATE, task_key, state)-- def fake_child(state_, **kw):- captured["input"] = kw.get("input_value")- return object()-- monkeypatch.setattr(mod, "_start_child_observation", fake_child)- return captured-- def _derive_and_fire(self, mod, api_kwargs, api_messages):- """Mirror agent/conversation_loop.py's pre_api_request emission:- derive request_messages exactly the way the loop does, derive- system_prompt via the loop's helper, and invoke the plugin hook."""- from agent.conversation_loop import _system_prompt_for_hooks-- request_messages = api_kwargs.get("messages")- if not isinstance(request_messages, list):- request_messages = api_kwargs.get("input")- if not isinstance(request_messages, list):- request_messages = api_messages- mod.on_pre_llm_request(- task_id="task-1",- session_id="sess-1",- model="m",- provider="p",- api_mode="x",- api_call_count=1,- request_messages=list(request_messages),- system_prompt=_system_prompt_for_hooks(api_kwargs, request_messages),- )-- def test_codex_instructions_reach_generation_input(self, monkeypatch):- from agent.transports.codex import ResponsesApiTransport-- api_messages = [- {"role": "system", "content": "SYS-CODEX"},- {"role": "user", "content": "hi"},- ]- api_kwargs = ResponsesApiTransport().build_kwargs("gpt-x", api_messages, None)- # Premise: the Responses API moves the system prompt out of the input.- assert api_kwargs["instructions"] == "SYS-CODEX"- assert all(i.get("role") != "system" for i in api_kwargs["input"] if isinstance(i, dict))-- mod = self._make_mod()- captured = self._capture_generation(mod, monkeypatch)- self._derive_and_fire(mod, api_kwargs, api_messages)- assert captured["input"][0]["role"] == "system"- assert captured["input"][0]["content"] == "SYS-CODEX"-- def test_anthropic_system_kwarg_reaches_generation_input(self, monkeypatch):- from agent.transports.anthropic import AnthropicTransport-- api_messages = [- {"role": "system", "content": "SYS-ANTHROPIC"},- {"role": "user", "content": "hi"},- ]- api_kwargs = AnthropicTransport().build_kwargs(- "claude-x", api_messages, None, max_tokens=64- )- # Premise: the Messages API moves the system prompt to a kwarg.- assert "system" in api_kwargs- assert all(m.get("role") != "system" for m in api_kwargs["messages"])-- mod = self._make_mod()- captured = self._capture_generation(mod, monkeypatch)- self._derive_and_fire(mod, api_kwargs, api_messages)- assert captured["input"][0]["role"] == "system"- assert "SYS-ANTHROPIC" in captured["input"][0]["content"]-- def test_bedrock_system_kwarg_reaches_generation_input(self, monkeypatch):- from agent.transports.bedrock import BedrockTransport-- api_messages = [- {"role": "system", "content": "SYS-BEDROCK"},- {"role": "user", "content": "hi"},- ]- api_kwargs = BedrockTransport().build_kwargs(- "anthropic.claude-x", api_messages, None, max_tokens=64- )- # Premise: Bedrock Converse moves system into a separate 'system' kwarg,- # shaped as [{"text": ...}] blocks — no "type" key, unlike Anthropic.- # (The transport may append extra blocks, e.g. cachePoint markers.)- assert {"text": "SYS-BEDROCK"} in api_kwargs["system"]- assert all(m.get("role") != "system" for m in api_kwargs["messages"])-- mod = self._make_mod()- captured = self._capture_generation(mod, monkeypatch)- self._derive_and_fire(mod, api_kwargs, api_messages)- assert captured["input"][0]["role"] == "system"- assert "SYS-BEDROCK" in captured["input"][0]["content"]-- def test_chat_completions_shape_needs_no_fallback(self, monkeypatch):- """When system stays in messages[0] (chat_completions), the helper- returns it but the plugin must not duplicate the entry."""- from agent.conversation_loop import _system_prompt_for_hooks-- api_kwargs = {- "messages": [- {"role": "system", "content": "SYS-CHAT"},- {"role": "user", "content": "hi"},- ]- }- sp = _system_prompt_for_hooks(api_kwargs, api_kwargs["messages"])- assert sp == "SYS-CHAT"-- mod = self._make_mod()- captured = self._capture_generation(mod, monkeypatch)- self._derive_and_fire(mod, api_kwargs, api_kwargs["messages"])- roles = [m["role"] for m in captured["input"]]- assert roles.count("system") == 1-class TestFinishTraceUsesUpdateTrace:- """Regression: SDK v3 has update_trace, not set_trace_io.-- Calling the non-existent set_trace_io raised AttributeError inside- _finish_trace's try block and skipped root_span.end(). Generations/tools- still exported, so the Langfuse list showed Observation Levels + Latency- but blank Input/Output columns (no CHAIN root).- """-- def test_finish_ends_root_and_calls_update_trace(self, monkeypatch):- sys.modules.pop("plugins.observability.langfuse", None)- mod = importlib.import_module("plugins.observability.langfuse")-- roots: list = []-- class _Span:- def __init__(self):- self.ended = False- self.updates = []- self.trace_updates = []-- def update(self, **kw):- self.updates.append(kw)-- def end(self, **kw):- self.ended = True-- def update_trace(self, **kw):- self.trace_updates.append(kw)-- def start_observation(self, **kw):- return _Span()-- # Deliberately NO set_trace_io — mirrors real LangfuseChain.-- class _RootCM:- def __init__(self):- self.span = _Span()- roots.append(self.span)-- def __enter__(self):- return self.span-- def __exit__(self, *exc):- return False-- class _Client:- def create_trace_id(self, seed=None):- return f"trace::{seed}"-- def start_as_current_observation(self, **kw):- return _RootCM()-- def flush(self):- pass-- monkeypatch.setattr(mod, "_get_langfuse", lambda: _Client())- monkeypatch.setattr(mod, "_end_observation", lambda *a, **k: None)- mod._TRACE_STATE.clear()-- mod.on_pre_llm_request(- task_id="t1",- session_id="s1",- model="m",- provider="p",- api_mode="chat",- api_call_count=1,- request_messages=[{"role": "user", "content": "hi"}],- turn_id="turn-1",- )- mod.on_post_llm_call(- task_id="t1",- session_id="s1",- model="m",- provider="p",- api_mode="chat",- api_call_count=1,- assistant_content_chars=12,- assistant_tool_call_count=0,- assistant_response="hello world!",- turn_id="turn-1",- )-- assert len(roots) == 1- root = roots[0]- assert root.ended is True- assert any("output" in u for u in root.trace_updates)- assert any("output" in u for u in root.updates)- assert mod._TRACE_STATE == {}-- def test_finish_still_ends_when_update_trace_raises(self, monkeypatch):- sys.modules.pop("plugins.observability.langfuse", None)- mod = importlib.import_module("plugins.observability.langfuse")-- roots: list = []-- class _Span:- def __init__(self):- self.ended = False-- def update(self, **kw):- pass-- def end(self, **kw):- self.ended = True-- def update_trace(self, **kw):- raise RuntimeError("simulated update_trace failure")-- def start_observation(self, **kw):- return _Span()-- class _RootCM:- def __init__(self):- self.span = _Span()- roots.append(self.span)-- def __enter__(self):- return self.span-- def __exit__(self, *exc):- return False-- class _Client:- def create_trace_id(self, seed=None):- return f"trace::{seed}"-- def start_as_current_observation(self, **kw):- return _RootCM()-- def flush(self):- pass-- monkeypatch.setattr(mod, "_get_langfuse", lambda: _Client())- monkeypatch.setattr(mod, "_end_observation", lambda *a, **k: None)- mod._TRACE_STATE.clear()-- mod.on_pre_llm_request(- task_id="t1",- session_id="s1",- model="m",- provider="p",- api_mode="chat",- api_call_count=1,- request_messages=[{"role": "user", "content": "hi"}],- turn_id="turn-1",- )- mod.on_post_llm_call(- task_id="t1",- session_id="s1",- model="m",- provider="p",- api_mode="chat",- api_call_count=1,- assistant_content_chars=5,- assistant_tool_call_count=0,- assistant_response="done",- turn_id="turn-1",- )-- assert roots[0].ended is True- assert mod._TRACE_STATE == {}--class TestCanonicalCostExport:- """Both supported response paths must export the same complete cost."""-- @staticmethod- def _response(input_tokens, output_tokens, cache_read=0, cache_write=0):- cache_details = SimpleNamespace(- cached_tokens=cache_read,- cache_write_tokens=cache_write,- )- usage = SimpleNamespace(- # Anthropic response shape.- input_tokens=input_tokens,- output_tokens=output_tokens,- cache_read_input_tokens=cache_read,- cache_creation_input_tokens=cache_write,- # OpenAI chat response shape used by the included-route case.- prompt_tokens=input_tokens + cache_read + cache_write,- completion_tokens=output_tokens,- prompt_tokens_details=cache_details,- )- return SimpleNamespace(usage=usage)-- @staticmethod- def _summary(input_tokens, output_tokens, cache_read=0, cache_write=0, request_count=1):- return {- "input_tokens": input_tokens,- "output_tokens": output_tokens,- "cache_read_tokens": cache_read,- "cache_write_tokens": cache_write,- "reasoning_tokens": 0,- "request_count": request_count,- }-- @staticmethod- def _capture_summary_path(mod, monkeypatch, usage, *, provider, model, api_mode):- monkeypatch.setattr(mod, "_get_langfuse", lambda: object())- observation = object()- state = mod.TraceState(trace_id="trace-cost", root_ctx=None, root_span=None)- state.generations[mod._request_key(1)] = observation- task_key = mod._trace_key("task-cost", "session-cost")- monkeypatch.setitem(mod._TRACE_STATE, task_key, state)- captured = {}-- def fake_end_observation(- obs,- *,- output=None,- metadata=None,- usage_details=None,- cost_details=None,- ):- captured["usage_details"] = usage_details- captured["cost_details"] = cost_details-- monkeypatch.setattr(mod, "_end_observation", fake_end_observation)- mod.on_post_llm_call(- task_id="task-cost",- session_id="session-cost",- api_call_count=1,- model=model,- provider=provider,- api_mode=api_mode,- response={"model": model},- usage=usage,- )- return captured["usage_details"], captured["cost_details"]-- def _run_both_paths(- self,- mod,- monkeypatch,- usage,- *,- provider="anthropic",- model="priced-model",- api_mode="anthropic_messages",- ):- response_result = mod._usage_and_cost(- self._response(- usage["input_tokens"],- usage["output_tokens"],- usage.get("cache_read_tokens", 0),- usage.get("cache_write_tokens", 0),- ),- provider=provider,- api_mode=api_mode,- model=model,- base_url="",- )- summary_result = self._capture_summary_path(- mod,- monkeypatch,- usage,- provider=provider,- model=model,- api_mode=api_mode,- )- assert response_result[0] == summary_result[0]- return response_result[1], summary_result[1]-- @pytest.mark.parametrize(- ("cache_read", "cache_write", "expected_total"),- [- (0, 0, 0.00002),- (2, 3, 0.0000255),- ],- ids=("no-cache", "cached"),- )- def test_known_costs_include_canonical_total_on_both_paths(- self,- monkeypatch,- cache_read,- cache_write,- expected_total,- ):- sys.modules.pop("plugins.observability.langfuse", None)- mod = importlib.import_module("plugins.observability.langfuse")- import agent.usage_pricing as pricing-- entry = pricing.PricingEntry(- input_cost_per_million=Decimal(1),- output_cost_per_million=Decimal(2),- cache_read_cost_per_million=Decimal("0.5"),- cache_write_cost_per_million=Decimal("1.5"),- source="custom_contract",- )- monkeypatch.setattr(pricing, "get_pricing_entry", lambda *_, **__: entry)- usage = self._summary(10, 5, cache_read, cache_write)-- response_cost, summary_cost = self._run_both_paths(mod, monkeypatch, usage)- expected = {- "total": expected_total,- "input": 0.00001,- "output": 0.00001,- }- if cache_read:- expected["cache_read_input_tokens"] = 0.000001- if cache_write:- expected["cache_creation_input_tokens"] = 0.0000045- assert response_cost == pytest.approx(expected)- assert summary_cost == pytest.approx(expected)-- def test_total_uses_request_cost_instead_of_component_sum(self, monkeypatch):- sys.modules.pop("plugins.observability.langfuse", None)- mod = importlib.import_module("plugins.observability.langfuse")- import agent.usage_pricing as pricing-- entry = pricing.PricingEntry(- input_cost_per_million=Decimal(1),- output_cost_per_million=Decimal(2),- cache_read_cost_per_million=Decimal("0.5"),- cache_write_cost_per_million=Decimal("1.5"),- request_cost=Decimal("0.01"),- source="provider_models_api",- )- monkeypatch.setattr(pricing, "get_pricing_entry", lambda *_, **__: entry)- usage = self._summary(10, 5, cache_read=2, cache_write=3)-- response_cost, summary_cost = self._run_both_paths(mod, monkeypatch, usage)- for cost_details in (response_cost, summary_cost):- component_sum = sum(- value for key, value in cost_details.items() if key != "total"- )- assert cost_details["total"] == pytest.approx(0.0100255)- assert component_sum == pytest.approx(0.0000255)-- def test_request_only_price_still_exports_total(self, monkeypatch):- sys.modules.pop("plugins.observability.langfuse", None)- mod = importlib.import_module("plugins.observability.langfuse")- import agent.usage_pricing as pricing-- entry = pricing.PricingEntry(- request_cost=Decimal("0.01"),- source="provider_models_api",- )- monkeypatch.setattr(pricing, "get_pricing_entry", lambda *_, **__: entry)- usage = self._summary(0, 0)-- response_cost, summary_cost = self._run_both_paths(mod, monkeypatch, usage)- assert response_cost == {"total": 0.01}- assert summary_cost == {"total": 0.01}-- def test_partial_cache_pricing_exports_no_costs(self, monkeypatch):- sys.modules.pop("plugins.observability.langfuse", None)- mod = importlib.import_module("plugins.observability.langfuse")- import agent.usage_pricing as pricing-- entry = pricing.PricingEntry(- input_cost_per_million=Decimal(1),- output_cost_per_million=Decimal(2),- cache_read_cost_per_million=None,- source="provider_models_api",- )- monkeypatch.setattr(pricing, "get_pricing_entry", lambda *_, **__: entry)- usage = self._summary(10, 5, cache_read=2)-- response_cost, summary_cost = self._run_both_paths(mod, monkeypatch, usage)- assert response_cost == {}- assert summary_cost == {}-- def test_unknown_pricing_exports_no_costs(self, monkeypatch):- sys.modules.pop("plugins.observability.langfuse", None)- mod = importlib.import_module("plugins.observability.langfuse")- import agent.usage_pricing as pricing-- monkeypatch.setattr(pricing, "get_pricing_entry", lambda *_, **__: None)- usage = self._summary(10, 5)-- response_cost, summary_cost = self._run_both_paths(mod, monkeypatch, usage)- assert response_cost == {}- assert summary_cost == {}-- def test_included_route_does_not_pin_total(self, monkeypatch):- sys.modules.pop("plugins.observability.langfuse", None)- mod = importlib.import_module("plugins.observability.langfuse")- usage = self._summary(10, 5, cache_read=2)-- response_cost, summary_cost = self._run_both_paths(- mod,- monkeypatch,- usage,- provider="openai-codex",- model="gpt-5.3-codex",- api_mode="chat_completions",- )- assert response_cost == summary_cost- assert "total" not in response_cost- # Subscription-included routes must send NO cost keys at all —- # explicit zeros are treated as authoritative by Langfuse and block- # its own model-based estimation (#43129).- assert response_cost == {}diff --git a/tests/plugins/test_scoped_secret_readers_fail_closed.py b/tests/plugins/test_scoped_secret_readers_fail_closed.pyindex f4ba207305e..1f4d0419b21 100644--- a/tests/plugins/test_scoped_secret_readers_fail_closed.py+++ b/tests/plugins/test_scoped_secret_readers_fail_closed.py@@ -1,7 +1,7 @@"""Credential shims outside the memory plugins honour the secret-scope contract.-``langfuse._secret`` and ``azure_identity_adapter._scoped_env`` used to catch ``UnscopedSecretError``-and fall back to ``os.environ`` / ``""``. Under multiplex ``os.environ`` is the DEFAULT profile's+``azure_identity_adapter._scoped_env`` used to catch ``UnscopedSecretError`` and fall back to+``os.environ`` / ``""``. Under multiplex ``os.environ`` is the DEFAULT profile's``.env``, so that fallback either shipped another profile's credentials or hid the spawn-site bug theexception exists to surface. Contract: scope wins over environ; no scope while multiplexing raises."""@@ -11,10 +11,8 @@ import pytestfrom agent import secret_scopefrom agent.azure_identity_adapter import _scoped_env as azure_scoped_env-from plugins.observability.langfuse import _secret as langfuse_secret-_READERS = {"langfuse": (langfuse_secret, "LANGFUSE_SECRET_KEY"),- "azure": (azure_scoped_env, "AZURE_CLIENT_SECRET")}+_READERS = {"azure": (azure_scoped_env, "AZURE_CLIENT_SECRET")}@pytest.fixturediff --git a/uv.lock b/uv.lockindex adb7e61f476..b5af60f4f02 100644--- a/uv.lock+++ b/uv.lock@@ -560,15 +560,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/77/f5/21d2de20e8b8b0408f0681956ca2c69f1320a3848ac50e6e7f39c6159675/babel-2.18.0-py3-none-any.whl", hash = "sha256:e2b422b277c2b9a9630c1d7903c2a00d0830c409c59ac8cae9081c92f1aeba35", size = 10196845, upload-time = "2026-02-01T12:30:53.445Z" },]-[[package]]-name = "backoff"-version = "2.2.1"-source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/47/d7/5bbeb12c44d7c4f2fb5b56abce497eb5ed9f34d85701de869acedd602619/backoff-2.2.1.tar.gz", hash = "sha256:03f829f5bb1923180821643f8753b0502c3b682293992485b0eef2807afa5cba", size = 17001, upload-time = "2022-10-05T19:19:32.061Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/df/73/b6e24bd22e6720ca8ee9a85a0c4a2971af8497d8f3193fa05390cbd46e09/backoff-2.2.1-py3-none-any.whl", hash = "sha256:63579f9a0628e06278f7e47b7d7d5b6ce20dc65c5e96a6f3ca99a6adca0396e8", size = 15148, upload-time = "2022-10-05T19:19:30.546Z" },-]-[[package]]name = "base58"version = "2.1.1"@@ -2382,9 +2373,6 @@ kittentts = [{ name = "misaki", extra = ["en"], marker = "(platform_machine != 'x86_64' and sys_platform == 'darwin') or (platform_machine != 'ARM64' and sys_platform == 'win32') or (sys_platform != 'darwin' and sys_platform != 'win32')" },{ name = "soundfile", marker = "(platform_machine != 'x86_64' and sys_platform == 'darwin') or (platform_machine != 'ARM64' and sys_platform == 'win32') or (sys_platform != 'darwin' and sys_platform != 'win32')" },]-langfuse = [- { name = "langfuse" },-]matrix = [{ name = "aiohttp", marker = "sys_platform == 'linux'" },{ name = "aiohttp-socks", marker = "sys_platform == 'linux'" },@@ -2609,7 +2597,6 @@ requires-dist = [{ name = "huggingface-hub", marker = "extra == 'trace-upload'", specifier = "==1.24.0" },{ name = "jinja2", marker = "python_full_version >= '3.14'", specifier = "==3.1.6" },{ name = "kittentts", marker = "(platform_machine != 'x86_64' and sys_platform == 'darwin' and extra == 'kittentts') or (platform_machine != 'ARM64' and sys_platform == 'win32' and extra == 'kittentts') or (sys_platform != 'darwin' and sys_platform != 'win32' and extra == 'kittentts')", url = "https://github.com/KittenML/KittenTTS/releases/download/0.8.1/kittentts-0.8.1-py3-none-any.whl" },- { name = "langfuse", marker = "extra == 'langfuse'", specifier = "==4.15.2" },{ name = "lark-oapi", marker = "extra == 'feishu'", specifier = "==1.6.8" },{ name = "markdown", marker = "python_full_version >= '3.14'", specifier = "==3.10.2" },{ name = "mautrix", extras = ["encryption"], marker = "sys_platform == 'linux' and extra == 'matrix'", specifier = "==0.21.1" },@@ -2699,7 +2686,7 @@ requires-dist = [{ name = "winrt-windows-services-store", marker = "python_full_version >= '3.14' and sys_platform == 'win32'", specifier = ">=3.2.1,<4" },{ name = "youtube-transcript-api", marker = "extra == 'youtube'", specifier = "==1.2.4" },]-provides-extras = ["uvloop", "anthropic", "exa", "firecrawl", "parallel-web", "ddgs", "fal", "edge-tts", "neutts", "kittentts", "piper", "modal", "daytona", "vercel", "google-meet", "messaging", "cron", "slack", "matrix", "wecom", "tts-premium", "voice", "wake", "telegram", "discord", "stt-whisper", "audio-io", "silk", "wake-openwakeword", "wake-sherpa", "wake-porcupine", "google-chat", "doc-extract", "trace-upload", "vision", "pty", "mcp", "nemo-relay", "sms", "teams", "computer-use", "acp", "mistral", "otlp", "langfuse", "bedrock", "vertex", "azure-identity", "termux", "termux-all", "dingtalk", "feishu", "google", "youtube", "web", "all"]+provides-extras = ["uvloop", "anthropic", "exa", "firecrawl", "parallel-web", "ddgs", "fal", "edge-tts", "neutts", "kittentts", "piper", "modal", "daytona", "vercel", "google-meet", "messaging", "cron", "slack", "matrix", "wecom", "tts-premium", "voice", "wake", "telegram", "discord", "stt-whisper", "audio-io", "silk", "wake-openwakeword", "wake-sherpa", "wake-porcupine", "google-chat", "doc-extract", "trace-upload", "vision", "pty", "mcp", "nemo-relay", "sms", "teams", "computer-use", "acp", "mistral", "otlp", "bedrock", "vertex", "azure-identity", "termux", "termux-all", "dingtalk", "feishu", "google", "youtube", "web", "all"][package.metadata.requires-dev]dev = [@@ -3129,26 +3116,6 @@ requires-dist = [{ name = "spacy" },]-[[package]]-name = "langfuse"-version = "4.15.2"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "backoff" },- { name = "httpx" },- { name = "opentelemetry-api" },- { name = "opentelemetry-exporter-otlp-proto-http" },- { name = "opentelemetry-sdk" },- { name = "packaging" },- { name = "pydantic" },- { name = "typing-extensions" },- { name = "wrapt" },-]-sdist = { url = "https://files.pythonhosted.org/packages/97/30/6a64dcf84de2f2eb4d03adbfd22cc7bdc95ce67e3e56cd6288405087fb8a/langfuse-4.15.2.tar.gz", hash = "sha256:7f818f38cc22daba88fdcec62d2addcee4e18d1af4529978b6d07501e86b6946", size = 391727, upload-time = "2026-09-09T16:01:25.73Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/02/de/e59da18cb5ca9cb8515a254199bd96ace8cf918788d13ded66aa2693e007/langfuse-4.15.2-py3-none-any.whl", hash = "sha256:98c27a3c06e18c4497045f2d4decce2c716ef11cb215cf5b27bbea6ee0877115", size = 705824, upload-time = "2026-09-09T16:01:23.696Z" },-]-[[package]]name = "language-tags"version = "1.3.1"diff --git a/website/docs/developer-guide/observer-hooks.md b/website/docs/developer-guide/observer-hooks.mdindex 5c7e95c6ae8..a9cfb60b9b1 100644--- a/website/docs/developer-guide/observer-hooks.md+++ b/website/docs/developer-guide/observer-hooks.md@@ -334,8 +334,8 @@ nested agent work or security lifecycle events.## Existing Consumers-The bundled Langfuse plugin demonstrates direct hook-based observability for-turns, provider requests, and tool calls.+The official [Langfuse catalog plugin](https://github.com/NousResearch/hermes-official-plugins/tree/main/langfuse) demonstrates direct hook-based+observability for turns, provider requests, and tool calls.The native NeMo Relay SDK integration maps Hermes session, turn, LLM, and toollifecycles to Relay. Relay's discovered user and system configuration, or andiff --git a/website/docs/reference/environment-variables.md b/website/docs/reference/environment-variables.mdindex 2367cd40e15..ea2df5af9f5 100644--- a/website/docs/reference/environment-variables.md+++ b/website/docs/reference/environment-variables.md@@ -218,7 +218,7 @@ Secrets consumed by specific bundled / optional skills. Each is only needed if y### Langfuse Observability-Environment variables for the bundled [`observability/langfuse`](../user-guide/features/built-in-plugins.md#observabilitylangfuse) plugin. Set these in `~/.hermes/.env`. The plugin must also be enabled (`hermes plugins enable observability/langfuse`, or check the box in `hermes plugins`) before any of these take effect.+Environment variables for the official [`langfuse`](https://github.com/NousResearch/hermes-official-plugins/tree/main/langfuse) catalog plugin (formerly bundled as `observability/langfuse`). Set these in `~/.hermes/.env`. The plugin must be installed (`hermes plugins install langfuse`) before any of these take effect.| Variable | Description ||----------|-------------|diff --git a/website/docs/user-guide/features/built-in-plugins.md b/website/docs/user-guide/features/built-in-plugins.mdindex f0f587aad4d..43a033d62ef 100644--- a/website/docs/user-guide/features/built-in-plugins.md+++ b/website/docs/user-guide/features/built-in-plugins.md@@ -57,7 +57,6 @@ The repo ships these bundled plugins under `plugins/`. All are opt-in — enable|---|---|---|| `disk-cleanup` | hooks + slash command | Auto-track ephemeral files and clean them on session end || `security-guidance` | hooks | Pattern-match dangerous code on `write_file`/`patch` and append a security warning (or block) — 25 rules (Apache-2.0 fork of Anthropic's `claude-plugins-official` patterns) |-| `observability/langfuse` | hooks | Trace turns / LLM calls / tools to [Langfuse](https://langfuse.com) || `teams_pipeline` | standalone | Microsoft Teams meeting pipeline — Graph-backed, transcript-first meeting summaries || `google_meet` | standalone | Join Meet calls, live-caption transcription, optional realtime duplex audio || `image_gen/openai` | image backend | OpenAI GPT Image 2 and 2.5 Flare/Sunburst generation and editing (API key) |@@ -139,76 +138,20 @@ The file is still written. The model reads the warning in the next turn's tool m**What it does not do (yet):** the upstream Anthropic plugin has two more layers — an LLM diff review on each agent turn that touched files, and an agentic commit-time review that traces data flow across files. Neither is ported. The agent can already run those reviews on demand via `delegate_task`.-### observability/langfuse+### Langfuse (moved to the plugin catalog)-Traces Hermes turns, LLM calls, and tool invocations to [Langfuse](https://langfuse.com) — an open-source LLM observability platform. One span per turn, one generation per API call, one tool observation per tool call. Usage totals, per-type token counts, and cost estimates come out of Hermes' canonical `agent.usage_pricing` numbers, so the Langfuse dashboard sees the same breakdown (input / output / `cache_read_input_tokens` / `cache_creation_input_tokens` / `reasoning_tokens`) that appears in `hermes logs`.--The plugin is fail-open: no SDK installed, no credentials, or a transient Langfuse error — all turn into a silent no-op in the hook. The agent loop is never impacted.--**Setup (interactive — recommended):**--```bash-hermes tools # → Langfuse Observability → Cloud or Self-Hosted-```--The wizard collects your keys, prepares the declared `langfuse` extra through PM-when needed, and enables `observability/langfuse`. Restart Hermes and the next-turn ships a trace. If preparation fails, retry through `hermes tools`; do not-install the SDK into the selected environment with pip.--**Setup (manual):**--For a source checkout, first follow the [PM developer workflow](../../reference/package-management.md#developer-workflow)-with the intended Hermes home. Use the checkout's prepared Python:+Langfuse tracing is no longer bundled with Hermes. It ships as the official+[`langfuse`](https://github.com/NousResearch/hermes-official-plugins/tree/main/langfuse) catalog plugin, with the same hooks, `HERMES_LANGFUSE_*`+environment variables and capture modes:```bash-python -c "import pm; pm.sync_venv(['langfuse'], explicit=True)"-source ./activate-python hermes plugins enable observability/langfuse+hermes plugins install langfuse```-Use `. .\activate.ps1` for PowerShell activation. Then put the credentials in-the active home's `.env` (`$HERMES_HOME/.env`, normally `~/.hermes/.env`):--```bash-HERMES_LANGFUSE_PUBLIC_KEY=pk-lf-...-HERMES_LANGFUSE_SECRET_KEY=sk-lf-...-HERMES_LANGFUSE_BASE_URL=https://cloud.langfuse.com # or your self-hosted URL-```--**How it works:**--| Hook | Behaviour |-|---|---|-| `pre_api_request` / `pre_llm_call` | Open (or reuse) a per-turn root span "Hermes turn". Start a `generation` child observation for this API call with serialized recent messages as input. |-| `post_api_request` / `post_llm_call` | Close the generation, attach `usage_details`, `cost_details`, `finish_reason`, assistant output + tool calls. If no tool calls and non-empty content, close the turn. |-| `pre_tool_call` | Start a `tool` child observation with sanitized `args`. |-| `post_tool_call` | Close the tool observation with sanitized `result`. `read_file` payloads get summarized (head + tail + omitted-line count) so a huge file read stays under `HERMES_LANGFUSE_MAX_CHARS`. |--Session grouping keys off the Hermes session ID (or task ID for sub-agents) via `langfuse.propagate_attributes`, so everything in a single `hermes chat` session lives under one Langfuse session.--**Verify:**--```bash-hermes plugins list # observability/langfuse should show "enabled"-hermes chat -q "hello" # check the Langfuse UI for a "Hermes turn" trace-```--**Optional tuning** (in `.env`):--| Variable | Default | Purpose |-|---|---|---|-| `HERMES_LANGFUSE_ENV` | — | Environment tag on traces (`production`, `staging`, …) |-| `HERMES_LANGFUSE_RELEASE` | — | Release/version tag |-| `HERMES_LANGFUSE_SAMPLE_RATE` | `1.0` | Sampling rate passed to the SDK (0.0–1.0) |-| `HERMES_LANGFUSE_MAX_CHARS` | `12000` | Per-field truncation for message content / tool args / tool results |-| `HERMES_LANGFUSE_DEBUG` | `false` | Verbose plugin logging to `agent.log` |--Hermes-prefixed and standard SDK env vars (`LANGFUSE_PUBLIC_KEY`, `LANGFUSE_SECRET_KEY`, `LANGFUSE_BASE_URL`) are both accepted — Hermes-prefixed wins when both are set.--**Performance:** the Langfuse client is cached after the first hook call. If credentials or SDK are missing, that decision is also cached — subsequent hooks fast-return without re-checking env vars or reloading config.--**Disabling:** `hermes plugins disable observability/langfuse`. The plugin module is still discovered, but no module code runs until you re-enable.+Profiles that had `observability/langfuse` enabled get the plugin installed and+enabled automatically by `hermes update` (or on the first start after updating),+and keep tracing to the same Langfuse project. Setup, tuning and capture modes+are documented in the [plugin's README](https://github.com/NousResearch/hermes-official-plugins/tree/main/langfuse).### NeMo Relay native integration (migration note)diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/environment-variables.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/environment-variables.mdindex 2b254e95b5b..a7651e1882b 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/environment-variables.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/reference/environment-variables.md@@ -159,7 +159,7 @@ description: "Hermes Agent 使用的所有环境变量完整参考"### Langfuse 可观测性-内置 [`observability/langfuse`](../user-guide/features/built-in-plugins.md#observabilitylangfuse) 插件的环境变量。在 `~/.hermes/.env` 中设置。在这些变量生效之前,还必须启用该插件(`hermes plugins enable observability/langfuse`,或在 `hermes plugins` 中勾选)。+官方目录插件 [`langfuse`](https://github.com/NousResearch/hermes-official-plugins/tree/main/langfuse)(原内置的 `observability/langfuse`)的环境变量。在 `~/.hermes/.env` 中设置。在这些变量生效之前,必须先安装该插件(`hermes plugins install langfuse`)。| 变量 | 描述 ||----------|-------------|diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/built-in-plugins.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/built-in-plugins.mdindex b6c2ee66920..f59351645ef 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/built-in-plugins.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/built-in-plugins.md@@ -56,7 +56,6 @@ hermes plugins disable disk-cleanup| 插件 | 类型 | 用途 ||---|---|---|| `disk-cleanup` | hook + 斜杠命令 | 自动追踪临时文件并在会话结束时清理 |-| `observability/langfuse` | hook | 将轮次 / LLM 调用 / 工具追踪到 [Langfuse](https://langfuse.com) || `google_meet` | 独立插件 | 加入 Meet 通话、实时字幕转录、可选实时双工音频 || `image_gen/openai` | 图像后端 | OpenAI `gpt-image-2` 图像生成后端(FAL 的替代方案) || `image_gen/openai-codex` | 图像后端 | 通过 Codex OAuth 使用 OpenAI 图像生成 |@@ -114,72 +113,17 @@ hermes plugins disable disk-cleanup**再次禁用:** `hermes plugins disable disk-cleanup`。-### observability/langfuse+### Langfuse(已移至插件目录)-将 Hermes 的轮次、LLM 调用和工具调用追踪到 [Langfuse](https://langfuse.com)——一个开源 LLM 可观测性平台。每轮一个 span,每次 API 调用一个 generation,每次工具调用一个 tool observation。用量总计、各类型 token 数量和成本估算来自 Hermes 的标准 `agent.usage_pricing` 数据,因此 Langfuse 仪表盘看到的分类(input / output / `cache_read_input_tokens` / `cache_creation_input_tokens` / `reasoning_tokens`)与 `hermes logs` 中显示的一致。--该插件采用失败开放(fail-open)策略:未安装 SDK、无凭据或 Langfuse 出现瞬时错误——所有情况都会在 hook 中静默处理为无操作。agent 循环不受任何影响。--**设置:**--```bash-hermes tools # → Langfuse Observability → Cloud 或 Self-Hosted-```--向导收集凭据,按需通过 PM 准备已声明的 `langfuse` extra,并启用插件。-完成后重启 Hermes;准备失败时通过 `hermes tools` 重试,不要直接 pip 安装到选中的环境。--源码检出的手动设置:先按照 [PM 开发流程](../../reference/package-management.md#developer-workflow)-激活目标检出并选择正确的 Hermes 数据目录,然后执行:+Langfuse 追踪不再随 Hermes 内置,而是作为官方目录插件 [`langfuse`](https://github.com/NousResearch/hermes-official-plugins/tree/main/langfuse) 提供,+hook、`HERMES_LANGFUSE_*` 环境变量和捕获模式保持不变:```bash-python -c "import pm; pm.sync_venv(['langfuse'], explicit=True)"-source ./activate-python hermes plugins enable observability/langfuse+hermes plugins install langfuse```-PowerShell 使用 `. .\activate.ps1` 激活。将凭据写入活动数据目录的 `.env`-(`$HERMES_HOME/.env`,通常为 `~/.hermes/.env`):--```bash-HERMES_LANGFUSE_PUBLIC_KEY=pk-lf-...-HERMES_LANGFUSE_SECRET_KEY=sk-lf-...-HERMES_LANGFUSE_BASE_URL=https://cloud.langfuse.com # 或你的自托管 URL-```--**工作原理:**--| Hook | 行为 |-|---|---|-| `pre_api_request` / `pre_llm_call` | 打开(或复用)每轮的根 span "Hermes turn"。为本次 API 调用启动一个 `generation` 子 observation,将最近的消息序列化为输入。 |-| `post_api_request` / `post_llm_call` | 关闭 generation,附加 `usage_details`、`cost_details`、`finish_reason`、助手输出和工具调用。如果没有工具调用且内容非空,则关闭本轮。 |-| `pre_tool_call` | 启动一个带有经过清理的 `args` 的 `tool` 子 observation。 |-| `post_tool_call` | 关闭 tool observation,附加经过清理的 `result`。`read_file` 的内容会被摘要化(头部 + 尾部 + 省略行数),以使大文件读取保持在 `HERMES_LANGFUSE_MAX_CHARS` 以内。 |--会话分组基于 Hermes 会话 ID(或子 agent 的任务 ID),通过 `langfuse.propagate_attributes` 实现,因此单次 `hermes chat` 会话中的所有内容都归属于同一个 Langfuse session。--**验证:**--```bash-hermes plugins list # observability/langfuse 应显示 "enabled"-hermes chat -q "hello" # 在 Langfuse UI 中检查是否有 "Hermes turn" trace-```--**可选调优**(在 `.env` 中):--| 变量 | 默认值 | 用途 |-|---|---|---|-| `HERMES_LANGFUSE_ENV` | — | trace 上的环境标签(`production`、`staging` 等) |-| `HERMES_LANGFUSE_RELEASE` | — | 发布/版本标签 |-| `HERMES_LANGFUSE_SAMPLE_RATE` | `1.0` | 传递给 SDK 的采样率(0.0–1.0) |-| `HERMES_LANGFUSE_MAX_CHARS` | `12000` | 消息内容 / 工具参数 / 工具结果的单字段截断长度 |-| `HERMES_LANGFUSE_DEBUG` | `false` | 向 `agent.log` 输出详细插件日志 |--Hermes 前缀的环境变量和标准 SDK 环境变量(`LANGFUSE_PUBLIC_KEY`、`LANGFUSE_SECRET_KEY`、`LANGFUSE_BASE_URL`)均被接受——两者同时设置时,Hermes 前缀的优先。--**性能:** Langfuse 客户端在第一次 hook 调用后被缓存。如果凭据或 SDK 缺失,该决定也会被缓存——后续 hook 会快速返回,不再重新检查环境变量或重新加载配置。--**禁用:** `hermes plugins disable observability/langfuse`。插件模块仍会被发现,但在你重新启用之前不会运行任何模块代码。+已启用 `observability/langfuse` 的配置文件会在 `hermes update`(或更新后的首次启动)时自动安装并启用该插件,+继续向同一个 Langfuse 项目发送 trace。安装、调优和捕获模式见[插件 README](https://github.com/NousResearch/hermes-official-plugins/tree/main/langfuse)。### google_meetdiff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/plugins.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/plugins.mdindex ee6926de3db..e573ba72922 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/plugins.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/plugins.md@@ -141,7 +141,7 @@ def register(ctx):`~/.hermes/plugins/model-providers/<name>/` 和 `~/.hermes/plugins/memory/<name>/` 下的用户插件会覆盖同名内置插件 — `register_provider()` / `register_memory_provider()` 中后写者胜出。放入一个目录即可替换内置实现,无需修改仓库。-子分类插件在 `hermes plugins list` 和交互式 `hermes plugins` UI 中以**路径派生的 key** 显示 — 例如 `observability/langfuse`、`image_gen/openai`、`platforms/teams`。该 key(而非 manifest 中的 `name:`)是传给 `hermes plugins enable …` / `disable …` 的值,也是在 `config.yaml` 的 `plugins.enabled` 下填写的字符串。+子分类插件在 `hermes plugins list` 和交互式 `hermes plugins` UI 中以**路径派生的 key** 显示 — 例如 `image_gen/openai`、`platforms/teams`。该 key(而非 manifest 中的 `name:`)是传给 `hermes plugins enable …` / `disable …` 的值,也是在 `config.yaml` 的 `plugins.enabled` 下填写的字符串。## 插件默认关闭(少数例外)@@ -269,11 +269,11 @@ hermes plugins install user/repo --no-enable # 安装但保持禁用(hermes plugins update my-plugin # 拉取最新版本hermes plugins remove my-plugin # 卸载hermes plugins enable my-plugin # 添加到允许列表(普通插件)-hermes plugins enable observability/langfuse # 添加到允许列表(子分类插件)+hermes plugins enable image_gen/openai # 添加到允许列表(子分类插件)hermes plugins disable my-plugin # 从允许列表移除并添加到禁用列表```-对于子分类目录下的插件(例如 `plugins/observability/langfuse/`、`plugins/image_gen/openai/`),使用完整的 `<category>/<plugin>` key — 这正是 `hermes plugins list` 在 **Name** 列中显示的内容。+对于子分类目录下的插件(例如 `plugins/image_gen/openai/`、`plugins/platforms/teams/`),使用完整的 `<category>/<plugin>` key — 这正是 `hermes plugins list` 在 **Name** 列中显示的内容。### 更新检查、来源与依赖@@ -312,7 +312,6 @@ Plugins→ [✓] my-tool-plugin — Custom search tool[ ] webhook-notifier — Event hooks[ ] disk-cleanup — Auto-cleanup of ephemeral files [bundled]- [ ] observability/langfuse — Trace turns / LLM calls / tools to Langfuse [bundled]Provider PluginsMemory Provider ▸ honcho