Skip to content

The agent that grows with you

feat(langfuse): widen tracing to errors, sessions, subagents, and MoA fan-out

kshitije665300d6b1e
diff --git a/agent/conversation_loop.py b/agent/conversation_loop.py
index 38fc16523fb..b56e0649e71 100644
--- a/agent/conversation_loop.py
+++ b/agent/conversation_loop.py
@@ -76,7 +76,6 @@ from agent.model_metadata import (
from agent.process_bootstrap import _install_safe_stdio
from agent.prompt_caching import (
build_prompt_cache_plan,
- effective_cache_ttl,
strip_anthropic_cache_control,
strip_anthropic_tool_cache_control,
)
@@ -87,9 +86,6 @@ from agent.retry_utils import (
zai_coding_overload_retry_ceiling,
)
from agent.trajectory import has_incomplete_scratchpad
-# Bind before the turn starts so a source-tree swap cannot load a skewed
-# finalizer at turn end.
-from agent.turn_finalizer import finalize_turn
from agent.usage_pricing import estimate_usage_cost, normalize_usage
from hermes_constants import PARTIAL_STREAM_STUB_ID
from hermes_logging import set_session_context
@@ -98,71 +94,6 @@ from utils import base_url_host_matches, env_var_enabled
logger = logging.getLogger(__name__)
-
-# Scaffold marker used by _apply_active_turn_redirect and the ghost-row filter
-# in the api_messages loop. Module-level so both sites can never drift.
-_INTERRUPT_SCAFFOLD_MARKER = "[This response was interrupted by a user correction.]"
-
-
-def _restore_user_after_reference_handoff(
- messages: List[Dict[str, Any]], user_message: Any
-) -> bool:
- """Re-append this turn's real user ask when compaction left only a handoff.
-
- Returns True when a restore append happened. The caller has already
- established that a reference-only handoff would drive the next model
- call (#80622); this helper only decides whether a restorable ask exists.
- """
- if user_message is None:
- return False
- if isinstance(user_message, str):
- if not user_message.strip():
- return False
- content: Any = user_message
- elif isinstance(user_message, list):
- if not user_message:
- return False
- content = user_message
- else:
- return False
- if (
- messages
- and isinstance(messages[-1], dict)
- and messages[-1].get("role") == "user"
- and messages[-1].get("content") == content
- ):
- return False
- messages.append({"role": "user", "content": content})
- return True
-
-
-def _should_skip_model_call_for_reference_handoff(
- messages: List[Dict[str, Any]], user_message: Any
-) -> bool:
- """Guard post-compaction continues against sole-handoff active turns (#80622)."""
- from agent.context_compressor import reference_handoff_would_drive_next_model_call
-
- if not reference_handoff_would_drive_next_model_call(messages):
- return False
- if _restore_user_after_reference_handoff(messages, user_message):
- # The restored ask is an actionable non-synthetic user row appended
- # after the handoff — by construction the handoff no longer drives.
- return False
- return True
-
-
-# Fallback final_response for a turn ended by the sole-handoff skip (#80622).
-# Deliberately NOT a replay of the last assistant text: finalize_turn's
-# non-assistant-tail chokepoint (#43849) appends final_response as a fresh
-# assistant row, so recovering the previous turn's prose here would duplicate
-# it in the durable transcript AND re-deliver it to the user as if it were
-# this turn's answer. A short status is honest and idempotent.
-_HANDOFF_SKIP_FINAL_RESPONSE = (
- "Context was compacted. The previous response is complete — "
- "awaiting your next message."
-)
-
-
# Stable prefix of the local interrupt status string emitted when a turn is
# cancelled while waiting on the provider. Surfaces (ACP, TUI) match on this
# to treat it as cancellation metadata rather than assistant prose.
@@ -188,16 +119,6 @@ _API_CALL_MODULES = frozenset({
})
-def _join_truncated_parts(parts: List[str]) -> str:
- """Join continuation fragments, adding a newline where two would glue together (#78577)."""
- joined = ""
- for part in parts:
- if joined and not joined[-1].isspace() and part and not part[0].isspace():
- joined += "\n"
- joined += part
- return joined
-
-
def _apply_active_turn_redirect(agent: Any, messages: List[Dict[str, Any]], text: str) -> None:
"""Append a provider-safe checkpoint and correction to the live turn.
@@ -226,61 +147,77 @@ def _apply_active_turn_redirect(agent: Any, messages: List[Dict[str, Any]], text
``[This response was interrupted by a user correction.]`` and its
``Visible response before the interruption:`` header exist so the MODEL
understands its own reply was cut off. They are not prose the user wrote
- or the agent said. Persisting them into an assistant row's ``content`` or
- ``api_content`` made the model treat the scaffold as *its own previous
- reply*, echo it, and self-replicate ghost rows across turns (#81841).
- Carry the scaffolded form only in the *user correction's* ``api_content``
- sidecar — never on the placeholder assistant row. When nothing was on
- screen the placeholder is marked ``display_kind="hidden"`` (empty
- content) so every transcript surface drops it, exactly like
+ or the agent said. Persisting them into ``content`` painted the raw
+ machinery as an assistant bubble on every reload (and merged it into the
+ preceding tool-call bubble), which is what made a steered transcript
+ unreadable. Carry the scaffolded form in the ``api_content`` sidecar --
+ the exact bytes replayed to the provider -- and keep ``content`` clean.
+ When nothing was on screen there is no clean form at all, so the row is
+ marked ``display_kind="hidden"``: still replayed to the model, dropped by
+ every transcript surface (desktop, TUI, CLI resume), exactly like the
compaction-reference rows.
"""
visible = agent._strip_think_blocks(
getattr(agent, "_current_streamed_assistant_text", "") or ""
).strip()
- checkpoint_parts = [_INTERRUPT_SCAFFOLD_MARKER]
+ checkpoint_parts = ["[This response was interrupted by a user correction.]"]
if visible:
checkpoint_parts.extend(
["Visible response before the interruption:", visible]
)
checkpoint = "\n\n".join(checkpoint_parts)
- correction = (
- "[Context from the interrupted assistant response]\n"
- f"{checkpoint}\n\n"
- f"{text}"
- )
- # The normal live tail is user or tool, so an assistant placeholder
- # followed by the correction preserves strict alternation. If a transport
- # already committed an assistant item, attribute the checkpoint inside the
- # user correction instead of creating assistant→assistant.
+ # The normal live tail is user or tool, so an assistant checkpoint followed
+ # by the correction preserves strict alternation. If a transport already
+ # committed an assistant item, attribute the checkpoint inside the user
+ # correction instead of creating assistant→assistant.
if messages and messages[-1].get("role") == "assistant":
+ correction = (
+ "[Context from the interrupted assistant response]\n"
+ f"{checkpoint}\n\n"
+ f"{text}"
+ )
# Transcript shows the user's own words; the provider replays the
# scaffolded form so it still sees the interrupted context.
messages.append(
{"role": "user", "content": text, "api_content": correction}
)
else:
- # Placeholder preserves role alternation only. Scaffold bytes must
- # never land here — the API replay path substitutes api_content back
- # into content, and a scaffold-as-assistant-reply is what the model
- # then echoes (#81841 / incomplete #73146 else branch).
- placeholder: Dict[str, Any] = {
+ entry: Dict[str, Any] = {
"role": "assistant",
- "content": visible or "",
+ "content": visible or checkpoint,
+ "api_content": checkpoint,
}
if not visible:
- placeholder["display_kind"] = "hidden"
- messages.append(placeholder)
- messages.append(
- {"role": "user", "content": text, "api_content": correction}
- )
+ # Nothing reached the screen — this row carries no assistant prose
+ # at all, only the cut-off notice for the model.
+ entry["display_kind"] = "hidden"
+ messages.append(entry)
+ messages.append({"role": "user", "content": text})
agent._current_streamed_assistant_text = ""
agent._stream_needs_break = True
+def _moa_reference_metrics_for_hook(agent: Any) -> Any:
+ """Per-advisor metrics for post_api_request, or None off the MoA path.
+
+ MoA runs N advisor models before its aggregator and returns only the
+ aggregator's response, so an observability plugin sees one generation for
+ the whole fan-out. The advisor spend is already computed per slot (see
+ ``_RefAccounting``); this only carries it across the hook boundary.
+ """
+ client = getattr(agent, "client", None)
+ getter = getattr(client, "last_reference_metrics", None)
+ if not callable(getter):
+ return None
+ try:
+ return getter()
+ except Exception:
+ return None
+
+
def _is_copilot_provider(agent: Any) -> bool:
"""Delegate to ``AIAgent._is_copilot_provider`` (single owner of the check).
@@ -437,6 +374,24 @@ def _print_nous_entitlement_guidance(agent, capability: str) -> bool:
return True
+def _system_prompt_for_hooks(api_kwargs: Any, request_messages: Any) -> Any:
+ """System prompt as actually sent to the provider, for observability hooks.
+
+ Providers move it out of ``messages``: Anthropic Messages uses a separate
+ ``system`` kwarg (str or content-block list), the Responses/Codex API uses
+ top-level ``instructions``; Chat Completions keeps it as ``messages[0]``.
+ Returns None when the request carries no system prompt.
+ """
+ system_prompt = api_kwargs.get("system")
+ if system_prompt is None:
+ system_prompt = api_kwargs.get("instructions")
+ if system_prompt is None and isinstance(request_messages, list) and request_messages:
+ first = request_messages[0]
+ if isinstance(first, dict) and first.get("role") == "system":
+ system_prompt = first.get("content")
+ return system_prompt
+
+
def _is_nous_inference_route(provider: str, base_url: str) -> bool:
provider = (provider or "").strip().lower()
if provider == "nous":
@@ -606,12 +561,6 @@ def _restore_or_build_system_prompt(agent, system_message, conversation_history)
# Continuing session — reuse the exact system prompt from the
# previous turn so the Anthropic cache prefix matches.
agent._cached_system_prompt = stored_prompt
- # Prompt-section callbacks are new-session-only. Recover their frozen
- # bytes from the persisted full prompt so a later compression rebuild
- # keeps them without evaluating plugin state in this resumed process.
- from agent.system_prompt import restore_plugin_prompt_sections
-
- restore_plugin_prompt_sections(agent, stored_prompt)
# Reconstruct the cross-session-stable prefix for the early cache
# breakpoint. The static prefix is not persisted (only the full
# prompt is), so gateway surfaces that build a fresh AIAgent per
@@ -773,34 +722,11 @@ def _stored_prompt_matches_runtime(agent, prompt: str) -> bool:
return True
-# The three _get_continuation_prompt variants below, in named-constant form
-# so agent.context_compressor's _is_synthetic_compression_user_turn can
-# recognize them by content after a crash/interrupt persists one mid-list —
-# these rows carry no durable role beyond driving the retry, and SessionDB
-# projection strips the _length_continuation_nudge metadata tag that marks
-# them in live memory (see agent/context_compressor.py).
-_LENGTH_CONTINUATION_NETWORK_STUB = (
- "[System: The previous response was cut off by a "
- "network error mid-stream. Continue exactly where "
- "you left off. Do not restart or repeat prior text. "
- "Finish the answer directly.]"
-)
-_LENGTH_CONTINUATION_OUTPUT_LIMIT = (
- "[System: Your previous response was truncated by the output "
- "length limit. Continue exactly where you left off. Do not "
- "restart or repeat prior text. Finish the answer directly.]"
-)
-# The dropped-tools variant interpolates the tool name list right after this
-# prefix, so it can't be exact-matched — this stable prefix is what
-# _is_synthetic_compression_user_turn checks with str.startswith instead.
-_LENGTH_CONTINUATION_DROPPED_TOOLS_PREFIX = "[System: Your previous tool call "
-
-
def _get_continuation_prompt(is_partial_stub: bool, dropped_tools: Optional[List[str]] = None) -> str:
if is_partial_stub and dropped_tools:
tool_list = ", ".join(dropped_tools[:3])
return (
- f"{_LENGTH_CONTINUATION_DROPPED_TOOLS_PREFIX}"
+ "[System: Your previous tool call "
f"({tool_list}) was too large and "
"the stream timed out before it "
"could be delivered. Do NOT retry "
@@ -813,9 +739,18 @@ def _get_continuation_prompt(is_partial_stub: bool, dropped_tools: Optional[List
"tokens to avoid stream timeouts.]"
)
elif is_partial_stub:
- return _LENGTH_CONTINUATION_NETWORK_STUB
+ return (
+ "[System: The previous response was cut off by a "
+ "network error mid-stream. Continue exactly where "
+ "you left off. Do not restart or repeat prior text. "
+ "Finish the answer directly.]"
+ )
else:
- return _LENGTH_CONTINUATION_OUTPUT_LIMIT
+ return (
+ "[System: Your previous response was truncated by the output "
+ "length limit. Continue exactly where you left off. Do not "
+ "restart or repeat prior text. Finish the answer directly.]"
+ )
# Continuation nudge for Codex/Responses turns that came back with only
@@ -833,36 +768,6 @@ _CODEX_INCOMPLETE_NUDGE = (
)
-# Re-prompt sent after a Codex/Responses turn ends with an acknowledgment-only
-# reply (no tool calls, no final answer) — named so
-# agent.context_compressor's _is_synthetic_compression_user_turn can
-# recognize it by content the same way it recognizes _CODEX_INCOMPLETE_NUDGE.
-_CODEX_ACK_CONTINUATION_NUDGE = (
- "[System: Continue now. Execute the required tool calls and only "
- "send your final answer after completing the task.]"
-)
-
-# Re-prompt sent when a provider returns finish_reason="tool_calls" with an
-# empty tool_calls array (dropped-tool-call recovery, see the retry loop
-# below). Named for the same reason as _CODEX_ACK_CONTINUATION_NUDGE — this
-# pair is only stripped from the durable transcript once the turn reaches
-# finalization; an interrupt/crash mid-retry can still persist it.
-_DROPPED_TOOLCALL_NUDGE_CONTENT = (
- "Your previous turn indicated a tool call but none was "
- "included. Do not narrate a plan or restate intent — issue "
- "the actual tool call now to continue the task."
-)
-
-# Re-prompt sent when the model returns an empty response after executing tool
-# calls (#9400). Named for the same reason as the nudges above — its
-# _empty_recovery_synthetic metadata flag doesn't survive SessionDB projection.
-_EMPTY_TOOL_RESPONSE_NUDGE = (
- "You just executed tool calls but returned an "
- "empty response. Please process the tool "
- "results above and continue with the task."
-)
-
-
# Shared recovery hint appended to every content-policy refusal message. Both
# the HTTP-200 refusal path (``finish_reason=content_filter``) and the
# exception path (a provider moderation error classified as
@@ -926,50 +831,6 @@ def _canonicalize_tool_call_arguments(arg_str: str) -> str:
return canonical
-def _clone_message_for_send(msg):
- """Structural clone of a history message for the per-call API copy.
-
- The send path builds ``api_messages`` from the persisted history and
- then rewrites the copies in place (canonicalization/repair of tool-call
- arguments, surrogate and non-ASCII sanitization, content strips, cache
- decoration). A shallow ``msg.copy()`` only decouples TOP-LEVEL fields:
- nested containers — ``tool_calls`` entries and their ``function`` dicts,
- multimodal ``content`` part lists, ``reasoning_details`` — remain the
- SAME objects the persisted history holds, so any in-place write there
- silently rewrites the stored transcript (#80498: an unrepairable
- ``write_file`` argument string was replaced with ``{}`` in the persisted
- turn, destroying the streamed file content).
-
- Cloning every container (dict/list) recursively while SHARING immutable
- leaves (strings, numbers, None) makes every downstream in-place
- transform safe by construction — current and future — at container-count
- cost, not string-byte cost: big argument strings and base64 image
- payloads are shared, never copied. Measured: ~1-5ms per 2000-message
- pathological build (20% multimodal, 30% tool calls) vs ~0.4ms for the
- shallow copy; compression keeps real request histories far smaller, and
- the build runs once per API call — noise next to the call itself.
- copy.deepcopy would be equally correct (CPython deepcopy also shares
- immutable str) but ~4x slower again and needs its memo machinery;
- history messages are JSON-shaped and acyclic (depth < 10 in practice;
- a >~1000-deep pathological nest would hit the recursion limit, exactly
- as deepcopy would), so cycle handling isn't needed here. Tuples are
- shared as leaves: JSON-derived message content never contains tuples,
- so a mutable container smuggled inside one is not a reachable shape on
- this path.
- """
- if isinstance(msg, dict):
- return {
- k: _clone_message_for_send(v) if isinstance(v, (dict, list)) else v
- for k, v in msg.items()
- }
- if isinstance(msg, list):
- return [
- _clone_message_for_send(v) if isinstance(v, (dict, list)) else v
- for v in msg
- ]
- return msg
-
-
def _canonicalize_api_tool_calls(api_messages) -> None:
"""Canonicalize tool-call argument JSON on the send-path message copy.
@@ -996,25 +857,10 @@ def _canonicalize_api_tool_calls(api_messages) -> None:
),
}}
except Exception:
- # Copy-on-write here too. The send-path build now hands
- # this pass structurally-cloned messages (see
- # _clone_message_for_send), but this branch keeps its own
- # copy as defense in depth: some callers (tests, future
- # call sites) pass shallow copies, and assigning into a
- # shared ``tc["function"]`` would rewrite the stored
- # turn. On the unrepairable path the repair returns "{}",
- # so a write-through here replaced the model's real
- # arguments with an empty object in the transcript: a
- # stream that died mid ``write_file`` lost the file
- # content it had already streamed, with only a WARNING
- # to show for it (#80498).
- tc = {**tc, "function": {
- **tc["function"],
- "arguments": _repair_tool_call_arguments(
- tc["function"]["arguments"],
- tc["function"].get("name", "?"),
- ),
- }}
+ tc["function"]["arguments"] = _repair_tool_call_arguments(
+ tc["function"]["arguments"],
+ tc["function"].get("name", "?"),
+ )
new_tcs.append(tc)
am["tool_calls"] = new_tcs
@@ -1277,13 +1123,7 @@ def _redecorate_prompt_cache_for_provider(
plan = build_prompt_cache_plan(
messages,
planned_tools,
- # Clamp per-destination: a configured 1h regresses to 5m on
- # Qwen/Alibaba routes, whose context cache is 5m-only (#84733).
- cache_ttl=effective_cache_ttl(
- agent._cache_ttl,
- provider=agent.provider,
- model=agent.model,
- ),
+ cache_ttl=agent._cache_ttl,
native_anthropic=agent._use_native_cache_layout,
static_system_prefix=static if isinstance(static, str) else None,
direct_native_tool_cache=direct_tool_cache,
@@ -1340,13 +1180,10 @@ def _apply_context_engine_selection(
# and it may be replaced wholesale via the return value — never mutated in
# place either. ``conversation_messages`` / ``incoming_message`` are
# read-only context; copying enforces the request-only contract rather than
- # merely documenting it. Structural clones, not dict(m): a shallow copy
- # would leave nested containers (tool_calls, content parts) aliased to
- # the persisted history, so an engine writing into them would rewrite
- # the transcript (#80498 aliasing class).
- _conv_copy = [_clone_message_for_send(m) for m in conversation_messages] \
+ # merely documenting it.
+ _conv_copy = [dict(m) if isinstance(m, dict) else m for m in conversation_messages] \
if conversation_messages is not None else None
- _incoming_copy = _clone_message_for_send(incoming_message) if isinstance(incoming_message, dict) else incoming_message
+ _incoming_copy = dict(incoming_message) if isinstance(incoming_message, dict) else incoming_message
try:
selected = engine.select_context(
api_messages,
@@ -1417,10 +1254,7 @@ def _notify_context_engine_turn_complete(
try:
hook(
- # Structural clones: on_turn_complete receives the PERSISTED
- # history; a shallow dict(m) would let a hook write through
- # nested containers into the transcript (#80498 aliasing class).
- [_clone_message_for_send(m) for m in messages],
+ [dict(m) if isinstance(m, dict) else m for m in messages],
usage=usage,
**meta,
)
@@ -1493,31 +1327,6 @@ def run_conversation(
agent._last_compression_attempt_recorded = False
agent._last_compression_attempt_in_place = None
- # If a background memory/skill review spawned at the end of a PRIOR turn
- # (agent/background_review.py) is still running its own run_conversation()
- # when THIS turn starts, cancel it now rather than letting both make
- # outbound API calls concurrently against the same session_id/credentials.
- # That concurrency can produce doubled prompt-token accounting on this
- # turn's own calls and, because the review fork is a fully separate
- # AIAgent with no route back to THIS agent's interrupt() by default, a
- # lockup that survives a normal /stop and needs a hard Ctrl+C.
- # ``review_agent.interrupt()`` is fire-and-forget here — it just flags
- # cancellation and aborts the review's in-flight socket; it does not
- # block waiting for the review's daemon thread to exit, so it can't add
- # latency to this turn. Only ever set on the real owning agent (the
- # review fork's own copy of this attribute stays None — reviews don't
- # spawn nested reviews), so this is a no-op on every other run_conversation
- # caller (subagents, the review fork itself, etc).
- _pending_review = getattr(agent, "_background_review_agent", None)
- if _pending_review is not None:
- try:
- _pending_review.interrupt("superseded by a new live turn")
- except Exception:
- logger.debug(
- "Failed to cancel in-flight background review for a new turn",
- exc_info=True,
- )
-
# Adopt any ~/.hermes/.env credential/base-url edits made since the last
# turn — a Settings save updates .env but not this worker's client, which
# was built at agent init (#67821). No-op when .env is unchanged.
@@ -1574,11 +1383,6 @@ def run_conversation(
# A configured SessionDB append failure halts only the affected turn. A
# cached gateway agent must recover on the next message if storage did.
agent._incremental_persistence_failed = False
- # Cause of the most recent persistence failure this turn ('locked',
- # 'disk', or 'unknown' — see hermes_state.classify_persistence_error).
- # Reset alongside the failure flag so a lock-contention diagnosis from a
- # previous turn can never leak into this turn's user-facing explanation.
- agent._last_persistence_error_cause = None
# Main conversation loop counters (pure locals consumed by the loop below).
api_call_count = 0
@@ -1797,30 +1601,6 @@ def run_conversation(
agent.session_id or "-",
)
- # Drop legacy ghost rows from the incomplete #73146 else branch BEFORE
- # the alternation repair below: a hidden assistant placeholder whose
- # content/api_content is the raw interrupt scaffold. Replaying that as
- # an assistant message makes the model echo it and self-replicate
- # (#81841). Dropping before repair lets repair_message_sequence fix
- # any user→user adjacency the filter creates.
- messages = [
- msg for msg in messages
- if not (
- msg.get("display_kind") == "hidden"
- and msg.get("role") == "assistant"
- and (
- (
- isinstance(msg.get("content"), str)
- and msg["content"].strip() == _INTERRUPT_SCAFFOLD_MARKER
- )
- or (
- isinstance(msg.get("api_content"), str)
- and msg["api_content"].strip() == _INTERRUPT_SCAFFOLD_MARKER
- )
- )
- )
- ]
-
# Defensive: repair malformed role-alternation before API call.
# Catches cases where the history got wedged into a
# ``tool → user`` or ``user → user`` tail (e.g. after empty-
@@ -1842,13 +1622,7 @@ def run_conversation(
api_messages = []
for idx, msg in enumerate(messages):
-
- # Structural clone, NOT msg.copy(): every in-place transform
- # below (canonicalize/repair, surrogate + non-ASCII sanitizers,
- # cache decoration) must be unable to reach the persisted
- # history through shared nested containers. See
- # _clone_message_for_send.
- api_msg = _clone_message_for_send(msg)
+ api_msg = msg.copy()
# api_content is the persistence sidecar carrying the exact bytes
# sent to the API for this message when they differ from the clean
@@ -1920,11 +1694,8 @@ def run_conversation(
# Remove finish_reason - not accepted by strict APIs (e.g. Mistral)
if "finish_reason" in api_msg:
api_msg.pop("finish_reason")
- # _thinking_prefill survives here intentionally: the drop pass below
- # needs it. The transport strips all underscore keys before the wire.
- # Strip length-continuation marks; not every transport drops underscore keys.
- api_msg.pop("_length_continuation_fragment", None)
- api_msg.pop("_length_continuation_nudge", None)
+ # Strip internal thinking-prefill marker
+ api_msg.pop("_thinking_prefill", None)
# Strip Codex Responses API fields (call_id, response_item_id) for
# strict providers like Mistral, Fireworks, etc. that reject unknown fields.
# Uses new dicts so the internal messages list retains the fields
@@ -2033,11 +1804,7 @@ def run_conversation(
if agent.prefill_messages:
sys_offset = 1 if (api_messages and api_messages[0].get("role") == "system") else 0
for idx, pfm in enumerate(agent.prefill_messages):
- # Structural clone: the sanitizers below run over
- # api_messages in place, and a shallow copy would let them
- # write through into agent.prefill_messages' nested
- # containers (same aliasing class as the history build).
- api_messages.insert(sys_offset + idx, _clone_message_for_send(pfm))
+ api_messages.insert(sys_offset + idx, pfm.copy())
# Per-turn context selection hook (additive, no-op by default).
# Lets a context engine select/replace which context enters the
@@ -2126,13 +1893,7 @@ def run_conversation(
_initial_cache_plan = build_prompt_cache_plan(
api_messages,
tools_for_api,
- # Clamp per-destination: a configured 1h regresses to 5m on
- # Qwen/Alibaba routes, whose context cache is 5m-only (#84733).
- cache_ttl=effective_cache_ttl(
- agent._cache_ttl,
- provider=agent.provider,
- model=agent.model,
- ),
+ cache_ttl=agent._cache_ttl,
native_anthropic=agent._use_native_cache_layout,
static_system_prefix=(
_static_system_prefix
@@ -2177,15 +1938,6 @@ def run_conversation(
_estimate_tools_tokens_rough(agent.tools) if agent.tools else 0
)
total_chars = approx_tokens * 4
- # Stash this request's rough estimate so update_from_response() can
- # pair it with the provider's real prompt count — the (rough, real)
- # anchor behind should_defer_preflight_to_real_usage()'s projection.
- # getattr guard: test doubles built via object.__new__ lack the method.
- _note_rough = getattr(
- agent.context_compressor, "note_request_rough_estimate", None
- )
- if callable(_note_rough):
- _note_rough(request_pressure_tokens)
_runtime_context_error = _ollama_context_limit_error(
agent, request_pressure_tokens
@@ -2352,30 +2104,9 @@ def run_conversation(
conversation_history = conversation_history_after_compression(
agent, messages, conversation_history
)
- # This preflight iteration never reaches the provider whether
- # we skip the turn (handoff guard below) or re-run the loop —
- # refund the consumed call/budget in BOTH cases, mirroring the
- # ollama_runtime_context_too_small early-exit above. Without
- # the refund on the break path, every skipped turn leaked one
- # iteration-budget unit for the agent's lifetime and
- # finalize_turn logged an api_call_count including a call that
- # was never made.
api_call_count -= 1
agent._api_call_count = api_call_count
agent.iteration_budget.refund()
- if _should_skip_model_call_for_reference_handoff(
- messages, user_message
- ):
- # Reference-only handoff must not become the active turn
- # after a completed assistant response (#80622).
- logger.info(
- "Skipping post-compaction model call: reference-only "
- "handoff would be the sole active user turn (#80622)"
- )
- if not final_response:
- final_response = _HANDOFF_SKIP_FINAL_RESPONSE
- _turn_exit_reason = "compaction_handoff_not_actionable"
- break
continue
elif (
agent.compression_enabled
@@ -2471,8 +2202,7 @@ def run_conversation(
retry_count = 0
compression_attempts = 0
_retry.primary_recovery_attempted = False
- _retry.restart_with_rebuilt_messages = True
- break
+ continue
# No fallback available — surface buffered context
# so user sees the rate-limit message that led here.
agent._flush_status_buffer()
@@ -2525,16 +2255,6 @@ def run_conversation(
api_messages,
tools_for_api=tools_for_api,
)
- # Outbound-request surrogate chokepoint (#50959): the messages
- # were scrubbed above, but the rest of the request body —
- # tool/function descriptions (session_search's ±-heavy text is
- # the recorded repro), extra_body, system strings routed via
- # kwargs — can still carry invalid code points that providers
- # reject with a non-retryable HTTP 400 ("invalid unicode code
- # point"). One in-place walk here guarantees the entire
- # payload json.dumps()-safe regardless of which leaf produced
- # the string. Fast no-op when the payload is clean.
- _sanitize_structure_surrogates(api_kwargs)
if agent._force_ascii_payload:
_sanitize_structure_non_ascii(api_kwargs)
if agent.api_mode == "codex_responses":
@@ -2586,6 +2306,13 @@ def run_conversation(
request_messages = api_kwargs.get("input")
if not isinstance(request_messages, list):
request_messages = api_messages
+ # Anthropic (``system``) and Responses/Codex
+ # (``instructions``) move the system prompt out of
+ # messages; pass it explicitly for observability
+ # plugins (Langfuse).
+ system_prompt_for_hooks = _system_prompt_for_hooks(
+ api_kwargs, request_messages
+ )
# Shallow-copy the outer list so plugins that retain the
# reference for async snapshotting don't observe later
# mutations of api_messages. The inner dicts are not
@@ -2621,6 +2348,7 @@ def run_conversation(
request_messages=list(request_messages)
if isinstance(request_messages, list)
else [],
+ system_prompt=system_prompt_for_hooks,
message_count=len(api_messages),
tool_count=len(agent.tools or []),
approx_input_tokens=approx_tokens,
@@ -2924,8 +2652,7 @@ def run_conversation(
retry_count = 0
compression_attempts = 0
_retry.primary_recovery_attempted = False
- _retry.restart_with_rebuilt_messages = True
- break
+ continue
# Check for error field in response (some providers include this)
error_msg = "Unknown"
@@ -2998,8 +2725,7 @@ def run_conversation(
retry_count = 0
compression_attempts = 0
_retry.primary_recovery_attempted = False
- _retry.restart_with_rebuilt_messages = True
- break
+ continue
# Terminal — flush buffered retry trace so user sees what happened.
agent._flush_status_buffer()
agent._emit_status(f"❌ Max retries ({max_retries}) exceeded for invalid responses. Giving up.")
@@ -3176,8 +2902,7 @@ def run_conversation(
retry_count = 0
compression_attempts = 0
_retry.primary_recovery_attempted = False
- _retry.restart_with_rebuilt_messages = True
- break
+ continue
agent._flush_status_buffer()
_refusal_log = (
@@ -3219,8 +2944,8 @@ def run_conversation(
if finish_reason == "length":
if getattr(response, "id", "") == PARTIAL_STREAM_STUB_ID:
agent._vprint(
- f"{agent.log_prefix}⚠️ Response truncated — stream "
- f"ended before completion",
+ f"{agent.log_prefix}⚠️ Stream interrupted by network error "
+ f"(finish_reason='length' on partial-stream-stub)",
force=True,
)
else:
@@ -3347,11 +3072,6 @@ def run_conversation(
# gets a coherent continuation point.
if truncated_response_parts:
messages = agent._get_messages_up_to_last_assistant(messages)
- # Unmark survivors: their text left the stitched partial.
- for _frag in messages:
- if isinstance(_frag, dict):
- _frag.pop("_length_continuation_fragment", None)
- _frag.pop("_length_continuation_nudge", None)
agent._session_messages = messages
length_continue_retries = 0
truncated_response_parts = []
@@ -3388,8 +3108,6 @@ def run_conversation(
)
if not _is_empty_partial_stub:
interim_msg = agent._build_assistant_message(assistant_message, finish_reason)
- # Marked so the ceiling exit can drop the fragment trail.
- interim_msg["_length_continuation_fragment"] = True
messages.append(interim_msg)
if assistant_message.content:
truncated_response_parts.append(assistant_message.content)
@@ -3428,45 +3146,13 @@ def run_conversation(
continue_msg = {
"role": "user",
"content": _continue_content,
- "_length_continuation_nudge": True,
}
messages.append(continue_msg)
agent._session_messages = messages
_retry.restart_with_length_continuation = True
break
- partial_response = agent._strip_think_blocks(_join_truncated_parts(truncated_response_parts)).strip()
- if partial_response:
- agent._vprint(
- f"{agent.log_prefix}⚠️ Response still truncated "
- f"after 4 continuation attempts — keeping the "
- f"partial response received so far.",
- force=True,
- )
- # Unanswered continue nudges made every later turn re-truncate.
- _turn_start = (
- current_turn_user_idx + 1
- if isinstance(current_turn_user_idx, int)
- and current_turn_user_idx >= 0
- else 0
- )
- messages[_turn_start:] = [
- m for m in messages[_turn_start:]
- if not (
- isinstance(m, dict)
- and (
- m.get("_length_continuation_fragment")
- or m.get("_length_continuation_nudge")
- )
- )
- ]
- if partial_response:
- messages.append({
- "role": "assistant",
- "content": partial_response,
- "finish_reason": "length",
- })
- agent._session_messages = messages
+ partial_response = agent._strip_think_blocks("".join(truncated_response_parts)).strip()
agent._cleanup_task_resources(effective_task_id)
agent._persist_session(messages, conversation_history)
return {
@@ -4502,39 +4188,6 @@ def run_conversation(
)
continue
- # ── Native compaction rejection recovery ──────────────
- # Provider explicitly rejected the ``context_management``
- # field (structured 400 naming the param). One-shot: turn
- # native compaction off for the rest of the session and
- # retry — the next _build_api_kwargs re-resolves the gate
- # and omits the field, and Hermes' local compression takes
- # over as the sole owner. Generic 4xx/5xx/timeouts do NOT
- # match (see is_native_compaction_rejection) and take the
- # normal retry path.
- if (
- agent.api_mode == "codex_responses"
- and not _retry.native_compaction_reject_retry_attempted
- and bool(getattr(agent, "codex_responses_native_compaction", False))
- ):
- from agent.native_compaction import is_native_compaction_rejection
- if is_native_compaction_rejection(
- api_error, getattr(api_error, "status_code", None)
- ):
- _retry.native_compaction_reject_retry_attempted = True
- agent.codex_responses_native_compaction = False
- agent._vprint(
- f"{agent.log_prefix}⚠️ Provider rejected native compaction "
- f"(context_management) — disabled for this session, "
- f"local compression stays active. Retrying...",
- force=True,
- )
- logger.warning(
- "%sNative compaction rejection recovery: disabled "
- "codex_responses_native for this session and retrying",
- agent.log_prefix,
- )
- continue
-
# ── llama.cpp grammar-parse recovery ──────────────────
# llama.cpp's ``json-schema-to-grammar`` converter rejects
# regex escape classes (``\d``, ``\w``, ``\s``) and most
@@ -4880,8 +4533,7 @@ def run_conversation(
retry_count = 0
compression_attempts = 0
_retry.primary_recovery_attempted = False
- _retry.restart_with_rebuilt_messages = True
- break
+ continue
# ── Auth-failure provider failover ───────────────────────
# A 401/403 that survives the per-provider credential-refresh
@@ -4914,8 +4566,7 @@ def run_conversation(
retry_count = 0
compression_attempts = 0
_retry.primary_recovery_attempted = False
- _retry.restart_with_rebuilt_messages = True
- break
+ continue
# ── Nous Portal: record rate limit & skip retries ─────
# When Nous returns a 429 that is a genuine account-
@@ -5522,8 +5173,7 @@ def run_conversation(
retry_count = 0
compression_attempts = 0
_retry.primary_recovery_attempted = False
- _retry.restart_with_rebuilt_messages = True
- break
+ continue
if api_kwargs is not None:
agent._dump_api_request_debug(
api_kwargs, reason="non_retryable_client_error", error=api_error,
@@ -5746,8 +5396,7 @@ def run_conversation(
retry_count = 0
compression_attempts = 0
_retry.primary_recovery_attempted = False
- _retry.restart_with_rebuilt_messages = True
- break
+ continue
# Terminal — flush buffered retry/fallback trace.
agent._flush_status_buffer()
_final_summary = agent._summarize_api_error(api_error)
@@ -6036,26 +5685,12 @@ def run_conversation(
# to fit the context window.
retry_count += 1
_retry.restart_with_compressed_messages = False
- if _should_skip_model_call_for_reference_handoff(
- messages, user_message
- ):
- logger.info(
- "Skipping compressed-restart model call: reference-only "
- "handoff would be the sole active user turn (#80622)"
- )
- if not final_response:
- final_response = _HANDOFF_SKIP_FINAL_RESPONSE
- _turn_exit_reason = "compaction_handoff_not_actionable"
- break
# In-loop compression rebuilt `messages` with fresh compaction
# copies, so the pre-compression current-turn index is stale.
# Re-anchor exactly like the prologue does: a stale index that
# lands on a historical user message would make the live-compose
# fallback inject this turn's prefetch into that message on the
# wire only, diverging the next turn's replayed prefix there.
- # Ordered AFTER the handoff guard: the guard may have re-appended
- # this turn's real user ask (restore path), and the anchor must
- # land on that restored row, not on -1 / a pre-restore index.
current_turn_user_idx = reanchor_current_turn_user_idx(
messages, user_message
)
@@ -6063,20 +5698,14 @@ def run_conversation(
continue
if _retry.restart_with_rebuilt_messages:
- # A stream stall or provider failure was escalated to the
- # fallback chain (10 activation sites in the retry loop set this
- # flag and break here). Re-issue the API call against the
- # now-active fallback provider. Refund the budget/count for the
- # stalled attempt so the fallback gets a fair turn.
+ # A content-filter stream stall (#32421) was escalated to the
+ # fallback chain and the partial content rolled back. Re-issue
+ # the API call against the now-active fallback provider. Refund
+ # the budget/count for the stalled attempt so the fallback gets a
+ # fair turn.
api_call_count -= 1
agent.iteration_budget.refund()
_retry.restart_with_rebuilt_messages = False
- # Failover shrank the compressor's context window to the
- # fallback's; clear the preflight block so the pre-API preflight
- # re-runs against the new threshold before the first fallback
- # call (#84733). Hoisted here (the single consumer) so every
- # activation site — including ones added later — gets it.
- _preflight_compression_blocked = False
continue
if _retry.restart_with_length_continuation:
@@ -6173,6 +5802,7 @@ def run_conversation(
assistant_message=assistant_message,
assistant_content_chars=len(_assistant_text),
assistant_tool_call_count=len(_assistant_tool_calls),
+ moa_references=_moa_reference_metrics_for_hook(agent),
)
except Exception:
pass
@@ -6295,20 +5925,7 @@ def run_conversation(
"codex_message_items",
):
if _key in interim_msg:
- if _key == "codex_reasoning_items":
- # Merge instead of overwrite: a native
- # compaction checkpoint captured on the
- # earlier incomplete response is the only
- # copy — the continuation won't re-emit
- # it. See merge_interim_reasoning_items.
- from agent.native_compaction import (
- merge_interim_reasoning_items,
- )
- last_msg[_key] = merge_interim_reasoning_items(
- last_msg.get(_key), interim_msg[_key]
- )
- else:
- last_msg[_key] = interim_msg[_key]
+ last_msg[_key] = interim_msg[_key]
else:
messages.append(interim_msg)
agent._emit_interim_assistant_message(interim_msg)
@@ -6755,10 +6372,6 @@ def run_conversation(
)
except Exception as exc:
_tool_turn_persisted = False
- from hermes_state import classify_persistence_error
- agent._last_persistence_error_cause = (
- classify_persistence_error(exc)
- )
logger.warning(
"Incremental tool-call persistence failed before execution "
"(session=%s): %s",
@@ -6771,10 +6384,6 @@ def run_conversation(
# run side-effecting tools from state that exists only in
# this process. Breaking also avoids retrying the same
# unpersisted turn until the iteration budget is exhausted.
- # The flush may have classified the cause internally; if
- # nothing was recorded, the cause is genuinely unknown.
- if getattr(agent, "_last_persistence_error_cause", None) is None:
- agent._last_persistence_error_cause = "unknown"
_turn_exit_reason = "session_persistence_failed"
final_response = ""
failed = True
@@ -6928,18 +6537,6 @@ def run_conversation(
conversation_history = conversation_history_after_compression(
agent, messages, conversation_history
)
- if _should_skip_model_call_for_reference_handoff(
- messages, user_message
- ):
- logger.info(
- "Skipping post-tool compaction model call: "
- "reference-only handoff would be the sole "
- "active user turn (#80622)"
- )
- if not final_response:
- final_response = _HANDOFF_SKIP_FINAL_RESPONSE
- _turn_exit_reason = "compaction_handoff_not_actionable"
- break
elif agent.compression_enabled:
# Over threshold but compression is blocked (summary-LLM
# cooldown or anti-thrashing). Surface a deduped warning so
@@ -6987,12 +6584,14 @@ def run_conversation(
# Standard no-op caller contract: only commit when the
# engine returned a NEW list object with a non-zero count.
if _pruned_n and _pruned_msgs is not messages:
- # Do NOT rebuild conversation_history here. The compressor
- # atomically rewrites the active transcript with the durable
- # rearm threshold, then stamps every returned row with
+ # Do NOT rebuild conversation_history here. Unlike the
+ # compression branch, the prune neither rotates the session
+ # nor calls archive_and_compact(), so there is no new
+ # persistence baseline to establish. _prune_old_tool_results
+ # returns per-message copies that preserve the
# _DB_PERSISTED_MARKER, so the marker-based flush dedup (see
- # _flush_messages_to_session_db) prevents duplicate writes.
- # Calling
+ # _flush_messages_to_session_db) already prevents both
+ # duplicate writes and dropped rows. Calling
# conversation_history_after_compression (a compaction-only
# helper keyed on the _last_compaction_in_place flag) would be
# a no-op at best, and on a stale in-place flag could seed
@@ -7146,7 +6745,11 @@ def run_conversation(
messages.append(_nudge_msg)
messages.append({
"role": "user",
- "content": _EMPTY_TOOL_RESPONSE_NUDGE,
+ "content": (
+ "You just executed tool calls but returned an "
+ "empty response. Please process the tool "
+ "results above and continue with the task."
+ ),
"_empty_recovery_synthetic": True,
})
continue
@@ -7276,15 +6879,6 @@ def run_conversation(
"now using %s on %s",
agent.model, agent.provider,
)
- # This site sits directly in the OUTER iteration
- # loop (not the retry loop), so `continue` already
- # restarts the iteration and re-runs the pre-API
- # preflight against the fallback's context window
- # (#84733). A `break` here would exit the outer
- # loop and end the turn without ever calling the
- # fallback. Clear the preflight block so the
- # re-run isn't skipped.
- _preflight_compression_blocked = False
continue
# Exhausted retries and fallback chain (or no
@@ -7388,7 +6982,10 @@ def run_conversation(
continue_msg = {
"role": "user",
- "content": _CODEX_ACK_CONTINUATION_NUDGE,
+ "content": (
+ "[System: Continue now. Execute the required tool calls and only "
+ "send your final answer after completing the task.]"
+ ),
}
messages.append(continue_msg)
agent._session_messages = messages
@@ -7401,14 +6998,9 @@ def run_conversation(
codex_ack_continuations = 0
if truncated_response_parts:
- final_response = _join_truncated_parts([*truncated_response_parts, final_response])
+ final_response = "".join(truncated_response_parts) + final_response
truncated_response_parts = []
length_continue_retries = 0
- # The continuation recovered, so the fragments stay in the transcript.
- for _frag in messages:
- if isinstance(_frag, dict):
- _frag.pop("_length_continuation_fragment", None)
- _frag.pop("_length_continuation_nudge", None)
final_response = agent._strip_think_blocks(final_response).strip()
@@ -7456,7 +7048,11 @@ def run_conversation(
messages.append(final_msg)
messages.append({
"role": "user",
- "content": _DROPPED_TOOLCALL_NUDGE_CONTENT,
+ "content": (
+ "Your previous turn indicated a tool call but none was "
+ "included. Do not narrate a plan or restate intent — issue "
+ "the actual tool call now to continue the task."
+ ),
"_dropped_toolcall_nudge": True,
})
agent._session_messages = messages
@@ -7657,24 +7253,7 @@ def run_conversation(
continue
messages.append(final_msg)
- # Make the completed answer durable before leaving the loop —
- # a session torn down before finalize_turn's _persist_session
- # otherwise loses a reply the user already saw (#81641). Same
- # contract as the tool-call exit (#49045) and the verify exits
- # above; _DB_PERSISTED_MARKER keeps _persist_session idempotent.
- # Unlike the tool-call exit, failure must NOT abort the turn:
- # no side effect follows and _persist_session retries the write.
- # Full incident narrative: tests/run_agent/test_81641_*.py.
- try:
- agent._flush_messages_to_session_db(messages, conversation_history)
- except Exception:
- logger.warning(
- "final text-turn flush failed (session=%s) — reply is "
- "not yet durable; relying on finalize_turn retry",
- getattr(agent, "session_id", None) or "none",
- exc_info=True,
- )
-
+
_turn_exit_reason = f"text_response(finish_reason={finish_reason})"
if not agent.quiet_mode:
agent._safe_print(f"🎉 Conversation completed after {api_call_count} OpenAI-compatible API call(s)")
@@ -7778,6 +7357,7 @@ def run_conversation(
# Post-loop turn finalization extracted to agent/turn_finalizer.finalize_turn
# (god-file decomposition Phase 1 step 4). Behavior-neutral: the assembled
# result dict is returned exactly as before.
+ from agent.turn_finalizer import finalize_turn
return finalize_turn(
agent,
final_response=final_response,
diff --git a/agent/moa_loop.py b/agent/moa_loop.py
index a55b29af29c..789c431c2d5 100644
--- a/agent/moa_loop.py
+++ b/agent/moa_loop.py
@@ -410,7 +410,6 @@ def _maybe_apply_moa_cache_control(
runtime: dict[str, Any],
*,
cache_disabled: bool | None = None,
- cache_ttl: str | None = None,
) -> list[dict[str, Any]]:
"""Decorate an advisor or aggregator request with cache_control when its
route honors it.
@@ -428,20 +427,13 @@ def _maybe_apply_moa_cache_control(
``cache_disabled`` (or the live config when omitted) is stamped onto the
policy stub so ``prompt_caching.cache_ttl: off`` is not bypassed by the
blank-agent pattern (#76085).
-
- ``cache_ttl`` threads the agent's configured tier (default ``5m``) so
- advisor/synthesis requests stop regressing 1h → 5m; it is clamped
- per-destination by :func:`effective_cache_ttl` (Qwen → 5m, #84733).
"""
try:
from agent.agent_runtime_helpers import (
anthropic_prompt_cache_policy,
blank_cache_policy_stub,
)
- from agent.prompt_caching import (
- apply_anthropic_cache_control,
- effective_cache_ttl,
- )
+ from agent.prompt_caching import apply_anthropic_cache_control
# Prefer an explicit kwarg, then a snapshot on the runtime dict
# (threaded from the live agent), else config via the stub factory.
@@ -462,15 +454,7 @@ def _maybe_apply_moa_cache_control(
if not should_cache:
return messages
return apply_anthropic_cache_control(
- messages,
- cache_ttl=effective_cache_ttl(
- # effective_cache_ttl resolves None → "5m"; the should_cache
- # gate above already returned for cache-disabled routes.
- cache_ttl,
- provider=runtime.get("provider") or "",
- model=runtime.get("model") or "",
- ),
- native_anthropic=native_layout,
+ messages, native_anthropic=native_layout
)
except Exception as exc: # pragma: no cover - decoration must never break a call
logger.debug("MoA cache_control decoration skipped: %s", exc)
@@ -486,7 +470,6 @@ def _run_reference(
reference_timeout: float | None = None,
context_length_cache: Any = None,
cache_disabled: bool | None = None,
- cache_ttl: str | None = None,
) -> tuple[str, str, Any]:
"""Call one reference model and return ``(label, text, accounting)``.
@@ -553,9 +536,7 @@ def _run_reference(
cache_runtime = runtime
if cache_disabled is not None:
cache_runtime = {**runtime, "_cache_disabled": cache_disabled}
- messages = _maybe_apply_moa_cache_control(
- messages, cache_runtime, cache_ttl=cache_ttl
- )
+ messages = _maybe_apply_moa_cache_control(messages, cache_runtime)
# Per-slot max_tokens takes precedence over the preset-level
# reference_max_tokens passed in by the caller. This lets each
# reference model have its own output cap independently.
@@ -862,10 +843,6 @@ def _run_references_parallel(
cache_disabled = (
getattr(agent, "_cache_disabled", None) if agent is not None else None
)
- # Thread the agent's configured cache TTL into every advisor request so
- # the fan-out stops regressing 1h → 5m (#84733); the destination-aware
- # clamp (Qwen → 5m) runs inside _maybe_apply_moa_cache_control.
- cache_ttl = getattr(agent, "_cache_ttl", None) if agent is not None else None
try:
for idx, slot in enumerate(reference_models):
if slot.get("provider") == "moa":
@@ -885,7 +862,6 @@ def _run_references_parallel(
reference_timeout=reference_timeout,
context_length_cache=_ctx_len_cache,
cache_disabled=cache_disabled,
- cache_ttl=cache_ttl,
)
] = idx
@@ -1346,9 +1322,6 @@ def aggregate_moa_context(
**agg_runtime,
"_cache_disabled": _agg_cache_disabled,
}
- # Thread the agent's configured cache TTL into the synthesis decoration
- # so the one-shot /moa path stops regressing 1h → 5m (#84733).
- _agg_cache_ttl = getattr(agent, "_cache_ttl", None) if agent is not None else None
try:
# Same cache_control decoration as _run_reference's advisor calls
# (see _maybe_apply_moa_cache_control) — this synthesis call is a
@@ -1361,9 +1334,7 @@ def aggregate_moa_context(
# breakpoints, even when the resolved aggregator slot is a
# cache-honoring route (e.g. Claude on OpenRouter/native Anthropic).
agg_messages = _maybe_apply_moa_cache_control(
- [{"role": "user", "content": synth_prompt}],
- agg_cache_runtime,
- cache_ttl=_agg_cache_ttl,
+ [{"role": "user", "content": synth_prompt}], agg_cache_runtime
)
response = call_llm(
task="moa_aggregator",
@@ -1591,6 +1562,11 @@ class MoAChatCompletions:
# caller to stitch in the live session_id + resolved aggregator output
# and flush to the trace file (only when moa.save_traces is on).
self._pending_trace: Any = None
+ # Per-advisor metrics for observability hooks. Unlike _pending_trace
+ # this is NOT consumed — post_api_request fires on a different branch
+ # than consume_and_save_trace, so a consuming read would race it. Holds
+ # until the next fan-out replaces it.
+ self._last_reference_metrics: Any = None
# every_n fan-out cadence state. The iteration counter is scoped to a
# single USER TURN (not the facade lifetime): it counts create() calls
# since the last new user message and resets whenever the user-turn
@@ -1622,6 +1598,14 @@ class MoAChatCompletions:
self._pending_reference_cost = None
return usage, cost
+ def last_reference_metrics(self) -> Any:
+ """Per-advisor metrics from the most recent fan-out, or None.
+
+ Read-only: a MoA turn's post_api_request hook must not disturb the
+ accounting that consume_reference_usage and consume_and_save_trace own.
+ """
+ return self._last_reference_metrics
+
def _record_late_reference_accounting(self, label: str, accounting: Any) -> None:
"""Fold a late-completing interrupted reference's real spend in.
@@ -1780,13 +1764,6 @@ class MoAChatCompletions:
api_mode=agg_runtime.get("api_mode") or "",
model=agg_runtime.get("model") or "",
cache_disabled=_cache_disabled,
- # Thread the agent's configured TTL and stable system prefix
- # into the aggregator plan so MoA stops regressing 1h → 5m and
- # marking the whole system prompt as one breakpoint (#84733).
- cache_ttl=getattr(_agent, "_cache_ttl", None),
- static_system_prefix=getattr(
- _agent, "_cached_system_prompt_static", None
- ),
)
if guidance:
_attach_reference_guidance(agg_messages, str(guidance))
@@ -2177,6 +2154,18 @@ class MoAChatCompletions:
"aggregator_slot": aggregator,
"aggregator_temperature": aggregator_temperature,
}
+ # Derived from the same privacy-redacted _trace_refs, so an active
+ # privacy mode redacts the observability payload too.
+ try:
+ from agent.moa_trace import slot_metrics
+
+ self._last_reference_metrics = [
+ slot_metrics(acct, label, output=text)
+ for label, text, acct in _trace_refs
+ ]
+ except Exception as exc: # pragma: no cover - never break a turn
+ logger.debug("MoA reference metrics render failed: %s", exc)
+ self._last_reference_metrics = None
# Surface each reference model's answer to the display BEFORE the
# aggregator acts — once per turn (only on the iteration that
@@ -2321,6 +2310,14 @@ class MoAClient:
session_id, aggregator_output_fallback=aggregator_output_fallback
)
+ def last_reference_metrics(self) -> Any:
+ """Per-advisor metrics from the most recent fan-out, or None.
+
+ Read-only, unlike the two consume_* methods above: the observability
+ hook fires on a different branch than the accounting they own.
+ """
+ return getattr(self.chat.completions, "_last_reference_metrics", None)
+
def build_moa_facade(agent, preset_name: Any = None) -> MoAClient:
"""Build the MoA facade client for ``agent``, wiring the reference relay.
diff --git a/agent/moa_trace.py b/agent/moa_trace.py
index 37a51700812..b261c3637c7 100644
--- a/agent/moa_trace.py
+++ b/agent/moa_trace.py
@@ -94,6 +94,21 @@ def _slot_trace(acct: Any, label: str) -> dict[str, Any]:
}
+def slot_metrics(acct: Any, label: str, output: Any = None) -> dict[str, Any]:
+ """Render one reference's accounting for observability hooks.
+
+ Same fields as ``_slot_trace`` minus ``input_messages``, which is the bulk
+ of a trace record and would cross the plugin-hook boundary for every
+ advisor on every turn. ``output`` comes from the caller because the
+ privacy-redacted advisor text lives alongside the accounting, not on it.
+ """
+ trace = _slot_trace(acct, label)
+ trace.pop("input_messages", None)
+ if output is not None:
+ trace["output"] = output
+ return trace
+
+
def save_moa_turn(
*,
session_id: Optional[str],
diff --git a/hermes_cli/hooks.py b/hermes_cli/hooks.py
index 5135d4a955e..549ce0e68c4 100644
--- a/hermes_cli/hooks.py
+++ b/hermes_cli/hooks.py
@@ -211,14 +211,10 @@ _DEFAULT_PAYLOADS = {
"usage": {"input_tokens": 2048, "output_tokens": 512},
"assistant_content_chars": 1200,
"assistant_tool_call_count": 0,
- },
- "pre_transcription": {
- "file_path": "/tmp/voice-message.ogg",
- "provider": "local",
- "model": "base",
- "language": "en",
- "prompt": None,
- "source": "gateway",
+ # Per-advisor metrics on a MoA turn, None otherwise. MoA returns only
+ # the aggregator's response, so without this an observer cannot see the
+ # fan-out or price it at each advisor's own model.
+ "moa_references": None,
},
"subagent_stop": {
"parent_session_id": "parent-sess",
@@ -298,11 +294,9 @@ def _cmd_test(args) -> None:
def _print_run_result(result: Dict[str, Any]) -> None:
if result.get("error"):
print(f" ✗ error: {result['error']}")
- _print_parsed(result)
return
if result.get("timed_out"):
print(f" ✗ timed out after {result['elapsed_seconds']}s")
- _print_parsed(result)
return
rc = result.get("returncode")
@@ -316,10 +310,6 @@ def _print_run_result(result: Dict[str, Any]) -> None:
if stderr:
print(f" stderr: {_truncate(stderr, 400)}")
- _print_parsed(result)
-
-
-def _print_parsed(result: Dict[str, Any]) -> None:
parsed = result.get("parsed")
if parsed:
print(f" parsed (Hermes wire shape): {json.dumps(parsed)}")
diff --git a/plugins/observability/langfuse/README.md b/plugins/observability/langfuse/README.md
index 864735d9688..8800cf75228 100644
--- a/plugins/observability/langfuse/README.md
+++ b/plugins/observability/langfuse/README.md
@@ -36,6 +36,10 @@ hermes plugins list # observability/langfuse should show "enable
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
@@ -43,9 +47,35 @@ 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_CAPTURE=sanitized # content capture mode (see below)
HERMES_LANGFUSE_DEBUG=true # verbose plugin logging
```
+## 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
diff --git a/plugins/observability/langfuse/__init__.py b/plugins/observability/langfuse/__init__.py
index 31904d47e30..eddc7c817fc 100644
--- a/plugins/observability/langfuse/__init__.py
+++ b/plugins/observability/langfuse/__init__.py
@@ -18,6 +18,10 @@ Optional env vars:
HERMES_LANGFUSE_RELEASE - release/version tag
HERMES_LANGFUSE_SAMPLE_RATE - sampling rate 0.0–1.0 (default: 1.0)
HERMES_LANGFUSE_MAX_CHARS - max chars per field (default: 12000)
+ HERMES_LANGFUSE_CAPTURE - content capture mode (default: "sanitized")
+ metadata - no content: sizes, roles, tool names, IDs, usage, cost only
+ sanitized - content with secret-pattern redaction + truncation
+ full - raw content (truncated only); explicit opt-in
HERMES_LANGFUSE_DEBUG - set to "true" for verbose logging
"""
from __future__ import annotations
@@ -49,6 +53,12 @@ class TraceState:
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 a tool-loop turn would re-emit the same
+ # advisors on every API call without this.
+ moa_emitted: set = field(default_factory=set)
last_updated_at: float = field(default_factory=time.time)
@@ -64,6 +74,13 @@ _TRACE_STATE: Dict[str, TraceState] = {}
# to bound the leak from non-finalizing turns, not to limit concurrency.
_MAX_TRACE_STATE = 256
_LANGFUSE_CLIENT = None
+# Guards _LANGFUSE_CLIENT initialization against the TOCTOU race: two
+# concurrent first callers both pass the ``is not None`` guard, both
+# construct a Langfuse(**kwargs) client, and the loser's client leaks an
+# open HTTPS connection + background flush thread. _STATE_LOCK is not
+# reused here because it guards _TRACE_STATE (hot path) and nesting the
+# two locks would risk deadlock with future callers.
+_LANGFUSE_CLIENT_LOCK = threading.Lock()
_READ_FILE_LINE_RE = re.compile(r"^\s*(\d+)\|(.*)$")
_READ_FILE_HEAD_LINES = 25
_READ_FILE_TAIL_LINES = 15
@@ -101,6 +118,101 @@ def _debug(message: str) -> None:
logger.info("Langfuse tracing: %s", message)
+# ---------------------------------------------------------------------------
+# Capture modes
+# ---------------------------------------------------------------------------
+
+_CAPTURE_MODES = ("metadata", "sanitized", "full")
+_DEFAULT_CAPTURE_MODE = "sanitized"
+_warned_invalid_capture = False
+
+
+def _capture_mode() -> str:
+ """Resolve the content-capture mode: ``metadata | sanitized | full``.
+
+ Read per call (cheap env lookup) so tests and long-lived processes can
+ flip modes without a client reset. Invalid values warn once per process
+ and fall back to the default rather than silently capturing more than
+ the operator intended.
+ """
+ global _warned_invalid_capture
+ value = _env("HERMES_LANGFUSE_CAPTURE").lower()
+ if not value:
+ return _DEFAULT_CAPTURE_MODE
+ if value in _CAPTURE_MODES:
+ return value
+ 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
+
+
+# Secret-shaped substrings redacted in ``sanitized`` mode. Ordered: specific
+# key formats first, generic assignment patterns last. Intentionally tight to
+# keep false positives low — this is defense in depth for accidental secret
+# passage through prompts/tool output, not a DLP system.
+_SECRET_PATTERNS: list[tuple[re.Pattern, str]] = [
+ (re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----.*?(?:-----END [A-Z ]*PRIVATE KEY-----|\Z)", re.DOTALL), "[REDACTED:private-key]"),
+ (re.compile(r"\b(?:sk|pk)-lf-[A-Za-z0-9\-]{8,}"), "[REDACTED:langfuse-key]"),
+ (re.compile(r"\bsk-ant-[A-Za-z0-9_\-]{8,}"), "[REDACTED:api-key]"),
+ (re.compile(r"\bsk-[A-Za-z0-9_\-]{16,}"), "[REDACTED:api-key]"),
+ (re.compile(r"\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}"), "[REDACTED:github-token]"),
+ (re.compile(r"\bgithub_pat_[A-Za-z0-9_]{20,}"), "[REDACTED:github-token]"),
+ (re.compile(r"\bAKIA[0-9A-Z]{16}\b"), "[REDACTED:aws-key]"),
+ (re.compile(r"\bxox[baprs]-[A-Za-z0-9\-]{10,}"), "[REDACTED:slack-token]"),
+ (re.compile(r"\beyJ[A-Za-z0-9_\-]{20,}\.[A-Za-z0-9_\-]{10,}\.[A-Za-z0-9_\-]{10,}\b"), "[REDACTED:jwt]"),
+ (re.compile(r"(?i)\b(authorization\s*:\s*bearer)\s+[A-Za-z0-9_\-.~+/=]{8,}"), r"\1 [REDACTED:token]"),
+ (re.compile(r"(?i)\b((?:api[_-]?key|secret[_-]?key|access[_-]?token|refresh[_-]?token|client[_-]?secret|password|passwd)\s*[=:]\s*)(['\"]?)[^\s'\"]{6,}\2"), r"\1\2[REDACTED]\2"),
+]
+
+
+def _redact_secrets(value: str) -> str:
+ for pattern, replacement in _SECRET_PATTERNS:
+ value = pattern.sub(replacement, value)
+ return value
+
+
+def _describe_content(value: Any, *, depth: int = 0) -> Any:
+ """Metadata-mode stand-in for content: shape and size, never payload."""
+ if value is None or isinstance(value, bool):
+ return value
+ if isinstance(value, (int, float)):
+ return {"omitted": True, "type": "number"}
+ if isinstance(value, bytes):
+ return {"omitted": True, "type": "bytes", "length": len(value)}
+ if isinstance(value, str):
+ return {"omitted": True, "type": "text", "chars": len(value)}
+ if isinstance(value, dict):
+ return {
+ "omitted": True,
+ "type": "object",
+ "keys": [str(k) for k in list(value.keys())[:20]],
+ }
+ if isinstance(value, (list, tuple, set)):
+ return {"omitted": True, "type": "array", "items": len(value)}
+ return {"omitted": True, "type": type(value).__name__}
+
+
+def _capture_content(value: Any, *, parse_json_strings: bool = False,
+ tool_name: str = "", args: Any = None) -> Any:
+ """Apply the active capture mode to a CONTENT value.
+
+ Metadata fields (provider, model, IDs, counts) should NOT go through
+ this — they stay as-is in every mode. Only prompt/response text, tool
+ arguments, and tool results are content.
+ """
+ mode = _capture_mode()
+ if mode == "metadata":
+ return _describe_content(value)
+ if tool_name or args is not None:
+ value = _normalize_payload(value, tool_name=tool_name, args=args)
+ return _safe_value(value, parse_json_strings=parse_json_strings)
+
+
# Sentinel: "_get_langfuse() has tried and failed". Lets us short-circuit
# every subsequent hook call without re-checking env vars or re-attempting
# SDK init. Tests clear this by reloading the module via
@@ -154,78 +266,106 @@ def _get_langfuse() -> Optional[Langfuse]:
+ credentials present). The result is cached: on the first call we try
to construct a client, and every subsequent call returns that client
(or fast-returns ``None`` if init failed).
+
+ Thread-safe: ``_LANGFUSE_CLIENT_LOCK`` serializes the first build so
+ concurrent callers can't both pass the ``is not None`` guard, both
+ construct a ``Langfuse(**kwargs)`` client, and leak the loser's open
+ HTTP connection and background flush thread (same TOCTOU class fixed
+ for the Honcho and FAL clients in ``plugins/plugin_utils.py``).
"""
global _LANGFUSE_CLIENT
+ # Fast path — already settled (success or _INIT_FAILED); no lock needed.
if _LANGFUSE_CLIENT is _INIT_FAILED:
return None
if _LANGFUSE_CLIENT is not None:
return _LANGFUSE_CLIENT
- if Langfuse is None:
- _LANGFUSE_CLIENT = _INIT_FAILED
- return None
-
- public_key = _env("HERMES_LANGFUSE_PUBLIC_KEY") or _env("LANGFUSE_PUBLIC_KEY")
- secret_key = _env("HERMES_LANGFUSE_SECRET_KEY") or _env("LANGFUSE_SECRET_KEY")
- if not (public_key and secret_key):
- _LANGFUSE_CLIENT = _INIT_FAILED
- return None
-
- # Reject placeholder credentials with a one-shot warning so the
- # operator sees the misconfiguration instead of silently shipping a
- # broken observability stack (#23823). The SDK does not validate
- # keys at construction time — it queues traces in memory and only
- # discovers the auth failure when the background flush thread tries
- # to post them, by which point the warning is buried under whatever
- # else the process is logging. Catch it here, surface it once, and
- # short-circuit via the same _INIT_FAILED path as the empty case.
- placeholder_issues = [
- msg
- for msg in (
- _validate_langfuse_key("HERMES_LANGFUSE_PUBLIC_KEY", public_key),
- _validate_langfuse_key("HERMES_LANGFUSE_SECRET_KEY", secret_key),
- )
- if msg
- ]
- 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),
- )
- _LANGFUSE_CLIENT = _INIT_FAILED
- return None
-
- base_url = _env("HERMES_LANGFUSE_BASE_URL") or _env("LANGFUSE_BASE_URL") or "https://cloud.langfuse.com"
- environment = _env("HERMES_LANGFUSE_ENV") or _env("LANGFUSE_ENV")
- release = _env("HERMES_LANGFUSE_RELEASE") or _env("LANGFUSE_RELEASE")
- sample_rate = _env("HERMES_LANGFUSE_SAMPLE_RATE")
+ with _LANGFUSE_CLIENT_LOCK:
+ # Re-check inside the lock: a racing thread may have completed init
+ # while we were waiting.
+ if _LANGFUSE_CLIENT is _INIT_FAILED:
+ return None
+ if _LANGFUSE_CLIENT is not None:
+ return _LANGFUSE_CLIENT
+
+ if Langfuse is None:
+ _LANGFUSE_CLIENT = _INIT_FAILED
+ return None
+
+ public_key = _env("HERMES_LANGFUSE_PUBLIC_KEY") or _env("LANGFUSE_PUBLIC_KEY")
+ secret_key = _env("HERMES_LANGFUSE_SECRET_KEY") or _env("LANGFUSE_SECRET_KEY")
+ if not (public_key and secret_key):
+ _LANGFUSE_CLIENT = _INIT_FAILED
+ return None
+
+ # Reject placeholder credentials with a one-shot warning so the
+ # operator sees the misconfiguration instead of silently shipping a
+ # broken observability stack (#23823). The SDK does not validate
+ # keys at construction time — it queues traces in memory and only
+ # discovers the auth failure when the background flush thread tries
+ # to post them, by which point the warning is buried under whatever
+ # else the process is logging. Catch it here, surface it once, and
+ # short-circuit via the same _INIT_FAILED path as the empty case.
+ placeholder_issues = [
+ msg
+ for msg in (
+ _validate_langfuse_key("HERMES_LANGFUSE_PUBLIC_KEY", public_key),
+ _validate_langfuse_key("HERMES_LANGFUSE_SECRET_KEY", secret_key),
+ )
+ if msg
+ ]
+ 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),
+ )
+ _LANGFUSE_CLIENT = _INIT_FAILED
+ return None
+
+ base_url = _env("HERMES_LANGFUSE_BASE_URL") or _env("LANGFUSE_BASE_URL") or "https://cloud.langfuse.com"
+ environment = _env("HERMES_LANGFUSE_ENV") or _env("LANGFUSE_ENV")
+ release = _env("HERMES_LANGFUSE_RELEASE") or _env("LANGFUSE_RELEASE")
+ sample_rate = _env("HERMES_LANGFUSE_SAMPLE_RATE")
+
+ kwargs: Dict[str, Any] = {
+ "public_key": public_key,
+ "secret_key": secret_key,
+ "base_url": base_url,
+ }
+ if environment:
+ kwargs["environment"] = environment
+ if release:
+ kwargs["release"] = release
+ if sample_rate:
+ try:
+ kwargs["sample_rate"] = float(sample_rate)
+ except ValueError:
+ logger.warning("Invalid HERMES_LANGFUSE_SAMPLE_RATE=%r", sample_rate)
- kwargs: Dict[str, Any] = {
- "public_key": public_key,
- "secret_key": secret_key,
- "base_url": base_url,
- }
- if environment:
- kwargs["environment"] = environment
- if release:
- kwargs["release"] = release
- if sample_rate:
try:
- kwargs["sample_rate"] = float(sample_rate)
- except ValueError:
- logger.warning("Invalid HERMES_LANGFUSE_SAMPLE_RATE=%r", sample_rate)
+ _LANGFUSE_CLIENT = Langfuse(**kwargs)
+ except Exception as exc: # pragma: no cover - fail-open
+ logger.warning("Could not initialize Langfuse client: %s", exc)
+ _LANGFUSE_CLIENT = _INIT_FAILED
+ return None
+
+ # atexit is LIFO: registering AFTER the SDK's constructor (which installs
+ # its own shutdown flush) means our finalizer runs FIRST at exit — root
+ # spans ended there are still picked up by the SDK's exporter. Closes the
+ # short-lived-process gap (kanban workers / hermes chat -q / cron): exit
+ # with tool calls still queued left the root span un-ended → anonymous
+ # trace with no name/session/metadata on the backend.
+ try:
+ import atexit
- try:
- _LANGFUSE_CLIENT = Langfuse(**kwargs)
- except Exception as exc: # pragma: no cover - fail-open
- logger.warning("Could not initialize Langfuse client: %s", exc)
- _LANGFUSE_CLIENT = _INIT_FAILED
- return None
+ atexit.register(_finalize_all_traces)
+ except Exception: # pragma: no cover - fail-open
+ pass
- return _LANGFUSE_CLIENT
+ return _LANGFUSE_CLIENT
def _scope_prefix(task_id: str, session_id: str) -> str:
@@ -265,6 +405,24 @@ def _trace_key(
return _scope_prefix(task_id, session_id)
+def _state_for_turn(turn_id: str) -> Optional[str]:
+ """Resolve a live trace key from a turn id alone.
+
+ The subagent hooks carry ``parent_turn_id`` but no ``task_id``, and
+ ``_scope_prefix`` prefers ``task_id`` when the LLM hooks minted the key —
+ so rebuilding the key here would miss whenever a task id is in play.
+ ``turn_id`` is already unique per turn, so match on its suffix instead.
+ Caller must hold ``_STATE_LOCK``.
+ """
+ if not turn_id:
+ return None
+ suffix = f":turn:{turn_id}"
+ for key in _TRACE_STATE:
+ if key.endswith(suffix):
+ return key
+ return None
+
+
def _is_base64_data_uri(value: str) -> bool:
prefix = value[:200].lower()
return prefix.startswith("data:") and ";base64," in prefix
@@ -289,6 +447,10 @@ def _truncate_text(value: str, max_chars: int) -> Any:
# reaches the SDK.
if _is_base64_data_uri(value):
return _redact_data_uri(value)
+ # Redact BEFORE truncating so a secret straddling the cut point cannot
+ # leak its prefix. Truncation is a size control, not redaction.
+ if _capture_mode() == "sanitized":
+ value = _redact_secrets(value)
if len(value) <= max_chars:
return value
return value[:max_chars] + f"... [truncated {len(value) - max_chars} chars]"
@@ -462,7 +624,7 @@ def _extract_last_user_message(messages: Any) -> Any:
if isinstance(message, dict) and message.get("role") == "user":
return {
"role": "user",
- "content": _safe_value(message.get("content")),
+ "content": _capture_content(message.get("content")),
}
return None
@@ -482,6 +644,57 @@ def _coerce_request_messages(
return [{"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 for Langfuse."""
+ if system_prompt is None:
+ return None
+ if isinstance(system_prompt, str):
+ text = system_prompt.strip()
+ if not text:
+ return None
+ return {"role": "system", "content": _capture_content(text)}
+ if isinstance(system_prompt, list):
+ parts: list[str] = []
+ for block in system_prompt:
+ if isinstance(block, dict):
+ # Anthropic blocks carry {"type": "text", "text": ...}; Bedrock
+ # Converse system blocks are {"text": ...} with no "type" key.
+ block_type = block.get("type")
+ if block_type == "text" or (block_type is None and "text" in block):
+ piece = block.get("text", "")
+ if isinstance(piece, str) and piece:
+ parts.append(piece)
+ elif isinstance(block, str) and block:
+ parts.append(block)
+ if not parts:
+ return None
+ return {"role": "system", "content": _capture_content("\n\n".join(parts))}
+ return 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]]:
+ """Build generation input: include Anthropic ``system`` when split out of ``messages``."""
+ raw = _coerce_request_messages(
+ request_messages=request_messages,
+ messages=messages,
+ conversation_history=conversation_history,
+ user_message=user_message,
+ )
+ if raw and raw[0].get("role") == "system":
+ return _serialize_messages(raw)
+ system_msg = _serialize_system_prompt(system_prompt)
+ if system_msg is None:
+ return _serialize_messages(raw)
+ return [system_msg, *_serialize_messages(raw)]
+
+
def _serialize_messages(messages: Any) -> list[dict[str, Any]]:
if not isinstance(messages, list):
return []
@@ -492,7 +705,7 @@ def _serialize_messages(messages: Any) -> list[dict[str, Any]]:
role = message.get("role")
item = {
"role": role,
- "content": _safe_value(
+ "content": _capture_content(
message.get("content"),
parse_json_strings=(role == "tool"),
),
@@ -503,7 +716,7 @@ def _serialize_messages(messages: Any) -> list[dict[str, Any]]:
if message.get("name"):
item["name"] = _safe_value(message.get("name"))
if message.get("tool_calls"):
- item["tool_calls"] = _safe_value(message.get("tool_calls"), parse_json_strings=True)
+ item["tool_calls"] = _capture_content(message.get("tool_calls"), parse_json_strings=True)
serialized.append(item)
return serialized
@@ -516,7 +729,7 @@ def _serialize_tool_calls(tool_calls: Any) -> list[dict[str, Any]]:
fn = getattr(tool_call, "function", None)
name = getattr(fn, "name", None) if fn else None
arguments = getattr(fn, "arguments", None) if fn else None
- safe_arguments = _safe_value(arguments, parse_json_strings=False)
+ safe_arguments = _capture_content(arguments, parse_json_strings=False)
serialized.append({
"id": getattr(tool_call, "id", None),
"type": getattr(tool_call, "type", None) or "function",
@@ -530,42 +743,53 @@ def _serialize_tool_calls(tool_calls: Any) -> list[dict[str, Any]]:
return serialized
+def _extract_assistant_reasoning(message: Any) -> Any:
+ for field in ("reasoning", "reasoning_content", "reasoning_details"):
+ value = getattr(message, field, None)
+ if value is not None:
+ return _capture_content(value)
+ return None
+
+
def _serialize_assistant_message(message: Any) -> dict[str, Any]:
return {
- "content": _safe_value(getattr(message, "content", None)),
- "reasoning": _safe_value(getattr(message, "reasoning", None)),
+ "content": _capture_content(getattr(message, "content", None)),
+ "reasoning": _extract_assistant_reasoning(message),
"tool_calls": _serialize_tool_calls(getattr(message, "tool_calls", None)),
}
-def _usage_and_cost(response: Any, *, provider: str, api_mode: str, model: str, base_url: str) -> tuple[dict[str, int], dict[str, float]]:
- usage_details: Dict[str, int] = {}
- cost_details: Dict[str, float] = {}
- raw_usage = getattr(response, "usage", None)
- if not raw_usage:
- return usage_details, cost_details
+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] = {
+ "input": canonical.input_tokens,
+ "output": canonical.output_tokens,
+ }
+ if canonical.cache_read_tokens:
+ usage_details["cache_read_input_tokens"] = canonical.cache_read_tokens
+ if canonical.cache_write_tokens:
+ usage_details["cache_creation_input_tokens"] = canonical.cache_write_tokens
+ if canonical.reasoning_tokens:
+ usage_details["reasoning_tokens"] = canonical.reasoning_tokens
+ cost_details: Dict[str, float] = {}
try:
- from agent.usage_pricing import estimate_usage_cost, normalize_usage
+ from agent.usage_pricing import estimate_usage_cost, resolve_billing_route
+
+ # Subscription-included routes (e.g. openai-codex): Langfuse treats
+ # provided cost_details as authoritative and will not recalculate
+ # from model pricing when explicit zeros are sent. Omit cost_details
+ # entirely so Langfuse falls back to its own estimation.
+ route = resolve_billing_route(model, provider=provider, base_url=base_url)
+ if getattr(route, "billing_mode", "") == "subscription_included":
+ return usage_details, cost_details
- canonical = normalize_usage(raw_usage, provider=provider, api_mode=api_mode)
- # Langfuse usage_details keys follow a naming convention:
- # - Dashboard sums all keys containing "input" as input total
- # - Dashboard sums all keys containing "output" as output total
- # - If no "total" key, Langfuse derives it from all usage types
- # Use Anthropic-style key names so cache tokens roll into the
- # dashboard input total automatically.
- # Ref: https://langfuse.com/docs/model-usage-and-cost
- usage_details = {
- "input": canonical.input_tokens,
- "output": canonical.output_tokens,
- }
- if canonical.cache_read_tokens:
- usage_details["cache_read_input_tokens"] = canonical.cache_read_tokens
- if canonical.cache_write_tokens:
- usage_details["cache_creation_input_tokens"] = canonical.cache_write_tokens
- if canonical.reasoning_tokens:
- usage_details["reasoning_tokens"] = canonical.reasoning_tokens
cost = estimate_usage_cost(
model,
canonical,
@@ -573,33 +797,88 @@ def _usage_and_cost(response: Any, *, provider: str, api_mode: str, model: str,
base_url=base_url,
api_key="",
)
- if cost.amount_usd is not None:
- # Langfuse cost_details keys must match usage_details keys.
- # Provide per-type breakdown so dashboard can show cost by type.
- try:
- from agent.usage_pricing import get_pricing_entry
- from decimal import Decimal
- _ONE_M = Decimal("1000000")
- entry = get_pricing_entry(model, provider=provider, base_url=base_url)
- if entry:
- if entry.input_cost_per_million is not None and canonical.input_tokens:
- cost_details["input"] = float(Decimal(canonical.input_tokens) * entry.input_cost_per_million / _ONE_M)
- if entry.output_cost_per_million is not None and canonical.output_tokens:
- cost_details["output"] = float(Decimal(canonical.output_tokens) * entry.output_cost_per_million / _ONE_M)
- if entry.cache_read_cost_per_million is not None and canonical.cache_read_tokens:
- cost_details["cache_read_input_tokens"] = float(Decimal(canonical.cache_read_tokens) * entry.cache_read_cost_per_million / _ONE_M)
- if entry.cache_write_cost_per_million is not None and canonical.cache_write_tokens:
- cost_details["cache_creation_input_tokens"] = float(Decimal(canonical.cache_write_tokens) * entry.cache_write_cost_per_million / _ONE_M)
- else:
- cost_details["total"] = float(cost.amount_usd)
- except Exception:
- cost_details["total"] = float(cost.amount_usd)
except Exception as exc: # pragma: no cover - fail-open
- _debug(f"usage normalization failed: {exc}")
+ _debug(f"usage pricing failed: {exc}")
+ return usage_details, cost_details
+
+ # A partial component breakdown is not a valid request total. In
+ # particular, cache pricing may be unavailable even when input/output
+ # rates are known. Leave all costs absent so Langfuse cannot mistake a
+ # partial subtotal for the full generation cost.
+ if cost.amount_usd is None:
+ return usage_details, cost_details
+
+ # Langfuse only derives a total for the built-in input/output cost keys.
+ # Cache/custom keys therefore need an explicit canonical total. Use the
+ # Hermes estimate rather than summing components because it also includes
+ # request-level pricing. Preserve the existing component-only payload for
+ # subscription-included routes; their export policy is handled separately.
+ # A zero estimate is not exported either: a priced model that billed no
+ # tokens writes no per-type keys, and an explicit 0.0 total would be
+ # treated as authoritative by Langfuse instead of left for it to derive.
+ if cost.status != "included" and float(cost.amount_usd) > 0:
+ cost_details["total"] = float(cost.amount_usd)
+
+ # Langfuse cost_details keys match usage_details keys. Keep the per-type
+ # breakdown for dashboards in addition to the authoritative request total.
+ try:
+ from decimal import Decimal
+
+ from agent.usage_pricing import get_pricing_entry
+
+ one_million = Decimal("1000000")
+ entry = get_pricing_entry(model, provider=provider, base_url=base_url)
+ if entry:
+ if entry.input_cost_per_million is not None and canonical.input_tokens:
+ cost_details["input"] = float(
+ Decimal(canonical.input_tokens)
+ * entry.input_cost_per_million
+ / one_million
+ )
+ if entry.output_cost_per_million is not None and canonical.output_tokens:
+ cost_details["output"] = float(
+ Decimal(canonical.output_tokens)
+ * entry.output_cost_per_million
+ / one_million
+ )
+ if entry.cache_read_cost_per_million is not None and canonical.cache_read_tokens:
+ cost_details["cache_read_input_tokens"] = float(
+ Decimal(canonical.cache_read_tokens)
+ * entry.cache_read_cost_per_million
+ / one_million
+ )
+ if entry.cache_write_cost_per_million is not None and canonical.cache_write_tokens:
+ cost_details["cache_creation_input_tokens"] = float(
+ Decimal(canonical.cache_write_tokens)
+ * entry.cache_write_cost_per_million
+ / one_million
+ )
+ except Exception: # pragma: no cover - canonical total remains usable
+ pass
return usage_details, cost_details
+def _usage_and_cost(response: Any, *, provider: str, api_mode: str, model: str, base_url: str) -> tuple[dict[str, int], dict[str, float]]:
+ raw_usage = getattr(response, "usage", None)
+ if not raw_usage:
+ return {}, {}
+
+ try:
+ from agent.usage_pricing import normalize_usage
+
+ canonical = normalize_usage(raw_usage, provider=provider, api_mode=api_mode)
+ return _canonical_usage_and_cost(
+ canonical,
+ provider=provider,
+ model=model,
+ base_url=base_url,
+ )
+ except Exception as exc: # pragma: no cover - fail-open
+ _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:
@@ -614,6 +893,7 @@ def _start_root_trace(task_key: str, *, task_id: str, session_id: str, platform:
"provider": provider,
"model": model,
"api_mode": api_mode,
+ "capture_mode": _capture_mode(),
}
# session_id must be passed in trace_context for Langfuse session grouping.
@@ -658,10 +938,12 @@ def _start_root_trace(task_key: str, *, task_id: str, session_id: str, platform:
)
root_span = root_ctx.__enter__()
+ # SDK v3 uses update_trace() (not set_trace_io). Failures must never block
+ # the rest of the turn — the observation still carries input from start.
try:
- root_span.set_trace_io(input=trace_input)
- except Exception:
- pass
+ root_span.update_trace(input=trace_input)
+ except Exception as exc:
+ _debug(f"update_trace(input) failed: {exc}")
_debug(f"started trace {trace_id} for {task_key}")
return TraceState(trace_id=trace_id, root_ctx=root_ctx, root_span=root_span)
@@ -730,10 +1012,66 @@ def _evict_stale_locked() -> None:
_TRACE_STATE.pop(key, None)
try:
state.root_span.end()
+ if state.root_ctx is not None:
+ try:
+ state.root_ctx.__exit__(None, None, None)
+ except Exception: # pragma: no cover - fail-open
+ pass
except Exception as exc: # pragma: no cover - fail-open
_debug(f"evict stale trace failed: {exc}")
+def _finalize_all_traces() -> None:
+ """End every open root span so short-lived processes export complete traces.
+
+ Gateway turns normally end their root span via ``_finish_trace`` (final
+ assistant message with no tool calls). But short-lived CLI processes —
+ kanban workers, ``hermes chat -q`` one-shots, cron jobs — can exit while
+ the last LLM call still has tool calls queued, leaving the root span
+ un-ended. Ended children DO export via the SDK's own atexit flush, so the
+ backend shows an anonymous trace (no name/session/metadata) whose
+ observations all point at a root that never arrived (observed live
+ 2026-08-08: kanban workers produced 4 such traces in one tick).
+
+ Registered with ``atexit`` AFTER the Langfuse client is constructed:
+ atexit is LIFO, so this runs BEFORE the SDK's own shutdown hook — spans
+ ended here still get flushed by the SDK's exporter.
+ """
+ with _STATE_LOCK:
+ states = list(_TRACE_STATE.items())
+ _TRACE_STATE.clear()
+ for _key, state in states:
+ try:
+ for observation in state.generations.values():
+ _end_observation(observation)
+ for observation in state.tools.values():
+ _end_observation(observation)
+ for queue in state.pending_tools_by_name.values():
+ for observation in queue:
+ _end_observation(observation)
+ for observation in state.subagents.values():
+ _end_observation(observation)
+ state.root_span.end()
+ # Exit the root observation's context manager so its generator
+ # unwinds now, while opentelemetry.trace.Span is still a real
+ # type — otherwise GC closes it during interpreter teardown and
+ # use_span's isinstance(span, Span) raises TypeError.
+ if state.root_ctx is not None:
+ try:
+ state.root_ctx.__exit__(None, None, None)
+ except Exception: # pragma: no cover - fail-open
+ pass
+ except Exception as exc: # pragma: no cover - fail-open
+ _debug(f"atexit finalize failed for {_key}: {exc}")
+ if states:
+ client = _get_langfuse()
+ if client is not None:
+ try:
+ client.flush()
+ except Exception:
+ pass
+
+
def _finish_trace(task_key: str, *, output: Any = None) -> None:
client = _get_langfuse()
if client is None:
@@ -754,11 +1092,41 @@ def _finish_trace(task_key: str, *, output: Any = None) -> None:
_end_observation(observation)
final_output = _merge_trace_output(output, state)
if final_output is not None:
- state.root_span.set_trace_io(output=final_output)
- state.root_span.update(output=final_output)
- state.root_span.end()
+ # update_trace sets TRACE-level Input/Output columns in the UI
+ # (SDK v3; set_trace_io was the pre-v3 spelling). Root observation
+ # I/O is set via update(); never let either call prevent end() —
+ # otherwise generations/tools export without a CHAIN root and the
+ # list view looks half-empty.
+ try:
+ state.root_span.update_trace(output=final_output)
+ except Exception as exc:
+ _debug(f"update_trace(output) failed: {exc}")
+ try:
+ state.root_span.update(output=final_output)
+ except Exception as exc:
+ _debug(f"root update(output) failed: {exc}")
+ try:
+ state.root_span.end()
+ except Exception as exc:
+ _debug(f"root end() failed: {exc}")
+ # Properly exit the root context manager so the generator unwinds
+ # now, while opentelemetry.trace.Span is still a real type. Without
+ # this the generator is left suspended; at interpreter teardown the
+ # GC calls .close(), which throws GeneratorExit through use_span
+ # __exit__ -> isinstance(span, Span) -- but Span has been torn down
+ # to None by then, producing the TypeError traceback on quit.
+ if state.root_ctx is not None:
+ try:
+ state.root_ctx.__exit__(None, None, None)
+ except Exception: # pragma: no cover - fail-open
+ pass
except Exception as exc: # pragma: no cover - fail-open
_debug(f"finish trace failed: {exc}")
+ # Last-chance end so an earlier unexpected error still exports the root.
+ try:
+ state.root_span.end()
+ except Exception:
+ pass
finally:
try:
client.flush()
@@ -823,6 +1191,77 @@ def on_pre_llm_call(*, task_id: str = "", session_id: str = "", platform: str =
state.last_updated_at = time.time()
+def _emit_moa_reference_generations(state: TraceState, *, client: Langfuse,
+ references: Any) -> None:
+ """Record each MoA advisor as its own generation under the turn.
+
+ MoA returns only the aggregator's response, so without this the whole
+ fan-out collapses into one generation priced at the aggregator's model.
+ Each advisor carries its own model, usage, and dollars — advisors routinely
+ run on a different provider than the aggregator, so their spend cannot be
+ 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 = {}
+ if isinstance(usage, dict):
+ if usage.get("input_tokens"):
+ usage_details["input"] = usage["input_tokens"]
+ if usage.get("output_tokens"):
+ usage_details["output"] = usage["output_tokens"]
+ if usage.get("cache_read_tokens"):
+ usage_details["cache_read_input_tokens"] = usage["cache_read_tokens"]
+ if usage.get("cache_write_tokens"):
+ usage_details["cache_creation_input_tokens"] = usage["cache_write_tokens"]
+ if usage.get("reasoning_tokens"):
+ usage_details["reasoning_tokens"] = usage["reasoning_tokens"]
+ cost_details = {}
+ cost_usd = ref.get("cost_usd")
+ if isinstance(cost_usd, (int, float)):
+ cost_details["total"] = float(cost_usd)
+
+ label = ref.get("label") or "advisor"
+ metadata = {"moa_role": "reference", "label": label}
+ for key in ("provider", "cost_status", "cost_source", "temperature"):
+ if ref.get(key) is not None:
+ metadata[key] = ref[key]
+
+ observation = _start_child_observation(
+ state,
+ client=client,
+ 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 = "",
@@ -845,18 +1284,41 @@ def on_pre_llm_request(
user_message: Any = None,
turn_id: str = "",
api_request_id: str = "",
+ request: Any = None,
+ system_prompt: Any = None,
**_: Any,
) -> None:
client = _get_langfuse()
if client is None:
return
+ # ``model`` is the agent's current attribute at hook time; the request
+ # body carries the model actually being dispatched. They can diverge
+ # (mid-session /model switch propagation, provider fallback, middleware
+ # rewrites) — prefer the wire truth for generation attribution.
+ if isinstance(request, dict):
+ body = request.get("body")
+ if isinstance(body, dict):
+ body_model = body.get("model")
+ 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=request_messages,
+ messages=messages,
+ conversation_history=conversation_history,
+ user_message=user_message,
+ system_prompt=system_prompt,
+ )
+ system_chars = 0
+ if langfuse_input and langfuse_input[0].get("role") == "system":
+ system_chars = len(str(langfuse_input[0].get("content") or ""))
task_key = _trace_key(
task_id,
@@ -888,18 +1350,23 @@ def on_pre_llm_request(
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,
+ }
+ if system_chars:
+ gen_metadata["system_prompt_chars"] = system_chars
state.generations[req_key] = _start_child_observation(
state,
client=client,
name=f"LLM call {api_call_count}",
as_type="generation",
- input_value=_serialize_messages(input_messages),
- metadata={
- "provider": provider,
- "platform": platform,
- "api_mode": api_mode,
- "base_url": base_url,
- },
+ input_value=langfuse_input,
+ metadata=gen_metadata,
model=model,
model_parameters={"api_mode": api_mode, "provider": provider},
)
@@ -912,11 +1379,18 @@ def on_post_llm_call(*, task_id: str = "", session_id: str = "", provider: 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 = _get_langfuse()
if client is None:
return
+ # The provider's response echoes the model that actually served the
+ # request. Prefer it over the agent attribute, which can be stale after
+ # a mid-session model switch or fallback.
+ if isinstance(response_model, str) and response_model:
+ model = response_model
+
task_key = _trace_key(
task_id,
session_id,
@@ -931,6 +1405,9 @@ def on_post_llm_call(*, task_id: str = "", session_id: str = "", provider: str =
if state is None or generation is None:
return
+ if moa_references:
+ _emit_moa_reference_generations(state, client=client, references=moa_references)
+
# Handle both call patterns:
# 1. post_api_request: passes usage (dict), assistant_content_chars, assistant_tool_call_count
# 2. post_llm_call: passes assistant_message (object), response (object), assistant_response (str)
@@ -938,7 +1415,7 @@ def on_post_llm_call(*, task_id: str = "", session_id: str = "", provider: str =
output = _serialize_assistant_message(assistant_message)
elif assistant_response is not None:
# post_llm_call passes assistant_response as a plain string
- output = {"content": _safe_value(assistant_response), "reasoning": None, "tool_calls": []}
+ output = {"content": _capture_content(assistant_response), "reasoning": None, "tool_calls": []}
else:
# post_api_request path — reconstruct from summary kwargs
output = {
@@ -969,53 +1446,30 @@ def on_post_llm_call(*, task_id: str = "", session_id: str = "", provider: str =
)
elif isinstance(usage, dict) and usage:
# post_api_request passes a pre-built CanonicalUsage summary dict.
- # Use Langfuse-convention key names: "input", "output", and
- # "cache_read_input_tokens" / "cache_creation_input_tokens" so the
- # dashboard sums cache tokens into the input total automatically.
_input = usage.get("input_tokens", 0)
_output = usage.get("output_tokens", 0) or usage.get("completion_tokens", 0)
_cache_read = usage.get("cache_read_tokens", 0)
_cache_write = usage.get("cache_write_tokens", 0)
_reasoning = usage.get("reasoning_tokens", 0)
- usage_details = {
- "input": _input,
- "output": _output,
- }
- if _cache_read:
- usage_details["cache_read_input_tokens"] = _cache_read
- if _cache_write:
- usage_details["cache_creation_input_tokens"] = _cache_write
- if _reasoning:
- usage_details["reasoning_tokens"] = _reasoning
- cost_details = {}
- # Estimate per-type cost from the summary if possible
try:
- from agent.usage_pricing import CanonicalUsage, estimate_usage_cost, get_pricing_entry
- from decimal import Decimal
- _ONE_M = Decimal("1000000")
+ from agent.usage_pricing import CanonicalUsage
+
_cu = CanonicalUsage(
input_tokens=_input,
output_tokens=_output,
cache_read_tokens=_cache_read,
cache_write_tokens=_cache_write,
reasoning_tokens=_reasoning,
+ request_count=usage.get("request_count", 1),
+ )
+ usage_details, cost_details = _canonical_usage_and_cost(
+ _cu,
+ provider=provider,
+ model=model,
+ base_url=base_url,
)
- entry = get_pricing_entry(model, provider=provider, base_url=base_url)
- if entry:
- if entry.input_cost_per_million is not None and _input:
- cost_details["input"] = float(Decimal(_input) * entry.input_cost_per_million / _ONE_M)
- if entry.output_cost_per_million is not None and _output:
- cost_details["output"] = float(Decimal(_output) * entry.output_cost_per_million / _ONE_M)
- if entry.cache_read_cost_per_million is not None and _cache_read:
- cost_details["cache_read_input_tokens"] = float(Decimal(_cache_read) * entry.cache_read_cost_per_million / _ONE_M)
- if entry.cache_write_cost_per_million is not None and _cache_write:
- cost_details["cache_creation_input_tokens"] = float(Decimal(_cache_write) * entry.cache_write_cost_per_million / _ONE_M)
- else:
- _cost = estimate_usage_cost(model, _cu, provider=provider, base_url=base_url, api_key="")
- if _cost.amount_usd is not None:
- cost_details["total"] = float(_cost.amount_usd)
except Exception:
- pass
+ usage_details, cost_details = {}, {}
else:
usage_details, cost_details = {}, {}
@@ -1062,7 +1516,7 @@ def on_pre_tool_call(*, tool_name: str = "", args: Any = None, task_id: str = ""
client=client,
name=f"Tool: {tool_name}",
as_type="tool",
- input_value=_safe_value(args),
+ input_value=_capture_content(args),
metadata={"tool_name": tool_name, "tool_call_id": tool_call_id},
)
if tool_call_id:
@@ -1098,12 +1552,15 @@ def on_post_tool_call(*, tool_name: str = "", args: Any = None, result: Any = No
if observation is None:
return
- if isinstance(result, str):
- result_value = _maybe_parse_json_string(result)
+ if _capture_mode() == "metadata":
+ safe_result_value = _describe_content(result)
else:
- result_value = result
- result_value = _normalize_payload(result_value, tool_name=tool_name, args=args)
- safe_result_value = _safe_value(result_value, parse_json_strings=True)
+ if isinstance(result, str):
+ result_value = _maybe_parse_json_string(result)
+ else:
+ result_value = result
+ result_value = _normalize_payload(result_value, tool_name=tool_name, args=args)
+ safe_result_value = _safe_value(result_value, parse_json_strings=True)
# Backfill so the generation's tool_call record carries the result alongside arguments.
if tool_call_id:
@@ -1121,7 +1578,207 @@ def on_post_tool_call(*, tool_name: str = "", args: Any = None, result: Any = No
_end_observation(
observation,
output=safe_result_value,
- metadata={"tool_name": tool_name, "args": _safe_value(args, parse_json_strings=True)},
+ metadata={"tool_name": tool_name, "args": _capture_content(args, parse_json_strings=True)},
+ )
+
+
+def on_api_request_error(*, task_id: str = "", session_id: str = "", provider: str = "",
+ model: str = "", api_mode: 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 the open generation for a failed API request.
+
+ Without this, a failed request leaves its generation open until trace
+ eviction — the failure is invisible in Langfuse and the turn appears
+ to hang. Marks the generation with ERROR level and the error summary.
+ If the request was not retryable (or retries are exhausted), the turn
+ is finished too, since the agent loop is about to unwind.
+ """
+ client = _get_langfuse()
+ if client is None:
+ return
+
+ task_key = _trace_key(
+ task_id,
+ session_id,
+ turn_id=turn_id,
+ api_request_id=api_request_id,
+ )
+ req_key = _request_key(api_call_count)
+
+ with _STATE_LOCK:
+ state = _TRACE_STATE.get(task_key)
+ generation = state.generations.pop(req_key, None) if state else None
+ if state is None:
+ return
+
+ error_type = ""
+ error_message = ""
+ if isinstance(error, dict):
+ error_type = str(error.get("type") or "")
+ error_message = str(error.get("message") or "")
+
+ error_metadata: Dict[str, Any] = {
+ "error": True,
+ "error_type": error_type,
+ # Error messages can embed request fragments (URLs w/ keys, prompt
+ # echoes) — run them through the capture pipeline like content.
+ "error_message": _capture_content(error_message),
+ }
+ if status_code is not None:
+ error_metadata["status_code"] = status_code
+ if retry_count is not None:
+ error_metadata["retry_count"] = retry_count
+ if max_retries is not None:
+ error_metadata["max_retries"] = max_retries
+ if retryable is not None:
+ error_metadata["retryable"] = retryable
+ if reason:
+ error_metadata["reason"] = str(reason)
+ if api_duration and api_duration > 0:
+ error_metadata["api_duration_s"] = round(api_duration, 3)
+
+ if generation is not None:
+ try:
+ generation.update(
+ level="ERROR",
+ status_message=(error_type or "api_request_error")[:200],
+ )
+ except Exception as exc: # pragma: no cover - fail-open
+ _debug(f"error-level update failed: {exc}")
+ _end_observation(generation, metadata=error_metadata)
+
+ # A retryable failure will be 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:
+ """True session-end boundary: close any traces still open and flush.
+
+ A turn that ended on a tool-only or empty final response never reaches
+ ``_finish_trace``; without this hook its root span dangles until state
+ eviction and queued events can be lost on process exit.
+ """
+ # Only act on an already-constructed client — do NOT lazily initialize
+ # one at finalize time; if init never happened there are no traces.
+ client = _LANGFUSE_CLIENT
+ if client is None or client is _INIT_FAILED or not isinstance(client, object) or not hasattr(client, "flush"):
+ return
+
+ # Close every trace belonging to this session (or all, when no
+ # session_id is provided — process-level finalization). Trace keys carry
+ # the session as either "session:<id>" (no task) or "task:<id>" (gateway
+ # sets task_id == session_id), plus the legacy bare-task_id shape — match
+ # on the id in any segment.
+ if session_id:
+ fragments = (f"session:{session_id}", f"task:{session_id}")
+ with _STATE_LOCK:
+ keys = [
+ k for k in _TRACE_STATE
+ if k == session_id or any(f in k for f in fragments)
+ ]
+ else:
+ with _STATE_LOCK:
+ keys = list(_TRACE_STATE)
+
+ for key in keys:
+ _finish_trace(key)
+
+ try:
+ client.flush()
+ except Exception as exc: # pragma: no cover - fail-open
+ _debug(f"finalize flush failed: {exc}")
+
+ # Explicitly shut down the Langfuse client — but only at a true
+ # process-exit boundary. on_session_finalize also fires on /new, /reset
+ # (reason "session_boundary"/"new_session") and gateway session expiry
+ # ("session_expired"), where the process lives on and the cached client
+ # must keep exporting for subsequent sessions. The shutdown matters at
+ # exit because the Langfuse SDK's own atexit handler runs during
+ # interpreter finalization — by then module globals (notably
+ # opentelemetry.trace.Span) may already be torn down to None, and the
+ # SDK's span-finalization path (use_span -> isinstance(span, Span))
+ # raises "TypeError: isinstance() arg 2 must be a type" which surfaces
+ # as a noisy "Exception ignored in: <generator>" traceback on quit.
+ # Calling shutdown() here flushes pending spans and joins the background
+ # export threads while all modules are intact; the SDK's atexit handler
+ # then becomes a no-op.
+ if reason == "shutdown":
+ shutdown = getattr(client, "shutdown", None)
+ if callable(shutdown):
+ try:
+ shutdown()
+ except Exception as exc: # pragma: no cover - fail-open
+ _debug(f"langfuse shutdown failed: {exc}")
+
+
+def on_subagent_start(*, parent_session_id: Any = None, 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:
+ key = _state_for_turn(parent_turn_id)
+ state = _TRACE_STATE.get(key) if key else None
+ if state is None:
+ return
+ metadata = {
+ "child_session_id": child_session_id,
+ "child_subagent_id": child_subagent_id,
+ "child_role": child_role,
+ }
+ if parent_subagent_id:
+ metadata["parent_subagent_id"] = parent_subagent_id
+ state.subagents[str(child_session_id)] = _start_child_observation(
+ state,
+ client=client,
+ name=f"Subagent: {child_role or 'delegate'}",
+ as_type="span",
+ input_value=_capture_content(child_goal),
+ metadata=metadata,
+ )
+
+
+def on_subagent_stop(*, parent_session_id: Any = None, 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:
+ key = _state_for_turn(parent_turn_id)
+ state = _TRACE_STATE.get(key) if key else None
+ if state is None:
+ return
+ observation = state.subagents.pop(str(child_session_id), None)
+
+ if observation is None:
+ return
+
+ metadata: Dict[str, Any] = {"child_role": child_role}
+ if child_status:
+ metadata["status"] = child_status
+ if duration_ms:
+ metadata["duration_ms"] = duration_ms
+ if isinstance(tool_call_history, list):
+ metadata["tool_call_count"] = len(tool_call_history)
+ metadata["tool_calls"] = _capture_content(tool_call_history)
+ _end_observation(
+ observation,
+ output=_capture_content(child_summary),
+ metadata=metadata,
)
@@ -1131,7 +1788,12 @@ def register(ctx) -> None:
# call (preferred); pre_llm_call / post_llm_call fire once per turn.
ctx.register_hook("pre_api_request", on_pre_llm_request)
ctx.register_hook("post_api_request", on_post_llm_call)
+ ctx.register_hook("api_request_error", on_api_request_error)
ctx.register_hook("pre_llm_call", on_pre_llm_call)
ctx.register_hook("post_llm_call", on_post_llm_call)
ctx.register_hook("pre_tool_call", on_pre_tool_call)
ctx.register_hook("post_tool_call", on_post_tool_call)
+ ctx.register_hook("on_session_finalize", on_session_finalize)
+ ctx.register_hook("on_session_end", on_session_finalize)
+ ctx.register_hook("subagent_start", on_subagent_start)
+ ctx.register_hook("subagent_stop", on_subagent_stop)
diff --git a/plugins/observability/langfuse/plugin.yaml b/plugins/observability/langfuse/plugin.yaml
index 18f1c6245d3..e1244e610aa 100644
--- a/plugins/observability/langfuse/plugin.yaml
+++ b/plugins/observability/langfuse/plugin.yaml
@@ -8,7 +8,12 @@ requires_env:
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_stop
diff --git a/tests/agent/test_moa_observability_bridge.py b/tests/agent/test_moa_observability_bridge.py
new file mode 100644
index 00000000000..f0add6e15b9
--- /dev/null
+++ b/tests/agent/test_moa_observability_bridge.py
@@ -0,0 +1,137 @@
+"""Per-advisor MoA metrics crossing the plugin-hook boundary.
+
+MoA runs N advisor models before its aggregator and returns only the
+aggregator's response, so an observability plugin sees one generation for the
+whole fan-out. ``_RefAccounting`` already computes each advisor's usage and
+dollars — advisors routinely run on a different provider than the aggregator,
+so their spend cannot be priced at the aggregator's rate. These tests pin the
+bridge that carries it out: the renderer, the non-consuming accessor, and the
+conversation-loop helper that reads it.
+"""
+
+from agent.moa_loop import _RefAccounting
+from agent.moa_trace import _slot_trace, slot_metrics
+from agent.usage_pricing import CanonicalUsage
+
+
+def _acct():
+ return _RefAccounting(
+ CanonicalUsage(input_tokens=100, output_tokens=50, reasoning_tokens=7),
+ 0.0042,
+ "ok",
+ "pricing_table",
+ messages=[{"role": "user", "content": "x" * 10000}],
+ output="advice",
+ model="claude-sonnet-4-6",
+ provider="anthropic",
+ temperature=0.7,
+ )
+
+
+class TestSlotMetrics:
+ def test_carries_model_provider_usage_and_cost(self):
+ m = slot_metrics(_acct(), "anthropic:claude-sonnet-4-6")
+
+ assert m["label"] == "anthropic:claude-sonnet-4-6"
+ assert m["model"] == "claude-sonnet-4-6"
+ assert m["provider"] == "anthropic"
+ assert m["cost_usd"] == 0.0042
+ assert m["cost_status"] == "ok"
+ assert m["cost_source"] == "pricing_table"
+ assert m["usage"]["input_tokens"] == 100
+ assert m["usage"]["output_tokens"] == 50
+ assert m["usage"]["reasoning_tokens"] == 7
+
+ def test_drops_input_messages(self):
+ # input_messages is the bulk of a trace record and would cross the hook
+ # boundary for every advisor on every turn.
+ assert "input_messages" in _slot_trace(_acct(), "label")
+ assert "input_messages" not in slot_metrics(_acct(), "label")
+
+ def test_output_override_wins(self):
+ # The privacy-redacted advisor text lives alongside the accounting, not
+ # on it, so the caller supplies the output.
+ m = slot_metrics(_acct(), "label", output="[redacted]")
+ assert m["output"] == "[redacted]"
+
+ def test_missing_accounting_does_not_raise(self):
+ m = slot_metrics(None, "label")
+ assert m["label"] == "label"
+ assert m["usage"] == {}
+
+
+class TestLastReferenceMetricsAccessor:
+ def _client(self):
+ from agent.moa_loop import MoAClient
+
+ return MoAClient("closed")
+
+ def test_defaults_to_none_off_the_fanout_path(self):
+ assert self._client().last_reference_metrics() is None
+
+ def test_read_does_not_consume(self):
+ client = self._client()
+ payload = [slot_metrics(_acct(), "label")]
+ client.chat.completions._last_reference_metrics = payload
+
+ # post_api_request fires on a different branch than
+ # consume_and_save_trace, so a consuming read would race it.
+ assert client.last_reference_metrics() is payload
+ assert client.last_reference_metrics() is payload
+
+ def test_read_does_not_disturb_usage_accounting(self):
+ client = self._client()
+ client.chat.completions._last_reference_metrics = [slot_metrics(_acct(), "label")]
+ client.chat.completions._pending_reference_usage = CanonicalUsage(input_tokens=5)
+ client.chat.completions._pending_reference_cost = 0.05
+
+ client.last_reference_metrics()
+
+ usage, cost = client.consume_reference_usage()
+ assert usage.input_tokens == 5
+ assert cost == 0.05
+
+
+class TestConversationLoopHelper:
+ def test_returns_none_for_a_non_moa_client(self):
+ from agent.conversation_loop import _moa_reference_metrics_for_hook
+
+ class _Agent:
+ client = object()
+
+ assert _moa_reference_metrics_for_hook(_Agent()) is None
+
+ def test_returns_none_when_there_is_no_client(self):
+ from agent.conversation_loop import _moa_reference_metrics_for_hook
+
+ class _Agent:
+ client = None
+
+ assert _moa_reference_metrics_for_hook(_Agent()) is None
+
+ def test_returns_metrics_for_a_moa_client(self):
+ from agent.conversation_loop import _moa_reference_metrics_for_hook
+
+ payload = [slot_metrics(_acct(), "label")]
+
+ class _Client:
+ def last_reference_metrics(self):
+ return payload
+
+ class _Agent:
+ client = _Client()
+
+ assert _moa_reference_metrics_for_hook(_Agent()) is payload
+
+ def test_a_raising_accessor_is_swallowed(self):
+ from agent.conversation_loop import _moa_reference_metrics_for_hook
+
+ class _Client:
+ def last_reference_metrics(self):
+ raise RuntimeError("boom")
+
+ class _Agent:
+ client = _Client()
+
+ # Observability must never break a turn.
+ assert _moa_reference_metrics_for_hook(_Agent()) is None
diff --git a/tests/plugins/test_langfuse_plugin.py b/tests/plugins/test_langfuse_plugin.py
index d18724b6607..c80f26bc800 100644
--- a/tests/plugins/test_langfuse_plugin.py
+++ b/tests/plugins/test_langfuse_plugin.py
@@ -4,7 +4,9 @@ from __future__ import annotations
import importlib
import logging
import sys
+from decimal import Decimal
from pathlib import Path
+from types import SimpleNamespace
import pytest
@@ -25,11 +27,13 @@ class TestManifest:
data = yaml.safe_load((PLUGIN_DIR / "plugin.yaml").read_text())
assert data["name"] == "langfuse"
assert data["version"]
- # All six hooks the plugin implements.
+ # All eleven hooks the plugin implements.
assert set(data["hooks"]) == {
- "pre_api_request", "post_api_request",
+ "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_stop",
}
# Required env vars are the user-facing HERMES_ prefixed keys.
assert "HERMES_LANGFUSE_PUBLIC_KEY" in data["requires_env"]
@@ -361,6 +365,60 @@ class TestTurnTraceIsolation:
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).
@@ -529,6 +587,89 @@ class TestRequestMessageCoercion:
) == [{"role": "user", "content": "h"}]
assert mod._coerce_request_messages(user_message="u") == [{"role": "user", "content": "u"}]
+ def test_messages_for_langfuse_includes_anthropic_system_param(self):
+ sys.modules.pop("plugins.observability.langfuse", None)
+ mod = importlib.import_module("plugins.observability.langfuse")
+
+ out = mod._messages_for_langfuse_input(
+ request_messages=[{"role": "user", "content": "hi"}],
+ system_prompt="You are Hermes.",
+ )
+ assert out[0]["role"] == "system"
+ assert out[0]["content"] == "You are Hermes."
+ assert out[1]["role"] == "user"
+
+ def test_messages_for_langfuse_skips_duplicate_system(self):
+ sys.modules.pop("plugins.observability.langfuse", None)
+ mod = importlib.import_module("plugins.observability.langfuse")
+
+ out = mod._messages_for_langfuse_input(
+ request_messages=[
+ {"role": "system", "content": "already here"},
+ {"role": "user", "content": "hi"},
+ ],
+ system_prompt="ignored when messages include system",
+ )
+ assert out[0]["role"] == "system"
+ assert out[0]["content"] == "already here"
+ assert out[1]["role"] == "user"
+
+
+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):
@@ -779,3 +920,1453 @@ class TestUsageFromSanitizedResponse:
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="",
+ )
+
+ assert cost_details["total"] == pytest.approx(0.0111)
+ 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-abcdefghijklmnop1234 done",
+ "anthropic": "key sk-ant-abcdefgh1234 x",
+ "github": "tok ghp_" + "a" * 36,
+ "aws": "AKIA" + "A" * 16,
+ "langfuse": "pk-lf-12345678-abcd",
+ "bearer": "Authorization: Bearer abc123def456ghi",
+ "assignment": 'api_key="supersecretvalue"',
+ }
+ for name, text in samples.items():
+ out = mod._capture_content(text)
+ assert "REDACTED" in 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 "REDACTED" in out
+
+ 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
+
+ def test_capture_mode_recorded_in_trace_metadata(self, monkeypatch):
+ mod = self._fresh_plugin()
+ monkeypatch.setenv("HERMES_LANGFUSE_CAPTURE", "metadata")
+ seen = {}
+
+ 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 "t1"
+ def start_as_current_observation(self, **kw):
+ seen.update(kw)
+ return _RootCM()
+
+ state = mod._start_root_trace(
+ "k", task_id="t", session_id="s", platform="cli", provider="p",
+ model="m", api_mode="chat", messages=[{"role": "user", "content": "hi"}],
+ client=_Client(),
+ )
+ assert seen["metadata"]["capture_mode"] == "metadata"
+ assert state is not None
+
+
+# ---------------------------------------------------------------------------
+# 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 = [u["metadata"] for u in gen.updates if "metadata" in u][0]
+ 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
+
+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_string_system_prompt_prepended(self, monkeypatch):
+ mod = self._make_mod()
+ captured = self._capture_generation(mod, monkeypatch)
+ self._fire(
+ mod,
+ request_messages=[{"role": "user", "content": "hi"}],
+ system_prompt="You are Hermes.",
+ )
+ assert captured["input"][0]["role"] == "system"
+ assert captured["input"][0]["content"] == "You are Hermes."
+ assert captured["input"][1]["role"] == "user"
+
+ 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_no_duplicate_when_messages_already_carry_system(self, monkeypatch):
+ """chat_completions keeps system in messages[0]; forwarding
+ system_prompt as well must not produce two system entries."""
+ mod = self._make_mod()
+ captured = self._capture_generation(mod, monkeypatch)
+ self._fire(
+ mod,
+ request_messages=[
+ {"role": "system", "content": "You are Hermes."},
+ {"role": "user", "content": "hi"},
+ ],
+ system_prompt="You are Hermes.",
+ )
+ roles = [m["role"] for m in captured["input"]]
+ assert roles.count("system") == 1
+ assert roles[0] == "system"
+
+ 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"
+ # window (12) + prepended system
+ assert len(captured["input"]) == 13
+
+ def test_metadata_records_chars(self, monkeypatch):
+ mod = self._make_mod()
+ captured = self._capture_generation(mod, monkeypatch)
+ self._fire(
+ mod,
+ request_messages=[{"role": "user", "content": "hi"}],
+ system_prompt="You are Hermes.",
+ )
+ assert captured["metadata"]["system_prompt_chars"] == len("You are Hermes.")
+
+
+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 == {}