JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
refactor(swarm): move single-agent observability into the openjiuwen harness
alan_cheng821980b9752b
diff --git a/jiuwenswarm/agents/harness/agent_observability.py b/jiuwenswarm/agents/harness/agent_observability.pyindex cf6729be71..c877a5f2fb 100644--- a/jiuwenswarm/agents/harness/agent_observability.py+++ b/jiuwenswarm/agents/harness/agent_observability.py@@ -1,206 +1,50 @@# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.-"""Single-agent / coding-agent observability lifecycle.+"""Config-gated lifecycle for single-agent / coding-agent observability.-This is the non-team counterpart of the team observability adapter in-``jiuwenswarm.agents.harness.team.team_manager`` (``sync_team_observability``-/ ``shutdown_team_observability``). It is kept in a **separate file with its-own state and config section** on purpose, so the existing team scenario is-not affected.+The non-team counterpart of ``sync_team_observability`` /+``shutdown_team_observability`` in+``jiuwenswarm.agents.harness.team.team_manager``, and symmetric with it: this+module only reads this platform's config and toggles the runtime, while the+tracing mechanics — run root span, the session-keyed fallback that keeps it+reachable from supervisor tasks, agent-tier rail wiring and the sub-agent+dispatch hook — live in the SDK under ``openjiuwen.harness.observability``.-Once ``openjiuwen.agent_teams.observability.init_observability`` has run, the-generic ``OtelCallbackHandler`` is registered against the **global**-``Runner.callback_framework``. LLM and tool events are emitted from the shared-foundation layer (``core/foundation/llm/model.py`` /-``core/foundation/tool/base.py``) for *every* agent, team or not — so simply-ensuring the provider is initialized before ``Runner.run_agent_streaming`` /-``Runner.run_agent`` gives single-agent and coding-agent runs automatic-LLM/tool span tracing. The team-only ``OtelTeamMonitorHandler`` (team/member/-task/message spans) is intentionally never attached here.+It is kept in a **separate file with its own state and config section** on+purpose, so the existing team scenario is not affected.Shared-provider caveat (important):- OpenTelemetry allows exactly ONE global ``TracerProvider`` per process,- and ``init_observability`` is a no-op if already initialized. In a process- where BOTH team and agent observability are enabled, whichever runs first- wins; the other silently reuses it (its exporter/endpoint/service_name are- ignored). Provider demands are coordinated by ``observability_runtime`` so- agent shutdown never tears down a provider the team subsystem depends on.+ OpenTelemetry allows exactly ONE global ``TracerProvider`` per process, and+ initialization is a no-op if one already exists. In a process where BOTH+ team and agent observability are enabled, whichever runs first wins; the+ other silently reuses it (its exporter/endpoint/service_name are ignored).+ Provider demands are coordinated inside the SDK, so agent shutdown never+ tears down a provider the team subsystem depends on."""from __future__ import annotationsimport logging-from dataclasses import dataclass, field-from threading import Event, Lock-from typing import TYPE_CHECKING, Any-from openjiuwen.harness.rails.base import DeepAgentRail--from jiuwenswarm.common.config import get_config, get_skill_evolution_enabled-from jiuwenswarm.common.utils import get_user_workspace_dir-from jiuwenswarm.agents.harness.observability_runtime import (- acquire_observability_demand,- build_observability_config,- release_observability_demand,+from openjiuwen.harness.observability import (+ acquire_observability,+ release_observability,)-if TYPE_CHECKING:- from jiuwenswarm.telemetry.request_context import (- TraceBindingHandle,- TraceBindingRegistry,- )- from jiuwenswarm.telemetry.runtime import TelemetryRuntime+from jiuwenswarm.agents.harness.observability_runtime import build_observability_config+from jiuwenswarm.common.config import (+ get_config,+ get_skill_evolution_enabled,+)+from jiuwenswarm.common.utils import get_user_workspace_dirlogger = logging.getLogger(__name__)-# ── Single-Agent Observability ─────────────────────────────────# Tracks whether observability is currently active so we can detect config# toggles (enabled -> disabled or vice-versa) and init / shutdown accordingly# on each single-agent request._agent_observability_active: bool = False-# get_team_span bindings already wrapped by _install_team_span_registry_fallback,-# keyed on the wrapper itself (it becomes the next lookup's orig) so repeat-# calls stay idempotent without stamping an attribute on the function object.-_team_span_patched: set[Any] = set()---class AgentTraceBindingRail(DeepAgentRail):- """Restore the request root inside the long-lived agent supervisor task."""-- @staticmethod- def _bind(ctx: Any) -> None:- session = getattr(ctx, "session", None)- getter = getattr(session, "get_session_id", None)- if not callable(getter):- return- try:- session_id = str(getter() or "")- binding = _get_unified_runtime().trace_bindings.resolve_session(session_id)- if binding is None:- return- root_span = binding.root_span- is_recording = getattr(root_span, "is_recording", None)- if callable(is_recording) and not is_recording():- return- from openjiuwen.agent_teams.observability.span_context import (- set_team_span,- )- from openjiuwen.extensions.observability.span_context import (- set_current_session_id,- set_root_span,- )-- set_team_span(root_span, team_name="single-agent")- set_root_span(root_span, session_id=session_id)- set_current_session_id(session_id)- except Exception as exc:- logger.debug("[AgentObservability] trace binding rail skipped: %s", exc)-- async def before_task_iteration(self, ctx: Any) -> None:- self._bind(ctx)-- async def before_invoke(self, ctx: Any) -> None:- self._bind(ctx)---def _get_unified_runtime() -> TelemetryRuntime:- from jiuwenswarm.telemetry import get_telemetry_runtime-- return get_telemetry_runtime()---def _install_team_span_registry_fallback() -> None:- """Patch AgentCore consumers to resolve cross-task roots by session.-- Each SDK consumer imports a root lookup directly, so each has its own- binding that must be rebound separately:- * extension callback_handler — creates llm/tool spans (parent lookup).- * rail (ObservabilityRail) — creates the agent.<type>.invoke spans; it- *returns early* when get_team_span() is None, which is why the agent-tier- spans (incl. sub-agent's agent.<type>.invoke) were missing.- * monitor_handler — team-only (harmless to patch; team_span is ContextVar-visible- there so the fallback never triggers).- Team mode is unaffected: its team_span is ContextVar-visible, so the original- lookup returns non-None and the fallback never triggers. The centralized- registry isolates concurrent sessions and uses compare-and-remove cleanup.- Best-effort, idempotent, never raises.- """- import importlib-- for mod_path, getter_name in (- # The current AgentCore runtime creates generic LLM/tool spans through- # this extension-level root accessor. The historical Team consumers- # below are kept for compatibility with older AgentCore revisions.- ("openjiuwen.extensions.observability.callback_handler", "get_root_span"),- ("openjiuwen.agent_teams.observability.callback_handler", "get_team_span"),- ("openjiuwen.agent_teams.observability.rail", "get_team_span"),- ("openjiuwen.agent_teams.observability.monitor_handler", "get_team_span"),- ):- try:- mod = importlib.import_module(mod_path)- except Exception as exc:- logger.debug(- "[AgentObservability] skip team-span fallback patch for %s: %s",- mod_path,- exc,- )- continue- orig = getattr(mod, getter_name, None)- if orig is None or orig in _team_span_patched:- continue-- def _get_span_with_registry(*args: Any, _orig=orig, **kwargs: Any) -> Any:- try:- from openjiuwen.agent_teams.context import get_session_id-- session_id = str(get_session_id() or "")- if not session_id:- return _orig(*args, **kwargs)- binding = _get_unified_runtime().trace_bindings.resolve_session(- session_id- )- if binding is None:- return _orig(*args, **kwargs)- root_span = binding.root_span- # Do not accept AgentCore's single-live-root fallback when the- # long-lived supervisor task belongs to a different session.- # In the expected session, retaining the original result keeps- # ordinary Team mode untouched.- span = _orig(*args, **kwargs)- if span is root_span:- return span- # The single-agent supervisor task is created before any- # request, so it cannot inherit the request ContextVar. Cache- # the registry fallback in this task after AGENT_*_INPUT; the- # later LLM/tool callbacks can then parent spans without a- # process-global current-request shortcut.- from openjiuwen.agent_teams.observability.span_context import (- set_team_span,- )- from openjiuwen.extensions.observability.span_context import (- set_current_session_id,- set_root_span,- )-- set_team_span(root_span, team_name="single-agent")- set_root_span(root_span, session_id=session_id)- set_current_session_id(session_id)- return root_span- except Exception as exc:- logger.debug("[AgentObservability] session root lookup failed: %s", exc)- return _orig(*args, **kwargs)-- _team_span_patched.add(_get_span_with_registry)- setattr(mod, getter_name, _get_span_with_registry)---_install_team_span_registry_fallback()-# True only when THIS module called ``init_observability()`` and therefore owns-# the shared global TracerProvider. When the team subsystem (or a prior run)-# already initialized it, this is False and shutdown must leave it intact.-_agent_owns_provider: bool = False-_runtime_managed_agent_observability: bool = False# Sticky flag: once any single-agent request has force-enabled observability# (e.g. a ``/debug`` run with ``debug_trace.<mode>.otel_enabled``), we never# auto-teardown the provider for the rest of the process. OTel allows only one@@ -218,7 +62,7 @@ def sync_agent_observability(*, force: bool = False) -> None:that hot-reloading the ``agent_observability.enabled`` flag takes effectimmediately:- * disabled -> enabled : ``init_observability()`` (or reuse if already up)+ * disabled -> enabled : acquire the provider (or reuse if already up)* enabled -> disabled : ``shutdown_agent_observability()``* unchanged : no-op@@ -232,38 +76,7 @@ def sync_agent_observability(*, force: bool = False) -> None:requests; the normal config hot-reload teardown is unchanged when evolutionis disabled."""- global _agent_observability_active, _agent_owns_provider- global _force_ever_enabled, _runtime_managed_agent_observability-- try:- unified_active = bool(_get_unified_runtime().is_unified_active())- except Exception as exc:- logger.debug("[AgentObservability] unified runtime lookup failed: %s", exc)- unified_active = False- if unified_active:- _agent_observability_active = True- _agent_owns_provider = False- _runtime_managed_agent_observability = True- # Unified telemetry owns the TracerProvider but historically omitted- # TrajectorySpanProcessor; attach it so SkillEvolutionRail can drain.- try:- from jiuwenswarm.agents.harness.observability_runtime import (- ensure_trajectory_span_processor_attached,- )-- ensure_trajectory_span_processor_attached()- except Exception as exc:- logger.warning(- "[AgentObservability] failed to attach trajectory processor "- "on unified path: %s",- exc,- )- return- if force:- _force_ever_enabled = True- if _runtime_managed_agent_observability:- _agent_observability_active = False- _runtime_managed_agent_observability = False+ global _agent_observability_active, _force_ever_enabledconfig = get_config()cfg = config.get("agent_observability", {}) or {}@@ -274,9 +87,11 @@ def sync_agent_observability(*, force: bool = False) -> None:or forceor _force_ever_enabled)+ if force:+ _force_ever_enabled = Trueif not want_enabled:- if _agent_observability_active and not _force_ever_enabled:+ if _agent_observability_active:shutdown_agent_observability()return@@ -287,13 +102,9 @@ def sync_agent_observability(*, force: bool = False) -> None:service_name="jiuwenswarm-agent",traces_dir=traces_dir,)- provider_existed = acquire_observability_demand(- "agent",- observability_config=obs_cfg,- )+ provider_existed = acquire_observability(obs_cfg)was_active = _agent_observability_active_agent_observability_active = True- _agent_owns_provider = not provider_existedif not was_active:if provider_existed:logger.info(@@ -314,7 +125,6 @@ def sync_agent_observability(*, force: bool = False) -> None:)except Exception as exc:_agent_observability_active = False- _agent_owns_provider = Falseif evolution_requested:raise RuntimeError("Agent evolution observability initialization failed"@@ -324,303 +134,12 @@ def sync_agent_observability(*, force: bool = False) -> None:def shutdown_agent_observability() -> None:"""Shutdown single-agent observability (on disable or process exit)."""- global _agent_observability_active, _agent_owns_provider- global _runtime_managed_agent_observability+ global _agent_observability_activeif not _agent_observability_active:return-- if _runtime_managed_agent_observability:- _agent_observability_active = False- _agent_owns_provider = False- _runtime_managed_agent_observability = False- return-try:- release_observability_demand("agent")+ release_observability()_agent_observability_active = False- _agent_owns_provider = Falselogger.info("[AgentObservability] disabled")except Exception as exc:logger.warning("[AgentObservability] shutdown failed: %s", exc)---# ── Per-run root span ───────────────────────────────────────────-# openjiuwen's OtelCallbackHandler skips LLM/tool span creation when no parent-# span exists (``get_team_span`` / ``get_current_agent_span`` both None — see-# callback_handler._get_parent_context_for_llm_tool). Single-agent runs set-# neither, so without a root span zero spans are produced even after a clean-# ``init_observability``. These helpers open a root span and register it via-# ``set_team_span`` — the exact mechanism team mode uses internally-# (team_runner._maybe_attach_observability → get_or_create_team_span). LLM/tool-# spans then nest under it and are exported.-#-# Usage (must be paired, in the same coroutine so the ContextVar propagates-# into the runner's LLM calls):-# handle = open_agent_run_span(session_id=sid)-# try:-# ... Runner.run_agent_streaming / Runner.run_agent ...-# finally:-# close_agent_run_span(handle)-@dataclass(frozen=True)-class AgentRunSpanHandle:- """Root span plus its compare-and-remove registry ownership."""-- root_span: Any- binding: TraceBindingHandle | None- trace_bindings: TraceBindingRegistry | None- unified: bool- _close_lock: Lock = field(default_factory=Lock, repr=False, compare=False)- _closed: Event = field(default_factory=Event, repr=False, compare=False)-- def get_span_context(self) -> Any:- """Preserve the legacy opaque handle's span-context convenience."""- return self.root_span.get_span_context()-- def claim_close(self) -> bool:- """Atomically claim the one allowed close for this root span."""- with self._close_lock:- if self._closed.is_set():- return False- self._closed.set()- return True---def _build_run_span_name(*, mode: str, session_id: str) -> str:- """Build a hierarchical OTel span name: ``agent.<mode>.<session_id>``.-- ``mode`` is the JiuwenSwarm request mode, shaped ``<category>.<submode>``- (e.g. ``agent.plan`` / ``agent.fast`` / ``code.normal`` / ``code.plan``),- so it yields the hierarchy directly:-- agent.plan -> agent.agent.plan.<session_id>- code.normal -> agent.code.normal.<session_id>-- Falls back gracefully when either component is empty.- """- m = (mode or "").strip()- sid = (session_id or "").strip()- if not m:- return f"agent.run.{sid}" if sid else "agent.run"- if not sid:- return f"agent.{m}.run"- return f"agent.{m}.{sid}"---def open_agent_run_span(- *,- session_id: str = "",- request_id: str = "",- channel_id: str = "",- mode: str = "",-) -> AgentRunSpanHandle | None:- """Open a root team span around a single-agent run.-- Returns an opaque handle to pass to :func:`close_agent_run_span`, or- ``None`` when observability is not initialized (in which case closing is- a no-op).- """- span: Any | None = None- try:- from opentelemetry.trace import SpanKind-- from openjiuwen.extensions.observability.setup import get_tracer, is_initialized- from openjiuwen.extensions.observability.semconv import LANGFUSE_SESSION_ID- from openjiuwen.agent_teams.observability.span_context import set_team_span- from jiuwenswarm.extensions.identity_provider import IdentityStore- from jiuwenswarm.telemetry.attributes import (- APP_ID,- DOMAIN_ID,- GEN_AI_CONVERSATION_ID,- JIUWENCLAW_APP_ID,- JIUWENCLAW_CHANNEL_ID,- JIUWENCLAW_DOMAIN_ID,- JIUWENCLAW_REQUEST_ID,- JIUWENCLAW_SESSION_ID,- JIUWENCLAW_USER_ID,- USER_ID,- )-- runtime = _get_unified_runtime()- unified = bool(runtime.is_unified_active())- if unified:- provider = runtime.tracer_provider- if provider is None:- return None- tracer = provider.get_tracer("jiuwenswarm.agent")- else:- if not is_initialized() or not _agent_observability_active:- return None- tracer = get_tracer("jiuwenswarm.agent")-- name = _build_run_span_name(mode=mode, session_id=session_id)- span = tracer.start_span(name=name, kind=SpanKind.SERVER)- try:- identity = IdentityStore.get_identity()- except Exception:- identity = None- attributes = {- LANGFUSE_SESSION_ID: session_id or "",- GEN_AI_CONVERSATION_ID: session_id or "",- JIUWENCLAW_SESSION_ID: session_id or "",- JIUWENCLAW_REQUEST_ID: request_id or "",- JIUWENCLAW_CHANNEL_ID: channel_id or "",- "jiuwenswarm.mode": mode or "",- }- for primary, alias, value in (- (USER_ID, JIUWENCLAW_USER_ID, getattr(identity, "user_id", None)),- (DOMAIN_ID, JIUWENCLAW_DOMAIN_ID, getattr(identity, "domain_id", None)),- (APP_ID, JIUWENCLAW_APP_ID, getattr(identity, "app_id", None)),- ):- if value not in (None, ""):- attributes[primary] = value- attributes[alias] = value- for key, value in attributes.items():- try:- span.set_attribute(key, value)- except (TypeError, ValueError) as exc:- logger.debug(- "[AgentObservability] root attribute rejected: key=%s error=%s",- key,- exc,- )- # Register as the team span so OtelCallbackHandler's parent lookup- # (get_team_span fallback) finds it for LLM/tool span creation.- set_team_span(span, team_name="single-agent")- from openjiuwen.extensions.observability.span_context import (- set_current_session_id,- set_root_span,- )-- set_root_span(span, session_id=session_id)- set_current_session_id(session_id)- trace_bindings = runtime.trace_bindings- try:- binding = trace_bindings.bind(session_id, request_id, span)- except Exception as exc:- logger.warning("[AgentObservability] root binding failed: %s", exc)- binding = None- span_registry = runtime.span_registry if unified else None- if span_registry is not None:- try:- context = span.get_span_context()- span_registry.bind_trace_attributes(context.trace_id, attributes)- except Exception as exc:- logger.debug(- "[AgentObservability] trace attribute binding failed: %s", exc- )- logger.info("[AgentObservability] root span opened: name=%s", name)- return AgentRunSpanHandle(- root_span=span,- binding=binding,- trace_bindings=trace_bindings,- unified=unified,- )- except Exception as exc:- if span is not None:- try:- from openjiuwen.agent_teams.observability.span_context import (- clear_team_span,- get_team_span,- )-- if get_team_span() is span:- clear_team_span()- except Exception as cleanup_error:- logger.debug(- "[AgentObservability] failed root span context cleanup failed: %s",- cleanup_error,- )- try:- span.end()- except Exception as cleanup_error:- logger.debug(- "[AgentObservability] end failed root span failed: %s",- cleanup_error,- )- logger.warning("[AgentObservability] open root span failed: %s", exc)- return None---def close_agent_run_span(handle: Any, *, session_id: str = "") -> None:- """End the root span opened by :func:`open_agent_run_span` and clear it."""- if handle is None:- return- if isinstance(handle, AgentRunSpanHandle) and not handle.claim_close():- return- root_span = handle.root_span if isinstance(handle, AgentRunSpanHandle) else handle- binding = handle.binding if isinstance(handle, AgentRunSpanHandle) else None- trace_bindings = (- handle.trace_bindings if isinstance(handle, AgentRunSpanHandle) else None- )- if binding is not None and trace_bindings is not None:- try:- trace_bindings.remove(binding)- except Exception as exc:- logger.debug("[AgentObservability] trace binding remove failed: %s", exc)- try:- from openjiuwen.agent_teams.observability.span_context import (- cascade_close_children,- clear_team_span,- flush_child_spans,- get_team_span,- )- except Exception as exc:- logger.warning(- "[AgentObservability] close helpers unavailable: session_id=%s error=%s",- session_id,- exc,- )- try:- root_span.end()- except Exception as end_error:- logger.debug(- "[AgentObservability] fallback root span end failed: %s",- end_error,- )- return-- # End any still-open child LLM/tool spans (e.g. run aborted mid-call).- # Two nets are needed for the single-agent path:- # 1. cascade_close_children — closes spans whose state was pushed on- # the _llm_span_stack / _tool_span_map ContextVars in THIS context.- # 2. flush_child_spans — the SpanProcessor-backed safety net Team mode- # relies on (finalize_trace -> flush_child_spans via- # ActiveSpanTracker). The single-agent runner opens LLM spans inside- # its own child context, so their ContextVar state is not visible- # here; the tracker closes them by trace_id regardless of context.- # Flush by the handle's explicit trace id before ending the root so one- # request can never drain another concurrent request's child spans.- try:- owns_current_context = get_team_span() is root_span- except Exception as exc:- logger.debug("[AgentObservability] current root lookup failed: %s", exc)- owns_current_context = False- if owns_current_context:- try:- cascade_close_children()- except Exception as exc:- logger.debug("[AgentObservability] cascade_close_children failed: %s", exc)- try:- span_context = root_span.get_span_context()- flush_child_spans(trace_id=span_context.trace_id)- except Exception as exc:- logger.debug("[AgentObservability] flush_child_spans failed: %s", exc)- try:- root_span.end()- except Exception as exc:- logger.debug("[AgentObservability] end root span failed: %s", exc)- if owns_current_context:- try:- clear_team_span()- except Exception as exc:- logger.debug("[AgentObservability] clear root span failed: %s", exc)- try:- from openjiuwen.extensions.observability.span_context import (- clear_current_session_id,- clear_root_span,- )-- clear_root_span(session_id=session_id, expected_span=root_span)- clear_current_session_id()- except Exception as exc:- logger.debug("[AgentObservability] clear extensions root span failed: %s", exc)diff --git a/jiuwenswarm/agents/harness/observability_runtime.py b/jiuwenswarm/agents/harness/observability_runtime.pyindex 0df36123d6..7e87b25ad3 100644--- a/jiuwenswarm/agents/harness/observability_runtime.py+++ b/jiuwenswarm/agents/harness/observability_runtime.py@@ -1,97 +1,21 @@# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.-"""Shared process-level observability and trajectory processor access."""+"""Mapping from JiuwenSwarm settings to the SDK observability config.++Provider lifecycle itself lives in the SDK: each runtime acquires and releases+its own demand (``openjiuwen.harness.observability`` for single agent,+``openjiuwen.agent_teams.observability`` for Team) and the shared coordinator in+``openjiuwen.extensions.observability.demand`` keeps one runtime's shutdown from+tearing down a provider the other still needs. What remains here is the part the+SDK cannot own: turning this platform's ``config.yaml`` section into an+``ObservabilityConfig``.+"""from __future__ import annotationsfrom collections.abc import Mapping-import logging-import threadingfrom typing import Any-from jiuwenswarm.common.openjiuwen_rail_compat import filter_unsupported_kwargs--logger = logging.getLogger(__name__)--_RUNTIMES = frozenset({"agent", "team"})-_ACTIVE_RUNTIMES: set[str] = set()-_DEMAND_LOCK = threading.RLock()-# Only shut down a provider that this coordinator created. A provider may be-# initialized by an RL collector or another SDK entry point before either-# runtime acquires a demand; those callers retain ownership of its lifecycle.-_PROVIDER_OWNED = False-_TRAJECTORY_SPAN_PROCESSOR: Any | None = None-_TRAJECTORY_UNAVAILABLE = False---def get_trajectory_span_processor() -> Any:- """Return the trajectory processor shared by all JiuwenClaw runtimes.-- Returns ``None`` when the installed openjiuwen SDK does not ship- ``TrajectorySpanProcessor``. Callers treat that as optional capture.- """- global _TRAJECTORY_SPAN_PROCESSOR, _TRAJECTORY_UNAVAILABLE- with _DEMAND_LOCK:- if _TRAJECTORY_UNAVAILABLE:- return None- if _TRAJECTORY_SPAN_PROCESSOR is not None:- return _TRAJECTORY_SPAN_PROCESSOR-- try:- from openjiuwen.agent_evolving.trajectory.processor import (- TrajectorySpanProcessor,- )- except ModuleNotFoundError:- _TRAJECTORY_UNAVAILABLE = True- logger.warning(- "openjiuwen trajectory processor is unavailable; "- "evolution span capture is disabled"- )- return None-- _TRAJECTORY_SPAN_PROCESSOR = TrajectorySpanProcessor()- return _TRAJECTORY_SPAN_PROCESSOR---def ensure_trajectory_span_processor_attached() -> bool:- """Attach the shared trajectory processor to the active OTel provider.-- Idempotent: ``ObservabilityRuntime.add_span_processors`` skips processors- already registered by object identity. Safe to call from both the unified- telemetry path and the legacy ``acquire_observability_demand`` path.- Returns ``True`` when a processor is present on an initialized provider.- """- processor = get_trajectory_span_processor()- if processor is None:- return False-- from openjiuwen.agent_teams.observability.setup import (- get_config,- init_observability,- is_initialized,- )-- if not is_initialized():- return False-- config = get_config()- if config is None:- return False-- init_kwargs = {"additional_span_processors": (processor,)}- compatible_kwargs = filter_unsupported_kwargs(init_observability, init_kwargs)- dropped = set(init_kwargs) - set(compatible_kwargs)- if dropped:- logger.warning(- "openjiuwen init_observability does not accept %s; "- "trajectory capture cannot attach on unified path",- ", ".join(sorted(dropped)),- )- return False-- init_observability(config, **compatible_kwargs)- return True-def build_observability_config(config: Mapping[str, Any],@@ -102,7 +26,7 @@ def build_observability_config(traces_dir: str,) -> Any:"""Build the SDK config for one runtime without initializing the provider."""- from openjiuwen.agent_teams.observability import ObservabilityConfig+ from openjiuwen.extensions.observability.config import ObservabilityConfigreturn ObservabilityConfig(enabled=True,@@ -118,82 +42,3 @@ def build_observability_config(traces_dir=config.get("traces_dir") or traces_dir,file_retention_days=config.get("file_retention_days", 7),)---def acquire_observability_demand(- runtime: str,- *,- observability_config: Any,-) -> bool:- """Acquire one runtime's demand for the shared provider.-- Initialization errors are deliberately propagated so the caller can- distinguish an optional tracing failure from a required evolution capture- failure.- """- global _PROVIDER_OWNED- with _DEMAND_LOCK:- if runtime not in _RUNTIMES:- raise ValueError(f"unknown observability runtime: {runtime}")-- from openjiuwen.agent_teams.observability import is_initialized-- if runtime in _ACTIVE_RUNTIMES and is_initialized():- # Provider may have been created by unified telemetry without the- # trajectory processor; re-ensure attachment on every demand.- ensure_trajectory_span_processor_attached()- return True-- from openjiuwen.agent_teams.observability import init_observability-- provider_existed = is_initialized()- processor = get_trajectory_span_processor()- extra_processors = (processor,) if processor is not None else ()- init_kwargs = {"additional_span_processors": extra_processors}- compatible_kwargs = filter_unsupported_kwargs(init_observability, init_kwargs)- dropped = set(init_kwargs) - set(compatible_kwargs)- if dropped:- logger.warning(- "openjiuwen init_observability does not accept %s; skipping",- ", ".join(sorted(dropped)),- )- init_observability(observability_config, **compatible_kwargs)- # When the provider already existed (e.g. unified telemetry), the kwargs- # above may have been a no-op on older SDKs; force an explicit attach.- if provider_existed:- ensure_trajectory_span_processor_attached()- if not is_initialized():- raise RuntimeError(- f"{runtime} observability initialization did not create a provider"- )- if not provider_existed:- _PROVIDER_OWNED = True- _ACTIVE_RUNTIMES.add(runtime)- return provider_existed---def release_observability_demand(runtime: str) -> None:- """Release a runtime demand during process shutdown."""- global _PROVIDER_OWNED- with _DEMAND_LOCK:- if runtime not in _RUNTIMES:- raise ValueError(f"unknown observability runtime: {runtime}")- _ACTIVE_RUNTIMES.discard(runtime)- if not _ACTIVE_RUNTIMES and _PROVIDER_OWNED:- from openjiuwen.agent_teams.observability import (- is_initialized,- shutdown_observability,- )-- if is_initialized():- shutdown_observability()- _PROVIDER_OWNED = False---def reset_observability_demands() -> None:- """Reset demand bookkeeping for isolated tests."""- global _PROVIDER_OWNED, _TRAJECTORY_UNAVAILABLE- with _DEMAND_LOCK:- _ACTIVE_RUNTIMES.clear()- _PROVIDER_OWNED = False- _TRAJECTORY_UNAVAILABLE = Falsediff --git a/jiuwenswarm/agents/harness/team/team_manager.py b/jiuwenswarm/agents/harness/team/team_manager.pyindex 1d8e329566..44b78dd6b1 100644--- a/jiuwenswarm/agents/harness/team/team_manager.py+++ b/jiuwenswarm/agents/harness/team/team_manager.py@@ -20,6 +20,7 @@ from openjiuwen.agent_teams.paths import team_homefrom openjiuwen.agent_teams.runtime.pool import RuntimeStatefrom openjiuwen.agent_teams.schema.blueprint import TeamAgentSpecfrom openjiuwen.agent_teams.context import reset_session_id, set_session_id+from openjiuwen.agent_teams import observability as team_observabilityfrom openjiuwen.core.runner import Runnerfrom openjiuwen.core.common.logging import server_loggerfrom openjiuwen.harness import DeepAgent@@ -64,11 +65,7 @@ from jiuwenswarm.common.config import (get_skill_create_enabled,get_skill_evolution_enabled,)-from jiuwenswarm.agents.harness.observability_runtime import (- acquire_observability_demand,- build_observability_config,- release_observability_demand,-)+from jiuwenswarm.agents.harness.observability_runtime import build_observability_configfrom jiuwenswarm.common.reasoning_injector import build_reasoning_model_request_kwargsfrom jiuwenswarm.agents.harness.team.team_runtime_inheritance import (MemberInfo,@@ -152,7 +149,7 @@ def sync_team_observability() -> None:# Same gap as single-agent: unified runtime must still host the# shared TrajectorySpanProcessor for skill / team evolution rails.try:- from jiuwenswarm.agents.harness.observability_runtime import (+ from openjiuwen.extensions.observability.demand import (ensure_trajectory_span_processor_attached,)@@ -185,10 +182,7 @@ def sync_team_observability() -> None:service_name="jiuwenswarm",traces_dir=traces_dir,)- provider_existed = acquire_observability_demand(- "team",- observability_config=obs_cfg,- )+ provider_existed = team_observability.acquire_observability(obs_cfg)was_active = _observability_active_observability_active = Trueif not was_active and not provider_existed:@@ -223,7 +217,7 @@ def shutdown_team_observability() -> None:_runtime_managed_observability = Falsereturntry:- release_observability_demand("team")+ team_observability.release_observability()_observability_active = Falselogger.info("[TeamObservability] disabled")except Exception as exc:diff --git a/jiuwenswarm/agents/harness/team/team_runtime_inheritance.py b/jiuwenswarm/agents/harness/team/team_runtime_inheritance.pyindex c165dc1305..33d079d3b5 100644--- a/jiuwenswarm/agents/harness/team/team_runtime_inheritance.py+++ b/jiuwenswarm/agents/harness/team/team_runtime_inheritance.py@@ -39,7 +39,7 @@ from jiuwenswarm.common.config import (get_passive_skill_evolution_triggers,get_skill_create_enabled,)-from jiuwenswarm.agents.harness.observability_runtime import (+from openjiuwen.extensions.observability.demand import (get_trajectory_span_processor,)from jiuwenswarm.common.reasoning_injector import build_reasoning_model_request_kwargsdiff --git a/jiuwenswarm/agents/swarm/providers/evolution_rails.py b/jiuwenswarm/agents/swarm/providers/evolution_rails.pyindex a0a67f09d9..62c47917cb 100644--- a/jiuwenswarm/agents/swarm/providers/evolution_rails.py+++ b/jiuwenswarm/agents/swarm/providers/evolution_rails.py@@ -38,7 +38,7 @@ from openjiuwen.harness.rails import (from openjiuwen.harness.rails.evolution import EvolutionReviewRuntimefrom jiuwenswarm.agents.swarm.context import SwarmBuildContext-from jiuwenswarm.agents.harness.observability_runtime import (+from openjiuwen.extensions.observability.demand import (get_trajectory_span_processor,)from jiuwenswarm.server.runtime.agent_adapter.evolution_helpers import (diff --git a/jiuwenswarm/server/app_agentserver.py b/jiuwenswarm/server/app_agentserver.pyindex ff8d516bba..8bebecf1d6 100644--- a/jiuwenswarm/server/app_agentserver.py+++ b/jiuwenswarm/server/app_agentserver.py@@ -168,6 +168,11 @@ from jiuwenswarm.server.runtime.debug_trace.task_tool_patch import (apply_task_tool_debug_patch()+# Ensure every harness-created subagent receives the SDK observability rail.+from openjiuwen.harness.observability import install_subagent_observability_hook++install_subagent_observability_hook()+# Subagent thinking control (task_tool optional ``thinking`` param).# Requires openjiuwen core with llm_call_kwargs + thinking_hook; otherwise no-op.from jiuwenswarm.common.thinking.register_hook import register_thinking_hookdiff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex 56119482a5..b01d96c603 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -7917,7 +7917,7 @@ class JiuWenSwarmDeepAdapter:"""if not get_skill_evolution_enabled(config):return None- from jiuwenswarm.agents.harness.observability_runtime import (+ from openjiuwen.extensions.observability.demand import (get_trajectory_span_processor,)@@ -8162,7 +8162,7 @@ class JiuWenSwarmDeepAdapter:if self._skill_manager is not Noneelse [])- from jiuwenswarm.agents.harness.observability_runtime import (+ from openjiuwen.extensions.observability.demand import (get_trajectory_span_processor,)@@ -8377,7 +8377,7 @@ class JiuWenSwarmDeepAdapter:logger.debug("[JiuWenSwarmDeepAdapter] SkillCreateRail disabled by config")return None- from jiuwenswarm.agents.harness.observability_runtime import (+ from openjiuwen.extensions.observability.demand import (get_trajectory_span_processor,)@@ -9132,9 +9132,7 @@ class JiuWenSwarmDeepAdapter:# enable/disable of agent_observability without rebuilding the agent.try:from openjiuwen.agent_teams.observability.rail import ObservabilityRail- from jiuwenswarm.agents.harness.agent_observability import (- AgentTraceBindingRail,- )+ from openjiuwen.harness.observability import AgentTraceBindingRailrails_list.append(AgentTraceBindingRail())rails_list.append(ObservabilityRail())@@ -10291,7 +10289,7 @@ class JiuWenSwarmDeepAdapter:should_enable_general_agent = should_add_general_agent and (sub_mode == "plan" or (isinstance(mode, str) and mode.startswith("agent")))- from jiuwenswarm.agents.harness.observability_runtime import (+ from openjiuwen.extensions.observability.demand import (get_trajectory_span_processor,)@@ -17888,9 +17886,11 @@ class JiuWenSwarmDeepAdapter:# Sync single-agent / coding-agent observability with current# config before running, and open a root span so OtelCallbackHandler# has a parent for LLM/tool spans (see streaming path for details).- from jiuwenswarm.agents.harness.agent_observability import (+ from openjiuwen.harness.observability import (close_agent_run_span,open_agent_run_span,+ )+ from jiuwenswarm.agents.harness.agent_observability import (sync_agent_observability,)sync_agent_observability()@@ -18985,9 +18985,11 @@ class JiuWenSwarmDeepAdapter:)# Sync single-agent / coding-agent observability with current config# before running.- from jiuwenswarm.agents.harness.agent_observability import (+ from openjiuwen.harness.observability import (close_agent_run_span,open_agent_run_span,+ )+ from jiuwenswarm.agents.harness.agent_observability import (sync_agent_observability,)sync_agent_observability(force=_dbg_settings.otel_enabled)diff --git a/jiuwenswarm/server/runtime/debug_trace/subagent_capture.py b/jiuwenswarm/server/runtime/debug_trace/subagent_capture.pyindex d700766302..f0ed56e18e 100644--- a/jiuwenswarm/server/runtime/debug_trace/subagent_capture.py+++ b/jiuwenswarm/server/runtime/debug_trace/subagent_capture.py@@ -27,56 +27,6 @@ from typing import Any_logger = logging.getLogger(__name__)-def _ensure_observability_rail(subagent: Any) -> None:- """Attach ``ObservabilityRail`` to *subagent* for correct OTel scoping.-- Without this rail, a harness-built subagent has no agent-level OTel span, so- its LLM/tool spans fall back to the parent agent's span and carry no- ``agentteam.agent.id`` (the SDK's ``_attach_observability_rail`` docstring- describes exactly this gap — it is only applied on the team-manifest path,- not the harness ``create_subagent`` path that TaskTool uses).-- Build-time attachment on the spec is unreliable: the parent agent is- constructed once, typically *before* observability is initialized, so- ``maybe_observability_rail()`` would return ``None``. At run time (here,- inside a request) observability is already up, so we attach via- ``add_rail``; the subagent's upcoming ``stream()/invoke()`` ->- ``_ensure_initialized()`` registers it before ``before_invoke`` fires.-- Idempotent, and a no-op when observability is off or *subagent* lacks the- DeepAgent rail API. Best-effort: never raises.- """- try:- from openjiuwen.agent_teams.observability.rail import (- ObservabilityRail,- maybe_observability_rail,- )-- rail = maybe_observability_rail()- if rail is None:- return # observability not initialized -> nothing to trace- configured = subagent.configured_rails() if hasattr(subagent, "configured_rails") else []- if any(isinstance(r, ObservabilityRail) for r in configured):- return # already attached (e.g. build-time succeeded) — don't double-add- if hasattr(subagent, "add_rail"):- subagent.add_rail(rail)- except Exception as exc:- # Never break the subagent run over tracing instrumentation.- _logger.debug("[subagent-capture] attach observability rail failed: %s", exc)-- # Newer openjiuwen guards ObservabilityRail.before_invoke with- # `if not team_name: return` BEFORE the session-registry get_team_span()- # fallback runs, so a team_name-less harness subagent gets no invoke span.- # Mirror the synthetic "single-agent" team from open_agent_run_span so the- # guard passes. team_name is a plain attr on DeepAgent (not a property);- # skipped when the subagent already has one (real team member).- if not getattr(subagent, "team_name", ""):- try:- subagent.team_name = "single-agent"- except Exception as exc:- _logger.debug("[subagent-capture] set team_name on subagent failed: %s", exc)--async def invoke_subagent_with_trace(subagent: Any,*,@@ -96,11 +46,12 @@ async def invoke_subagent_with_trace(An invoke-style result dict (``{"output": ..., "result_type": ...}``),matching what ``subagent.invoke`` would have returned."""- # Attach the OTel ObservabilityRail so the subagent gets its own agent-level- # span (agent.<type>.invoke) with correct nesting + agentteam.agent.id in- # the OTLP trace. Done at run time (not build time) because the parent agent- # is built once, often before observability is initialized.- _ensure_observability_rail(subagent)+ # Safety net for a subagent that reached here without going through the+ # create_subagent hook (a host-built instance, say). Idempotent, so the+ # normal path — where the hook already attached the rail — pays nothing.+ from openjiuwen.harness.observability import attach_subagent_observability++ attach_subagent_observability(subagent)from jiuwenswarm.server.runtime.debug_trace.context import (get_debug_trace_logger,diff --git a/jiuwenswarm/telemetry/runtime.py b/jiuwenswarm/telemetry/runtime.pyindex 24dd4a1ba4..949bf9f123 100644--- a/jiuwenswarm/telemetry/runtime.py+++ b/jiuwenswarm/telemetry/runtime.py@@ -322,7 +322,7 @@ class TelemetryRuntime:# Skill / team evolution rails subscribe to this processor; without# registering it on the unified TracerProvider, after_invoke never# receives LLM/tool spans and run_evolution is skipped silently.- from jiuwenswarm.agents.harness.observability_runtime import (+ from openjiuwen.extensions.observability.demand import (get_trajectory_span_processor,)